@liberseek/boft-cli-linux-x64 0.8.3 → 0.8.5

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 +117 -13
  4. package/app/console-web.js +713 -129
  5. package/app/desktop-controller.mjs +713 -42
  6. package/app/host-runtime.mjs +2535 -855
  7. package/app/plugins/antigravity/plugin.mjs +437 -67
  8. package/app/plugins/claude-code/plugin.mjs +758 -248
  9. package/app/plugins/codebuddy/plugin.mjs +348 -156
  10. package/app/plugins/codex-usage/plugin.mjs +258 -106
  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 +34651 -0
  14. package/app/plugins/cursor-cli/plugin.mjs +20905 -44961
  15. package/app/plugins/deepseek-harness/plugin.mjs +195 -53
  16. package/app/plugins/enabled.json +1 -0
  17. package/app/plugins/grok/plugin.mjs +584 -138
  18. package/app/plugins/hermes/plugin.mjs +134 -13
  19. package/app/plugins/kimi-code/plugin.mjs +145 -26
  20. package/app/plugins/kiro-cli/plugin.mjs +145 -26
  21. package/app/plugins/muse/plugin.mjs +132 -14
  22. package/app/plugins/omp/plugin.mjs +2245 -2040
  23. package/app/plugins/opencode/plugin.mjs +196 -72
  24. package/app/plugins/pi/plugin.mjs +2643 -2309
  25. package/app/plugins/qoder/plugin.mjs +162 -40
  26. package/app/plugins/qoder-cn/plugin.mjs +162 -40
  27. package/app/plugins/workbuddy/plugin.mjs +609 -180
  28. package/app/plugins/zcode/plugin.mjs +192 -44
  29. package/app/renderer-extension.js +3405 -429
  30. package/bin/boft +0 -0
  31. package/libexec/boft-shim +0 -0
  32. package/libexec/boft-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;
@@ -3580,10 +3583,10 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
3580
3583
  const shape = def.shape;
3581
3584
  const propValues = {};
3582
3585
  for (const key in shape) {
3583
- const field = shape[key]._zod;
3584
- if (field.values) {
3586
+ const field2 = shape[key]._zod;
3587
+ if (field2.values) {
3585
3588
  propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
3586
- for (const v of field.values)
3589
+ for (const v of field2.values)
3587
3590
  propValues[key].add(v);
3588
3591
  }
3589
3592
  }
@@ -15202,10 +15205,19 @@ var model = external_exports.string().min(1).max(512);
15202
15205
  var project = external_exports.string().min(1).max(4096);
15203
15206
  var usageStatisticsParamsSchema = external_exports.strictObject({
15204
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(),
15205
15217
  harness: harness.optional(),
15206
15218
  model: model.nullable().optional(),
15207
15219
  project: project.nullable().optional(),
15208
- /** One local date inside the range. */
15220
+ /** One date in the query timezone inside the range. */
15209
15221
  date: localDate.optional()
15210
15222
  });
15211
15223
  var usageStatisticsTotalsSchema = external_exports.strictObject({
@@ -15214,6 +15226,8 @@ var usageStatisticsTotalsSchema = external_exports.strictObject({
15214
15226
  cachedInputTokens: count,
15215
15227
  cacheWriteInputTokens: count,
15216
15228
  cacheKnownInputTokens: count,
15229
+ cacheHitCachedInputTokens: count,
15230
+ cacheHitInputTokens: count,
15217
15231
  outputTokens: count,
15218
15232
  reasoningOutputTokens: count,
15219
15233
  /** USD at the public price, summed over the priced requests only. */
@@ -15241,7 +15255,7 @@ var usageStatisticsSessionSchema = external_exports.strictObject({
15241
15255
  });
15242
15256
  var usageStatisticsResultSchema = external_exports.strictObject({
15243
15257
  range: external_exports.enum(USAGE_STATISTICS_RANGES),
15244
- /** First local date of the range; null for all time. */
15258
+ /** First date in the query timezone (Host local when omitted); null for all time. */
15245
15259
  from: localDate.nullable(),
15246
15260
  to: localDate,
15247
15261
  /** The filters these figures apply, echoed so a late answer to older filters is recognised. */
@@ -15281,7 +15295,7 @@ var usageStatisticsResultSchema = external_exports.strictObject({
15281
15295
  totals: usageStatisticsTotalsSchema,
15282
15296
  /** Each date and Harness of the range: every filter except the day. */
15283
15297
  daily: external_exports.array(external_exports.strictObject({ date: localDate, harness, ...totals })).max(2e5),
15284
- /** Local weekday (0 = Sunday) and hour, all filters applied. */
15298
+ /** Weekday (0 = Sunday) and hour in the query timezone, all filters applied. */
15285
15299
  hourly: external_exports.array(external_exports.strictObject({
15286
15300
  weekday: external_exports.number().int().min(0).max(6),
15287
15301
  hour: external_exports.number().int().min(0).max(23),
@@ -15321,6 +15335,51 @@ var hostInteractionIdSchema = opaqueIdSchema.brand();
15321
15335
  var threadPrewarmDiscardParamsSchema = external_exports.object({ threadId: hostThreadIdSchema });
15322
15336
  var threadPrewarmDiscardResultSchema = external_exports.object({ discarded: external_exports.boolean() });
15323
15337
 
15338
+ // ../../shared-contracts/dist/thread-questions.js
15339
+ var field = external_exports.discriminatedUnion("type", [
15340
+ external_exports.object({
15341
+ id: external_exports.string().min(1),
15342
+ type: external_exports.literal("choice"),
15343
+ prompt: external_exports.string(),
15344
+ options: external_exports.array(external_exports.object({
15345
+ value: external_exports.string().min(1),
15346
+ label: external_exports.string(),
15347
+ description: external_exports.string().optional()
15348
+ })).min(1),
15349
+ multiple: external_exports.boolean(),
15350
+ allowOther: external_exports.boolean(),
15351
+ optional: external_exports.boolean()
15352
+ }),
15353
+ external_exports.object({
15354
+ id: external_exports.string().min(1),
15355
+ type: external_exports.literal("text"),
15356
+ prompt: external_exports.string(),
15357
+ multiline: external_exports.boolean(),
15358
+ secret: external_exports.literal(false),
15359
+ optional: external_exports.boolean(),
15360
+ placeholder: external_exports.string().optional(),
15361
+ prefill: external_exports.string().optional()
15362
+ })
15363
+ ]);
15364
+ var threadQuestionSchema = external_exports.object({
15365
+ interactionId: external_exports.string().min(1),
15366
+ turnId: external_exports.string().min(1),
15367
+ title: external_exports.string().optional(),
15368
+ questions: external_exports.array(field).min(1)
15369
+ }).refine(({ questions }) => questions.some((q) => q.type === "choice" && q.multiple), {
15370
+ message: "Shared cards require at least one multi-select question"
15371
+ });
15372
+ var threadQuestionsListParamsSchema = external_exports.strictObject({ threadId: external_exports.string().min(1) });
15373
+ var threadQuestionsResultSchema = external_exports.object({ questions: external_exports.array(threadQuestionSchema) });
15374
+ var threadQuestionRespondParamsSchema = external_exports.strictObject({
15375
+ threadId: external_exports.string().min(1),
15376
+ turnId: external_exports.string().min(1),
15377
+ interactionId: external_exports.string().min(1),
15378
+ answers: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
15379
+ cancelled: external_exports.boolean().default(false)
15380
+ });
15381
+ var threadQuestionRespondResultSchema = external_exports.object({ accepted: external_exports.literal(true) });
15382
+
15324
15383
  // ../../shared-contracts/dist/harness-plugins.js
15325
15384
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15326
15385
  var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
@@ -15423,6 +15482,8 @@ var CONSOLE_HOST_METHODS = Object.freeze([
15423
15482
  "codexhost/harness/display-settings/set",
15424
15483
  "codexhost/harness/inspect",
15425
15484
  "codexhost/harness/installation",
15485
+ "codexhost/harness/installation/start",
15486
+ "codexhost/harness/installation/status",
15426
15487
  "codexhost/harness/launch-settings/get",
15427
15488
  "codexhost/harness/launch-settings/set",
15428
15489
  HARNESS_LONG_CONTEXT_GET_METHOD,
@@ -15500,7 +15561,18 @@ var threadManualCompactionStartedSchema = external_exports.strictObject({
15500
15561
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15501
15562
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
15502
15563
  var cacheHitRatePercentSchema = external_exports.number().finite().min(0).max(100);
15564
+ var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text) => text.length <= maximum));
15565
+ var composerIndicatorsSchema = external_exports.array(external_exports.object({
15566
+ kind: external_exports.literal("countdown"),
15567
+ id: external_exports.string().min(1).max(64),
15568
+ expiresAtUnix: nonNegativeSafeIntegerSchema,
15569
+ label: indicatorTextSchema(256).optional(),
15570
+ tooltip: indicatorTextSchema(1024).optional()
15571
+ }).strict()).max(2).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, {
15572
+ message: "Composer indicator IDs must be unique"
15573
+ });
15503
15574
  var threadUsageSnapshotSchema = external_exports.object({
15575
+ composerIndicators: composerIndicatorsSchema.optional(),
15504
15576
  inputTokens: nonNegativeSafeIntegerSchema.optional(),
15505
15577
  cachedInputTokens: nonNegativeSafeIntegerSchema.optional(),
15506
15578
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
@@ -15926,7 +15998,9 @@ var harnessSessionCapabilitiesSchema = external_exports.object({
15926
15998
  }).strict().optional(),
15927
15999
  input: external_exports.object({
15928
16000
  image: external_exports.boolean()
15929
- }).strict().optional()
16001
+ }).strict().optional(),
16002
+ /** True only when `turn.steer` delivers input into the active Turn through a native primitive. */
16003
+ steer: external_exports.boolean().optional()
15930
16004
  }).strict();
15931
16005
  var harnessConfigurationStateSchema = external_exports.object({
15932
16006
  effectiveModel: harnessModelRefSchema.optional(),
@@ -15973,7 +16047,9 @@ var harnessInspectionSchema = external_exports.union([
15973
16047
  var harnessInspectParamsSchema = external_exports.object({
15974
16048
  harnessId: harnessIdSchema,
15975
16049
  cwd: nonBlankTextSchema2.max(16384).optional(),
15976
- refresh: external_exports.boolean().optional()
16050
+ refresh: external_exports.boolean().optional(),
16051
+ /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
16052
+ purpose: external_exports.literal("availability").optional()
15977
16053
  }).strict();
15978
16054
  var harnessWebUiOpenParamsSchema = external_exports.object({
15979
16055
  harnessId: harnessIdSchema
@@ -16058,13 +16134,25 @@ var threadOwnershipListResultSchema = external_exports.object({
16058
16134
  seen.add(thread.threadId);
16059
16135
  }
16060
16136
  });
16137
+ var threadSteeringInspectParamsSchema = external_exports.object({
16138
+ threadId: hostThreadIdSchema,
16139
+ /** The text about to be steered; a Harness command always stops and restarts. */
16140
+ text: external_exports.string().optional()
16141
+ }).strict();
16142
+ var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
16143
+ var threadSteeringInspectResultSchema = external_exports.object({
16144
+ delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
16145
+ }).strict();
16061
16146
 
16062
16147
  // ../../shared-contracts/dist/harness-route.js
16063
16148
  var harnessPluginRouteSchema = external_exports.object({
16064
16149
  harnessId: harnessPluginIdSchema,
16065
16150
  model: harnessModelRefSchema.optional(),
16066
16151
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
16067
- permissionModeId: harnessPermissionModeIdSchema.optional()
16152
+ permissionModeId: harnessPermissionModeIdSchema.optional(),
16153
+ /** A draft prewarm create: stays unsubmitted until the user's first Turn.
16154
+ * Desktop forwards only the Model of a main-process prewarm to thread/start. */
16155
+ prewarm: external_exports.literal(true).optional()
16068
16156
  }).strict();
16069
16157
 
16070
16158
  // ../../shared-contracts/dist/harness-launch-settings.js
@@ -16090,6 +16178,10 @@ var harnessInstallationStateSchema = external_exports.object({
16090
16178
  latestVersion: external_exports.string().min(1).max(128),
16091
16179
  updateAvailable: external_exports.boolean(),
16092
16180
  canUpdate: external_exports.boolean(),
16181
+ /** Defaults to CLI; some Harnesses ship only inside a desktop application. */
16182
+ versionKind: external_exports.enum(["cli", "application"]).optional(),
16183
+ /** Official download opened by the user; does not imply an automatic installation. */
16184
+ manualUpdateUrl: external_exports.url().max(2048).refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Manual updates require a credential-free HTTPS URL").optional(),
16093
16185
  // Adapter-owned diagnostic text; UI uses messageCode rather than displaying it verbatim.
16094
16186
  message: external_exports.string().max(2048).optional(),
16095
16187
  messageCode: external_exports.string().min(1).max(128).optional(),
@@ -16097,6 +16189,20 @@ var harnessInstallationStateSchema = external_exports.object({
16097
16189
  notice: harnessLocalizedTextSchema.optional(),
16098
16190
  latestVersionKind: external_exports.enum(["unknown", "tracking-branch"]).optional()
16099
16191
  }).strict();
16192
+ var harnessInstallationTaskParamsSchema = external_exports.object({ taskId: external_exports.string().uuid() }).strict();
16193
+ var harnessInstallationTaskSchema = external_exports.discriminatedUnion("status", [
16194
+ external_exports.object({ taskId: external_exports.string().uuid(), status: external_exports.literal("running") }).strict(),
16195
+ external_exports.object({
16196
+ taskId: external_exports.string().uuid(),
16197
+ status: external_exports.literal("succeeded"),
16198
+ result: harnessInstallationStateSchema
16199
+ }).strict(),
16200
+ external_exports.object({
16201
+ taskId: external_exports.string().uuid(),
16202
+ status: external_exports.literal("failed"),
16203
+ error: external_exports.object({ code: external_exports.number().int(), message: external_exports.string().min(1).max(2048) }).strict()
16204
+ }).strict()
16205
+ ]);
16100
16206
 
16101
16207
  // ../../shared-contracts/dist/codex-accounts.js
16102
16208
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
@@ -16910,6 +17016,18 @@ function sanitizeDiagnosticTail(value) {
16910
17016
  return redacted.length <= DIAGNOSTIC_TAIL_MAX_LENGTH ? redacted : redacted.slice(-DIAGNOSTIC_TAIL_MAX_LENGTH);
16911
17017
  }
16912
17018
 
17019
+ // ../../harness-adapter/dist/steer.js
17020
+ function unsupportedSteer(harnessLabel) {
17021
+ return {
17022
+ ok: false,
17023
+ error: {
17024
+ code: "unsupported",
17025
+ message: `${harnessLabel} cannot steer an active Turn natively`,
17026
+ retryable: false
17027
+ }
17028
+ };
17029
+ }
17030
+
16913
17031
  // ../../harness-adapter/dist/usage.js
16914
17032
  var tokenFields = [
16915
17033
  "inputTokens",
@@ -16937,6 +17055,7 @@ var usageFields = /* @__PURE__ */ new Set([
16937
17055
  ...safeIntegerFields,
16938
17056
  ...percentFields,
16939
17057
  "sessionCacheUsage",
17058
+ "composerIndicators",
16940
17059
  "totalCostUsd",
16941
17060
  "totalCredits",
16942
17061
  "contextUsagePercent",
@@ -16959,26 +17078,27 @@ function parseHostUsage(value) {
16959
17078
  throw new Error(`Harness Usage contains unknown field '${key}'`);
16960
17079
  }
16961
17080
  }
16962
- for (const field of [
17081
+ const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
17082
+ for (const field2 of [
16963
17083
  "totalCredits",
16964
17084
  "contextUsagePercent",
16965
17085
  "apiOutputTokensPerSecond"
16966
17086
  ]) {
16967
- const candidate = value[field];
17087
+ const candidate = value[field2];
16968
17088
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16969
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
17089
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
16970
17090
  }
16971
17091
  }
16972
- for (const field of tokenFields) {
16973
- const candidate = value[field];
17092
+ for (const field2 of tokenFields) {
17093
+ const candidate = value[field2];
16974
17094
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16975
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
17095
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
16976
17096
  }
16977
17097
  }
16978
- for (const field of safeIntegerFields) {
16979
- const candidate = value[field];
17098
+ for (const field2 of safeIntegerFields) {
17099
+ const candidate = value[field2];
16980
17100
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16981
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
17101
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
16982
17102
  }
16983
17103
  }
16984
17104
  if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
@@ -16987,16 +17107,16 @@ function parseHostUsage(value) {
16987
17107
  if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
16988
17108
  throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
16989
17109
  }
16990
- for (const field of ["totalCredits", "contextUsagePercent"]) {
16991
- const candidate = value[field];
17110
+ for (const field2 of ["totalCredits", "contextUsagePercent"]) {
17111
+ const candidate = value[field2];
16992
17112
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16993
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
17113
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
16994
17114
  }
16995
17115
  }
16996
- for (const field of percentFields) {
16997
- const candidate = value[field];
17116
+ for (const field2 of percentFields) {
17117
+ const candidate = value[field2];
16998
17118
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
16999
- throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
17119
+ throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
17000
17120
  }
17001
17121
  }
17002
17122
  if (value.sessionCacheUsage !== void 0) {
@@ -17035,9 +17155,9 @@ function parseHostUsage(value) {
17035
17155
  if (value.costSource !== "publicPrice") {
17036
17156
  throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
17037
17157
  }
17038
- return { ...value, unpricedModels: [...models] };
17158
+ return { ...value, ...indicators, unpricedModels: [...models] };
17039
17159
  }
17040
- return { ...value };
17160
+ return { ...value, ...indicators };
17041
17161
  }
17042
17162
  var requestTokenFields = [
17043
17163
  "inputTokens",
@@ -17067,19 +17187,19 @@ function parseHostUsageRequest(value) {
17067
17187
  if (typeof value.requestId !== "string" || value.requestId.length === 0) {
17068
17188
  throw new Error("Harness Usage request 'requestId' must be a non-empty string");
17069
17189
  }
17070
- for (const field of ["model", "provider"]) {
17071
- const candidate = value[field];
17190
+ for (const field2 of ["model", "provider"]) {
17191
+ const candidate = value[field2];
17072
17192
  if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
17073
- throw new Error(`Harness Usage request '${field}' must be a non-empty string`);
17193
+ throw new Error(`Harness Usage request '${field2}' must be a non-empty string`);
17074
17194
  }
17075
17195
  }
17076
17196
  if (value.historical !== void 0 && typeof value.historical !== "boolean") {
17077
17197
  throw new Error("Harness Usage request 'historical' must be a boolean");
17078
17198
  }
17079
- for (const field of requestTokenFields) {
17080
- const candidate = value[field];
17199
+ for (const field2 of requestTokenFields) {
17200
+ const candidate = value[field2];
17081
17201
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17082
- throw new Error(`Harness Usage request '${field}' must be a non-negative safe integer`);
17202
+ throw new Error(`Harness Usage request '${field2}' must be a non-negative safe integer`);
17083
17203
  }
17084
17204
  }
17085
17205
  if (value.inputTokens === void 0 || value.outputTokens === void 0) {
@@ -17764,857 +17884,283 @@ function createOmpUsageStatistics(environment) {
17764
17884
  });
17765
17885
  }
17766
17886
 
17767
- // ../../../node_modules/diff/libesm/diff/base.js
17768
- var Diff = class {
17769
- diff(oldStr, newStr, options = {}) {
17770
- let callback;
17771
- if (typeof options === "function") {
17772
- callback = options;
17773
- options = {};
17774
- } else if ("callback" in options) {
17775
- callback = options.callback;
17776
- }
17777
- const oldString = this.castInput(oldStr, options);
17778
- const newString = this.castInput(newStr, options);
17779
- const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
17780
- const newTokens = this.removeEmpty(this.tokenize(newString, options));
17781
- return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
17887
+ // dist/omp-model-list.js
17888
+ import { spawn as spawn2 } from "node:child_process";
17889
+
17890
+ // dist/command.js
17891
+ var ompDiscoverySpec = {
17892
+ id: "omp",
17893
+ command: "omp",
17894
+ commandEnvironmentVariable: "OMP_COMMAND",
17895
+ installRoots: {
17896
+ posix: [
17897
+ "~/.npm-global/bin",
17898
+ "~/.local/bin",
17899
+ VERSION_MANAGER_ROOTS,
17900
+ "/opt/homebrew/bin",
17901
+ "/usr/local/bin"
17902
+ ],
17903
+ windows: ["${APPDATA}/npm", "~/.local/bin", VERSION_MANAGER_ROOTS]
17782
17904
  }
17783
- diffWithOptionsObj(oldTokens, newTokens, options, callback) {
17784
- var _a3;
17785
- const done = (value) => {
17786
- value = this.postProcess(value, options);
17787
- if (callback) {
17788
- setTimeout(function() {
17789
- callback(value);
17790
- }, 0);
17791
- return void 0;
17792
- } else {
17793
- return value;
17905
+ };
17906
+ function resolveOmpExecutable(input, dependencies = {}) {
17907
+ const resolution = resolveHarnessExecutable(ompDiscoverySpec, {
17908
+ ...input.command ? { command: input.command } : {},
17909
+ environment: input.environment,
17910
+ ...dependencies.platform ? { platform: dependencies.platform } : {},
17911
+ ...dependencies.homeDirectory ? { homeDirectory: dependencies.homeDirectory } : {}
17912
+ }, { ...dependencies.isExecutable ? { isExecutable: dependencies.isExecutable } : {} });
17913
+ return resolution?.executable ?? input.command ?? input.environment.OMP_COMMAND ?? "omp";
17914
+ }
17915
+
17916
+ // dist/omp-rpc-session.js
17917
+ import { spawn, spawnSync } from "node:child_process";
17918
+ import { randomUUID } from "node:crypto";
17919
+ import path6 from "node:path";
17920
+
17921
+ // dist/omp-slash-commands.js
17922
+ var OMP_LIVE_COMMAND_ID_PREFIX = "omp.slash.";
17923
+ function isRecord6(value) {
17924
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17925
+ }
17926
+ function parseOmpAvailableCommands(value) {
17927
+ if (!Array.isArray(value))
17928
+ return [];
17929
+ return value.flatMap((entry) => {
17930
+ if (!isRecord6(entry))
17931
+ return [];
17932
+ const name = typeof entry.name === "string" ? entry.name.trim().replace(/^\//u, "") : "";
17933
+ if (!name)
17934
+ return [];
17935
+ return [
17936
+ {
17937
+ name,
17938
+ description: typeof entry.description === "string" ? entry.description : "",
17939
+ source: typeof entry.source === "string" ? entry.source : null
17794
17940
  }
17795
- };
17796
- const newLen = newTokens.length, oldLen = oldTokens.length;
17797
- let editLength = 1;
17798
- let maxEditLength = newLen + oldLen;
17799
- if (options.maxEditLength != null) {
17800
- maxEditLength = Math.min(maxEditLength, options.maxEditLength);
17801
- }
17802
- const maxExecutionTime = (_a3 = options.timeout) !== null && _a3 !== void 0 ? _a3 : Infinity;
17803
- const abortAfterTimestamp = Date.now() + maxExecutionTime;
17804
- const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
17805
- let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
17806
- if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
17807
- return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
17808
- }
17809
- let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
17810
- const execEditLength = () => {
17811
- for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
17812
- let basePath;
17813
- const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
17814
- if (removePath) {
17815
- bestPath[diagonalPath - 1] = void 0;
17816
- }
17817
- let canAdd = false;
17818
- if (addPath) {
17819
- const addPathNewPos = addPath.oldPos - diagonalPath;
17820
- canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
17821
- }
17822
- const canRemove = removePath && removePath.oldPos + 1 < oldLen;
17823
- if (!canAdd && !canRemove) {
17824
- bestPath[diagonalPath] = void 0;
17825
- continue;
17826
- }
17827
- if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
17828
- basePath = this.addToPath(addPath, true, false, 0, options);
17829
- } else {
17830
- basePath = this.addToPath(removePath, false, true, 1, options);
17831
- }
17832
- newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
17833
- if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
17834
- return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
17835
- } else {
17836
- bestPath[diagonalPath] = basePath;
17837
- if (basePath.oldPos + 1 >= oldLen) {
17838
- maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
17839
- }
17840
- if (newPos + 1 >= newLen) {
17841
- minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
17842
- }
17843
- }
17941
+ ];
17942
+ });
17943
+ }
17944
+ function ompLiveCommands(native) {
17945
+ return native.filter(({ source, name }) => source !== "builtin" || name === "context").map((command) => ({
17946
+ name: command.name,
17947
+ description: command.description,
17948
+ kind: command.source === "skill" ? "skill" : "command"
17949
+ }));
17950
+ }
17951
+
17952
+ // dist/omp-session-file.js
17953
+ import { createReadStream as createReadStream3 } from "node:fs";
17954
+ import { open, realpath as realpath2 } from "node:fs/promises";
17955
+ import readline from "node:readline";
17956
+ var MAX_SESSION_HEADER_BYTES = 64 * 1024;
17957
+ var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
17958
+ function isRecord7(value) {
17959
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17960
+ }
17961
+ function historyEntry(value) {
17962
+ 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") {
17963
+ return null;
17964
+ }
17965
+ return value;
17966
+ }
17967
+ async function readOmpSessionHistory(sessionFile, maxBytes) {
17968
+ const entries = [];
17969
+ let leafId = null;
17970
+ let incomplete = false;
17971
+ const lines = readline.createInterface({
17972
+ input: createReadStream3(sessionFile, {
17973
+ encoding: "utf8",
17974
+ ...maxBytes === void 0 ? {} : { end: maxBytes - 1 }
17975
+ }),
17976
+ crlfDelay: Number.POSITIVE_INFINITY
17977
+ });
17978
+ try {
17979
+ for await (const line of lines) {
17980
+ if (line.length === 0)
17981
+ continue;
17982
+ let parsed;
17983
+ try {
17984
+ parsed = JSON.parse(line);
17985
+ } catch {
17986
+ incomplete = true;
17987
+ continue;
17844
17988
  }
17845
- editLength++;
17846
- };
17847
- if (callback) {
17848
- (function exec() {
17849
- setTimeout(function() {
17850
- if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
17851
- return callback(void 0);
17852
- }
17853
- if (!execEditLength()) {
17854
- exec();
17855
- }
17856
- }, 0);
17857
- })();
17858
- } else {
17859
- while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
17860
- const ret = execEditLength();
17861
- if (ret) {
17862
- return ret;
17989
+ const entry = historyEntry(parsed);
17990
+ if (!entry) {
17991
+ if (!isRecord7(parsed) || parsed.type !== "title" && parsed.type !== "session") {
17992
+ incomplete = true;
17863
17993
  }
17994
+ continue;
17864
17995
  }
17996
+ entries.push(entry);
17997
+ leafId = entry.id;
17865
17998
  }
17999
+ } finally {
18000
+ lines.close();
17866
18001
  }
17867
- addToPath(path9, added, removed, oldPosInc, options) {
17868
- const last = path9.lastComponent;
17869
- if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
17870
- return {
17871
- oldPos: path9.oldPos + oldPosInc,
17872
- lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
17873
- };
17874
- } else {
17875
- return {
17876
- oldPos: path9.oldPos + oldPosInc,
17877
- lastComponent: { count: 1, added, removed, previousComponent: last }
17878
- };
17879
- }
17880
- }
17881
- extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
17882
- const newLen = newTokens.length, oldLen = oldTokens.length;
17883
- let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
17884
- while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
17885
- newPos++;
17886
- oldPos++;
17887
- commonCount++;
17888
- if (options.oneChangePerToken) {
17889
- basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
17890
- }
17891
- }
17892
- if (commonCount && !options.oneChangePerToken) {
17893
- basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
17894
- }
17895
- basePath.oldPos = oldPos;
17896
- return newPos;
17897
- }
17898
- equals(left, right, options) {
17899
- if (options.comparator) {
17900
- return options.comparator(left, right);
17901
- } else {
17902
- return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
18002
+ return { entries, leafId, ...incomplete ? { incomplete: true } : {} };
18003
+ }
18004
+ async function readOmpSessionHeader(sessionFile) {
18005
+ const handle = await open(sessionFile, "r");
18006
+ try {
18007
+ const buffer = Buffer.allocUnsafe(MAX_SESSION_HEADER_BYTES);
18008
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
18009
+ const contents = buffer.subarray(0, bytesRead);
18010
+ const newline = contents.indexOf(10);
18011
+ if (newline < 0 && bytesRead === buffer.length) {
18012
+ throw new Error("Omp Session header exceeds the supported size");
17903
18013
  }
17904
- }
17905
- removeEmpty(array2) {
17906
- const ret = [];
17907
- for (let i = 0; i < array2.length; i++) {
17908
- if (array2[i]) {
17909
- ret.push(array2[i]);
18014
+ const contentsText = utf8Decoder.decode(contents);
18015
+ for (const line of contentsText.split("\n")) {
18016
+ if (line.length === 0)
18017
+ continue;
18018
+ let parsed;
18019
+ try {
18020
+ parsed = JSON.parse(line);
18021
+ } catch {
18022
+ continue;
17910
18023
  }
18024
+ if (!isRecord7(parsed) || parsed.type !== "session")
18025
+ continue;
18026
+ if (typeof parsed.id !== "string" || parsed.id.length === 0 || typeof parsed.cwd !== "string" || parsed.cwd.length === 0) {
18027
+ throw new Error("Omp Session header is invalid");
18028
+ }
18029
+ return { type: "session", id: parsed.id, cwd: parsed.cwd };
17911
18030
  }
17912
- return ret;
17913
- }
17914
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
17915
- castInput(value, options) {
17916
- return value;
17917
- }
17918
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
17919
- tokenize(value, options) {
17920
- return Array.from(value);
17921
- }
17922
- join(chars) {
17923
- return chars.join("");
18031
+ throw new Error("Omp Session header is invalid");
18032
+ } finally {
18033
+ await handle.close();
17924
18034
  }
17925
- postProcess(changeObjects, options) {
17926
- return changeObjects;
18035
+ }
18036
+ async function verifyOmpSessionCwd(input) {
18037
+ if (!input.sessionFile)
18038
+ throw new Error("Omp Fork Session has no persisted Session file");
18039
+ const header = await readOmpSessionHeader(input.sessionFile);
18040
+ if (header.id !== input.sessionId) {
18041
+ throw new Error("Omp Fork Session header identity does not match RPC state");
17927
18042
  }
17928
- get useLongestToken() {
17929
- return false;
18043
+ const [actualCwd, expectedCwd] = await Promise.all([
18044
+ realpath2(header.cwd),
18045
+ realpath2(input.expectedCwd)
18046
+ ]);
18047
+ if (actualCwd !== expectedCwd) {
18048
+ throw new Error("Omp Fork Session did not bind the requested cwd");
17930
18049
  }
17931
- buildValues(lastComponent, newTokens, oldTokens) {
17932
- const components = [];
17933
- let nextComponent;
17934
- while (lastComponent) {
17935
- components.push(lastComponent);
17936
- nextComponent = lastComponent.previousComponent;
17937
- delete lastComponent.previousComponent;
17938
- lastComponent = nextComponent;
18050
+ }
18051
+
18052
+ // dist/omp-protocol.js
18053
+ var MAX_FRAME_BYTES = 1024 * 1024;
18054
+ var MAX_REASSEMBLED_BYTES = 64 * 1024 * 1024;
18055
+ var MAX_CHUNK_BYTES = 256 * 1024;
18056
+ function isObject2(value) {
18057
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18058
+ }
18059
+ var OmpFrameDecoder = class {
18060
+ #pending = null;
18061
+ push(value) {
18062
+ if (!isObject2(value))
18063
+ throw new Error("OMP RPC frame must be a JSON object");
18064
+ if (value.type !== "rpc_chunk") {
18065
+ if (this.#pending)
18066
+ throw new Error("OMP RPC chunk sequence was interrupted");
18067
+ return value;
17939
18068
  }
17940
- components.reverse();
17941
- const componentLen = components.length;
17942
- let componentPos = 0, newPos = 0, oldPos = 0;
17943
- for (; componentPos < componentLen; componentPos++) {
17944
- const component = components[componentPos];
17945
- if (!component.removed) {
17946
- if (!component.added && this.useLongestToken) {
17947
- let value = newTokens.slice(newPos, newPos + component.count);
17948
- value = value.map(function(value2, i) {
17949
- const oldValue = oldTokens[oldPos + i];
17950
- return oldValue.length > value2.length ? oldValue : value2;
17951
- });
17952
- component.value = this.join(value);
17953
- } else {
17954
- component.value = this.join(newTokens.slice(newPos, newPos + component.count));
17955
- }
17956
- newPos += component.count;
17957
- if (!component.added) {
17958
- oldPos += component.count;
17959
- }
17960
- } else {
17961
- component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
17962
- oldPos += component.count;
17963
- }
18069
+ const chunkId = value.chunkId;
18070
+ const index = value.index;
18071
+ const count2 = value.count;
18072
+ const byteLength = value.byteLength;
18073
+ const data = value.data;
18074
+ 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)
18075
+ throw new Error("Invalid OMP RPC chunk metadata");
18076
+ let bytes;
18077
+ try {
18078
+ bytes = Buffer.from(data, "base64");
18079
+ } catch {
18080
+ throw new Error("Invalid OMP RPC chunk data");
17964
18081
  }
17965
- return components;
18082
+ if (bytes.length === 0 || bytes.length > MAX_CHUNK_BYTES || bytes.toString("base64") !== data) {
18083
+ throw new Error("Invalid OMP RPC chunk data");
18084
+ }
18085
+ const chunkIndex = index;
18086
+ const chunkCount = count2;
18087
+ const declaredByteLength = byteLength;
18088
+ if (!this.#pending) {
18089
+ if (chunkIndex !== 0)
18090
+ throw new Error("OMP RPC chunk sequence must start at index 0");
18091
+ this.#pending = {
18092
+ chunkId,
18093
+ count: chunkCount,
18094
+ byteLength: declaredByteLength,
18095
+ nextIndex: 0,
18096
+ chunks: [],
18097
+ received: 0
18098
+ };
18099
+ }
18100
+ const pending = this.#pending;
18101
+ if (!pending)
18102
+ throw new Error("OMP RPC chunk state was lost");
18103
+ if (pending.chunkId !== chunkId || pending.count !== chunkCount || pending.byteLength !== declaredByteLength || pending.nextIndex !== chunkIndex) {
18104
+ throw new Error("OMP RPC chunk sequence mismatch");
18105
+ }
18106
+ pending.chunks.push(bytes);
18107
+ pending.received += bytes.length;
18108
+ pending.nextIndex += 1;
18109
+ if (pending.received > pending.byteLength)
18110
+ throw new Error("OMP RPC chunk sequence exceeds its declared length");
18111
+ if (pending.nextIndex < pending.count)
18112
+ return null;
18113
+ if (pending.received !== pending.byteLength)
18114
+ throw new Error("OMP RPC chunk sequence length mismatch");
18115
+ this.#pending = null;
18116
+ let decoded;
18117
+ try {
18118
+ decoded = JSON.parse(Buffer.concat(pending.chunks).toString("utf8"));
18119
+ } catch {
18120
+ throw new Error("Failed to decode reassembled OMP RPC frame");
18121
+ }
18122
+ if (!isObject2(decoded))
18123
+ throw new Error("Reassembled OMP RPC frame must be an object");
18124
+ return decoded;
17966
18125
  }
17967
18126
  };
17968
18127
 
17969
- // ../../../node_modules/diff/libesm/diff/line.js
17970
- var LineDiff = class extends Diff {
17971
- constructor() {
17972
- super(...arguments);
17973
- this.tokenize = tokenize;
18128
+ // dist/omp-rpc-session.js
18129
+ var OmpRpcFaultError = class extends Error {
18130
+ kind;
18131
+ diagnostic;
18132
+ constructor(kind, message3, diagnostic) {
18133
+ super(message3);
18134
+ this.kind = kind;
18135
+ this.diagnostic = diagnostic;
18136
+ this.name = "OmpRpcFaultError";
17974
18137
  }
17975
- equals(left, right, options) {
17976
- if (options.ignoreWhitespace) {
17977
- if (!options.newlineIsToken || !left.includes("\n")) {
17978
- left = left.trim();
17979
- }
17980
- if (!options.newlineIsToken || !right.includes("\n")) {
17981
- right = right.trim();
17982
- }
17983
- } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
17984
- if (left.endsWith("\n")) {
17985
- left = left.slice(0, -1);
17986
- }
17987
- if (right.endsWith("\n")) {
17988
- right = right.slice(0, -1);
17989
- }
17990
- }
17991
- return super.equals(left, right, options);
18138
+ };
18139
+ var OmpRpcUnsupportedCommandError = class extends Error {
18140
+ command;
18141
+ constructor(command) {
18142
+ super(`Omp RPC does not support '${command}'`);
18143
+ this.command = command;
18144
+ this.name = "OmpRpcUnsupportedCommandError";
17992
18145
  }
17993
18146
  };
17994
- var lineDiff = new LineDiff();
17995
- function diffLines(oldStr, newStr, options) {
17996
- return lineDiff.diff(oldStr, newStr, options);
18147
+ var textDecoder = new TextDecoder("utf-8", { fatal: true });
18148
+ function isRecord8(value) {
18149
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17997
18150
  }
17998
- function tokenize(value, options) {
17999
- if (options.stripTrailingCr) {
18000
- value = value.replace(/\r\n/g, "\n");
18001
- }
18002
- const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
18003
- if (!linesAndNewlines[linesAndNewlines.length - 1]) {
18004
- linesAndNewlines.pop();
18005
- }
18006
- for (let i = 0; i < linesAndNewlines.length; i++) {
18007
- const line = linesAndNewlines[i];
18008
- if (i % 2 && !options.newlineIsToken) {
18009
- retLines[retLines.length - 1] += line;
18010
- } else {
18011
- retLines.push(line);
18012
- }
18151
+ function message2(value) {
18152
+ return value instanceof Error ? value.message : String(value);
18153
+ }
18154
+ function nonBlankString(value) {
18155
+ return typeof value === "string" && value.trim().length > 0;
18156
+ }
18157
+ function parseNativeModel(value, context) {
18158
+ if (value === null || value === void 0)
18159
+ return null;
18160
+ if (!isRecord8(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
18161
+ throw new OmpRpcFaultError("protocolError", `Omp RPC returned an invalid ${context} Model`);
18013
18162
  }
18014
- return retLines;
18015
- }
18016
-
18017
- // ../../../node_modules/diff/libesm/patch/parse.js
18018
- function parsePatch(uniDiff) {
18019
- const diffstr = uniDiff.split(/\n/), list = [];
18020
- let i = 0;
18021
- function parseIndex() {
18022
- const index = {};
18023
- list.push(index);
18024
- while (i < diffstr.length) {
18025
- const line = diffstr[i];
18026
- if (/^(---|\+\+\+|@@)\s/.test(line)) {
18027
- break;
18028
- }
18029
- const header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
18030
- if (header) {
18031
- index.index = header[1];
18032
- }
18033
- i++;
18034
- }
18035
- parseFileHeader(index);
18036
- parseFileHeader(index);
18037
- index.hunks = [];
18038
- while (i < diffstr.length) {
18039
- const line = diffstr[i];
18040
- if (/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/.test(line)) {
18041
- break;
18042
- } else if (/^@@/.test(line)) {
18043
- index.hunks.push(parseHunk());
18044
- } else if (line) {
18045
- throw new Error("Unknown line " + (i + 1) + " " + JSON.stringify(line));
18046
- } else {
18047
- i++;
18048
- }
18049
- }
18050
- }
18051
- function parseFileHeader(index) {
18052
- const fileHeader = /^(---|\+\+\+)\s+(.*)\r?$/.exec(diffstr[i]);
18053
- if (fileHeader) {
18054
- const data = fileHeader[2].split(" ", 2), header = (data[1] || "").trim();
18055
- let fileName = data[0].replace(/\\\\/g, "\\");
18056
- if (/^".*"$/.test(fileName)) {
18057
- fileName = fileName.substr(1, fileName.length - 2);
18058
- }
18059
- if (fileHeader[1] === "---") {
18060
- index.oldFileName = fileName;
18061
- index.oldHeader = header;
18062
- } else {
18063
- index.newFileName = fileName;
18064
- index.newHeader = header;
18065
- }
18066
- i++;
18067
- }
18068
- }
18069
- function parseHunk() {
18070
- var _a3;
18071
- const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
18072
- const hunk = {
18073
- oldStart: +chunkHeader[1],
18074
- oldLines: typeof chunkHeader[2] === "undefined" ? 1 : +chunkHeader[2],
18075
- newStart: +chunkHeader[3],
18076
- newLines: typeof chunkHeader[4] === "undefined" ? 1 : +chunkHeader[4],
18077
- lines: []
18078
- };
18079
- if (hunk.oldLines === 0) {
18080
- hunk.oldStart += 1;
18081
- }
18082
- if (hunk.newLines === 0) {
18083
- hunk.newStart += 1;
18084
- }
18085
- let addCount = 0, removeCount = 0;
18086
- for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a3 = diffstr[i]) === null || _a3 === void 0 ? void 0 : _a3.startsWith("\\"))); i++) {
18087
- const operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? " " : diffstr[i][0];
18088
- if (operation === "+" || operation === "-" || operation === " " || operation === "\\") {
18089
- hunk.lines.push(diffstr[i]);
18090
- if (operation === "+") {
18091
- addCount++;
18092
- } else if (operation === "-") {
18093
- removeCount++;
18094
- } else if (operation === " ") {
18095
- addCount++;
18096
- removeCount++;
18097
- }
18098
- } else {
18099
- throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`);
18100
- }
18101
- }
18102
- if (!addCount && hunk.newLines === 1) {
18103
- hunk.newLines = 0;
18104
- }
18105
- if (!removeCount && hunk.oldLines === 1) {
18106
- hunk.oldLines = 0;
18107
- }
18108
- if (addCount !== hunk.newLines) {
18109
- throw new Error("Added line count did not match for hunk at line " + (chunkHeaderIndex + 1));
18110
- }
18111
- if (removeCount !== hunk.oldLines) {
18112
- throw new Error("Removed line count did not match for hunk at line " + (chunkHeaderIndex + 1));
18113
- }
18114
- return hunk;
18115
- }
18116
- while (i < diffstr.length) {
18117
- parseIndex();
18118
- }
18119
- return list;
18120
- }
18121
-
18122
- // ../../../node_modules/diff/libesm/patch/create.js
18123
- function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
18124
- let optionsObj;
18125
- if (!options) {
18126
- optionsObj = {};
18127
- } else if (typeof options === "function") {
18128
- optionsObj = { callback: options };
18129
- } else {
18130
- optionsObj = options;
18131
- }
18132
- if (typeof optionsObj.context === "undefined") {
18133
- optionsObj.context = 4;
18134
- }
18135
- const context = optionsObj.context;
18136
- if (optionsObj.newlineIsToken) {
18137
- throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");
18138
- }
18139
- if (!optionsObj.callback) {
18140
- return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj));
18141
- } else {
18142
- const { callback } = optionsObj;
18143
- diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => {
18144
- const patch = diffLinesResultToPatch(diff);
18145
- callback(patch);
18146
- } }));
18147
- }
18148
- function diffLinesResultToPatch(diff) {
18149
- if (!diff) {
18150
- return;
18151
- }
18152
- diff.push({ value: "", lines: [] });
18153
- function contextLines(lines) {
18154
- return lines.map(function(entry) {
18155
- return " " + entry;
18156
- });
18157
- }
18158
- const hunks = [];
18159
- let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
18160
- for (let i = 0; i < diff.length; i++) {
18161
- const current = diff[i], lines = current.lines || splitLines(current.value);
18162
- current.lines = lines;
18163
- if (current.added || current.removed) {
18164
- if (!oldRangeStart) {
18165
- const prev = diff[i - 1];
18166
- oldRangeStart = oldLine;
18167
- newRangeStart = newLine;
18168
- if (prev) {
18169
- curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : [];
18170
- oldRangeStart -= curRange.length;
18171
- newRangeStart -= curRange.length;
18172
- }
18173
- }
18174
- for (const line of lines) {
18175
- curRange.push((current.added ? "+" : "-") + line);
18176
- }
18177
- if (current.added) {
18178
- newLine += lines.length;
18179
- } else {
18180
- oldLine += lines.length;
18181
- }
18182
- } else {
18183
- if (oldRangeStart) {
18184
- if (lines.length <= context * 2 && i < diff.length - 2) {
18185
- for (const line of contextLines(lines)) {
18186
- curRange.push(line);
18187
- }
18188
- } else {
18189
- const contextSize = Math.min(lines.length, context);
18190
- for (const line of contextLines(lines.slice(0, contextSize))) {
18191
- curRange.push(line);
18192
- }
18193
- const hunk = {
18194
- oldStart: oldRangeStart,
18195
- oldLines: oldLine - oldRangeStart + contextSize,
18196
- newStart: newRangeStart,
18197
- newLines: newLine - newRangeStart + contextSize,
18198
- lines: curRange
18199
- };
18200
- hunks.push(hunk);
18201
- oldRangeStart = 0;
18202
- newRangeStart = 0;
18203
- curRange = [];
18204
- }
18205
- }
18206
- oldLine += lines.length;
18207
- newLine += lines.length;
18208
- }
18209
- }
18210
- for (const hunk of hunks) {
18211
- for (let i = 0; i < hunk.lines.length; i++) {
18212
- if (hunk.lines[i].endsWith("\n")) {
18213
- hunk.lines[i] = hunk.lines[i].slice(0, -1);
18214
- } else {
18215
- hunk.lines.splice(i + 1, 0, "\");
18216
- i++;
18217
- }
18218
- }
18219
- }
18220
- return {
18221
- oldFileName,
18222
- newFileName,
18223
- oldHeader,
18224
- newHeader,
18225
- hunks
18226
- };
18227
- }
18228
- }
18229
- function formatPatch(patch) {
18230
- if (Array.isArray(patch)) {
18231
- return patch.map(formatPatch).join("\n");
18232
- }
18233
- const ret = [];
18234
- if (patch.oldFileName == patch.newFileName) {
18235
- ret.push("Index: " + patch.oldFileName);
18236
- }
18237
- ret.push("===================================================================");
18238
- ret.push("--- " + patch.oldFileName + (typeof patch.oldHeader === "undefined" ? "" : " " + patch.oldHeader));
18239
- ret.push("+++ " + patch.newFileName + (typeof patch.newHeader === "undefined" ? "" : " " + patch.newHeader));
18240
- for (let i = 0; i < patch.hunks.length; i++) {
18241
- const hunk = patch.hunks[i];
18242
- if (hunk.oldLines === 0) {
18243
- hunk.oldStart -= 1;
18244
- }
18245
- if (hunk.newLines === 0) {
18246
- hunk.newStart -= 1;
18247
- }
18248
- ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@");
18249
- for (const line of hunk.lines) {
18250
- ret.push(line);
18251
- }
18252
- }
18253
- return ret.join("\n") + "\n";
18254
- }
18255
- function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
18256
- if (typeof options === "function") {
18257
- options = { callback: options };
18258
- }
18259
- if (!(options === null || options === void 0 ? void 0 : options.callback)) {
18260
- const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
18261
- if (!patchObj) {
18262
- return;
18263
- }
18264
- return formatPatch(patchObj);
18265
- } else {
18266
- const { callback } = options;
18267
- structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: (patchObj) => {
18268
- if (!patchObj) {
18269
- callback(void 0);
18270
- } else {
18271
- callback(formatPatch(patchObj));
18272
- }
18273
- } }));
18274
- }
18275
- }
18276
- function splitLines(text) {
18277
- const hasTrailingNl = text.endsWith("\n");
18278
- const result = text.split("\n").map((line) => line + "\n");
18279
- if (hasTrailingNl) {
18280
- result.pop();
18281
- } else {
18282
- result.push(result.pop().slice(0, -1));
18283
- }
18284
- return result;
18285
- }
18286
-
18287
- // dist/omp-adapter.js
18288
- import { randomUUID as randomUUID2 } from "node:crypto";
18289
- import { realpath as realpath3, stat as stat2 } from "node:fs/promises";
18290
- import path7 from "node:path";
18291
-
18292
- // dist/omp-slash-commands.js
18293
- var OMP_LIVE_COMMAND_ID_PREFIX = "omp.slash.";
18294
- function isRecord6(value) {
18295
- return typeof value === "object" && value !== null && !Array.isArray(value);
18296
- }
18297
- function parseOmpAvailableCommands(value) {
18298
- if (!Array.isArray(value))
18299
- return [];
18300
- return value.flatMap((entry) => {
18301
- if (!isRecord6(entry))
18302
- return [];
18303
- const name = typeof entry.name === "string" ? entry.name.trim().replace(/^\//u, "") : "";
18304
- if (!name)
18305
- return [];
18306
- return [
18307
- {
18308
- name,
18309
- description: typeof entry.description === "string" ? entry.description : "",
18310
- source: typeof entry.source === "string" ? entry.source : null
18311
- }
18312
- ];
18313
- });
18314
- }
18315
- function ompLiveCommands(native) {
18316
- return native.filter(({ source, name }) => source !== "builtin" || name === "context").map((command) => ({
18317
- name: command.name,
18318
- description: command.description,
18319
- kind: command.source === "skill" ? "skill" : "command"
18320
- }));
18321
- }
18322
-
18323
- // dist/omp-session-file.js
18324
- import { createReadStream as createReadStream3 } from "node:fs";
18325
- import { open, realpath as realpath2 } from "node:fs/promises";
18326
- import readline from "node:readline";
18327
- var MAX_SESSION_HEADER_BYTES = 64 * 1024;
18328
- var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
18329
- function isRecord7(value) {
18330
- return typeof value === "object" && value !== null && !Array.isArray(value);
18331
- }
18332
- function historyEntry(value) {
18333
- 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") {
18334
- return null;
18335
- }
18336
- return value;
18337
- }
18338
- async function readOmpSessionHistory(sessionFile, maxBytes) {
18339
- const entries = [];
18340
- let leafId = null;
18341
- let incomplete = false;
18342
- const lines = readline.createInterface({
18343
- input: createReadStream3(sessionFile, {
18344
- encoding: "utf8",
18345
- ...maxBytes === void 0 ? {} : { end: maxBytes - 1 }
18346
- }),
18347
- crlfDelay: Number.POSITIVE_INFINITY
18348
- });
18349
- try {
18350
- for await (const line of lines) {
18351
- if (line.length === 0)
18352
- continue;
18353
- let parsed;
18354
- try {
18355
- parsed = JSON.parse(line);
18356
- } catch {
18357
- incomplete = true;
18358
- continue;
18359
- }
18360
- const entry = historyEntry(parsed);
18361
- if (!entry) {
18362
- if (!isRecord7(parsed) || parsed.type !== "title" && parsed.type !== "session") {
18363
- incomplete = true;
18364
- }
18365
- continue;
18366
- }
18367
- entries.push(entry);
18368
- leafId = entry.id;
18369
- }
18370
- } finally {
18371
- lines.close();
18372
- }
18373
- return { entries, leafId, ...incomplete ? { incomplete: true } : {} };
18374
- }
18375
- async function readOmpSessionHeader(sessionFile) {
18376
- const handle = await open(sessionFile, "r");
18377
- try {
18378
- const buffer = Buffer.allocUnsafe(MAX_SESSION_HEADER_BYTES);
18379
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
18380
- const contents = buffer.subarray(0, bytesRead);
18381
- const newline = contents.indexOf(10);
18382
- if (newline < 0 && bytesRead === buffer.length) {
18383
- throw new Error("Omp Session header exceeds the supported size");
18384
- }
18385
- const contentsText = utf8Decoder.decode(contents);
18386
- for (const line of contentsText.split("\n")) {
18387
- if (line.length === 0)
18388
- continue;
18389
- let parsed;
18390
- try {
18391
- parsed = JSON.parse(line);
18392
- } catch {
18393
- continue;
18394
- }
18395
- if (!isRecord7(parsed) || parsed.type !== "session")
18396
- continue;
18397
- if (typeof parsed.id !== "string" || parsed.id.length === 0 || typeof parsed.cwd !== "string" || parsed.cwd.length === 0) {
18398
- throw new Error("Omp Session header is invalid");
18399
- }
18400
- return { type: "session", id: parsed.id, cwd: parsed.cwd };
18401
- }
18402
- throw new Error("Omp Session header is invalid");
18403
- } finally {
18404
- await handle.close();
18405
- }
18406
- }
18407
- async function verifyOmpSessionCwd(input) {
18408
- if (!input.sessionFile)
18409
- throw new Error("Omp Fork Session has no persisted Session file");
18410
- const header = await readOmpSessionHeader(input.sessionFile);
18411
- if (header.id !== input.sessionId) {
18412
- throw new Error("Omp Fork Session header identity does not match RPC state");
18413
- }
18414
- const [actualCwd, expectedCwd] = await Promise.all([
18415
- realpath2(header.cwd),
18416
- realpath2(input.expectedCwd)
18417
- ]);
18418
- if (actualCwd !== expectedCwd) {
18419
- throw new Error("Omp Fork Session did not bind the requested cwd");
18420
- }
18421
- }
18422
-
18423
- // dist/omp-last-turn-rollback.js
18424
- function modelFromState(state) {
18425
- if (state.provider === null && state.modelId === null)
18426
- return null;
18427
- if (state.provider === null || state.modelId === null) {
18428
- throw new Error("Omp state contains a partial Model identity");
18429
- }
18430
- return { provider: state.provider, id: state.modelId };
18431
- }
18432
- async function rollbackOmpLastTurn(transport, sourceSessionId, cwd) {
18433
- const startupState = transport.state;
18434
- const startupSessionId = startupState.sessionId;
18435
- const currentModel = modelFromState(startupState);
18436
- const currentThinking = startupState.thinkingLevel;
18437
- const copiedHistory = await transport.getEntries();
18438
- const boundary = resolveOmpLastTurnBoundary(copiedHistory);
18439
- if (!boundary)
18440
- return { ok: false, reason: "empty" };
18441
- const sourceSnapshot = mapOmpSnapshot(copiedHistory, {
18442
- sessionId: startupSessionId,
18443
- model: currentModel
18444
- });
18445
- let state = await transport.fork(boundary.lastUserEntryId);
18446
- if (state.sessionId === sourceSessionId || state.sessionId === startupSessionId) {
18447
- throw new Error("Omp last-Turn rollback did not create a distinct Native Session");
18448
- }
18449
- if (!sameOmpModel(modelFromState(state), currentModel)) {
18450
- if (!currentModel)
18451
- throw new Error("Omp last-Turn rollback changed the current Model");
18452
- state = await transport.selectModel(currentModel);
18453
- }
18454
- if (state.thinkingLevel !== currentThinking) {
18455
- if (!currentThinking)
18456
- throw new Error("Omp last-Turn rollback changed current Thinking");
18457
- state = await transport.selectThinkingOption(currentThinking);
18458
- }
18459
- if (!sameOmpModel(modelFromState(state), currentModel) || state.thinkingLevel !== currentThinking) {
18460
- throw new Error("Omp last-Turn rollback could not restore current Model and Thinking");
18461
- }
18462
- const snapshot = mapOmpSnapshot(await transport.getEntries(), {
18463
- sessionId: state.sessionId,
18464
- model: modelFromState(state)
18465
- });
18466
- const expectedTurnKeys = sourceSnapshot.turns.slice(0, -1).map((turn) => turn.nativeTurnRef.nativeTurnKey);
18467
- const actualTurnKeys = snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey);
18468
- if (snapshot.turns.length !== boundary.sourceTurnCount - 1 || actualTurnKeys.some((key, index) => key !== expectedTurnKeys[index])) {
18469
- throw new Error("Omp last-Turn rollback did not produce the exact retained history prefix");
18470
- }
18471
- await transport.verifySessionCwd(cwd);
18472
- return { ok: true };
18473
- }
18474
-
18475
- // dist/omp-rpc-session.js
18476
- import { spawn, spawnSync } from "node:child_process";
18477
- import { randomUUID } from "node:crypto";
18478
- import path6 from "node:path";
18479
-
18480
- // dist/command.js
18481
- var ompDiscoverySpec = {
18482
- id: "omp",
18483
- command: "omp",
18484
- commandEnvironmentVariable: "OMP_COMMAND",
18485
- installRoots: {
18486
- posix: [
18487
- "~/.npm-global/bin",
18488
- "~/.local/bin",
18489
- VERSION_MANAGER_ROOTS,
18490
- "/opt/homebrew/bin",
18491
- "/usr/local/bin"
18492
- ],
18493
- windows: ["${APPDATA}/npm", "~/.local/bin", VERSION_MANAGER_ROOTS]
18494
- }
18495
- };
18496
- function resolveOmpExecutable(input, dependencies = {}) {
18497
- const resolution = resolveHarnessExecutable(ompDiscoverySpec, {
18498
- ...input.command ? { command: input.command } : {},
18499
- environment: input.environment,
18500
- ...dependencies.platform ? { platform: dependencies.platform } : {},
18501
- ...dependencies.homeDirectory ? { homeDirectory: dependencies.homeDirectory } : {}
18502
- }, { ...dependencies.isExecutable ? { isExecutable: dependencies.isExecutable } : {} });
18503
- return resolution?.executable ?? input.command ?? input.environment.OMP_COMMAND ?? "omp";
18504
- }
18505
-
18506
- // dist/omp-protocol.js
18507
- var MAX_FRAME_BYTES = 1024 * 1024;
18508
- var MAX_REASSEMBLED_BYTES = 64 * 1024 * 1024;
18509
- var MAX_CHUNK_BYTES = 256 * 1024;
18510
- function isObject2(value) {
18511
- return typeof value === "object" && value !== null && !Array.isArray(value);
18512
- }
18513
- var OmpFrameDecoder = class {
18514
- #pending = null;
18515
- push(value) {
18516
- if (!isObject2(value))
18517
- throw new Error("OMP RPC frame must be a JSON object");
18518
- if (value.type !== "rpc_chunk") {
18519
- if (this.#pending)
18520
- throw new Error("OMP RPC chunk sequence was interrupted");
18521
- return value;
18522
- }
18523
- const chunkId = value.chunkId;
18524
- const index = value.index;
18525
- const count2 = value.count;
18526
- const byteLength = value.byteLength;
18527
- const data = value.data;
18528
- 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)
18529
- throw new Error("Invalid OMP RPC chunk metadata");
18530
- let bytes;
18531
- try {
18532
- bytes = Buffer.from(data, "base64");
18533
- } catch {
18534
- throw new Error("Invalid OMP RPC chunk data");
18535
- }
18536
- if (bytes.length === 0 || bytes.length > MAX_CHUNK_BYTES || bytes.toString("base64") !== data) {
18537
- throw new Error("Invalid OMP RPC chunk data");
18538
- }
18539
- const chunkIndex = index;
18540
- const chunkCount = count2;
18541
- const declaredByteLength = byteLength;
18542
- if (!this.#pending) {
18543
- if (chunkIndex !== 0)
18544
- throw new Error("OMP RPC chunk sequence must start at index 0");
18545
- this.#pending = {
18546
- chunkId,
18547
- count: chunkCount,
18548
- byteLength: declaredByteLength,
18549
- nextIndex: 0,
18550
- chunks: [],
18551
- received: 0
18552
- };
18553
- }
18554
- const pending = this.#pending;
18555
- if (!pending)
18556
- throw new Error("OMP RPC chunk state was lost");
18557
- if (pending.chunkId !== chunkId || pending.count !== chunkCount || pending.byteLength !== declaredByteLength || pending.nextIndex !== chunkIndex) {
18558
- throw new Error("OMP RPC chunk sequence mismatch");
18559
- }
18560
- pending.chunks.push(bytes);
18561
- pending.received += bytes.length;
18562
- pending.nextIndex += 1;
18563
- if (pending.received > pending.byteLength)
18564
- throw new Error("OMP RPC chunk sequence exceeds its declared length");
18565
- if (pending.nextIndex < pending.count)
18566
- return null;
18567
- if (pending.received !== pending.byteLength)
18568
- throw new Error("OMP RPC chunk sequence length mismatch");
18569
- this.#pending = null;
18570
- let decoded;
18571
- try {
18572
- decoded = JSON.parse(Buffer.concat(pending.chunks).toString("utf8"));
18573
- } catch {
18574
- throw new Error("Failed to decode reassembled OMP RPC frame");
18575
- }
18576
- if (!isObject2(decoded))
18577
- throw new Error("Reassembled OMP RPC frame must be an object");
18578
- return decoded;
18579
- }
18580
- };
18581
-
18582
- // dist/omp-rpc-session.js
18583
- var OmpRpcFaultError = class extends Error {
18584
- kind;
18585
- diagnostic;
18586
- constructor(kind, message3, diagnostic) {
18587
- super(message3);
18588
- this.kind = kind;
18589
- this.diagnostic = diagnostic;
18590
- this.name = "OmpRpcFaultError";
18591
- }
18592
- };
18593
- var OmpRpcUnsupportedCommandError = class extends Error {
18594
- command;
18595
- constructor(command) {
18596
- super(`Omp RPC does not support '${command}'`);
18597
- this.command = command;
18598
- this.name = "OmpRpcUnsupportedCommandError";
18599
- }
18600
- };
18601
- var textDecoder = new TextDecoder("utf-8", { fatal: true });
18602
- function isRecord8(value) {
18603
- return typeof value === "object" && value !== null && !Array.isArray(value);
18604
- }
18605
- function message2(value) {
18606
- return value instanceof Error ? value.message : String(value);
18607
- }
18608
- function nonBlankString(value) {
18609
- return typeof value === "string" && value.trim().length > 0;
18610
- }
18611
- function parseNativeModel(value, context) {
18612
- if (value === null || value === void 0)
18613
- return null;
18614
- if (!isRecord8(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
18615
- throw new OmpRpcFaultError("protocolError", `Omp RPC returned an invalid ${context} Model`);
18616
- }
18617
- return { provider: value.provider, id: value.id };
18163
+ return { provider: value.provider, id: value.id };
18618
18164
  }
18619
18165
  function sessionStateData(response) {
18620
18166
  const data = isRecord8(response.data) ? response.data : null;
@@ -18842,1178 +18388,1844 @@ var OmpRpcSession = class {
18842
18388
  if (options.model && (options.sessionFile || options.forkSessionFile)) {
18843
18389
  throw new Error("Omp RPC cannot combine a startup Model with Session restore or Fork");
18844
18390
  }
18845
- this.#options = {
18846
- commandTimeoutMs: 3e4,
18847
- compactionTimeoutMs: 3e5,
18848
- // Native Abort waits for tools, persistence and deferred work to unwind.
18849
- // Stable cancellation must outlast the Host's 20s steering wait.
18850
- cancelTimeoutMs: 3e4,
18851
- closeTimeoutMs: 2e3,
18852
- ...options
18853
- };
18854
- this.#processAdapter = processAdapter;
18391
+ this.#options = {
18392
+ commandTimeoutMs: 3e4,
18393
+ compactionTimeoutMs: 3e5,
18394
+ // Native Abort waits for tools, persistence and deferred work to unwind.
18395
+ // Stable cancellation must outlast the Host's 20s steering wait.
18396
+ cancelTimeoutMs: 3e4,
18397
+ closeTimeoutMs: 2e3,
18398
+ ...options
18399
+ };
18400
+ this.#processAdapter = processAdapter;
18401
+ }
18402
+ get state() {
18403
+ if (!this.#state)
18404
+ throw new Error("Omp RPC Session has not started");
18405
+ return this.#state;
18406
+ }
18407
+ get stderrTail() {
18408
+ return this.#stderrTail;
18409
+ }
18410
+ async start() {
18411
+ if (this.#child || this.#closed)
18412
+ throw new Error("Omp RPC Session cannot be started twice");
18413
+ const child = this.#processAdapter.spawn({
18414
+ cwd: this.#options.cwd,
18415
+ ...this.#options.command ? { command: this.#options.command } : {},
18416
+ environment: withNodeRuntimeOnPath({
18417
+ ...process.env,
18418
+ ...this.#options.environment,
18419
+ OMP_SKIP_VERSION_CHECK: "1",
18420
+ OMP_TELEMETRY: "0"
18421
+ }),
18422
+ ...this.#options.sessionFile ? { sessionFile: this.#options.sessionFile } : {},
18423
+ ...this.#options.forkSessionFile ? { forkSessionFile: this.#options.forkSessionFile } : {},
18424
+ ...this.#options.model ? { model: this.#options.model } : {},
18425
+ ...this.#options.permissionMode ? { permissionMode: this.#options.permissionMode } : {}
18426
+ });
18427
+ this.#child = child;
18428
+ child.stdout.on("data", (chunk) => this.#push(chunk));
18429
+ child.stdout.on("end", () => {
18430
+ if (this.#buffer.length !== 0) {
18431
+ this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC stdout ended mid-frame"));
18432
+ }
18433
+ });
18434
+ child.stderr.on("data", (chunk) => {
18435
+ this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
18436
+ });
18437
+ child.once("error", (error51) => {
18438
+ const kind = isRecord8(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
18439
+ this.#fail(new OmpRpcFaultError(kind, `Omp RPC failed to start: ${error51.message}`, this.stderrTail));
18440
+ });
18441
+ child.once("exit", (code, signal) => {
18442
+ if (!this.#closed) {
18443
+ this.#fail(new OmpRpcFaultError("processExited", `Omp RPC exited (code=${code}, signal=${signal})`, this.stderrTail));
18444
+ }
18445
+ });
18446
+ await Promise.race([
18447
+ new Promise((resolve, reject) => {
18448
+ child.once("spawn", resolve);
18449
+ child.once("error", reject);
18450
+ }),
18451
+ new Promise((_resolve, reject) => setTimeout(() => reject(new Error("Omp RPC start timed out")), this.#options.commandTimeoutMs))
18452
+ ]);
18453
+ let readyTimeout;
18454
+ try {
18455
+ await Promise.race([
18456
+ this.#ready,
18457
+ this.#startupFault.then((error51) => {
18458
+ throw error51;
18459
+ }),
18460
+ new Promise((_resolve, reject) => {
18461
+ readyTimeout = setTimeout(() => reject(new Error("Omp RPC ready signal timed out")), this.#options.commandTimeoutMs);
18462
+ })
18463
+ ]);
18464
+ } finally {
18465
+ clearTimeout(readyTimeout);
18466
+ }
18467
+ await this.#send("negotiate_protocol", { protocolVersion: 2 }).catch(() => void 0);
18468
+ if (this.#options.subscribeSubagentEvents !== false) {
18469
+ await this.#send("set_subagent_subscription", { level: "events" }).catch(() => void 0);
18470
+ }
18471
+ try {
18472
+ this.#state = parseSessionState(await this.#send("get_state", {}));
18473
+ } catch (error51) {
18474
+ const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("unavailable", `Omp RPC state unavailable: ${message2(error51)}`);
18475
+ this.#fail(fault);
18476
+ throw fault;
18477
+ }
18478
+ return this;
18479
+ }
18480
+ async getEntries() {
18481
+ try {
18482
+ if (this.state.sessionFile) {
18483
+ try {
18484
+ return await readOmpSessionHistory(this.state.sessionFile);
18485
+ } catch (error51) {
18486
+ if (!isRecord8(error51) || error51.code !== "ENOENT" || this.#options.sessionFile || this.#options.forkSessionFile)
18487
+ throw error51;
18488
+ const response2 = await this.#send("get_messages", {});
18489
+ const data2 = isRecord8(response2.data) ? response2.data : null;
18490
+ if (data2 && Array.isArray(data2.messages) && data2.messages.length === 0) {
18491
+ return { entries: [], leafId: null };
18492
+ }
18493
+ throw error51;
18494
+ }
18495
+ }
18496
+ const response = await this.#send("get_messages", {});
18497
+ const data = isRecord8(response.data) ? response.data : null;
18498
+ if (!data || !Array.isArray(data.messages)) {
18499
+ throw new OmpRpcFaultError("protocolError", "Omp RPC messages response has no messages");
18500
+ }
18501
+ let branchEntryIds = null;
18502
+ try {
18503
+ const branchResponse = await this.#send("get_branch_messages", {});
18504
+ const branchData = isRecord8(branchResponse.data) ? branchResponse.data : null;
18505
+ if (branchData && Array.isArray(branchData.messages)) {
18506
+ const parsed = branchData.messages.flatMap((entry) => {
18507
+ if (!isRecord8(entry) || !nonBlankString(entry.entryId))
18508
+ return [];
18509
+ return [entry.entryId];
18510
+ });
18511
+ if (parsed.length === branchData.messages.length)
18512
+ branchEntryIds = parsed;
18513
+ }
18514
+ } catch (error51) {
18515
+ if (!(error51 instanceof OmpRpcUnsupportedCommandError))
18516
+ throw error51;
18517
+ }
18518
+ let userIndex = 0;
18519
+ let parentId = null;
18520
+ const entries = data.messages.map((nativeMessage, index) => {
18521
+ const role = isRecord8(nativeMessage) ? nativeMessage.role : void 0;
18522
+ const branchId = role === "user" ? branchEntryIds?.[userIndex] : void 0;
18523
+ if (branchId)
18524
+ userIndex += 1;
18525
+ const id = branchId ?? (isRecord8(nativeMessage) && nonBlankString(nativeMessage.id) ? nativeMessage.id : `omp-message-${index}`);
18526
+ const entry = { id, parentId, type: "message", message: nativeMessage };
18527
+ parentId = id;
18528
+ return entry;
18529
+ });
18530
+ return { entries, leafId: parentId };
18531
+ } catch (error51) {
18532
+ if (error51 instanceof OmpRpcFaultError)
18533
+ this.#fail(error51);
18534
+ throw error51;
18535
+ }
18536
+ }
18537
+ async getSubagentMessages(input) {
18538
+ if ((input.subagentId === void 0 || !nonBlankString(input.subagentId)) && (input.sessionFile === void 0 || !nonBlankString(input.sessionFile))) {
18539
+ throw new Error("Omp Subagent transcript requires a Subagent ID or Session file");
18540
+ }
18541
+ if (input.fromByte !== void 0 && (!Number.isSafeInteger(input.fromByte) || input.fromByte < 0)) {
18542
+ throw new Error("Omp Subagent transcript offset is invalid");
18543
+ }
18544
+ const response = await this.#send("get_subagent_messages", {
18545
+ ...input.subagentId ? { subagentId: input.subagentId } : {},
18546
+ ...input.sessionFile ? { sessionFile: input.sessionFile } : {},
18547
+ ...input.fromByte !== void 0 ? { fromByte: input.fromByte } : {}
18548
+ });
18549
+ return parseSubagentMessages(response);
18550
+ }
18551
+ async compact(customInstructions, onEvent) {
18552
+ if (!this.#child || !this.#state || this.#closed || this.#failed) {
18553
+ throw new Error("Omp RPC Session is unavailable");
18554
+ }
18555
+ if (this.#activeTurn || this.#manualCompaction || this.#compactionActive) {
18556
+ throw new Error("Omp RPC Session already has an active operation");
18557
+ }
18558
+ const result = new Promise((resolve, reject) => {
18559
+ this.#manualCompaction = { onEvent, resolve, reject };
18560
+ });
18561
+ try {
18562
+ await this.#send("compact", customInstructions ? { customInstructions } : {});
18563
+ } catch (error51) {
18564
+ const pending = this.#manualCompaction;
18565
+ this.#manualCompaction = null;
18566
+ pending?.reject(error51 instanceof Error ? error51 : new Error(message2(error51)));
18567
+ }
18568
+ return result;
18569
+ }
18570
+ async getSessionUsage() {
18571
+ try {
18572
+ const usage = parseOmpSessionUsage(await this.#send("get_session_stats", {}));
18573
+ await this.#ensureLatestCacheHitRate();
18574
+ return this.#withLatestCacheHitRate(usage);
18575
+ } catch (error51) {
18576
+ if (!(error51 instanceof OmpRpcUnsupportedCommandError))
18577
+ throw error51;
18578
+ const response = await this.#send("get_state", {});
18579
+ const observedState = parseSessionState(response);
18580
+ if (!this.#state || observedState.sessionId !== this.#state.sessionId || observedState.provider !== this.#state.provider || observedState.modelId !== this.#state.modelId) {
18581
+ throw new Error("Omp RPC Usage fallback does not match the confirmed Session state");
18582
+ }
18583
+ await this.#ensureLatestCacheHitRate();
18584
+ const usage = parseOmpStateContextUsage(response);
18585
+ return usage ? this.#withLatestCacheHitRate(usage) : null;
18586
+ }
18855
18587
  }
18856
- get state() {
18857
- if (!this.#state)
18858
- throw new Error("Omp RPC Session has not started");
18859
- return this.#state;
18588
+ async #ensureLatestCacheHitRate() {
18589
+ if (this.#latestCacheHitRatePercent !== void 0)
18590
+ return;
18591
+ try {
18592
+ this.#latestCacheHitRatePercent = latestOmpCacheHitRatePercent(await this.getEntries());
18593
+ } catch {
18594
+ this.#latestCacheHitRatePercent = null;
18595
+ }
18860
18596
  }
18861
- get stderrTail() {
18862
- return this.#stderrTail;
18597
+ #withLatestCacheHitRate(usage) {
18598
+ return this.#latestCacheHitRatePercent === null || this.#latestCacheHitRatePercent === void 0 ? usage : parseHostUsage({ ...usage, cacheHitRatePercent: this.#latestCacheHitRatePercent });
18863
18599
  }
18864
- async start() {
18865
- if (this.#child || this.#closed)
18866
- throw new Error("Omp RPC Session cannot be started twice");
18867
- const child = this.#processAdapter.spawn({
18868
- cwd: this.#options.cwd,
18869
- ...this.#options.command ? { command: this.#options.command } : {},
18870
- environment: withNodeRuntimeOnPath({
18871
- ...process.env,
18872
- ...this.#options.environment,
18873
- OMP_SKIP_VERSION_CHECK: "1",
18874
- OMP_TELEMETRY: "0"
18875
- }),
18876
- ...this.#options.sessionFile ? { sessionFile: this.#options.sessionFile } : {},
18877
- ...this.#options.forkSessionFile ? { forkSessionFile: this.#options.forkSessionFile } : {},
18878
- ...this.#options.model ? { model: this.#options.model } : {},
18879
- ...this.#options.permissionMode ? { permissionMode: this.#options.permissionMode } : {}
18880
- });
18881
- this.#child = child;
18882
- child.stdout.on("data", (chunk) => this.#push(chunk));
18883
- child.stdout.on("end", () => {
18884
- if (this.#buffer.length !== 0) {
18885
- this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC stdout ended mid-frame"));
18600
+ async fork(entryId) {
18601
+ if (!nonBlankString(entryId))
18602
+ throw new Error("Omp RPC Fork requires an Entry identity");
18603
+ try {
18604
+ const response = await this.#send("branch", { entryId });
18605
+ const data = isRecord8(response.data) ? response.data : null;
18606
+ if (!data || data.cancelled === true) {
18607
+ throw new OmpRpcFaultError("unavailable", "Omp RPC Fork was cancelled");
18886
18608
  }
18609
+ this.#state = parseSessionState(await this.#send("get_state", {}));
18610
+ return this.#state;
18611
+ } catch (error51) {
18612
+ if (error51 instanceof OmpRpcFaultError)
18613
+ this.#fail(error51);
18614
+ throw error51;
18615
+ }
18616
+ }
18617
+ verifySessionCwd(expectedCwd) {
18618
+ return verifyOmpSessionCwd({
18619
+ sessionFile: this.state.sessionFile,
18620
+ sessionId: this.state.sessionId,
18621
+ expectedCwd
18887
18622
  });
18888
- child.stderr.on("data", (chunk) => {
18889
- this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
18890
- });
18891
- child.once("error", (error51) => {
18892
- const kind = isRecord8(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
18893
- this.#fail(new OmpRpcFaultError(kind, `Omp RPC failed to start: ${error51.message}`, this.stderrTail));
18894
- });
18895
- child.once("exit", (code, signal) => {
18896
- if (!this.#closed) {
18897
- this.#fail(new OmpRpcFaultError("processExited", `Omp RPC exited (code=${code}, signal=${signal})`, this.stderrTail));
18898
- }
18623
+ }
18624
+ async getAvailableModels() {
18625
+ try {
18626
+ return parseAvailableModels(await this.#send("get_available_models", {}));
18627
+ } catch (error51) {
18628
+ if (error51 instanceof OmpRpcFaultError)
18629
+ this.#fail(error51);
18630
+ throw error51;
18631
+ }
18632
+ }
18633
+ async getAvailableThinkingLevels() {
18634
+ return this.state.availableThinkingLevels;
18635
+ }
18636
+ async selectModel(model2) {
18637
+ await this.#send("set_model", { provider: model2.provider, modelId: model2.id });
18638
+ return this.#refreshState("Model");
18639
+ }
18640
+ async selectThinkingOption(thinkingOptionId) {
18641
+ const level = harnessThinkingOptionIdSchema.parse(thinkingOptionId);
18642
+ await this.#send("set_thinking_level", { level });
18643
+ return this.#refreshState("Thinking");
18644
+ }
18645
+ async #refreshState(operation) {
18646
+ try {
18647
+ this.#state = parseSessionState(await this.#send("get_state", {}));
18648
+ return this.#state;
18649
+ } catch (error51) {
18650
+ const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC ${operation} state could not be confirmed: ${message2(error51)}`);
18651
+ this.#fail(fault);
18652
+ throw fault;
18653
+ }
18654
+ }
18655
+ async runTurn(text, onEvent) {
18656
+ if (!this.#child || !this.#state || this.#closed || this.#failed) {
18657
+ throw new Error("Omp RPC Session is unavailable");
18658
+ }
18659
+ if (this.#activeTurn)
18660
+ throw new Error("Omp RPC Session already has an active Turn");
18661
+ if (text.length === 0)
18662
+ throw new Error("Omp text Turn must not be empty");
18663
+ const promptId = `codexhost-${randomUUID()}`;
18664
+ const settled = new Promise((resolve, reject) => {
18665
+ this.#activeTurn = {
18666
+ promptId,
18667
+ localResult: null,
18668
+ text: "",
18669
+ assistantMessageId: null,
18670
+ sawStreamedMessageText: false,
18671
+ sawStreamedMessageReasoning: false,
18672
+ lastFinalizedMessageText: null,
18673
+ lastFinalizedMessageReasoning: null,
18674
+ reasoningMessageOpen: false,
18675
+ onEvent,
18676
+ resolve,
18677
+ reject,
18678
+ failure: null,
18679
+ sawTool: false,
18680
+ tools: /* @__PURE__ */ new Map(),
18681
+ interactions: /* @__PURE__ */ new Map(),
18682
+ settlement: "pending",
18683
+ terminalEnd: false,
18684
+ cancellation: "none",
18685
+ cancellationTimeout: null,
18686
+ cancellationRecheck: null,
18687
+ cancellationChecking: false,
18688
+ cancellationReloaded: false,
18689
+ abortPromise: null
18690
+ };
18899
18691
  });
18900
- await Promise.race([
18901
- new Promise((resolve, reject) => {
18902
- child.once("spawn", resolve);
18903
- child.once("error", reject);
18904
- }),
18905
- new Promise((_resolve, reject) => setTimeout(() => reject(new Error("Omp RPC start timed out")), this.#options.commandTimeoutMs))
18906
- ]);
18907
- let readyTimeout;
18908
18692
  try {
18909
- await Promise.race([
18910
- this.#ready,
18911
- this.#startupFault.then((error51) => {
18912
- throw error51;
18913
- }),
18914
- new Promise((_resolve, reject) => {
18915
- readyTimeout = setTimeout(() => reject(new Error("Omp RPC ready signal timed out")), this.#options.commandTimeoutMs);
18916
- })
18917
- ]);
18918
- } finally {
18919
- clearTimeout(readyTimeout);
18693
+ await this.#send("prompt", { message: text }, promptId);
18694
+ } catch (error51) {
18695
+ this.#rejectActiveTurn(error51 instanceof Error ? error51 : new Error(message2(error51)));
18920
18696
  }
18921
- await this.#send("negotiate_protocol", { protocolVersion: 2 }).catch(() => void 0);
18922
- if (this.#options.subscribeSubagentEvents !== false) {
18923
- await this.#send("set_subagent_subscription", { level: "events" }).catch(() => void 0);
18697
+ return settled;
18698
+ }
18699
+ respondToInteraction(response) {
18700
+ return this.#resolveInteraction(response, "cancelled" in response ? "cancelled" : "responded");
18701
+ }
18702
+ async #resolveInteraction(response, reason) {
18703
+ const active = this.#activeTurn;
18704
+ const pending = active?.interactions.get(response.requestId);
18705
+ if (!active || !pending || this.#closed || this.#failed) {
18706
+ throw new Error("Omp RPC interaction is not pending");
18707
+ }
18708
+ if ("value" in response && !["select", "input", "editor"].includes(pending.request.method)) {
18709
+ throw new Error("Omp RPC interaction response type does not match the request");
18710
+ }
18711
+ if ("confirmed" in response && pending.request.method !== "confirm") {
18712
+ throw new Error("Omp RPC confirmation does not match the request");
18713
+ }
18714
+ const frame = "cancelled" in response ? {
18715
+ type: "extension_ui_response",
18716
+ id: response.requestId,
18717
+ cancelled: true,
18718
+ ...reason === "expired" ? { timedOut: true } : {}
18719
+ } : "confirmed" in response ? { type: "extension_ui_response", id: response.requestId, confirmed: response.confirmed } : { type: "extension_ui_response", id: response.requestId, value: response.value };
18720
+ if (!active.interactions.delete(response.requestId)) {
18721
+ throw new Error("Omp RPC interaction is not pending");
18924
18722
  }
18723
+ if (pending.timeout)
18724
+ clearTimeout(pending.timeout);
18725
+ active.onEvent({ type: "interaction.closed", requestId: response.requestId, reason });
18925
18726
  try {
18926
- this.#state = parseSessionState(await this.#send("get_state", {}));
18727
+ await this.#write(frame);
18927
18728
  } catch (error51) {
18928
- const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("unavailable", `Omp RPC state unavailable: ${message2(error51)}`);
18729
+ const fault = new OmpRpcFaultError("protocolError", `Omp RPC interaction response failed: ${message2(error51)}`);
18929
18730
  this.#fail(fault);
18930
18731
  throw fault;
18931
18732
  }
18932
- return this;
18933
18733
  }
18934
- async getEntries() {
18935
- try {
18936
- if (this.state.sessionFile) {
18937
- try {
18938
- return await readOmpSessionHistory(this.state.sessionFile);
18939
- } catch (error51) {
18940
- if (!isRecord8(error51) || error51.code !== "ENOENT" || this.#options.sessionFile || this.#options.forkSessionFile)
18941
- throw error51;
18942
- const response2 = await this.#send("get_messages", {});
18943
- const data2 = isRecord8(response2.data) ? response2.data : null;
18944
- if (data2 && Array.isArray(data2.messages) && data2.messages.length === 0) {
18945
- return { entries: [], leafId: null };
18946
- }
18947
- throw error51;
18948
- }
18949
- }
18950
- const response = await this.#send("get_messages", {});
18951
- const data = isRecord8(response.data) ? response.data : null;
18952
- if (!data || !Array.isArray(data.messages)) {
18953
- throw new OmpRpcFaultError("protocolError", "Omp RPC messages response has no messages");
18734
+ abort() {
18735
+ const active = this.#activeTurn;
18736
+ if (!active || this.#closed || this.#failed) {
18737
+ return Promise.reject(new Error("Omp RPC Session has no cancellable Turn"));
18738
+ }
18739
+ if (active.abortPromise)
18740
+ return active.abortPromise;
18741
+ active.cancellation = "requesting";
18742
+ active.cancellationTimeout = setTimeout(() => {
18743
+ this.#terminateFailedCancellation(active, new OmpRpcFaultError("protocolError", "Omp Turn cancellation did not settle within its bound"));
18744
+ }, this.#options.cancelTimeoutMs);
18745
+ const aborting = this.#send("abort", {}).then(async () => {
18746
+ if (this.#activeTurn !== active)
18747
+ return;
18748
+ active.cancellation = "accepted";
18749
+ await this.#confirmCancelledTurn(active);
18750
+ }).catch((error51) => {
18751
+ if (this.#activeTurn !== active)
18752
+ throw error51;
18753
+ const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC Abort failed: ${message2(error51)}`);
18754
+ this.#terminateFailedCancellation(active, fault);
18755
+ throw fault;
18756
+ });
18757
+ active.abortPromise = aborting;
18758
+ return aborting;
18759
+ }
18760
+ #terminateFailedCancellation(active, fault) {
18761
+ if (this.#activeTurn !== active)
18762
+ return;
18763
+ if (active.cancellationTimeout)
18764
+ clearTimeout(active.cancellationTimeout);
18765
+ active.cancellationTimeout = null;
18766
+ this.#fail(fault);
18767
+ void this.close().catch(() => void 0);
18768
+ }
18769
+ close() {
18770
+ if (!this.#closed) {
18771
+ this.#closed = true;
18772
+ this.#rejectAll(new Error("Omp RPC Session closed"));
18773
+ }
18774
+ this.#closePromise ??= this.#stopProcess();
18775
+ return this.#closePromise;
18776
+ }
18777
+ async #stopProcess() {
18778
+ const child = this.#child;
18779
+ if (!child)
18780
+ return;
18781
+ if (child.stdin.writable)
18782
+ child.stdin.end();
18783
+ if (await waitForExit(child, this.#options.closeTimeoutMs))
18784
+ return;
18785
+ signalProcessTree(child, "SIGTERM");
18786
+ if (await waitForExit(child, this.#options.closeTimeoutMs))
18787
+ return;
18788
+ signalProcessTree(child, "SIGKILL");
18789
+ if (!await waitForExit(child, this.#options.closeTimeoutMs)) {
18790
+ throw new Error("Omp RPC process tree did not exit within cleanup bounds");
18791
+ }
18792
+ }
18793
+ #push(chunk) {
18794
+ this.#buffer = this.#buffer.length === 0 ? chunk : Buffer.concat([this.#buffer, chunk]);
18795
+ let newline = this.#buffer.indexOf(10);
18796
+ while (newline >= 0) {
18797
+ const frame = this.#buffer.subarray(0, newline);
18798
+ this.#buffer = this.#buffer.subarray(newline + 1);
18799
+ let parsed;
18800
+ try {
18801
+ parsed = JSON.parse(textDecoder.decode(frame));
18802
+ } catch (error51) {
18803
+ this.#fail(new OmpRpcFaultError("protocolError", `Omp RPC returned invalid JSONL: ${message2(error51)}`));
18804
+ newline = this.#buffer.indexOf(10);
18805
+ continue;
18954
18806
  }
18955
- let branchEntryIds = null;
18956
18807
  try {
18957
- const branchResponse = await this.#send("get_branch_messages", {});
18958
- const branchData = isRecord8(branchResponse.data) ? branchResponse.data : null;
18959
- if (branchData && Array.isArray(branchData.messages)) {
18960
- const parsed = branchData.messages.flatMap((entry) => {
18961
- if (!isRecord8(entry) || !nonBlankString(entry.entryId))
18962
- return [];
18963
- return [entry.entryId];
18964
- });
18965
- if (parsed.length === branchData.messages.length)
18966
- branchEntryIds = parsed;
18808
+ const decoded = this.#frameDecoder.push(parsed);
18809
+ if (decoded === null) {
18810
+ newline = this.#buffer.indexOf(10);
18811
+ continue;
18812
+ }
18813
+ const value = decoded;
18814
+ if (!isRecord8(value) || typeof value.type !== "string") {
18815
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid envelope");
18967
18816
  }
18817
+ this.#handle(value);
18968
18818
  } catch (error51) {
18969
- if (!(error51 instanceof OmpRpcUnsupportedCommandError))
18970
- throw error51;
18819
+ this.#fail(error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC frame handling failed: ${message2(error51)}`));
18971
18820
  }
18972
- let userIndex = 0;
18973
- let parentId = null;
18974
- const entries = data.messages.map((nativeMessage, index) => {
18975
- const role = isRecord8(nativeMessage) ? nativeMessage.role : void 0;
18976
- const branchId = role === "user" ? branchEntryIds?.[userIndex] : void 0;
18977
- if (branchId)
18978
- userIndex += 1;
18979
- const id = branchId ?? (isRecord8(nativeMessage) && nonBlankString(nativeMessage.id) ? nativeMessage.id : `omp-message-${index}`);
18980
- const entry = { id, parentId, type: "message", message: nativeMessage };
18981
- parentId = id;
18982
- return entry;
18983
- });
18984
- return { entries, leafId: parentId };
18985
- } catch (error51) {
18986
- if (error51 instanceof OmpRpcFaultError)
18987
- this.#fail(error51);
18988
- throw error51;
18821
+ newline = this.#buffer.indexOf(10);
18989
18822
  }
18990
18823
  }
18991
- async getSubagentMessages(input) {
18992
- if ((input.subagentId === void 0 || !nonBlankString(input.subagentId)) && (input.sessionFile === void 0 || !nonBlankString(input.sessionFile))) {
18993
- throw new Error("Omp Subagent transcript requires a Subagent ID or Session file");
18824
+ /** Latest `available_commands_update` of the running process, if any. */
18825
+ get availableCommands() {
18826
+ return this.#availableCommands;
18827
+ }
18828
+ #handle(value) {
18829
+ if (this.#closed || this.#failed)
18830
+ return;
18831
+ if (value.type === "available_commands_update") {
18832
+ this.#availableCommands = parseOmpAvailableCommands(value.commands);
18833
+ return;
18994
18834
  }
18995
- if (input.fromByte !== void 0 && (!Number.isSafeInteger(input.fromByte) || input.fromByte < 0)) {
18996
- throw new Error("Omp Subagent transcript offset is invalid");
18835
+ if (value.type === "ready") {
18836
+ this.#readyResolve?.();
18837
+ this.#readyResolve = null;
18838
+ return;
18839
+ }
18840
+ if (value.type === "response") {
18841
+ this.#handleResponse(value);
18842
+ return;
18843
+ }
18844
+ if (value.type === "auto_compaction_start" || value.type === "compaction_start") {
18845
+ this.#compactionActive = true;
18846
+ this.#compactionTurn = this.#activeTurn;
18847
+ this.#compactionTimeout ??= setTimeout(() => {
18848
+ this.#compactionTimeout = null;
18849
+ this.#fail(new OmpRpcFaultError("protocolError", `Omp RPC compaction timed out after ${this.#options.compactionTimeoutMs}ms`));
18850
+ }, this.#options.compactionTimeoutMs);
18851
+ const onEvent = this.#activeTurn?.onEvent ?? this.#manualCompaction?.onEvent;
18852
+ onEvent?.({ type: "compaction.started" });
18853
+ for (const pending of this.#pending.values()) {
18854
+ if (pending.command !== "prompt" && pending.command !== "compact" || !pending.timeout)
18855
+ continue;
18856
+ clearTimeout(pending.timeout);
18857
+ pending.timeout = null;
18858
+ }
18859
+ return;
18860
+ }
18861
+ if (value.type === "auto_compaction_end" || value.type === "compaction_end") {
18862
+ this.#compactionActive = false;
18863
+ if (this.#compactionTimeout)
18864
+ clearTimeout(this.#compactionTimeout);
18865
+ this.#compactionTimeout = null;
18866
+ const compactionTurn = this.#compactionTurn;
18867
+ this.#compactionTurn = null;
18868
+ for (const [id, pending] of this.#pending) {
18869
+ if (pending.command === "prompt" || pending.command === "compact") {
18870
+ this.#armCommandTimeout(id, pending);
18871
+ }
18872
+ }
18873
+ const outcome = value.aborted === true ? "cancelled" : isRecord8(value.result) ? "succeeded" : "failed";
18874
+ const event = {
18875
+ type: "compaction.completed",
18876
+ outcome,
18877
+ ...nonBlankString(value.errorMessage) ? { errorMessage: value.errorMessage } : {}
18878
+ };
18879
+ compactionTurn?.onEvent(event);
18880
+ const manual = this.#manualCompaction;
18881
+ this.#manualCompaction = null;
18882
+ manual?.onEvent(event);
18883
+ manual?.resolve({
18884
+ outcome,
18885
+ ...event.errorMessage ? { errorMessage: event.errorMessage } : {}
18886
+ });
18887
+ return;
18888
+ }
18889
+ const active = this.#activeTurn;
18890
+ if (this.#handleSubagentFrame(active, value))
18891
+ return;
18892
+ this.#observeUsage(value);
18893
+ if (value.type === "agent_start" && active)
18894
+ active.terminalEnd = false;
18895
+ if ((value.type === "session_settled" || value.type === "agent_start") && active?.cancellation === "accepted") {
18896
+ void this.#confirmCancelledTurn(active);
18897
+ return;
18898
+ }
18899
+ if (!active) {
18900
+ if (value.type === "extension_ui_request" && this.#isBlockingInteraction(value)) {
18901
+ this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC requested blocking Extension UI outside an active Turn"));
18902
+ }
18903
+ return;
18904
+ }
18905
+ if (value.type === "command_output") {
18906
+ if (active.settlement !== "pending")
18907
+ return;
18908
+ if (typeof value.text !== "string") {
18909
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned invalid command output");
18910
+ }
18911
+ active.text += value.text;
18912
+ active.onEvent({ type: "text.delta", messageId: active.promptId, delta: value.text });
18913
+ return;
18914
+ }
18915
+ if (value.type === "prompt_result") {
18916
+ if (value.id !== active.promptId || value.agentInvoked !== false)
18917
+ return;
18918
+ if (value.status === "completed" || value.status === "aborted") {
18919
+ this.#settleLocalTurn(active, { cancelled: value.status === "aborted" });
18920
+ } else if (value.status === "error" && isRecord8(value.error) && typeof value.error.message === "string") {
18921
+ this.#settleLocalTurn(active, { cancelled: false, error: value.error.message });
18922
+ } else {
18923
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid local prompt result");
18924
+ }
18925
+ return;
18926
+ }
18927
+ if (value.type === "extension_ui_request") {
18928
+ this.#startInteraction(active, value);
18929
+ return;
18930
+ }
18931
+ if (value.type === "message_start" && assistantText(value.message) !== null) {
18932
+ this.#startAssistantMessage(active, value.message);
18933
+ return;
18934
+ }
18935
+ if (value.type === "message_update" && isRecord8(value.assistantMessageEvent)) {
18936
+ const event = value.assistantMessageEvent;
18937
+ const eventType = String(event.type ?? "");
18938
+ const isThinking = eventType === "thinking_delta" || eventType === "reasoning_delta" || eventType === "thought_delta" || eventType === "thinking" || eventType === "reasoning";
18939
+ const isText = eventType === "text_delta" || eventType === "text" || eventType === "content_block_delta";
18940
+ 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;
18941
+ if (isThinking && delta !== null && delta.length > 0) {
18942
+ const messageId = this.#ensureAssistantMessage(active, value.message);
18943
+ active.reasoningMessageOpen = true;
18944
+ active.sawStreamedMessageReasoning = true;
18945
+ active.onEvent({ type: "reasoning.delta", messageId, delta });
18946
+ } else if (isText && delta !== null && delta.length > 0) {
18947
+ const messageId = this.#ensureAssistantMessage(active, value.message);
18948
+ active.text += delta;
18949
+ active.sawStreamedMessageText = true;
18950
+ active.onEvent({ type: "text.delta", messageId, delta });
18951
+ } else if (event.type === "error") {
18952
+ this.#ensureAssistantMessage(active, value.message);
18953
+ active.failure = assistantFailure(event.error) ?? assistantFailure(value.message) ?? new Error("Omp assistant message failed");
18954
+ }
18955
+ return;
18956
+ }
18957
+ if (value.type === "message_end") {
18958
+ this.#finalizeAssistantMessage(active, value.message);
18959
+ return;
18960
+ }
18961
+ if (value.type === "turn_end") {
18962
+ this.#finalizeAssistantMessage(active, value.message);
18963
+ return;
18964
+ }
18965
+ if (value.type === "tool_execution_start") {
18966
+ this.#startTool(active, value);
18967
+ return;
18968
+ }
18969
+ if (value.type === "tool_execution_update") {
18970
+ this.#updateTool(active, value);
18971
+ return;
18972
+ }
18973
+ if (value.type === "tool_execution_end") {
18974
+ this.#completeTool(active, value);
18975
+ return;
18976
+ }
18977
+ if (value.type === "agent_end" && Array.isArray(value.messages)) {
18978
+ for (let index = value.messages.length - 1; index >= 0; index -= 1) {
18979
+ const message3 = value.messages[index];
18980
+ if (!isRecord8(message3) || message3.role !== "assistant")
18981
+ continue;
18982
+ this.#finalizeAssistantMessage(active, message3);
18983
+ break;
18984
+ }
18985
+ }
18986
+ if (value.type === "agent_end" && value.isTerminal !== false) {
18987
+ active.terminalEnd = true;
18988
+ if (active.cancellation !== "none") {
18989
+ if (active.cancellation === "accepted")
18990
+ void this.#confirmCancelledTurn(active);
18991
+ return;
18992
+ }
18993
+ if (active.settlement !== "pending")
18994
+ return;
18995
+ active.settlement = "confirming";
18996
+ void this.#confirmSettledTurn(active);
18997
18997
  }
18998
- const response = await this.#send("get_subagent_messages", {
18999
- ...input.subagentId ? { subagentId: input.subagentId } : {},
19000
- ...input.sessionFile ? { sessionFile: input.sessionFile } : {},
19001
- ...input.fromByte !== void 0 ? { fromByte: input.fromByte } : {}
19002
- });
19003
- return parseSubagentMessages(response);
19004
18998
  }
19005
- async compact(customInstructions, onEvent) {
19006
- if (!this.#child || !this.#state || this.#closed || this.#failed) {
19007
- throw new Error("Omp RPC Session is unavailable");
18999
+ /** Every finished assistant message is one model request, with or without an active Turn. */
19000
+ #observeUsage(value) {
19001
+ if (value.type === "message_start") {
19002
+ this.#usageRequestStartedAtMs = null;
19003
+ return;
19008
19004
  }
19009
- if (this.#activeTurn || this.#manualCompaction || this.#compactionActive) {
19010
- throw new Error("Omp RPC Session already has an active operation");
19005
+ if (value.type === "message_update") {
19006
+ const event = value.assistantMessageEvent;
19007
+ if (this.#usageRequestStartedAtMs === null && isRecord8(event) && typeof event.type === "string" && /^(text|thinking|reasoning|thought|toolcall)_(start|delta)$/u.test(event.type)) {
19008
+ this.#usageRequestStartedAtMs = Date.now();
19009
+ }
19010
+ return;
19011
19011
  }
19012
- const result = new Promise((resolve, reject) => {
19013
- this.#manualCompaction = { onEvent, resolve, reject };
19014
- });
19015
- try {
19016
- await this.#send("compact", customInstructions ? { customInstructions } : {});
19017
- } catch (error51) {
19018
- const pending = this.#manualCompaction;
19019
- this.#manualCompaction = null;
19020
- pending?.reject(error51 instanceof Error ? error51 : new Error(message2(error51)));
19012
+ if (value.type === "message_end" && isRecord8(value.message)) {
19013
+ if (value.message.role !== "assistant")
19014
+ return;
19015
+ const startedAtMs = this.#usageRequestStartedAtMs;
19016
+ this.#usageRequestStartedAtMs = null;
19017
+ this.#options.onUsage?.({
19018
+ message: value.message,
19019
+ startedAtMs,
19020
+ completedAtMs: Date.now()
19021
+ });
19021
19022
  }
19022
- return result;
19023
19023
  }
19024
- async getSessionUsage() {
19025
- try {
19026
- const usage = parseOmpSessionUsage(await this.#send("get_session_stats", {}));
19027
- await this.#ensureLatestCacheHitRate();
19028
- return this.#withLatestCacheHitRate(usage);
19029
- } catch (error51) {
19030
- if (!(error51 instanceof OmpRpcUnsupportedCommandError))
19031
- throw error51;
19032
- const response = await this.#send("get_state", {});
19033
- const observedState = parseSessionState(response);
19034
- if (!this.#state || observedState.sessionId !== this.#state.sessionId || observedState.provider !== this.#state.provider || observedState.modelId !== this.#state.modelId) {
19035
- throw new Error("Omp RPC Usage fallback does not match the confirmed Session state");
19036
- }
19037
- await this.#ensureLatestCacheHitRate();
19038
- const usage = parseOmpStateContextUsage(response);
19039
- return usage ? this.#withLatestCacheHitRate(usage) : null;
19024
+ #handleSubagentFrame(active, value) {
19025
+ if (value.type !== "subagent_lifecycle" && value.type !== "subagent_progress" && value.type !== "subagent_event") {
19026
+ return false;
19040
19027
  }
19041
- }
19042
- async #ensureLatestCacheHitRate() {
19043
- if (this.#latestCacheHitRatePercent !== void 0)
19044
- return;
19045
- try {
19046
- this.#latestCacheHitRatePercent = latestOmpCacheHitRatePercent(await this.getEntries());
19047
- } catch {
19048
- this.#latestCacheHitRatePercent = null;
19028
+ const payload = isRecord8(value.payload) ? value.payload : null;
19029
+ const progressPayload = value.type === "subagent_progress" && payload && isRecord8(payload.progress) ? payload.progress : null;
19030
+ const nativeIdValue = progressPayload?.id ?? payload?.id;
19031
+ if (!payload || !nonBlankString(nativeIdValue)) {
19032
+ throw new OmpRpcFaultError("protocolError", "Omp RPC Subagent frame has no stable ID");
19049
19033
  }
19050
- }
19051
- #withLatestCacheHitRate(usage) {
19052
- return this.#latestCacheHitRatePercent === null || this.#latestCacheHitRatePercent === void 0 ? usage : parseHostUsage({ ...usage, cacheHitRatePercent: this.#latestCacheHitRatePercent });
19053
- }
19054
- async fork(entryId) {
19055
- if (!nonBlankString(entryId))
19056
- throw new Error("Omp RPC Fork requires an Entry identity");
19057
- try {
19058
- const response = await this.#send("branch", { entryId });
19059
- const data = isRecord8(response.data) ? response.data : null;
19060
- if (!data || data.cancelled === true) {
19061
- throw new OmpRpcFaultError("unavailable", "Omp RPC Fork was cancelled");
19034
+ const nativeSubagentId = nativeIdValue;
19035
+ const callId = nativeSubagentId;
19036
+ const emit = active?.onEvent ?? this.#options.onSubagentEvent;
19037
+ if (value.type === "subagent_event") {
19038
+ emit?.({ type: "subagent.transcript.changed", callId, nativeSubagentId });
19039
+ return true;
19040
+ }
19041
+ if (value.type === "subagent_lifecycle") {
19042
+ const status2 = payload.status;
19043
+ if (status2 === "started") {
19044
+ const description = nonBlankString(payload.description) ? payload.description : nonBlankString(payload.agent) ? `${payload.agent} delegation` : "Subagent delegation";
19045
+ emit?.({
19046
+ type: "subagent.started",
19047
+ callId,
19048
+ nativeSubagentId,
19049
+ description,
19050
+ ...nonBlankString(payload.agent) ? { role: payload.agent } : {},
19051
+ ...nonBlankString(payload.task) ? { prompt: payload.task } : {},
19052
+ background: payload.detached === true,
19053
+ ...typeof payload.sessionFile === "string" ? { sessionFile: payload.sessionFile } : {}
19054
+ });
19055
+ return true;
19062
19056
  }
19063
- this.#state = parseSessionState(await this.#send("get_state", {}));
19064
- return this.#state;
19065
- } catch (error51) {
19066
- if (error51 instanceof OmpRpcFaultError)
19067
- this.#fail(error51);
19068
- throw error51;
19057
+ if (status2 !== "completed" && status2 !== "failed" && status2 !== "aborted") {
19058
+ throw new OmpRpcFaultError("protocolError", "Omp RPC Subagent lifecycle status is invalid");
19059
+ }
19060
+ emit?.({
19061
+ type: "subagent.completed",
19062
+ callId,
19063
+ nativeSubagentId,
19064
+ isError: status2 !== "completed",
19065
+ ...nonBlankString(payload.resultSummary) ? { resultSummary: payload.resultSummary } : {},
19066
+ ...typeof payload.sessionFile === "string" ? { sessionFile: payload.sessionFile } : {}
19067
+ });
19068
+ return true;
19069
19069
  }
19070
- }
19071
- verifySessionCwd(expectedCwd) {
19072
- return verifyOmpSessionCwd({
19073
- sessionFile: this.state.sessionFile,
19074
- sessionId: this.state.sessionId,
19075
- expectedCwd
19076
- });
19077
- }
19078
- async getAvailableModels() {
19079
- try {
19080
- return parseAvailableModels(await this.#send("get_available_models", {}));
19081
- } catch (error51) {
19082
- if (error51 instanceof OmpRpcFaultError)
19083
- this.#fail(error51);
19084
- throw error51;
19070
+ const progress = progressPayload;
19071
+ if (!progress || !nonBlankString(progress.id) || progress.id !== nativeSubagentId) {
19072
+ throw new OmpRpcFaultError("protocolError", "Omp RPC Subagent progress is invalid");
19085
19073
  }
19074
+ const status = subagentStatus(progress.status);
19075
+ const recentOutput = Array.isArray(progress.recentOutput) ? progress.recentOutput.filter((item) => typeof item === "string") : [];
19076
+ const resultSummary = recentOutput.at(-1);
19077
+ emit?.({
19078
+ type: "subagent.updated",
19079
+ callId,
19080
+ nativeSubagentId,
19081
+ status,
19082
+ ...nonBlankString(progress.description) ? { description: progress.description } : nonBlankString(payload.task) ? { description: payload.task } : {},
19083
+ ...resultSummary !== void 0 ? { resultSummary } : {},
19084
+ ...typeof payload.sessionFile === "string" ? { sessionFile: payload.sessionFile } : {}
19085
+ });
19086
+ return true;
19086
19087
  }
19087
- async getAvailableThinkingLevels() {
19088
- return this.state.availableThinkingLevels;
19089
- }
19090
- async selectModel(model2) {
19091
- await this.#send("set_model", { provider: model2.provider, modelId: model2.id });
19092
- return this.#refreshState("Model");
19093
- }
19094
- async selectThinkingOption(thinkingOptionId) {
19095
- const level = harnessThinkingOptionIdSchema.parse(thinkingOptionId);
19096
- await this.#send("set_thinking_level", { level });
19097
- return this.#refreshState("Thinking");
19098
- }
19099
- async #refreshState(operation) {
19100
- try {
19101
- this.#state = parseSessionState(await this.#send("get_state", {}));
19102
- return this.#state;
19103
- } catch (error51) {
19104
- const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC ${operation} state could not be confirmed: ${message2(error51)}`);
19105
- this.#fail(fault);
19106
- throw fault;
19107
- }
19088
+ #isBlockingInteraction(value) {
19089
+ return ["select", "confirm", "input", "editor"].includes(String(value.method));
19108
19090
  }
19109
- async runTurn(text, onEvent) {
19110
- if (!this.#child || !this.#state || this.#closed || this.#failed) {
19111
- throw new Error("Omp RPC Session is unavailable");
19091
+ #startInteraction(active, value) {
19092
+ if (!this.#isBlockingInteraction(value))
19093
+ return;
19094
+ const requestId = value.id;
19095
+ const method = value.method;
19096
+ const title = value.title;
19097
+ const timeoutMs = value.timeout;
19098
+ 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)) {
19099
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Interaction request");
19112
19100
  }
19113
- if (this.#activeTurn)
19114
- throw new Error("Omp RPC Session already has an active Turn");
19115
- if (text.length === 0)
19116
- throw new Error("Omp text Turn must not be empty");
19117
- const promptId = `codexhost-${randomUUID()}`;
19118
- const settled = new Promise((resolve, reject) => {
19119
- this.#activeTurn = {
19120
- promptId,
19121
- localResult: null,
19122
- text: "",
19123
- assistantMessageId: null,
19124
- sawStreamedMessageText: false,
19125
- sawStreamedMessageReasoning: false,
19126
- lastFinalizedMessageText: null,
19127
- lastFinalizedMessageReasoning: null,
19128
- reasoningMessageOpen: false,
19129
- onEvent,
19130
- resolve,
19131
- reject,
19132
- failure: null,
19133
- sawTool: false,
19134
- tools: /* @__PURE__ */ new Map(),
19135
- interactions: /* @__PURE__ */ new Map(),
19136
- settlement: "pending",
19137
- terminalEnd: false,
19138
- cancellation: "none",
19139
- cancellationTimeout: null,
19140
- cancellationRecheck: null,
19141
- cancellationChecking: false,
19142
- cancellationReloaded: false,
19143
- abortPromise: null
19101
+ let request;
19102
+ if (method === "select") {
19103
+ if (!Array.isArray(value.options) || value.options.length === 0 || !value.options.every((option) => typeof option === "string" && option.length > 0)) {
19104
+ throw new OmpRpcFaultError("protocolError", "Omp RPC select request has invalid options");
19105
+ }
19106
+ let optionDetails;
19107
+ if (value.optionDetails !== void 0) {
19108
+ 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"))) {
19109
+ throw new OmpRpcFaultError("protocolError", "Omp RPC select option details are invalid");
19110
+ }
19111
+ optionDetails = value.optionDetails.map(({ description }) => description === void 0 ? {} : { description });
19112
+ }
19113
+ request = {
19114
+ requestId,
19115
+ method,
19116
+ title,
19117
+ options: [...value.options],
19118
+ ...optionDetails ? { optionDetails } : {},
19119
+ ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19120
+ };
19121
+ } else if (method === "confirm") {
19122
+ if (typeof value.message !== "string") {
19123
+ throw new OmpRpcFaultError("protocolError", "Omp RPC confirm request has no message");
19124
+ }
19125
+ request = {
19126
+ requestId,
19127
+ method,
19128
+ title,
19129
+ message: value.message,
19130
+ ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19131
+ };
19132
+ } else if (method === "input") {
19133
+ if (value.placeholder !== void 0 && typeof value.placeholder !== "string") {
19134
+ throw new OmpRpcFaultError("protocolError", "Omp RPC input placeholder is invalid");
19135
+ }
19136
+ request = {
19137
+ requestId,
19138
+ method,
19139
+ title,
19140
+ ...typeof value.placeholder === "string" ? { placeholder: value.placeholder } : {},
19141
+ ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19142
+ };
19143
+ } else {
19144
+ if (value.prefill !== void 0 && typeof value.prefill !== "string") {
19145
+ throw new OmpRpcFaultError("protocolError", "Omp RPC editor prefill is invalid");
19146
+ }
19147
+ request = {
19148
+ requestId,
19149
+ method: "editor",
19150
+ title,
19151
+ ...typeof value.prefill === "string" ? { prefill: value.prefill } : {},
19152
+ ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19144
19153
  };
19145
- });
19146
- try {
19147
- await this.#send("prompt", { message: text }, promptId);
19148
- } catch (error51) {
19149
- this.#rejectActiveTurn(error51 instanceof Error ? error51 : new Error(message2(error51)));
19150
- }
19151
- return settled;
19152
- }
19153
- respondToInteraction(response) {
19154
- return this.#resolveInteraction(response, "cancelled" in response ? "cancelled" : "responded");
19155
- }
19156
- async #resolveInteraction(response, reason) {
19157
- const active = this.#activeTurn;
19158
- const pending = active?.interactions.get(response.requestId);
19159
- if (!active || !pending || this.#closed || this.#failed) {
19160
- throw new Error("Omp RPC interaction is not pending");
19161
19154
  }
19162
- if ("value" in response && !["select", "input", "editor"].includes(pending.request.method)) {
19163
- throw new Error("Omp RPC interaction response type does not match the request");
19155
+ const pending = { request, timeout: null };
19156
+ if (request.timeoutMs !== void 0) {
19157
+ pending.timeout = setTimeout(() => {
19158
+ if (this.#activeTurn !== active || !active.interactions.has(requestId))
19159
+ return;
19160
+ void this.#resolveInteraction({ requestId, cancelled: true }, "expired").catch((error51) => {
19161
+ if (this.#closed || this.#failed)
19162
+ return;
19163
+ this.#fail(new OmpRpcFaultError("protocolError", `Omp RPC Interaction timeout handling failed: ${message2(error51)}`));
19164
+ });
19165
+ }, request.timeoutMs);
19164
19166
  }
19165
- if ("confirmed" in response && pending.request.method !== "confirm") {
19166
- throw new Error("Omp RPC confirmation does not match the request");
19167
+ active.interactions.set(requestId, pending);
19168
+ active.onEvent({ type: "interaction.requested", request });
19169
+ }
19170
+ #handleResponse(value) {
19171
+ const id = value.id;
19172
+ if (typeof id !== "string") {
19173
+ this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC response has no id"));
19174
+ return;
19167
19175
  }
19168
- const frame = "cancelled" in response ? {
19169
- type: "extension_ui_response",
19170
- id: response.requestId,
19171
- cancelled: true,
19172
- ...reason === "expired" ? { timedOut: true } : {}
19173
- } : "confirmed" in response ? { type: "extension_ui_response", id: response.requestId, confirmed: response.confirmed } : { type: "extension_ui_response", id: response.requestId, value: response.value };
19174
- if (!active.interactions.delete(response.requestId)) {
19175
- throw new Error("Omp RPC interaction is not pending");
19176
+ const pending = this.#pending.get(id);
19177
+ const active = this.#activeTurn;
19178
+ if (!pending) {
19179
+ if (active?.promptId === id && value.command === "prompt" && value.success === false) {
19180
+ active.failure = new Error(typeof value.error === "string" ? value.error : "Omp RPC command failed");
19181
+ return;
19182
+ }
19183
+ this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC response id is not pending"));
19184
+ return;
19176
19185
  }
19177
19186
  if (pending.timeout)
19178
19187
  clearTimeout(pending.timeout);
19179
- active.onEvent({ type: "interaction.closed", requestId: response.requestId, reason });
19180
- try {
19181
- await this.#write(frame);
19182
- } catch (error51) {
19183
- const fault = new OmpRpcFaultError("protocolError", `Omp RPC interaction response failed: ${message2(error51)}`);
19184
- this.#fail(fault);
19185
- throw fault;
19188
+ this.#pending.delete(id);
19189
+ if (value.success === true) {
19190
+ if (pending.command === "prompt" && active?.promptId === id && isRecord8(value.data) && value.data.agentInvoked === false) {
19191
+ this.#settleLocalTurn(active, { cancelled: false });
19192
+ }
19193
+ pending.resolve(value);
19194
+ } else {
19195
+ const error51 = typeof value.error === "string" ? value.error : "Omp RPC command failed";
19196
+ if (value.command === pending.command && error51 === `Unknown command: ${pending.command}`) {
19197
+ pending.reject(new OmpRpcUnsupportedCommandError(pending.command));
19198
+ } else {
19199
+ pending.reject(new Error(error51));
19200
+ }
19186
19201
  }
19187
19202
  }
19188
- abort() {
19189
- const active = this.#activeTurn;
19190
- if (!active || this.#closed || this.#failed) {
19191
- return Promise.reject(new Error("Omp RPC Session has no cancellable Turn"));
19203
+ #startTool(active, value) {
19204
+ const callId = value.toolCallId;
19205
+ const toolName = value.toolName;
19206
+ const argumentsResult = jsonValueSchema.safeParse(value.args);
19207
+ if (typeof callId !== "string" || callId.length === 0 || typeof toolName !== "string" || toolName.length === 0 || !argumentsResult.success || active.tools.has(callId)) {
19208
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool start");
19192
19209
  }
19193
- if (active.abortPromise)
19194
- return active.abortPromise;
19195
- active.cancellation = "requesting";
19196
- active.cancellationTimeout = setTimeout(() => {
19197
- this.#terminateFailedCancellation(active, new OmpRpcFaultError("protocolError", "Omp Turn cancellation did not settle within its bound"));
19198
- }, this.#options.cancelTimeoutMs);
19199
- const aborting = this.#send("abort", {}).then(async () => {
19200
- if (this.#activeTurn !== active)
19201
- return;
19202
- active.cancellation = "accepted";
19203
- await this.#confirmCancelledTurn(active);
19204
- }).catch((error51) => {
19205
- if (this.#activeTurn !== active)
19206
- throw error51;
19207
- const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC Abort failed: ${message2(error51)}`);
19208
- this.#terminateFailedCancellation(active, fault);
19209
- throw fault;
19210
+ active.sawTool = true;
19211
+ active.tools.set(callId, toolName);
19212
+ active.onEvent({
19213
+ type: "tool.started",
19214
+ callId,
19215
+ toolName,
19216
+ arguments: argumentsResult.data
19210
19217
  });
19211
- active.abortPromise = aborting;
19212
- return aborting;
19213
19218
  }
19214
- #terminateFailedCancellation(active, fault) {
19215
- if (this.#activeTurn !== active)
19219
+ #updateTool(active, value) {
19220
+ const callId = value.toolCallId;
19221
+ if (typeof callId !== "string" || callId.length === 0) {
19222
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool update");
19223
+ }
19224
+ if (!active.tools.has(callId))
19216
19225
  return;
19217
- if (active.cancellationTimeout)
19218
- clearTimeout(active.cancellationTimeout);
19219
- active.cancellationTimeout = null;
19220
- this.#fail(fault);
19221
- void this.close().catch(() => void 0);
19222
- }
19223
- close() {
19224
- if (!this.#closed) {
19225
- this.#closed = true;
19226
- this.#rejectAll(new Error("Omp RPC Session closed"));
19226
+ const outputResult = jsonValueSchema.safeParse(value.partialResult ?? null);
19227
+ if (!outputResult.success) {
19228
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool update");
19227
19229
  }
19228
- this.#closePromise ??= this.#stopProcess();
19229
- return this.#closePromise;
19230
+ active.onEvent({ type: "tool.updated", callId, output: outputResult.data });
19230
19231
  }
19231
- async #stopProcess() {
19232
- const child = this.#child;
19233
- if (!child)
19234
- return;
19235
- if (child.stdin.writable)
19236
- child.stdin.end();
19237
- if (await waitForExit(child, this.#options.closeTimeoutMs))
19238
- return;
19239
- signalProcessTree(child, "SIGTERM");
19240
- if (await waitForExit(child, this.#options.closeTimeoutMs))
19232
+ #completeTool(active, value) {
19233
+ const callId = value.toolCallId;
19234
+ const toolName = value.toolName;
19235
+ if (typeof callId !== "string" || callId.length === 0) {
19236
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool end");
19237
+ }
19238
+ const expectedName = active.tools.get(callId);
19239
+ if (expectedName === void 0)
19241
19240
  return;
19242
- signalProcessTree(child, "SIGKILL");
19243
- if (!await waitForExit(child, this.#options.closeTimeoutMs)) {
19244
- throw new Error("Omp RPC process tree did not exit within cleanup bounds");
19241
+ const result = jsonValueSchema.safeParse(value.result);
19242
+ if (typeof toolName !== "string" || expectedName !== toolName || value.isError !== void 0 && typeof value.isError !== "boolean" || !result.success) {
19243
+ throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool end");
19245
19244
  }
19245
+ active.tools.delete(callId);
19246
+ active.onEvent({
19247
+ type: "tool.completed",
19248
+ callId,
19249
+ toolName,
19250
+ result: result.data,
19251
+ isError: value.isError === true
19252
+ });
19246
19253
  }
19247
- #push(chunk) {
19248
- this.#buffer = this.#buffer.length === 0 ? chunk : Buffer.concat([this.#buffer, chunk]);
19249
- let newline = this.#buffer.indexOf(10);
19250
- while (newline >= 0) {
19251
- const frame = this.#buffer.subarray(0, newline);
19252
- this.#buffer = this.#buffer.subarray(newline + 1);
19253
- let parsed;
19254
- try {
19255
- parsed = JSON.parse(textDecoder.decode(frame));
19256
- } catch (error51) {
19257
- this.#fail(new OmpRpcFaultError("protocolError", `Omp RPC returned invalid JSONL: ${message2(error51)}`));
19258
- newline = this.#buffer.indexOf(10);
19259
- continue;
19254
+ async #confirmCancelledTurn(active) {
19255
+ if (this.#activeTurn !== active || active.cancellation !== "accepted" || active.settlement === "confirming" || active.cancellationChecking)
19256
+ return;
19257
+ active.cancellationChecking = true;
19258
+ if (active.cancellationRecheck)
19259
+ clearTimeout(active.cancellationRecheck);
19260
+ active.cancellationRecheck = null;
19261
+ try {
19262
+ let response = await this.#send("get_state", {});
19263
+ if (this.#activeTurn !== active)
19264
+ return;
19265
+ if (parseSessionStreaming(response)) {
19266
+ await this.#send("abort", {});
19267
+ if (this.#activeTurn !== active)
19268
+ return;
19269
+ response = await this.#send("get_state", {});
19260
19270
  }
19261
- try {
19262
- const decoded = this.#frameDecoder.push(parsed);
19263
- if (decoded === null) {
19264
- newline = this.#buffer.indexOf(10);
19265
- continue;
19271
+ let state = parseSessionState(response);
19272
+ if (this.#activeTurn !== active || active.cancellation !== "accepted")
19273
+ return;
19274
+ const data = sessionStateData(response);
19275
+ 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) {
19276
+ await this.verifySessionCwd(this.#options.cwd);
19277
+ if (this.#activeTurn !== active)
19278
+ return;
19279
+ active.cancellationReloaded = true;
19280
+ const reset = await this.#send("new_session", {});
19281
+ if (this.#activeTurn !== active)
19282
+ return;
19283
+ if (!isRecord8(reset.data) || reset.data.cancelled !== false) {
19284
+ throw new OmpRpcFaultError("unavailable", "Omp cancelled Session reset was refused");
19285
+ }
19286
+ const reloaded = await this.#send("switch_session", { sessionPath: state.sessionFile });
19287
+ if (this.#activeTurn !== active)
19288
+ return;
19289
+ if (!isRecord8(reloaded.data) || reloaded.data.cancelled !== false) {
19290
+ throw new OmpRpcFaultError("unavailable", "Omp cancelled Session reload was refused");
19291
+ }
19292
+ const previous = state;
19293
+ response = await this.#send("get_state", {});
19294
+ state = parseSessionState(response);
19295
+ if (state.sessionId !== previous.sessionId || state.sessionFile !== previous.sessionFile) {
19296
+ throw new OmpRpcFaultError("protocolError", "Omp cancelled Session reload changed its identity");
19297
+ }
19298
+ if (state.provider !== previous.provider || state.modelId !== previous.modelId) {
19299
+ if (!previous.provider || !previous.modelId) {
19300
+ throw new OmpRpcFaultError("protocolError", "Omp cancelled Session has no restorable Model");
19301
+ }
19302
+ await this.#send("set_model", { provider: previous.provider, modelId: previous.modelId });
19266
19303
  }
19267
- const value = decoded;
19268
- if (!isRecord8(value) || typeof value.type !== "string") {
19269
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid envelope");
19304
+ if (previous.thinkingLevel && state.thinkingLevel !== previous.thinkingLevel) {
19305
+ await this.#send("set_thinking_level", { level: previous.thinkingLevel });
19306
+ }
19307
+ response = await this.#send("get_state", {});
19308
+ state = parseSessionState(response);
19309
+ if (state.sessionId !== previous.sessionId || state.sessionFile !== previous.sessionFile || state.provider !== previous.provider || state.modelId !== previous.modelId || previous.thinkingLevel !== null && state.thinkingLevel !== previous.thinkingLevel) {
19310
+ throw new OmpRpcFaultError("protocolError", "Omp cancelled Session reload changed its identity or configuration");
19270
19311
  }
19271
- this.#handle(value);
19272
- } catch (error51) {
19273
- this.#fail(error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC frame handling failed: ${message2(error51)}`));
19274
19312
  }
19275
- newline = this.#buffer.indexOf(10);
19313
+ if (!cancellationSettled(response, active.terminalEnd)) {
19314
+ active.settlement = "pending";
19315
+ active.cancellationRecheck = setTimeout(() => {
19316
+ active.cancellationRecheck = null;
19317
+ void this.#confirmCancelledTurn(active);
19318
+ }, 250);
19319
+ return;
19320
+ }
19321
+ this.#state = state;
19322
+ active.settlement = "confirmed";
19323
+ this.#finishSettledTurn(active);
19324
+ } catch (error51) {
19325
+ if (this.#activeTurn !== active)
19326
+ return;
19327
+ const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC cancelled Turn state could not be confirmed: ${message2(error51)}`);
19328
+ this.#terminateFailedCancellation(active, fault);
19329
+ } finally {
19330
+ active.cancellationChecking = false;
19276
19331
  }
19277
19332
  }
19278
- /** Latest `available_commands_update` of the running process, if any. */
19279
- get availableCommands() {
19280
- return this.#availableCommands;
19281
- }
19282
- #handle(value) {
19283
- if (this.#closed || this.#failed)
19284
- return;
19285
- if (value.type === "available_commands_update") {
19286
- this.#availableCommands = parseOmpAvailableCommands(value.commands);
19287
- return;
19288
- }
19289
- if (value.type === "ready") {
19290
- this.#readyResolve?.();
19291
- this.#readyResolve = null;
19292
- return;
19293
- }
19294
- if (value.type === "response") {
19295
- this.#handleResponse(value);
19296
- return;
19297
- }
19298
- if (value.type === "auto_compaction_start" || value.type === "compaction_start") {
19299
- this.#compactionActive = true;
19300
- this.#compactionTurn = this.#activeTurn;
19301
- this.#compactionTimeout ??= setTimeout(() => {
19302
- this.#compactionTimeout = null;
19303
- this.#fail(new OmpRpcFaultError("protocolError", `Omp RPC compaction timed out after ${this.#options.compactionTimeoutMs}ms`));
19304
- }, this.#options.compactionTimeoutMs);
19305
- const onEvent = this.#activeTurn?.onEvent ?? this.#manualCompaction?.onEvent;
19306
- onEvent?.({ type: "compaction.started" });
19307
- for (const pending of this.#pending.values()) {
19308
- if (pending.command !== "prompt" && pending.command !== "compact" || !pending.timeout)
19309
- continue;
19310
- clearTimeout(pending.timeout);
19311
- pending.timeout = null;
19312
- }
19333
+ #settleLocalTurn(active, result) {
19334
+ if (this.#activeTurn !== active || active.settlement !== "pending")
19313
19335
  return;
19314
- }
19315
- if (value.type === "auto_compaction_end" || value.type === "compaction_end") {
19316
- this.#compactionActive = false;
19317
- if (this.#compactionTimeout)
19318
- clearTimeout(this.#compactionTimeout);
19319
- this.#compactionTimeout = null;
19320
- const compactionTurn = this.#compactionTurn;
19321
- this.#compactionTurn = null;
19322
- for (const [id, pending] of this.#pending) {
19323
- if (pending.command === "prompt" || pending.command === "compact") {
19324
- this.#armCommandTimeout(id, pending);
19325
- }
19336
+ active.localResult = result;
19337
+ active.settlement = "confirming";
19338
+ void this.#confirmSettledTurn(active);
19339
+ }
19340
+ async #confirmSettledTurn(active) {
19341
+ try {
19342
+ const response = await this.#send("get_state", {});
19343
+ const state = parseSessionState(response);
19344
+ if (this.#activeTurn !== active)
19345
+ return;
19346
+ if (active.cancellation !== "none") {
19347
+ active.settlement = "pending";
19348
+ if (active.cancellation === "accepted")
19349
+ void this.#confirmCancelledTurn(active);
19350
+ return;
19326
19351
  }
19327
- const outcome = value.aborted === true ? "cancelled" : isRecord8(value.result) ? "succeeded" : "failed";
19328
- const event = {
19329
- type: "compaction.completed",
19330
- outcome,
19331
- ...nonBlankString(value.errorMessage) ? { errorMessage: value.errorMessage } : {}
19332
- };
19333
- compactionTurn?.onEvent(event);
19334
- const manual = this.#manualCompaction;
19335
- this.#manualCompaction = null;
19336
- manual?.onEvent(event);
19337
- manual?.resolve({
19338
- outcome,
19339
- ...event.errorMessage ? { errorMessage: event.errorMessage } : {}
19340
- });
19341
- return;
19342
- }
19343
- const active = this.#activeTurn;
19344
- if (this.#handleSubagentFrame(active, value))
19345
- return;
19346
- this.#observeUsage(value);
19347
- if (value.type === "agent_start" && active)
19348
- active.terminalEnd = false;
19349
- if ((value.type === "session_settled" || value.type === "agent_start") && active?.cancellation === "accepted") {
19350
- void this.#confirmCancelledTurn(active);
19351
- return;
19352
- }
19353
- if (!active) {
19354
- if (value.type === "extension_ui_request" && this.#isBlockingInteraction(value)) {
19355
- this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC requested blocking Extension UI outside an active Turn"));
19352
+ if (parseSessionStreaming(response)) {
19353
+ throw new OmpRpcFaultError("protocolError", "Omp RPC completed Turn state is still Streaming");
19356
19354
  }
19357
- return;
19358
- }
19359
- if (value.type === "command_output") {
19360
- if (active.settlement !== "pending")
19355
+ this.#state = state;
19356
+ active.settlement = "confirmed";
19357
+ this.#finishSettledTurn(active);
19358
+ } catch (error51) {
19359
+ if (this.#activeTurn !== active)
19361
19360
  return;
19362
- if (typeof value.text !== "string") {
19363
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned invalid command output");
19364
- }
19365
- active.text += value.text;
19366
- active.onEvent({ type: "text.delta", messageId: active.promptId, delta: value.text });
19367
- return;
19361
+ const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC stable Turn state could not be confirmed: ${message2(error51)}`);
19362
+ this.#fail(fault);
19368
19363
  }
19369
- if (value.type === "prompt_result") {
19370
- if (value.id !== active.promptId || value.agentInvoked !== false)
19371
- return;
19372
- if (value.status === "completed" || value.status === "aborted") {
19373
- this.#settleLocalTurn(active, { cancelled: value.status === "aborted" });
19374
- } else if (value.status === "error" && isRecord8(value.error) && typeof value.error.message === "string") {
19375
- this.#settleLocalTurn(active, { cancelled: false, error: value.error.message });
19376
- } else {
19377
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid local prompt result");
19378
- }
19364
+ }
19365
+ #finishSettledTurn(active) {
19366
+ if (this.#activeTurn !== active || active.settlement !== "confirmed" || active.cancellation === "requesting") {
19379
19367
  return;
19380
19368
  }
19381
- if (value.type === "extension_ui_request") {
19382
- this.#startInteraction(active, value);
19369
+ if (active.cancellationTimeout)
19370
+ clearTimeout(active.cancellationTimeout);
19371
+ active.cancellationTimeout = null;
19372
+ if (active.cancellationRecheck)
19373
+ clearTimeout(active.cancellationRecheck);
19374
+ active.cancellationRecheck = null;
19375
+ this.#closeInteractions(active, active.cancellation === "accepted" ? "cancelled" : "superseded");
19376
+ if (active.tools.size > 0) {
19377
+ this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC settled with active Tool executions"));
19383
19378
  return;
19384
19379
  }
19385
- if (value.type === "message_start" && assistantText(value.message) !== null) {
19386
- this.#startAssistantMessage(active, value.message);
19387
- return;
19380
+ this.#activeTurn = null;
19381
+ if (active.localResult) {
19382
+ active.resolve({
19383
+ text: active.text,
19384
+ agentInvoked: false,
19385
+ ...active.localResult,
19386
+ cancelled: active.localResult.cancelled || active.cancellation === "accepted"
19387
+ });
19388
+ } else if (active.cancellation === "accepted") {
19389
+ active.resolve({ text: active.text, cancelled: true, agentInvoked: true });
19390
+ } else if (active.failure) {
19391
+ active.reject(active.failure);
19392
+ } else if (active.text.trim().length === 0 && !active.sawTool) {
19393
+ active.reject(new Error("Omp RPC settled without displayable output"));
19394
+ } else {
19395
+ active.resolve({ text: active.text, cancelled: false, agentInvoked: true });
19388
19396
  }
19389
- if (value.type === "message_update" && isRecord8(value.assistantMessageEvent)) {
19390
- const event = value.assistantMessageEvent;
19391
- const eventType = String(event.type ?? "");
19392
- const isThinking = eventType === "thinking_delta" || eventType === "reasoning_delta" || eventType === "thought_delta" || eventType === "thinking" || eventType === "reasoning";
19393
- const isText = eventType === "text_delta" || eventType === "text" || eventType === "content_block_delta";
19394
- 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;
19395
- if (isThinking && delta !== null && delta.length > 0) {
19396
- const messageId = this.#ensureAssistantMessage(active, value.message);
19397
- active.reasoningMessageOpen = true;
19398
- active.sawStreamedMessageReasoning = true;
19399
- active.onEvent({ type: "reasoning.delta", messageId, delta });
19400
- } else if (isText && delta !== null && delta.length > 0) {
19401
- const messageId = this.#ensureAssistantMessage(active, value.message);
19402
- active.text += delta;
19403
- active.sawStreamedMessageText = true;
19404
- active.onEvent({ type: "text.delta", messageId, delta });
19405
- } else if (event.type === "error") {
19406
- this.#ensureAssistantMessage(active, value.message);
19407
- active.failure = assistantFailure(event.error) ?? assistantFailure(value.message) ?? new Error("Omp assistant message failed");
19408
- }
19409
- return;
19397
+ }
19398
+ #startAssistantMessage(active, value) {
19399
+ if (active.assistantMessageId !== null && active.reasoningMessageOpen) {
19400
+ active.onEvent({ type: "reasoning.completed", messageId: active.assistantMessageId });
19410
19401
  }
19411
- if (value.type === "message_end") {
19412
- this.#finalizeAssistantMessage(active, value.message);
19402
+ const messageId = assistantMessageId(value) ?? randomUUID();
19403
+ active.assistantMessageId = messageId;
19404
+ active.sawStreamedMessageText = false;
19405
+ active.sawStreamedMessageReasoning = false;
19406
+ active.reasoningMessageOpen = false;
19407
+ return messageId;
19408
+ }
19409
+ #ensureAssistantMessage(active, value) {
19410
+ return active.assistantMessageId ?? this.#startAssistantMessage(active, value);
19411
+ }
19412
+ #finalizeAssistantMessage(active, value) {
19413
+ const finalText = assistantText(value);
19414
+ const finalReasoning = assistantReasoning(value);
19415
+ const failure = assistantFailure(value);
19416
+ const cacheHitRatePercent = optionalOmpCacheHitRatePercent(value);
19417
+ if (finalText === null || finalReasoning === null || failure === void 0)
19413
19418
  return;
19414
- }
19415
- if (value.type === "turn_end") {
19416
- this.#finalizeAssistantMessage(active, value.message);
19419
+ if (active.assistantMessageId === null && finalText === active.lastFinalizedMessageText && finalReasoning === active.lastFinalizedMessageReasoning && !active.sawStreamedMessageText && !active.sawStreamedMessageReasoning) {
19417
19420
  return;
19418
19421
  }
19419
- if (value.type === "tool_execution_start") {
19420
- this.#startTool(active, value);
19421
- return;
19422
+ active.failure = failure;
19423
+ this.#latestCacheHitRatePercent = cacheHitRatePercent;
19424
+ const messageId = this.#ensureAssistantMessage(active, value);
19425
+ if (!active.sawStreamedMessageReasoning && finalReasoning.length > 0) {
19426
+ active.reasoningMessageOpen = true;
19427
+ active.onEvent({ type: "reasoning.delta", messageId, delta: finalReasoning });
19422
19428
  }
19423
- if (value.type === "tool_execution_update") {
19424
- this.#updateTool(active, value);
19425
- return;
19429
+ if (active.reasoningMessageOpen && active.failure === null) {
19430
+ active.onEvent({ type: "reasoning.completed", messageId });
19426
19431
  }
19427
- if (value.type === "tool_execution_end") {
19428
- this.#completeTool(active, value);
19429
- return;
19432
+ if (!active.sawStreamedMessageText && finalText.length > 0) {
19433
+ active.text += finalText;
19434
+ active.onEvent({ type: "text.delta", messageId, delta: finalText });
19430
19435
  }
19431
- if (value.type === "agent_end" && Array.isArray(value.messages)) {
19432
- for (let index = value.messages.length - 1; index >= 0; index -= 1) {
19433
- const message3 = value.messages[index];
19434
- if (!isRecord8(message3) || message3.role !== "assistant")
19435
- continue;
19436
- this.#finalizeAssistantMessage(active, message3);
19437
- break;
19438
- }
19436
+ active.assistantMessageId = null;
19437
+ active.sawStreamedMessageText = false;
19438
+ active.sawStreamedMessageReasoning = false;
19439
+ active.reasoningMessageOpen = false;
19440
+ active.lastFinalizedMessageText = finalText;
19441
+ active.lastFinalizedMessageReasoning = finalReasoning;
19442
+ active.onEvent({ type: "message.completed", messageId });
19443
+ }
19444
+ #write(value) {
19445
+ const child = this.#child;
19446
+ if (!child?.stdin.writable || this.#closed || this.#failed) {
19447
+ return Promise.reject(new Error("Omp RPC stdin is unavailable"));
19439
19448
  }
19440
- if (value.type === "agent_end" && value.isTerminal !== false) {
19441
- active.terminalEnd = true;
19442
- if (active.cancellation !== "none") {
19443
- if (active.cancellation === "accepted")
19444
- void this.#confirmCancelledTurn(active);
19445
- return;
19446
- }
19447
- if (active.settlement !== "pending")
19448
- return;
19449
- active.settlement = "confirming";
19450
- void this.#confirmSettledTurn(active);
19449
+ return new Promise((resolve, reject) => {
19450
+ const frame = Buffer.from(`${JSON.stringify(value)}
19451
+ `, "utf8");
19452
+ child.stdin.write(frame, (error51) => error51 ? reject(error51) : resolve());
19453
+ });
19454
+ }
19455
+ #send(type, payload, id = `codexhost-${randomUUID()}`) {
19456
+ const child = this.#child;
19457
+ if (!child?.stdin.writable || this.#closed || this.#failed) {
19458
+ return Promise.reject(new Error("Omp RPC stdin is unavailable"));
19451
19459
  }
19460
+ return new Promise((resolve, reject) => {
19461
+ const pending = {
19462
+ command: type,
19463
+ resolve,
19464
+ reject,
19465
+ timeout: null
19466
+ };
19467
+ this.#pending.set(id, pending);
19468
+ this.#armCommandTimeout(id, pending);
19469
+ const frame = Buffer.from(`${JSON.stringify({ id, type, ...payload })}
19470
+ `, "utf8");
19471
+ child.stdin.write(frame, (error51) => {
19472
+ if (error51) {
19473
+ if (pending.timeout)
19474
+ clearTimeout(pending.timeout);
19475
+ this.#pending.delete(id);
19476
+ reject(error51);
19477
+ }
19478
+ });
19479
+ });
19452
19480
  }
19453
- /** Every finished assistant message is one model request, with or without an active Turn. */
19454
- #observeUsage(value) {
19455
- if (value.type === "message_start") {
19456
- this.#usageRequestStartedAtMs = null;
19481
+ #armCommandTimeout(id, pending) {
19482
+ if (pending.timeout || this.#pending.get(id) !== pending || (pending.command === "prompt" || pending.command === "compact") && this.#compactionActive) {
19457
19483
  return;
19458
19484
  }
19459
- if (value.type === "message_update") {
19460
- const event = value.assistantMessageEvent;
19461
- if (this.#usageRequestStartedAtMs === null && isRecord8(event) && typeof event.type === "string" && /^(text|thinking|reasoning|thought|toolcall)_(start|delta)$/u.test(event.type)) {
19462
- this.#usageRequestStartedAtMs = Date.now();
19485
+ pending.timeout = setTimeout(() => {
19486
+ if (this.#pending.get(id) !== pending)
19487
+ return;
19488
+ pending.timeout = null;
19489
+ const error51 = new Error(`Omp RPC '${pending.command}' command timed out`);
19490
+ if (pending.command !== "prompt") {
19491
+ this.#pending.delete(id);
19492
+ pending.reject(error51);
19493
+ return;
19463
19494
  }
19495
+ const fault = new OmpRpcFaultError("protocolError", error51.message);
19496
+ void this.#terminateTimedOutPrompt(fault);
19497
+ }, this.#options.commandTimeoutMs);
19498
+ }
19499
+ async #terminateTimedOutPrompt(fault) {
19500
+ if (this.#closed || this.#failed)
19464
19501
  return;
19502
+ this.#failed = true;
19503
+ this.#closed = true;
19504
+ for (const pending of this.#pending.values()) {
19505
+ if (pending.timeout)
19506
+ clearTimeout(pending.timeout);
19507
+ pending.timeout = null;
19465
19508
  }
19466
- if (value.type === "message_end" && isRecord8(value.message)) {
19467
- if (value.message.role !== "assistant")
19468
- return;
19469
- const startedAtMs = this.#usageRequestStartedAtMs;
19470
- this.#usageRequestStartedAtMs = null;
19471
- this.#options.onUsage?.({
19472
- message: value.message,
19473
- startedAtMs,
19474
- completedAtMs: Date.now()
19475
- });
19509
+ let finalFault = fault;
19510
+ try {
19511
+ await this.close();
19512
+ } catch (error51) {
19513
+ finalFault = new OmpRpcFaultError("processExited", `Omp RPC timed-out Prompt cleanup failed: ${message2(error51)}`);
19476
19514
  }
19515
+ this.#rejectAll(finalFault);
19516
+ this.#options.onFault?.(finalFault);
19477
19517
  }
19478
- #handleSubagentFrame(active, value) {
19479
- if (value.type !== "subagent_lifecycle" && value.type !== "subagent_progress" && value.type !== "subagent_event") {
19480
- return false;
19481
- }
19482
- const payload = isRecord8(value.payload) ? value.payload : null;
19483
- const progressPayload = value.type === "subagent_progress" && payload && isRecord8(payload.progress) ? payload.progress : null;
19484
- const nativeIdValue = progressPayload?.id ?? payload?.id;
19485
- if (!payload || !nonBlankString(nativeIdValue)) {
19486
- throw new OmpRpcFaultError("protocolError", "Omp RPC Subagent frame has no stable ID");
19518
+ #closeInteractions(active, reason) {
19519
+ for (const [requestId, pending] of active.interactions) {
19520
+ active.interactions.delete(requestId);
19521
+ if (pending.timeout)
19522
+ clearTimeout(pending.timeout);
19523
+ active.onEvent({ type: "interaction.closed", requestId, reason });
19487
19524
  }
19488
- const nativeSubagentId = nativeIdValue;
19489
- const callId = nativeSubagentId;
19490
- const emit = active?.onEvent ?? this.#options.onSubagentEvent;
19491
- if (value.type === "subagent_event") {
19492
- emit?.({ type: "subagent.transcript.changed", callId, nativeSubagentId });
19493
- return true;
19525
+ }
19526
+ #rejectActiveTurn(error51) {
19527
+ const active = this.#activeTurn;
19528
+ if (!active)
19529
+ return;
19530
+ if (active.cancellationTimeout)
19531
+ clearTimeout(active.cancellationTimeout);
19532
+ if (active.cancellationRecheck)
19533
+ clearTimeout(active.cancellationRecheck);
19534
+ this.#closeInteractions(active, "cancelled");
19535
+ this.#activeTurn = null;
19536
+ active.reject(error51);
19537
+ }
19538
+ #rejectAll(error51) {
19539
+ if (this.#compactionTimeout)
19540
+ clearTimeout(this.#compactionTimeout);
19541
+ this.#compactionTimeout = null;
19542
+ for (const pending of this.#pending.values()) {
19543
+ if (pending.timeout)
19544
+ clearTimeout(pending.timeout);
19545
+ pending.reject(error51);
19494
19546
  }
19495
- if (value.type === "subagent_lifecycle") {
19496
- const status2 = payload.status;
19497
- if (status2 === "started") {
19498
- const description = nonBlankString(payload.description) ? payload.description : nonBlankString(payload.agent) ? `${payload.agent} delegation` : "Subagent delegation";
19499
- emit?.({
19500
- type: "subagent.started",
19501
- callId,
19502
- nativeSubagentId,
19503
- description,
19504
- ...nonBlankString(payload.agent) ? { role: payload.agent } : {},
19505
- ...nonBlankString(payload.task) ? { prompt: payload.task } : {},
19506
- background: payload.detached === true,
19507
- ...typeof payload.sessionFile === "string" ? { sessionFile: payload.sessionFile } : {}
19508
- });
19509
- return true;
19510
- }
19511
- if (status2 !== "completed" && status2 !== "failed" && status2 !== "aborted") {
19512
- throw new OmpRpcFaultError("protocolError", "Omp RPC Subagent lifecycle status is invalid");
19547
+ this.#pending.clear();
19548
+ const manual = this.#manualCompaction;
19549
+ this.#manualCompaction = null;
19550
+ manual?.reject(error51);
19551
+ this.#rejectActiveTurn(error51);
19552
+ }
19553
+ #fail(error51) {
19554
+ if (this.#closed || this.#failed)
19555
+ return;
19556
+ this.#failed = true;
19557
+ this.#startupFaultResolve?.(error51);
19558
+ this.#startupFaultResolve = null;
19559
+ this.#rejectAll(error51);
19560
+ this.#options.onFault?.(error51);
19561
+ }
19562
+ };
19563
+
19564
+ // dist/omp-model-list.js
19565
+ var OMP_MODEL_LIST_TIMEOUT_MS = 15e3;
19566
+ var OMP_MODEL_LIST_OUTPUT_LIMIT = 4 * 1024 * 1024;
19567
+ function listOmpModels(input) {
19568
+ const environment = withNodeRuntimeOnPath({
19569
+ ...process.env,
19570
+ ...input.environment,
19571
+ OMP_SKIP_VERSION_CHECK: "1",
19572
+ OMP_TELEMETRY: "0"
19573
+ });
19574
+ const executable = resolveOmpExecutable({
19575
+ ...input.command ? { command: input.command } : {},
19576
+ environment
19577
+ });
19578
+ const invocation = commandInvocation(executable, ["models", "--json"], environment);
19579
+ return new Promise((resolve) => {
19580
+ if (input.signal?.aborted)
19581
+ return resolve({ kind: "unanswered" });
19582
+ const child = spawn2(invocation.command, invocation.arguments, {
19583
+ cwd: input.cwd,
19584
+ env: environment,
19585
+ // A process group lets a stop reach OMP and its descendants, not only a launcher shim.
19586
+ detached: process.platform !== "win32",
19587
+ stdio: ["ignore", "pipe", "ignore"],
19588
+ windowsHide: true,
19589
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments
19590
+ });
19591
+ let settled = false;
19592
+ let stdout = "";
19593
+ const finish = (result, stop = false) => {
19594
+ if (settled)
19595
+ return;
19596
+ settled = true;
19597
+ clearTimeout(timer);
19598
+ input.signal?.removeEventListener("abort", onAbort);
19599
+ child.stdout.removeAllListeners("data");
19600
+ if (stop) {
19601
+ child.stdout.destroy();
19602
+ try {
19603
+ signalProcessTree(child, "SIGKILL");
19604
+ } catch {
19605
+ }
19513
19606
  }
19514
- emit?.({
19515
- type: "subagent.completed",
19516
- callId,
19517
- nativeSubagentId,
19518
- isError: status2 !== "completed",
19519
- ...nonBlankString(payload.resultSummary) ? { resultSummary: payload.resultSummary } : {},
19520
- ...typeof payload.sessionFile === "string" ? { sessionFile: payload.sessionFile } : {}
19521
- });
19522
- return true;
19523
- }
19524
- const progress = progressPayload;
19525
- if (!progress || !nonBlankString(progress.id) || progress.id !== nativeSubagentId) {
19526
- throw new OmpRpcFaultError("protocolError", "Omp RPC Subagent progress is invalid");
19527
- }
19528
- const status = subagentStatus(progress.status);
19529
- const recentOutput = Array.isArray(progress.recentOutput) ? progress.recentOutput.filter((item) => typeof item === "string") : [];
19530
- const resultSummary = recentOutput.at(-1);
19531
- emit?.({
19532
- type: "subagent.updated",
19533
- callId,
19534
- nativeSubagentId,
19535
- status,
19536
- ...nonBlankString(progress.description) ? { description: progress.description } : nonBlankString(payload.task) ? { description: payload.task } : {},
19537
- ...resultSummary !== void 0 ? { resultSummary } : {},
19538
- ...typeof payload.sessionFile === "string" ? { sessionFile: payload.sessionFile } : {}
19607
+ resolve(result);
19608
+ };
19609
+ const onAbort = () => finish({ kind: "unanswered" }, true);
19610
+ input.signal?.addEventListener("abort", onAbort, { once: true });
19611
+ const timer = setTimeout(() => finish({ kind: "timedOut" }, true), input.timeoutMs ?? OMP_MODEL_LIST_TIMEOUT_MS);
19612
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
19613
+ stdout += chunk;
19614
+ if (stdout.length > OMP_MODEL_LIST_OUTPUT_LIMIT)
19615
+ finish({ kind: "unanswered" }, true);
19539
19616
  });
19540
- return true;
19617
+ child.once("error", (error51) => {
19618
+ finish(error51.code === "ENOENT" ? { kind: "notInstalled", message: "Oh My Pi (omp) is not installed" } : { kind: "unanswered" });
19619
+ });
19620
+ child.once("close", (code) => {
19621
+ if (code !== 0)
19622
+ return finish({ kind: "unanswered" });
19623
+ const models = parseOmpModelList(stdout);
19624
+ finish(models ? { kind: "models", models } : { kind: "unanswered" });
19625
+ });
19626
+ });
19627
+ }
19628
+ function parseOmpModelList(output) {
19629
+ let parsed;
19630
+ try {
19631
+ parsed = JSON.parse(output);
19632
+ } catch {
19633
+ return null;
19541
19634
  }
19542
- #isBlockingInteraction(value) {
19543
- return ["select", "confirm", "input", "editor"].includes(String(value.method));
19635
+ if (!isRecord9(parsed) || !Array.isArray(parsed.models))
19636
+ return null;
19637
+ const models = [];
19638
+ for (const model2 of parsed.models) {
19639
+ if (!isRecord9(model2) || !nonBlankString2(model2.provider) || !nonBlankString2(model2.id) || typeof model2.reasoning !== "boolean") {
19640
+ return null;
19641
+ }
19642
+ models.push({ provider: model2.provider, id: model2.id, reasoning: model2.reasoning });
19544
19643
  }
19545
- #startInteraction(active, value) {
19546
- if (!this.#isBlockingInteraction(value))
19547
- return;
19548
- const requestId = value.id;
19549
- const method = value.method;
19550
- const title = value.title;
19551
- const timeoutMs = value.timeout;
19552
- 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)) {
19553
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Interaction request");
19644
+ return models;
19645
+ }
19646
+ function isRecord9(value) {
19647
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19648
+ }
19649
+ function nonBlankString2(value) {
19650
+ return typeof value === "string" && value.trim().length > 0;
19651
+ }
19652
+
19653
+ // ../../../node_modules/diff/libesm/diff/base.js
19654
+ var Diff = class {
19655
+ diff(oldStr, newStr, options = {}) {
19656
+ let callback;
19657
+ if (typeof options === "function") {
19658
+ callback = options;
19659
+ options = {};
19660
+ } else if ("callback" in options) {
19661
+ callback = options.callback;
19554
19662
  }
19555
- let request;
19556
- if (method === "select") {
19557
- if (!Array.isArray(value.options) || value.options.length === 0 || !value.options.every((option) => typeof option === "string" && option.length > 0)) {
19558
- throw new OmpRpcFaultError("protocolError", "Omp RPC select request has invalid options");
19663
+ const oldString = this.castInput(oldStr, options);
19664
+ const newString = this.castInput(newStr, options);
19665
+ const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
19666
+ const newTokens = this.removeEmpty(this.tokenize(newString, options));
19667
+ return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
19668
+ }
19669
+ diffWithOptionsObj(oldTokens, newTokens, options, callback) {
19670
+ var _a3;
19671
+ const done = (value) => {
19672
+ value = this.postProcess(value, options);
19673
+ if (callback) {
19674
+ setTimeout(function() {
19675
+ callback(value);
19676
+ }, 0);
19677
+ return void 0;
19678
+ } else {
19679
+ return value;
19559
19680
  }
19560
- let optionDetails;
19561
- if (value.optionDetails !== void 0) {
19562
- 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"))) {
19563
- throw new OmpRpcFaultError("protocolError", "Omp RPC select option details are invalid");
19681
+ };
19682
+ const newLen = newTokens.length, oldLen = oldTokens.length;
19683
+ let editLength = 1;
19684
+ let maxEditLength = newLen + oldLen;
19685
+ if (options.maxEditLength != null) {
19686
+ maxEditLength = Math.min(maxEditLength, options.maxEditLength);
19687
+ }
19688
+ const maxExecutionTime = (_a3 = options.timeout) !== null && _a3 !== void 0 ? _a3 : Infinity;
19689
+ const abortAfterTimestamp = Date.now() + maxExecutionTime;
19690
+ const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
19691
+ let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
19692
+ if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
19693
+ return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
19694
+ }
19695
+ let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
19696
+ const execEditLength = () => {
19697
+ for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
19698
+ let basePath;
19699
+ const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
19700
+ if (removePath) {
19701
+ bestPath[diagonalPath - 1] = void 0;
19702
+ }
19703
+ let canAdd = false;
19704
+ if (addPath) {
19705
+ const addPathNewPos = addPath.oldPos - diagonalPath;
19706
+ canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
19707
+ }
19708
+ const canRemove = removePath && removePath.oldPos + 1 < oldLen;
19709
+ if (!canAdd && !canRemove) {
19710
+ bestPath[diagonalPath] = void 0;
19711
+ continue;
19712
+ }
19713
+ if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
19714
+ basePath = this.addToPath(addPath, true, false, 0, options);
19715
+ } else {
19716
+ basePath = this.addToPath(removePath, false, true, 1, options);
19717
+ }
19718
+ newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
19719
+ if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
19720
+ return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
19721
+ } else {
19722
+ bestPath[diagonalPath] = basePath;
19723
+ if (basePath.oldPos + 1 >= oldLen) {
19724
+ maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
19725
+ }
19726
+ if (newPos + 1 >= newLen) {
19727
+ minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
19728
+ }
19564
19729
  }
19565
- optionDetails = value.optionDetails.map(({ description }) => description === void 0 ? {} : { description });
19566
- }
19567
- request = {
19568
- requestId,
19569
- method,
19570
- title,
19571
- options: [...value.options],
19572
- ...optionDetails ? { optionDetails } : {},
19573
- ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19574
- };
19575
- } else if (method === "confirm") {
19576
- if (typeof value.message !== "string") {
19577
- throw new OmpRpcFaultError("protocolError", "Omp RPC confirm request has no message");
19578
19730
  }
19579
- request = {
19580
- requestId,
19581
- method,
19582
- title,
19583
- message: value.message,
19584
- ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19585
- };
19586
- } else if (method === "input") {
19587
- if (value.placeholder !== void 0 && typeof value.placeholder !== "string") {
19588
- throw new OmpRpcFaultError("protocolError", "Omp RPC input placeholder is invalid");
19731
+ editLength++;
19732
+ };
19733
+ if (callback) {
19734
+ (function exec() {
19735
+ setTimeout(function() {
19736
+ if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
19737
+ return callback(void 0);
19738
+ }
19739
+ if (!execEditLength()) {
19740
+ exec();
19741
+ }
19742
+ }, 0);
19743
+ })();
19744
+ } else {
19745
+ while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
19746
+ const ret = execEditLength();
19747
+ if (ret) {
19748
+ return ret;
19749
+ }
19589
19750
  }
19590
- request = {
19591
- requestId,
19592
- method,
19593
- title,
19594
- ...typeof value.placeholder === "string" ? { placeholder: value.placeholder } : {},
19595
- ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19751
+ }
19752
+ }
19753
+ addToPath(path9, added, removed, oldPosInc, options) {
19754
+ const last = path9.lastComponent;
19755
+ if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
19756
+ return {
19757
+ oldPos: path9.oldPos + oldPosInc,
19758
+ lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
19596
19759
  };
19597
19760
  } else {
19598
- if (value.prefill !== void 0 && typeof value.prefill !== "string") {
19599
- throw new OmpRpcFaultError("protocolError", "Omp RPC editor prefill is invalid");
19600
- }
19601
- request = {
19602
- requestId,
19603
- method: "editor",
19604
- title,
19605
- ...typeof value.prefill === "string" ? { prefill: value.prefill } : {},
19606
- ...typeof timeoutMs === "number" ? { timeoutMs } : {}
19761
+ return {
19762
+ oldPos: path9.oldPos + oldPosInc,
19763
+ lastComponent: { count: 1, added, removed, previousComponent: last }
19607
19764
  };
19608
19765
  }
19609
- const pending = { request, timeout: null };
19610
- if (request.timeoutMs !== void 0) {
19611
- pending.timeout = setTimeout(() => {
19612
- if (this.#activeTurn !== active || !active.interactions.has(requestId))
19613
- return;
19614
- void this.#resolveInteraction({ requestId, cancelled: true }, "expired").catch((error51) => {
19615
- if (this.#closed || this.#failed)
19616
- return;
19617
- this.#fail(new OmpRpcFaultError("protocolError", `Omp RPC Interaction timeout handling failed: ${message2(error51)}`));
19618
- });
19619
- }, request.timeoutMs);
19766
+ }
19767
+ extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
19768
+ const newLen = newTokens.length, oldLen = oldTokens.length;
19769
+ let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
19770
+ while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
19771
+ newPos++;
19772
+ oldPos++;
19773
+ commonCount++;
19774
+ if (options.oneChangePerToken) {
19775
+ basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
19776
+ }
19620
19777
  }
19621
- active.interactions.set(requestId, pending);
19622
- active.onEvent({ type: "interaction.requested", request });
19778
+ if (commonCount && !options.oneChangePerToken) {
19779
+ basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
19780
+ }
19781
+ basePath.oldPos = oldPos;
19782
+ return newPos;
19623
19783
  }
19624
- #handleResponse(value) {
19625
- const id = value.id;
19626
- if (typeof id !== "string") {
19627
- this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC response has no id"));
19628
- return;
19784
+ equals(left, right, options) {
19785
+ if (options.comparator) {
19786
+ return options.comparator(left, right);
19787
+ } else {
19788
+ return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
19629
19789
  }
19630
- const pending = this.#pending.get(id);
19631
- const active = this.#activeTurn;
19632
- if (!pending) {
19633
- if (active?.promptId === id && value.command === "prompt" && value.success === false) {
19634
- active.failure = new Error(typeof value.error === "string" ? value.error : "Omp RPC command failed");
19635
- return;
19790
+ }
19791
+ removeEmpty(array2) {
19792
+ const ret = [];
19793
+ for (let i = 0; i < array2.length; i++) {
19794
+ if (array2[i]) {
19795
+ ret.push(array2[i]);
19636
19796
  }
19637
- this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC response id is not pending"));
19638
- return;
19639
19797
  }
19640
- if (pending.timeout)
19641
- clearTimeout(pending.timeout);
19642
- this.#pending.delete(id);
19643
- if (value.success === true) {
19644
- if (pending.command === "prompt" && active?.promptId === id && isRecord8(value.data) && value.data.agentInvoked === false) {
19645
- this.#settleLocalTurn(active, { cancelled: false });
19646
- }
19647
- pending.resolve(value);
19648
- } else {
19649
- const error51 = typeof value.error === "string" ? value.error : "Omp RPC command failed";
19650
- if (value.command === pending.command && error51 === `Unknown command: ${pending.command}`) {
19651
- pending.reject(new OmpRpcUnsupportedCommandError(pending.command));
19798
+ return ret;
19799
+ }
19800
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
19801
+ castInput(value, options) {
19802
+ return value;
19803
+ }
19804
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
19805
+ tokenize(value, options) {
19806
+ return Array.from(value);
19807
+ }
19808
+ join(chars) {
19809
+ return chars.join("");
19810
+ }
19811
+ postProcess(changeObjects, options) {
19812
+ return changeObjects;
19813
+ }
19814
+ get useLongestToken() {
19815
+ return false;
19816
+ }
19817
+ buildValues(lastComponent, newTokens, oldTokens) {
19818
+ const components = [];
19819
+ let nextComponent;
19820
+ while (lastComponent) {
19821
+ components.push(lastComponent);
19822
+ nextComponent = lastComponent.previousComponent;
19823
+ delete lastComponent.previousComponent;
19824
+ lastComponent = nextComponent;
19825
+ }
19826
+ components.reverse();
19827
+ const componentLen = components.length;
19828
+ let componentPos = 0, newPos = 0, oldPos = 0;
19829
+ for (; componentPos < componentLen; componentPos++) {
19830
+ const component = components[componentPos];
19831
+ if (!component.removed) {
19832
+ if (!component.added && this.useLongestToken) {
19833
+ let value = newTokens.slice(newPos, newPos + component.count);
19834
+ value = value.map(function(value2, i) {
19835
+ const oldValue = oldTokens[oldPos + i];
19836
+ return oldValue.length > value2.length ? oldValue : value2;
19837
+ });
19838
+ component.value = this.join(value);
19839
+ } else {
19840
+ component.value = this.join(newTokens.slice(newPos, newPos + component.count));
19841
+ }
19842
+ newPos += component.count;
19843
+ if (!component.added) {
19844
+ oldPos += component.count;
19845
+ }
19652
19846
  } else {
19653
- pending.reject(new Error(error51));
19847
+ component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
19848
+ oldPos += component.count;
19654
19849
  }
19655
19850
  }
19851
+ return components;
19656
19852
  }
19657
- #startTool(active, value) {
19658
- const callId = value.toolCallId;
19659
- const toolName = value.toolName;
19660
- const argumentsResult = jsonValueSchema.safeParse(value.args);
19661
- if (typeof callId !== "string" || callId.length === 0 || typeof toolName !== "string" || toolName.length === 0 || !argumentsResult.success || active.tools.has(callId)) {
19662
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool start");
19663
- }
19664
- active.sawTool = true;
19665
- active.tools.set(callId, toolName);
19666
- active.onEvent({
19667
- type: "tool.started",
19668
- callId,
19669
- toolName,
19670
- arguments: argumentsResult.data
19671
- });
19853
+ };
19854
+
19855
+ // ../../../node_modules/diff/libesm/diff/line.js
19856
+ var LineDiff = class extends Diff {
19857
+ constructor() {
19858
+ super(...arguments);
19859
+ this.tokenize = tokenize;
19672
19860
  }
19673
- #updateTool(active, value) {
19674
- const callId = value.toolCallId;
19675
- if (typeof callId !== "string" || callId.length === 0) {
19676
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool update");
19677
- }
19678
- if (!active.tools.has(callId))
19679
- return;
19680
- const outputResult = jsonValueSchema.safeParse(value.partialResult ?? null);
19681
- if (!outputResult.success) {
19682
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool update");
19861
+ equals(left, right, options) {
19862
+ if (options.ignoreWhitespace) {
19863
+ if (!options.newlineIsToken || !left.includes("\n")) {
19864
+ left = left.trim();
19865
+ }
19866
+ if (!options.newlineIsToken || !right.includes("\n")) {
19867
+ right = right.trim();
19868
+ }
19869
+ } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
19870
+ if (left.endsWith("\n")) {
19871
+ left = left.slice(0, -1);
19872
+ }
19873
+ if (right.endsWith("\n")) {
19874
+ right = right.slice(0, -1);
19875
+ }
19683
19876
  }
19684
- active.onEvent({ type: "tool.updated", callId, output: outputResult.data });
19877
+ return super.equals(left, right, options);
19685
19878
  }
19686
- #completeTool(active, value) {
19687
- const callId = value.toolCallId;
19688
- const toolName = value.toolName;
19689
- if (typeof callId !== "string" || callId.length === 0) {
19690
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool end");
19691
- }
19692
- const expectedName = active.tools.get(callId);
19693
- if (expectedName === void 0)
19694
- return;
19695
- const result = jsonValueSchema.safeParse(value.result);
19696
- if (typeof toolName !== "string" || expectedName !== toolName || value.isError !== void 0 && typeof value.isError !== "boolean" || !result.success) {
19697
- throw new OmpRpcFaultError("protocolError", "Omp RPC returned an invalid Tool end");
19879
+ };
19880
+ var lineDiff = new LineDiff();
19881
+ function diffLines(oldStr, newStr, options) {
19882
+ return lineDiff.diff(oldStr, newStr, options);
19883
+ }
19884
+ function tokenize(value, options) {
19885
+ if (options.stripTrailingCr) {
19886
+ value = value.replace(/\r\n/g, "\n");
19887
+ }
19888
+ const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
19889
+ if (!linesAndNewlines[linesAndNewlines.length - 1]) {
19890
+ linesAndNewlines.pop();
19891
+ }
19892
+ for (let i = 0; i < linesAndNewlines.length; i++) {
19893
+ const line = linesAndNewlines[i];
19894
+ if (i % 2 && !options.newlineIsToken) {
19895
+ retLines[retLines.length - 1] += line;
19896
+ } else {
19897
+ retLines.push(line);
19698
19898
  }
19699
- active.tools.delete(callId);
19700
- active.onEvent({
19701
- type: "tool.completed",
19702
- callId,
19703
- toolName,
19704
- result: result.data,
19705
- isError: value.isError === true
19706
- });
19707
19899
  }
19708
- async #confirmCancelledTurn(active) {
19709
- if (this.#activeTurn !== active || active.cancellation !== "accepted" || active.settlement === "confirming" || active.cancellationChecking)
19710
- return;
19711
- active.cancellationChecking = true;
19712
- if (active.cancellationRecheck)
19713
- clearTimeout(active.cancellationRecheck);
19714
- active.cancellationRecheck = null;
19715
- try {
19716
- let response = await this.#send("get_state", {});
19717
- if (this.#activeTurn !== active)
19718
- return;
19719
- if (parseSessionStreaming(response)) {
19720
- await this.#send("abort", {});
19721
- if (this.#activeTurn !== active)
19722
- return;
19723
- response = await this.#send("get_state", {});
19900
+ return retLines;
19901
+ }
19902
+
19903
+ // ../../../node_modules/diff/libesm/patch/parse.js
19904
+ function parsePatch(uniDiff) {
19905
+ const diffstr = uniDiff.split(/\n/), list = [];
19906
+ let i = 0;
19907
+ function parseIndex() {
19908
+ const index = {};
19909
+ list.push(index);
19910
+ while (i < diffstr.length) {
19911
+ const line = diffstr[i];
19912
+ if (/^(---|\+\+\+|@@)\s/.test(line)) {
19913
+ break;
19724
19914
  }
19725
- let state = parseSessionState(response);
19726
- if (this.#activeTurn !== active || active.cancellation !== "accepted")
19727
- return;
19728
- const data = sessionStateData(response);
19729
- 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) {
19730
- await this.verifySessionCwd(this.#options.cwd);
19731
- if (this.#activeTurn !== active)
19732
- return;
19733
- active.cancellationReloaded = true;
19734
- const reset = await this.#send("new_session", {});
19735
- if (this.#activeTurn !== active)
19736
- return;
19737
- if (!isRecord8(reset.data) || reset.data.cancelled !== false) {
19738
- throw new OmpRpcFaultError("unavailable", "Omp cancelled Session reset was refused");
19739
- }
19740
- const reloaded = await this.#send("switch_session", { sessionPath: state.sessionFile });
19741
- if (this.#activeTurn !== active)
19742
- return;
19743
- if (!isRecord8(reloaded.data) || reloaded.data.cancelled !== false) {
19744
- throw new OmpRpcFaultError("unavailable", "Omp cancelled Session reload was refused");
19745
- }
19746
- const previous = state;
19747
- response = await this.#send("get_state", {});
19748
- state = parseSessionState(response);
19749
- if (state.sessionId !== previous.sessionId || state.sessionFile !== previous.sessionFile) {
19750
- throw new OmpRpcFaultError("protocolError", "Omp cancelled Session reload changed its identity");
19751
- }
19752
- if (state.provider !== previous.provider || state.modelId !== previous.modelId) {
19753
- if (!previous.provider || !previous.modelId) {
19754
- throw new OmpRpcFaultError("protocolError", "Omp cancelled Session has no restorable Model");
19755
- }
19756
- await this.#send("set_model", { provider: previous.provider, modelId: previous.modelId });
19757
- }
19758
- if (previous.thinkingLevel && state.thinkingLevel !== previous.thinkingLevel) {
19759
- await this.#send("set_thinking_level", { level: previous.thinkingLevel });
19760
- }
19761
- response = await this.#send("get_state", {});
19762
- state = parseSessionState(response);
19763
- if (state.sessionId !== previous.sessionId || state.sessionFile !== previous.sessionFile || state.provider !== previous.provider || state.modelId !== previous.modelId || previous.thinkingLevel !== null && state.thinkingLevel !== previous.thinkingLevel) {
19764
- throw new OmpRpcFaultError("protocolError", "Omp cancelled Session reload changed its identity or configuration");
19765
- }
19915
+ const header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
19916
+ if (header) {
19917
+ index.index = header[1];
19766
19918
  }
19767
- if (!cancellationSettled(response, active.terminalEnd)) {
19768
- active.settlement = "pending";
19769
- active.cancellationRecheck = setTimeout(() => {
19770
- active.cancellationRecheck = null;
19771
- void this.#confirmCancelledTurn(active);
19772
- }, 250);
19773
- return;
19919
+ i++;
19920
+ }
19921
+ parseFileHeader(index);
19922
+ parseFileHeader(index);
19923
+ index.hunks = [];
19924
+ while (i < diffstr.length) {
19925
+ const line = diffstr[i];
19926
+ if (/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/.test(line)) {
19927
+ break;
19928
+ } else if (/^@@/.test(line)) {
19929
+ index.hunks.push(parseHunk());
19930
+ } else if (line) {
19931
+ throw new Error("Unknown line " + (i + 1) + " " + JSON.stringify(line));
19932
+ } else {
19933
+ i++;
19774
19934
  }
19775
- this.#state = state;
19776
- active.settlement = "confirmed";
19777
- this.#finishSettledTurn(active);
19778
- } catch (error51) {
19779
- if (this.#activeTurn !== active)
19780
- return;
19781
- const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC cancelled Turn state could not be confirmed: ${message2(error51)}`);
19782
- this.#terminateFailedCancellation(active, fault);
19783
- } finally {
19784
- active.cancellationChecking = false;
19785
19935
  }
19786
19936
  }
19787
- #settleLocalTurn(active, result) {
19788
- if (this.#activeTurn !== active || active.settlement !== "pending")
19789
- return;
19790
- active.localResult = result;
19791
- active.settlement = "confirming";
19792
- void this.#confirmSettledTurn(active);
19793
- }
19794
- async #confirmSettledTurn(active) {
19795
- try {
19796
- const response = await this.#send("get_state", {});
19797
- const state = parseSessionState(response);
19798
- if (this.#activeTurn !== active)
19799
- return;
19800
- if (active.cancellation !== "none") {
19801
- active.settlement = "pending";
19802
- if (active.cancellation === "accepted")
19803
- void this.#confirmCancelledTurn(active);
19804
- return;
19937
+ function parseFileHeader(index) {
19938
+ const fileHeader = /^(---|\+\+\+)\s+(.*)\r?$/.exec(diffstr[i]);
19939
+ if (fileHeader) {
19940
+ const data = fileHeader[2].split(" ", 2), header = (data[1] || "").trim();
19941
+ let fileName = data[0].replace(/\\\\/g, "\\");
19942
+ if (/^".*"$/.test(fileName)) {
19943
+ fileName = fileName.substr(1, fileName.length - 2);
19805
19944
  }
19806
- if (parseSessionStreaming(response)) {
19807
- throw new OmpRpcFaultError("protocolError", "Omp RPC completed Turn state is still Streaming");
19945
+ if (fileHeader[1] === "---") {
19946
+ index.oldFileName = fileName;
19947
+ index.oldHeader = header;
19948
+ } else {
19949
+ index.newFileName = fileName;
19950
+ index.newHeader = header;
19951
+ }
19952
+ i++;
19953
+ }
19954
+ }
19955
+ function parseHunk() {
19956
+ var _a3;
19957
+ const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
19958
+ const hunk = {
19959
+ oldStart: +chunkHeader[1],
19960
+ oldLines: typeof chunkHeader[2] === "undefined" ? 1 : +chunkHeader[2],
19961
+ newStart: +chunkHeader[3],
19962
+ newLines: typeof chunkHeader[4] === "undefined" ? 1 : +chunkHeader[4],
19963
+ lines: []
19964
+ };
19965
+ if (hunk.oldLines === 0) {
19966
+ hunk.oldStart += 1;
19967
+ }
19968
+ if (hunk.newLines === 0) {
19969
+ hunk.newStart += 1;
19970
+ }
19971
+ let addCount = 0, removeCount = 0;
19972
+ for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a3 = diffstr[i]) === null || _a3 === void 0 ? void 0 : _a3.startsWith("\\"))); i++) {
19973
+ const operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? " " : diffstr[i][0];
19974
+ if (operation === "+" || operation === "-" || operation === " " || operation === "\\") {
19975
+ hunk.lines.push(diffstr[i]);
19976
+ if (operation === "+") {
19977
+ addCount++;
19978
+ } else if (operation === "-") {
19979
+ removeCount++;
19980
+ } else if (operation === " ") {
19981
+ addCount++;
19982
+ removeCount++;
19983
+ }
19984
+ } else {
19985
+ throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`);
19808
19986
  }
19809
- this.#state = state;
19810
- active.settlement = "confirmed";
19811
- this.#finishSettledTurn(active);
19812
- } catch (error51) {
19813
- if (this.#activeTurn !== active)
19814
- return;
19815
- const fault = error51 instanceof OmpRpcFaultError ? error51 : new OmpRpcFaultError("protocolError", `Omp RPC stable Turn state could not be confirmed: ${message2(error51)}`);
19816
- this.#fail(fault);
19817
19987
  }
19818
- }
19819
- #finishSettledTurn(active) {
19820
- if (this.#activeTurn !== active || active.settlement !== "confirmed" || active.cancellation === "requesting") {
19821
- return;
19988
+ if (!addCount && hunk.newLines === 1) {
19989
+ hunk.newLines = 0;
19822
19990
  }
19823
- if (active.cancellationTimeout)
19824
- clearTimeout(active.cancellationTimeout);
19825
- active.cancellationTimeout = null;
19826
- if (active.cancellationRecheck)
19827
- clearTimeout(active.cancellationRecheck);
19828
- active.cancellationRecheck = null;
19829
- this.#closeInteractions(active, active.cancellation === "accepted" ? "cancelled" : "superseded");
19830
- if (active.tools.size > 0) {
19831
- this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC settled with active Tool executions"));
19832
- return;
19991
+ if (!removeCount && hunk.oldLines === 1) {
19992
+ hunk.oldLines = 0;
19833
19993
  }
19834
- this.#activeTurn = null;
19835
- if (active.localResult) {
19836
- active.resolve({
19837
- text: active.text,
19838
- agentInvoked: false,
19839
- ...active.localResult,
19840
- cancelled: active.localResult.cancelled || active.cancellation === "accepted"
19841
- });
19842
- } else if (active.cancellation === "accepted") {
19843
- active.resolve({ text: active.text, cancelled: true, agentInvoked: true });
19844
- } else if (active.failure) {
19845
- active.reject(active.failure);
19846
- } else if (active.text.trim().length === 0 && !active.sawTool) {
19847
- active.reject(new Error("Omp RPC settled without displayable output"));
19848
- } else {
19849
- active.resolve({ text: active.text, cancelled: false, agentInvoked: true });
19994
+ if (addCount !== hunk.newLines) {
19995
+ throw new Error("Added line count did not match for hunk at line " + (chunkHeaderIndex + 1));
19850
19996
  }
19851
- }
19852
- #startAssistantMessage(active, value) {
19853
- if (active.assistantMessageId !== null && active.reasoningMessageOpen) {
19854
- active.onEvent({ type: "reasoning.completed", messageId: active.assistantMessageId });
19997
+ if (removeCount !== hunk.oldLines) {
19998
+ throw new Error("Removed line count did not match for hunk at line " + (chunkHeaderIndex + 1));
19855
19999
  }
19856
- const messageId = assistantMessageId(value) ?? randomUUID();
19857
- active.assistantMessageId = messageId;
19858
- active.sawStreamedMessageText = false;
19859
- active.sawStreamedMessageReasoning = false;
19860
- active.reasoningMessageOpen = false;
19861
- return messageId;
20000
+ return hunk;
19862
20001
  }
19863
- #ensureAssistantMessage(active, value) {
19864
- return active.assistantMessageId ?? this.#startAssistantMessage(active, value);
20002
+ while (i < diffstr.length) {
20003
+ parseIndex();
19865
20004
  }
19866
- #finalizeAssistantMessage(active, value) {
19867
- const finalText = assistantText(value);
19868
- const finalReasoning = assistantReasoning(value);
19869
- const failure = assistantFailure(value);
19870
- const cacheHitRatePercent = optionalOmpCacheHitRatePercent(value);
19871
- if (finalText === null || finalReasoning === null || failure === void 0)
19872
- return;
19873
- if (active.assistantMessageId === null && finalText === active.lastFinalizedMessageText && finalReasoning === active.lastFinalizedMessageReasoning && !active.sawStreamedMessageText && !active.sawStreamedMessageReasoning) {
20005
+ return list;
20006
+ }
20007
+
20008
+ // ../../../node_modules/diff/libesm/patch/create.js
20009
+ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
20010
+ let optionsObj;
20011
+ if (!options) {
20012
+ optionsObj = {};
20013
+ } else if (typeof options === "function") {
20014
+ optionsObj = { callback: options };
20015
+ } else {
20016
+ optionsObj = options;
20017
+ }
20018
+ if (typeof optionsObj.context === "undefined") {
20019
+ optionsObj.context = 4;
20020
+ }
20021
+ const context = optionsObj.context;
20022
+ if (optionsObj.newlineIsToken) {
20023
+ throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");
20024
+ }
20025
+ if (!optionsObj.callback) {
20026
+ return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj));
20027
+ } else {
20028
+ const { callback } = optionsObj;
20029
+ diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => {
20030
+ const patch = diffLinesResultToPatch(diff);
20031
+ callback(patch);
20032
+ } }));
20033
+ }
20034
+ function diffLinesResultToPatch(diff) {
20035
+ if (!diff) {
19874
20036
  return;
19875
20037
  }
19876
- active.failure = failure;
19877
- this.#latestCacheHitRatePercent = cacheHitRatePercent;
19878
- const messageId = this.#ensureAssistantMessage(active, value);
19879
- if (!active.sawStreamedMessageReasoning && finalReasoning.length > 0) {
19880
- active.reasoningMessageOpen = true;
19881
- active.onEvent({ type: "reasoning.delta", messageId, delta: finalReasoning });
20038
+ diff.push({ value: "", lines: [] });
20039
+ function contextLines(lines) {
20040
+ return lines.map(function(entry) {
20041
+ return " " + entry;
20042
+ });
19882
20043
  }
19883
- if (active.reasoningMessageOpen && active.failure === null) {
19884
- active.onEvent({ type: "reasoning.completed", messageId });
20044
+ const hunks = [];
20045
+ let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
20046
+ for (let i = 0; i < diff.length; i++) {
20047
+ const current = diff[i], lines = current.lines || splitLines(current.value);
20048
+ current.lines = lines;
20049
+ if (current.added || current.removed) {
20050
+ if (!oldRangeStart) {
20051
+ const prev = diff[i - 1];
20052
+ oldRangeStart = oldLine;
20053
+ newRangeStart = newLine;
20054
+ if (prev) {
20055
+ curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : [];
20056
+ oldRangeStart -= curRange.length;
20057
+ newRangeStart -= curRange.length;
20058
+ }
20059
+ }
20060
+ for (const line of lines) {
20061
+ curRange.push((current.added ? "+" : "-") + line);
20062
+ }
20063
+ if (current.added) {
20064
+ newLine += lines.length;
20065
+ } else {
20066
+ oldLine += lines.length;
20067
+ }
20068
+ } else {
20069
+ if (oldRangeStart) {
20070
+ if (lines.length <= context * 2 && i < diff.length - 2) {
20071
+ for (const line of contextLines(lines)) {
20072
+ curRange.push(line);
20073
+ }
20074
+ } else {
20075
+ const contextSize = Math.min(lines.length, context);
20076
+ for (const line of contextLines(lines.slice(0, contextSize))) {
20077
+ curRange.push(line);
20078
+ }
20079
+ const hunk = {
20080
+ oldStart: oldRangeStart,
20081
+ oldLines: oldLine - oldRangeStart + contextSize,
20082
+ newStart: newRangeStart,
20083
+ newLines: newLine - newRangeStart + contextSize,
20084
+ lines: curRange
20085
+ };
20086
+ hunks.push(hunk);
20087
+ oldRangeStart = 0;
20088
+ newRangeStart = 0;
20089
+ curRange = [];
20090
+ }
20091
+ }
20092
+ oldLine += lines.length;
20093
+ newLine += lines.length;
20094
+ }
19885
20095
  }
19886
- if (!active.sawStreamedMessageText && finalText.length > 0) {
19887
- active.text += finalText;
19888
- active.onEvent({ type: "text.delta", messageId, delta: finalText });
20096
+ for (const hunk of hunks) {
20097
+ for (let i = 0; i < hunk.lines.length; i++) {
20098
+ if (hunk.lines[i].endsWith("\n")) {
20099
+ hunk.lines[i] = hunk.lines[i].slice(0, -1);
20100
+ } else {
20101
+ hunk.lines.splice(i + 1, 0, "\");
20102
+ i++;
20103
+ }
20104
+ }
19889
20105
  }
19890
- active.assistantMessageId = null;
19891
- active.sawStreamedMessageText = false;
19892
- active.sawStreamedMessageReasoning = false;
19893
- active.reasoningMessageOpen = false;
19894
- active.lastFinalizedMessageText = finalText;
19895
- active.lastFinalizedMessageReasoning = finalReasoning;
19896
- active.onEvent({ type: "message.completed", messageId });
20106
+ return {
20107
+ oldFileName,
20108
+ newFileName,
20109
+ oldHeader,
20110
+ newHeader,
20111
+ hunks
20112
+ };
19897
20113
  }
19898
- #write(value) {
19899
- const child = this.#child;
19900
- if (!child?.stdin.writable || this.#closed || this.#failed) {
19901
- return Promise.reject(new Error("Omp RPC stdin is unavailable"));
19902
- }
19903
- return new Promise((resolve, reject) => {
19904
- const frame = Buffer.from(`${JSON.stringify(value)}
19905
- `, "utf8");
19906
- child.stdin.write(frame, (error51) => error51 ? reject(error51) : resolve());
19907
- });
20114
+ }
20115
+ function formatPatch(patch) {
20116
+ if (Array.isArray(patch)) {
20117
+ return patch.map(formatPatch).join("\n");
19908
20118
  }
19909
- #send(type, payload, id = `codexhost-${randomUUID()}`) {
19910
- const child = this.#child;
19911
- if (!child?.stdin.writable || this.#closed || this.#failed) {
19912
- return Promise.reject(new Error("Omp RPC stdin is unavailable"));
19913
- }
19914
- return new Promise((resolve, reject) => {
19915
- const pending = {
19916
- command: type,
19917
- resolve,
19918
- reject,
19919
- timeout: null
19920
- };
19921
- this.#pending.set(id, pending);
19922
- this.#armCommandTimeout(id, pending);
19923
- const frame = Buffer.from(`${JSON.stringify({ id, type, ...payload })}
19924
- `, "utf8");
19925
- child.stdin.write(frame, (error51) => {
19926
- if (error51) {
19927
- if (pending.timeout)
19928
- clearTimeout(pending.timeout);
19929
- this.#pending.delete(id);
19930
- reject(error51);
19931
- }
19932
- });
19933
- });
20119
+ const ret = [];
20120
+ if (patch.oldFileName == patch.newFileName) {
20121
+ ret.push("Index: " + patch.oldFileName);
20122
+ }
20123
+ ret.push("===================================================================");
20124
+ ret.push("--- " + patch.oldFileName + (typeof patch.oldHeader === "undefined" ? "" : " " + patch.oldHeader));
20125
+ ret.push("+++ " + patch.newFileName + (typeof patch.newHeader === "undefined" ? "" : " " + patch.newHeader));
20126
+ for (let i = 0; i < patch.hunks.length; i++) {
20127
+ const hunk = patch.hunks[i];
20128
+ if (hunk.oldLines === 0) {
20129
+ hunk.oldStart -= 1;
20130
+ }
20131
+ if (hunk.newLines === 0) {
20132
+ hunk.newStart -= 1;
20133
+ }
20134
+ ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@");
20135
+ for (const line of hunk.lines) {
20136
+ ret.push(line);
20137
+ }
19934
20138
  }
19935
- #armCommandTimeout(id, pending) {
19936
- if (pending.timeout || this.#pending.get(id) !== pending || (pending.command === "prompt" || pending.command === "compact") && this.#compactionActive) {
20139
+ return ret.join("\n") + "\n";
20140
+ }
20141
+ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
20142
+ if (typeof options === "function") {
20143
+ options = { callback: options };
20144
+ }
20145
+ if (!(options === null || options === void 0 ? void 0 : options.callback)) {
20146
+ const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
20147
+ if (!patchObj) {
19937
20148
  return;
19938
20149
  }
19939
- pending.timeout = setTimeout(() => {
19940
- if (this.#pending.get(id) !== pending)
19941
- return;
19942
- pending.timeout = null;
19943
- const error51 = new Error(`Omp RPC '${pending.command}' command timed out`);
19944
- if (pending.command !== "prompt") {
19945
- this.#pending.delete(id);
19946
- pending.reject(error51);
19947
- return;
20150
+ return formatPatch(patchObj);
20151
+ } else {
20152
+ const { callback } = options;
20153
+ structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: (patchObj) => {
20154
+ if (!patchObj) {
20155
+ callback(void 0);
20156
+ } else {
20157
+ callback(formatPatch(patchObj));
19948
20158
  }
19949
- const fault = new OmpRpcFaultError("protocolError", error51.message);
19950
- void this.#terminateTimedOutPrompt(fault);
19951
- }, this.#options.commandTimeoutMs);
20159
+ } }));
19952
20160
  }
19953
- async #terminateTimedOutPrompt(fault) {
19954
- if (this.#closed || this.#failed)
19955
- return;
19956
- this.#failed = true;
19957
- this.#closed = true;
19958
- for (const pending of this.#pending.values()) {
19959
- if (pending.timeout)
19960
- clearTimeout(pending.timeout);
19961
- pending.timeout = null;
19962
- }
19963
- let finalFault = fault;
19964
- try {
19965
- await this.close();
19966
- } catch (error51) {
19967
- finalFault = new OmpRpcFaultError("processExited", `Omp RPC timed-out Prompt cleanup failed: ${message2(error51)}`);
19968
- }
19969
- this.#rejectAll(finalFault);
19970
- this.#options.onFault?.(finalFault);
20161
+ }
20162
+ function splitLines(text) {
20163
+ const hasTrailingNl = text.endsWith("\n");
20164
+ const result = text.split("\n").map((line) => line + "\n");
20165
+ if (hasTrailingNl) {
20166
+ result.pop();
20167
+ } else {
20168
+ result.push(result.pop().slice(0, -1));
19971
20169
  }
19972
- #closeInteractions(active, reason) {
19973
- for (const [requestId, pending] of active.interactions) {
19974
- active.interactions.delete(requestId);
19975
- if (pending.timeout)
19976
- clearTimeout(pending.timeout);
19977
- active.onEvent({ type: "interaction.closed", requestId, reason });
19978
- }
20170
+ return result;
20171
+ }
20172
+
20173
+ // dist/omp-adapter.js
20174
+ import { randomUUID as randomUUID2 } from "node:crypto";
20175
+ import { realpath as realpath3, stat as stat2 } from "node:fs/promises";
20176
+ import path7 from "node:path";
20177
+
20178
+ // dist/omp-last-turn-rollback.js
20179
+ function modelFromState(state) {
20180
+ if (state.provider === null && state.modelId === null)
20181
+ return null;
20182
+ if (state.provider === null || state.modelId === null) {
20183
+ throw new Error("Omp state contains a partial Model identity");
19979
20184
  }
19980
- #rejectActiveTurn(error51) {
19981
- const active = this.#activeTurn;
19982
- if (!active)
19983
- return;
19984
- if (active.cancellationTimeout)
19985
- clearTimeout(active.cancellationTimeout);
19986
- if (active.cancellationRecheck)
19987
- clearTimeout(active.cancellationRecheck);
19988
- this.#closeInteractions(active, "cancelled");
19989
- this.#activeTurn = null;
19990
- active.reject(error51);
20185
+ return { provider: state.provider, id: state.modelId };
20186
+ }
20187
+ async function rollbackOmpLastTurn(transport, sourceSessionId, cwd) {
20188
+ const startupState = transport.state;
20189
+ const startupSessionId = startupState.sessionId;
20190
+ const currentModel = modelFromState(startupState);
20191
+ const currentThinking = startupState.thinkingLevel;
20192
+ const copiedHistory = await transport.getEntries();
20193
+ const boundary = resolveOmpLastTurnBoundary(copiedHistory);
20194
+ if (!boundary)
20195
+ return { ok: false, reason: "empty" };
20196
+ const sourceSnapshot = mapOmpSnapshot(copiedHistory, {
20197
+ sessionId: startupSessionId,
20198
+ model: currentModel
20199
+ });
20200
+ let state = await transport.fork(boundary.lastUserEntryId);
20201
+ if (state.sessionId === sourceSessionId || state.sessionId === startupSessionId) {
20202
+ throw new Error("Omp last-Turn rollback did not create a distinct Native Session");
19991
20203
  }
19992
- #rejectAll(error51) {
19993
- if (this.#compactionTimeout)
19994
- clearTimeout(this.#compactionTimeout);
19995
- this.#compactionTimeout = null;
19996
- for (const pending of this.#pending.values()) {
19997
- if (pending.timeout)
19998
- clearTimeout(pending.timeout);
19999
- pending.reject(error51);
20000
- }
20001
- this.#pending.clear();
20002
- const manual = this.#manualCompaction;
20003
- this.#manualCompaction = null;
20004
- manual?.reject(error51);
20005
- this.#rejectActiveTurn(error51);
20204
+ if (!sameOmpModel(modelFromState(state), currentModel)) {
20205
+ if (!currentModel)
20206
+ throw new Error("Omp last-Turn rollback changed the current Model");
20207
+ state = await transport.selectModel(currentModel);
20006
20208
  }
20007
- #fail(error51) {
20008
- if (this.#closed || this.#failed)
20009
- return;
20010
- this.#failed = true;
20011
- this.#startupFaultResolve?.(error51);
20012
- this.#startupFaultResolve = null;
20013
- this.#rejectAll(error51);
20014
- this.#options.onFault?.(error51);
20209
+ if (state.thinkingLevel !== currentThinking) {
20210
+ if (!currentThinking)
20211
+ throw new Error("Omp last-Turn rollback changed current Thinking");
20212
+ state = await transport.selectThinkingOption(currentThinking);
20015
20213
  }
20016
- };
20214
+ if (!sameOmpModel(modelFromState(state), currentModel) || state.thinkingLevel !== currentThinking) {
20215
+ throw new Error("Omp last-Turn rollback could not restore current Model and Thinking");
20216
+ }
20217
+ const snapshot = mapOmpSnapshot(await transport.getEntries(), {
20218
+ sessionId: state.sessionId,
20219
+ model: modelFromState(state)
20220
+ });
20221
+ const expectedTurnKeys = sourceSnapshot.turns.slice(0, -1).map((turn) => turn.nativeTurnRef.nativeTurnKey);
20222
+ const actualTurnKeys = snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey);
20223
+ if (snapshot.turns.length !== boundary.sourceTurnCount - 1 || actualTurnKeys.some((key, index) => key !== expectedTurnKeys[index])) {
20224
+ throw new Error("Omp last-Turn rollback did not produce the exact retained history prefix");
20225
+ }
20226
+ await transport.verifySessionCwd(cwd);
20227
+ return { ok: true };
20228
+ }
20017
20229
 
20018
20230
  // dist/omp-permission-modes.js
20019
20231
  var nativePermissionModes = /* @__PURE__ */ new Set(["always-ask", "write", "yolo"]);
@@ -20166,6 +20378,24 @@ var OmpSubagentLifecycle = class {
20166
20378
  };
20167
20379
 
20168
20380
  // dist/omp-adapter.js
20381
+ function closedInspection() {
20382
+ return {
20383
+ status: "unavailable",
20384
+ error: { code: "invalidState", message: "Omp Adapter is closed", retryable: false }
20385
+ };
20386
+ }
20387
+ function ompInspectionCapabilities(selectThinkingOption) {
20388
+ return {
20389
+ configuration: {
20390
+ selectModel: true,
20391
+ selectThinkingOption,
20392
+ selectPermissionMode: true,
20393
+ permissionModeScope: "live"
20394
+ },
20395
+ history: { fork: true, forkAcrossCwd: true, rollbackLastTurn: true },
20396
+ subagents: { observe: true, readTranscript: true }
20397
+ };
20398
+ }
20169
20399
  var ompHarnessId2 = harnessIdSchema.parse("omp");
20170
20400
  var ompCommandCatalog = harnessCommandCatalogSchema.parse({
20171
20401
  commands: [
@@ -20180,7 +20410,7 @@ var ompCommandCatalog = harnessCommandCatalogSchema.parse({
20180
20410
  ]
20181
20411
  });
20182
20412
  var DEFAULT_TOOL_OUTPUT_LIMIT = 64e3;
20183
- function isRecord9(value) {
20413
+ function isRecord10(value) {
20184
20414
  return typeof value === "object" && value !== null && !Array.isArray(value);
20185
20415
  }
20186
20416
  function errorMessage(error51) {
@@ -20195,7 +20425,7 @@ var OmpAdapterFaultError = class extends Error {
20195
20425
  }
20196
20426
  };
20197
20427
  function normalizedError(error51, fallbackCode) {
20198
- if (isRecord9(error51) && error51.code === "ENOENT") {
20428
+ if (isRecord10(error51) && error51.code === "ENOENT") {
20199
20429
  return { code: "notInstalled", message: errorMessage(error51), retryable: false };
20200
20430
  }
20201
20431
  if (error51 instanceof OmpAdapterFaultError)
@@ -20272,7 +20502,7 @@ function nativeModelForHistory(state) {
20272
20502
  return nativeModelFromState(state);
20273
20503
  }
20274
20504
  function sessionFileFromRef(ref) {
20275
- if (ref.harnessId !== ompHarnessId2 || !isRecord9(ref.locator) || typeof ref.locator.sessionFile !== "string" || ref.locator.sessionFile.length === 0) {
20505
+ if (ref.harnessId !== ompHarnessId2 || !isRecord10(ref.locator) || typeof ref.locator.sessionFile !== "string" || ref.locator.sessionFile.length === 0) {
20276
20506
  throw new Error("Omp Native Session Ref has no resumable Session file");
20277
20507
  }
20278
20508
  return ref.locator.sessionFile;
@@ -20327,9 +20557,9 @@ function toolFailure(toolName) {
20327
20557
  function nativeText(value) {
20328
20558
  if (typeof value === "string")
20329
20559
  return value;
20330
- if (!isRecord9(value) || !Array.isArray(value.content))
20560
+ if (!isRecord10(value) || !Array.isArray(value.content))
20331
20561
  return "";
20332
- return value.content.filter((content) => isRecord9(content) && content.type === "text" && typeof content.text === "string").map(({ text }) => text).join("");
20562
+ return value.content.filter((content) => isRecord10(content) && content.type === "text" && typeof content.text === "string").map(({ text }) => text).join("");
20333
20563
  }
20334
20564
  function boundedOutput(value, limit) {
20335
20565
  const text = nativeText(value);
@@ -20345,17 +20575,17 @@ function outputText(output) {
20345
20575
  return output?.content.filter((content) => content.type === "text").map(({ text }) => text).join("") ?? "";
20346
20576
  }
20347
20577
  function stringField2(value, key) {
20348
- if (!isRecord9(value))
20578
+ if (!isRecord10(value))
20349
20579
  return void 0;
20350
- const field = value[key];
20351
- if (typeof field === "string" && field.length > 0)
20352
- return field;
20353
- if (isRecord9(value.input)) {
20580
+ const field2 = value[key];
20581
+ if (typeof field2 === "string" && field2.length > 0)
20582
+ return field2;
20583
+ if (isRecord10(value.input)) {
20354
20584
  const nested = value.input[key];
20355
20585
  if (typeof nested === "string" && nested.length > 0)
20356
20586
  return nested;
20357
20587
  }
20358
- if (isRecord9(value.arguments)) {
20588
+ if (isRecord10(value.arguments)) {
20359
20589
  const nested = value.arguments[key];
20360
20590
  if (typeof nested === "string" && nested.length > 0)
20361
20591
  return nested;
@@ -20363,10 +20593,10 @@ function stringField2(value, key) {
20363
20593
  return void 0;
20364
20594
  }
20365
20595
  function numberField(value, key) {
20366
- if (!isRecord9(value))
20596
+ if (!isRecord10(value))
20367
20597
  return void 0;
20368
- const field = value[key];
20369
- return typeof field === "number" || field === null ? field : void 0;
20598
+ const field2 = value[key];
20599
+ return typeof field2 === "number" || field2 === null ? field2 : void 0;
20370
20600
  }
20371
20601
  function stripDiffPrefix(pathString) {
20372
20602
  if (typeof pathString !== "string" || pathString.length === 0)
@@ -20402,12 +20632,12 @@ function fileMutatingKind(toolName) {
20402
20632
  return null;
20403
20633
  }
20404
20634
  function nestedToolString(value, keys) {
20405
- if (!isRecord9(value))
20635
+ if (!isRecord10(value))
20406
20636
  return void 0;
20407
20637
  for (const key of keys) {
20408
- const field = value[key];
20409
- if (typeof field === "string" && field.length > 0)
20410
- return field;
20638
+ const field2 = value[key];
20639
+ if (typeof field2 === "string" && field2.length > 0)
20640
+ return field2;
20411
20641
  }
20412
20642
  for (const wrapper of ["input", "arguments", "params", "details"]) {
20413
20643
  const nested = nestedToolString(value[wrapper], keys);
@@ -20417,18 +20647,18 @@ function nestedToolString(value, keys) {
20417
20647
  return void 0;
20418
20648
  }
20419
20649
  function patchFromResult(result) {
20420
- if (!isRecord9(result))
20650
+ if (!isRecord10(result))
20421
20651
  return void 0;
20422
20652
  for (const key of ["patch", "diff", "unifiedDiff"]) {
20423
- const field = result[key];
20424
- if (typeof field === "string" && field.length > 0)
20425
- return field;
20653
+ const field2 = result[key];
20654
+ if (typeof field2 === "string" && field2.length > 0)
20655
+ return field2;
20426
20656
  }
20427
- if (isRecord9(result.details)) {
20657
+ if (isRecord10(result.details)) {
20428
20658
  for (const key of ["patch", "diff", "unifiedDiff"]) {
20429
- const field = result.details[key];
20430
- if (typeof field === "string" && field.length > 0)
20431
- return field;
20659
+ const field2 = result.details[key];
20660
+ if (typeof field2 === "string" && field2.length > 0)
20661
+ return field2;
20432
20662
  }
20433
20663
  }
20434
20664
  return void 0;
@@ -20551,9 +20781,6 @@ var OmpHarnessSession = class {
20551
20781
  #usage;
20552
20782
  #usageGeneration = 0;
20553
20783
  #usageRefreshSequence = 0;
20554
- #backgroundTurnId = null;
20555
- #backgroundSubagents = /* @__PURE__ */ new Map();
20556
- #backgroundTurnFailed = false;
20557
20784
  constructor(cwd, createTransport, onClosed, options) {
20558
20785
  this.#cwd = cwd;
20559
20786
  this.#createTransport = createTransport;
@@ -20611,44 +20838,6 @@ var OmpHarnessSession = class {
20611
20838
  #backgroundStatus(status) {
20612
20839
  return status === "pending" || status === "running" ? "running" : status === "interrupted" ? "interrupted" : status;
20613
20840
  }
20614
- #ensureBackgroundTurn() {
20615
- if (this.#backgroundTurnId)
20616
- return this.#backgroundTurnId;
20617
- const turnId = hostTurnIdSchema.parse(randomUUID2());
20618
- this.#backgroundTurnId = turnId;
20619
- this.#backgroundTurnFailed = false;
20620
- this.#event({
20621
- type: "turn.autonomous.started",
20622
- turnId,
20623
- input: []
20624
- });
20625
- return turnId;
20626
- }
20627
- #backgroundDelegationStart(event) {
20628
- const turnId = this.#ensureBackgroundTurn();
20629
- const description = event.type === "subagent.started" ? event.description : event.type === "subagent.updated" ? event.description ?? "Background subagent" : "Background subagent";
20630
- const role = event.type === "subagent.started" ? event.role : void 0;
20631
- const background = event.type === "subagent.started" ? event.background : true;
20632
- const state = {
20633
- subagentId: event.nativeSubagentId,
20634
- nativeSubagentId: event.nativeSubagentId,
20635
- description,
20636
- ...role ? { role } : {},
20637
- background,
20638
- status: "running"
20639
- };
20640
- const item = {
20641
- type: "subagentDelegation",
20642
- itemId: this.#newItemId(),
20643
- operation: "spawn",
20644
- ...event.type === "subagent.started" && event.prompt ? { prompt: event.prompt } : {},
20645
- subagents: [state]
20646
- };
20647
- const delegation = { item, turnId };
20648
- this.#backgroundSubagents.set(event.callId, delegation);
20649
- this.#event({ type: "item.started", turnId, item });
20650
- return delegation;
20651
- }
20652
20841
  #handleBackgroundSubagentEvent(event) {
20653
20842
  if (event.type === "subagent.transcript.changed") {
20654
20843
  this.#event({
@@ -20660,12 +20849,6 @@ var OmpHarnessSession = class {
20660
20849
  if (event.type !== "subagent.started" && event.type !== "subagent.updated" && event.type !== "subagent.completed") {
20661
20850
  return;
20662
20851
  }
20663
- let delegation = this.#backgroundSubagents.get(event.callId);
20664
- if (!delegation)
20665
- delegation = this.#backgroundDelegationStart(event);
20666
- const current = delegation.item.subagents[0];
20667
- if (!current)
20668
- throw new Error("Omp background delegation has no Agent state");
20669
20852
  if (event.type === "subagent.started") {
20670
20853
  this.#event({
20671
20854
  type: "subagent.state.changed",
@@ -20676,19 +20859,6 @@ var OmpHarnessSession = class {
20676
20859
  }
20677
20860
  if (event.type === "subagent.updated") {
20678
20861
  const status2 = this.#backgroundStatus(event.status);
20679
- const subagent2 = {
20680
- ...current,
20681
- status: status2,
20682
- ...event.description ? { description: event.description } : {},
20683
- ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
20684
- };
20685
- delegation.item = { ...delegation.item, subagents: [subagent2] };
20686
- this.#event({
20687
- type: "item.updated",
20688
- turnId: delegation.turnId,
20689
- itemId: delegation.item.itemId,
20690
- update: { type: "subagents.replace", subagents: delegation.item.subagents }
20691
- });
20692
20862
  this.#event({
20693
20863
  type: "subagent.state.changed",
20694
20864
  nativeSubagentId: event.nativeSubagentId,
@@ -20698,58 +20868,12 @@ var OmpHarnessSession = class {
20698
20868
  return;
20699
20869
  }
20700
20870
  const status = event.isError ? "failed" : "completed";
20701
- const subagent = {
20702
- ...current,
20703
- status,
20704
- ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
20705
- };
20706
- delegation.item = { ...delegation.item, subagents: [subagent] };
20707
- this.#event({
20708
- type: "item.updated",
20709
- turnId: delegation.turnId,
20710
- itemId: delegation.item.itemId,
20711
- update: { type: "subagents.replace", subagents: delegation.item.subagents }
20712
- });
20713
- this.#event({
20714
- type: "item.completed",
20715
- turnId: delegation.turnId,
20716
- snapshot: {
20717
- item: delegation.item,
20718
- outcome: event.isError ? {
20719
- status: "failed",
20720
- error: {
20721
- code: "nativeFailure",
20722
- message: "Omp background Subagent failed",
20723
- retryable: false
20724
- }
20725
- } : { status: "succeeded" }
20726
- }
20727
- });
20728
20871
  this.#event({
20729
20872
  type: "subagent.state.changed",
20730
20873
  nativeSubagentId: event.nativeSubagentId,
20731
20874
  status,
20732
20875
  ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
20733
20876
  });
20734
- this.#backgroundTurnFailed ||= event.isError;
20735
- this.#backgroundSubagents.delete(event.callId);
20736
- if (this.#backgroundSubagents.size === 0 && this.#backgroundTurnId === delegation.turnId) {
20737
- const turnId = this.#backgroundTurnId;
20738
- this.#backgroundTurnId = null;
20739
- this.#event({
20740
- type: "turn.completed",
20741
- turnId,
20742
- outcome: this.#backgroundTurnFailed ? {
20743
- status: "failed",
20744
- error: {
20745
- code: "nativeFailure",
20746
- message: "Omp background Subagent failed",
20747
- retryable: false
20748
- }
20749
- } : { status: "succeeded" }
20750
- });
20751
- this.#backgroundTurnFailed = false;
20752
- }
20753
20877
  }
20754
20878
  async readSnapshot() {
20755
20879
  if (this.#phase !== "open" && this.#phase !== "faulted") {
@@ -20807,6 +20931,8 @@ var OmpHarnessSession = class {
20807
20931
  }
20808
20932
  if (command.type === "turn.cancel")
20809
20933
  return this.#cancel(command);
20934
+ if (command.type === "turn.steer")
20935
+ return unsupportedSteer("OMP");
20810
20936
  if (command.type === "interaction.respond")
20811
20937
  return this.#respond(command);
20812
20938
  if (command.type === "model.select")
@@ -22002,6 +22128,9 @@ var OmpAdapter = class {
22002
22128
  #inspectionCache = /* @__PURE__ */ new Map();
22003
22129
  #inspectionInFlight = /* @__PURE__ */ new Map();
22004
22130
  #inspections = /* @__PURE__ */ new Set();
22131
+ #availabilityInFlight = /* @__PURE__ */ new Map();
22132
+ #availabilityListings = /* @__PURE__ */ new Set();
22133
+ #listModels;
22005
22134
  #sessions = /* @__PURE__ */ new Set();
22006
22135
  #toolOutputLimit;
22007
22136
  #closePromise = null;
@@ -22010,22 +22139,21 @@ var OmpAdapter = class {
22010
22139
  createTransport: (sessionOptions) => new OmpRpcSession({ ...options, ...sessionOptions })
22011
22140
  }) {
22012
22141
  this.#createTransport = dependencies.createTransport;
22142
+ const listModels = dependencies.listModels ?? listOmpModels;
22143
+ this.#listModels = ({ cwd, signal }) => listModels({
22144
+ cwd,
22145
+ signal,
22146
+ ...options.command ? { command: options.command } : {},
22147
+ ...options.environment ? { environment: options.environment } : {}
22148
+ });
22013
22149
  this.sessionImport = new OmpSessionImport({ ...process.env, ...options.environment });
22014
22150
  this.usageStatistics = createOmpUsageStatistics({ ...process.env, ...options.environment });
22015
22151
  this.#closeTimeoutMs = options.closeTimeoutMs ?? 2e3;
22016
22152
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_TOOL_OUTPUT_LIMIT;
22017
22153
  }
22018
22154
  async inspect(input = {}) {
22019
- if (this.#closePromise) {
22020
- return {
22021
- status: "unavailable",
22022
- error: {
22023
- code: "invalidState",
22024
- message: "Omp Adapter is closed",
22025
- retryable: false
22026
- }
22027
- };
22028
- }
22155
+ if (this.#closePromise)
22156
+ return closedInspection();
22029
22157
  const cwd = input.cwd ?? process.cwd();
22030
22158
  const inFlight = this.#inspectionInFlight.get(cwd);
22031
22159
  if (inFlight)
@@ -22035,6 +22163,37 @@ var OmpAdapter = class {
22035
22163
  if (cached2)
22036
22164
  return cached2;
22037
22165
  }
22166
+ if (input.purpose === "availability")
22167
+ return this.#inspectAvailability(cwd, input.refresh);
22168
+ return this.#startFullInspection(cwd);
22169
+ }
22170
+ /**
22171
+ * Availability without a Session: a Session startup runs OMP's own startup work, including
22172
+ * Provider connection prewarm, for a Harness the user may never select. The listed result
22173
+ * carries no native default Model or Thinking option, so it is neither cached nor used to
22174
+ * update `#thinkingSelectionSupported`. When the list cannot answer, a full inspection answers
22175
+ * instead, reusing one that is in flight or finished meanwhile.
22176
+ */
22177
+ async #inspectAvailability(cwd, refresh = false) {
22178
+ if (refresh)
22179
+ this.#inspectionCache.delete(cwd);
22180
+ let pending = this.#availabilityInFlight.get(cwd);
22181
+ if (!pending) {
22182
+ const listing = this.#listAvailability(cwd);
22183
+ pending = listing.finally(() => {
22184
+ if (this.#availabilityInFlight.get(cwd) === pending)
22185
+ this.#availabilityInFlight.delete(cwd);
22186
+ });
22187
+ this.#availabilityInFlight.set(cwd, pending);
22188
+ }
22189
+ const listed = await pending;
22190
+ if (listed)
22191
+ return listed;
22192
+ if (this.#closePromise)
22193
+ return closedInspection();
22194
+ return this.#inspectionInFlight.get(cwd) ?? this.#inspectionCache.get(cwd) ?? this.#startFullInspection(cwd);
22195
+ }
22196
+ #startFullInspection(cwd) {
22038
22197
  const inspection = this.#inspectCwd(cwd).then((result) => {
22039
22198
  if (result.status === "ready")
22040
22199
  this.#inspectionCache.set(cwd, result);
@@ -22047,6 +22206,59 @@ var OmpAdapter = class {
22047
22206
  }
22048
22207
  });
22049
22208
  }
22209
+ /** Returns null when a Session must answer: this OMP cannot list Models, or lists none. */
22210
+ async #listAvailability(cwd) {
22211
+ const startedAt = Date.now();
22212
+ const stage = "model-list";
22213
+ const controller = new AbortController();
22214
+ this.#availabilityListings.add(controller);
22215
+ let listed;
22216
+ try {
22217
+ listed = await this.#listModels({ cwd, signal: controller.signal });
22218
+ } finally {
22219
+ this.#availabilityListings.delete(controller);
22220
+ }
22221
+ if (listed.kind === "unanswered")
22222
+ return null;
22223
+ if (listed.kind === "notInstalled") {
22224
+ return {
22225
+ status: "notInstalled",
22226
+ error: {
22227
+ code: "notInstalled",
22228
+ message: listed.message,
22229
+ retryable: false,
22230
+ stage,
22231
+ durationMs: Date.now() - startedAt
22232
+ }
22233
+ };
22234
+ }
22235
+ if (listed.kind === "timedOut") {
22236
+ return {
22237
+ status: "error",
22238
+ error: {
22239
+ code: "unavailable",
22240
+ message: "Oh My Pi did not list its models in time",
22241
+ retryable: true,
22242
+ stage,
22243
+ durationMs: Date.now() - startedAt
22244
+ }
22245
+ };
22246
+ }
22247
+ if (listed.models.length === 0)
22248
+ return null;
22249
+ let catalog;
22250
+ try {
22251
+ catalog = normalizeOmpModelCatalog(listed.models, null, null, null);
22252
+ } catch {
22253
+ return null;
22254
+ }
22255
+ return {
22256
+ status: "ready",
22257
+ catalog,
22258
+ permissionModes: OMP_PERMISSION_MODE_CATALOG,
22259
+ capabilities: ompInspectionCapabilities(false)
22260
+ };
22261
+ }
22050
22262
  async #inspectCwd(cwd) {
22051
22263
  const startedAt = Date.now();
22052
22264
  let stage = "spawn";
@@ -22070,16 +22282,7 @@ var OmpAdapter = class {
22070
22282
  status: "ready",
22071
22283
  catalog,
22072
22284
  permissionModes: OMP_PERMISSION_MODE_CATALOG,
22073
- capabilities: {
22074
- configuration: {
22075
- selectModel: true,
22076
- selectThinkingOption: thinkingLevels !== null,
22077
- selectPermissionMode: true,
22078
- permissionModeScope: "live"
22079
- },
22080
- history: { fork: true, forkAcrossCwd: true, rollbackLastTurn: true },
22081
- subagents: { observe: true, readTranscript: true }
22082
- }
22285
+ capabilities: ompInspectionCapabilities(thinkingLevels !== null)
22083
22286
  };
22084
22287
  } catch (error51) {
22085
22288
  await transport.close().catch(() => void 0);
@@ -22290,6 +22493,8 @@ var OmpAdapter = class {
22290
22493
  }
22291
22494
  close() {
22292
22495
  if (!this.#closePromise) {
22496
+ for (const listing of this.#availabilityListings)
22497
+ listing.abort();
22293
22498
  this.#closePromise = Promise.all([
22294
22499
  this.sessionImport.close(),
22295
22500
  ...[...this.#inspections].map((transport) => transport.close()),