@codexhost/cli-darwin-x64 0.13.2 → 0.14.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 (33) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +94 -8
  4. package/app/console-web.js +537 -146
  5. package/app/desktop-controller.mjs +108 -12
  6. package/app/host-runtime.mjs +847 -235
  7. package/app/plugins/antigravity/plugin.mjs +143 -20
  8. package/app/plugins/claude-code/plugin.mjs +601 -71
  9. package/app/plugins/codebuddy/plugin.mjs +227 -30
  10. package/app/plugins/codex-usage/plugin.mjs +212 -77
  11. package/app/plugins/copilot/assets/icon.png +0 -0
  12. package/app/plugins/copilot/manifest.json +26 -0
  13. package/app/plugins/copilot/plugin.mjs +34546 -0
  14. package/app/plugins/cursor-cli/plugin.mjs +20805 -44862
  15. package/app/plugins/deepseek-harness/manifest.json +2 -2
  16. package/app/plugins/deepseek-harness/plugin.mjs +202 -21
  17. package/app/plugins/enabled.json +1 -0
  18. package/app/plugins/grok/plugin.mjs +278 -29
  19. package/app/plugins/hermes/plugin.mjs +143 -12
  20. package/app/plugins/kimi-code/plugin.mjs +140 -16
  21. package/app/plugins/kiro-cli/plugin.mjs +121 -10
  22. package/app/plugins/omp/plugin.mjs +2200 -2002
  23. package/app/plugins/opencode/plugin.mjs +137 -16
  24. package/app/plugins/pi/plugin.mjs +2563 -2282
  25. package/app/plugins/qoder/plugin.mjs +133 -14
  26. package/app/plugins/qoder-cn/plugin.mjs +133 -14
  27. package/app/plugins/workbuddy/plugin.mjs +603 -56
  28. package/app/plugins/zcode/plugin.mjs +133 -14
  29. package/app/renderer-extension.js +1171 -529
  30. package/bin/codexhost +0 -0
  31. package/libexec/codexhost-shim +0 -0
  32. package/libexec/codexhost-updater +0 -0
  33. package/package.json +1 -1
@@ -424,10 +424,13 @@ function usageSessionTitle(value) {
424
424
  return void 0;
425
425
  if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
426
426
  return normalized;
427
- const characters = [...normalized];
428
- if (characters.length <= MAX_SESSION_TITLE_LENGTH)
429
- return normalized;
430
- return `${characters.slice(0, MAX_SESSION_TITLE_LENGTH - 1).join("").trimEnd()}…`;
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()}…`;
431
434
  }
432
435
  function sessionIdOk(value) {
433
436
  return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
@@ -15144,6 +15147,15 @@ var harnessDisplaySetSchema = external_exports.strictObject({
15144
15147
  initializeOnly: external_exports.boolean().optional()
15145
15148
  });
15146
15149
 
15150
+ // ../../shared-contracts/dist/harness-presentation.js
15151
+ var localeSchema = external_exports.string().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u);
15152
+ var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text) => text.trim().length > 0);
15153
+ var harnessLocalizationsSchema = external_exports.record(localeSchema, external_exports.object({
15154
+ label: displayText(256).optional(),
15155
+ description: displayText(1024).optional()
15156
+ }).strict()).refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
15157
+ var harnessLocalizedTextSchema = external_exports.record(localeSchema, displayText(4096)).refine((entries) => typeof entries.en === "string", "English fallback is required").refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
15158
+
15147
15159
  // ../../shared-contracts/dist/model-price-overrides.js
15148
15160
  var usdPerMillionTokens = external_exports.number().finite().nonnegative();
15149
15161
  var modelPriceOverrideSchema = external_exports.strictObject({
@@ -15193,10 +15205,19 @@ var model = external_exports.string().min(1).max(512);
15193
15205
  var project = external_exports.string().min(1).max(4096);
15194
15206
  var usageStatisticsParamsSchema = external_exports.strictObject({
15195
15207
  range: external_exports.enum(USAGE_STATISTICS_RANGES),
15208
+ /** Display timezone for ranges, dates and hourly buckets; omitted means the Host's local zone. */
15209
+ timeZone: external_exports.string().min(1).max(128).refine((value) => {
15210
+ try {
15211
+ new Intl.DateTimeFormat("en", { timeZone: value });
15212
+ return true;
15213
+ } catch {
15214
+ return false;
15215
+ }
15216
+ }, "Unsupported usage statistics timezone").optional(),
15196
15217
  harness: harness.optional(),
15197
15218
  model: model.nullable().optional(),
15198
15219
  project: project.nullable().optional(),
15199
- /** One local date inside the range. */
15220
+ /** One date in the query timezone inside the range. */
15200
15221
  date: localDate.optional()
15201
15222
  });
15202
15223
  var usageStatisticsTotalsSchema = external_exports.strictObject({
@@ -15232,7 +15253,7 @@ var usageStatisticsSessionSchema = external_exports.strictObject({
15232
15253
  });
15233
15254
  var usageStatisticsResultSchema = external_exports.strictObject({
15234
15255
  range: external_exports.enum(USAGE_STATISTICS_RANGES),
15235
- /** First local date of the range; null for all time. */
15256
+ /** First date in the query timezone (Host local when omitted); null for all time. */
15236
15257
  from: localDate.nullable(),
15237
15258
  to: localDate,
15238
15259
  /** The filters these figures apply, echoed so a late answer to older filters is recognised. */
@@ -15272,7 +15293,7 @@ var usageStatisticsResultSchema = external_exports.strictObject({
15272
15293
  totals: usageStatisticsTotalsSchema,
15273
15294
  /** Each date and Harness of the range: every filter except the day. */
15274
15295
  daily: external_exports.array(external_exports.strictObject({ date: localDate, harness, ...totals })).max(2e5),
15275
- /** Local weekday (0 = Sunday) and hour, all filters applied. */
15296
+ /** Weekday (0 = Sunday) and hour in the query timezone, all filters applied. */
15276
15297
  hourly: external_exports.array(external_exports.strictObject({
15277
15298
  weekday: external_exports.number().int().min(0).max(6),
15278
15299
  hour: external_exports.number().int().min(0).max(23),
@@ -15332,6 +15353,8 @@ var CONSOLE_HOST_METHODS = Object.freeze([
15332
15353
  "codexhost/harness/display-settings/set",
15333
15354
  "codexhost/harness/inspect",
15334
15355
  "codexhost/harness/installation",
15356
+ "codexhost/harness/installation/start",
15357
+ "codexhost/harness/installation/status",
15335
15358
  "codexhost/harness/launch-settings/get",
15336
15359
  "codexhost/harness/launch-settings/set",
15337
15360
  "codexhost/harness/web-ui/open",
@@ -15407,7 +15430,18 @@ var threadManualCompactionStartedSchema = external_exports.strictObject({
15407
15430
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15408
15431
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
15409
15432
  var cacheHitRatePercentSchema = external_exports.number().finite().min(0).max(100);
15433
+ var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text) => text.length <= maximum));
15434
+ var composerIndicatorsSchema = external_exports.array(external_exports.object({
15435
+ kind: external_exports.literal("countdown"),
15436
+ id: external_exports.string().min(1).max(64),
15437
+ expiresAtUnix: nonNegativeSafeIntegerSchema,
15438
+ label: indicatorTextSchema(256).optional(),
15439
+ tooltip: indicatorTextSchema(1024).optional()
15440
+ }).strict()).max(2).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, {
15441
+ message: "Composer indicator IDs must be unique"
15442
+ });
15410
15443
  var threadUsageSnapshotSchema = external_exports.object({
15444
+ composerIndicators: composerIndicatorsSchema.optional(),
15411
15445
  inputTokens: nonNegativeSafeIntegerSchema.optional(),
15412
15446
  cachedInputTokens: nonNegativeSafeIntegerSchema.optional(),
15413
15447
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
@@ -15480,8 +15514,24 @@ var threadUsageSnapshotSchema = external_exports.object({
15480
15514
  }
15481
15515
  });
15482
15516
  var usagePercentSchema = external_exports.number().finite().min(0).max(100);
15517
+ var accountCreditsPeriodSchema = external_exports.enum([
15518
+ "weekly",
15519
+ "monthly",
15520
+ "five_hour",
15521
+ "seven_day",
15522
+ "unknown"
15523
+ ]);
15524
+ var accountCreditsScopeSchema = external_exports.object({
15525
+ id: external_exports.string().min(1).max(256),
15526
+ label: external_exports.string().min(1).max(256),
15527
+ localizations: harnessLocalizationsSchema.optional()
15528
+ }).strict();
15483
15529
  var accountCreditsProductUsageSchema = external_exports.object({
15484
15530
  product: external_exports.string().min(1),
15531
+ /** Native period and scope, never inferred from the display name. */
15532
+ periodType: accountCreditsPeriodSchema.optional(),
15533
+ scope: accountCreditsScopeSchema.optional(),
15534
+ localizations: harnessLocalizationsSchema.optional(),
15485
15535
  used: external_exports.number().finite().nonnegative().optional(),
15486
15536
  // Zero is a real empty cap, not an absent field.
15487
15537
  limit: external_exports.number().finite().nonnegative().optional(),
@@ -15501,9 +15551,11 @@ var accountCreditsSnapshotSchema = external_exports.object({
15501
15551
  unit: external_exports.string().min(1).max(32).optional(),
15502
15552
  /** Native label when the primary limit is scoped to a model or product group. */
15503
15553
  label: external_exports.string().min(1).optional(),
15554
+ scope: accountCreditsScopeSchema.optional(),
15555
+ localizations: harnessLocalizationsSchema.optional(),
15504
15556
  usedPercent: usagePercentSchema,
15505
15557
  resetsAt: external_exports.string().min(1).optional(),
15506
- periodType: external_exports.enum(["weekly", "monthly", "five_hour", "seven_day", "unknown"]),
15558
+ periodType: accountCreditsPeriodSchema,
15507
15559
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
15508
15560
  resetCredits: accountResetCreditsSchema.optional()
15509
15561
  }).strict();
@@ -15514,7 +15566,9 @@ var threadUsageInspectionParamsSchema = external_exports.object({
15514
15566
  var threadUsageInspectionSchema = external_exports.object({
15515
15567
  threadId: hostThreadIdSchema,
15516
15568
  usage: threadUsageSnapshotSchema.nullable(),
15517
- accountCredits: accountCreditsSnapshotSchema.optional()
15569
+ accountCredits: accountCreditsSnapshotSchema.optional(),
15570
+ /** Whether this source can provide cached account quota independently of usage. */
15571
+ accountCreditsSupported: external_exports.boolean().optional()
15518
15572
  }).strict();
15519
15573
 
15520
15574
  // ../../shared-contracts/dist/harness-accounts.js
@@ -15641,7 +15695,8 @@ var harnessPermissionModeSchema = external_exports.object({
15641
15695
  id: harnessPermissionModeIdSchema,
15642
15696
  label: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH),
15643
15697
  description: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH).optional(),
15644
- dangerous: external_exports.boolean().optional()
15698
+ dangerous: external_exports.boolean().optional(),
15699
+ localizations: harnessLocalizationsSchema.optional()
15645
15700
  }).strict();
15646
15701
  var harnessPermissionModeCatalogSchema = external_exports.object({
15647
15702
  modes: external_exports.array(harnessPermissionModeSchema).min(1).max(HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH),
@@ -15794,7 +15849,9 @@ var harnessSessionCapabilitiesSchema = external_exports.object({
15794
15849
  }).strict().optional(),
15795
15850
  autonomousTurns: external_exports.object({
15796
15851
  observe: external_exports.boolean()
15797
- }).strict().optional()
15852
+ }).strict().optional(),
15853
+ /** True only when `turn.steer` delivers input into the active Turn through a native primitive. */
15854
+ steer: external_exports.boolean().optional()
15798
15855
  }).strict();
15799
15856
  var harnessConfigurationStateSchema = external_exports.object({
15800
15857
  effectiveModel: harnessModelRefSchema.optional(),
@@ -15841,7 +15898,9 @@ var harnessInspectionSchema = external_exports.union([
15841
15898
  var harnessInspectParamsSchema = external_exports.object({
15842
15899
  harnessId: harnessIdSchema,
15843
15900
  cwd: nonBlankTextSchema2.max(16384).optional(),
15844
- refresh: external_exports.boolean().optional()
15901
+ refresh: external_exports.boolean().optional(),
15902
+ /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
15903
+ purpose: external_exports.literal("availability").optional()
15845
15904
  }).strict();
15846
15905
  var harnessWebUiOpenParamsSchema = external_exports.object({
15847
15906
  harnessId: harnessIdSchema
@@ -15924,6 +15983,15 @@ var threadOwnershipListResultSchema = external_exports.object({
15924
15983
  seen.add(thread.threadId);
15925
15984
  }
15926
15985
  });
15986
+ var threadSteeringInspectParamsSchema = external_exports.object({
15987
+ threadId: hostThreadIdSchema,
15988
+ /** The text about to be steered; a Harness command always stops and restarts. */
15989
+ text: external_exports.string().optional()
15990
+ }).strict();
15991
+ var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
15992
+ var threadSteeringInspectResultSchema = external_exports.object({
15993
+ delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15994
+ }).strict();
15927
15995
 
15928
15996
  // ../../shared-contracts/dist/harness-plugins.js
15929
15997
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
@@ -16025,11 +16093,31 @@ var harnessInstallationStateSchema = external_exports.object({
16025
16093
  latestVersion: external_exports.string().min(1).max(128),
16026
16094
  updateAvailable: external_exports.boolean(),
16027
16095
  canUpdate: external_exports.boolean(),
16096
+ /** Defaults to CLI; some Harnesses ship only inside a desktop application. */
16097
+ versionKind: external_exports.enum(["cli", "application"]).optional(),
16098
+ /** Official download opened by the user; does not imply an automatic installation. */
16099
+ manualUpdateUrl: external_exports.url().max(2048).refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Manual updates require a credential-free HTTPS URL").optional(),
16028
16100
  // Adapter-owned diagnostic text; UI uses messageCode rather than displaying it verbatim.
16029
16101
  message: external_exports.string().max(2048).optional(),
16030
16102
  messageCode: external_exports.string().min(1).max(128).optional(),
16103
+ /** Safe plugin-owned explanation, distinct from raw diagnostic message. */
16104
+ notice: harnessLocalizedTextSchema.optional(),
16031
16105
  latestVersionKind: external_exports.enum(["unknown", "tracking-branch"]).optional()
16032
16106
  }).strict();
16107
+ var harnessInstallationTaskParamsSchema = external_exports.object({ taskId: external_exports.string().uuid() }).strict();
16108
+ var harnessInstallationTaskSchema = external_exports.discriminatedUnion("status", [
16109
+ external_exports.object({ taskId: external_exports.string().uuid(), status: external_exports.literal("running") }).strict(),
16110
+ external_exports.object({
16111
+ taskId: external_exports.string().uuid(),
16112
+ status: external_exports.literal("succeeded"),
16113
+ result: harnessInstallationStateSchema
16114
+ }).strict(),
16115
+ external_exports.object({
16116
+ taskId: external_exports.string().uuid(),
16117
+ status: external_exports.literal("failed"),
16118
+ error: external_exports.object({ code: external_exports.number().int(), message: external_exports.string().min(1).max(2048) }).strict()
16119
+ }).strict()
16120
+ ]);
16033
16121
 
16034
16122
  // ../../shared-contracts/dist/codex-accounts.js
16035
16123
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
@@ -16154,6 +16242,7 @@ var harnessCommandDescriptorSchema = external_exports.object({
16154
16242
  invocation: commandInvocationSchema,
16155
16243
  label: commandLabelSchema,
16156
16244
  description: commandDescriptionSchema.optional(),
16245
+ localizations: harnessLocalizationsSchema.optional(),
16157
16246
  argumentMode: external_exports.enum(["none", "text"]),
16158
16247
  /**
16159
16248
  * Native distinction reported by the Harness. Omitted when the Harness does
@@ -16830,6 +16919,18 @@ function sanitizeDiagnosticTail(value) {
16830
16919
  return redacted.length <= DIAGNOSTIC_TAIL_MAX_LENGTH ? redacted : redacted.slice(-DIAGNOSTIC_TAIL_MAX_LENGTH);
16831
16920
  }
16832
16921
 
16922
+ // ../../harness-adapter/dist/steer.js
16923
+ function unsupportedSteer(harnessLabel) {
16924
+ return {
16925
+ ok: false,
16926
+ error: {
16927
+ code: "unsupported",
16928
+ message: `${harnessLabel} cannot steer an active Turn natively`,
16929
+ retryable: false
16930
+ }
16931
+ };
16932
+ }
16933
+
16833
16934
  // ../../harness-adapter/dist/usage.js
16834
16935
  var tokenFields = [
16835
16936
  "inputTokens",
@@ -16857,6 +16958,7 @@ var usageFields = /* @__PURE__ */ new Set([
16857
16958
  ...safeIntegerFields,
16858
16959
  ...percentFields,
16859
16960
  "sessionCacheUsage",
16961
+ "composerIndicators",
16860
16962
  "totalCostUsd",
16861
16963
  "totalCredits",
16862
16964
  "contextUsagePercent",
@@ -16879,6 +16981,7 @@ function parseHostUsage(value) {
16879
16981
  throw new Error(`Harness Usage contains unknown field '${key}'`);
16880
16982
  }
16881
16983
  }
16984
+ const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
16882
16985
  for (const field of [
16883
16986
  "totalCredits",
16884
16987
  "contextUsagePercent",
@@ -16949,9 +17052,9 @@ function parseHostUsage(value) {
16949
17052
  if (value.costSource !== "publicPrice") {
16950
17053
  throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
16951
17054
  }
16952
- return { ...value, unpricedModels: [...models] };
17055
+ return { ...value, ...indicators, unpricedModels: [...models] };
16953
17056
  }
16954
- return { ...value };
17057
+ return { ...value, ...indicators };
16955
17058
  }
16956
17059
  var requestTokenFields = [
16957
17060
  "inputTokens",
@@ -17678,857 +17781,283 @@ function createOmpUsageStatistics(environment) {
17678
17781
  });
17679
17782
  }
17680
17783
 
17681
- // ../../../node_modules/diff/libesm/diff/base.js
17682
- var Diff = class {
17683
- diff(oldStr, newStr, options = {}) {
17684
- let callback;
17685
- if (typeof options === "function") {
17686
- callback = options;
17687
- options = {};
17688
- } else if ("callback" in options) {
17689
- callback = options.callback;
17690
- }
17691
- const oldString = this.castInput(oldStr, options);
17692
- const newString = this.castInput(newStr, options);
17693
- const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
17694
- const newTokens = this.removeEmpty(this.tokenize(newString, options));
17695
- return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
17784
+ // dist/omp-model-list.js
17785
+ import { spawn as spawn2 } from "node:child_process";
17786
+
17787
+ // dist/command.js
17788
+ var ompDiscoverySpec = {
17789
+ id: "omp",
17790
+ command: "omp",
17791
+ commandEnvironmentVariable: "OMP_COMMAND",
17792
+ installRoots: {
17793
+ posix: [
17794
+ "~/.npm-global/bin",
17795
+ "~/.local/bin",
17796
+ VERSION_MANAGER_ROOTS,
17797
+ "/opt/homebrew/bin",
17798
+ "/usr/local/bin"
17799
+ ],
17800
+ windows: ["${APPDATA}/npm", "~/.local/bin", VERSION_MANAGER_ROOTS]
17696
17801
  }
17697
- diffWithOptionsObj(oldTokens, newTokens, options, callback) {
17698
- var _a3;
17699
- const done = (value) => {
17700
- value = this.postProcess(value, options);
17701
- if (callback) {
17702
- setTimeout(function() {
17703
- callback(value);
17704
- }, 0);
17705
- return void 0;
17706
- } else {
17707
- return value;
17802
+ };
17803
+ function resolveOmpExecutable(input, dependencies = {}) {
17804
+ const resolution = resolveHarnessExecutable(ompDiscoverySpec, {
17805
+ ...input.command ? { command: input.command } : {},
17806
+ environment: input.environment,
17807
+ ...dependencies.platform ? { platform: dependencies.platform } : {},
17808
+ ...dependencies.homeDirectory ? { homeDirectory: dependencies.homeDirectory } : {}
17809
+ }, { ...dependencies.isExecutable ? { isExecutable: dependencies.isExecutable } : {} });
17810
+ return resolution?.executable ?? input.command ?? input.environment.OMP_COMMAND ?? "omp";
17811
+ }
17812
+
17813
+ // dist/omp-rpc-session.js
17814
+ import { spawn, spawnSync } from "node:child_process";
17815
+ import { randomUUID } from "node:crypto";
17816
+ import path6 from "node:path";
17817
+
17818
+ // dist/omp-slash-commands.js
17819
+ var OMP_LIVE_COMMAND_ID_PREFIX = "omp.slash.";
17820
+ function isRecord6(value) {
17821
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17822
+ }
17823
+ function parseOmpAvailableCommands(value) {
17824
+ if (!Array.isArray(value))
17825
+ return [];
17826
+ return value.flatMap((entry) => {
17827
+ if (!isRecord6(entry))
17828
+ return [];
17829
+ const name = typeof entry.name === "string" ? entry.name.trim().replace(/^\//u, "") : "";
17830
+ if (!name)
17831
+ return [];
17832
+ return [
17833
+ {
17834
+ name,
17835
+ description: typeof entry.description === "string" ? entry.description : "",
17836
+ source: typeof entry.source === "string" ? entry.source : null
17708
17837
  }
17709
- };
17710
- const newLen = newTokens.length, oldLen = oldTokens.length;
17711
- let editLength = 1;
17712
- let maxEditLength = newLen + oldLen;
17713
- if (options.maxEditLength != null) {
17714
- maxEditLength = Math.min(maxEditLength, options.maxEditLength);
17715
- }
17716
- const maxExecutionTime = (_a3 = options.timeout) !== null && _a3 !== void 0 ? _a3 : Infinity;
17717
- const abortAfterTimestamp = Date.now() + maxExecutionTime;
17718
- const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
17719
- let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
17720
- if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
17721
- return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
17722
- }
17723
- let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
17724
- const execEditLength = () => {
17725
- for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
17726
- let basePath;
17727
- const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
17728
- if (removePath) {
17729
- bestPath[diagonalPath - 1] = void 0;
17730
- }
17731
- let canAdd = false;
17732
- if (addPath) {
17733
- const addPathNewPos = addPath.oldPos - diagonalPath;
17734
- canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
17735
- }
17736
- const canRemove = removePath && removePath.oldPos + 1 < oldLen;
17737
- if (!canAdd && !canRemove) {
17738
- bestPath[diagonalPath] = void 0;
17739
- continue;
17740
- }
17741
- if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
17742
- basePath = this.addToPath(addPath, true, false, 0, options);
17743
- } else {
17744
- basePath = this.addToPath(removePath, false, true, 1, options);
17745
- }
17746
- newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
17747
- if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
17748
- return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
17749
- } else {
17750
- bestPath[diagonalPath] = basePath;
17751
- if (basePath.oldPos + 1 >= oldLen) {
17752
- maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
17753
- }
17754
- if (newPos + 1 >= newLen) {
17755
- minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
17756
- }
17757
- }
17838
+ ];
17839
+ });
17840
+ }
17841
+ function ompLiveCommands(native) {
17842
+ return native.filter(({ source, name }) => source !== "builtin" || name === "context").map((command) => ({
17843
+ name: command.name,
17844
+ description: command.description,
17845
+ kind: command.source === "skill" ? "skill" : "command"
17846
+ }));
17847
+ }
17848
+
17849
+ // dist/omp-session-file.js
17850
+ import { createReadStream as createReadStream3 } from "node:fs";
17851
+ import { open, realpath as realpath2 } from "node:fs/promises";
17852
+ import readline from "node:readline";
17853
+ var MAX_SESSION_HEADER_BYTES = 64 * 1024;
17854
+ var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
17855
+ function isRecord7(value) {
17856
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17857
+ }
17858
+ function historyEntry(value) {
17859
+ if (!isRecord7(value) || value.type === "title" || value.type === "session" || typeof value.id !== "string" || value.id.length === 0 || value.parentId !== null && typeof value.parentId !== "string" || typeof value.type !== "string") {
17860
+ return null;
17861
+ }
17862
+ return value;
17863
+ }
17864
+ async function readOmpSessionHistory(sessionFile, maxBytes) {
17865
+ const entries = [];
17866
+ let leafId = null;
17867
+ let incomplete = false;
17868
+ const lines = readline.createInterface({
17869
+ input: createReadStream3(sessionFile, {
17870
+ encoding: "utf8",
17871
+ ...maxBytes === void 0 ? {} : { end: maxBytes - 1 }
17872
+ }),
17873
+ crlfDelay: Number.POSITIVE_INFINITY
17874
+ });
17875
+ try {
17876
+ for await (const line of lines) {
17877
+ if (line.length === 0)
17878
+ continue;
17879
+ let parsed;
17880
+ try {
17881
+ parsed = JSON.parse(line);
17882
+ } catch {
17883
+ incomplete = true;
17884
+ continue;
17758
17885
  }
17759
- editLength++;
17760
- };
17761
- if (callback) {
17762
- (function exec() {
17763
- setTimeout(function() {
17764
- if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
17765
- return callback(void 0);
17766
- }
17767
- if (!execEditLength()) {
17768
- exec();
17769
- }
17770
- }, 0);
17771
- })();
17772
- } else {
17773
- while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
17774
- const ret = execEditLength();
17775
- if (ret) {
17776
- return ret;
17886
+ const entry = historyEntry(parsed);
17887
+ if (!entry) {
17888
+ if (!isRecord7(parsed) || parsed.type !== "title" && parsed.type !== "session") {
17889
+ incomplete = true;
17777
17890
  }
17891
+ continue;
17778
17892
  }
17893
+ entries.push(entry);
17894
+ leafId = entry.id;
17779
17895
  }
17896
+ } finally {
17897
+ lines.close();
17780
17898
  }
17781
- addToPath(path9, added, removed, oldPosInc, options) {
17782
- const last = path9.lastComponent;
17783
- if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
17784
- return {
17785
- oldPos: path9.oldPos + oldPosInc,
17786
- lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
17787
- };
17788
- } else {
17789
- return {
17790
- oldPos: path9.oldPos + oldPosInc,
17791
- lastComponent: { count: 1, added, removed, previousComponent: last }
17792
- };
17899
+ return { entries, leafId, ...incomplete ? { incomplete: true } : {} };
17900
+ }
17901
+ async function readOmpSessionHeader(sessionFile) {
17902
+ const handle = await open(sessionFile, "r");
17903
+ try {
17904
+ const buffer = Buffer.allocUnsafe(MAX_SESSION_HEADER_BYTES);
17905
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
17906
+ const contents = buffer.subarray(0, bytesRead);
17907
+ const newline = contents.indexOf(10);
17908
+ if (newline < 0 && bytesRead === buffer.length) {
17909
+ throw new Error("Omp Session header exceeds the supported size");
17793
17910
  }
17794
- }
17795
- extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
17796
- const newLen = newTokens.length, oldLen = oldTokens.length;
17797
- let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
17798
- while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
17799
- newPos++;
17800
- oldPos++;
17801
- commonCount++;
17802
- if (options.oneChangePerToken) {
17803
- basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
17911
+ const contentsText = utf8Decoder.decode(contents);
17912
+ for (const line of contentsText.split("\n")) {
17913
+ if (line.length === 0)
17914
+ continue;
17915
+ let parsed;
17916
+ try {
17917
+ parsed = JSON.parse(line);
17918
+ } catch {
17919
+ continue;
17804
17920
  }
17805
- }
17806
- if (commonCount && !options.oneChangePerToken) {
17807
- basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
17808
- }
17809
- basePath.oldPos = oldPos;
17810
- return newPos;
17811
- }
17812
- equals(left, right, options) {
17813
- if (options.comparator) {
17814
- return options.comparator(left, right);
17815
- } else {
17816
- return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
17817
- }
17818
- }
17819
- removeEmpty(array2) {
17820
- const ret = [];
17821
- for (let i = 0; i < array2.length; i++) {
17822
- if (array2[i]) {
17823
- ret.push(array2[i]);
17921
+ if (!isRecord7(parsed) || parsed.type !== "session")
17922
+ continue;
17923
+ if (typeof parsed.id !== "string" || parsed.id.length === 0 || typeof parsed.cwd !== "string" || parsed.cwd.length === 0) {
17924
+ throw new Error("Omp Session header is invalid");
17824
17925
  }
17926
+ return { type: "session", id: parsed.id, cwd: parsed.cwd };
17825
17927
  }
17826
- return ret;
17827
- }
17828
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
17829
- castInput(value, options) {
17830
- return value;
17831
- }
17832
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
17833
- tokenize(value, options) {
17834
- return Array.from(value);
17835
- }
17836
- join(chars) {
17837
- return chars.join("");
17928
+ throw new Error("Omp Session header is invalid");
17929
+ } finally {
17930
+ await handle.close();
17838
17931
  }
17839
- postProcess(changeObjects, options) {
17840
- return changeObjects;
17932
+ }
17933
+ async function verifyOmpSessionCwd(input) {
17934
+ if (!input.sessionFile)
17935
+ throw new Error("Omp Fork Session has no persisted Session file");
17936
+ const header = await readOmpSessionHeader(input.sessionFile);
17937
+ if (header.id !== input.sessionId) {
17938
+ throw new Error("Omp Fork Session header identity does not match RPC state");
17841
17939
  }
17842
- get useLongestToken() {
17843
- return false;
17940
+ const [actualCwd, expectedCwd] = await Promise.all([
17941
+ realpath2(header.cwd),
17942
+ realpath2(input.expectedCwd)
17943
+ ]);
17944
+ if (actualCwd !== expectedCwd) {
17945
+ throw new Error("Omp Fork Session did not bind the requested cwd");
17844
17946
  }
17845
- buildValues(lastComponent, newTokens, oldTokens) {
17846
- const components = [];
17847
- let nextComponent;
17848
- while (lastComponent) {
17849
- components.push(lastComponent);
17850
- nextComponent = lastComponent.previousComponent;
17851
- delete lastComponent.previousComponent;
17852
- lastComponent = nextComponent;
17947
+ }
17948
+
17949
+ // dist/omp-protocol.js
17950
+ var MAX_FRAME_BYTES = 1024 * 1024;
17951
+ var MAX_REASSEMBLED_BYTES = 64 * 1024 * 1024;
17952
+ var MAX_CHUNK_BYTES = 256 * 1024;
17953
+ function isObject2(value) {
17954
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17955
+ }
17956
+ var OmpFrameDecoder = class {
17957
+ #pending = null;
17958
+ push(value) {
17959
+ if (!isObject2(value))
17960
+ throw new Error("OMP RPC frame must be a JSON object");
17961
+ if (value.type !== "rpc_chunk") {
17962
+ if (this.#pending)
17963
+ throw new Error("OMP RPC chunk sequence was interrupted");
17964
+ return value;
17853
17965
  }
17854
- components.reverse();
17855
- const componentLen = components.length;
17856
- let componentPos = 0, newPos = 0, oldPos = 0;
17857
- for (; componentPos < componentLen; componentPos++) {
17858
- const component = components[componentPos];
17859
- if (!component.removed) {
17860
- if (!component.added && this.useLongestToken) {
17861
- let value = newTokens.slice(newPos, newPos + component.count);
17862
- value = value.map(function(value2, i) {
17863
- const oldValue = oldTokens[oldPos + i];
17864
- return oldValue.length > value2.length ? oldValue : value2;
17865
- });
17866
- component.value = this.join(value);
17867
- } else {
17868
- component.value = this.join(newTokens.slice(newPos, newPos + component.count));
17869
- }
17870
- newPos += component.count;
17871
- if (!component.added) {
17872
- oldPos += component.count;
17873
- }
17874
- } else {
17875
- component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
17876
- oldPos += component.count;
17877
- }
17966
+ const chunkId = value.chunkId;
17967
+ const index = value.index;
17968
+ const count2 = value.count;
17969
+ const byteLength = value.byteLength;
17970
+ const data = value.data;
17971
+ if (typeof chunkId !== "string" || chunkId.length === 0 || chunkId.length > 128 || !Number.isInteger(index) || !Number.isInteger(count2) || !Number.isInteger(byteLength) || index < 0 || count2 < 2 || index >= count2 || byteLength < MAX_FRAME_BYTES || byteLength > MAX_REASSEMBLED_BYTES || typeof data !== "string" || data.length === 0)
17972
+ throw new Error("Invalid OMP RPC chunk metadata");
17973
+ let bytes;
17974
+ try {
17975
+ bytes = Buffer.from(data, "base64");
17976
+ } catch {
17977
+ throw new Error("Invalid OMP RPC chunk data");
17878
17978
  }
17879
- return components;
17979
+ if (bytes.length === 0 || bytes.length > MAX_CHUNK_BYTES || bytes.toString("base64") !== data) {
17980
+ throw new Error("Invalid OMP RPC chunk data");
17981
+ }
17982
+ const chunkIndex = index;
17983
+ const chunkCount = count2;
17984
+ const declaredByteLength = byteLength;
17985
+ if (!this.#pending) {
17986
+ if (chunkIndex !== 0)
17987
+ throw new Error("OMP RPC chunk sequence must start at index 0");
17988
+ this.#pending = {
17989
+ chunkId,
17990
+ count: chunkCount,
17991
+ byteLength: declaredByteLength,
17992
+ nextIndex: 0,
17993
+ chunks: [],
17994
+ received: 0
17995
+ };
17996
+ }
17997
+ const pending = this.#pending;
17998
+ if (!pending)
17999
+ throw new Error("OMP RPC chunk state was lost");
18000
+ if (pending.chunkId !== chunkId || pending.count !== chunkCount || pending.byteLength !== declaredByteLength || pending.nextIndex !== chunkIndex) {
18001
+ throw new Error("OMP RPC chunk sequence mismatch");
18002
+ }
18003
+ pending.chunks.push(bytes);
18004
+ pending.received += bytes.length;
18005
+ pending.nextIndex += 1;
18006
+ if (pending.received > pending.byteLength)
18007
+ throw new Error("OMP RPC chunk sequence exceeds its declared length");
18008
+ if (pending.nextIndex < pending.count)
18009
+ return null;
18010
+ if (pending.received !== pending.byteLength)
18011
+ throw new Error("OMP RPC chunk sequence length mismatch");
18012
+ this.#pending = null;
18013
+ let decoded;
18014
+ try {
18015
+ decoded = JSON.parse(Buffer.concat(pending.chunks).toString("utf8"));
18016
+ } catch {
18017
+ throw new Error("Failed to decode reassembled OMP RPC frame");
18018
+ }
18019
+ if (!isObject2(decoded))
18020
+ throw new Error("Reassembled OMP RPC frame must be an object");
18021
+ return decoded;
17880
18022
  }
17881
18023
  };
17882
18024
 
17883
- // ../../../node_modules/diff/libesm/diff/line.js
17884
- var LineDiff = class extends Diff {
17885
- constructor() {
17886
- super(...arguments);
17887
- this.tokenize = tokenize;
18025
+ // dist/omp-rpc-session.js
18026
+ var OmpRpcFaultError = class extends Error {
18027
+ kind;
18028
+ diagnostic;
18029
+ constructor(kind, message3, diagnostic) {
18030
+ super(message3);
18031
+ this.kind = kind;
18032
+ this.diagnostic = diagnostic;
18033
+ this.name = "OmpRpcFaultError";
17888
18034
  }
17889
- equals(left, right, options) {
17890
- if (options.ignoreWhitespace) {
17891
- if (!options.newlineIsToken || !left.includes("\n")) {
17892
- left = left.trim();
17893
- }
17894
- if (!options.newlineIsToken || !right.includes("\n")) {
17895
- right = right.trim();
17896
- }
17897
- } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
17898
- if (left.endsWith("\n")) {
17899
- left = left.slice(0, -1);
17900
- }
17901
- if (right.endsWith("\n")) {
17902
- right = right.slice(0, -1);
17903
- }
17904
- }
17905
- return super.equals(left, right, options);
18035
+ };
18036
+ var OmpRpcUnsupportedCommandError = class extends Error {
18037
+ command;
18038
+ constructor(command) {
18039
+ super(`Omp RPC does not support '${command}'`);
18040
+ this.command = command;
18041
+ this.name = "OmpRpcUnsupportedCommandError";
17906
18042
  }
17907
18043
  };
17908
- var lineDiff = new LineDiff();
17909
- function diffLines(oldStr, newStr, options) {
17910
- return lineDiff.diff(oldStr, newStr, options);
18044
+ var textDecoder = new TextDecoder("utf-8", { fatal: true });
18045
+ function isRecord8(value) {
18046
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17911
18047
  }
17912
- function tokenize(value, options) {
17913
- if (options.stripTrailingCr) {
17914
- value = value.replace(/\r\n/g, "\n");
17915
- }
17916
- const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
17917
- if (!linesAndNewlines[linesAndNewlines.length - 1]) {
17918
- linesAndNewlines.pop();
17919
- }
17920
- for (let i = 0; i < linesAndNewlines.length; i++) {
17921
- const line = linesAndNewlines[i];
17922
- if (i % 2 && !options.newlineIsToken) {
17923
- retLines[retLines.length - 1] += line;
17924
- } else {
17925
- retLines.push(line);
17926
- }
18048
+ function message2(value) {
18049
+ return value instanceof Error ? value.message : String(value);
18050
+ }
18051
+ function nonBlankString(value) {
18052
+ return typeof value === "string" && value.trim().length > 0;
18053
+ }
18054
+ function parseNativeModel(value, context) {
18055
+ if (value === null || value === void 0)
18056
+ return null;
18057
+ if (!isRecord8(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
18058
+ throw new OmpRpcFaultError("protocolError", `Omp RPC returned an invalid ${context} Model`);
17927
18059
  }
17928
- return retLines;
17929
- }
17930
-
17931
- // ../../../node_modules/diff/libesm/patch/parse.js
17932
- function parsePatch(uniDiff) {
17933
- const diffstr = uniDiff.split(/\n/), list = [];
17934
- let i = 0;
17935
- function parseIndex() {
17936
- const index = {};
17937
- list.push(index);
17938
- while (i < diffstr.length) {
17939
- const line = diffstr[i];
17940
- if (/^(---|\+\+\+|@@)\s/.test(line)) {
17941
- break;
17942
- }
17943
- const header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
17944
- if (header) {
17945
- index.index = header[1];
17946
- }
17947
- i++;
17948
- }
17949
- parseFileHeader(index);
17950
- parseFileHeader(index);
17951
- index.hunks = [];
17952
- while (i < diffstr.length) {
17953
- const line = diffstr[i];
17954
- if (/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/.test(line)) {
17955
- break;
17956
- } else if (/^@@/.test(line)) {
17957
- index.hunks.push(parseHunk());
17958
- } else if (line) {
17959
- throw new Error("Unknown line " + (i + 1) + " " + JSON.stringify(line));
17960
- } else {
17961
- i++;
17962
- }
17963
- }
17964
- }
17965
- function parseFileHeader(index) {
17966
- const fileHeader = /^(---|\+\+\+)\s+(.*)\r?$/.exec(diffstr[i]);
17967
- if (fileHeader) {
17968
- const data = fileHeader[2].split(" ", 2), header = (data[1] || "").trim();
17969
- let fileName = data[0].replace(/\\\\/g, "\\");
17970
- if (/^".*"$/.test(fileName)) {
17971
- fileName = fileName.substr(1, fileName.length - 2);
17972
- }
17973
- if (fileHeader[1] === "---") {
17974
- index.oldFileName = fileName;
17975
- index.oldHeader = header;
17976
- } else {
17977
- index.newFileName = fileName;
17978
- index.newHeader = header;
17979
- }
17980
- i++;
17981
- }
17982
- }
17983
- function parseHunk() {
17984
- var _a3;
17985
- const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
17986
- const hunk = {
17987
- oldStart: +chunkHeader[1],
17988
- oldLines: typeof chunkHeader[2] === "undefined" ? 1 : +chunkHeader[2],
17989
- newStart: +chunkHeader[3],
17990
- newLines: typeof chunkHeader[4] === "undefined" ? 1 : +chunkHeader[4],
17991
- lines: []
17992
- };
17993
- if (hunk.oldLines === 0) {
17994
- hunk.oldStart += 1;
17995
- }
17996
- if (hunk.newLines === 0) {
17997
- hunk.newStart += 1;
17998
- }
17999
- let addCount = 0, removeCount = 0;
18000
- for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a3 = diffstr[i]) === null || _a3 === void 0 ? void 0 : _a3.startsWith("\\"))); i++) {
18001
- const operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? " " : diffstr[i][0];
18002
- if (operation === "+" || operation === "-" || operation === " " || operation === "\\") {
18003
- hunk.lines.push(diffstr[i]);
18004
- if (operation === "+") {
18005
- addCount++;
18006
- } else if (operation === "-") {
18007
- removeCount++;
18008
- } else if (operation === " ") {
18009
- addCount++;
18010
- removeCount++;
18011
- }
18012
- } else {
18013
- throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`);
18014
- }
18015
- }
18016
- if (!addCount && hunk.newLines === 1) {
18017
- hunk.newLines = 0;
18018
- }
18019
- if (!removeCount && hunk.oldLines === 1) {
18020
- hunk.oldLines = 0;
18021
- }
18022
- if (addCount !== hunk.newLines) {
18023
- throw new Error("Added line count did not match for hunk at line " + (chunkHeaderIndex + 1));
18024
- }
18025
- if (removeCount !== hunk.oldLines) {
18026
- throw new Error("Removed line count did not match for hunk at line " + (chunkHeaderIndex + 1));
18027
- }
18028
- return hunk;
18029
- }
18030
- while (i < diffstr.length) {
18031
- parseIndex();
18032
- }
18033
- return list;
18034
- }
18035
-
18036
- // ../../../node_modules/diff/libesm/patch/create.js
18037
- function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
18038
- let optionsObj;
18039
- if (!options) {
18040
- optionsObj = {};
18041
- } else if (typeof options === "function") {
18042
- optionsObj = { callback: options };
18043
- } else {
18044
- optionsObj = options;
18045
- }
18046
- if (typeof optionsObj.context === "undefined") {
18047
- optionsObj.context = 4;
18048
- }
18049
- const context = optionsObj.context;
18050
- if (optionsObj.newlineIsToken) {
18051
- throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");
18052
- }
18053
- if (!optionsObj.callback) {
18054
- return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj));
18055
- } else {
18056
- const { callback } = optionsObj;
18057
- diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => {
18058
- const patch = diffLinesResultToPatch(diff);
18059
- callback(patch);
18060
- } }));
18061
- }
18062
- function diffLinesResultToPatch(diff) {
18063
- if (!diff) {
18064
- return;
18065
- }
18066
- diff.push({ value: "", lines: [] });
18067
- function contextLines(lines) {
18068
- return lines.map(function(entry) {
18069
- return " " + entry;
18070
- });
18071
- }
18072
- const hunks = [];
18073
- let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
18074
- for (let i = 0; i < diff.length; i++) {
18075
- const current = diff[i], lines = current.lines || splitLines(current.value);
18076
- current.lines = lines;
18077
- if (current.added || current.removed) {
18078
- if (!oldRangeStart) {
18079
- const prev = diff[i - 1];
18080
- oldRangeStart = oldLine;
18081
- newRangeStart = newLine;
18082
- if (prev) {
18083
- curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : [];
18084
- oldRangeStart -= curRange.length;
18085
- newRangeStart -= curRange.length;
18086
- }
18087
- }
18088
- for (const line of lines) {
18089
- curRange.push((current.added ? "+" : "-") + line);
18090
- }
18091
- if (current.added) {
18092
- newLine += lines.length;
18093
- } else {
18094
- oldLine += lines.length;
18095
- }
18096
- } else {
18097
- if (oldRangeStart) {
18098
- if (lines.length <= context * 2 && i < diff.length - 2) {
18099
- for (const line of contextLines(lines)) {
18100
- curRange.push(line);
18101
- }
18102
- } else {
18103
- const contextSize = Math.min(lines.length, context);
18104
- for (const line of contextLines(lines.slice(0, contextSize))) {
18105
- curRange.push(line);
18106
- }
18107
- const hunk = {
18108
- oldStart: oldRangeStart,
18109
- oldLines: oldLine - oldRangeStart + contextSize,
18110
- newStart: newRangeStart,
18111
- newLines: newLine - newRangeStart + contextSize,
18112
- lines: curRange
18113
- };
18114
- hunks.push(hunk);
18115
- oldRangeStart = 0;
18116
- newRangeStart = 0;
18117
- curRange = [];
18118
- }
18119
- }
18120
- oldLine += lines.length;
18121
- newLine += lines.length;
18122
- }
18123
- }
18124
- for (const hunk of hunks) {
18125
- for (let i = 0; i < hunk.lines.length; i++) {
18126
- if (hunk.lines[i].endsWith("\n")) {
18127
- hunk.lines[i] = hunk.lines[i].slice(0, -1);
18128
- } else {
18129
- hunk.lines.splice(i + 1, 0, "\");
18130
- i++;
18131
- }
18132
- }
18133
- }
18134
- return {
18135
- oldFileName,
18136
- newFileName,
18137
- oldHeader,
18138
- newHeader,
18139
- hunks
18140
- };
18141
- }
18142
- }
18143
- function formatPatch(patch) {
18144
- if (Array.isArray(patch)) {
18145
- return patch.map(formatPatch).join("\n");
18146
- }
18147
- const ret = [];
18148
- if (patch.oldFileName == patch.newFileName) {
18149
- ret.push("Index: " + patch.oldFileName);
18150
- }
18151
- ret.push("===================================================================");
18152
- ret.push("--- " + patch.oldFileName + (typeof patch.oldHeader === "undefined" ? "" : " " + patch.oldHeader));
18153
- ret.push("+++ " + patch.newFileName + (typeof patch.newHeader === "undefined" ? "" : " " + patch.newHeader));
18154
- for (let i = 0; i < patch.hunks.length; i++) {
18155
- const hunk = patch.hunks[i];
18156
- if (hunk.oldLines === 0) {
18157
- hunk.oldStart -= 1;
18158
- }
18159
- if (hunk.newLines === 0) {
18160
- hunk.newStart -= 1;
18161
- }
18162
- ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@");
18163
- for (const line of hunk.lines) {
18164
- ret.push(line);
18165
- }
18166
- }
18167
- return ret.join("\n") + "\n";
18168
- }
18169
- function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
18170
- if (typeof options === "function") {
18171
- options = { callback: options };
18172
- }
18173
- if (!(options === null || options === void 0 ? void 0 : options.callback)) {
18174
- const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
18175
- if (!patchObj) {
18176
- return;
18177
- }
18178
- return formatPatch(patchObj);
18179
- } else {
18180
- const { callback } = options;
18181
- structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: (patchObj) => {
18182
- if (!patchObj) {
18183
- callback(void 0);
18184
- } else {
18185
- callback(formatPatch(patchObj));
18186
- }
18187
- } }));
18188
- }
18189
- }
18190
- function splitLines(text) {
18191
- const hasTrailingNl = text.endsWith("\n");
18192
- const result = text.split("\n").map((line) => line + "\n");
18193
- if (hasTrailingNl) {
18194
- result.pop();
18195
- } else {
18196
- result.push(result.pop().slice(0, -1));
18197
- }
18198
- return result;
18199
- }
18200
-
18201
- // dist/omp-adapter.js
18202
- import { randomUUID as randomUUID2 } from "node:crypto";
18203
- import { realpath as realpath3, stat as stat2 } from "node:fs/promises";
18204
- import path7 from "node:path";
18205
-
18206
- // dist/omp-slash-commands.js
18207
- var OMP_LIVE_COMMAND_ID_PREFIX = "omp.slash.";
18208
- function isRecord6(value) {
18209
- return typeof value === "object" && value !== null && !Array.isArray(value);
18210
- }
18211
- function parseOmpAvailableCommands(value) {
18212
- if (!Array.isArray(value))
18213
- return [];
18214
- return value.flatMap((entry) => {
18215
- if (!isRecord6(entry))
18216
- return [];
18217
- const name = typeof entry.name === "string" ? entry.name.trim().replace(/^\//u, "") : "";
18218
- if (!name)
18219
- return [];
18220
- return [
18221
- {
18222
- name,
18223
- description: typeof entry.description === "string" ? entry.description : "",
18224
- source: typeof entry.source === "string" ? entry.source : null
18225
- }
18226
- ];
18227
- });
18228
- }
18229
- function ompLiveCommands(native) {
18230
- return native.filter(({ source, name }) => source !== "builtin" || name === "context").map((command) => ({
18231
- name: command.name,
18232
- description: command.description,
18233
- kind: command.source === "skill" ? "skill" : "command"
18234
- }));
18235
- }
18236
-
18237
- // dist/omp-session-file.js
18238
- import { createReadStream as createReadStream3 } from "node:fs";
18239
- import { open, realpath as realpath2 } from "node:fs/promises";
18240
- import readline from "node:readline";
18241
- var MAX_SESSION_HEADER_BYTES = 64 * 1024;
18242
- var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
18243
- function isRecord7(value) {
18244
- return typeof value === "object" && value !== null && !Array.isArray(value);
18245
- }
18246
- function historyEntry(value) {
18247
- if (!isRecord7(value) || value.type === "title" || value.type === "session" || typeof value.id !== "string" || value.id.length === 0 || value.parentId !== null && typeof value.parentId !== "string" || typeof value.type !== "string") {
18248
- return null;
18249
- }
18250
- return value;
18251
- }
18252
- async function readOmpSessionHistory(sessionFile, maxBytes) {
18253
- const entries = [];
18254
- let leafId = null;
18255
- let incomplete = false;
18256
- const lines = readline.createInterface({
18257
- input: createReadStream3(sessionFile, {
18258
- encoding: "utf8",
18259
- ...maxBytes === void 0 ? {} : { end: maxBytes - 1 }
18260
- }),
18261
- crlfDelay: Number.POSITIVE_INFINITY
18262
- });
18263
- try {
18264
- for await (const line of lines) {
18265
- if (line.length === 0)
18266
- continue;
18267
- let parsed;
18268
- try {
18269
- parsed = JSON.parse(line);
18270
- } catch {
18271
- incomplete = true;
18272
- continue;
18273
- }
18274
- const entry = historyEntry(parsed);
18275
- if (!entry) {
18276
- if (!isRecord7(parsed) || parsed.type !== "title" && parsed.type !== "session") {
18277
- incomplete = true;
18278
- }
18279
- continue;
18280
- }
18281
- entries.push(entry);
18282
- leafId = entry.id;
18283
- }
18284
- } finally {
18285
- lines.close();
18286
- }
18287
- return { entries, leafId, ...incomplete ? { incomplete: true } : {} };
18288
- }
18289
- async function readOmpSessionHeader(sessionFile) {
18290
- const handle = await open(sessionFile, "r");
18291
- try {
18292
- const buffer = Buffer.allocUnsafe(MAX_SESSION_HEADER_BYTES);
18293
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
18294
- const contents = buffer.subarray(0, bytesRead);
18295
- const newline = contents.indexOf(10);
18296
- if (newline < 0 && bytesRead === buffer.length) {
18297
- throw new Error("Omp Session header exceeds the supported size");
18298
- }
18299
- const contentsText = utf8Decoder.decode(contents);
18300
- for (const line of contentsText.split("\n")) {
18301
- if (line.length === 0)
18302
- continue;
18303
- let parsed;
18304
- try {
18305
- parsed = JSON.parse(line);
18306
- } catch {
18307
- continue;
18308
- }
18309
- if (!isRecord7(parsed) || parsed.type !== "session")
18310
- continue;
18311
- if (typeof parsed.id !== "string" || parsed.id.length === 0 || typeof parsed.cwd !== "string" || parsed.cwd.length === 0) {
18312
- throw new Error("Omp Session header is invalid");
18313
- }
18314
- return { type: "session", id: parsed.id, cwd: parsed.cwd };
18315
- }
18316
- throw new Error("Omp Session header is invalid");
18317
- } finally {
18318
- await handle.close();
18319
- }
18320
- }
18321
- async function verifyOmpSessionCwd(input) {
18322
- if (!input.sessionFile)
18323
- throw new Error("Omp Fork Session has no persisted Session file");
18324
- const header = await readOmpSessionHeader(input.sessionFile);
18325
- if (header.id !== input.sessionId) {
18326
- throw new Error("Omp Fork Session header identity does not match RPC state");
18327
- }
18328
- const [actualCwd, expectedCwd] = await Promise.all([
18329
- realpath2(header.cwd),
18330
- realpath2(input.expectedCwd)
18331
- ]);
18332
- if (actualCwd !== expectedCwd) {
18333
- throw new Error("Omp Fork Session did not bind the requested cwd");
18334
- }
18335
- }
18336
-
18337
- // dist/omp-last-turn-rollback.js
18338
- function modelFromState(state) {
18339
- if (state.provider === null && state.modelId === null)
18340
- return null;
18341
- if (state.provider === null || state.modelId === null) {
18342
- throw new Error("Omp state contains a partial Model identity");
18343
- }
18344
- return { provider: state.provider, id: state.modelId };
18345
- }
18346
- async function rollbackOmpLastTurn(transport, sourceSessionId, cwd) {
18347
- const startupState = transport.state;
18348
- const startupSessionId = startupState.sessionId;
18349
- const currentModel = modelFromState(startupState);
18350
- const currentThinking = startupState.thinkingLevel;
18351
- const copiedHistory = await transport.getEntries();
18352
- const boundary = resolveOmpLastTurnBoundary(copiedHistory);
18353
- if (!boundary)
18354
- return { ok: false, reason: "empty" };
18355
- const sourceSnapshot = mapOmpSnapshot(copiedHistory, {
18356
- sessionId: startupSessionId,
18357
- model: currentModel
18358
- });
18359
- let state = await transport.fork(boundary.lastUserEntryId);
18360
- if (state.sessionId === sourceSessionId || state.sessionId === startupSessionId) {
18361
- throw new Error("Omp last-Turn rollback did not create a distinct Native Session");
18362
- }
18363
- if (!sameOmpModel(modelFromState(state), currentModel)) {
18364
- if (!currentModel)
18365
- throw new Error("Omp last-Turn rollback changed the current Model");
18366
- state = await transport.selectModel(currentModel);
18367
- }
18368
- if (state.thinkingLevel !== currentThinking) {
18369
- if (!currentThinking)
18370
- throw new Error("Omp last-Turn rollback changed current Thinking");
18371
- state = await transport.selectThinkingOption(currentThinking);
18372
- }
18373
- if (!sameOmpModel(modelFromState(state), currentModel) || state.thinkingLevel !== currentThinking) {
18374
- throw new Error("Omp last-Turn rollback could not restore current Model and Thinking");
18375
- }
18376
- const snapshot = mapOmpSnapshot(await transport.getEntries(), {
18377
- sessionId: state.sessionId,
18378
- model: modelFromState(state)
18379
- });
18380
- const expectedTurnKeys = sourceSnapshot.turns.slice(0, -1).map((turn) => turn.nativeTurnRef.nativeTurnKey);
18381
- const actualTurnKeys = snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey);
18382
- if (snapshot.turns.length !== boundary.sourceTurnCount - 1 || actualTurnKeys.some((key, index) => key !== expectedTurnKeys[index])) {
18383
- throw new Error("Omp last-Turn rollback did not produce the exact retained history prefix");
18384
- }
18385
- await transport.verifySessionCwd(cwd);
18386
- return { ok: true };
18387
- }
18388
-
18389
- // dist/omp-rpc-session.js
18390
- import { spawn, spawnSync } from "node:child_process";
18391
- import { randomUUID } from "node:crypto";
18392
- import path6 from "node:path";
18393
-
18394
- // dist/command.js
18395
- var ompDiscoverySpec = {
18396
- id: "omp",
18397
- command: "omp",
18398
- commandEnvironmentVariable: "OMP_COMMAND",
18399
- installRoots: {
18400
- posix: [
18401
- "~/.npm-global/bin",
18402
- "~/.local/bin",
18403
- VERSION_MANAGER_ROOTS,
18404
- "/opt/homebrew/bin",
18405
- "/usr/local/bin"
18406
- ],
18407
- windows: ["${APPDATA}/npm", "~/.local/bin", VERSION_MANAGER_ROOTS]
18408
- }
18409
- };
18410
- function resolveOmpExecutable(input, dependencies = {}) {
18411
- const resolution = resolveHarnessExecutable(ompDiscoverySpec, {
18412
- ...input.command ? { command: input.command } : {},
18413
- environment: input.environment,
18414
- ...dependencies.platform ? { platform: dependencies.platform } : {},
18415
- ...dependencies.homeDirectory ? { homeDirectory: dependencies.homeDirectory } : {}
18416
- }, { ...dependencies.isExecutable ? { isExecutable: dependencies.isExecutable } : {} });
18417
- return resolution?.executable ?? input.command ?? input.environment.OMP_COMMAND ?? "omp";
18418
- }
18419
-
18420
- // dist/omp-protocol.js
18421
- var MAX_FRAME_BYTES = 1024 * 1024;
18422
- var MAX_REASSEMBLED_BYTES = 64 * 1024 * 1024;
18423
- var MAX_CHUNK_BYTES = 256 * 1024;
18424
- function isObject2(value) {
18425
- return typeof value === "object" && value !== null && !Array.isArray(value);
18426
- }
18427
- var OmpFrameDecoder = class {
18428
- #pending = null;
18429
- push(value) {
18430
- if (!isObject2(value))
18431
- throw new Error("OMP RPC frame must be a JSON object");
18432
- if (value.type !== "rpc_chunk") {
18433
- if (this.#pending)
18434
- throw new Error("OMP RPC chunk sequence was interrupted");
18435
- return value;
18436
- }
18437
- const chunkId = value.chunkId;
18438
- const index = value.index;
18439
- const count2 = value.count;
18440
- const byteLength = value.byteLength;
18441
- const data = value.data;
18442
- if (typeof chunkId !== "string" || chunkId.length === 0 || chunkId.length > 128 || !Number.isInteger(index) || !Number.isInteger(count2) || !Number.isInteger(byteLength) || index < 0 || count2 < 2 || index >= count2 || byteLength < MAX_FRAME_BYTES || byteLength > MAX_REASSEMBLED_BYTES || typeof data !== "string" || data.length === 0)
18443
- throw new Error("Invalid OMP RPC chunk metadata");
18444
- let bytes;
18445
- try {
18446
- bytes = Buffer.from(data, "base64");
18447
- } catch {
18448
- throw new Error("Invalid OMP RPC chunk data");
18449
- }
18450
- if (bytes.length === 0 || bytes.length > MAX_CHUNK_BYTES || bytes.toString("base64") !== data) {
18451
- throw new Error("Invalid OMP RPC chunk data");
18452
- }
18453
- const chunkIndex = index;
18454
- const chunkCount = count2;
18455
- const declaredByteLength = byteLength;
18456
- if (!this.#pending) {
18457
- if (chunkIndex !== 0)
18458
- throw new Error("OMP RPC chunk sequence must start at index 0");
18459
- this.#pending = {
18460
- chunkId,
18461
- count: chunkCount,
18462
- byteLength: declaredByteLength,
18463
- nextIndex: 0,
18464
- chunks: [],
18465
- received: 0
18466
- };
18467
- }
18468
- const pending = this.#pending;
18469
- if (!pending)
18470
- throw new Error("OMP RPC chunk state was lost");
18471
- if (pending.chunkId !== chunkId || pending.count !== chunkCount || pending.byteLength !== declaredByteLength || pending.nextIndex !== chunkIndex) {
18472
- throw new Error("OMP RPC chunk sequence mismatch");
18473
- }
18474
- pending.chunks.push(bytes);
18475
- pending.received += bytes.length;
18476
- pending.nextIndex += 1;
18477
- if (pending.received > pending.byteLength)
18478
- throw new Error("OMP RPC chunk sequence exceeds its declared length");
18479
- if (pending.nextIndex < pending.count)
18480
- return null;
18481
- if (pending.received !== pending.byteLength)
18482
- throw new Error("OMP RPC chunk sequence length mismatch");
18483
- this.#pending = null;
18484
- let decoded;
18485
- try {
18486
- decoded = JSON.parse(Buffer.concat(pending.chunks).toString("utf8"));
18487
- } catch {
18488
- throw new Error("Failed to decode reassembled OMP RPC frame");
18489
- }
18490
- if (!isObject2(decoded))
18491
- throw new Error("Reassembled OMP RPC frame must be an object");
18492
- return decoded;
18493
- }
18494
- };
18495
-
18496
- // dist/omp-rpc-session.js
18497
- var OmpRpcFaultError = class extends Error {
18498
- kind;
18499
- diagnostic;
18500
- constructor(kind, message3, diagnostic) {
18501
- super(message3);
18502
- this.kind = kind;
18503
- this.diagnostic = diagnostic;
18504
- this.name = "OmpRpcFaultError";
18505
- }
18506
- };
18507
- var OmpRpcUnsupportedCommandError = class extends Error {
18508
- command;
18509
- constructor(command) {
18510
- super(`Omp RPC does not support '${command}'`);
18511
- this.command = command;
18512
- this.name = "OmpRpcUnsupportedCommandError";
18513
- }
18514
- };
18515
- var textDecoder = new TextDecoder("utf-8", { fatal: true });
18516
- function isRecord8(value) {
18517
- return typeof value === "object" && value !== null && !Array.isArray(value);
18518
- }
18519
- function message2(value) {
18520
- return value instanceof Error ? value.message : String(value);
18521
- }
18522
- function nonBlankString(value) {
18523
- return typeof value === "string" && value.trim().length > 0;
18524
- }
18525
- function parseNativeModel(value, context) {
18526
- if (value === null || value === void 0)
18527
- return null;
18528
- if (!isRecord8(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
18529
- throw new OmpRpcFaultError("protocolError", `Omp RPC returned an invalid ${context} Model`);
18530
- }
18531
- return { provider: value.provider, id: value.id };
18060
+ return { provider: value.provider, id: value.id };
18532
18061
  }
18533
18062
  function sessionStateData(response) {
18534
18063
  const data = isRecord8(response.data) ? response.data : null;
@@ -18756,1178 +18285,1844 @@ var OmpRpcSession = class {
18756
18285
  if (options.model && (options.sessionFile || options.forkSessionFile)) {
18757
18286
  throw new Error("Omp RPC cannot combine a startup Model with Session restore or Fork");
18758
18287
  }
18759
- this.#options = {
18760
- commandTimeoutMs: 3e4,
18761
- compactionTimeoutMs: 3e5,
18762
- // Native Abort waits for tools, persistence and deferred work to unwind.
18763
- // Stable cancellation must outlast the Host's 20s steering wait.
18764
- cancelTimeoutMs: 3e4,
18765
- closeTimeoutMs: 2e3,
18766
- ...options
18767
- };
18768
- this.#processAdapter = processAdapter;
18288
+ this.#options = {
18289
+ commandTimeoutMs: 3e4,
18290
+ compactionTimeoutMs: 3e5,
18291
+ // Native Abort waits for tools, persistence and deferred work to unwind.
18292
+ // Stable cancellation must outlast the Host's 20s steering wait.
18293
+ cancelTimeoutMs: 3e4,
18294
+ closeTimeoutMs: 2e3,
18295
+ ...options
18296
+ };
18297
+ this.#processAdapter = processAdapter;
18298
+ }
18299
+ get state() {
18300
+ if (!this.#state)
18301
+ throw new Error("Omp RPC Session has not started");
18302
+ return this.#state;
18303
+ }
18304
+ get stderrTail() {
18305
+ return this.#stderrTail;
18306
+ }
18307
+ async start() {
18308
+ if (this.#child || this.#closed)
18309
+ throw new Error("Omp RPC Session cannot be started twice");
18310
+ const child = this.#processAdapter.spawn({
18311
+ cwd: this.#options.cwd,
18312
+ ...this.#options.command ? { command: this.#options.command } : {},
18313
+ environment: withNodeRuntimeOnPath({
18314
+ ...process.env,
18315
+ ...this.#options.environment,
18316
+ OMP_SKIP_VERSION_CHECK: "1",
18317
+ OMP_TELEMETRY: "0"
18318
+ }),
18319
+ ...this.#options.sessionFile ? { sessionFile: this.#options.sessionFile } : {},
18320
+ ...this.#options.forkSessionFile ? { forkSessionFile: this.#options.forkSessionFile } : {},
18321
+ ...this.#options.model ? { model: this.#options.model } : {},
18322
+ ...this.#options.permissionMode ? { permissionMode: this.#options.permissionMode } : {}
18323
+ });
18324
+ this.#child = child;
18325
+ child.stdout.on("data", (chunk) => this.#push(chunk));
18326
+ child.stdout.on("end", () => {
18327
+ if (this.#buffer.length !== 0) {
18328
+ this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC stdout ended mid-frame"));
18329
+ }
18330
+ });
18331
+ child.stderr.on("data", (chunk) => {
18332
+ this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
18333
+ });
18334
+ child.once("error", (error51) => {
18335
+ const kind = isRecord8(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
18336
+ this.#fail(new OmpRpcFaultError(kind, `Omp RPC failed to start: ${error51.message}`, this.stderrTail));
18337
+ });
18338
+ child.once("exit", (code, signal) => {
18339
+ if (!this.#closed) {
18340
+ this.#fail(new OmpRpcFaultError("processExited", `Omp RPC exited (code=${code}, signal=${signal})`, this.stderrTail));
18341
+ }
18342
+ });
18343
+ await Promise.race([
18344
+ new Promise((resolve, reject) => {
18345
+ child.once("spawn", resolve);
18346
+ child.once("error", reject);
18347
+ }),
18348
+ new Promise((_resolve, reject) => setTimeout(() => reject(new Error("Omp RPC start timed out")), this.#options.commandTimeoutMs))
18349
+ ]);
18350
+ let readyTimeout;
18351
+ try {
18352
+ await Promise.race([
18353
+ this.#ready,
18354
+ this.#startupFault.then((error51) => {
18355
+ throw error51;
18356
+ }),
18357
+ new Promise((_resolve, reject) => {
18358
+ readyTimeout = setTimeout(() => reject(new Error("Omp RPC ready signal timed out")), this.#options.commandTimeoutMs);
18359
+ })
18360
+ ]);
18361
+ } finally {
18362
+ clearTimeout(readyTimeout);
18363
+ }
18364
+ await this.#send("negotiate_protocol", { protocolVersion: 2 }).catch(() => void 0);
18365
+ if (this.#options.subscribeSubagentEvents !== false) {
18366
+ await this.#send("set_subagent_subscription", { level: "events" }).catch(() => void 0);
18367
+ }
18368
+ try {
18369
+ this.#state = parseSessionState(await this.#send("get_state", {}));
18370
+ } catch (error51) {
18371
+ const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("unavailable", `Omp RPC state unavailable: ${message2(error51)}`);
18372
+ this.#fail(fault);
18373
+ throw fault;
18374
+ }
18375
+ return this;
18376
+ }
18377
+ async getEntries() {
18378
+ try {
18379
+ if (this.state.sessionFile) {
18380
+ try {
18381
+ return await readOmpSessionHistory(this.state.sessionFile);
18382
+ } catch (error51) {
18383
+ if (!isRecord8(error51) || error51.code !== "ENOENT" || this.#options.sessionFile || this.#options.forkSessionFile)
18384
+ throw error51;
18385
+ const response2 = await this.#send("get_messages", {});
18386
+ const data2 = isRecord8(response2.data) ? response2.data : null;
18387
+ if (data2 && Array.isArray(data2.messages) && data2.messages.length === 0) {
18388
+ return { entries: [], leafId: null };
18389
+ }
18390
+ throw error51;
18391
+ }
18392
+ }
18393
+ const response = await this.#send("get_messages", {});
18394
+ const data = isRecord8(response.data) ? response.data : null;
18395
+ if (!data || !Array.isArray(data.messages)) {
18396
+ throw new OmpRpcFaultError("protocolError", "Omp RPC messages response has no messages");
18397
+ }
18398
+ let branchEntryIds = null;
18399
+ try {
18400
+ const branchResponse = await this.#send("get_branch_messages", {});
18401
+ const branchData = isRecord8(branchResponse.data) ? branchResponse.data : null;
18402
+ if (branchData && Array.isArray(branchData.messages)) {
18403
+ const parsed = branchData.messages.flatMap((entry) => {
18404
+ if (!isRecord8(entry) || !nonBlankString(entry.entryId))
18405
+ return [];
18406
+ return [entry.entryId];
18407
+ });
18408
+ if (parsed.length === branchData.messages.length)
18409
+ branchEntryIds = parsed;
18410
+ }
18411
+ } catch (error51) {
18412
+ if (!(error51 instanceof OmpRpcUnsupportedCommandError))
18413
+ throw error51;
18414
+ }
18415
+ let userIndex = 0;
18416
+ let parentId = null;
18417
+ const entries = data.messages.map((nativeMessage, index) => {
18418
+ const role = isRecord8(nativeMessage) ? nativeMessage.role : void 0;
18419
+ const branchId = role === "user" ? branchEntryIds?.[userIndex] : void 0;
18420
+ if (branchId)
18421
+ userIndex += 1;
18422
+ const id = branchId ?? (isRecord8(nativeMessage) && nonBlankString(nativeMessage.id) ? nativeMessage.id : `omp-message-${index}`);
18423
+ const entry = { id, parentId, type: "message", message: nativeMessage };
18424
+ parentId = id;
18425
+ return entry;
18426
+ });
18427
+ return { entries, leafId: parentId };
18428
+ } catch (error51) {
18429
+ if (error51 instanceof OmpRpcFaultError)
18430
+ this.#fail(error51);
18431
+ throw error51;
18432
+ }
18433
+ }
18434
+ async getSubagentMessages(input) {
18435
+ if ((input.subagentId === void 0 || !nonBlankString(input.subagentId)) && (input.sessionFile === void 0 || !nonBlankString(input.sessionFile))) {
18436
+ throw new Error("Omp Subagent transcript requires a Subagent ID or Session file");
18437
+ }
18438
+ if (input.fromByte !== void 0 && (!Number.isSafeInteger(input.fromByte) || input.fromByte < 0)) {
18439
+ throw new Error("Omp Subagent transcript offset is invalid");
18440
+ }
18441
+ const response = await this.#send("get_subagent_messages", {
18442
+ ...input.subagentId ? { subagentId: input.subagentId } : {},
18443
+ ...input.sessionFile ? { sessionFile: input.sessionFile } : {},
18444
+ ...input.fromByte !== void 0 ? { fromByte: input.fromByte } : {}
18445
+ });
18446
+ return parseSubagentMessages(response);
18447
+ }
18448
+ async compact(customInstructions, onEvent) {
18449
+ if (!this.#child || !this.#state || this.#closed || this.#failed) {
18450
+ throw new Error("Omp RPC Session is unavailable");
18451
+ }
18452
+ if (this.#activeTurn || this.#manualCompaction || this.#compactionActive) {
18453
+ throw new Error("Omp RPC Session already has an active operation");
18454
+ }
18455
+ const result = new Promise((resolve, reject) => {
18456
+ this.#manualCompaction = { onEvent, resolve, reject };
18457
+ });
18458
+ try {
18459
+ await this.#send("compact", customInstructions ? { customInstructions } : {});
18460
+ } catch (error51) {
18461
+ const pending = this.#manualCompaction;
18462
+ this.#manualCompaction = null;
18463
+ pending?.reject(error51 instanceof Error ? error51 : new Error(message2(error51)));
18464
+ }
18465
+ return result;
18466
+ }
18467
+ async getSessionUsage() {
18468
+ try {
18469
+ const usage = parseOmpSessionUsage(await this.#send("get_session_stats", {}));
18470
+ await this.#ensureLatestCacheHitRate();
18471
+ return this.#withLatestCacheHitRate(usage);
18472
+ } catch (error51) {
18473
+ if (!(error51 instanceof OmpRpcUnsupportedCommandError))
18474
+ throw error51;
18475
+ const response = await this.#send("get_state", {});
18476
+ const observedState = parseSessionState(response);
18477
+ if (!this.#state || observedState.sessionId !== this.#state.sessionId || observedState.provider !== this.#state.provider || observedState.modelId !== this.#state.modelId) {
18478
+ throw new Error("Omp RPC Usage fallback does not match the confirmed Session state");
18479
+ }
18480
+ await this.#ensureLatestCacheHitRate();
18481
+ const usage = parseOmpStateContextUsage(response);
18482
+ return usage ? this.#withLatestCacheHitRate(usage) : null;
18483
+ }
18769
18484
  }
18770
- get state() {
18771
- if (!this.#state)
18772
- throw new Error("Omp RPC Session has not started");
18773
- return this.#state;
18485
+ async #ensureLatestCacheHitRate() {
18486
+ if (this.#latestCacheHitRatePercent !== void 0)
18487
+ return;
18488
+ try {
18489
+ this.#latestCacheHitRatePercent = latestOmpCacheHitRatePercent(await this.getEntries());
18490
+ } catch {
18491
+ this.#latestCacheHitRatePercent = null;
18492
+ }
18774
18493
  }
18775
- get stderrTail() {
18776
- return this.#stderrTail;
18494
+ #withLatestCacheHitRate(usage) {
18495
+ return this.#latestCacheHitRatePercent === null || this.#latestCacheHitRatePercent === void 0 ? usage : parseHostUsage({ ...usage, cacheHitRatePercent: this.#latestCacheHitRatePercent });
18777
18496
  }
18778
- async start() {
18779
- if (this.#child || this.#closed)
18780
- throw new Error("Omp RPC Session cannot be started twice");
18781
- const child = this.#processAdapter.spawn({
18782
- cwd: this.#options.cwd,
18783
- ...this.#options.command ? { command: this.#options.command } : {},
18784
- environment: withNodeRuntimeOnPath({
18785
- ...process.env,
18786
- ...this.#options.environment,
18787
- OMP_SKIP_VERSION_CHECK: "1",
18788
- OMP_TELEMETRY: "0"
18789
- }),
18790
- ...this.#options.sessionFile ? { sessionFile: this.#options.sessionFile } : {},
18791
- ...this.#options.forkSessionFile ? { forkSessionFile: this.#options.forkSessionFile } : {},
18792
- ...this.#options.model ? { model: this.#options.model } : {},
18793
- ...this.#options.permissionMode ? { permissionMode: this.#options.permissionMode } : {}
18794
- });
18795
- this.#child = child;
18796
- child.stdout.on("data", (chunk) => this.#push(chunk));
18797
- child.stdout.on("end", () => {
18798
- if (this.#buffer.length !== 0) {
18799
- this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC stdout ended mid-frame"));
18497
+ async fork(entryId) {
18498
+ if (!nonBlankString(entryId))
18499
+ throw new Error("Omp RPC Fork requires an Entry identity");
18500
+ try {
18501
+ const response = await this.#send("branch", { entryId });
18502
+ const data = isRecord8(response.data) ? response.data : null;
18503
+ if (!data || data.cancelled === true) {
18504
+ throw new OmpRpcFaultError("unavailable", "Omp RPC Fork was cancelled");
18800
18505
  }
18506
+ this.#state = parseSessionState(await this.#send("get_state", {}));
18507
+ return this.#state;
18508
+ } catch (error51) {
18509
+ if (error51 instanceof OmpRpcFaultError)
18510
+ this.#fail(error51);
18511
+ throw error51;
18512
+ }
18513
+ }
18514
+ verifySessionCwd(expectedCwd) {
18515
+ return verifyOmpSessionCwd({
18516
+ sessionFile: this.state.sessionFile,
18517
+ sessionId: this.state.sessionId,
18518
+ expectedCwd
18801
18519
  });
18802
- child.stderr.on("data", (chunk) => {
18803
- this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
18804
- });
18805
- child.once("error", (error51) => {
18806
- const kind = isRecord8(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
18807
- this.#fail(new OmpRpcFaultError(kind, `Omp RPC failed to start: ${error51.message}`, this.stderrTail));
18808
- });
18809
- child.once("exit", (code, signal) => {
18810
- if (!this.#closed) {
18811
- this.#fail(new OmpRpcFaultError("processExited", `Omp RPC exited (code=${code}, signal=${signal})`, this.stderrTail));
18812
- }
18520
+ }
18521
+ async getAvailableModels() {
18522
+ try {
18523
+ return parseAvailableModels(await this.#send("get_available_models", {}));
18524
+ } catch (error51) {
18525
+ if (error51 instanceof OmpRpcFaultError)
18526
+ this.#fail(error51);
18527
+ throw error51;
18528
+ }
18529
+ }
18530
+ async getAvailableThinkingLevels() {
18531
+ return this.state.availableThinkingLevels;
18532
+ }
18533
+ async selectModel(model2) {
18534
+ await this.#send("set_model", { provider: model2.provider, modelId: model2.id });
18535
+ return this.#refreshState("Model");
18536
+ }
18537
+ async selectThinkingOption(thinkingOptionId) {
18538
+ const level = harnessThinkingOptionIdSchema.parse(thinkingOptionId);
18539
+ await this.#send("set_thinking_level", { level });
18540
+ return this.#refreshState("Thinking");
18541
+ }
18542
+ async #refreshState(operation) {
18543
+ try {
18544
+ this.#state = parseSessionState(await this.#send("get_state", {}));
18545
+ return this.#state;
18546
+ } catch (error51) {
18547
+ const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC ${operation} state could not be confirmed: ${message2(error51)}`);
18548
+ this.#fail(fault);
18549
+ throw fault;
18550
+ }
18551
+ }
18552
+ async runTurn(text, onEvent) {
18553
+ if (!this.#child || !this.#state || this.#closed || this.#failed) {
18554
+ throw new Error("Omp RPC Session is unavailable");
18555
+ }
18556
+ if (this.#activeTurn)
18557
+ throw new Error("Omp RPC Session already has an active Turn");
18558
+ if (text.length === 0)
18559
+ throw new Error("Omp text Turn must not be empty");
18560
+ const promptId = `codexhost-${randomUUID()}`;
18561
+ const settled = new Promise((resolve, reject) => {
18562
+ this.#activeTurn = {
18563
+ promptId,
18564
+ localResult: null,
18565
+ text: "",
18566
+ assistantMessageId: null,
18567
+ sawStreamedMessageText: false,
18568
+ sawStreamedMessageReasoning: false,
18569
+ lastFinalizedMessageText: null,
18570
+ lastFinalizedMessageReasoning: null,
18571
+ reasoningMessageOpen: false,
18572
+ onEvent,
18573
+ resolve,
18574
+ reject,
18575
+ failure: null,
18576
+ sawTool: false,
18577
+ tools: /* @__PURE__ */ new Map(),
18578
+ interactions: /* @__PURE__ */ new Map(),
18579
+ settlement: "pending",
18580
+ terminalEnd: false,
18581
+ cancellation: "none",
18582
+ cancellationTimeout: null,
18583
+ cancellationRecheck: null,
18584
+ cancellationChecking: false,
18585
+ cancellationReloaded: false,
18586
+ abortPromise: null
18587
+ };
18813
18588
  });
18814
- await Promise.race([
18815
- new Promise((resolve, reject) => {
18816
- child.once("spawn", resolve);
18817
- child.once("error", reject);
18818
- }),
18819
- new Promise((_resolve, reject) => setTimeout(() => reject(new Error("Omp RPC start timed out")), this.#options.commandTimeoutMs))
18820
- ]);
18821
- let readyTimeout;
18822
18589
  try {
18823
- await Promise.race([
18824
- this.#ready,
18825
- this.#startupFault.then((error51) => {
18826
- throw error51;
18827
- }),
18828
- new Promise((_resolve, reject) => {
18829
- readyTimeout = setTimeout(() => reject(new Error("Omp RPC ready signal timed out")), this.#options.commandTimeoutMs);
18830
- })
18831
- ]);
18832
- } finally {
18833
- clearTimeout(readyTimeout);
18590
+ await this.#send("prompt", { message: text }, promptId);
18591
+ } catch (error51) {
18592
+ this.#rejectActiveTurn(error51 instanceof Error ? error51 : new Error(message2(error51)));
18834
18593
  }
18835
- await this.#send("negotiate_protocol", { protocolVersion: 2 }).catch(() => void 0);
18836
- if (this.#options.subscribeSubagentEvents !== false) {
18837
- await this.#send("set_subagent_subscription", { level: "events" }).catch(() => void 0);
18594
+ return settled;
18595
+ }
18596
+ respondToInteraction(response) {
18597
+ return this.#resolveInteraction(response, "cancelled" in response ? "cancelled" : "responded");
18598
+ }
18599
+ async #resolveInteraction(response, reason) {
18600
+ const active = this.#activeTurn;
18601
+ const pending = active?.interactions.get(response.requestId);
18602
+ if (!active || !pending || this.#closed || this.#failed) {
18603
+ throw new Error("Omp RPC interaction is not pending");
18604
+ }
18605
+ if ("value" in response && !["select", "input", "editor"].includes(pending.request.method)) {
18606
+ throw new Error("Omp RPC interaction response type does not match the request");
18607
+ }
18608
+ if ("confirmed" in response && pending.request.method !== "confirm") {
18609
+ throw new Error("Omp RPC confirmation does not match the request");
18610
+ }
18611
+ const frame = "cancelled" in response ? {
18612
+ type: "extension_ui_response",
18613
+ id: response.requestId,
18614
+ cancelled: true,
18615
+ ...reason === "expired" ? { timedOut: true } : {}
18616
+ } : "confirmed" in response ? { type: "extension_ui_response", id: response.requestId, confirmed: response.confirmed } : { type: "extension_ui_response", id: response.requestId, value: response.value };
18617
+ if (!active.interactions.delete(response.requestId)) {
18618
+ throw new Error("Omp RPC interaction is not pending");
18838
18619
  }
18620
+ if (pending.timeout)
18621
+ clearTimeout(pending.timeout);
18622
+ active.onEvent({ type: "interaction.closed", requestId: response.requestId, reason });
18839
18623
  try {
18840
- this.#state = parseSessionState(await this.#send("get_state", {}));
18624
+ await this.#write(frame);
18841
18625
  } catch (error51) {
18842
- const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("unavailable", `Omp RPC state unavailable: ${message2(error51)}`);
18626
+ const fault = new OmpRpcFaultError("protocolError", `Omp RPC interaction response failed: ${message2(error51)}`);
18843
18627
  this.#fail(fault);
18844
18628
  throw fault;
18845
18629
  }
18846
- return this;
18847
18630
  }
18848
- async getEntries() {
18849
- try {
18850
- if (this.state.sessionFile) {
18851
- try {
18852
- return await readOmpSessionHistory(this.state.sessionFile);
18853
- } catch (error51) {
18854
- if (!isRecord8(error51) || error51.code !== "ENOENT" || this.#options.sessionFile || this.#options.forkSessionFile)
18855
- throw error51;
18856
- const response2 = await this.#send("get_messages", {});
18857
- const data2 = isRecord8(response2.data) ? response2.data : null;
18858
- if (data2 && Array.isArray(data2.messages) && data2.messages.length === 0) {
18859
- return { entries: [], leafId: null };
18860
- }
18861
- throw error51;
18862
- }
18863
- }
18864
- const response = await this.#send("get_messages", {});
18865
- const data = isRecord8(response.data) ? response.data : null;
18866
- if (!data || !Array.isArray(data.messages)) {
18867
- throw new OmpRpcFaultError("protocolError", "Omp RPC messages response has no messages");
18631
+ abort() {
18632
+ const active = this.#activeTurn;
18633
+ if (!active || this.#closed || this.#failed) {
18634
+ return Promise.reject(new Error("Omp RPC Session has no cancellable Turn"));
18635
+ }
18636
+ if (active.abortPromise)
18637
+ return active.abortPromise;
18638
+ active.cancellation = "requesting";
18639
+ active.cancellationTimeout = setTimeout(() => {
18640
+ this.#terminateFailedCancellation(active, new OmpRpcFaultError("protocolError", "Omp Turn cancellation did not settle within its bound"));
18641
+ }, this.#options.cancelTimeoutMs);
18642
+ const aborting = this.#send("abort", {}).then(async () => {
18643
+ if (this.#activeTurn !== active)
18644
+ return;
18645
+ active.cancellation = "accepted";
18646
+ await this.#confirmCancelledTurn(active);
18647
+ }).catch((error51) => {
18648
+ if (this.#activeTurn !== active)
18649
+ throw error51;
18650
+ const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC Abort failed: ${message2(error51)}`);
18651
+ this.#terminateFailedCancellation(active, fault);
18652
+ throw fault;
18653
+ });
18654
+ active.abortPromise = aborting;
18655
+ return aborting;
18656
+ }
18657
+ #terminateFailedCancellation(active, fault) {
18658
+ if (this.#activeTurn !== active)
18659
+ return;
18660
+ if (active.cancellationTimeout)
18661
+ clearTimeout(active.cancellationTimeout);
18662
+ active.cancellationTimeout = null;
18663
+ this.#fail(fault);
18664
+ void this.close().catch(() => void 0);
18665
+ }
18666
+ close() {
18667
+ if (!this.#closed) {
18668
+ this.#closed = true;
18669
+ this.#rejectAll(new Error("Omp RPC Session closed"));
18670
+ }
18671
+ this.#closePromise ??= this.#stopProcess();
18672
+ return this.#closePromise;
18673
+ }
18674
+ async #stopProcess() {
18675
+ const child = this.#child;
18676
+ if (!child)
18677
+ return;
18678
+ if (child.stdin.writable)
18679
+ child.stdin.end();
18680
+ if (await waitForExit(child, this.#options.closeTimeoutMs))
18681
+ return;
18682
+ signalProcessTree(child, "SIGTERM");
18683
+ if (await waitForExit(child, this.#options.closeTimeoutMs))
18684
+ return;
18685
+ signalProcessTree(child, "SIGKILL");
18686
+ if (!await waitForExit(child, this.#options.closeTimeoutMs)) {
18687
+ throw new Error("Omp RPC process tree did not exit within cleanup bounds");
18688
+ }
18689
+ }
18690
+ #push(chunk) {
18691
+ this.#buffer = this.#buffer.length === 0 ? chunk : Buffer.concat([this.#buffer, chunk]);
18692
+ let newline = this.#buffer.indexOf(10);
18693
+ while (newline >= 0) {
18694
+ const frame = this.#buffer.subarray(0, newline);
18695
+ this.#buffer = this.#buffer.subarray(newline + 1);
18696
+ let parsed;
18697
+ try {
18698
+ parsed = JSON.parse(textDecoder.decode(frame));
18699
+ } catch (error51) {
18700
+ this.#fail(new OmpRpcFaultError("protocolError", `Omp RPC returned invalid JSONL: ${message2(error51)}`));
18701
+ newline = this.#buffer.indexOf(10);
18702
+ continue;
18868
18703
  }
18869
- let branchEntryIds = null;
18870
18704
  try {
18871
- const branchResponse = await this.#send("get_branch_messages", {});
18872
- const branchData = isRecord8(branchResponse.data) ? branchResponse.data : null;
18873
- if (branchData && Array.isArray(branchData.messages)) {
18874
- const parsed = branchData.messages.flatMap((entry) => {
18875
- if (!isRecord8(entry) || !nonBlankString(entry.entryId))
18876
- return [];
18877
- return [entry.entryId];
18878
- });
18879
- if (parsed.length === branchData.messages.length)
18880
- branchEntryIds = parsed;
18705
+ const decoded = this.#frameDecoder.push(parsed);
18706
+ if (decoded === null) {
18707
+ newline = this.#buffer.indexOf(10);
18708
+ continue;
18709
+ }
18710
+ const value = decoded;
18711
+ if (!isRecord8(value) || typeof value.type !== "string") {
18712
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid envelope");
18881
18713
  }
18714
+ this.#handle(value);
18882
18715
  } catch (error51) {
18883
- if (!(error51 instanceof OmpRpcUnsupportedCommandError))
18884
- throw error51;
18716
+ this.#fail(error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC frame handling failed: ${message2(error51)}`));
18885
18717
  }
18886
- let userIndex = 0;
18887
- let parentId = null;
18888
- const entries = data.messages.map((nativeMessage, index) => {
18889
- const role = isRecord8(nativeMessage) ? nativeMessage.role : void 0;
18890
- const branchId = role === "user" ? branchEntryIds?.[userIndex] : void 0;
18891
- if (branchId)
18892
- userIndex += 1;
18893
- const id = branchId ?? (isRecord8(nativeMessage) && nonBlankString(nativeMessage.id) ? nativeMessage.id : `omp-message-${index}`);
18894
- const entry = { id, parentId, type: "message", message: nativeMessage };
18895
- parentId = id;
18896
- return entry;
18897
- });
18898
- return { entries, leafId: parentId };
18899
- } catch (error51) {
18900
- if (error51 instanceof OmpRpcFaultError)
18901
- this.#fail(error51);
18902
- throw error51;
18718
+ newline = this.#buffer.indexOf(10);
18903
18719
  }
18904
18720
  }
18905
- async getSubagentMessages(input) {
18906
- if ((input.subagentId === void 0 || !nonBlankString(input.subagentId)) && (input.sessionFile === void 0 || !nonBlankString(input.sessionFile))) {
18907
- throw new Error("Omp Subagent transcript requires a Subagent ID or Session file");
18721
+ /** Latest `available_commands_update` of the running process, if any. */
18722
+ get availableCommands() {
18723
+ return this.#availableCommands;
18724
+ }
18725
+ #handle(value) {
18726
+ if (this.#closed || this.#failed)
18727
+ return;
18728
+ if (value.type === "available_commands_update") {
18729
+ this.#availableCommands = parseOmpAvailableCommands(value.commands);
18730
+ return;
18908
18731
  }
18909
- if (input.fromByte !== void 0 && (!Number.isSafeInteger(input.fromByte) || input.fromByte < 0)) {
18910
- throw new Error("Omp Subagent transcript offset is invalid");
18732
+ if (value.type === "ready") {
18733
+ this.#readyResolve?.();
18734
+ this.#readyResolve = null;
18735
+ return;
18736
+ }
18737
+ if (value.type === "response") {
18738
+ this.#handleResponse(value);
18739
+ return;
18740
+ }
18741
+ if (value.type === "auto_compaction_start" || value.type === "compaction_start") {
18742
+ this.#compactionActive = true;
18743
+ this.#compactionTurn = this.#activeTurn;
18744
+ this.#compactionTimeout ??= setTimeout(() => {
18745
+ this.#compactionTimeout = null;
18746
+ this.#fail(new OmpRpcFaultError("protocolError", `Omp RPC compaction timed out after ${this.#options.compactionTimeoutMs}ms`));
18747
+ }, this.#options.compactionTimeoutMs);
18748
+ const onEvent = this.#activeTurn?.onEvent ?? this.#manualCompaction?.onEvent;
18749
+ onEvent?.({ type: "compaction.started" });
18750
+ for (const pending of this.#pending.values()) {
18751
+ if (pending.command !== "prompt" && pending.command !== "compact" || !pending.timeout)
18752
+ continue;
18753
+ clearTimeout(pending.timeout);
18754
+ pending.timeout = null;
18755
+ }
18756
+ return;
18757
+ }
18758
+ if (value.type === "auto_compaction_end" || value.type === "compaction_end") {
18759
+ this.#compactionActive = false;
18760
+ if (this.#compactionTimeout)
18761
+ clearTimeout(this.#compactionTimeout);
18762
+ this.#compactionTimeout = null;
18763
+ const compactionTurn = this.#compactionTurn;
18764
+ this.#compactionTurn = null;
18765
+ for (const [id, pending] of this.#pending) {
18766
+ if (pending.command === "prompt" || pending.command === "compact") {
18767
+ this.#armCommandTimeout(id, pending);
18768
+ }
18769
+ }
18770
+ const outcome = value.aborted === true ? "cancelled" : isRecord8(value.result) ? "succeeded" : "failed";
18771
+ const event = {
18772
+ type: "compaction.completed",
18773
+ outcome,
18774
+ ...nonBlankString(value.errorMessage) ? { errorMessage: value.errorMessage } : {}
18775
+ };
18776
+ compactionTurn?.onEvent(event);
18777
+ const manual = this.#manualCompaction;
18778
+ this.#manualCompaction = null;
18779
+ manual?.onEvent(event);
18780
+ manual?.resolve({
18781
+ outcome,
18782
+ ...event.errorMessage ? { errorMessage: event.errorMessage } : {}
18783
+ });
18784
+ return;
18785
+ }
18786
+ const active = this.#activeTurn;
18787
+ if (this.#handleSubagentFrame(active, value))
18788
+ return;
18789
+ this.#observeUsage(value);
18790
+ if (value.type === "agent_start" && active)
18791
+ active.terminalEnd = false;
18792
+ if ((value.type === "session_settled" || value.type === "agent_start") && active?.cancellation === "accepted") {
18793
+ void this.#confirmCancelledTurn(active);
18794
+ return;
18795
+ }
18796
+ if (!active) {
18797
+ if (value.type === "extension_ui_request" && this.#isBlockingInteraction(value)) {
18798
+ this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC requested blocking Extension UI outside an active Turn"));
18799
+ }
18800
+ return;
18801
+ }
18802
+ if (value.type === "command_output") {
18803
+ if (active.settlement !== "pending")
18804
+ return;
18805
+ if (typeof value.text !== "string") {
18806
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned invalid command output");
18807
+ }
18808
+ active.text += value.text;
18809
+ active.onEvent({ type: "text.delta", messageId: active.promptId, delta: value.text });
18810
+ return;
18811
+ }
18812
+ if (value.type === "prompt_result") {
18813
+ if (value.id !== active.promptId || value.agentInvoked !== false)
18814
+ return;
18815
+ if (value.status === "completed" || value.status === "aborted") {
18816
+ this.#settleLocalTurn(active, { cancelled: value.status === "aborted" });
18817
+ } else if (value.status === "error" && isRecord8(value.error) && typeof value.error.message === "string") {
18818
+ this.#settleLocalTurn(active, { cancelled: false, error: value.error.message });
18819
+ } else {
18820
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid local prompt result");
18821
+ }
18822
+ return;
18823
+ }
18824
+ if (value.type === "extension_ui_request") {
18825
+ this.#startInteraction(active, value);
18826
+ return;
18827
+ }
18828
+ if (value.type === "message_start" && assistantText(value.message) !== null) {
18829
+ this.#startAssistantMessage(active, value.message);
18830
+ return;
18831
+ }
18832
+ if (value.type === "message_update" && isRecord8(value.assistantMessageEvent)) {
18833
+ const event = value.assistantMessageEvent;
18834
+ const eventType = String(event.type ?? "");
18835
+ const isThinking = eventType === "thinking_delta" || eventType === "reasoning_delta" || eventType === "thought_delta" || eventType === "thinking" || eventType === "reasoning";
18836
+ const isText = eventType === "text_delta" || eventType === "text" || eventType === "content_block_delta";
18837
+ const delta = typeof event.delta === "string" ? event.delta : typeof event.thinking === "string" ? event.thinking : typeof event.reasoning === "string" ? event.reasoning : typeof event.text === "string" ? event.text : isRecord8(event.delta) && typeof event.delta.thinking === "string" ? event.delta.thinking : isRecord8(event.delta) && typeof event.delta.text === "string" ? event.delta.text : null;
18838
+ if (isThinking && delta !== null && delta.length > 0) {
18839
+ const messageId = this.#ensureAssistantMessage(active, value.message);
18840
+ active.reasoningMessageOpen = true;
18841
+ active.sawStreamedMessageReasoning = true;
18842
+ active.onEvent({ type: "reasoning.delta", messageId, delta });
18843
+ } else if (isText && delta !== null && delta.length > 0) {
18844
+ const messageId = this.#ensureAssistantMessage(active, value.message);
18845
+ active.text += delta;
18846
+ active.sawStreamedMessageText = true;
18847
+ active.onEvent({ type: "text.delta", messageId, delta });
18848
+ } else if (event.type === "error") {
18849
+ this.#ensureAssistantMessage(active, value.message);
18850
+ active.failure = assistantFailure(event.error) ?? assistantFailure(value.message) ?? new Error("Omp assistant message failed");
18851
+ }
18852
+ return;
18853
+ }
18854
+ if (value.type === "message_end") {
18855
+ this.#finalizeAssistantMessage(active, value.message);
18856
+ return;
18857
+ }
18858
+ if (value.type === "turn_end") {
18859
+ this.#finalizeAssistantMessage(active, value.message);
18860
+ return;
18861
+ }
18862
+ if (value.type === "tool_execution_start") {
18863
+ this.#startTool(active, value);
18864
+ return;
18865
+ }
18866
+ if (value.type === "tool_execution_update") {
18867
+ this.#updateTool(active, value);
18868
+ return;
18869
+ }
18870
+ if (value.type === "tool_execution_end") {
18871
+ this.#completeTool(active, value);
18872
+ return;
18873
+ }
18874
+ if (value.type === "agent_end" && Array.isArray(value.messages)) {
18875
+ for (let index = value.messages.length - 1; index >= 0; index -= 1) {
18876
+ const message3 = value.messages[index];
18877
+ if (!isRecord8(message3) || message3.role !== "assistant")
18878
+ continue;
18879
+ this.#finalizeAssistantMessage(active, message3);
18880
+ break;
18881
+ }
18882
+ }
18883
+ if (value.type === "agent_end" && value.isTerminal !== false) {
18884
+ active.terminalEnd = true;
18885
+ if (active.cancellation !== "none") {
18886
+ if (active.cancellation === "accepted")
18887
+ void this.#confirmCancelledTurn(active);
18888
+ return;
18889
+ }
18890
+ if (active.settlement !== "pending")
18891
+ return;
18892
+ active.settlement = "confirming";
18893
+ void this.#confirmSettledTurn(active);
18911
18894
  }
18912
- const response = await this.#send("get_subagent_messages", {
18913
- ...input.subagentId ? { subagentId: input.subagentId } : {},
18914
- ...input.sessionFile ? { sessionFile: input.sessionFile } : {},
18915
- ...input.fromByte !== void 0 ? { fromByte: input.fromByte } : {}
18916
- });
18917
- return parseSubagentMessages(response);
18918
18895
  }
18919
- async compact(customInstructions, onEvent) {
18920
- if (!this.#child || !this.#state || this.#closed || this.#failed) {
18921
- throw new Error("Omp RPC Session is unavailable");
18896
+ /** Every finished assistant message is one model request, with or without an active Turn. */
18897
+ #observeUsage(value) {
18898
+ if (value.type === "message_start") {
18899
+ this.#usageRequestStartedAtMs = null;
18900
+ return;
18922
18901
  }
18923
- if (this.#activeTurn || this.#manualCompaction || this.#compactionActive) {
18924
- throw new Error("Omp RPC Session already has an active operation");
18902
+ if (value.type === "message_update") {
18903
+ const event = value.assistantMessageEvent;
18904
+ if (this.#usageRequestStartedAtMs === null && isRecord8(event) && typeof event.type === "string" && /^(text|thinking|reasoning|thought|toolcall)_(start|delta)$/u.test(event.type)) {
18905
+ this.#usageRequestStartedAtMs = Date.now();
18906
+ }
18907
+ return;
18925
18908
  }
18926
- const result = new Promise((resolve, reject) => {
18927
- this.#manualCompaction = { onEvent, resolve, reject };
18928
- });
18929
- try {
18930
- await this.#send("compact", customInstructions ? { customInstructions } : {});
18931
- } catch (error51) {
18932
- const pending = this.#manualCompaction;
18933
- this.#manualCompaction = null;
18934
- pending?.reject(error51 instanceof Error ? error51 : new Error(message2(error51)));
18909
+ if (value.type === "message_end" && isRecord8(value.message)) {
18910
+ if (value.message.role !== "assistant")
18911
+ return;
18912
+ const startedAtMs = this.#usageRequestStartedAtMs;
18913
+ this.#usageRequestStartedAtMs = null;
18914
+ this.#options.onUsage?.({
18915
+ message: value.message,
18916
+ startedAtMs,
18917
+ completedAtMs: Date.now()
18918
+ });
18935
18919
  }
18936
- return result;
18937
18920
  }
18938
- async getSessionUsage() {
18939
- try {
18940
- const usage = parseOmpSessionUsage(await this.#send("get_session_stats", {}));
18941
- await this.#ensureLatestCacheHitRate();
18942
- return this.#withLatestCacheHitRate(usage);
18943
- } catch (error51) {
18944
- if (!(error51 instanceof OmpRpcUnsupportedCommandError))
18945
- throw error51;
18946
- const response = await this.#send("get_state", {});
18947
- const observedState = parseSessionState(response);
18948
- if (!this.#state || observedState.sessionId !== this.#state.sessionId || observedState.provider !== this.#state.provider || observedState.modelId !== this.#state.modelId) {
18949
- throw new Error("Omp RPC Usage fallback does not match the confirmed Session state");
18950
- }
18951
- await this.#ensureLatestCacheHitRate();
18952
- const usage = parseOmpStateContextUsage(response);
18953
- return usage ? this.#withLatestCacheHitRate(usage) : null;
18921
+ #handleSubagentFrame(active, value) {
18922
+ if (value.type !== "subagent_lifecycle" && value.type !== "subagent_progress" && value.type !== "subagent_event") {
18923
+ return false;
18954
18924
  }
18955
- }
18956
- async #ensureLatestCacheHitRate() {
18957
- if (this.#latestCacheHitRatePercent !== void 0)
18958
- return;
18959
- try {
18960
- this.#latestCacheHitRatePercent = latestOmpCacheHitRatePercent(await this.getEntries());
18961
- } catch {
18962
- this.#latestCacheHitRatePercent = null;
18925
+ const payload = isRecord8(value.payload) ? value.payload : null;
18926
+ const progressPayload = value.type === "subagent_progress" && payload && isRecord8(payload.progress) ? payload.progress : null;
18927
+ const nativeIdValue = progressPayload?.id ?? payload?.id;
18928
+ if (!payload || !nonBlankString(nativeIdValue)) {
18929
+ throw new OmpRpcFaultError("protocolError", "Omp RPC Subagent frame has no stable ID");
18963
18930
  }
18964
- }
18965
- #withLatestCacheHitRate(usage) {
18966
- return this.#latestCacheHitRatePercent === null || this.#latestCacheHitRatePercent === void 0 ? usage : parseHostUsage({ ...usage, cacheHitRatePercent: this.#latestCacheHitRatePercent });
18967
- }
18968
- async fork(entryId) {
18969
- if (!nonBlankString(entryId))
18970
- throw new Error("Omp RPC Fork requires an Entry identity");
18971
- try {
18972
- const response = await this.#send("branch", { entryId });
18973
- const data = isRecord8(response.data) ? response.data : null;
18974
- if (!data || data.cancelled === true) {
18975
- throw new OmpRpcFaultError("unavailable", "Omp RPC Fork was cancelled");
18931
+ const nativeSubagentId = nativeIdValue;
18932
+ const callId = nativeSubagentId;
18933
+ const emit = active?.onEvent ?? this.#options.onSubagentEvent;
18934
+ if (value.type === "subagent_event") {
18935
+ emit?.({ type: "subagent.transcript.changed", callId, nativeSubagentId });
18936
+ return true;
18937
+ }
18938
+ if (value.type === "subagent_lifecycle") {
18939
+ const status2 = payload.status;
18940
+ if (status2 === "started") {
18941
+ const description = nonBlankString(payload.description) ? payload.description : nonBlankString(payload.agent) ? `${payload.agent} delegation` : "Subagent delegation";
18942
+ emit?.({
18943
+ type: "subagent.started",
18944
+ callId,
18945
+ nativeSubagentId,
18946
+ description,
18947
+ ...nonBlankString(payload.agent) ? { role: payload.agent } : {},
18948
+ ...nonBlankString(payload.task) ? { prompt: payload.task } : {},
18949
+ background: payload.detached === true,
18950
+ ...typeof payload.sessionFile === "string" ? { sessionFile: payload.sessionFile } : {}
18951
+ });
18952
+ return true;
18976
18953
  }
18977
- this.#state = parseSessionState(await this.#send("get_state", {}));
18978
- return this.#state;
18979
- } catch (error51) {
18980
- if (error51 instanceof OmpRpcFaultError)
18981
- this.#fail(error51);
18982
- throw error51;
18954
+ if (status2 !== "completed" && status2 !== "failed" && status2 !== "aborted") {
18955
+ throw new OmpRpcFaultError("protocolError", "Omp RPC Subagent lifecycle status is invalid");
18956
+ }
18957
+ emit?.({
18958
+ type: "subagent.completed",
18959
+ callId,
18960
+ nativeSubagentId,
18961
+ isError: status2 !== "completed",
18962
+ ...nonBlankString(payload.resultSummary) ? { resultSummary: payload.resultSummary } : {},
18963
+ ...typeof payload.sessionFile === "string" ? { sessionFile: payload.sessionFile } : {}
18964
+ });
18965
+ return true;
18983
18966
  }
18984
- }
18985
- verifySessionCwd(expectedCwd) {
18986
- return verifyOmpSessionCwd({
18987
- sessionFile: this.state.sessionFile,
18988
- sessionId: this.state.sessionId,
18989
- expectedCwd
18990
- });
18991
- }
18992
- async getAvailableModels() {
18993
- try {
18994
- return parseAvailableModels(await this.#send("get_available_models", {}));
18995
- } catch (error51) {
18996
- if (error51 instanceof OmpRpcFaultError)
18997
- this.#fail(error51);
18998
- throw error51;
18967
+ const progress = progressPayload;
18968
+ if (!progress || !nonBlankString(progress.id) || progress.id !== nativeSubagentId) {
18969
+ throw new OmpRpcFaultError("protocolError", "Omp RPC Subagent progress is invalid");
18999
18970
  }
18971
+ const status = subagentStatus(progress.status);
18972
+ const recentOutput = Array.isArray(progress.recentOutput) ? progress.recentOutput.filter((item) => typeof item === "string") : [];
18973
+ const resultSummary = recentOutput.at(-1);
18974
+ emit?.({
18975
+ type: "subagent.updated",
18976
+ callId,
18977
+ nativeSubagentId,
18978
+ status,
18979
+ ...nonBlankString(progress.description) ? { description: progress.description } : nonBlankString(payload.task) ? { description: payload.task } : {},
18980
+ ...resultSummary !== void 0 ? { resultSummary } : {},
18981
+ ...typeof payload.sessionFile === "string" ? { sessionFile: payload.sessionFile } : {}
18982
+ });
18983
+ return true;
19000
18984
  }
19001
- async getAvailableThinkingLevels() {
19002
- return this.state.availableThinkingLevels;
19003
- }
19004
- async selectModel(model2) {
19005
- await this.#send("set_model", { provider: model2.provider, modelId: model2.id });
19006
- return this.#refreshState("Model");
19007
- }
19008
- async selectThinkingOption(thinkingOptionId) {
19009
- const level = harnessThinkingOptionIdSchema.parse(thinkingOptionId);
19010
- await this.#send("set_thinking_level", { level });
19011
- return this.#refreshState("Thinking");
19012
- }
19013
- async #refreshState(operation) {
19014
- try {
19015
- this.#state = parseSessionState(await this.#send("get_state", {}));
19016
- return this.#state;
19017
- } catch (error51) {
19018
- const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC ${operation} state could not be confirmed: ${message2(error51)}`);
19019
- this.#fail(fault);
19020
- throw fault;
19021
- }
18985
+ #isBlockingInteraction(value) {
18986
+ return ["select", "confirm", "input", "editor"].includes(String(value.method));
19022
18987
  }
19023
- async runTurn(text, onEvent) {
19024
- if (!this.#child || !this.#state || this.#closed || this.#failed) {
19025
- throw new Error("Omp RPC Session is unavailable");
18988
+ #startInteraction(active, value) {
18989
+ if (!this.#isBlockingInteraction(value))
18990
+ return;
18991
+ const requestId = value.id;
18992
+ const method = value.method;
18993
+ const title = value.title;
18994
+ const timeoutMs = value.timeout;
18995
+ if (typeof requestId !== "string" || requestId.length === 0 || typeof method !== "string" || typeof title !== "string" || title.length === 0 || timeoutMs !== void 0 && (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs < 0) || active.interactions.has(requestId)) {
18996
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Interaction request");
19026
18997
  }
19027
- if (this.#activeTurn)
19028
- throw new Error("Omp RPC Session already has an active Turn");
19029
- if (text.length === 0)
19030
- throw new Error("Omp text Turn must not be empty");
19031
- const promptId = `codexhost-${randomUUID()}`;
19032
- const settled = new Promise((resolve, reject) => {
19033
- this.#activeTurn = {
19034
- promptId,
19035
- localResult: null,
19036
- text: "",
19037
- assistantMessageId: null,
19038
- sawStreamedMessageText: false,
19039
- sawStreamedMessageReasoning: false,
19040
- lastFinalizedMessageText: null,
19041
- lastFinalizedMessageReasoning: null,
19042
- reasoningMessageOpen: false,
19043
- onEvent,
19044
- resolve,
19045
- reject,
19046
- failure: null,
19047
- sawTool: false,
19048
- tools: /* @__PURE__ */ new Map(),
19049
- interactions: /* @__PURE__ */ new Map(),
19050
- settlement: "pending",
19051
- terminalEnd: false,
19052
- cancellation: "none",
19053
- cancellationTimeout: null,
19054
- cancellationRecheck: null,
19055
- cancellationChecking: false,
19056
- cancellationReloaded: false,
19057
- abortPromise: null
18998
+ let request;
18999
+ if (method === "select") {
19000
+ if (!Array.isArray(value.options) || value.options.length === 0 || !value.options.every((option) => typeof option === "string" && option.length > 0)) {
19001
+ throw new OmpRpcFaultError("protocolError", "Omp RPC select request has invalid options");
19002
+ }
19003
+ let optionDetails;
19004
+ if (value.optionDetails !== void 0) {
19005
+ if (!Array.isArray(value.optionDetails) || value.optionDetails.length !== value.options.length || !value.optionDetails.every((detail) => typeof detail === "object" && detail !== null && !Array.isArray(detail) && (detail.description === void 0 || typeof detail.description === "string"))) {
19006
+ throw new OmpRpcFaultError("protocolError", "Omp RPC select option details are invalid");
19007
+ }
19008
+ optionDetails = value.optionDetails.map(({ description }) => description === void 0 ? {} : { description });
19009
+ }
19010
+ request = {
19011
+ requestId,
19012
+ method,
19013
+ title,
19014
+ options: [...value.options],
19015
+ ...optionDetails ? { optionDetails } : {},
19016
+ ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19017
+ };
19018
+ } else if (method === "confirm") {
19019
+ if (typeof value.message !== "string") {
19020
+ throw new OmpRpcFaultError("protocolError", "Omp RPC confirm request has no message");
19021
+ }
19022
+ request = {
19023
+ requestId,
19024
+ method,
19025
+ title,
19026
+ message: value.message,
19027
+ ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19028
+ };
19029
+ } else if (method === "input") {
19030
+ if (value.placeholder !== void 0 && typeof value.placeholder !== "string") {
19031
+ throw new OmpRpcFaultError("protocolError", "Omp RPC input placeholder is invalid");
19032
+ }
19033
+ request = {
19034
+ requestId,
19035
+ method,
19036
+ title,
19037
+ ...typeof value.placeholder === "string" ? { placeholder: value.placeholder } : {},
19038
+ ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19039
+ };
19040
+ } else {
19041
+ if (value.prefill !== void 0 && typeof value.prefill !== "string") {
19042
+ throw new OmpRpcFaultError("protocolError", "Omp RPC editor prefill is invalid");
19043
+ }
19044
+ request = {
19045
+ requestId,
19046
+ method: "editor",
19047
+ title,
19048
+ ...typeof value.prefill === "string" ? { prefill: value.prefill } : {},
19049
+ ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19058
19050
  };
19059
- });
19060
- try {
19061
- await this.#send("prompt", { message: text }, promptId);
19062
- } catch (error51) {
19063
- this.#rejectActiveTurn(error51 instanceof Error ? error51 : new Error(message2(error51)));
19064
- }
19065
- return settled;
19066
- }
19067
- respondToInteraction(response) {
19068
- return this.#resolveInteraction(response, "cancelled" in response ? "cancelled" : "responded");
19069
- }
19070
- async #resolveInteraction(response, reason) {
19071
- const active = this.#activeTurn;
19072
- const pending = active?.interactions.get(response.requestId);
19073
- if (!active || !pending || this.#closed || this.#failed) {
19074
- throw new Error("Omp RPC interaction is not pending");
19075
19051
  }
19076
- if ("value" in response && !["select", "input", "editor"].includes(pending.request.method)) {
19077
- throw new Error("Omp RPC interaction response type does not match the request");
19052
+ const pending = { request, timeout: null };
19053
+ if (request.timeoutMs !== void 0) {
19054
+ pending.timeout = setTimeout(() => {
19055
+ if (this.#activeTurn !== active || !active.interactions.has(requestId))
19056
+ return;
19057
+ void this.#resolveInteraction({ requestId, cancelled: true }, "expired").catch((error51) => {
19058
+ if (this.#closed || this.#failed)
19059
+ return;
19060
+ this.#fail(new OmpRpcFaultError("protocolError", `Omp RPC Interaction timeout handling failed: ${message2(error51)}`));
19061
+ });
19062
+ }, request.timeoutMs);
19078
19063
  }
19079
- if ("confirmed" in response && pending.request.method !== "confirm") {
19080
- throw new Error("Omp RPC confirmation does not match the request");
19064
+ active.interactions.set(requestId, pending);
19065
+ active.onEvent({ type: "interaction.requested", request });
19066
+ }
19067
+ #handleResponse(value) {
19068
+ const id = value.id;
19069
+ if (typeof id !== "string") {
19070
+ this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC response has no id"));
19071
+ return;
19081
19072
  }
19082
- const frame = "cancelled" in response ? {
19083
- type: "extension_ui_response",
19084
- id: response.requestId,
19085
- cancelled: true,
19086
- ...reason === "expired" ? { timedOut: true } : {}
19087
- } : "confirmed" in response ? { type: "extension_ui_response", id: response.requestId, confirmed: response.confirmed } : { type: "extension_ui_response", id: response.requestId, value: response.value };
19088
- if (!active.interactions.delete(response.requestId)) {
19089
- throw new Error("Omp RPC interaction is not pending");
19073
+ const pending = this.#pending.get(id);
19074
+ const active = this.#activeTurn;
19075
+ if (!pending) {
19076
+ if (active?.promptId === id && value.command === "prompt" && value.success === false) {
19077
+ active.failure = new Error(typeof value.error === "string" ? value.error : "Omp RPC command failed");
19078
+ return;
19079
+ }
19080
+ this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC response id is not pending"));
19081
+ return;
19090
19082
  }
19091
19083
  if (pending.timeout)
19092
19084
  clearTimeout(pending.timeout);
19093
- active.onEvent({ type: "interaction.closed", requestId: response.requestId, reason });
19094
- try {
19095
- await this.#write(frame);
19096
- } catch (error51) {
19097
- const fault = new OmpRpcFaultError("protocolError", `Omp RPC interaction response failed: ${message2(error51)}`);
19098
- this.#fail(fault);
19099
- throw fault;
19085
+ this.#pending.delete(id);
19086
+ if (value.success === true) {
19087
+ if (pending.command === "prompt" && active?.promptId === id && isRecord8(value.data) && value.data.agentInvoked === false) {
19088
+ this.#settleLocalTurn(active, { cancelled: false });
19089
+ }
19090
+ pending.resolve(value);
19091
+ } else {
19092
+ const error51 = typeof value.error === "string" ? value.error : "Omp RPC command failed";
19093
+ if (value.command === pending.command && error51 === `Unknown command: ${pending.command}`) {
19094
+ pending.reject(new OmpRpcUnsupportedCommandError(pending.command));
19095
+ } else {
19096
+ pending.reject(new Error(error51));
19097
+ }
19100
19098
  }
19101
19099
  }
19102
- abort() {
19103
- const active = this.#activeTurn;
19104
- if (!active || this.#closed || this.#failed) {
19105
- return Promise.reject(new Error("Omp RPC Session has no cancellable Turn"));
19100
+ #startTool(active, value) {
19101
+ const callId = value.toolCallId;
19102
+ const toolName = value.toolName;
19103
+ const argumentsResult = jsonValueSchema.safeParse(value.args);
19104
+ if (typeof callId !== "string" || callId.length === 0 || typeof toolName !== "string" || toolName.length === 0 || !argumentsResult.success || active.tools.has(callId)) {
19105
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool start");
19106
19106
  }
19107
- if (active.abortPromise)
19108
- return active.abortPromise;
19109
- active.cancellation = "requesting";
19110
- active.cancellationTimeout = setTimeout(() => {
19111
- this.#terminateFailedCancellation(active, new OmpRpcFaultError("protocolError", "Omp Turn cancellation did not settle within its bound"));
19112
- }, this.#options.cancelTimeoutMs);
19113
- const aborting = this.#send("abort", {}).then(async () => {
19114
- if (this.#activeTurn !== active)
19115
- return;
19116
- active.cancellation = "accepted";
19117
- await this.#confirmCancelledTurn(active);
19118
- }).catch((error51) => {
19119
- if (this.#activeTurn !== active)
19120
- throw error51;
19121
- const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC Abort failed: ${message2(error51)}`);
19122
- this.#terminateFailedCancellation(active, fault);
19123
- throw fault;
19107
+ active.sawTool = true;
19108
+ active.tools.set(callId, toolName);
19109
+ active.onEvent({
19110
+ type: "tool.started",
19111
+ callId,
19112
+ toolName,
19113
+ arguments: argumentsResult.data
19124
19114
  });
19125
- active.abortPromise = aborting;
19126
- return aborting;
19127
19115
  }
19128
- #terminateFailedCancellation(active, fault) {
19129
- if (this.#activeTurn !== active)
19116
+ #updateTool(active, value) {
19117
+ const callId = value.toolCallId;
19118
+ if (typeof callId !== "string" || callId.length === 0) {
19119
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool update");
19120
+ }
19121
+ if (!active.tools.has(callId))
19130
19122
  return;
19131
- if (active.cancellationTimeout)
19132
- clearTimeout(active.cancellationTimeout);
19133
- active.cancellationTimeout = null;
19134
- this.#fail(fault);
19135
- void this.close().catch(() => void 0);
19136
- }
19137
- close() {
19138
- if (!this.#closed) {
19139
- this.#closed = true;
19140
- this.#rejectAll(new Error("Omp RPC Session closed"));
19123
+ const outputResult = jsonValueSchema.safeParse(value.partialResult ?? null);
19124
+ if (!outputResult.success) {
19125
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool update");
19141
19126
  }
19142
- this.#closePromise ??= this.#stopProcess();
19143
- return this.#closePromise;
19127
+ active.onEvent({ type: "tool.updated", callId, output: outputResult.data });
19144
19128
  }
19145
- async #stopProcess() {
19146
- const child = this.#child;
19147
- if (!child)
19148
- return;
19149
- if (child.stdin.writable)
19150
- child.stdin.end();
19151
- if (await waitForExit(child, this.#options.closeTimeoutMs))
19152
- return;
19153
- signalProcessTree(child, "SIGTERM");
19154
- if (await waitForExit(child, this.#options.closeTimeoutMs))
19129
+ #completeTool(active, value) {
19130
+ const callId = value.toolCallId;
19131
+ const toolName = value.toolName;
19132
+ if (typeof callId !== "string" || callId.length === 0) {
19133
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool end");
19134
+ }
19135
+ const expectedName = active.tools.get(callId);
19136
+ if (expectedName === void 0)
19155
19137
  return;
19156
- signalProcessTree(child, "SIGKILL");
19157
- if (!await waitForExit(child, this.#options.closeTimeoutMs)) {
19158
- throw new Error("Omp RPC process tree did not exit within cleanup bounds");
19138
+ const result = jsonValueSchema.safeParse(value.result);
19139
+ if (typeof toolName !== "string" || expectedName !== toolName || value.isError !== void 0 && typeof value.isError !== "boolean" || !result.success) {
19140
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool end");
19159
19141
  }
19142
+ active.tools.delete(callId);
19143
+ active.onEvent({
19144
+ type: "tool.completed",
19145
+ callId,
19146
+ toolName,
19147
+ result: result.data,
19148
+ isError: value.isError === true
19149
+ });
19160
19150
  }
19161
- #push(chunk) {
19162
- this.#buffer = this.#buffer.length === 0 ? chunk : Buffer.concat([this.#buffer, chunk]);
19163
- let newline = this.#buffer.indexOf(10);
19164
- while (newline >= 0) {
19165
- const frame = this.#buffer.subarray(0, newline);
19166
- this.#buffer = this.#buffer.subarray(newline + 1);
19167
- let parsed;
19168
- try {
19169
- parsed = JSON.parse(textDecoder.decode(frame));
19170
- } catch (error51) {
19171
- this.#fail(new OmpRpcFaultError("protocolError", `Omp RPC returned invalid JSONL: ${message2(error51)}`));
19172
- newline = this.#buffer.indexOf(10);
19173
- continue;
19151
+ async #confirmCancelledTurn(active) {
19152
+ if (this.#activeTurn !== active || active.cancellation !== "accepted" || active.settlement === "confirming" || active.cancellationChecking)
19153
+ return;
19154
+ active.cancellationChecking = true;
19155
+ if (active.cancellationRecheck)
19156
+ clearTimeout(active.cancellationRecheck);
19157
+ active.cancellationRecheck = null;
19158
+ try {
19159
+ let response = await this.#send("get_state", {});
19160
+ if (this.#activeTurn !== active)
19161
+ return;
19162
+ if (parseSessionStreaming(response)) {
19163
+ await this.#send("abort", {});
19164
+ if (this.#activeTurn !== active)
19165
+ return;
19166
+ response = await this.#send("get_state", {});
19174
19167
  }
19175
- try {
19176
- const decoded = this.#frameDecoder.push(parsed);
19177
- if (decoded === null) {
19178
- newline = this.#buffer.indexOf(10);
19179
- continue;
19168
+ let state = parseSessionState(response);
19169
+ if (this.#activeTurn !== active || active.cancellation !== "accepted")
19170
+ return;
19171
+ const data = sessionStateData(response);
19172
+ if (!active.cancellationReloaded && state.sessionFile && state.sessionId === this.state.sessionId && state.sessionFile === this.state.sessionFile && data.isStreaming === false && data.isCompacting === false && data.queuedMessageCount === 0 && data.hasPendingAsyncWork === true && active.tools.size === 0) {
19173
+ await this.verifySessionCwd(this.#options.cwd);
19174
+ if (this.#activeTurn !== active)
19175
+ return;
19176
+ active.cancellationReloaded = true;
19177
+ const reset = await this.#send("new_session", {});
19178
+ if (this.#activeTurn !== active)
19179
+ return;
19180
+ if (!isRecord8(reset.data) || reset.data.cancelled !== false) {
19181
+ throw new OmpRpcFaultError("unavailable", "Omp cancelled Session reset was refused");
19182
+ }
19183
+ const reloaded = await this.#send("switch_session", { sessionPath: state.sessionFile });
19184
+ if (this.#activeTurn !== active)
19185
+ return;
19186
+ if (!isRecord8(reloaded.data) || reloaded.data.cancelled !== false) {
19187
+ throw new OmpRpcFaultError("unavailable", "Omp cancelled Session reload was refused");
19188
+ }
19189
+ const previous = state;
19190
+ response = await this.#send("get_state", {});
19191
+ state = parseSessionState(response);
19192
+ if (state.sessionId !== previous.sessionId || state.sessionFile !== previous.sessionFile) {
19193
+ throw new OmpRpcFaultError("protocolError", "Omp cancelled Session reload changed its identity");
19194
+ }
19195
+ if (state.provider !== previous.provider || state.modelId !== previous.modelId) {
19196
+ if (!previous.provider || !previous.modelId) {
19197
+ throw new OmpRpcFaultError("protocolError", "Omp cancelled Session has no restorable Model");
19198
+ }
19199
+ await this.#send("set_model", { provider: previous.provider, modelId: previous.modelId });
19180
19200
  }
19181
- const value = decoded;
19182
- if (!isRecord8(value) || typeof value.type !== "string") {
19183
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid envelope");
19201
+ if (previous.thinkingLevel && state.thinkingLevel !== previous.thinkingLevel) {
19202
+ await this.#send("set_thinking_level", { level: previous.thinkingLevel });
19203
+ }
19204
+ response = await this.#send("get_state", {});
19205
+ state = parseSessionState(response);
19206
+ if (state.sessionId !== previous.sessionId || state.sessionFile !== previous.sessionFile || state.provider !== previous.provider || state.modelId !== previous.modelId || previous.thinkingLevel !== null && state.thinkingLevel !== previous.thinkingLevel) {
19207
+ throw new OmpRpcFaultError("protocolError", "Omp cancelled Session reload changed its identity or configuration");
19184
19208
  }
19185
- this.#handle(value);
19186
- } catch (error51) {
19187
- this.#fail(error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC frame handling failed: ${message2(error51)}`));
19188
19209
  }
19189
- newline = this.#buffer.indexOf(10);
19210
+ if (!cancellationSettled(response, active.terminalEnd)) {
19211
+ active.settlement = "pending";
19212
+ active.cancellationRecheck = setTimeout(() => {
19213
+ active.cancellationRecheck = null;
19214
+ void this.#confirmCancelledTurn(active);
19215
+ }, 250);
19216
+ return;
19217
+ }
19218
+ this.#state = state;
19219
+ active.settlement = "confirmed";
19220
+ this.#finishSettledTurn(active);
19221
+ } catch (error51) {
19222
+ if (this.#activeTurn !== active)
19223
+ return;
19224
+ const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC cancelled Turn state could not be confirmed: ${message2(error51)}`);
19225
+ this.#terminateFailedCancellation(active, fault);
19226
+ } finally {
19227
+ active.cancellationChecking = false;
19190
19228
  }
19191
19229
  }
19192
- /** Latest `available_commands_update` of the running process, if any. */
19193
- get availableCommands() {
19194
- return this.#availableCommands;
19195
- }
19196
- #handle(value) {
19197
- if (this.#closed || this.#failed)
19198
- return;
19199
- if (value.type === "available_commands_update") {
19200
- this.#availableCommands = parseOmpAvailableCommands(value.commands);
19201
- return;
19202
- }
19203
- if (value.type === "ready") {
19204
- this.#readyResolve?.();
19205
- this.#readyResolve = null;
19206
- return;
19207
- }
19208
- if (value.type === "response") {
19209
- this.#handleResponse(value);
19230
+ #settleLocalTurn(active, result) {
19231
+ if (this.#activeTurn !== active || active.settlement !== "pending")
19210
19232
  return;
19211
- }
19212
- if (value.type === "auto_compaction_start" || value.type === "compaction_start") {
19213
- this.#compactionActive = true;
19214
- this.#compactionTurn = this.#activeTurn;
19215
- this.#compactionTimeout ??= setTimeout(() => {
19216
- this.#compactionTimeout = null;
19217
- this.#fail(new OmpRpcFaultError("protocolError", `Omp RPC compaction timed out after ${this.#options.compactionTimeoutMs}ms`));
19218
- }, this.#options.compactionTimeoutMs);
19219
- const onEvent = this.#activeTurn?.onEvent ?? this.#manualCompaction?.onEvent;
19220
- onEvent?.({ type: "compaction.started" });
19221
- for (const pending of this.#pending.values()) {
19222
- if (pending.command !== "prompt" && pending.command !== "compact" || !pending.timeout)
19223
- continue;
19224
- clearTimeout(pending.timeout);
19225
- pending.timeout = null;
19233
+ active.localResult = result;
19234
+ active.settlement = "confirming";
19235
+ void this.#confirmSettledTurn(active);
19236
+ }
19237
+ async #confirmSettledTurn(active) {
19238
+ try {
19239
+ const response = await this.#send("get_state", {});
19240
+ const state = parseSessionState(response);
19241
+ if (this.#activeTurn !== active)
19242
+ return;
19243
+ if (active.cancellation !== "none") {
19244
+ active.settlement = "pending";
19245
+ if (active.cancellation === "accepted")
19246
+ void this.#confirmCancelledTurn(active);
19247
+ return;
19226
19248
  }
19227
- return;
19228
- }
19229
- if (value.type === "auto_compaction_end" || value.type === "compaction_end") {
19230
- this.#compactionActive = false;
19231
- if (this.#compactionTimeout)
19232
- clearTimeout(this.#compactionTimeout);
19233
- this.#compactionTimeout = null;
19234
- const compactionTurn = this.#compactionTurn;
19235
- this.#compactionTurn = null;
19236
- for (const [id, pending] of this.#pending) {
19237
- if (pending.command === "prompt" || pending.command === "compact") {
19238
- this.#armCommandTimeout(id, pending);
19239
- }
19249
+ if (parseSessionStreaming(response)) {
19250
+ throw new OmpRpcFaultError("protocolError", "Omp RPC completed Turn state is still Streaming");
19240
19251
  }
19241
- const outcome = value.aborted === true ? "cancelled" : isRecord8(value.result) ? "succeeded" : "failed";
19242
- const event = {
19243
- type: "compaction.completed",
19244
- outcome,
19245
- ...nonBlankString(value.errorMessage) ? { errorMessage: value.errorMessage } : {}
19246
- };
19247
- compactionTurn?.onEvent(event);
19248
- const manual = this.#manualCompaction;
19249
- this.#manualCompaction = null;
19250
- manual?.onEvent(event);
19251
- manual?.resolve({
19252
- outcome,
19253
- ...event.errorMessage ? { errorMessage: event.errorMessage } : {}
19254
- });
19255
- return;
19252
+ this.#state = state;
19253
+ active.settlement = "confirmed";
19254
+ this.#finishSettledTurn(active);
19255
+ } catch (error51) {
19256
+ if (this.#activeTurn !== active)
19257
+ return;
19258
+ const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC stable Turn state could not be confirmed: ${message2(error51)}`);
19259
+ this.#fail(fault);
19256
19260
  }
19257
- const active = this.#activeTurn;
19258
- if (this.#handleSubagentFrame(active, value))
19259
- return;
19260
- this.#observeUsage(value);
19261
- if (value.type === "agent_start" && active)
19262
- active.terminalEnd = false;
19263
- if ((value.type === "session_settled" || value.type === "agent_start") && active?.cancellation === "accepted") {
19264
- void this.#confirmCancelledTurn(active);
19261
+ }
19262
+ #finishSettledTurn(active) {
19263
+ if (this.#activeTurn !== active || active.settlement !== "confirmed" || active.cancellation === "requesting") {
19265
19264
  return;
19266
19265
  }
19267
- if (!active) {
19268
- if (value.type === "extension_ui_request" && this.#isBlockingInteraction(value)) {
19269
- this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC requested blocking Extension UI outside an active Turn"));
19270
- }
19266
+ if (active.cancellationTimeout)
19267
+ clearTimeout(active.cancellationTimeout);
19268
+ active.cancellationTimeout = null;
19269
+ if (active.cancellationRecheck)
19270
+ clearTimeout(active.cancellationRecheck);
19271
+ active.cancellationRecheck = null;
19272
+ this.#closeInteractions(active, active.cancellation === "accepted" ? "cancelled" : "superseded");
19273
+ if (active.tools.size > 0) {
19274
+ this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC settled with active Tool executions"));
19271
19275
  return;
19272
19276
  }
19273
- if (value.type === "command_output") {
19274
- if (active.settlement !== "pending")
19275
- return;
19276
- if (typeof value.text !== "string") {
19277
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned invalid command output");
19278
- }
19279
- active.text += value.text;
19280
- active.onEvent({ type: "text.delta", messageId: active.promptId, delta: value.text });
19281
- return;
19277
+ this.#activeTurn = null;
19278
+ if (active.localResult) {
19279
+ active.resolve({
19280
+ text: active.text,
19281
+ agentInvoked: false,
19282
+ ...active.localResult,
19283
+ cancelled: active.localResult.cancelled || active.cancellation === "accepted"
19284
+ });
19285
+ } else if (active.cancellation === "accepted") {
19286
+ active.resolve({ text: active.text, cancelled: true, agentInvoked: true });
19287
+ } else if (active.failure) {
19288
+ active.reject(active.failure);
19289
+ } else if (active.text.trim().length === 0 && !active.sawTool) {
19290
+ active.reject(new Error("Omp RPC settled without displayable output"));
19291
+ } else {
19292
+ active.resolve({ text: active.text, cancelled: false, agentInvoked: true });
19282
19293
  }
19283
- if (value.type === "prompt_result") {
19284
- if (value.id !== active.promptId || value.agentInvoked !== false)
19285
- return;
19286
- if (value.status === "completed" || value.status === "aborted") {
19287
- this.#settleLocalTurn(active, { cancelled: value.status === "aborted" });
19288
- } else if (value.status === "error" && isRecord8(value.error) && typeof value.error.message === "string") {
19289
- this.#settleLocalTurn(active, { cancelled: false, error: value.error.message });
19290
- } else {
19291
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid local prompt result");
19292
- }
19293
- return;
19294
+ }
19295
+ #startAssistantMessage(active, value) {
19296
+ if (active.assistantMessageId !== null && active.reasoningMessageOpen) {
19297
+ active.onEvent({ type: "reasoning.completed", messageId: active.assistantMessageId });
19294
19298
  }
19295
- if (value.type === "extension_ui_request") {
19296
- this.#startInteraction(active, value);
19299
+ const messageId = assistantMessageId(value) ?? randomUUID();
19300
+ active.assistantMessageId = messageId;
19301
+ active.sawStreamedMessageText = false;
19302
+ active.sawStreamedMessageReasoning = false;
19303
+ active.reasoningMessageOpen = false;
19304
+ return messageId;
19305
+ }
19306
+ #ensureAssistantMessage(active, value) {
19307
+ return active.assistantMessageId ?? this.#startAssistantMessage(active, value);
19308
+ }
19309
+ #finalizeAssistantMessage(active, value) {
19310
+ const finalText = assistantText(value);
19311
+ const finalReasoning = assistantReasoning(value);
19312
+ const failure = assistantFailure(value);
19313
+ const cacheHitRatePercent = optionalOmpCacheHitRatePercent(value);
19314
+ if (finalText === null || finalReasoning === null || failure === void 0)
19297
19315
  return;
19298
- }
19299
- if (value.type === "message_start" && assistantText(value.message) !== null) {
19300
- this.#startAssistantMessage(active, value.message);
19316
+ if (active.assistantMessageId === null && finalText === active.lastFinalizedMessageText && finalReasoning === active.lastFinalizedMessageReasoning && !active.sawStreamedMessageText && !active.sawStreamedMessageReasoning) {
19301
19317
  return;
19302
19318
  }
19303
- if (value.type === "message_update" && isRecord8(value.assistantMessageEvent)) {
19304
- const event = value.assistantMessageEvent;
19305
- const eventType = String(event.type ?? "");
19306
- const isThinking = eventType === "thinking_delta" || eventType === "reasoning_delta" || eventType === "thought_delta" || eventType === "thinking" || eventType === "reasoning";
19307
- const isText = eventType === "text_delta" || eventType === "text" || eventType === "content_block_delta";
19308
- const delta = typeof event.delta === "string" ? event.delta : typeof event.thinking === "string" ? event.thinking : typeof event.reasoning === "string" ? event.reasoning : typeof event.text === "string" ? event.text : isRecord8(event.delta) && typeof event.delta.thinking === "string" ? event.delta.thinking : isRecord8(event.delta) && typeof event.delta.text === "string" ? event.delta.text : null;
19309
- if (isThinking && delta !== null && delta.length > 0) {
19310
- const messageId = this.#ensureAssistantMessage(active, value.message);
19311
- active.reasoningMessageOpen = true;
19312
- active.sawStreamedMessageReasoning = true;
19313
- active.onEvent({ type: "reasoning.delta", messageId, delta });
19314
- } else if (isText && delta !== null && delta.length > 0) {
19315
- const messageId = this.#ensureAssistantMessage(active, value.message);
19316
- active.text += delta;
19317
- active.sawStreamedMessageText = true;
19318
- active.onEvent({ type: "text.delta", messageId, delta });
19319
- } else if (event.type === "error") {
19320
- this.#ensureAssistantMessage(active, value.message);
19321
- active.failure = assistantFailure(event.error) ?? assistantFailure(value.message) ?? new Error("Omp assistant message failed");
19322
- }
19323
- return;
19319
+ active.failure = failure;
19320
+ this.#latestCacheHitRatePercent = cacheHitRatePercent;
19321
+ const messageId = this.#ensureAssistantMessage(active, value);
19322
+ if (!active.sawStreamedMessageReasoning && finalReasoning.length > 0) {
19323
+ active.reasoningMessageOpen = true;
19324
+ active.onEvent({ type: "reasoning.delta", messageId, delta: finalReasoning });
19324
19325
  }
19325
- if (value.type === "message_end") {
19326
- this.#finalizeAssistantMessage(active, value.message);
19327
- return;
19326
+ if (active.reasoningMessageOpen && active.failure === null) {
19327
+ active.onEvent({ type: "reasoning.completed", messageId });
19328
19328
  }
19329
- if (value.type === "turn_end") {
19330
- this.#finalizeAssistantMessage(active, value.message);
19331
- return;
19329
+ if (!active.sawStreamedMessageText && finalText.length > 0) {
19330
+ active.text += finalText;
19331
+ active.onEvent({ type: "text.delta", messageId, delta: finalText });
19332
19332
  }
19333
- if (value.type === "tool_execution_start") {
19334
- this.#startTool(active, value);
19335
- return;
19333
+ active.assistantMessageId = null;
19334
+ active.sawStreamedMessageText = false;
19335
+ active.sawStreamedMessageReasoning = false;
19336
+ active.reasoningMessageOpen = false;
19337
+ active.lastFinalizedMessageText = finalText;
19338
+ active.lastFinalizedMessageReasoning = finalReasoning;
19339
+ active.onEvent({ type: "message.completed", messageId });
19340
+ }
19341
+ #write(value) {
19342
+ const child = this.#child;
19343
+ if (!child?.stdin.writable || this.#closed || this.#failed) {
19344
+ return Promise.reject(new Error("Omp RPC stdin is unavailable"));
19336
19345
  }
19337
- if (value.type === "tool_execution_update") {
19338
- this.#updateTool(active, value);
19339
- return;
19346
+ return new Promise((resolve, reject) => {
19347
+ const frame = Buffer.from(`${JSON.stringify(value)}
19348
+ `, "utf8");
19349
+ child.stdin.write(frame, (error51) => error51 ? reject(error51) : resolve());
19350
+ });
19351
+ }
19352
+ #send(type, payload, id = `codexhost-${randomUUID()}`) {
19353
+ const child = this.#child;
19354
+ if (!child?.stdin.writable || this.#closed || this.#failed) {
19355
+ return Promise.reject(new Error("Omp RPC stdin is unavailable"));
19340
19356
  }
19341
- if (value.type === "tool_execution_end") {
19342
- this.#completeTool(active, value);
19357
+ return new Promise((resolve, reject) => {
19358
+ const pending = {
19359
+ command: type,
19360
+ resolve,
19361
+ reject,
19362
+ timeout: null
19363
+ };
19364
+ this.#pending.set(id, pending);
19365
+ this.#armCommandTimeout(id, pending);
19366
+ const frame = Buffer.from(`${JSON.stringify({ id, type, ...payload })}
19367
+ `, "utf8");
19368
+ child.stdin.write(frame, (error51) => {
19369
+ if (error51) {
19370
+ if (pending.timeout)
19371
+ clearTimeout(pending.timeout);
19372
+ this.#pending.delete(id);
19373
+ reject(error51);
19374
+ }
19375
+ });
19376
+ });
19377
+ }
19378
+ #armCommandTimeout(id, pending) {
19379
+ if (pending.timeout || this.#pending.get(id) !== pending || (pending.command === "prompt" || pending.command === "compact") && this.#compactionActive) {
19343
19380
  return;
19344
19381
  }
19345
- if (value.type === "agent_end" && Array.isArray(value.messages)) {
19346
- for (let index = value.messages.length - 1; index >= 0; index -= 1) {
19347
- const message3 = value.messages[index];
19348
- if (!isRecord8(message3) || message3.role !== "assistant")
19349
- continue;
19350
- this.#finalizeAssistantMessage(active, message3);
19351
- break;
19352
- }
19353
- }
19354
- if (value.type === "agent_end" && value.isTerminal !== false) {
19355
- active.terminalEnd = true;
19356
- if (active.cancellation !== "none") {
19357
- if (active.cancellation === "accepted")
19358
- void this.#confirmCancelledTurn(active);
19382
+ pending.timeout = setTimeout(() => {
19383
+ if (this.#pending.get(id) !== pending)
19359
19384
  return;
19360
- }
19361
- if (active.settlement !== "pending")
19385
+ pending.timeout = null;
19386
+ const error51 = new Error(`Omp RPC '${pending.command}' command timed out`);
19387
+ if (pending.command !== "prompt") {
19388
+ this.#pending.delete(id);
19389
+ pending.reject(error51);
19362
19390
  return;
19363
- active.settlement = "confirming";
19364
- void this.#confirmSettledTurn(active);
19365
- }
19366
- }
19367
- /** Every finished assistant message is one model request, with or without an active Turn. */
19368
- #observeUsage(value) {
19369
- if (value.type === "message_start") {
19370
- this.#usageRequestStartedAtMs = null;
19371
- return;
19372
- }
19373
- if (value.type === "message_update") {
19374
- const event = value.assistantMessageEvent;
19375
- if (this.#usageRequestStartedAtMs === null && isRecord8(event) && typeof event.type === "string" && /^(text|thinking|reasoning|thought|toolcall)_(start|delta)$/u.test(event.type)) {
19376
- this.#usageRequestStartedAtMs = Date.now();
19377
19391
  }
19392
+ const fault = new OmpRpcFaultError("protocolError", error51.message);
19393
+ void this.#terminateTimedOutPrompt(fault);
19394
+ }, this.#options.commandTimeoutMs);
19395
+ }
19396
+ async #terminateTimedOutPrompt(fault) {
19397
+ if (this.#closed || this.#failed)
19378
19398
  return;
19399
+ this.#failed = true;
19400
+ this.#closed = true;
19401
+ for (const pending of this.#pending.values()) {
19402
+ if (pending.timeout)
19403
+ clearTimeout(pending.timeout);
19404
+ pending.timeout = null;
19379
19405
  }
19380
- if (value.type === "message_end" && isRecord8(value.message)) {
19381
- if (value.message.role !== "assistant")
19382
- return;
19383
- const startedAtMs = this.#usageRequestStartedAtMs;
19384
- this.#usageRequestStartedAtMs = null;
19385
- this.#options.onUsage?.({
19386
- message: value.message,
19387
- startedAtMs,
19388
- completedAtMs: Date.now()
19389
- });
19406
+ let finalFault = fault;
19407
+ try {
19408
+ await this.close();
19409
+ } catch (error51) {
19410
+ finalFault = new OmpRpcFaultError("processExited", `Omp RPC timed-out Prompt cleanup failed: ${message2(error51)}`);
19390
19411
  }
19412
+ this.#rejectAll(finalFault);
19413
+ this.#options.onFault?.(finalFault);
19391
19414
  }
19392
- #handleSubagentFrame(active, value) {
19393
- if (value.type !== "subagent_lifecycle" && value.type !== "subagent_progress" && value.type !== "subagent_event") {
19394
- return false;
19395
- }
19396
- const payload = isRecord8(value.payload) ? value.payload : null;
19397
- const progressPayload = value.type === "subagent_progress" && payload && isRecord8(payload.progress) ? payload.progress : null;
19398
- const nativeIdValue = progressPayload?.id ?? payload?.id;
19399
- if (!payload || !nonBlankString(nativeIdValue)) {
19400
- throw new OmpRpcFaultError("protocolError", "Omp RPC Subagent frame has no stable ID");
19415
+ #closeInteractions(active, reason) {
19416
+ for (const [requestId, pending] of active.interactions) {
19417
+ active.interactions.delete(requestId);
19418
+ if (pending.timeout)
19419
+ clearTimeout(pending.timeout);
19420
+ active.onEvent({ type: "interaction.closed", requestId, reason });
19401
19421
  }
19402
- const nativeSubagentId = nativeIdValue;
19403
- const callId = nativeSubagentId;
19404
- const emit = active?.onEvent ?? this.#options.onSubagentEvent;
19405
- if (value.type === "subagent_event") {
19406
- emit?.({ type: "subagent.transcript.changed", callId, nativeSubagentId });
19407
- return true;
19422
+ }
19423
+ #rejectActiveTurn(error51) {
19424
+ const active = this.#activeTurn;
19425
+ if (!active)
19426
+ return;
19427
+ if (active.cancellationTimeout)
19428
+ clearTimeout(active.cancellationTimeout);
19429
+ if (active.cancellationRecheck)
19430
+ clearTimeout(active.cancellationRecheck);
19431
+ this.#closeInteractions(active, "cancelled");
19432
+ this.#activeTurn = null;
19433
+ active.reject(error51);
19434
+ }
19435
+ #rejectAll(error51) {
19436
+ if (this.#compactionTimeout)
19437
+ clearTimeout(this.#compactionTimeout);
19438
+ this.#compactionTimeout = null;
19439
+ for (const pending of this.#pending.values()) {
19440
+ if (pending.timeout)
19441
+ clearTimeout(pending.timeout);
19442
+ pending.reject(error51);
19408
19443
  }
19409
- if (value.type === "subagent_lifecycle") {
19410
- const status2 = payload.status;
19411
- if (status2 === "started") {
19412
- const description = nonBlankString(payload.description) ? payload.description : nonBlankString(payload.agent) ? `${payload.agent} delegation` : "Subagent delegation";
19413
- emit?.({
19414
- type: "subagent.started",
19415
- callId,
19416
- nativeSubagentId,
19417
- description,
19418
- ...nonBlankString(payload.agent) ? { role: payload.agent } : {},
19419
- ...nonBlankString(payload.task) ? { prompt: payload.task } : {},
19420
- background: payload.detached === true,
19421
- ...typeof payload.sessionFile === "string" ? { sessionFile: payload.sessionFile } : {}
19422
- });
19423
- return true;
19424
- }
19425
- if (status2 !== "completed" && status2 !== "failed" && status2 !== "aborted") {
19426
- throw new OmpRpcFaultError("protocolError", "Omp RPC Subagent lifecycle status is invalid");
19444
+ this.#pending.clear();
19445
+ const manual = this.#manualCompaction;
19446
+ this.#manualCompaction = null;
19447
+ manual?.reject(error51);
19448
+ this.#rejectActiveTurn(error51);
19449
+ }
19450
+ #fail(error51) {
19451
+ if (this.#closed || this.#failed)
19452
+ return;
19453
+ this.#failed = true;
19454
+ this.#startupFaultResolve?.(error51);
19455
+ this.#startupFaultResolve = null;
19456
+ this.#rejectAll(error51);
19457
+ this.#options.onFault?.(error51);
19458
+ }
19459
+ };
19460
+
19461
+ // dist/omp-model-list.js
19462
+ var OMP_MODEL_LIST_TIMEOUT_MS = 15e3;
19463
+ var OMP_MODEL_LIST_OUTPUT_LIMIT = 4 * 1024 * 1024;
19464
+ function listOmpModels(input) {
19465
+ const environment = withNodeRuntimeOnPath({
19466
+ ...process.env,
19467
+ ...input.environment,
19468
+ OMP_SKIP_VERSION_CHECK: "1",
19469
+ OMP_TELEMETRY: "0"
19470
+ });
19471
+ const executable = resolveOmpExecutable({
19472
+ ...input.command ? { command: input.command } : {},
19473
+ environment
19474
+ });
19475
+ const invocation = commandInvocation(executable, ["models", "--json"], environment);
19476
+ return new Promise((resolve) => {
19477
+ if (input.signal?.aborted)
19478
+ return resolve({ kind: "unanswered" });
19479
+ const child = spawn2(invocation.command, invocation.arguments, {
19480
+ cwd: input.cwd,
19481
+ env: environment,
19482
+ // A process group lets a stop reach OMP and its descendants, not only a launcher shim.
19483
+ detached: process.platform !== "win32",
19484
+ stdio: ["ignore", "pipe", "ignore"],
19485
+ windowsHide: true,
19486
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments
19487
+ });
19488
+ let settled = false;
19489
+ let stdout = "";
19490
+ const finish = (result, stop = false) => {
19491
+ if (settled)
19492
+ return;
19493
+ settled = true;
19494
+ clearTimeout(timer);
19495
+ input.signal?.removeEventListener("abort", onAbort);
19496
+ child.stdout.removeAllListeners("data");
19497
+ if (stop) {
19498
+ child.stdout.destroy();
19499
+ try {
19500
+ signalProcessTree(child, "SIGKILL");
19501
+ } catch {
19502
+ }
19427
19503
  }
19428
- emit?.({
19429
- type: "subagent.completed",
19430
- callId,
19431
- nativeSubagentId,
19432
- isError: status2 !== "completed",
19433
- ...nonBlankString(payload.resultSummary) ? { resultSummary: payload.resultSummary } : {},
19434
- ...typeof payload.sessionFile === "string" ? { sessionFile: payload.sessionFile } : {}
19435
- });
19436
- return true;
19437
- }
19438
- const progress = progressPayload;
19439
- if (!progress || !nonBlankString(progress.id) || progress.id !== nativeSubagentId) {
19440
- throw new OmpRpcFaultError("protocolError", "Omp RPC Subagent progress is invalid");
19441
- }
19442
- const status = subagentStatus(progress.status);
19443
- const recentOutput = Array.isArray(progress.recentOutput) ? progress.recentOutput.filter((item) => typeof item === "string") : [];
19444
- const resultSummary = recentOutput.at(-1);
19445
- emit?.({
19446
- type: "subagent.updated",
19447
- callId,
19448
- nativeSubagentId,
19449
- status,
19450
- ...nonBlankString(progress.description) ? { description: progress.description } : nonBlankString(payload.task) ? { description: payload.task } : {},
19451
- ...resultSummary !== void 0 ? { resultSummary } : {},
19452
- ...typeof payload.sessionFile === "string" ? { sessionFile: payload.sessionFile } : {}
19504
+ resolve(result);
19505
+ };
19506
+ const onAbort = () => finish({ kind: "unanswered" }, true);
19507
+ input.signal?.addEventListener("abort", onAbort, { once: true });
19508
+ const timer = setTimeout(() => finish({ kind: "timedOut" }, true), input.timeoutMs ?? OMP_MODEL_LIST_TIMEOUT_MS);
19509
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
19510
+ stdout += chunk;
19511
+ if (stdout.length > OMP_MODEL_LIST_OUTPUT_LIMIT)
19512
+ finish({ kind: "unanswered" }, true);
19453
19513
  });
19454
- return true;
19514
+ child.once("error", (error51) => {
19515
+ finish(error51.code === "ENOENT" ? { kind: "notInstalled", message: "Oh My Pi (omp) is not installed" } : { kind: "unanswered" });
19516
+ });
19517
+ child.once("close", (code) => {
19518
+ if (code !== 0)
19519
+ return finish({ kind: "unanswered" });
19520
+ const models = parseOmpModelList(stdout);
19521
+ finish(models ? { kind: "models", models } : { kind: "unanswered" });
19522
+ });
19523
+ });
19524
+ }
19525
+ function parseOmpModelList(output) {
19526
+ let parsed;
19527
+ try {
19528
+ parsed = JSON.parse(output);
19529
+ } catch {
19530
+ return null;
19455
19531
  }
19456
- #isBlockingInteraction(value) {
19457
- return ["select", "confirm", "input", "editor"].includes(String(value.method));
19532
+ if (!isRecord9(parsed) || !Array.isArray(parsed.models))
19533
+ return null;
19534
+ const models = [];
19535
+ for (const model2 of parsed.models) {
19536
+ if (!isRecord9(model2) || !nonBlankString2(model2.provider) || !nonBlankString2(model2.id) || typeof model2.reasoning !== "boolean") {
19537
+ return null;
19538
+ }
19539
+ models.push({ provider: model2.provider, id: model2.id, reasoning: model2.reasoning });
19458
19540
  }
19459
- #startInteraction(active, value) {
19460
- if (!this.#isBlockingInteraction(value))
19461
- return;
19462
- const requestId = value.id;
19463
- const method = value.method;
19464
- const title = value.title;
19465
- const timeoutMs = value.timeout;
19466
- if (typeof requestId !== "string" || requestId.length === 0 || typeof method !== "string" || typeof title !== "string" || title.length === 0 || timeoutMs !== void 0 && (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs < 0) || active.interactions.has(requestId)) {
19467
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Interaction request");
19541
+ return models;
19542
+ }
19543
+ function isRecord9(value) {
19544
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19545
+ }
19546
+ function nonBlankString2(value) {
19547
+ return typeof value === "string" && value.trim().length > 0;
19548
+ }
19549
+
19550
+ // ../../../node_modules/diff/libesm/diff/base.js
19551
+ var Diff = class {
19552
+ diff(oldStr, newStr, options = {}) {
19553
+ let callback;
19554
+ if (typeof options === "function") {
19555
+ callback = options;
19556
+ options = {};
19557
+ } else if ("callback" in options) {
19558
+ callback = options.callback;
19468
19559
  }
19469
- let request;
19470
- if (method === "select") {
19471
- if (!Array.isArray(value.options) || value.options.length === 0 || !value.options.every((option) => typeof option === "string" && option.length > 0)) {
19472
- throw new OmpRpcFaultError("protocolError", "Omp RPC select request has invalid options");
19560
+ const oldString = this.castInput(oldStr, options);
19561
+ const newString = this.castInput(newStr, options);
19562
+ const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
19563
+ const newTokens = this.removeEmpty(this.tokenize(newString, options));
19564
+ return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
19565
+ }
19566
+ diffWithOptionsObj(oldTokens, newTokens, options, callback) {
19567
+ var _a3;
19568
+ const done = (value) => {
19569
+ value = this.postProcess(value, options);
19570
+ if (callback) {
19571
+ setTimeout(function() {
19572
+ callback(value);
19573
+ }, 0);
19574
+ return void 0;
19575
+ } else {
19576
+ return value;
19473
19577
  }
19474
- let optionDetails;
19475
- if (value.optionDetails !== void 0) {
19476
- if (!Array.isArray(value.optionDetails) || value.optionDetails.length !== value.options.length || !value.optionDetails.every((detail) => typeof detail === "object" && detail !== null && !Array.isArray(detail) && (detail.description === void 0 || typeof detail.description === "string"))) {
19477
- throw new OmpRpcFaultError("protocolError", "Omp RPC select option details are invalid");
19578
+ };
19579
+ const newLen = newTokens.length, oldLen = oldTokens.length;
19580
+ let editLength = 1;
19581
+ let maxEditLength = newLen + oldLen;
19582
+ if (options.maxEditLength != null) {
19583
+ maxEditLength = Math.min(maxEditLength, options.maxEditLength);
19584
+ }
19585
+ const maxExecutionTime = (_a3 = options.timeout) !== null && _a3 !== void 0 ? _a3 : Infinity;
19586
+ const abortAfterTimestamp = Date.now() + maxExecutionTime;
19587
+ const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
19588
+ let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
19589
+ if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
19590
+ return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
19591
+ }
19592
+ let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
19593
+ const execEditLength = () => {
19594
+ for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
19595
+ let basePath;
19596
+ const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
19597
+ if (removePath) {
19598
+ bestPath[diagonalPath - 1] = void 0;
19599
+ }
19600
+ let canAdd = false;
19601
+ if (addPath) {
19602
+ const addPathNewPos = addPath.oldPos - diagonalPath;
19603
+ canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
19604
+ }
19605
+ const canRemove = removePath && removePath.oldPos + 1 < oldLen;
19606
+ if (!canAdd && !canRemove) {
19607
+ bestPath[diagonalPath] = void 0;
19608
+ continue;
19609
+ }
19610
+ if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
19611
+ basePath = this.addToPath(addPath, true, false, 0, options);
19612
+ } else {
19613
+ basePath = this.addToPath(removePath, false, true, 1, options);
19614
+ }
19615
+ newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
19616
+ if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
19617
+ return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
19618
+ } else {
19619
+ bestPath[diagonalPath] = basePath;
19620
+ if (basePath.oldPos + 1 >= oldLen) {
19621
+ maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
19622
+ }
19623
+ if (newPos + 1 >= newLen) {
19624
+ minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
19625
+ }
19478
19626
  }
19479
- optionDetails = value.optionDetails.map(({ description }) => description === void 0 ? {} : { description });
19480
- }
19481
- request = {
19482
- requestId,
19483
- method,
19484
- title,
19485
- options: [...value.options],
19486
- ...optionDetails ? { optionDetails } : {},
19487
- ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19488
- };
19489
- } else if (method === "confirm") {
19490
- if (typeof value.message !== "string") {
19491
- throw new OmpRpcFaultError("protocolError", "Omp RPC confirm request has no message");
19492
19627
  }
19493
- request = {
19494
- requestId,
19495
- method,
19496
- title,
19497
- message: value.message,
19498
- ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19499
- };
19500
- } else if (method === "input") {
19501
- if (value.placeholder !== void 0 && typeof value.placeholder !== "string") {
19502
- throw new OmpRpcFaultError("protocolError", "Omp RPC input placeholder is invalid");
19628
+ editLength++;
19629
+ };
19630
+ if (callback) {
19631
+ (function exec() {
19632
+ setTimeout(function() {
19633
+ if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
19634
+ return callback(void 0);
19635
+ }
19636
+ if (!execEditLength()) {
19637
+ exec();
19638
+ }
19639
+ }, 0);
19640
+ })();
19641
+ } else {
19642
+ while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
19643
+ const ret = execEditLength();
19644
+ if (ret) {
19645
+ return ret;
19646
+ }
19503
19647
  }
19504
- request = {
19505
- requestId,
19506
- method,
19507
- title,
19508
- ...typeof value.placeholder === "string" ? { placeholder: value.placeholder } : {},
19509
- ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19648
+ }
19649
+ }
19650
+ addToPath(path9, added, removed, oldPosInc, options) {
19651
+ const last = path9.lastComponent;
19652
+ if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
19653
+ return {
19654
+ oldPos: path9.oldPos + oldPosInc,
19655
+ lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
19510
19656
  };
19511
19657
  } else {
19512
- if (value.prefill !== void 0 && typeof value.prefill !== "string") {
19513
- throw new OmpRpcFaultError("protocolError", "Omp RPC editor prefill is invalid");
19514
- }
19515
- request = {
19516
- requestId,
19517
- method: "editor",
19518
- title,
19519
- ...typeof value.prefill === "string" ? { prefill: value.prefill } : {},
19520
- ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19658
+ return {
19659
+ oldPos: path9.oldPos + oldPosInc,
19660
+ lastComponent: { count: 1, added, removed, previousComponent: last }
19521
19661
  };
19522
19662
  }
19523
- const pending = { request, timeout: null };
19524
- if (request.timeoutMs !== void 0) {
19525
- pending.timeout = setTimeout(() => {
19526
- if (this.#activeTurn !== active || !active.interactions.has(requestId))
19527
- return;
19528
- void this.#resolveInteraction({ requestId, cancelled: true }, "expired").catch((error51) => {
19529
- if (this.#closed || this.#failed)
19530
- return;
19531
- this.#fail(new OmpRpcFaultError("protocolError", `Omp RPC Interaction timeout handling failed: ${message2(error51)}`));
19532
- });
19533
- }, request.timeoutMs);
19663
+ }
19664
+ extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
19665
+ const newLen = newTokens.length, oldLen = oldTokens.length;
19666
+ let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
19667
+ while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
19668
+ newPos++;
19669
+ oldPos++;
19670
+ commonCount++;
19671
+ if (options.oneChangePerToken) {
19672
+ basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
19673
+ }
19534
19674
  }
19535
- active.interactions.set(requestId, pending);
19536
- active.onEvent({ type: "interaction.requested", request });
19675
+ if (commonCount && !options.oneChangePerToken) {
19676
+ basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
19677
+ }
19678
+ basePath.oldPos = oldPos;
19679
+ return newPos;
19537
19680
  }
19538
- #handleResponse(value) {
19539
- const id = value.id;
19540
- if (typeof id !== "string") {
19541
- this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC response has no id"));
19542
- return;
19681
+ equals(left, right, options) {
19682
+ if (options.comparator) {
19683
+ return options.comparator(left, right);
19684
+ } else {
19685
+ return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
19543
19686
  }
19544
- const pending = this.#pending.get(id);
19545
- const active = this.#activeTurn;
19546
- if (!pending) {
19547
- if (active?.promptId === id && value.command === "prompt" && value.success === false) {
19548
- active.failure = new Error(typeof value.error === "string" ? value.error : "Omp RPC command failed");
19549
- return;
19687
+ }
19688
+ removeEmpty(array2) {
19689
+ const ret = [];
19690
+ for (let i = 0; i < array2.length; i++) {
19691
+ if (array2[i]) {
19692
+ ret.push(array2[i]);
19550
19693
  }
19551
- this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC response id is not pending"));
19552
- return;
19553
19694
  }
19554
- if (pending.timeout)
19555
- clearTimeout(pending.timeout);
19556
- this.#pending.delete(id);
19557
- if (value.success === true) {
19558
- if (pending.command === "prompt" && active?.promptId === id && isRecord8(value.data) && value.data.agentInvoked === false) {
19559
- this.#settleLocalTurn(active, { cancelled: false });
19560
- }
19561
- pending.resolve(value);
19562
- } else {
19563
- const error51 = typeof value.error === "string" ? value.error : "Omp RPC command failed";
19564
- if (value.command === pending.command && error51 === `Unknown command: ${pending.command}`) {
19565
- pending.reject(new OmpRpcUnsupportedCommandError(pending.command));
19695
+ return ret;
19696
+ }
19697
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
19698
+ castInput(value, options) {
19699
+ return value;
19700
+ }
19701
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
19702
+ tokenize(value, options) {
19703
+ return Array.from(value);
19704
+ }
19705
+ join(chars) {
19706
+ return chars.join("");
19707
+ }
19708
+ postProcess(changeObjects, options) {
19709
+ return changeObjects;
19710
+ }
19711
+ get useLongestToken() {
19712
+ return false;
19713
+ }
19714
+ buildValues(lastComponent, newTokens, oldTokens) {
19715
+ const components = [];
19716
+ let nextComponent;
19717
+ while (lastComponent) {
19718
+ components.push(lastComponent);
19719
+ nextComponent = lastComponent.previousComponent;
19720
+ delete lastComponent.previousComponent;
19721
+ lastComponent = nextComponent;
19722
+ }
19723
+ components.reverse();
19724
+ const componentLen = components.length;
19725
+ let componentPos = 0, newPos = 0, oldPos = 0;
19726
+ for (; componentPos < componentLen; componentPos++) {
19727
+ const component = components[componentPos];
19728
+ if (!component.removed) {
19729
+ if (!component.added && this.useLongestToken) {
19730
+ let value = newTokens.slice(newPos, newPos + component.count);
19731
+ value = value.map(function(value2, i) {
19732
+ const oldValue = oldTokens[oldPos + i];
19733
+ return oldValue.length > value2.length ? oldValue : value2;
19734
+ });
19735
+ component.value = this.join(value);
19736
+ } else {
19737
+ component.value = this.join(newTokens.slice(newPos, newPos + component.count));
19738
+ }
19739
+ newPos += component.count;
19740
+ if (!component.added) {
19741
+ oldPos += component.count;
19742
+ }
19566
19743
  } else {
19567
- pending.reject(new Error(error51));
19744
+ component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
19745
+ oldPos += component.count;
19568
19746
  }
19569
19747
  }
19748
+ return components;
19570
19749
  }
19571
- #startTool(active, value) {
19572
- const callId = value.toolCallId;
19573
- const toolName = value.toolName;
19574
- const argumentsResult = jsonValueSchema.safeParse(value.args);
19575
- if (typeof callId !== "string" || callId.length === 0 || typeof toolName !== "string" || toolName.length === 0 || !argumentsResult.success || active.tools.has(callId)) {
19576
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool start");
19577
- }
19578
- active.sawTool = true;
19579
- active.tools.set(callId, toolName);
19580
- active.onEvent({
19581
- type: "tool.started",
19582
- callId,
19583
- toolName,
19584
- arguments: argumentsResult.data
19585
- });
19750
+ };
19751
+
19752
+ // ../../../node_modules/diff/libesm/diff/line.js
19753
+ var LineDiff = class extends Diff {
19754
+ constructor() {
19755
+ super(...arguments);
19756
+ this.tokenize = tokenize;
19586
19757
  }
19587
- #updateTool(active, value) {
19588
- const callId = value.toolCallId;
19589
- if (typeof callId !== "string" || callId.length === 0) {
19590
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool update");
19591
- }
19592
- if (!active.tools.has(callId))
19593
- return;
19594
- const outputResult = jsonValueSchema.safeParse(value.partialResult ?? null);
19595
- if (!outputResult.success) {
19596
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool update");
19758
+ equals(left, right, options) {
19759
+ if (options.ignoreWhitespace) {
19760
+ if (!options.newlineIsToken || !left.includes("\n")) {
19761
+ left = left.trim();
19762
+ }
19763
+ if (!options.newlineIsToken || !right.includes("\n")) {
19764
+ right = right.trim();
19765
+ }
19766
+ } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
19767
+ if (left.endsWith("\n")) {
19768
+ left = left.slice(0, -1);
19769
+ }
19770
+ if (right.endsWith("\n")) {
19771
+ right = right.slice(0, -1);
19772
+ }
19597
19773
  }
19598
- active.onEvent({ type: "tool.updated", callId, output: outputResult.data });
19774
+ return super.equals(left, right, options);
19599
19775
  }
19600
- #completeTool(active, value) {
19601
- const callId = value.toolCallId;
19602
- const toolName = value.toolName;
19603
- if (typeof callId !== "string" || callId.length === 0) {
19604
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool end");
19605
- }
19606
- const expectedName = active.tools.get(callId);
19607
- if (expectedName === void 0)
19608
- return;
19609
- const result = jsonValueSchema.safeParse(value.result);
19610
- if (typeof toolName !== "string" || expectedName !== toolName || value.isError !== void 0 && typeof value.isError !== "boolean" || !result.success) {
19611
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool end");
19776
+ };
19777
+ var lineDiff = new LineDiff();
19778
+ function diffLines(oldStr, newStr, options) {
19779
+ return lineDiff.diff(oldStr, newStr, options);
19780
+ }
19781
+ function tokenize(value, options) {
19782
+ if (options.stripTrailingCr) {
19783
+ value = value.replace(/\r\n/g, "\n");
19784
+ }
19785
+ const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
19786
+ if (!linesAndNewlines[linesAndNewlines.length - 1]) {
19787
+ linesAndNewlines.pop();
19788
+ }
19789
+ for (let i = 0; i < linesAndNewlines.length; i++) {
19790
+ const line = linesAndNewlines[i];
19791
+ if (i % 2 && !options.newlineIsToken) {
19792
+ retLines[retLines.length - 1] += line;
19793
+ } else {
19794
+ retLines.push(line);
19612
19795
  }
19613
- active.tools.delete(callId);
19614
- active.onEvent({
19615
- type: "tool.completed",
19616
- callId,
19617
- toolName,
19618
- result: result.data,
19619
- isError: value.isError === true
19620
- });
19621
19796
  }
19622
- async #confirmCancelledTurn(active) {
19623
- if (this.#activeTurn !== active || active.cancellation !== "accepted" || active.settlement === "confirming" || active.cancellationChecking)
19624
- return;
19625
- active.cancellationChecking = true;
19626
- if (active.cancellationRecheck)
19627
- clearTimeout(active.cancellationRecheck);
19628
- active.cancellationRecheck = null;
19629
- try {
19630
- let response = await this.#send("get_state", {});
19631
- if (this.#activeTurn !== active)
19632
- return;
19633
- if (parseSessionStreaming(response)) {
19634
- await this.#send("abort", {});
19635
- if (this.#activeTurn !== active)
19636
- return;
19637
- response = await this.#send("get_state", {});
19797
+ return retLines;
19798
+ }
19799
+
19800
+ // ../../../node_modules/diff/libesm/patch/parse.js
19801
+ function parsePatch(uniDiff) {
19802
+ const diffstr = uniDiff.split(/\n/), list = [];
19803
+ let i = 0;
19804
+ function parseIndex() {
19805
+ const index = {};
19806
+ list.push(index);
19807
+ while (i < diffstr.length) {
19808
+ const line = diffstr[i];
19809
+ if (/^(---|\+\+\+|@@)\s/.test(line)) {
19810
+ break;
19638
19811
  }
19639
- let state = parseSessionState(response);
19640
- if (this.#activeTurn !== active || active.cancellation !== "accepted")
19641
- return;
19642
- const data = sessionStateData(response);
19643
- if (!active.cancellationReloaded && state.sessionFile && state.sessionId === this.state.sessionId && state.sessionFile === this.state.sessionFile && data.isStreaming === false && data.isCompacting === false && data.queuedMessageCount === 0 && data.hasPendingAsyncWork === true && active.tools.size === 0) {
19644
- await this.verifySessionCwd(this.#options.cwd);
19645
- if (this.#activeTurn !== active)
19646
- return;
19647
- active.cancellationReloaded = true;
19648
- const reset = await this.#send("new_session", {});
19649
- if (this.#activeTurn !== active)
19650
- return;
19651
- if (!isRecord8(reset.data) || reset.data.cancelled !== false) {
19652
- throw new OmpRpcFaultError("unavailable", "Omp cancelled Session reset was refused");
19653
- }
19654
- const reloaded = await this.#send("switch_session", { sessionPath: state.sessionFile });
19655
- if (this.#activeTurn !== active)
19656
- return;
19657
- if (!isRecord8(reloaded.data) || reloaded.data.cancelled !== false) {
19658
- throw new OmpRpcFaultError("unavailable", "Omp cancelled Session reload was refused");
19659
- }
19660
- const previous = state;
19661
- response = await this.#send("get_state", {});
19662
- state = parseSessionState(response);
19663
- if (state.sessionId !== previous.sessionId || state.sessionFile !== previous.sessionFile) {
19664
- throw new OmpRpcFaultError("protocolError", "Omp cancelled Session reload changed its identity");
19665
- }
19666
- if (state.provider !== previous.provider || state.modelId !== previous.modelId) {
19667
- if (!previous.provider || !previous.modelId) {
19668
- throw new OmpRpcFaultError("protocolError", "Omp cancelled Session has no restorable Model");
19669
- }
19670
- await this.#send("set_model", { provider: previous.provider, modelId: previous.modelId });
19671
- }
19672
- if (previous.thinkingLevel && state.thinkingLevel !== previous.thinkingLevel) {
19673
- await this.#send("set_thinking_level", { level: previous.thinkingLevel });
19674
- }
19675
- response = await this.#send("get_state", {});
19676
- state = parseSessionState(response);
19677
- if (state.sessionId !== previous.sessionId || state.sessionFile !== previous.sessionFile || state.provider !== previous.provider || state.modelId !== previous.modelId || previous.thinkingLevel !== null && state.thinkingLevel !== previous.thinkingLevel) {
19678
- throw new OmpRpcFaultError("protocolError", "Omp cancelled Session reload changed its identity or configuration");
19679
- }
19812
+ const header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
19813
+ if (header) {
19814
+ index.index = header[1];
19680
19815
  }
19681
- if (!cancellationSettled(response, active.terminalEnd)) {
19682
- active.settlement = "pending";
19683
- active.cancellationRecheck = setTimeout(() => {
19684
- active.cancellationRecheck = null;
19685
- void this.#confirmCancelledTurn(active);
19686
- }, 250);
19687
- return;
19816
+ i++;
19817
+ }
19818
+ parseFileHeader(index);
19819
+ parseFileHeader(index);
19820
+ index.hunks = [];
19821
+ while (i < diffstr.length) {
19822
+ const line = diffstr[i];
19823
+ if (/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/.test(line)) {
19824
+ break;
19825
+ } else if (/^@@/.test(line)) {
19826
+ index.hunks.push(parseHunk());
19827
+ } else if (line) {
19828
+ throw new Error("Unknown line " + (i + 1) + " " + JSON.stringify(line));
19829
+ } else {
19830
+ i++;
19688
19831
  }
19689
- this.#state = state;
19690
- active.settlement = "confirmed";
19691
- this.#finishSettledTurn(active);
19692
- } catch (error51) {
19693
- if (this.#activeTurn !== active)
19694
- return;
19695
- const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC cancelled Turn state could not be confirmed: ${message2(error51)}`);
19696
- this.#terminateFailedCancellation(active, fault);
19697
- } finally {
19698
- active.cancellationChecking = false;
19699
19832
  }
19700
19833
  }
19701
- #settleLocalTurn(active, result) {
19702
- if (this.#activeTurn !== active || active.settlement !== "pending")
19703
- return;
19704
- active.localResult = result;
19705
- active.settlement = "confirming";
19706
- void this.#confirmSettledTurn(active);
19707
- }
19708
- async #confirmSettledTurn(active) {
19709
- try {
19710
- const response = await this.#send("get_state", {});
19711
- const state = parseSessionState(response);
19712
- if (this.#activeTurn !== active)
19713
- return;
19714
- if (active.cancellation !== "none") {
19715
- active.settlement = "pending";
19716
- if (active.cancellation === "accepted")
19717
- void this.#confirmCancelledTurn(active);
19718
- return;
19834
+ function parseFileHeader(index) {
19835
+ const fileHeader = /^(---|\+\+\+)\s+(.*)\r?$/.exec(diffstr[i]);
19836
+ if (fileHeader) {
19837
+ const data = fileHeader[2].split(" ", 2), header = (data[1] || "").trim();
19838
+ let fileName = data[0].replace(/\\\\/g, "\\");
19839
+ if (/^".*"$/.test(fileName)) {
19840
+ fileName = fileName.substr(1, fileName.length - 2);
19719
19841
  }
19720
- if (parseSessionStreaming(response)) {
19721
- throw new OmpRpcFaultError("protocolError", "Omp RPC completed Turn state is still Streaming");
19842
+ if (fileHeader[1] === "---") {
19843
+ index.oldFileName = fileName;
19844
+ index.oldHeader = header;
19845
+ } else {
19846
+ index.newFileName = fileName;
19847
+ index.newHeader = header;
19848
+ }
19849
+ i++;
19850
+ }
19851
+ }
19852
+ function parseHunk() {
19853
+ var _a3;
19854
+ const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
19855
+ const hunk = {
19856
+ oldStart: +chunkHeader[1],
19857
+ oldLines: typeof chunkHeader[2] === "undefined" ? 1 : +chunkHeader[2],
19858
+ newStart: +chunkHeader[3],
19859
+ newLines: typeof chunkHeader[4] === "undefined" ? 1 : +chunkHeader[4],
19860
+ lines: []
19861
+ };
19862
+ if (hunk.oldLines === 0) {
19863
+ hunk.oldStart += 1;
19864
+ }
19865
+ if (hunk.newLines === 0) {
19866
+ hunk.newStart += 1;
19867
+ }
19868
+ let addCount = 0, removeCount = 0;
19869
+ for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a3 = diffstr[i]) === null || _a3 === void 0 ? void 0 : _a3.startsWith("\\"))); i++) {
19870
+ const operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? " " : diffstr[i][0];
19871
+ if (operation === "+" || operation === "-" || operation === " " || operation === "\\") {
19872
+ hunk.lines.push(diffstr[i]);
19873
+ if (operation === "+") {
19874
+ addCount++;
19875
+ } else if (operation === "-") {
19876
+ removeCount++;
19877
+ } else if (operation === " ") {
19878
+ addCount++;
19879
+ removeCount++;
19880
+ }
19881
+ } else {
19882
+ throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`);
19722
19883
  }
19723
- this.#state = state;
19724
- active.settlement = "confirmed";
19725
- this.#finishSettledTurn(active);
19726
- } catch (error51) {
19727
- if (this.#activeTurn !== active)
19728
- return;
19729
- const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC stable Turn state could not be confirmed: ${message2(error51)}`);
19730
- this.#fail(fault);
19731
19884
  }
19732
- }
19733
- #finishSettledTurn(active) {
19734
- if (this.#activeTurn !== active || active.settlement !== "confirmed" || active.cancellation === "requesting") {
19735
- return;
19885
+ if (!addCount && hunk.newLines === 1) {
19886
+ hunk.newLines = 0;
19736
19887
  }
19737
- if (active.cancellationTimeout)
19738
- clearTimeout(active.cancellationTimeout);
19739
- active.cancellationTimeout = null;
19740
- if (active.cancellationRecheck)
19741
- clearTimeout(active.cancellationRecheck);
19742
- active.cancellationRecheck = null;
19743
- this.#closeInteractions(active, active.cancellation === "accepted" ? "cancelled" : "superseded");
19744
- if (active.tools.size > 0) {
19745
- this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC settled with active Tool executions"));
19746
- return;
19888
+ if (!removeCount && hunk.oldLines === 1) {
19889
+ hunk.oldLines = 0;
19747
19890
  }
19748
- this.#activeTurn = null;
19749
- if (active.localResult) {
19750
- active.resolve({
19751
- text: active.text,
19752
- agentInvoked: false,
19753
- ...active.localResult,
19754
- cancelled: active.localResult.cancelled || active.cancellation === "accepted"
19755
- });
19756
- } else if (active.cancellation === "accepted") {
19757
- active.resolve({ text: active.text, cancelled: true, agentInvoked: true });
19758
- } else if (active.failure) {
19759
- active.reject(active.failure);
19760
- } else if (active.text.trim().length === 0 && !active.sawTool) {
19761
- active.reject(new Error("Omp RPC settled without displayable output"));
19762
- } else {
19763
- active.resolve({ text: active.text, cancelled: false, agentInvoked: true });
19891
+ if (addCount !== hunk.newLines) {
19892
+ throw new Error("Added line count did not match for hunk at line " + (chunkHeaderIndex + 1));
19764
19893
  }
19765
- }
19766
- #startAssistantMessage(active, value) {
19767
- if (active.assistantMessageId !== null && active.reasoningMessageOpen) {
19768
- active.onEvent({ type: "reasoning.completed", messageId: active.assistantMessageId });
19894
+ if (removeCount !== hunk.oldLines) {
19895
+ throw new Error("Removed line count did not match for hunk at line " + (chunkHeaderIndex + 1));
19769
19896
  }
19770
- const messageId = assistantMessageId(value) ?? randomUUID();
19771
- active.assistantMessageId = messageId;
19772
- active.sawStreamedMessageText = false;
19773
- active.sawStreamedMessageReasoning = false;
19774
- active.reasoningMessageOpen = false;
19775
- return messageId;
19897
+ return hunk;
19776
19898
  }
19777
- #ensureAssistantMessage(active, value) {
19778
- return active.assistantMessageId ?? this.#startAssistantMessage(active, value);
19899
+ while (i < diffstr.length) {
19900
+ parseIndex();
19779
19901
  }
19780
- #finalizeAssistantMessage(active, value) {
19781
- const finalText = assistantText(value);
19782
- const finalReasoning = assistantReasoning(value);
19783
- const failure = assistantFailure(value);
19784
- const cacheHitRatePercent = optionalOmpCacheHitRatePercent(value);
19785
- if (finalText === null || finalReasoning === null || failure === void 0)
19786
- return;
19787
- if (active.assistantMessageId === null && finalText === active.lastFinalizedMessageText && finalReasoning === active.lastFinalizedMessageReasoning && !active.sawStreamedMessageText && !active.sawStreamedMessageReasoning) {
19902
+ return list;
19903
+ }
19904
+
19905
+ // ../../../node_modules/diff/libesm/patch/create.js
19906
+ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
19907
+ let optionsObj;
19908
+ if (!options) {
19909
+ optionsObj = {};
19910
+ } else if (typeof options === "function") {
19911
+ optionsObj = { callback: options };
19912
+ } else {
19913
+ optionsObj = options;
19914
+ }
19915
+ if (typeof optionsObj.context === "undefined") {
19916
+ optionsObj.context = 4;
19917
+ }
19918
+ const context = optionsObj.context;
19919
+ if (optionsObj.newlineIsToken) {
19920
+ throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");
19921
+ }
19922
+ if (!optionsObj.callback) {
19923
+ return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj));
19924
+ } else {
19925
+ const { callback } = optionsObj;
19926
+ diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => {
19927
+ const patch = diffLinesResultToPatch(diff);
19928
+ callback(patch);
19929
+ } }));
19930
+ }
19931
+ function diffLinesResultToPatch(diff) {
19932
+ if (!diff) {
19788
19933
  return;
19789
19934
  }
19790
- active.failure = failure;
19791
- this.#latestCacheHitRatePercent = cacheHitRatePercent;
19792
- const messageId = this.#ensureAssistantMessage(active, value);
19793
- if (!active.sawStreamedMessageReasoning && finalReasoning.length > 0) {
19794
- active.reasoningMessageOpen = true;
19795
- active.onEvent({ type: "reasoning.delta", messageId, delta: finalReasoning });
19935
+ diff.push({ value: "", lines: [] });
19936
+ function contextLines(lines) {
19937
+ return lines.map(function(entry) {
19938
+ return " " + entry;
19939
+ });
19796
19940
  }
19797
- if (active.reasoningMessageOpen && active.failure === null) {
19798
- active.onEvent({ type: "reasoning.completed", messageId });
19941
+ const hunks = [];
19942
+ let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
19943
+ for (let i = 0; i < diff.length; i++) {
19944
+ const current = diff[i], lines = current.lines || splitLines(current.value);
19945
+ current.lines = lines;
19946
+ if (current.added || current.removed) {
19947
+ if (!oldRangeStart) {
19948
+ const prev = diff[i - 1];
19949
+ oldRangeStart = oldLine;
19950
+ newRangeStart = newLine;
19951
+ if (prev) {
19952
+ curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : [];
19953
+ oldRangeStart -= curRange.length;
19954
+ newRangeStart -= curRange.length;
19955
+ }
19956
+ }
19957
+ for (const line of lines) {
19958
+ curRange.push((current.added ? "+" : "-") + line);
19959
+ }
19960
+ if (current.added) {
19961
+ newLine += lines.length;
19962
+ } else {
19963
+ oldLine += lines.length;
19964
+ }
19965
+ } else {
19966
+ if (oldRangeStart) {
19967
+ if (lines.length <= context * 2 && i < diff.length - 2) {
19968
+ for (const line of contextLines(lines)) {
19969
+ curRange.push(line);
19970
+ }
19971
+ } else {
19972
+ const contextSize = Math.min(lines.length, context);
19973
+ for (const line of contextLines(lines.slice(0, contextSize))) {
19974
+ curRange.push(line);
19975
+ }
19976
+ const hunk = {
19977
+ oldStart: oldRangeStart,
19978
+ oldLines: oldLine - oldRangeStart + contextSize,
19979
+ newStart: newRangeStart,
19980
+ newLines: newLine - newRangeStart + contextSize,
19981
+ lines: curRange
19982
+ };
19983
+ hunks.push(hunk);
19984
+ oldRangeStart = 0;
19985
+ newRangeStart = 0;
19986
+ curRange = [];
19987
+ }
19988
+ }
19989
+ oldLine += lines.length;
19990
+ newLine += lines.length;
19991
+ }
19799
19992
  }
19800
- if (!active.sawStreamedMessageText && finalText.length > 0) {
19801
- active.text += finalText;
19802
- active.onEvent({ type: "text.delta", messageId, delta: finalText });
19993
+ for (const hunk of hunks) {
19994
+ for (let i = 0; i < hunk.lines.length; i++) {
19995
+ if (hunk.lines[i].endsWith("\n")) {
19996
+ hunk.lines[i] = hunk.lines[i].slice(0, -1);
19997
+ } else {
19998
+ hunk.lines.splice(i + 1, 0, "\");
19999
+ i++;
20000
+ }
20001
+ }
19803
20002
  }
19804
- active.assistantMessageId = null;
19805
- active.sawStreamedMessageText = false;
19806
- active.sawStreamedMessageReasoning = false;
19807
- active.reasoningMessageOpen = false;
19808
- active.lastFinalizedMessageText = finalText;
19809
- active.lastFinalizedMessageReasoning = finalReasoning;
19810
- active.onEvent({ type: "message.completed", messageId });
20003
+ return {
20004
+ oldFileName,
20005
+ newFileName,
20006
+ oldHeader,
20007
+ newHeader,
20008
+ hunks
20009
+ };
19811
20010
  }
19812
- #write(value) {
19813
- const child = this.#child;
19814
- if (!child?.stdin.writable || this.#closed || this.#failed) {
19815
- return Promise.reject(new Error("Omp RPC stdin is unavailable"));
19816
- }
19817
- return new Promise((resolve, reject) => {
19818
- const frame = Buffer.from(`${JSON.stringify(value)}
19819
- `, "utf8");
19820
- child.stdin.write(frame, (error51) => error51 ? reject(error51) : resolve());
19821
- });
20011
+ }
20012
+ function formatPatch(patch) {
20013
+ if (Array.isArray(patch)) {
20014
+ return patch.map(formatPatch).join("\n");
19822
20015
  }
19823
- #send(type, payload, id = `codexhost-${randomUUID()}`) {
19824
- const child = this.#child;
19825
- if (!child?.stdin.writable || this.#closed || this.#failed) {
19826
- return Promise.reject(new Error("Omp RPC stdin is unavailable"));
20016
+ const ret = [];
20017
+ if (patch.oldFileName == patch.newFileName) {
20018
+ ret.push("Index: " + patch.oldFileName);
20019
+ }
20020
+ ret.push("===================================================================");
20021
+ ret.push("--- " + patch.oldFileName + (typeof patch.oldHeader === "undefined" ? "" : " " + patch.oldHeader));
20022
+ ret.push("+++ " + patch.newFileName + (typeof patch.newHeader === "undefined" ? "" : " " + patch.newHeader));
20023
+ for (let i = 0; i < patch.hunks.length; i++) {
20024
+ const hunk = patch.hunks[i];
20025
+ if (hunk.oldLines === 0) {
20026
+ hunk.oldStart -= 1;
20027
+ }
20028
+ if (hunk.newLines === 0) {
20029
+ hunk.newStart -= 1;
20030
+ }
20031
+ ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@");
20032
+ for (const line of hunk.lines) {
20033
+ ret.push(line);
19827
20034
  }
19828
- return new Promise((resolve, reject) => {
19829
- const pending = {
19830
- command: type,
19831
- resolve,
19832
- reject,
19833
- timeout: null
19834
- };
19835
- this.#pending.set(id, pending);
19836
- this.#armCommandTimeout(id, pending);
19837
- const frame = Buffer.from(`${JSON.stringify({ id, type, ...payload })}
19838
- `, "utf8");
19839
- child.stdin.write(frame, (error51) => {
19840
- if (error51) {
19841
- if (pending.timeout)
19842
- clearTimeout(pending.timeout);
19843
- this.#pending.delete(id);
19844
- reject(error51);
19845
- }
19846
- });
19847
- });
19848
20035
  }
19849
- #armCommandTimeout(id, pending) {
19850
- if (pending.timeout || this.#pending.get(id) !== pending || (pending.command === "prompt" || pending.command === "compact") && this.#compactionActive) {
20036
+ return ret.join("\n") + "\n";
20037
+ }
20038
+ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
20039
+ if (typeof options === "function") {
20040
+ options = { callback: options };
20041
+ }
20042
+ if (!(options === null || options === void 0 ? void 0 : options.callback)) {
20043
+ const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
20044
+ if (!patchObj) {
19851
20045
  return;
19852
20046
  }
19853
- pending.timeout = setTimeout(() => {
19854
- if (this.#pending.get(id) !== pending)
19855
- return;
19856
- pending.timeout = null;
19857
- const error51 = new Error(`Omp RPC '${pending.command}' command timed out`);
19858
- if (pending.command !== "prompt") {
19859
- this.#pending.delete(id);
19860
- pending.reject(error51);
19861
- return;
20047
+ return formatPatch(patchObj);
20048
+ } else {
20049
+ const { callback } = options;
20050
+ structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: (patchObj) => {
20051
+ if (!patchObj) {
20052
+ callback(void 0);
20053
+ } else {
20054
+ callback(formatPatch(patchObj));
19862
20055
  }
19863
- const fault = new OmpRpcFaultError("protocolError", error51.message);
19864
- void this.#terminateTimedOutPrompt(fault);
19865
- }, this.#options.commandTimeoutMs);
20056
+ } }));
19866
20057
  }
19867
- async #terminateTimedOutPrompt(fault) {
19868
- if (this.#closed || this.#failed)
19869
- return;
19870
- this.#failed = true;
19871
- this.#closed = true;
19872
- for (const pending of this.#pending.values()) {
19873
- if (pending.timeout)
19874
- clearTimeout(pending.timeout);
19875
- pending.timeout = null;
19876
- }
19877
- let finalFault = fault;
19878
- try {
19879
- await this.close();
19880
- } catch (error51) {
19881
- finalFault = new OmpRpcFaultError("processExited", `Omp RPC timed-out Prompt cleanup failed: ${message2(error51)}`);
19882
- }
19883
- this.#rejectAll(finalFault);
19884
- this.#options.onFault?.(finalFault);
20058
+ }
20059
+ function splitLines(text) {
20060
+ const hasTrailingNl = text.endsWith("\n");
20061
+ const result = text.split("\n").map((line) => line + "\n");
20062
+ if (hasTrailingNl) {
20063
+ result.pop();
20064
+ } else {
20065
+ result.push(result.pop().slice(0, -1));
19885
20066
  }
19886
- #closeInteractions(active, reason) {
19887
- for (const [requestId, pending] of active.interactions) {
19888
- active.interactions.delete(requestId);
19889
- if (pending.timeout)
19890
- clearTimeout(pending.timeout);
19891
- active.onEvent({ type: "interaction.closed", requestId, reason });
19892
- }
20067
+ return result;
20068
+ }
20069
+
20070
+ // dist/omp-adapter.js
20071
+ import { randomUUID as randomUUID2 } from "node:crypto";
20072
+ import { realpath as realpath3, stat as stat2 } from "node:fs/promises";
20073
+ import path7 from "node:path";
20074
+
20075
+ // dist/omp-last-turn-rollback.js
20076
+ function modelFromState(state) {
20077
+ if (state.provider === null && state.modelId === null)
20078
+ return null;
20079
+ if (state.provider === null || state.modelId === null) {
20080
+ throw new Error("Omp state contains a partial Model identity");
19893
20081
  }
19894
- #rejectActiveTurn(error51) {
19895
- const active = this.#activeTurn;
19896
- if (!active)
19897
- return;
19898
- if (active.cancellationTimeout)
19899
- clearTimeout(active.cancellationTimeout);
19900
- if (active.cancellationRecheck)
19901
- clearTimeout(active.cancellationRecheck);
19902
- this.#closeInteractions(active, "cancelled");
19903
- this.#activeTurn = null;
19904
- active.reject(error51);
20082
+ return { provider: state.provider, id: state.modelId };
20083
+ }
20084
+ async function rollbackOmpLastTurn(transport, sourceSessionId, cwd) {
20085
+ const startupState = transport.state;
20086
+ const startupSessionId = startupState.sessionId;
20087
+ const currentModel = modelFromState(startupState);
20088
+ const currentThinking = startupState.thinkingLevel;
20089
+ const copiedHistory = await transport.getEntries();
20090
+ const boundary = resolveOmpLastTurnBoundary(copiedHistory);
20091
+ if (!boundary)
20092
+ return { ok: false, reason: "empty" };
20093
+ const sourceSnapshot = mapOmpSnapshot(copiedHistory, {
20094
+ sessionId: startupSessionId,
20095
+ model: currentModel
20096
+ });
20097
+ let state = await transport.fork(boundary.lastUserEntryId);
20098
+ if (state.sessionId === sourceSessionId || state.sessionId === startupSessionId) {
20099
+ throw new Error("Omp last-Turn rollback did not create a distinct Native Session");
19905
20100
  }
19906
- #rejectAll(error51) {
19907
- if (this.#compactionTimeout)
19908
- clearTimeout(this.#compactionTimeout);
19909
- this.#compactionTimeout = null;
19910
- for (const pending of this.#pending.values()) {
19911
- if (pending.timeout)
19912
- clearTimeout(pending.timeout);
19913
- pending.reject(error51);
19914
- }
19915
- this.#pending.clear();
19916
- const manual = this.#manualCompaction;
19917
- this.#manualCompaction = null;
19918
- manual?.reject(error51);
19919
- this.#rejectActiveTurn(error51);
20101
+ if (!sameOmpModel(modelFromState(state), currentModel)) {
20102
+ if (!currentModel)
20103
+ throw new Error("Omp last-Turn rollback changed the current Model");
20104
+ state = await transport.selectModel(currentModel);
19920
20105
  }
19921
- #fail(error51) {
19922
- if (this.#closed || this.#failed)
19923
- return;
19924
- this.#failed = true;
19925
- this.#startupFaultResolve?.(error51);
19926
- this.#startupFaultResolve = null;
19927
- this.#rejectAll(error51);
19928
- this.#options.onFault?.(error51);
20106
+ if (state.thinkingLevel !== currentThinking) {
20107
+ if (!currentThinking)
20108
+ throw new Error("Omp last-Turn rollback changed current Thinking");
20109
+ state = await transport.selectThinkingOption(currentThinking);
19929
20110
  }
19930
- };
20111
+ if (!sameOmpModel(modelFromState(state), currentModel) || state.thinkingLevel !== currentThinking) {
20112
+ throw new Error("Omp last-Turn rollback could not restore current Model and Thinking");
20113
+ }
20114
+ const snapshot = mapOmpSnapshot(await transport.getEntries(), {
20115
+ sessionId: state.sessionId,
20116
+ model: modelFromState(state)
20117
+ });
20118
+ const expectedTurnKeys = sourceSnapshot.turns.slice(0, -1).map((turn) => turn.nativeTurnRef.nativeTurnKey);
20119
+ const actualTurnKeys = snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey);
20120
+ if (snapshot.turns.length !== boundary.sourceTurnCount - 1 || actualTurnKeys.some((key, index) => key !== expectedTurnKeys[index])) {
20121
+ throw new Error("Omp last-Turn rollback did not produce the exact retained history prefix");
20122
+ }
20123
+ await transport.verifySessionCwd(cwd);
20124
+ return { ok: true };
20125
+ }
19931
20126
 
19932
20127
  // dist/omp-permission-modes.js
19933
20128
  var nativePermissionModes = /* @__PURE__ */ new Set(["always-ask", "write", "yolo"]);
@@ -19937,16 +20132,25 @@ var OMP_PERMISSION_MODE_CATALOG = harnessPermissionModeCatalogSchema.parse({
19937
20132
  {
19938
20133
  id: "always-ask",
19939
20134
  label: "Always ask",
20135
+ localizations: {
20136
+ "zh-CN": { label: "始终询问", description: "自动允许读取;写入或执行操作前询问。" }
20137
+ },
19940
20138
  description: "Automatically allow reads and ask before write or execution actions."
19941
20139
  },
19942
20140
  {
19943
20141
  id: "write",
19944
20142
  label: "Write",
20143
+ localizations: {
20144
+ "zh-CN": { label: "写入", description: "自动允许读取和写入;执行操作前询问。" }
20145
+ },
19945
20146
  description: "Automatically allow reads and writes; ask before execution actions."
19946
20147
  },
19947
20148
  {
19948
20149
  id: "yolo",
19949
20150
  label: "Full access",
20151
+ localizations: {
20152
+ "zh-CN": { label: "完全访问", description: "无需批准提示即可运行所有工具操作。" }
20153
+ },
19950
20154
  description: "Run all tool actions without approval prompts.",
19951
20155
  dangerous: true
19952
20156
  }
@@ -20071,12 +20275,31 @@ var OmpSubagentLifecycle = class {
20071
20275
  };
20072
20276
 
20073
20277
  // dist/omp-adapter.js
20278
+ function closedInspection() {
20279
+ return {
20280
+ status: "unavailable",
20281
+ error: { code: "invalidState", message: "Omp Adapter is closed", retryable: false }
20282
+ };
20283
+ }
20284
+ function ompInspectionCapabilities(selectThinkingOption) {
20285
+ return {
20286
+ configuration: {
20287
+ selectModel: true,
20288
+ selectThinkingOption,
20289
+ selectPermissionMode: true,
20290
+ permissionModeScope: "live"
20291
+ },
20292
+ history: { fork: true, forkAcrossCwd: true, rollbackLastTurn: true },
20293
+ subagents: { observe: true, readTranscript: true }
20294
+ };
20295
+ }
20074
20296
  var ompHarnessId2 = harnessIdSchema.parse("omp");
20075
20297
  var ompCommandCatalog = harnessCommandCatalogSchema.parse({
20076
20298
  commands: [
20077
20299
  {
20078
20300
  id: "omp.compact",
20079
20301
  invocation: "/compact",
20302
+ localizations: { "zh-CN": { label: "压缩上下文", description: "压缩当前对话上下文" } },
20080
20303
  label: "Compact context",
20081
20304
  description: "Compact the current conversation context",
20082
20305
  argumentMode: "text"
@@ -20084,7 +20307,7 @@ var ompCommandCatalog = harnessCommandCatalogSchema.parse({
20084
20307
  ]
20085
20308
  });
20086
20309
  var DEFAULT_TOOL_OUTPUT_LIMIT = 64e3;
20087
- function isRecord9(value) {
20310
+ function isRecord10(value) {
20088
20311
  return typeof value === "object" && value !== null && !Array.isArray(value);
20089
20312
  }
20090
20313
  function errorMessage(error51) {
@@ -20099,7 +20322,7 @@ var OmpAdapterFaultError = class extends Error {
20099
20322
  }
20100
20323
  };
20101
20324
  function normalizedError(error51, fallbackCode) {
20102
- if (isRecord9(error51) && error51.code === "ENOENT") {
20325
+ if (isRecord10(error51) && error51.code === "ENOENT") {
20103
20326
  return { code: "notInstalled", message: errorMessage(error51), retryable: false };
20104
20327
  }
20105
20328
  if (error51 instanceof OmpAdapterFaultError)
@@ -20176,7 +20399,7 @@ function nativeModelForHistory(state) {
20176
20399
  return nativeModelFromState(state);
20177
20400
  }
20178
20401
  function sessionFileFromRef(ref) {
20179
- if (ref.harnessId !== ompHarnessId2 || !isRecord9(ref.locator) || typeof ref.locator.sessionFile !== "string" || ref.locator.sessionFile.length === 0) {
20402
+ if (ref.harnessId !== ompHarnessId2 || !isRecord10(ref.locator) || typeof ref.locator.sessionFile !== "string" || ref.locator.sessionFile.length === 0) {
20180
20403
  throw new Error("Omp Native Session Ref has no resumable Session file");
20181
20404
  }
20182
20405
  return ref.locator.sessionFile;
@@ -20231,9 +20454,9 @@ function toolFailure(toolName) {
20231
20454
  function nativeText(value) {
20232
20455
  if (typeof value === "string")
20233
20456
  return value;
20234
- if (!isRecord9(value) || !Array.isArray(value.content))
20457
+ if (!isRecord10(value) || !Array.isArray(value.content))
20235
20458
  return "";
20236
- return value.content.filter((content) => isRecord9(content) && content.type === "text" && typeof content.text === "string").map(({ text }) => text).join("");
20459
+ return value.content.filter((content) => isRecord10(content) && content.type === "text" && typeof content.text === "string").map(({ text }) => text).join("");
20237
20460
  }
20238
20461
  function boundedOutput(value, limit) {
20239
20462
  const text = nativeText(value);
@@ -20249,17 +20472,17 @@ function outputText(output) {
20249
20472
  return output?.content.filter((content) => content.type === "text").map(({ text }) => text).join("") ?? "";
20250
20473
  }
20251
20474
  function stringField2(value, key) {
20252
- if (!isRecord9(value))
20475
+ if (!isRecord10(value))
20253
20476
  return void 0;
20254
20477
  const field = value[key];
20255
20478
  if (typeof field === "string" && field.length > 0)
20256
20479
  return field;
20257
- if (isRecord9(value.input)) {
20480
+ if (isRecord10(value.input)) {
20258
20481
  const nested = value.input[key];
20259
20482
  if (typeof nested === "string" && nested.length > 0)
20260
20483
  return nested;
20261
20484
  }
20262
- if (isRecord9(value.arguments)) {
20485
+ if (isRecord10(value.arguments)) {
20263
20486
  const nested = value.arguments[key];
20264
20487
  if (typeof nested === "string" && nested.length > 0)
20265
20488
  return nested;
@@ -20267,7 +20490,7 @@ function stringField2(value, key) {
20267
20490
  return void 0;
20268
20491
  }
20269
20492
  function numberField(value, key) {
20270
- if (!isRecord9(value))
20493
+ if (!isRecord10(value))
20271
20494
  return void 0;
20272
20495
  const field = value[key];
20273
20496
  return typeof field === "number" || field === null ? field : void 0;
@@ -20306,7 +20529,7 @@ function fileMutatingKind(toolName) {
20306
20529
  return null;
20307
20530
  }
20308
20531
  function nestedToolString(value, keys) {
20309
- if (!isRecord9(value))
20532
+ if (!isRecord10(value))
20310
20533
  return void 0;
20311
20534
  for (const key of keys) {
20312
20535
  const field = value[key];
@@ -20321,14 +20544,14 @@ function nestedToolString(value, keys) {
20321
20544
  return void 0;
20322
20545
  }
20323
20546
  function patchFromResult(result) {
20324
- if (!isRecord9(result))
20547
+ if (!isRecord10(result))
20325
20548
  return void 0;
20326
20549
  for (const key of ["patch", "diff", "unifiedDiff"]) {
20327
20550
  const field = result[key];
20328
20551
  if (typeof field === "string" && field.length > 0)
20329
20552
  return field;
20330
20553
  }
20331
- if (isRecord9(result.details)) {
20554
+ if (isRecord10(result.details)) {
20332
20555
  for (const key of ["patch", "diff", "unifiedDiff"]) {
20333
20556
  const field = result.details[key];
20334
20557
  if (typeof field === "string" && field.length > 0)
@@ -20455,9 +20678,6 @@ var OmpHarnessSession = class {
20455
20678
  #usage;
20456
20679
  #usageGeneration = 0;
20457
20680
  #usageRefreshSequence = 0;
20458
- #backgroundTurnId = null;
20459
- #backgroundSubagents = /* @__PURE__ */ new Map();
20460
- #backgroundTurnFailed = false;
20461
20681
  constructor(cwd, createTransport, onClosed, options) {
20462
20682
  this.#cwd = cwd;
20463
20683
  this.#createTransport = createTransport;
@@ -20515,44 +20735,6 @@ var OmpHarnessSession = class {
20515
20735
  #backgroundStatus(status) {
20516
20736
  return status === "pending" || status === "running" ? "running" : status === "interrupted" ? "interrupted" : status;
20517
20737
  }
20518
- #ensureBackgroundTurn() {
20519
- if (this.#backgroundTurnId)
20520
- return this.#backgroundTurnId;
20521
- const turnId = hostTurnIdSchema.parse(randomUUID2());
20522
- this.#backgroundTurnId = turnId;
20523
- this.#backgroundTurnFailed = false;
20524
- this.#event({
20525
- type: "turn.autonomous.started",
20526
- turnId,
20527
- input: []
20528
- });
20529
- return turnId;
20530
- }
20531
- #backgroundDelegationStart(event) {
20532
- const turnId = this.#ensureBackgroundTurn();
20533
- const description = event.type === "subagent.started" ? event.description : event.type === "subagent.updated" ? event.description ?? "Background subagent" : "Background subagent";
20534
- const role = event.type === "subagent.started" ? event.role : void 0;
20535
- const background = event.type === "subagent.started" ? event.background : true;
20536
- const state = {
20537
- subagentId: event.nativeSubagentId,
20538
- nativeSubagentId: event.nativeSubagentId,
20539
- description,
20540
- ...role ? { role } : {},
20541
- background,
20542
- status: "running"
20543
- };
20544
- const item = {
20545
- type: "subagentDelegation",
20546
- itemId: this.#newItemId(),
20547
- operation: "spawn",
20548
- ...event.type === "subagent.started" && event.prompt ? { prompt: event.prompt } : {},
20549
- subagents: [state]
20550
- };
20551
- const delegation = { item, turnId };
20552
- this.#backgroundSubagents.set(event.callId, delegation);
20553
- this.#event({ type: "item.started", turnId, item });
20554
- return delegation;
20555
- }
20556
20738
  #handleBackgroundSubagentEvent(event) {
20557
20739
  if (event.type === "subagent.transcript.changed") {
20558
20740
  this.#event({
@@ -20564,12 +20746,6 @@ var OmpHarnessSession = class {
20564
20746
  if (event.type !== "subagent.started" && event.type !== "subagent.updated" && event.type !== "subagent.completed") {
20565
20747
  return;
20566
20748
  }
20567
- let delegation = this.#backgroundSubagents.get(event.callId);
20568
- if (!delegation)
20569
- delegation = this.#backgroundDelegationStart(event);
20570
- const current = delegation.item.subagents[0];
20571
- if (!current)
20572
- throw new Error("Omp background delegation has no Agent state");
20573
20749
  if (event.type === "subagent.started") {
20574
20750
  this.#event({
20575
20751
  type: "subagent.state.changed",
@@ -20580,19 +20756,6 @@ var OmpHarnessSession = class {
20580
20756
  }
20581
20757
  if (event.type === "subagent.updated") {
20582
20758
  const status2 = this.#backgroundStatus(event.status);
20583
- const subagent2 = {
20584
- ...current,
20585
- status: status2,
20586
- ...event.description ? { description: event.description } : {},
20587
- ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
20588
- };
20589
- delegation.item = { ...delegation.item, subagents: [subagent2] };
20590
- this.#event({
20591
- type: "item.updated",
20592
- turnId: delegation.turnId,
20593
- itemId: delegation.item.itemId,
20594
- update: { type: "subagents.replace", subagents: delegation.item.subagents }
20595
- });
20596
20759
  this.#event({
20597
20760
  type: "subagent.state.changed",
20598
20761
  nativeSubagentId: event.nativeSubagentId,
@@ -20602,58 +20765,12 @@ var OmpHarnessSession = class {
20602
20765
  return;
20603
20766
  }
20604
20767
  const status = event.isError ? "failed" : "completed";
20605
- const subagent = {
20606
- ...current,
20607
- status,
20608
- ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
20609
- };
20610
- delegation.item = { ...delegation.item, subagents: [subagent] };
20611
- this.#event({
20612
- type: "item.updated",
20613
- turnId: delegation.turnId,
20614
- itemId: delegation.item.itemId,
20615
- update: { type: "subagents.replace", subagents: delegation.item.subagents }
20616
- });
20617
- this.#event({
20618
- type: "item.completed",
20619
- turnId: delegation.turnId,
20620
- snapshot: {
20621
- item: delegation.item,
20622
- outcome: event.isError ? {
20623
- status: "failed",
20624
- error: {
20625
- code: "nativeFailure",
20626
- message: "Omp background Subagent failed",
20627
- retryable: false
20628
- }
20629
- } : { status: "succeeded" }
20630
- }
20631
- });
20632
20768
  this.#event({
20633
20769
  type: "subagent.state.changed",
20634
20770
  nativeSubagentId: event.nativeSubagentId,
20635
20771
  status,
20636
20772
  ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
20637
20773
  });
20638
- this.#backgroundTurnFailed ||= event.isError;
20639
- this.#backgroundSubagents.delete(event.callId);
20640
- if (this.#backgroundSubagents.size === 0 && this.#backgroundTurnId === delegation.turnId) {
20641
- const turnId = this.#backgroundTurnId;
20642
- this.#backgroundTurnId = null;
20643
- this.#event({
20644
- type: "turn.completed",
20645
- turnId,
20646
- outcome: this.#backgroundTurnFailed ? {
20647
- status: "failed",
20648
- error: {
20649
- code: "nativeFailure",
20650
- message: "Omp background Subagent failed",
20651
- retryable: false
20652
- }
20653
- } : { status: "succeeded" }
20654
- });
20655
- this.#backgroundTurnFailed = false;
20656
- }
20657
20774
  }
20658
20775
  async readSnapshot() {
20659
20776
  if (this.#phase !== "open" && this.#phase !== "faulted") {
@@ -20708,6 +20825,8 @@ var OmpHarnessSession = class {
20708
20825
  }
20709
20826
  if (command.type === "turn.cancel")
20710
20827
  return this.#cancel(command);
20828
+ if (command.type === "turn.steer")
20829
+ return unsupportedSteer("OMP");
20711
20830
  if (command.type === "interaction.respond")
20712
20831
  return this.#respond(command);
20713
20832
  if (command.type === "model.select")
@@ -21903,6 +22022,9 @@ var OmpAdapter = class {
21903
22022
  #inspectionCache = /* @__PURE__ */ new Map();
21904
22023
  #inspectionInFlight = /* @__PURE__ */ new Map();
21905
22024
  #inspections = /* @__PURE__ */ new Set();
22025
+ #availabilityInFlight = /* @__PURE__ */ new Map();
22026
+ #availabilityListings = /* @__PURE__ */ new Set();
22027
+ #listModels;
21906
22028
  #sessions = /* @__PURE__ */ new Set();
21907
22029
  #toolOutputLimit;
21908
22030
  #closePromise = null;
@@ -21911,22 +22033,21 @@ var OmpAdapter = class {
21911
22033
  createTransport: (sessionOptions) => new OmpRpcSession({ ...options, ...sessionOptions })
21912
22034
  }) {
21913
22035
  this.#createTransport = dependencies.createTransport;
22036
+ const listModels = dependencies.listModels ?? listOmpModels;
22037
+ this.#listModels = ({ cwd, signal }) => listModels({
22038
+ cwd,
22039
+ signal,
22040
+ ...options.command ? { command: options.command } : {},
22041
+ ...options.environment ? { environment: options.environment } : {}
22042
+ });
21914
22043
  this.sessionImport = new OmpSessionImport({ ...process.env, ...options.environment });
21915
22044
  this.usageStatistics = createOmpUsageStatistics({ ...process.env, ...options.environment });
21916
22045
  this.#closeTimeoutMs = options.closeTimeoutMs ?? 2e3;
21917
22046
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_TOOL_OUTPUT_LIMIT;
21918
22047
  }
21919
22048
  async inspect(input = {}) {
21920
- if (this.#closePromise) {
21921
- return {
21922
- status: "unavailable",
21923
- error: {
21924
- code: "invalidState",
21925
- message: "Omp Adapter is closed",
21926
- retryable: false
21927
- }
21928
- };
21929
- }
22049
+ if (this.#closePromise)
22050
+ return closedInspection();
21930
22051
  const cwd = input.cwd ?? process.cwd();
21931
22052
  const inFlight = this.#inspectionInFlight.get(cwd);
21932
22053
  if (inFlight)
@@ -21936,6 +22057,37 @@ var OmpAdapter = class {
21936
22057
  if (cached2)
21937
22058
  return cached2;
21938
22059
  }
22060
+ if (input.purpose === "availability")
22061
+ return this.#inspectAvailability(cwd, input.refresh);
22062
+ return this.#startFullInspection(cwd);
22063
+ }
22064
+ /**
22065
+ * Availability without a Session: a Session startup runs OMP's own startup work, including
22066
+ * Provider connection prewarm, for a Harness the user may never select. The listed result
22067
+ * carries no native default Model or Thinking option, so it is neither cached nor used to
22068
+ * update `#thinkingSelectionSupported`. When the list cannot answer, a full inspection answers
22069
+ * instead, reusing one that is in flight or finished meanwhile.
22070
+ */
22071
+ async #inspectAvailability(cwd, refresh = false) {
22072
+ if (refresh)
22073
+ this.#inspectionCache.delete(cwd);
22074
+ let pending = this.#availabilityInFlight.get(cwd);
22075
+ if (!pending) {
22076
+ const listing = this.#listAvailability(cwd);
22077
+ pending = listing.finally(() => {
22078
+ if (this.#availabilityInFlight.get(cwd) === pending)
22079
+ this.#availabilityInFlight.delete(cwd);
22080
+ });
22081
+ this.#availabilityInFlight.set(cwd, pending);
22082
+ }
22083
+ const listed = await pending;
22084
+ if (listed)
22085
+ return listed;
22086
+ if (this.#closePromise)
22087
+ return closedInspection();
22088
+ return this.#inspectionInFlight.get(cwd) ?? this.#inspectionCache.get(cwd) ?? this.#startFullInspection(cwd);
22089
+ }
22090
+ #startFullInspection(cwd) {
21939
22091
  const inspection = this.#inspectCwd(cwd).then((result) => {
21940
22092
  if (result.status === "ready")
21941
22093
  this.#inspectionCache.set(cwd, result);
@@ -21948,6 +22100,59 @@ var OmpAdapter = class {
21948
22100
  }
21949
22101
  });
21950
22102
  }
22103
+ /** Returns null when a Session must answer: this OMP cannot list Models, or lists none. */
22104
+ async #listAvailability(cwd) {
22105
+ const startedAt = Date.now();
22106
+ const stage = "model-list";
22107
+ const controller = new AbortController();
22108
+ this.#availabilityListings.add(controller);
22109
+ let listed;
22110
+ try {
22111
+ listed = await this.#listModels({ cwd, signal: controller.signal });
22112
+ } finally {
22113
+ this.#availabilityListings.delete(controller);
22114
+ }
22115
+ if (listed.kind === "unanswered")
22116
+ return null;
22117
+ if (listed.kind === "notInstalled") {
22118
+ return {
22119
+ status: "notInstalled",
22120
+ error: {
22121
+ code: "notInstalled",
22122
+ message: listed.message,
22123
+ retryable: false,
22124
+ stage,
22125
+ durationMs: Date.now() - startedAt
22126
+ }
22127
+ };
22128
+ }
22129
+ if (listed.kind === "timedOut") {
22130
+ return {
22131
+ status: "error",
22132
+ error: {
22133
+ code: "unavailable",
22134
+ message: "Oh My Pi did not list its models in time",
22135
+ retryable: true,
22136
+ stage,
22137
+ durationMs: Date.now() - startedAt
22138
+ }
22139
+ };
22140
+ }
22141
+ if (listed.models.length === 0)
22142
+ return null;
22143
+ let catalog;
22144
+ try {
22145
+ catalog = normalizeOmpModelCatalog(listed.models, null, null, null);
22146
+ } catch {
22147
+ return null;
22148
+ }
22149
+ return {
22150
+ status: "ready",
22151
+ catalog,
22152
+ permissionModes: OMP_PERMISSION_MODE_CATALOG,
22153
+ capabilities: ompInspectionCapabilities(false)
22154
+ };
22155
+ }
21951
22156
  async #inspectCwd(cwd) {
21952
22157
  const startedAt = Date.now();
21953
22158
  let stage = "spawn";
@@ -21971,16 +22176,7 @@ var OmpAdapter = class {
21971
22176
  status: "ready",
21972
22177
  catalog,
21973
22178
  permissionModes: OMP_PERMISSION_MODE_CATALOG,
21974
- capabilities: {
21975
- configuration: {
21976
- selectModel: true,
21977
- selectThinkingOption: thinkingLevels !== null,
21978
- selectPermissionMode: true,
21979
- permissionModeScope: "live"
21980
- },
21981
- history: { fork: true, forkAcrossCwd: true, rollbackLastTurn: true },
21982
- subagents: { observe: true, readTranscript: true }
21983
- }
22179
+ capabilities: ompInspectionCapabilities(thinkingLevels !== null)
21984
22180
  };
21985
22181
  } catch (error51) {
21986
22182
  await transport.close().catch(() => void 0);
@@ -22191,6 +22387,8 @@ var OmpAdapter = class {
22191
22387
  }
22192
22388
  close() {
22193
22389
  if (!this.#closePromise) {
22390
+ for (const listing of this.#availabilityListings)
22391
+ listing.abort();
22194
22392
  this.#closePromise = Promise.all([
22195
22393
  this.sessionImport.close(),
22196
22394
  ...[...this.#inspections].map((transport) => transport.close()),