@codexhost/cli-linux-arm64 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,152 +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 record3 = value;
532
- if (match(record3))
533
- return record3;
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/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
- // ../../harness-adapter/dist/session-import.js
555
- import { lstat as lstat2 } from "node:fs/promises";
556
-
557
411
  // ../../../node_modules/zod/v4/classic/external.js
558
412
  var external_exports = {};
559
413
  __export(external_exports, {
@@ -15205,13 +15059,25 @@ var threadPermissionModeSelectParamsSchema = external_exports.object({
15205
15059
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15206
15060
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
15207
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);
15208
15070
  var usageMeasurementSchema = external_exports.object({
15071
+ version: external_exports.union([external_exports.literal(2), external_exports.literal(3)]).optional(),
15209
15072
  value: finiteNonNegativeNumberSchema,
15210
15073
  turnId: external_exports.string().min(1).max(1024),
15211
15074
  at: nonNegativeSafeIntegerSchema
15212
15075
  }).strict();
15213
15076
  var usageMeasurementsSchema = external_exports.object({
15214
- 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),
15215
15081
  timeToFirstOutputMs: usageMeasurementSchema.extend({ value: nonNegativeSafeIntegerSchema }).optional()
15216
15082
  }).strict();
15217
15083
  var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text) => text.length <= maximum));
@@ -15231,6 +15097,7 @@ var threadUsageSnapshotSchema = external_exports.object({
15231
15097
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
15232
15098
  outputTokens: nonNegativeSafeIntegerSchema.optional(),
15233
15099
  outputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
15100
+ sessionOutputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
15234
15101
  apiOutputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
15235
15102
  reasoningOutputTokens: nonNegativeSafeIntegerSchema.optional(),
15236
15103
  totalTokens: nonNegativeSafeIntegerSchema.optional(),
@@ -15642,11 +15509,19 @@ var threadSteeringInspectResultSchema = external_exports.object({
15642
15509
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15643
15510
  }).strict();
15644
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
+
15645
15516
  // ../../shared-contracts/dist/client-channel.js
15646
15517
  var CLIENT_CHANNEL_VERSION = 1;
15647
15518
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
15648
15519
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
15649
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();
15650
15525
  var clientProjectlessWorkspaceSchema = external_exports.object({
15651
15526
  prompt: external_exports.string().max(16384).optional()
15652
15527
  }).strict();
@@ -15663,6 +15538,11 @@ var clientChannelCursorSchema = external_exports.object({
15663
15538
  sequence: external_exports.number().int().nonnegative()
15664
15539
  });
15665
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
+ }),
15666
15546
  external_exports.object({ type: external_exports.literal("display-settings-changed"), cursor: clientChannelCursorSchema }),
15667
15547
  external_exports.object({
15668
15548
  type: external_exports.literal("preferences-changed"),
@@ -15772,7 +15652,12 @@ var clientThreadSnapshotSchema = external_exports.object({
15772
15652
  /** Current interruptible Host Turn, including command Turns omitted from client history. */
15773
15653
  activeTurnId: external_exports.string().min(1).nullable().optional(),
15774
15654
  /** Most recent explicit command in this Host process; not native conversation history. */
15775
- 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(),
15776
15661
  thread: external_exports.object({
15777
15662
  id: external_exports.string().min(1),
15778
15663
  cwd: external_exports.string(),
@@ -15860,6 +15745,28 @@ var voiceTranscribeResultSchema = external_exports.discriminatedUnion("ok", [
15860
15745
  external_exports.object({ ok: external_exports.literal(false), error: external_exports.object({ code: voiceErrorCodeSchema }).strict() }).strict()
15861
15746
  ]);
15862
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
+
15863
15770
  // ../../shared-contracts/dist/web-access-tokens.js
15864
15771
  var webNetworkAccessUrlSchema = external_exports.object({
15865
15772
  /**
@@ -15958,15 +15865,14 @@ var webAccessStateSchema = external_exports.object({
15958
15865
  quotaUntil: external_exports.string().optional()
15959
15866
  }).strict().optional()
15960
15867
  }).strict();
15961
- var webLocalAccessRequiredDetailsSchema = external_exports.object({ url: external_exports.string() }).strict();
15962
15868
 
15963
15869
  // ../../shared-contracts/dist/delegation-read.js
15964
15870
  var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
15965
15871
  var delegationReadParamsSchema = external_exports.strictObject({
15966
15872
  threadId: external_exports.string().min(1).max(1024),
15967
15873
  view: external_exports.enum(["result", "messages"]),
15968
- cursor: external_exports.string().min(1).max(8192).optional(),
15969
- 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()
15970
15876
  });
15971
15877
 
15972
15878
  // ../../shared-contracts/dist/credential-imports.js
@@ -16919,6 +16825,17 @@ var updateStatusResultSchema = external_exports.strictObject({
16919
16825
  status: updateStatusSchema.nullable()
16920
16826
  });
16921
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
+
16922
16839
  // ../../shared-contracts/dist/remote-runtime.js
16923
16840
  var remoteUpdatePhaseSchema = external_exports.enum([
16924
16841
  "idle",
@@ -16966,6 +16883,14 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
16966
16883
  archived: external_exports.boolean()
16967
16884
  }),
16968
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"),
16969
16894
  external_exports.strictObject({
16970
16895
  kind: external_exports.literal("prompt"),
16971
16896
  ...thread,
@@ -17038,6 +16963,13 @@ var remoteConnectionsReplySchema = external_exports.union([
17038
16963
  external_exports.strictObject({ error: external_exports.strictObject({ code: external_exports.number().int(), message: external_exports.string() }) })
17039
16964
  ]);
17040
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
+
17041
16973
  // ../../shared-contracts/dist/web-ui-extensions.js
17042
16974
  var webUiExtensionIdSchema = external_exports.string().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u);
17043
16975
  var localizedTextSchema2 = external_exports.union([
@@ -17081,570 +17013,256 @@ var webUiExtensionRemoveSchema = external_exports.object({ id: webUiExtensionIdS
17081
17013
  // ../../shared-contracts/dist/index.js
17082
17014
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
17083
17015
 
17084
- // ../../harness-adapter/dist/session-import.js
17085
- var SessionImportChangedError = class extends Error {
17086
- constructor(message3 = "Native Session changed during discovery; refresh and retry") {
17087
- super(message3);
17088
- this.name = "SessionImportChangedError";
17089
- }
17090
- };
17091
- function isMissingFileError(error51) {
17092
- return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "ENOENT";
17093
- }
17094
- function sameFileFingerprint(left, right) {
17095
- 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;
17096
- }
17097
- var STORAGE_ACCESS_ERRORS = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EIO", "EMFILE", "ENFILE"]);
17098
- function isStorageAccessError(error51) {
17099
- return typeof error51 === "object" && error51 !== null && "code" in error51 && typeof error51.code === "string" && STORAGE_ACCESS_ERRORS.has(error51.code);
17100
- }
17101
- async function optionalLstat(file2) {
17102
- try {
17103
- return await lstat2(file2);
17104
- } catch (error51) {
17105
- if (isMissingFileError(error51))
17106
- return null;
17107
- throw error51;
17108
- }
17109
- }
17110
- async function readStableFiles(files, read) {
17111
- const before = await Promise.all(files.map(optionalLstat));
17112
- const value = await read(before);
17113
- const after = await Promise.all(files.map(optionalLstat));
17114
- if (before.some((info, index) => !sameFileFingerprint(info, after[index] ?? null)))
17115
- throw new SessionImportChangedError();
17116
- return value;
17016
+ // ../../harness-adapter/dist/approval.js
17017
+ function invalidRequest(message3) {
17018
+ return { code: "invalidRequest", message: message3, retryable: false };
17117
17019
  }
17118
- function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
17119
- if (typeof value !== "string")
17120
- return null;
17121
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17122
- if (!normalized)
17123
- return null;
17124
- if (normalized.length <= maxLength)
17125
- return normalized;
17126
- const characters = [...normalized];
17127
- if (characters.length <= maxLength)
17128
- return normalized;
17129
- return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
17020
+ function validateHostApprovalResponse(interaction, response) {
17021
+ return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17130
17022
  }
17131
- function sessionImportCandidate(input) {
17132
- const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
17133
- const parsed = harnessSessionImportCandidateSchema.safeParse({
17134
- nativeSessionId: input.nativeSessionId,
17135
- cwd: input.cwd,
17136
- title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
17137
- updatedAt: Math.floor(time3),
17138
- // Unknown must stay unknown; only an explicit boolean is a native statement.
17139
- running: typeof input.running === "boolean" ? input.running : null
17140
- });
17141
- return parsed.success ? parsed.data : null;
17023
+
17024
+ // ../../harness-adapter/dist/question.js
17025
+ function invalidRequest2(message3) {
17026
+ return { code: "invalidRequest", message: message3, retryable: false };
17142
17027
  }
17143
- var SessionImportScope = class {
17144
- #abort = new AbortController();
17145
- #options;
17146
- #pending = /* @__PURE__ */ new Set();
17147
- constructor(options) {
17148
- this.#options = options;
17028
+ function validateHostQuestionResponse(interaction, response) {
17029
+ const questionIds = new Set(interaction.questions.map(({ id }) => id));
17030
+ if (response.cancelled) {
17031
+ return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
17149
17032
  }
17150
- #closed() {
17151
- return {
17152
- ok: false,
17153
- error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
17154
- };
17033
+ for (const answerId of Object.keys(response.answers)) {
17034
+ if (!questionIds.has(answerId)) {
17035
+ return invalidRequest2("Question Response contains an unknown Question ID");
17036
+ }
17155
17037
  }
17156
- read(operation) {
17157
- const signal = this.#abort.signal;
17158
- if (signal.aborted)
17159
- return Promise.resolve(this.#closed());
17160
- let started;
17161
- try {
17162
- started = operation(signal);
17163
- } catch (error51) {
17164
- started = Promise.reject(error51 instanceof Error ? error51 : new Error("Session read failed"));
17038
+ for (const question of interaction.questions) {
17039
+ const answers = response.answers[question.id] ?? [];
17040
+ if (!question.optional && answers.length === 0) {
17041
+ return invalidRequest2("Question Response omits a required answer");
17165
17042
  }
17166
- const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
17167
- ok: false,
17168
- error: {
17169
- code: "unavailable",
17170
- message: this.#options.unavailableMessage,
17171
- retryable: true
17043
+ if (question.type === "text") {
17044
+ if (answers.length > 1) {
17045
+ return invalidRequest2("Text Question accepts at most one answer");
17172
17046
  }
17173
- }).finally(() => this.#pending.delete(request));
17174
- this.#pending.add(request);
17175
- return request;
17047
+ continue;
17048
+ }
17049
+ if (!question.multiple && answers.length > 1) {
17050
+ return invalidRequest2("Single-choice Question accepts at most one answer");
17051
+ }
17052
+ const declared = new Set(question.options.map(({ value }) => value));
17053
+ if (!question.allowOther && answers.some((answer) => !declared.has(answer))) {
17054
+ return invalidRequest2("Question Response contains an undeclared choice");
17055
+ }
17176
17056
  }
17177
- /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
17178
- async resolve(operation) {
17179
- const result = await this.read(operation);
17180
- if (!result.ok)
17181
- return result;
17182
- return result.value ? { ok: true, value: result.value } : {
17183
- ok: false,
17184
- error: {
17185
- code: "sessionNotFound",
17186
- message: this.#options.notFoundMessage,
17187
- retryable: false
17057
+ return null;
17058
+ }
17059
+
17060
+ // ../../harness-adapter/dist/output-channel.js
17061
+ var HarnessOutputChannel = class {
17062
+ outputs;
17063
+ #consumerCreated = false;
17064
+ #ended = false;
17065
+ #pending = [];
17066
+ #values = [];
17067
+ constructor() {
17068
+ this.outputs = {
17069
+ [Symbol.asyncIterator]: () => {
17070
+ if (this.#consumerCreated) {
17071
+ throw new Error("Harness outputs allow only one consumer");
17072
+ }
17073
+ this.#consumerCreated = true;
17074
+ return {
17075
+ next: () => this.#next()
17076
+ };
17188
17077
  }
17189
17078
  };
17190
17079
  }
17191
- /** Idempotent. Resolves after every started read has settled. */
17192
- async close() {
17193
- this.#abort.abort();
17194
- await Promise.allSettled(this.#pending);
17080
+ emit(value) {
17081
+ if (this.#ended)
17082
+ return false;
17083
+ const resolve = this.#pending.shift();
17084
+ if (resolve)
17085
+ resolve({ done: false, value });
17086
+ else
17087
+ this.#values.push(value);
17088
+ return true;
17089
+ }
17090
+ end() {
17091
+ if (this.#ended)
17092
+ return;
17093
+ this.#ended = true;
17094
+ if (this.#values.length !== 0)
17095
+ return;
17096
+ for (const resolve of this.#pending.splice(0))
17097
+ resolve({ done: true, value: void 0 });
17098
+ }
17099
+ #next() {
17100
+ const value = this.#values.shift();
17101
+ if (value !== void 0)
17102
+ return Promise.resolve({ done: false, value });
17103
+ if (this.#ended)
17104
+ return Promise.resolve({ done: true, value: void 0 });
17105
+ return new Promise((resolve) => this.#pending.push(resolve));
17195
17106
  }
17196
17107
  };
17197
17108
 
17198
- // dist/session-import.js
17199
- function isRecord(value) {
17200
- return typeof value === "object" && value !== null && !Array.isArray(value);
17201
- }
17202
- function expandDirectory(value, home) {
17203
- return path5.resolve(value === "~" ? home : value.startsWith(`~${path5.sep}`) || value.startsWith("~/") ? path5.join(home, value.slice(2)) : value);
17109
+ // ../../harness-adapter/dist/diagnostics.js
17110
+ var DIAGNOSTIC_TAIL_MAX_LENGTH = 8e3;
17111
+ var SENSITIVE_VALUE_PATTERN = /(api[_-]?key|access[_-]?token|auth(?:orization)?|password|secret)(\s*[:=]\s*)([^\s,;]+)/giu;
17112
+ var BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]+/giu;
17113
+ function sanitizeDiagnosticTail(value) {
17114
+ const redacted = value.replace(BEARER_PATTERN, "Bearer [redacted]").replace(SENSITIVE_VALUE_PATTERN, "$1$2[redacted]");
17115
+ return redacted.length <= DIAGNOSTIC_TAIL_MAX_LENGTH ? redacted : redacted.slice(-DIAGNOSTIC_TAIL_MAX_LENGTH);
17204
17116
  }
17205
- function ompSessionImportDirectory(environment) {
17206
- const home = (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
17207
- const custom2 = environment.PI_CODING_AGENT_SESSION_DIR;
17208
- if (custom2)
17209
- return { directory: expandDirectory(custom2, home), flat: true };
17210
- const agent = environment.PI_CODING_AGENT_DIR;
17117
+
17118
+ // ../../harness-adapter/dist/steer.js
17119
+ function unsupportedSteer(harnessLabel) {
17211
17120
  return {
17212
- directory: path5.join(agent ? expandDirectory(agent, home) : path5.join(home, ".omp", "agent"), "sessions"),
17213
- flat: false
17121
+ ok: false,
17122
+ error: {
17123
+ code: "unsupported",
17124
+ message: `${harnessLabel} cannot steer an active Turn natively`,
17125
+ retryable: false
17126
+ }
17214
17127
  };
17215
17128
  }
17216
- function messageText(content) {
17217
- if (typeof content === "string")
17218
- return content;
17219
- if (!Array.isArray(content))
17220
- return "";
17221
- return content.filter((part) => isRecord(part) && part.type === "text" && typeof part.text === "string").map((part) => String(part.text)).join(" ");
17129
+
17130
+ // ../../harness-adapter/dist/usage.js
17131
+ var tokenFields = [
17132
+ "inputTokens",
17133
+ "cachedInputTokens",
17134
+ "cacheWriteInputTokens",
17135
+ "outputTokens",
17136
+ "reasoningOutputTokens",
17137
+ "totalTokens",
17138
+ "contextWindowTokens",
17139
+ "contextUsedTokens"
17140
+ ];
17141
+ var safeIntegerFields = [
17142
+ "planFiveHourResetsAtUnix",
17143
+ "planSevenDayResetsAtUnix",
17144
+ "timeToFirstOutputMs"
17145
+ ];
17146
+ var percentFields = [
17147
+ "cacheHitRatePercent",
17148
+ "sessionCacheHitRatePercent",
17149
+ "planFiveHourUsedPercent",
17150
+ "planSevenDayUsedPercent"
17151
+ ];
17152
+ var usageFields = /* @__PURE__ */ new Set([
17153
+ ...tokenFields,
17154
+ ...safeIntegerFields,
17155
+ ...percentFields,
17156
+ "sessionCacheUsage",
17157
+ "composerIndicators",
17158
+ "totalCostUsd",
17159
+ "totalCredits",
17160
+ "contextUsagePercent",
17161
+ "outputTokensPerSecond",
17162
+ "sessionOutputTokensPerSecond",
17163
+ "apiOutputTokensPerSecond",
17164
+ "costSource",
17165
+ "unpricedModels"
17166
+ ]);
17167
+ function isRecord(value) {
17168
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17222
17169
  }
17223
- async function readFacts(file2, signal) {
17224
- const stream = createReadStream2(file2, { encoding: "utf8", signal });
17225
- const lines = createInterface2({ input: stream, crlfDelay: Infinity });
17226
- let header = null;
17227
- let nativeTitle = null;
17228
- let firstPrompt = null;
17229
- let updatedAt = null;
17230
- let leafHasUser = false;
17231
- const hasUserAncestry = /* @__PURE__ */ new Map();
17232
- try {
17233
- for await (const line of lines) {
17234
- signal.throwIfAborted();
17235
- if (!line.trim())
17236
- continue;
17237
- let entry;
17238
- try {
17239
- entry = JSON.parse(line);
17240
- } catch {
17241
- continue;
17242
- }
17243
- if (!isRecord(entry))
17244
- continue;
17245
- if (entry.type === "title") {
17246
- nativeTitle = sessionImportTitle(entry.title);
17247
- continue;
17248
- }
17249
- if (entry.type === "session") {
17250
- if (header)
17251
- return null;
17252
- if (typeof entry.id !== "string" || entry.id.length === 0 || typeof entry.cwd !== "string" || !path5.isAbsolute(entry.cwd))
17253
- return null;
17254
- header = { id: entry.id, cwd: entry.cwd };
17255
- continue;
17256
- }
17257
- if (typeof entry.id !== "string" || entry.id.length === 0)
17258
- continue;
17259
- const message3 = isRecord(entry.message) ? entry.message : null;
17260
- const isUser = entry.type === "message" && message3?.role === "user";
17261
- if (isUser)
17262
- firstPrompt ??= sessionImportTitle(messageText(message3?.content));
17263
- leafHasUser = isUser || typeof entry.parentId === "string" && hasUserAncestry.get(entry.parentId) === true;
17264
- hasUserAncestry.set(entry.id, leafHasUser);
17265
- if (entry.type === "message" && (message3?.role === "user" || message3?.role === "assistant")) {
17266
- const time3 = typeof message3.timestamp === "number" ? message3.timestamp : typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : Number.NaN;
17267
- if (Number.isFinite(time3) && time3 >= 0)
17268
- updatedAt = time3;
17269
- }
17170
+ function parseHostUsage(value) {
17171
+ if (!isRecord(value))
17172
+ throw new Error("Harness Usage must be an object");
17173
+ const keys = Object.keys(value);
17174
+ if (keys.length === 0)
17175
+ throw new Error("Harness Usage must contain a reliable field");
17176
+ for (const key of keys) {
17177
+ if (!usageFields.has(key)) {
17178
+ throw new Error(`Harness Usage contains unknown field '${key}'`);
17270
17179
  }
17271
- } finally {
17272
- lines.close();
17273
- stream.destroy();
17274
- }
17275
- if (!header || !leafHasUser)
17276
- return null;
17277
- return {
17278
- nativeSessionId: header.id,
17279
- cwd: header.cwd,
17280
- title: nativeTitle ?? firstPrompt,
17281
- updatedAt
17282
- };
17283
- }
17284
- var OmpSessionImport = class {
17285
- #location;
17286
- #scope = new SessionImportScope({
17287
- closedMessage: "Omp Session import is closed",
17288
- unavailableMessage: "Omp sessions could not be read; close native clients, check storage access and retry",
17289
- notFoundMessage: "Omp Session is no longer importable"
17290
- });
17291
- constructor(environment) {
17292
- this.#location = ompSessionImportDirectory(environment);
17293
17180
  }
17294
- listCandidates() {
17295
- return this.#scope.read(async (signal) => [...(await this.#sources(signal)).values()].flatMap((sources) => (
17296
- // One identity in two files cannot be resumed unambiguously.
17297
- sources.length === 1 && sources[0] ? [sources[0].candidate] : []
17298
- )));
17181
+ const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
17182
+ for (const field2 of [
17183
+ "totalCredits",
17184
+ "contextUsagePercent",
17185
+ "sessionOutputTokensPerSecond",
17186
+ "apiOutputTokensPerSecond"
17187
+ ]) {
17188
+ const candidate = value[field2];
17189
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
17190
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
17191
+ }
17299
17192
  }
17300
- resolveCandidate(nativeSessionId) {
17301
- return this.#scope.resolve(async (signal) => {
17302
- const sources = (await this.#sources(signal)).get(nativeSessionId);
17303
- if (sources?.length !== 1 || !sources[0])
17304
- return null;
17305
- const source = await this.#source(sources[0].file, signal);
17306
- return source?.nativeRef.nativeSessionId === nativeSessionId ? { candidate: source.candidate, nativeRef: source.nativeRef } : null;
17307
- });
17308
- }
17309
- close() {
17310
- return this.#scope.close();
17311
- }
17312
- async #sessionFiles(signal) {
17313
- const { directory, flat } = this.#location;
17314
- const info = await optionalLstat(directory);
17315
- if (!info)
17316
- return [];
17317
- if (!info.isDirectory())
17318
- throw new Error("Omp Session store is not a directory");
17319
- const files = [];
17320
- const visit = async (current, projectLevel) => {
17321
- const entries = await opendir2(current).catch((error51) => {
17322
- if (isMissingFileError(error51))
17323
- return null;
17324
- throw error51;
17325
- });
17326
- if (!entries)
17327
- return;
17328
- for await (const entry of entries) {
17329
- signal.throwIfAborted();
17330
- if (projectLevel && entry.isDirectory())
17331
- await visit(path5.join(current, entry.name), false);
17332
- else if (!projectLevel && entry.isFile() && entry.name.endsWith(".jsonl"))
17333
- files.push(path5.join(current, entry.name));
17334
- }
17335
- };
17336
- await visit(directory, !flat);
17337
- return files;
17193
+ for (const field2 of tokenFields) {
17194
+ const candidate = value[field2];
17195
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17196
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
17197
+ }
17338
17198
  }
17339
- /** Session ID to every readable file claiming it. Files changing under the read are skipped. */
17340
- async #sources(signal) {
17341
- const found = /* @__PURE__ */ new Map();
17342
- for (const file2 of await this.#sessionFiles(signal)) {
17343
- signal.throwIfAborted();
17344
- try {
17345
- const source = await this.#source(file2, signal);
17346
- if (!source)
17347
- continue;
17348
- const sources = found.get(source.nativeRef.nativeSessionId) ?? [];
17349
- sources.push(source);
17350
- found.set(source.nativeRef.nativeSessionId, sources);
17351
- } catch (error51) {
17352
- if (!(error51 instanceof SessionImportChangedError))
17353
- throw error51;
17354
- }
17199
+ for (const field2 of safeIntegerFields) {
17200
+ const candidate = value[field2];
17201
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17202
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
17355
17203
  }
17356
- return found;
17357
17204
  }
17358
- async #source(file2, signal) {
17359
- signal.throwIfAborted();
17360
- return readStableFiles([file2], async ([info]) => {
17361
- if (!info?.isFile() || info.size === 0)
17362
- return null;
17363
- try {
17364
- const facts = await readFacts(file2, signal);
17365
- if (!facts)
17366
- return null;
17367
- const cwd = await realpath(facts.cwd);
17368
- if (!(await stat(cwd)).isDirectory())
17369
- return null;
17370
- const candidate = sessionImportCandidate({
17371
- nativeSessionId: facts.nativeSessionId,
17372
- cwd,
17373
- title: facts.title,
17374
- updatedAt: facts.updatedAt ?? info.mtimeMs
17375
- // OMP has no cross-process activity marker: idleness cannot be established.
17376
- });
17377
- if (!candidate)
17378
- return null;
17379
- return {
17380
- file: file2,
17381
- candidate,
17382
- // Resume needs the file itself: OMP is started with `--session <file>`.
17383
- nativeRef: nativeSessionRefSchema.parse({
17384
- harnessId: "omp",
17385
- nativeSessionId: facts.nativeSessionId,
17386
- locator: { sessionFile: await realpath(file2) },
17387
- formatVersion: 1
17388
- })
17389
- };
17390
- } catch (error51) {
17391
- signal.throwIfAborted();
17392
- if (isStorageAccessError(error51))
17393
- throw error51;
17394
- return null;
17395
- }
17396
- });
17205
+ if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
17206
+ throw new Error("Harness Usage 'outputTokensPerSecond' must be a finite non-negative number");
17397
17207
  }
17398
- };
17399
-
17400
- // ../../harness-adapter/dist/approval.js
17401
- function invalidRequest(message3) {
17402
- return { code: "invalidRequest", message: message3, retryable: false };
17403
- }
17404
- function validateHostApprovalResponse(interaction, response) {
17405
- return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17406
- }
17407
-
17408
- // ../../harness-adapter/dist/question.js
17409
- function invalidRequest2(message3) {
17410
- return { code: "invalidRequest", message: message3, retryable: false };
17411
- }
17412
- function validateHostQuestionResponse(interaction, response) {
17413
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
17414
- if (response.cancelled) {
17415
- return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
17208
+ if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
17209
+ throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
17416
17210
  }
17417
- for (const answerId of Object.keys(response.answers)) {
17418
- if (!questionIds.has(answerId)) {
17419
- return invalidRequest2("Question Response contains an unknown Question ID");
17211
+ for (const field2 of percentFields) {
17212
+ const candidate = value[field2];
17213
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
17214
+ throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
17420
17215
  }
17421
17216
  }
17422
- for (const question of interaction.questions) {
17423
- const answers = response.answers[question.id] ?? [];
17424
- if (!question.optional && answers.length === 0) {
17425
- return invalidRequest2("Question Response omits a required answer");
17426
- }
17427
- if (question.type === "text") {
17428
- if (answers.length > 1) {
17429
- return invalidRequest2("Text Question accepts at most one answer");
17430
- }
17431
- continue;
17432
- }
17433
- if (!question.multiple && answers.length > 1) {
17434
- return invalidRequest2("Single-choice Question accepts at most one answer");
17435
- }
17436
- const declared = new Set(question.options.map(({ value }) => value));
17437
- if (!question.allowOther && answers.some((answer) => !declared.has(answer))) {
17438
- return invalidRequest2("Question Response contains an undeclared choice");
17217
+ if (value.sessionCacheUsage !== void 0) {
17218
+ const totals2 = value.sessionCacheUsage;
17219
+ 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) {
17220
+ throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
17439
17221
  }
17440
17222
  }
17441
- return null;
17442
- }
17443
-
17444
- // ../../harness-adapter/dist/output-channel.js
17445
- var HarnessOutputChannel = class {
17446
- outputs;
17447
- #consumerCreated = false;
17448
- #ended = false;
17449
- #pending = [];
17450
- #values = [];
17451
- constructor() {
17452
- this.outputs = {
17453
- [Symbol.asyncIterator]: () => {
17454
- if (this.#consumerCreated) {
17455
- throw new Error("Harness outputs allow only one consumer");
17456
- }
17457
- this.#consumerCreated = true;
17458
- return {
17459
- next: () => this.#next()
17460
- };
17461
- }
17462
- };
17223
+ const hasContextUsed = value.contextUsedTokens !== void 0;
17224
+ const hasContextWindow = value.contextWindowTokens !== void 0;
17225
+ if (hasContextUsed !== hasContextWindow) {
17226
+ throw new Error("Harness Usage context fields must be provided together");
17463
17227
  }
17464
- emit(value) {
17465
- if (this.#ended)
17466
- return false;
17467
- const resolve = this.#pending.shift();
17468
- if (resolve)
17469
- resolve({ done: false, value });
17470
- else
17471
- this.#values.push(value);
17472
- return true;
17228
+ if (hasContextWindow && value.contextWindowTokens === 0) {
17229
+ throw new Error("Harness Usage 'contextWindowTokens' must be greater than zero");
17473
17230
  }
17474
- end() {
17475
- if (this.#ended)
17476
- return;
17477
- this.#ended = true;
17478
- if (this.#values.length !== 0)
17479
- return;
17480
- for (const resolve of this.#pending.splice(0))
17481
- resolve({ done: true, value: void 0 });
17231
+ if (value.planFiveHourResetsAtUnix !== void 0 && value.planFiveHourUsedPercent === void 0) {
17232
+ throw new Error("Harness Usage 'planFiveHourResetsAtUnix' must be provided with 'planFiveHourUsedPercent'");
17482
17233
  }
17483
- #next() {
17484
- const value = this.#values.shift();
17485
- if (value !== void 0)
17486
- return Promise.resolve({ done: false, value });
17487
- if (this.#ended)
17488
- return Promise.resolve({ done: true, value: void 0 });
17489
- return new Promise((resolve) => this.#pending.push(resolve));
17234
+ if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
17235
+ throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
17490
17236
  }
17491
- };
17492
-
17493
- // ../../harness-adapter/dist/diagnostics.js
17494
- var DIAGNOSTIC_TAIL_MAX_LENGTH = 8e3;
17495
- var SENSITIVE_VALUE_PATTERN = /(api[_-]?key|access[_-]?token|auth(?:orization)?|password|secret)(\s*[:=]\s*)([^\s,;]+)/giu;
17496
- var BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]+/giu;
17497
- function sanitizeDiagnosticTail(value) {
17498
- const redacted = value.replace(BEARER_PATTERN, "Bearer [redacted]").replace(SENSITIVE_VALUE_PATTERN, "$1$2[redacted]");
17499
- return redacted.length <= DIAGNOSTIC_TAIL_MAX_LENGTH ? redacted : redacted.slice(-DIAGNOSTIC_TAIL_MAX_LENGTH);
17500
- }
17501
-
17502
- // ../../harness-adapter/dist/steer.js
17503
- function unsupportedSteer(harnessLabel) {
17504
- return {
17505
- ok: false,
17506
- error: {
17507
- code: "unsupported",
17508
- message: `${harnessLabel} cannot steer an active Turn natively`,
17509
- retryable: false
17237
+ if (value.costSource !== void 0) {
17238
+ if (value.costSource !== "publicPrice" && value.costSource !== "native") {
17239
+ throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
17510
17240
  }
17511
- };
17241
+ if (value.totalCostUsd === void 0) {
17242
+ throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
17243
+ }
17244
+ }
17245
+ if (value.unpricedModels !== void 0) {
17246
+ const models = value.unpricedModels;
17247
+ if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
17248
+ throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
17249
+ }
17250
+ if (value.costSource !== "publicPrice") {
17251
+ throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
17252
+ }
17253
+ return { ...value, ...indicators, unpricedModels: [...models] };
17254
+ }
17255
+ return { ...value, ...indicators };
17512
17256
  }
17513
-
17514
- // ../../harness-adapter/dist/usage.js
17515
- var tokenFields = [
17257
+ var requestTokenFields = [
17516
17258
  "inputTokens",
17517
17259
  "cachedInputTokens",
17518
17260
  "cacheWriteInputTokens",
17261
+ "cacheWrite1hInputTokens",
17519
17262
  "outputTokens",
17520
17263
  "reasoningOutputTokens",
17521
- "totalTokens",
17522
- "contextWindowTokens",
17523
- "contextUsedTokens"
17524
- ];
17525
- var safeIntegerFields = [
17526
- "planFiveHourResetsAtUnix",
17527
- "planSevenDayResetsAtUnix",
17528
- "timeToFirstOutputMs"
17529
- ];
17530
- var percentFields = [
17531
- "cacheHitRatePercent",
17532
- "sessionCacheHitRatePercent",
17533
- "planFiveHourUsedPercent",
17534
- "planSevenDayUsedPercent"
17535
- ];
17536
- var usageFields = /* @__PURE__ */ new Set([
17537
- ...tokenFields,
17538
- ...safeIntegerFields,
17539
- ...percentFields,
17540
- "sessionCacheUsage",
17541
- "composerIndicators",
17542
- "totalCostUsd",
17543
- "totalCredits",
17544
- "contextUsagePercent",
17545
- "outputTokensPerSecond",
17546
- "apiOutputTokensPerSecond",
17547
- "costSource",
17548
- "unpricedModels"
17549
- ]);
17550
- function isRecord2(value) {
17551
- return typeof value === "object" && value !== null && !Array.isArray(value);
17552
- }
17553
- function parseHostUsage(value) {
17554
- if (!isRecord2(value))
17555
- throw new Error("Harness Usage must be an object");
17556
- const keys = Object.keys(value);
17557
- if (keys.length === 0)
17558
- throw new Error("Harness Usage must contain a reliable field");
17559
- for (const key of keys) {
17560
- if (!usageFields.has(key)) {
17561
- throw new Error(`Harness Usage contains unknown field '${key}'`);
17562
- }
17563
- }
17564
- const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
17565
- for (const field2 of [
17566
- "totalCredits",
17567
- "contextUsagePercent",
17568
- "apiOutputTokensPerSecond"
17569
- ]) {
17570
- const candidate = value[field2];
17571
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
17572
- throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
17573
- }
17574
- }
17575
- for (const field2 of tokenFields) {
17576
- const candidate = value[field2];
17577
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17578
- throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
17579
- }
17580
- }
17581
- for (const field2 of safeIntegerFields) {
17582
- const candidate = value[field2];
17583
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17584
- throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
17585
- }
17586
- }
17587
- if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
17588
- throw new Error("Harness Usage 'outputTokensPerSecond' must be a finite non-negative number");
17589
- }
17590
- if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
17591
- throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
17592
- }
17593
- for (const field2 of percentFields) {
17594
- const candidate = value[field2];
17595
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
17596
- throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
17597
- }
17598
- }
17599
- if (value.sessionCacheUsage !== void 0) {
17600
- const totals2 = value.sessionCacheUsage;
17601
- 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) {
17602
- throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
17603
- }
17604
- }
17605
- const hasContextUsed = value.contextUsedTokens !== void 0;
17606
- const hasContextWindow = value.contextWindowTokens !== void 0;
17607
- if (hasContextUsed !== hasContextWindow) {
17608
- throw new Error("Harness Usage context fields must be provided together");
17609
- }
17610
- if (hasContextWindow && value.contextWindowTokens === 0) {
17611
- throw new Error("Harness Usage 'contextWindowTokens' must be greater than zero");
17612
- }
17613
- if (value.planFiveHourResetsAtUnix !== void 0 && value.planFiveHourUsedPercent === void 0) {
17614
- throw new Error("Harness Usage 'planFiveHourResetsAtUnix' must be provided with 'planFiveHourUsedPercent'");
17615
- }
17616
- if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
17617
- throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
17618
- }
17619
- if (value.costSource !== void 0) {
17620
- if (value.costSource !== "publicPrice" && value.costSource !== "native") {
17621
- throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
17622
- }
17623
- if (value.totalCostUsd === void 0) {
17624
- throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
17625
- }
17626
- }
17627
- if (value.unpricedModels !== void 0) {
17628
- const models = value.unpricedModels;
17629
- if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
17630
- throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
17631
- }
17632
- if (value.costSource !== "publicPrice") {
17633
- throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
17634
- }
17635
- return { ...value, ...indicators, unpricedModels: [...models] };
17636
- }
17637
- return { ...value, ...indicators };
17638
- }
17639
- var requestTokenFields = [
17640
- "inputTokens",
17641
- "cachedInputTokens",
17642
- "cacheWriteInputTokens",
17643
- "cacheWrite1hInputTokens",
17644
- "outputTokens",
17645
- "reasoningOutputTokens",
17646
- "startedAtMs",
17647
- "completedAtMs"
17264
+ "startedAtMs",
17265
+ "completedAtMs"
17648
17266
  ];
17649
17267
  var requestFields = /* @__PURE__ */ new Set([
17650
17268
  ...requestTokenFields,
@@ -17654,7 +17272,7 @@ var requestFields = /* @__PURE__ */ new Set([
17654
17272
  "provider"
17655
17273
  ]);
17656
17274
  function parseHostUsageRequest(value) {
17657
- if (!isRecord2(value))
17275
+ if (!isRecord(value))
17658
17276
  throw new Error("Harness Usage request must be an object");
17659
17277
  for (const key of Object.keys(value)) {
17660
17278
  if (!requestFields.has(key)) {
@@ -17682,142 +17300,653 @@ function parseHostUsageRequest(value) {
17682
17300
  if (value.inputTokens === void 0 || value.outputTokens === void 0) {
17683
17301
  throw new Error("Harness Usage request must contain 'inputTokens' and 'outputTokens'");
17684
17302
  }
17685
- const request = value;
17686
- if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
17687
- throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
17303
+ const request = value;
17304
+ if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
17305
+ throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
17306
+ }
17307
+ if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
17308
+ throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
17309
+ }
17310
+ if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
17311
+ throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
17312
+ }
17313
+ if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
17314
+ throw new Error("Harness Usage request timing fields must be provided together");
17315
+ }
17316
+ if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
17317
+ throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
17318
+ }
17319
+ return { ...request };
17320
+ }
17321
+
17322
+ // ../../harness-adapter/dist/live-command-catalog.js
17323
+ var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
17324
+ // Session lifecycle
17325
+ "branch",
17326
+ "clear",
17327
+ "exit",
17328
+ "fork",
17329
+ "fresh",
17330
+ "new",
17331
+ "quit",
17332
+ "rename",
17333
+ "rename-chat",
17334
+ "reset",
17335
+ "resume",
17336
+ "rewind",
17337
+ "session",
17338
+ "sessions",
17339
+ // Desktop-owned configuration
17340
+ "autocompact",
17341
+ "color",
17342
+ "config",
17343
+ "effort",
17344
+ "fast",
17345
+ "keybindings",
17346
+ "model",
17347
+ "models",
17348
+ "output-style",
17349
+ "permissions",
17350
+ "settings",
17351
+ "statusline",
17352
+ "terminal-setup",
17353
+ "theme",
17354
+ "vim",
17355
+ // Trust and approval policy
17356
+ "always-approve",
17357
+ "auto-mode-setup",
17358
+ // Native login
17359
+ "login",
17360
+ "logout",
17361
+ // Work outliving the Turn
17362
+ "autopilot",
17363
+ "background",
17364
+ "bg",
17365
+ "goal",
17366
+ "jobs",
17367
+ "loop",
17368
+ "multitask",
17369
+ "queue",
17370
+ "remote-control",
17371
+ "schedule",
17372
+ "steer",
17373
+ // Native terminal UI
17374
+ "copy",
17375
+ "debug",
17376
+ "feedback",
17377
+ "heapdump",
17378
+ "share",
17379
+ "shell",
17380
+ // Plugin and MCP management
17381
+ "marketplace",
17382
+ "mcp",
17383
+ "plugins",
17384
+ "reload-plugins"
17385
+ ]);
17386
+ var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
17387
+ function isExcludedLiveCommand(name, extra = {}) {
17388
+ const normalized = name.trim().replace(/^\//u, "");
17389
+ if (new Set(extra.names ?? []).has(normalized))
17390
+ return true;
17391
+ if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
17392
+ return true;
17393
+ return COMMON_EXCLUDED_LIVE_COMMANDS.has(normalized) || COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES.some((prefix) => normalized.startsWith(prefix));
17394
+ }
17395
+ function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17396
+ if (!commandId.startsWith(idPrefix))
17397
+ return null;
17398
+ const descriptor = catalog.commands.find(({ id }) => id === commandId);
17399
+ if (!descriptor)
17400
+ return null;
17401
+ const text = typeof argumentText === "string" ? argumentText.trim() : "";
17402
+ return text ? `${descriptor.invocation} ${text}` : descriptor.invocation;
17403
+ }
17404
+ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17405
+ if (!live)
17406
+ return builtIns;
17407
+ const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
17408
+ const ids = new Set(builtIns.commands.map(({ id }) => id));
17409
+ const dynamic = [];
17410
+ for (const command of live) {
17411
+ const name = command.name.trim().replace(/^\//u, "");
17412
+ if (!name || /\s/u.test(name))
17413
+ continue;
17414
+ if (isExcludedLiveCommand(name, exclusions))
17415
+ continue;
17416
+ const invocation = `/${name}`;
17417
+ const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
17418
+ if (invocations.has(invocation) || ids.has(id))
17419
+ continue;
17420
+ const description = command.description?.trim().slice(0, 512);
17421
+ const parsed = harnessCommandDescriptorSchema.safeParse({
17422
+ id,
17423
+ invocation,
17424
+ label: name.slice(0, 128),
17425
+ ...description ? { description } : {},
17426
+ argumentMode: "text"
17427
+ });
17428
+ if (!parsed.success)
17429
+ continue;
17430
+ invocations.add(invocation);
17431
+ ids.add(id);
17432
+ dynamic.push(parsed.data);
17433
+ }
17434
+ return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
17435
+ }
17436
+
17437
+ // ../../harness-adapter/dist/subagent-configuration.js
17438
+ function subagentConfiguration(value) {
17439
+ if (typeof value !== "object" || value === null || Array.isArray(value))
17440
+ return {};
17441
+ const row = value;
17442
+ const text = (value2) => typeof value2 === "string" && value2.trim() ? value2 : void 0;
17443
+ const model2 = row.model === "inherit" ? void 0 : text(row.model);
17444
+ const reasoningEffort = text(row.reasoningEffort) ?? text(row.reasoning_effort) ?? text(row.thinking);
17445
+ return { ...model2 ? { model: model2 } : {}, ...reasoningEffort ? { reasoningEffort } : {} };
17446
+ }
17447
+ function inheritSubagentConfiguration(child, parent) {
17448
+ const native = subagentConfiguration(child);
17449
+ const model2 = native.model ?? parent.model;
17450
+ const reasoningEffort = native.reasoningEffort ?? parent.reasoningEffort;
17451
+ const next = { ...child };
17452
+ delete next.model;
17453
+ delete next.reasoningEffort;
17454
+ return { ...next, ...model2 ? { model: model2 } : {}, ...reasoningEffort ? { reasoningEffort } : {} };
17455
+ }
17456
+ function configureSubagentEvent(event, parent) {
17457
+ const children = (states) => states.map((child) => inheritSubagentConfiguration(child, parent));
17458
+ if (event.type === "item.started" && event.item.type === "subagentDelegation")
17459
+ return { ...event, item: { ...event.item, subagents: children(event.item.subagents) } };
17460
+ if (event.type === "item.updated" && event.update.type === "subagents.replace")
17461
+ return { ...event, update: { ...event.update, subagents: children(event.update.subagents) } };
17462
+ if (event.type === "item.completed" && event.snapshot.item.type === "subagentDelegation")
17463
+ return {
17464
+ ...event,
17465
+ snapshot: {
17466
+ ...event.snapshot,
17467
+ item: {
17468
+ ...event.snapshot.item,
17469
+ subagents: children(event.snapshot.item.subagents)
17470
+ }
17471
+ }
17472
+ };
17473
+ return event;
17474
+ }
17475
+ function configureSubagentSnapshot(snapshot, parent) {
17476
+ return {
17477
+ ...snapshot,
17478
+ turns: snapshot.turns.map((turn) => ({
17479
+ ...turn,
17480
+ items: turn.items.map((entry) => entry.item.type === "subagentDelegation" ? {
17481
+ ...entry,
17482
+ item: {
17483
+ ...entry.item,
17484
+ subagents: entry.item.subagents.map((child) => inheritSubagentConfiguration(child, parent))
17485
+ }
17486
+ } : entry)
17487
+ }))
17488
+ };
17489
+ }
17490
+
17491
+ // ../../harness-adapter/dist/usage-statistics.js
17492
+ import { createReadStream } from "node:fs";
17493
+ import { lstat, opendir } from "node:fs/promises";
17494
+ import path4 from "node:path";
17495
+ import { createInterface } from "node:readline";
17496
+ var MAX_SESSION_ID_LENGTH = 512;
17497
+ var MAX_CWD_LENGTH = 4096;
17498
+ var MAX_SESSION_TITLE_LENGTH = 200;
17499
+ function usageSessionTitle(value) {
17500
+ if (typeof value !== "string")
17501
+ return void 0;
17502
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17503
+ if (!normalized)
17504
+ return void 0;
17505
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
17506
+ return normalized;
17507
+ let title = "";
17508
+ for (const character of normalized) {
17509
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
17510
+ break;
17511
+ title += character;
17512
+ }
17513
+ return `${title.trimEnd()}…`;
17514
+ }
17515
+ function sessionIdOk(value) {
17516
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
17517
+ }
17518
+ function cwdOk(value) {
17519
+ 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("\\\\"));
17520
+ }
17521
+ function withUsageSession(entry, session) {
17522
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
17523
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
17524
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
17525
+ if (sessionId === void 0 && cwd === void 0)
17526
+ return entry;
17527
+ return {
17528
+ ...entry,
17529
+ ...sessionId !== void 0 ? { sessionId } : {},
17530
+ ...cwd !== void 0 ? { cwd } : {},
17531
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
17532
+ };
17533
+ }
17534
+ function usageEntryFromRequest(request, occurredAtMs) {
17535
+ if (!Number.isSafeInteger(occurredAtMs) || occurredAtMs <= 0)
17536
+ return null;
17537
+ return {
17538
+ id: request.requestId,
17539
+ occurredAtMs,
17540
+ ...request.model !== void 0 ? { model: request.model } : {},
17541
+ inputTokens: request.inputTokens,
17542
+ ...request.cachedInputTokens !== void 0 ? { cachedInputTokens: request.cachedInputTokens } : {},
17543
+ ...request.cacheWriteInputTokens !== void 0 ? { cacheWriteInputTokens: request.cacheWriteInputTokens } : {},
17544
+ ...request.cacheWrite1hInputTokens !== void 0 ? { cacheWrite1hInputTokens: request.cacheWrite1hInputTokens } : {},
17545
+ outputTokens: request.outputTokens,
17546
+ ...request.reasoningOutputTokens !== void 0 ? { reasoningOutputTokens: request.reasoningOutputTokens } : {}
17547
+ };
17548
+ }
17549
+ async function jsonlUsageSources(root, maxDepth, signal) {
17550
+ const sources = [];
17551
+ const visit = async (directory, depth) => {
17552
+ signal.throwIfAborted();
17553
+ const entries = await opendir(directory).catch((error51) => {
17554
+ if (error51.code === "ENOENT")
17555
+ return null;
17556
+ throw error51;
17557
+ });
17558
+ if (!entries)
17559
+ return;
17560
+ for await (const entry of entries) {
17561
+ signal.throwIfAborted();
17562
+ const file2 = path4.join(directory, entry.name);
17563
+ if (entry.isDirectory()) {
17564
+ if (depth < maxDepth)
17565
+ await visit(file2, depth + 1);
17566
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
17567
+ const info = await lstat(file2).catch(() => null);
17568
+ if (info?.isFile() && info.size > 0) {
17569
+ sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
17570
+ }
17571
+ }
17572
+ }
17573
+ };
17574
+ await visit(root, 0);
17575
+ return sources;
17576
+ }
17577
+ async function* jsonlRecords(file2, marker, signal) {
17578
+ const lines = createInterface({
17579
+ input: createReadStream(file2, { encoding: "utf8", signal }),
17580
+ crlfDelay: Infinity
17581
+ });
17582
+ for await (const line of lines) {
17583
+ if (!line.includes(marker))
17584
+ continue;
17585
+ let value;
17586
+ try {
17587
+ value = JSON.parse(line);
17588
+ } catch {
17589
+ continue;
17590
+ }
17591
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
17592
+ yield value;
17593
+ }
17594
+ }
17595
+ }
17596
+ async function jsonlHeader(file2, match, signal, maxLines = 4) {
17597
+ const stream = createReadStream(file2, { encoding: "utf8", signal });
17598
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
17599
+ let seen = 0;
17600
+ try {
17601
+ for await (const line of lines) {
17602
+ if (++seen > maxLines)
17603
+ break;
17604
+ let value;
17605
+ try {
17606
+ value = JSON.parse(line);
17607
+ } catch {
17608
+ continue;
17609
+ }
17610
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
17611
+ const record3 = value;
17612
+ if (match(record3))
17613
+ return record3;
17614
+ }
17615
+ }
17616
+ return null;
17617
+ } finally {
17618
+ lines.close();
17619
+ stream.destroy();
17620
+ }
17621
+ }
17622
+ function nativeTimeMs(value) {
17623
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
17624
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
17625
+ }
17626
+
17627
+ // dist/session-import.js
17628
+ import { createReadStream as createReadStream2 } from "node:fs";
17629
+ import { opendir as opendir2, realpath, stat } from "node:fs/promises";
17630
+ import os2 from "node:os";
17631
+ import path5 from "node:path";
17632
+ import { createInterface as createInterface2 } from "node:readline";
17633
+
17634
+ // ../../harness-adapter/dist/session-import.js
17635
+ import { lstat as lstat2 } from "node:fs/promises";
17636
+ var SessionImportChangedError = class extends Error {
17637
+ constructor(message3 = "Native Session changed during discovery; refresh and retry") {
17638
+ super(message3);
17639
+ this.name = "SessionImportChangedError";
17640
+ }
17641
+ };
17642
+ function isMissingFileError(error51) {
17643
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "ENOENT";
17644
+ }
17645
+ function sameFileFingerprint(left, right) {
17646
+ 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;
17647
+ }
17648
+ var STORAGE_ACCESS_ERRORS = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EIO", "EMFILE", "ENFILE"]);
17649
+ function isStorageAccessError(error51) {
17650
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && typeof error51.code === "string" && STORAGE_ACCESS_ERRORS.has(error51.code);
17651
+ }
17652
+ async function optionalLstat(file2) {
17653
+ try {
17654
+ return await lstat2(file2);
17655
+ } catch (error51) {
17656
+ if (isMissingFileError(error51))
17657
+ return null;
17658
+ throw error51;
17659
+ }
17660
+ }
17661
+ async function readStableFiles(files, read) {
17662
+ const before = await Promise.all(files.map(optionalLstat));
17663
+ const value = await read(before);
17664
+ const after = await Promise.all(files.map(optionalLstat));
17665
+ if (before.some((info, index) => !sameFileFingerprint(info, after[index] ?? null)))
17666
+ throw new SessionImportChangedError();
17667
+ return value;
17668
+ }
17669
+ function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
17670
+ if (typeof value !== "string")
17671
+ return null;
17672
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17673
+ if (!normalized)
17674
+ return null;
17675
+ if (normalized.length <= maxLength)
17676
+ return normalized;
17677
+ const characters = [...normalized];
17678
+ if (characters.length <= maxLength)
17679
+ return normalized;
17680
+ return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
17681
+ }
17682
+ function sessionImportCandidate(input) {
17683
+ const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
17684
+ const parsed = harnessSessionImportCandidateSchema.safeParse({
17685
+ nativeSessionId: input.nativeSessionId,
17686
+ cwd: input.cwd,
17687
+ title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
17688
+ updatedAt: Math.floor(time3),
17689
+ // Unknown must stay unknown; only an explicit boolean is a native statement.
17690
+ running: typeof input.running === "boolean" ? input.running : null
17691
+ });
17692
+ return parsed.success ? parsed.data : null;
17693
+ }
17694
+ var SessionImportScope = class {
17695
+ #abort = new AbortController();
17696
+ #options;
17697
+ #pending = /* @__PURE__ */ new Set();
17698
+ constructor(options) {
17699
+ this.#options = options;
17700
+ }
17701
+ #closed() {
17702
+ return {
17703
+ ok: false,
17704
+ error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
17705
+ };
17706
+ }
17707
+ read(operation) {
17708
+ const signal = this.#abort.signal;
17709
+ if (signal.aborted)
17710
+ return Promise.resolve(this.#closed());
17711
+ let started;
17712
+ try {
17713
+ started = operation(signal);
17714
+ } catch (error51) {
17715
+ started = Promise.reject(error51 instanceof Error ? error51 : new Error("Session read failed"));
17716
+ }
17717
+ const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
17718
+ ok: false,
17719
+ error: {
17720
+ code: "unavailable",
17721
+ message: this.#options.unavailableMessage,
17722
+ retryable: true
17723
+ }
17724
+ }).finally(() => this.#pending.delete(request));
17725
+ this.#pending.add(request);
17726
+ return request;
17727
+ }
17728
+ /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
17729
+ async resolve(operation) {
17730
+ const result = await this.read(operation);
17731
+ if (!result.ok)
17732
+ return result;
17733
+ return result.value ? { ok: true, value: result.value } : {
17734
+ ok: false,
17735
+ error: {
17736
+ code: "sessionNotFound",
17737
+ message: this.#options.notFoundMessage,
17738
+ retryable: false
17739
+ }
17740
+ };
17741
+ }
17742
+ /** Idempotent. Resolves after every started read has settled. */
17743
+ async close() {
17744
+ this.#abort.abort();
17745
+ await Promise.allSettled(this.#pending);
17746
+ }
17747
+ };
17748
+
17749
+ // dist/session-import.js
17750
+ function isRecord2(value) {
17751
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17752
+ }
17753
+ function expandDirectory(value, home) {
17754
+ return path5.resolve(value === "~" ? home : value.startsWith(`~${path5.sep}`) || value.startsWith("~/") ? path5.join(home, value.slice(2)) : value);
17755
+ }
17756
+ function ompSessionImportDirectory(environment) {
17757
+ const home = (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
17758
+ const custom2 = environment.PI_CODING_AGENT_SESSION_DIR;
17759
+ if (custom2)
17760
+ return { directory: expandDirectory(custom2, home), flat: true };
17761
+ const agent = environment.PI_CODING_AGENT_DIR;
17762
+ return {
17763
+ directory: path5.join(agent ? expandDirectory(agent, home) : path5.join(home, ".omp", "agent"), "sessions"),
17764
+ flat: false
17765
+ };
17766
+ }
17767
+ function messageText(content) {
17768
+ if (typeof content === "string")
17769
+ return content;
17770
+ if (!Array.isArray(content))
17771
+ return "";
17772
+ return content.filter((part) => isRecord2(part) && part.type === "text" && typeof part.text === "string").map((part) => String(part.text)).join(" ");
17773
+ }
17774
+ async function readFacts(file2, signal) {
17775
+ const stream = createReadStream2(file2, { encoding: "utf8", signal });
17776
+ const lines = createInterface2({ input: stream, crlfDelay: Infinity });
17777
+ let header = null;
17778
+ let nativeTitle = null;
17779
+ let firstPrompt = null;
17780
+ let updatedAt = null;
17781
+ let leafHasUser = false;
17782
+ const hasUserAncestry = /* @__PURE__ */ new Map();
17783
+ try {
17784
+ for await (const line of lines) {
17785
+ signal.throwIfAborted();
17786
+ if (!line.trim())
17787
+ continue;
17788
+ let entry;
17789
+ try {
17790
+ entry = JSON.parse(line);
17791
+ } catch {
17792
+ continue;
17793
+ }
17794
+ if (!isRecord2(entry))
17795
+ continue;
17796
+ if (entry.type === "title") {
17797
+ nativeTitle = sessionImportTitle(entry.title);
17798
+ continue;
17799
+ }
17800
+ if (entry.type === "session") {
17801
+ if (header)
17802
+ return null;
17803
+ if (typeof entry.id !== "string" || entry.id.length === 0 || typeof entry.cwd !== "string" || !path5.isAbsolute(entry.cwd))
17804
+ return null;
17805
+ header = { id: entry.id, cwd: entry.cwd };
17806
+ continue;
17807
+ }
17808
+ if (typeof entry.id !== "string" || entry.id.length === 0)
17809
+ continue;
17810
+ const message3 = isRecord2(entry.message) ? entry.message : null;
17811
+ const isUser = entry.type === "message" && message3?.role === "user";
17812
+ if (isUser)
17813
+ firstPrompt ??= sessionImportTitle(messageText(message3?.content));
17814
+ leafHasUser = isUser || typeof entry.parentId === "string" && hasUserAncestry.get(entry.parentId) === true;
17815
+ hasUserAncestry.set(entry.id, leafHasUser);
17816
+ if (entry.type === "message" && (message3?.role === "user" || message3?.role === "assistant")) {
17817
+ const time3 = typeof message3.timestamp === "number" ? message3.timestamp : typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : Number.NaN;
17818
+ if (Number.isFinite(time3) && time3 >= 0)
17819
+ updatedAt = time3;
17820
+ }
17821
+ }
17822
+ } finally {
17823
+ lines.close();
17824
+ stream.destroy();
17825
+ }
17826
+ if (!header || !leafHasUser)
17827
+ return null;
17828
+ return {
17829
+ nativeSessionId: header.id,
17830
+ cwd: header.cwd,
17831
+ title: nativeTitle ?? firstPrompt,
17832
+ updatedAt
17833
+ };
17834
+ }
17835
+ var OmpSessionImport = class {
17836
+ #location;
17837
+ #scope = new SessionImportScope({
17838
+ closedMessage: "Omp Session import is closed",
17839
+ unavailableMessage: "Omp sessions could not be read; close native clients, check storage access and retry",
17840
+ notFoundMessage: "Omp Session is no longer importable"
17841
+ });
17842
+ constructor(environment) {
17843
+ this.#location = ompSessionImportDirectory(environment);
17844
+ }
17845
+ listCandidates() {
17846
+ return this.#scope.read(async (signal) => [...(await this.#sources(signal)).values()].flatMap((sources) => (
17847
+ // One identity in two files cannot be resumed unambiguously.
17848
+ sources.length === 1 && sources[0] ? [sources[0].candidate] : []
17849
+ )));
17688
17850
  }
17689
- if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
17690
- throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
17851
+ resolveCandidate(nativeSessionId) {
17852
+ return this.#scope.resolve(async (signal) => {
17853
+ const sources = (await this.#sources(signal)).get(nativeSessionId);
17854
+ if (sources?.length !== 1 || !sources[0])
17855
+ return null;
17856
+ const source = await this.#source(sources[0].file, signal);
17857
+ return source?.nativeRef.nativeSessionId === nativeSessionId ? { candidate: source.candidate, nativeRef: source.nativeRef } : null;
17858
+ });
17691
17859
  }
17692
- if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
17693
- throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
17860
+ close() {
17861
+ return this.#scope.close();
17694
17862
  }
17695
- if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
17696
- throw new Error("Harness Usage request timing fields must be provided together");
17863
+ async #sessionFiles(signal) {
17864
+ const { directory, flat } = this.#location;
17865
+ const info = await optionalLstat(directory);
17866
+ if (!info)
17867
+ return [];
17868
+ if (!info.isDirectory())
17869
+ throw new Error("Omp Session store is not a directory");
17870
+ const files = [];
17871
+ const visit = async (current, projectLevel) => {
17872
+ const entries = await opendir2(current).catch((error51) => {
17873
+ if (isMissingFileError(error51))
17874
+ return null;
17875
+ throw error51;
17876
+ });
17877
+ if (!entries)
17878
+ return;
17879
+ for await (const entry of entries) {
17880
+ signal.throwIfAborted();
17881
+ if (projectLevel && entry.isDirectory())
17882
+ await visit(path5.join(current, entry.name), false);
17883
+ else if (!projectLevel && entry.isFile() && entry.name.endsWith(".jsonl"))
17884
+ files.push(path5.join(current, entry.name));
17885
+ }
17886
+ };
17887
+ await visit(directory, !flat);
17888
+ return files;
17697
17889
  }
17698
- if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
17699
- throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
17890
+ /** Session ID to every readable file claiming it. Files changing under the read are skipped. */
17891
+ async #sources(signal) {
17892
+ const found = /* @__PURE__ */ new Map();
17893
+ for (const file2 of await this.#sessionFiles(signal)) {
17894
+ signal.throwIfAborted();
17895
+ try {
17896
+ const source = await this.#source(file2, signal);
17897
+ if (!source)
17898
+ continue;
17899
+ const sources = found.get(source.nativeRef.nativeSessionId) ?? [];
17900
+ sources.push(source);
17901
+ found.set(source.nativeRef.nativeSessionId, sources);
17902
+ } catch (error51) {
17903
+ if (!(error51 instanceof SessionImportChangedError))
17904
+ throw error51;
17905
+ }
17906
+ }
17907
+ return found;
17700
17908
  }
17701
- return { ...request };
17702
- }
17703
-
17704
- // ../../harness-adapter/dist/live-command-catalog.js
17705
- var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
17706
- // Session lifecycle
17707
- "branch",
17708
- "clear",
17709
- "exit",
17710
- "fork",
17711
- "fresh",
17712
- "new",
17713
- "quit",
17714
- "rename",
17715
- "rename-chat",
17716
- "reset",
17717
- "resume",
17718
- "rewind",
17719
- "session",
17720
- "sessions",
17721
- // Desktop-owned configuration
17722
- "autocompact",
17723
- "color",
17724
- "config",
17725
- "effort",
17726
- "fast",
17727
- "keybindings",
17728
- "model",
17729
- "models",
17730
- "output-style",
17731
- "permissions",
17732
- "settings",
17733
- "statusline",
17734
- "terminal-setup",
17735
- "theme",
17736
- "vim",
17737
- // Trust and approval policy
17738
- "always-approve",
17739
- "auto-mode-setup",
17740
- // Native login
17741
- "login",
17742
- "logout",
17743
- // Work outliving the Turn
17744
- "autopilot",
17745
- "background",
17746
- "bg",
17747
- "goal",
17748
- "jobs",
17749
- "loop",
17750
- "multitask",
17751
- "queue",
17752
- "remote-control",
17753
- "schedule",
17754
- "steer",
17755
- // Native terminal UI
17756
- "copy",
17757
- "debug",
17758
- "feedback",
17759
- "heapdump",
17760
- "share",
17761
- "shell",
17762
- // Plugin and MCP management
17763
- "marketplace",
17764
- "mcp",
17765
- "plugins",
17766
- "reload-plugins"
17767
- ]);
17768
- var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
17769
- function isExcludedLiveCommand(name, kind, extra = {}) {
17770
- const normalized = name.trim().replace(/^\//u, "");
17771
- if (new Set(extra.names ?? []).has(normalized))
17772
- return true;
17773
- if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
17774
- return true;
17775
- if (kind === "skill")
17776
- return false;
17777
- return COMMON_EXCLUDED_LIVE_COMMANDS.has(normalized) || COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES.some((prefix) => normalized.startsWith(prefix));
17778
- }
17779
- function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17780
- if (!commandId.startsWith(idPrefix))
17781
- return null;
17782
- const descriptor = catalog.commands.find(({ id }) => id === commandId);
17783
- if (!descriptor)
17784
- return null;
17785
- const text = typeof argumentText === "string" ? argumentText.trim() : "";
17786
- return text ? `${descriptor.invocation} ${text}` : descriptor.invocation;
17787
- }
17788
- function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17789
- if (!live)
17790
- return builtIns;
17791
- const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
17792
- const ids = new Set(builtIns.commands.map(({ id }) => id));
17793
- const dynamic = [];
17794
- for (const command of live) {
17795
- const name = command.name.trim().replace(/^\//u, "");
17796
- if (!name || /\s/u.test(name))
17797
- continue;
17798
- if (isExcludedLiveCommand(name, command.kind, exclusions))
17799
- continue;
17800
- const invocation = `/${name}`;
17801
- const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
17802
- if (invocations.has(invocation) || ids.has(id))
17803
- continue;
17804
- const description = command.description?.trim().slice(0, 512);
17805
- const parsed = harnessCommandDescriptorSchema.safeParse({
17806
- id,
17807
- invocation,
17808
- label: name.slice(0, 128),
17809
- ...description ? { description } : {},
17810
- argumentMode: "text",
17811
- kind: command.kind
17909
+ async #source(file2, signal) {
17910
+ signal.throwIfAborted();
17911
+ return readStableFiles([file2], async ([info]) => {
17912
+ if (!info?.isFile() || info.size === 0)
17913
+ return null;
17914
+ try {
17915
+ const facts = await readFacts(file2, signal);
17916
+ if (!facts)
17917
+ return null;
17918
+ const cwd = await realpath(facts.cwd);
17919
+ if (!(await stat(cwd)).isDirectory())
17920
+ return null;
17921
+ const candidate = sessionImportCandidate({
17922
+ nativeSessionId: facts.nativeSessionId,
17923
+ cwd,
17924
+ title: facts.title,
17925
+ updatedAt: facts.updatedAt ?? info.mtimeMs
17926
+ // OMP has no cross-process activity marker: idleness cannot be established.
17927
+ });
17928
+ if (!candidate)
17929
+ return null;
17930
+ return {
17931
+ file: file2,
17932
+ candidate,
17933
+ // Resume needs the file itself: OMP is started with `--session <file>`.
17934
+ nativeRef: nativeSessionRefSchema.parse({
17935
+ harnessId: "omp",
17936
+ nativeSessionId: facts.nativeSessionId,
17937
+ locator: { sessionFile: await realpath(file2) },
17938
+ formatVersion: 1
17939
+ })
17940
+ };
17941
+ } catch (error51) {
17942
+ signal.throwIfAborted();
17943
+ if (isStorageAccessError(error51))
17944
+ throw error51;
17945
+ return null;
17946
+ }
17812
17947
  });
17813
- if (!parsed.success)
17814
- continue;
17815
- invocations.add(invocation);
17816
- ids.add(id);
17817
- dynamic.push(parsed.data);
17818
17948
  }
17819
- return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
17820
- }
17949
+ };
17821
17950
 
17822
17951
  // dist/omp-model-catalog.js
17823
17952
  var OMP_MODEL_REF_PREFIX = "omp-model-v1.";
@@ -18377,7 +18506,7 @@ var ompDiscoverySpec = {
18377
18506
  "/opt/homebrew/bin",
18378
18507
  "/usr/local/bin"
18379
18508
  ],
18380
- windows: ["${APPDATA}/npm", "~/.local/bin", VERSION_MANAGER_ROOTS]
18509
+ windows: ["${APPDATA}/npm", "${LOCALAPPDATA}/omp", "~/.local/bin", VERSION_MANAGER_ROOTS]
18381
18510
  }
18382
18511
  };
18383
18512
  function resolveOmpExecutable(input, dependencies = {}) {
@@ -18419,10 +18548,9 @@ function parseOmpAvailableCommands(value) {
18419
18548
  });
18420
18549
  }
18421
18550
  function ompLiveCommands(native) {
18422
- return native.filter(({ source, name }) => source !== "builtin" || name === "context").map((command) => ({
18551
+ return native.filter(({ source, name }) => source !== "skill" && (source !== "builtin" || name === "context")).map((command) => ({
18423
18552
  name: command.name,
18424
- description: command.description,
18425
- kind: command.source === "skill" ? "skill" : "command"
18553
+ description: command.description
18426
18554
  }));
18427
18555
  }
18428
18556
 
@@ -18634,6 +18762,9 @@ var OmpRpcUnsupportedCommandError = class extends Error {
18634
18762
  this.name = "OmpRpcUnsupportedCommandError";
18635
18763
  }
18636
18764
  };
18765
+ function hasTurnCompletion(active) {
18766
+ return active.terminalEnd || active.localResult !== null && !active.sawAgentStart;
18767
+ }
18637
18768
  var textDecoder = new TextDecoder("utf-8", { fatal: true });
18638
18769
  function isRecord8(value) {
18639
18770
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -18690,9 +18821,9 @@ function parseSessionStreaming(response) {
18690
18821
  }
18691
18822
  return isStreaming;
18692
18823
  }
18693
- function cancellationSettled(response, terminalEnd) {
18824
+ function sessionSettled(response, completed) {
18694
18825
  const data = sessionStateData(response);
18695
- return !parseSessionStreaming(response) && (data.isSettled === true || data.isSettled === void 0 && terminalEnd) && data.isCompacting !== true && data.hasPendingAsyncWork !== true && !(typeof data.queuedMessageCount === "number" && data.queuedMessageCount > 0);
18826
+ return !parseSessionStreaming(response) && (data.isSettled === true || data.isSettled === void 0 && completed) && data.isCompacting !== true && data.hasPendingAsyncWork !== true && !(typeof data.queuedMessageCount === "number" && data.queuedMessageCount > 0);
18696
18827
  }
18697
18828
  function parseAvailableModels(response) {
18698
18829
  const data = isRecord8(response.data) ? response.data : null;
@@ -18861,6 +18992,7 @@ var OmpRpcSession = class {
18861
18992
  #latestCacheHitRatePercent;
18862
18993
  #manualCompaction = null;
18863
18994
  #usageRequestStartedAtMs = null;
18995
+ #usageRequestTimingUnavailable = false;
18864
18996
  #stderrTail = "";
18865
18997
  #frameDecoder = new OmpFrameDecoder();
18866
18998
  #startupFaultResolve = null;
@@ -18924,6 +19056,9 @@ var OmpRpcSession = class {
18924
19056
  child.stderr.on("data", (chunk) => {
18925
19057
  this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
18926
19058
  });
19059
+ child.stdin.on("error", (error51) => {
19060
+ this.#fail(new OmpRpcFaultError("processExited", `Omp RPC stdin closed: ${error51.message}`, this.stderrTail));
19061
+ });
18927
19062
  child.once("error", (error51) => {
18928
19063
  const kind = isRecord8(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
18929
19064
  this.#fail(new OmpRpcFaultError(kind, `Omp RPC failed to start: ${error51.message}`, this.stderrTail));
@@ -19170,7 +19305,10 @@ var OmpRpcSession = class {
19170
19305
  tools: /* @__PURE__ */ new Map(),
19171
19306
  interactions: /* @__PURE__ */ new Map(),
19172
19307
  settlement: "pending",
19308
+ settledNotice: false,
19309
+ settlementRecheck: null,
19173
19310
  terminalEnd: false,
19311
+ sawAgentStart: false,
19174
19312
  cancellation: "none",
19175
19313
  cancellationTimeout: null,
19176
19314
  cancellationRecheck: null,
@@ -19380,12 +19518,21 @@ var OmpRpcSession = class {
19380
19518
  if (this.#handleSubagentFrame(active, value))
19381
19519
  return;
19382
19520
  this.#observeUsage(value);
19383
- if (value.type === "agent_start" && active)
19521
+ if (value.type === "agent_start" && active) {
19384
19522
  active.terminalEnd = false;
19523
+ active.sawAgentStart = true;
19524
+ }
19385
19525
  if ((value.type === "session_settled" || value.type === "agent_start") && active?.cancellation === "accepted") {
19386
19526
  void this.#confirmCancelledTurn(active);
19387
19527
  return;
19388
19528
  }
19529
+ if (value.type === "session_settled") {
19530
+ if (active && hasTurnCompletion(active)) {
19531
+ active.settledNotice = true;
19532
+ void this.#confirmSettledTurn(active);
19533
+ }
19534
+ return;
19535
+ }
19389
19536
  if (!active) {
19390
19537
  if (value.type === "extension_ui_request" && this.#isBlockingInteraction(value)) {
19391
19538
  this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC requested blocking Extension UI outside an active Turn"));
@@ -19480,9 +19627,6 @@ var OmpRpcSession = class {
19480
19627
  void this.#confirmCancelledTurn(active);
19481
19628
  return;
19482
19629
  }
19483
- if (active.settlement !== "pending")
19484
- return;
19485
- active.settlement = "confirming";
19486
19630
  void this.#confirmSettledTurn(active);
19487
19631
  }
19488
19632
  }
@@ -19490,12 +19634,26 @@ var OmpRpcSession = class {
19490
19634
  #observeUsage(value) {
19491
19635
  if (value.type === "message_start") {
19492
19636
  this.#usageRequestStartedAtMs = null;
19637
+ this.#usageRequestTimingUnavailable = false;
19493
19638
  return;
19494
19639
  }
19495
19640
  if (value.type === "message_update") {
19496
19641
  const event = value.assistantMessageEvent;
19497
- if (this.#usageRequestStartedAtMs === null && isRecord8(event) && typeof event.type === "string" && /^(text|thinking|reasoning|thought|toolcall)_(start|delta)$/u.test(event.type)) {
19498
- this.#usageRequestStartedAtMs = Date.now();
19642
+ if (this.#usageRequestStartedAtMs === null && !this.#usageRequestTimingUnavailable && isRecord8(event) && typeof event.type === "string") {
19643
+ if (
19644
+ // Native thinking starts can precede visible text by seconds; output usage includes it.
19645
+ /^(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
19646
+ )
19647
+ this.#usageRequestStartedAtMs = Date.now();
19648
+ else if (event.type === "toolcall_delta" && typeof event.delta === "string" && event.delta.length > 0) {
19649
+ try {
19650
+ JSON.parse(event.delta);
19651
+ this.#usageRequestTimingUnavailable = true;
19652
+ } catch {
19653
+ this.#usageRequestStartedAtMs = Date.now();
19654
+ }
19655
+ } else if (event.type === "toolcall_end")
19656
+ this.#usageRequestTimingUnavailable = true;
19499
19657
  }
19500
19658
  return;
19501
19659
  }
@@ -19534,6 +19692,7 @@ var OmpRpcSession = class {
19534
19692
  const description = nonBlankString(payload.description) ? payload.description : nonBlankString(payload.agent) ? `${payload.agent} delegation` : "Subagent delegation";
19535
19693
  emit?.({
19536
19694
  type: "subagent.started",
19695
+ ...subagentConfiguration(payload),
19537
19696
  callId,
19538
19697
  nativeSubagentId,
19539
19698
  description,
@@ -19566,6 +19725,8 @@ var OmpRpcSession = class {
19566
19725
  const resultSummary = recentOutput.at(-1);
19567
19726
  emit?.({
19568
19727
  type: "subagent.updated",
19728
+ ...subagentConfiguration(payload),
19729
+ ...subagentConfiguration(progress),
19569
19730
  callId,
19570
19731
  nativeSubagentId,
19571
19732
  status,
@@ -19800,7 +19961,7 @@ var OmpRpcSession = class {
19800
19961
  throw new OmpRpcFaultError("protocolError", "Omp cancelled Session reload changed its identity or configuration");
19801
19962
  }
19802
19963
  }
19803
- if (!cancellationSettled(response, active.terminalEnd)) {
19964
+ if (!sessionSettled(response, active.terminalEnd)) {
19804
19965
  active.settlement = "pending";
19805
19966
  active.cancellationRecheck = setTimeout(() => {
19806
19967
  active.cancellationRecheck = null;
@@ -19824,10 +19985,15 @@ var OmpRpcSession = class {
19824
19985
  if (this.#activeTurn !== active || active.settlement !== "pending")
19825
19986
  return;
19826
19987
  active.localResult = result;
19827
- active.settlement = "confirming";
19828
19988
  void this.#confirmSettledTurn(active);
19829
19989
  }
19830
19990
  async #confirmSettledTurn(active) {
19991
+ if (this.#activeTurn !== active || active.settlement !== "pending" || active.cancellation !== "none" || !hasTurnCompletion(active))
19992
+ return;
19993
+ if (active.settlementRecheck)
19994
+ clearTimeout(active.settlementRecheck);
19995
+ active.settlementRecheck = null;
19996
+ active.settlement = "confirming";
19831
19997
  try {
19832
19998
  const response = await this.#send("get_state", {});
19833
19999
  const state = parseSessionState(response);
@@ -19839,8 +20005,21 @@ var OmpRpcSession = class {
19839
20005
  void this.#confirmCancelledTurn(active);
19840
20006
  return;
19841
20007
  }
19842
- if (parseSessionStreaming(response)) {
19843
- throw new OmpRpcFaultError("protocolError", "Omp RPC completed Turn state is still Streaming");
20008
+ if (!hasTurnCompletion(active)) {
20009
+ active.settlement = "pending";
20010
+ active.settledNotice = false;
20011
+ return;
20012
+ }
20013
+ if (!sessionSettled(response, hasTurnCompletion(active))) {
20014
+ active.settlement = "pending";
20015
+ if (active.settledNotice) {
20016
+ active.settledNotice = false;
20017
+ active.settlementRecheck = setTimeout(() => {
20018
+ active.settlementRecheck = null;
20019
+ void this.#confirmSettledTurn(active);
20020
+ }, 50);
20021
+ }
20022
+ return;
19844
20023
  }
19845
20024
  this.#state = state;
19846
20025
  active.settlement = "confirmed";
@@ -19856,6 +20035,9 @@ var OmpRpcSession = class {
19856
20035
  if (this.#activeTurn !== active || active.settlement !== "confirmed" || active.cancellation === "requesting") {
19857
20036
  return;
19858
20037
  }
20038
+ if (active.settlementRecheck)
20039
+ clearTimeout(active.settlementRecheck);
20040
+ active.settlementRecheck = null;
19859
20041
  if (active.cancellationTimeout)
19860
20042
  clearTimeout(active.cancellationTimeout);
19861
20043
  active.cancellationTimeout = null;
@@ -20017,6 +20199,8 @@ var OmpRpcSession = class {
20017
20199
  const active = this.#activeTurn;
20018
20200
  if (!active)
20019
20201
  return;
20202
+ if (active.settlementRecheck)
20203
+ clearTimeout(active.settlementRecheck);
20020
20204
  if (active.cancellationTimeout)
20021
20205
  clearTimeout(active.cancellationTimeout);
20022
20206
  if (active.cancellationRecheck)
@@ -20791,6 +20975,7 @@ var OmpSubagentLifecycle = class {
20791
20975
  subagentId: event.nativeSubagentId,
20792
20976
  nativeSubagentId: event.nativeSubagentId,
20793
20977
  description: event.description,
20978
+ ...subagentConfiguration(event),
20794
20979
  ...event.role ? { role: event.role } : {},
20795
20980
  background: event.background,
20796
20981
  status: "running"
@@ -20815,6 +21000,7 @@ var OmpSubagentLifecycle = class {
20815
21000
  throw new Error("Omp Subagent delegation has no Agent state");
20816
21001
  const subagent = {
20817
21002
  ...current,
21003
+ ...subagentConfiguration(event),
20818
21004
  status: event.status === "interrupted" ? "interrupted" : event.status,
20819
21005
  ...event.description ? { description: event.description } : {},
20820
21006
  ...event.resultSummary ? { resultSummary: event.resultSummary } : {},
@@ -21365,7 +21551,19 @@ var OmpHarnessSession = class {
21365
21551
  ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
21366
21552
  });
21367
21553
  }
21554
+ #subagentConfiguration() {
21555
+ const state = this.#state;
21556
+ const model2 = state.effectiveModel ? decodeOmpModelRef(state.effectiveModel).id : void 0;
21557
+ return {
21558
+ ...model2 ? { model: model2 } : {},
21559
+ ...state.effectiveThinkingOptionId ? { reasoningEffort: state.effectiveThinkingOptionId } : {}
21560
+ };
21561
+ }
21368
21562
  async readSnapshot() {
21563
+ const result = await this.#readSnapshot();
21564
+ return result.ok ? { ok: true, value: configureSubagentSnapshot(result.value, this.#subagentConfiguration()) } : result;
21565
+ }
21566
+ async #readSnapshot() {
21369
21567
  if (this.#phase !== "open" && this.#phase !== "faulted") {
21370
21568
  return { ok: false, error: invalidState("Omp Session is not open") };
21371
21569
  }
@@ -22552,6 +22750,7 @@ var OmpHarnessSession = class {
22552
22750
  }
22553
22751
  }
22554
22752
  #event(event) {
22753
+ event = configureSubagentEvent(event, this.#subagentConfiguration());
22555
22754
  this.#channel.emit({ kind: "event", event });
22556
22755
  }
22557
22756
  #newItemId() {