@liberseek/boft-cli-win32-arm64 0.7.6 → 0.7.7

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.
@@ -5,364 +5,767 @@ var __export = (target, all) => {
5
5
  __defProp(target, name, { get: all[name], enumerable: true });
6
6
  };
7
7
 
8
- // ../../../node_modules/diff/libesm/diff/base.js
9
- var Diff = class {
10
- diff(oldStr, newStr, options = {}) {
11
- let callback;
12
- if (typeof options === "function") {
13
- callback = options;
14
- options = {};
15
- } else if ("callback" in options) {
16
- callback = options.callback;
17
- }
18
- const oldString = this.castInput(oldStr, options);
19
- const newString = this.castInput(newStr, options);
20
- const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
21
- const newTokens = this.removeEmpty(this.tokenize(newString, options));
22
- return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
8
+ // ../../harness-discovery/dist/environment.js
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ function targetPath(platform) {
12
+ return platform === "win32" ? path.win32 : path.posix;
13
+ }
14
+ function environmentValue(environment, name) {
15
+ const lowered = name.toLowerCase();
16
+ for (const [key, value] of Object.entries(environment)) {
17
+ if (key.toLowerCase() === lowered)
18
+ return value;
23
19
  }
24
- diffWithOptionsObj(oldTokens, newTokens, options, callback) {
25
- var _a3;
26
- const done = (value) => {
27
- value = this.postProcess(value, options);
28
- if (callback) {
29
- setTimeout(function() {
30
- callback(value);
31
- }, 0);
32
- return void 0;
33
- } else {
34
- return value;
35
- }
36
- };
37
- const newLen = newTokens.length, oldLen = oldTokens.length;
38
- let editLength = 1;
39
- let maxEditLength = newLen + oldLen;
40
- if (options.maxEditLength != null) {
41
- maxEditLength = Math.min(maxEditLength, options.maxEditLength);
42
- }
43
- const maxExecutionTime = (_a3 = options.timeout) !== null && _a3 !== void 0 ? _a3 : Infinity;
44
- const abortAfterTimestamp = Date.now() + maxExecutionTime;
45
- const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
46
- let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
47
- if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
48
- return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
49
- }
50
- let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
51
- const execEditLength = () => {
52
- for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
53
- let basePath;
54
- const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
55
- if (removePath) {
56
- bestPath[diagonalPath - 1] = void 0;
57
- }
58
- let canAdd = false;
59
- if (addPath) {
60
- const addPathNewPos = addPath.oldPos - diagonalPath;
61
- canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
62
- }
63
- const canRemove = removePath && removePath.oldPos + 1 < oldLen;
64
- if (!canAdd && !canRemove) {
65
- bestPath[diagonalPath] = void 0;
66
- continue;
67
- }
68
- if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
69
- basePath = this.addToPath(addPath, true, false, 0, options);
70
- } else {
71
- basePath = this.addToPath(removePath, false, true, 1, options);
72
- }
73
- newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
74
- if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
75
- return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
76
- } else {
77
- bestPath[diagonalPath] = basePath;
78
- if (basePath.oldPos + 1 >= oldLen) {
79
- maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
80
- }
81
- if (newPos + 1 >= newLen) {
82
- minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
83
- }
84
- }
85
- }
86
- editLength++;
87
- };
88
- if (callback) {
89
- (function exec() {
90
- setTimeout(function() {
91
- if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
92
- return callback(void 0);
93
- }
94
- if (!execEditLength()) {
95
- exec();
96
- }
97
- }, 0);
98
- })();
99
- } else {
100
- while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
101
- const ret = execEditLength();
102
- if (ret) {
103
- return ret;
104
- }
105
- }
106
- }
20
+ return void 0;
21
+ }
22
+ function pathDelimiter(platform) {
23
+ return platform === "win32" ? ";" : ":";
24
+ }
25
+ function pathDirectories(environment, platform) {
26
+ return (environmentValue(environment, "PATH") ?? "").split(pathDelimiter(platform)).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean);
27
+ }
28
+ function executableExtensions(command, platform, environment) {
29
+ if (platform !== "win32")
30
+ return [""];
31
+ if (targetPath(platform).extname(command) !== "")
32
+ return [""];
33
+ return (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean);
34
+ }
35
+ function isExecutableFile(filePath, platform) {
36
+ try {
37
+ fs.accessSync(filePath, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
38
+ return fs.statSync(filePath).isFile();
39
+ } catch {
40
+ return false;
107
41
  }
108
- addToPath(path7, added, removed, oldPosInc, options) {
109
- const last = path7.lastComponent;
110
- if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
111
- return {
112
- oldPos: path7.oldPos + oldPosInc,
113
- lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
114
- };
115
- } else {
116
- return {
117
- oldPos: path7.oldPos + oldPosInc,
118
- lastComponent: { count: 1, added, removed, previousComponent: last }
119
- };
120
- }
42
+ }
43
+ function subdirectoryNames(directory) {
44
+ try {
45
+ return fs.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
46
+ } catch {
47
+ return [];
121
48
  }
122
- extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
123
- const newLen = newTokens.length, oldLen = oldTokens.length;
124
- let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
125
- while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
126
- newPos++;
127
- oldPos++;
128
- commonCount++;
129
- if (options.oneChangePerToken) {
130
- basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
131
- }
132
- }
133
- if (commonCount && !options.oneChangePerToken) {
134
- basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
135
- }
136
- basePath.oldPos = oldPos;
137
- return newPos;
49
+ }
50
+ function newestFirst(names) {
51
+ return [...names].sort((left, right) => right.localeCompare(left, void 0, { numeric: true }));
52
+ }
53
+
54
+ // ../../harness-discovery/dist/invocation.js
55
+ import path2 from "node:path";
56
+ function commandInvocation(command, arguments_, environment, platform = process.platform) {
57
+ const extension = path2.win32.extname(command).toLowerCase();
58
+ if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
59
+ return { command, arguments: [...arguments_], windowsVerbatimArguments: false };
138
60
  }
139
- equals(left, right, options) {
140
- if (options.comparator) {
141
- return options.comparator(left, right);
142
- } else {
143
- return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
144
- }
61
+ const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
62
+ const commandLine = [command, ...arguments_].map(quote).join(" ");
63
+ return {
64
+ command: environmentValue(environment, "ComSpec") ?? "cmd.exe",
65
+ arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
66
+ windowsVerbatimArguments: true
67
+ };
68
+ }
69
+
70
+ // ../../harness-discovery/dist/node-runtime.js
71
+ import path3 from "node:path";
72
+ function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath, platform = process.platform) {
73
+ const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
74
+ const delimiter = platform === "win32" ? ";" : ":";
75
+ const runtimeDirectory = path3.dirname(runtimeExecutable);
76
+ const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
77
+ const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
78
+ if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
79
+ directories.push(runtimeDirectory);
145
80
  }
146
- removeEmpty(array2) {
147
- const ret = [];
148
- for (let i = 0; i < array2.length; i++) {
149
- if (array2[i]) {
150
- ret.push(array2[i]);
151
- }
81
+ return { ...environment, [pathKey]: directories.join(delimiter) };
82
+ }
83
+
84
+ // ../../harness-discovery/dist/resolve.js
85
+ import os from "node:os";
86
+
87
+ // ../../harness-discovery/dist/version-managers.js
88
+ function versionManagerBinaryDirectories(context) {
89
+ const { platform, environment, home } = context;
90
+ const list = context.subdirectories ?? subdirectoryNames;
91
+ const pathFlavor = targetPath(platform);
92
+ const value = (name) => environmentValue(environment, name);
93
+ const directories = [];
94
+ const versioned = (root, ...tail) => {
95
+ for (const version2 of newestFirst(list(root))) {
96
+ directories.push(pathFlavor.join(root, version2, ...tail));
152
97
  }
153
- return ret;
154
- }
155
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
156
- castInput(value, options) {
157
- return value;
158
- }
159
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
160
- tokenize(value, options) {
161
- return Array.from(value);
98
+ };
99
+ if (platform === "win32") {
100
+ const appData = value("APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming");
101
+ const localAppData = value("LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local");
102
+ versioned(pathFlavor.join(appData, "nvm"));
103
+ versioned(value("FNM_DIR") ?? pathFlavor.join(appData, "fnm", "node-versions"), "installation");
104
+ directories.push(pathFlavor.join(localAppData, "Volta", "bin"));
105
+ directories.push(pathFlavor.join(home, ".bun", "bin"));
106
+ const pnpmHome2 = value("PNPM_HOME");
107
+ if (pnpmHome2)
108
+ directories.push(pnpmHome2);
109
+ directories.push(pathFlavor.join(localAppData, "pnpm"));
110
+ return directories;
162
111
  }
163
- join(chars) {
164
- return chars.join("");
112
+ versioned(pathFlavor.join(value("NVM_DIR") ?? pathFlavor.join(home, ".nvm"), "versions", "node"), "bin");
113
+ const fnmRoots = [
114
+ value("FNM_DIR"),
115
+ pathFlavor.join(home, ".local", "share", "fnm"),
116
+ pathFlavor.join(home, "Library", "Application Support", "fnm")
117
+ ].filter((root) => root !== void 0);
118
+ for (const root of fnmRoots) {
119
+ versioned(pathFlavor.join(root, "node-versions"), "installation", "bin");
165
120
  }
166
- postProcess(changeObjects, options) {
167
- return changeObjects;
168
- }
169
- get useLongestToken() {
170
- return false;
121
+ const voltaHome = value("VOLTA_HOME") ?? pathFlavor.join(home, ".volta");
122
+ versioned(pathFlavor.join(voltaHome, "tools", "image", "node"), "bin");
123
+ directories.push(pathFlavor.join(voltaHome, "bin"));
124
+ const asdfHome = value("ASDF_DATA_DIR") ?? pathFlavor.join(home, ".asdf");
125
+ versioned(pathFlavor.join(asdfHome, "installs", "nodejs"), "bin");
126
+ directories.push(pathFlavor.join(asdfHome, "shims"));
127
+ const nodenvHome = value("NODENV_ROOT") ?? pathFlavor.join(home, ".nodenv");
128
+ versioned(pathFlavor.join(nodenvHome, "versions"), "bin");
129
+ directories.push(pathFlavor.join(nodenvHome, "shims"));
130
+ versioned(pathFlavor.join(value("N_PREFIX") ?? "/usr/local", "n", "versions", "node"), "bin");
131
+ directories.push(pathFlavor.join(home, ".bun", "bin"));
132
+ const pnpmHome = value("PNPM_HOME");
133
+ if (pnpmHome)
134
+ directories.push(pnpmHome);
135
+ directories.push(pathFlavor.join(home, "Library", "pnpm"));
136
+ directories.push(pathFlavor.join(home, ".local", "share", "pnpm"));
137
+ for (const prefix of ["/opt/homebrew/opt", "/usr/local/opt"]) {
138
+ for (const formula of newestFirst(list(prefix).filter((name) => name.startsWith("node@")))) {
139
+ directories.push(pathFlavor.join(prefix, formula, "bin"));
140
+ }
171
141
  }
172
- buildValues(lastComponent, newTokens, oldTokens) {
173
- const components = [];
174
- let nextComponent;
175
- while (lastComponent) {
176
- components.push(lastComponent);
177
- nextComponent = lastComponent.previousComponent;
178
- delete lastComponent.previousComponent;
179
- lastComponent = nextComponent;
142
+ return directories;
143
+ }
144
+
145
+ // ../../harness-discovery/dist/resolve.js
146
+ var VERSION_MANAGER_ROOTS = "<version-managers>";
147
+ function installRootExtensions(platform) {
148
+ return platform === "win32" ? [".exe", ".cmd"] : [""];
149
+ }
150
+ function resolveHomeDirectory(input) {
151
+ return input.homeDirectory ?? environmentValue(input.environment, "HOME") ?? environmentValue(input.environment, "USERPROFILE") ?? os.homedir();
152
+ }
153
+ function templateVariables(environment, platform, home) {
154
+ const pathFlavor = targetPath(platform);
155
+ return {
156
+ HOME: home,
157
+ USERPROFILE: home,
158
+ APPDATA: environmentValue(environment, "APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming"),
159
+ LOCALAPPDATA: environmentValue(environment, "LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local")
160
+ };
161
+ }
162
+ function joinTemplate(platform, value) {
163
+ const pathFlavor = targetPath(platform);
164
+ const segments = value.split("/");
165
+ const head = segments[0] ?? "";
166
+ const tail = segments.slice(1);
167
+ if (head === "")
168
+ return pathFlavor.join(pathFlavor.sep, ...tail);
169
+ return tail.length === 0 ? head : pathFlavor.join(head, ...tail);
170
+ }
171
+ function expandInstallRoot(template, environment, platform, home) {
172
+ const variables = templateVariables(environment, platform, home);
173
+ let unresolved = false;
174
+ const substituted = template.replace(/^~(?=\/|$)/u, home).replace(/\$\{(\w+)\}/gu, (_match, name) => {
175
+ const value = variables[name] ?? environmentValue(environment, name);
176
+ if (value === void 0 || value === "") {
177
+ unresolved = true;
178
+ return "";
180
179
  }
181
- components.reverse();
182
- const componentLen = components.length;
183
- let componentPos = 0, newPos = 0, oldPos = 0;
184
- for (; componentPos < componentLen; componentPos++) {
185
- const component = components[componentPos];
186
- if (!component.removed) {
187
- if (!component.added && this.useLongestToken) {
188
- let value = newTokens.slice(newPos, newPos + component.count);
189
- value = value.map(function(value2, i) {
190
- const oldValue = oldTokens[oldPos + i];
191
- return oldValue.length > value2.length ? oldValue : value2;
192
- });
193
- component.value = this.join(value);
194
- } else {
195
- component.value = this.join(newTokens.slice(newPos, newPos + component.count));
196
- }
197
- newPos += component.count;
198
- if (!component.added) {
199
- oldPos += component.count;
200
- }
201
- } else {
202
- component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
203
- oldPos += component.count;
204
- }
180
+ return value;
181
+ });
182
+ return unresolved ? void 0 : joinTemplate(platform, substituted);
183
+ }
184
+ function installRootDirectories(spec, input, dependencies, platform, home) {
185
+ const templates = (platform === "win32" ? spec.installRoots?.windows : spec.installRoots?.posix) ?? [];
186
+ const directories = [];
187
+ for (const template of templates) {
188
+ if (template === VERSION_MANAGER_ROOTS) {
189
+ directories.push(...versionManagerBinaryDirectories({
190
+ platform,
191
+ environment: input.environment,
192
+ home,
193
+ ...dependencies.subdirectories ? { subdirectories: dependencies.subdirectories } : {}
194
+ }));
195
+ continue;
205
196
  }
206
- return components;
197
+ const directory = expandInstallRoot(template, input.environment, platform, home);
198
+ if (directory !== void 0)
199
+ directories.push(directory);
207
200
  }
208
- };
209
-
210
- // ../../../node_modules/diff/libesm/diff/line.js
211
- var LineDiff = class extends Diff {
212
- constructor() {
213
- super(...arguments);
214
- this.tokenize = tokenize;
201
+ return directories;
202
+ }
203
+ function harnessCandidates(spec, input, dependencies = {}) {
204
+ const platform = input.platform ?? process.platform;
205
+ const pathFlavor = targetPath(platform);
206
+ const configured = input.command ?? (spec.commandEnvironmentVariable ? environmentValue(input.environment, spec.commandEnvironmentVariable) : void 0);
207
+ const command = configured ?? spec.command;
208
+ if (pathFlavor.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
209
+ return [{ candidate: command, source: "configured" }];
215
210
  }
216
- equals(left, right, options) {
217
- if (options.ignoreWhitespace) {
218
- if (!options.newlineIsToken || !left.includes("\n")) {
219
- left = left.trim();
220
- }
221
- if (!options.newlineIsToken || !right.includes("\n")) {
222
- right = right.trim();
223
- }
224
- } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
225
- if (left.endsWith("\n")) {
226
- left = left.slice(0, -1);
227
- }
228
- if (right.endsWith("\n")) {
229
- right = right.slice(0, -1);
230
- }
211
+ const candidates = [];
212
+ const extensions = executableExtensions(command, platform, input.environment);
213
+ for (const directory of pathDirectories(input.environment, platform)) {
214
+ for (const extension of extensions) {
215
+ candidates.push({
216
+ candidate: pathFlavor.join(directory, command + extension),
217
+ source: "path"
218
+ });
231
219
  }
232
- return super.equals(left, right, options);
233
220
  }
234
- };
235
- var lineDiff = new LineDiff();
236
- function diffLines(oldStr, newStr, options) {
237
- return lineDiff.diff(oldStr, newStr, options);
221
+ if (configured !== void 0)
222
+ return candidates;
223
+ const home = resolveHomeDirectory(input);
224
+ for (const directory of installRootDirectories(spec, input, dependencies, platform, home)) {
225
+ for (const extension of installRootExtensions(platform)) {
226
+ candidates.push({
227
+ candidate: pathFlavor.join(directory, spec.command + extension),
228
+ source: "install-root"
229
+ });
230
+ }
231
+ }
232
+ return candidates;
238
233
  }
239
- function tokenize(value, options) {
240
- if (options.stripTrailingCr) {
241
- value = value.replace(/\r\n/g, "\n");
234
+ function resolveHarnessExecutable(spec, input, dependencies = {}) {
235
+ const platform = input.platform ?? process.platform;
236
+ const isExecutable = dependencies.isExecutable ?? ((candidate) => isExecutableFile(candidate, platform));
237
+ const runnable = spec.runnableCandidate ?? ((candidate) => candidate);
238
+ const context = { platform, isExecutable };
239
+ for (const { candidate, source } of harnessCandidates(spec, input, dependencies)) {
240
+ const executable = runnable(candidate, context);
241
+ if (executable !== void 0 && isExecutable(executable))
242
+ return { executable, source };
242
243
  }
243
- const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
244
- if (!linesAndNewlines[linesAndNewlines.length - 1]) {
245
- linesAndNewlines.pop();
244
+ return void 0;
245
+ }
246
+
247
+ // ../../harness-discovery/dist/installation.js
248
+ import { execFile } from "node:child_process";
249
+ import { homedir } from "node:os";
250
+ function runInstallationCommand(command, args, environment, timeout = 3e4) {
251
+ const env = withNodeRuntimeOnPath(environment);
252
+ const invocation = /\.[cm]?js$/i.test(command) ? commandInvocation(process.execPath, [command, ...args], env) : commandInvocation(command, args, env);
253
+ return new Promise((resolve, reject) => {
254
+ const child = execFile(invocation.command, invocation.arguments, {
255
+ env,
256
+ cwd: env.HOME ?? env.USERPROFILE ?? homedir(),
257
+ encoding: "utf8",
258
+ timeout,
259
+ killSignal: "SIGKILL",
260
+ maxBuffer: 1024 * 1024,
261
+ windowsHide: true,
262
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments
263
+ }, (error51, stdout, stderr) => {
264
+ if (error51)
265
+ reject(new Error(error51.killed ? "Harness command timed out" : "Harness command failed; check the native installation and retry"));
266
+ else
267
+ resolve((stdout || stderr).trim());
268
+ });
269
+ child.stdin?.end();
270
+ });
271
+ }
272
+ function installationVersion(value) {
273
+ if (typeof value !== "string" || !/^v?\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(value.trim()))
274
+ throw new Error("Harness returned an invalid version");
275
+ return value.trim().replace(/^v/, "");
276
+ }
277
+ function versionFromOutput(output) {
278
+ return installationVersion(output.match(/\b\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?\b/)?.[0]);
279
+ }
280
+ function newerInstallationVersion(current, latest) {
281
+ const a = installationVersion(current).replace(/\+.*/, "");
282
+ const b = installationVersion(latest).replace(/\+.*/, "");
283
+ const coreA = a.replace(/-.*/, "").split(".").map(BigInt);
284
+ const coreB = b.replace(/-.*/, "").split(".").map(BigInt);
285
+ for (let i = 0; i < Math.max(coreA.length, coreB.length); i++) {
286
+ if ((coreA[i] ?? 0n) !== (coreB[i] ?? 0n))
287
+ return (coreB[i] ?? 0n) > (coreA[i] ?? 0n);
246
288
  }
247
- for (let i = 0; i < linesAndNewlines.length; i++) {
248
- const line = linesAndNewlines[i];
249
- if (i % 2 && !options.newlineIsToken) {
250
- retLines[retLines.length - 1] += line;
251
- } else {
252
- retLines.push(line);
289
+ const preA = a.includes("-") ? a.slice(a.indexOf("-") + 1).split(".") : [];
290
+ const preB = b.includes("-") ? b.slice(b.indexOf("-") + 1).split(".") : [];
291
+ if (!preA.length || !preB.length)
292
+ return !!preA.length && !preB.length;
293
+ for (let i = 0; i < Math.max(preA.length, preB.length); i++) {
294
+ const x = preA[i];
295
+ const y = preB[i];
296
+ if (x === y)
297
+ continue;
298
+ if (x === void 0 || y === void 0)
299
+ return x === void 0;
300
+ const numericX = /^\d+$/.test(x);
301
+ const numericY = /^\d+$/.test(y);
302
+ if (numericX && numericY) {
303
+ if (BigInt(x) === BigInt(y))
304
+ continue;
305
+ return BigInt(y) > BigInt(x);
253
306
  }
307
+ if (numericX !== numericY)
308
+ return numericX;
309
+ return y > x;
310
+ }
311
+ return false;
312
+ }
313
+ function createInstallationManager(options) {
314
+ let checking;
315
+ let updating;
316
+ const check2 = () => checking ??= options.check().finally(() => {
317
+ checking = void 0;
318
+ });
319
+ return (action) => {
320
+ if (updating)
321
+ return updating;
322
+ if (action === "check")
323
+ return check2();
324
+ updating = (async () => {
325
+ const before = await check2();
326
+ if (!before.updateAvailable)
327
+ return before;
328
+ if (!before.canUpdate)
329
+ throw new Error(before.message ?? "This installation cannot be updated automatically");
330
+ await options.update(before);
331
+ const after = await check2();
332
+ if (after.currentVersion === before.currentVersion)
333
+ throw new Error("The Harness version did not change; check the native updater and retry");
334
+ return after;
335
+ })().finally(() => {
336
+ updating = void 0;
337
+ });
338
+ return updating;
339
+ };
340
+ }
341
+ async function fetchInstallationText(url2) {
342
+ const request = async () => {
343
+ const response = await fetch(url2, { signal: AbortSignal.timeout(15e3) });
344
+ if (!response.ok)
345
+ throw new Error("Could not check the latest Harness version");
346
+ return response.text();
347
+ };
348
+ try {
349
+ return await request();
350
+ } catch (error51) {
351
+ if (error51 instanceof DOMException && (error51.name === "AbortError" || error51.name === "TimeoutError"))
352
+ throw error51;
353
+ return request();
254
354
  }
255
- return retLines;
256
355
  }
257
356
 
258
- // ../../../node_modules/diff/libesm/patch/parse.js
259
- function parsePatch(uniDiff) {
260
- const diffstr = uniDiff.split(/\n/), list = [];
261
- let i = 0;
262
- function parseIndex() {
263
- const index = {};
264
- list.push(index);
265
- while (i < diffstr.length) {
266
- const line = diffstr[i];
267
- if (/^(---|\+\+\+|@@)\s/.test(line)) {
268
- break;
269
- }
270
- const header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
271
- if (header) {
272
- index.index = header[1];
273
- }
274
- i++;
357
+ // ../../harness-discovery/dist/installer.js
358
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
359
+ import { tmpdir } from "node:os";
360
+ import { join } from "node:path";
361
+ function createHarnessInstaller(environment, source) {
362
+ return async () => {
363
+ if (!["darwin", "linux", "win32"].includes(process.platform))
364
+ throw new Error("Unsupported installation platform");
365
+ const env = withNodeRuntimeOnPath(environment);
366
+ if ("npm" in source) {
367
+ const npm = resolveHarnessExecutable({
368
+ id: "npm",
369
+ command: "npm",
370
+ installRoots: {
371
+ posix: [
372
+ "~/.npm-global/bin",
373
+ "~/.local/bin",
374
+ VERSION_MANAGER_ROOTS,
375
+ "/opt/homebrew/bin",
376
+ "/usr/local/bin",
377
+ "/usr/bin"
378
+ ],
379
+ windows: [
380
+ "${APPDATA}/npm",
381
+ VERSION_MANAGER_ROOTS,
382
+ "${ProgramFiles}/nodejs",
383
+ "${LOCALAPPDATA}/Programs/nodejs"
384
+ ]
385
+ }
386
+ }, { environment: env });
387
+ if (!npm)
388
+ throw new Error("Install Node.js and npm first");
389
+ await runInstallationCommand(npm.executable, ["install", "--global", source.npm], {
390
+ ...env,
391
+ ...source.allowScripts ? { npm_config_allow_scripts: source.allowScripts } : {}
392
+ }, 6e5);
393
+ return;
275
394
  }
276
- parseFileHeader(index);
277
- parseFileHeader(index);
278
- index.hunks = [];
279
- while (i < diffstr.length) {
280
- const line = diffstr[i];
281
- if (/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/.test(line)) {
282
- break;
283
- } else if (/^@@/.test(line)) {
284
- index.hunks.push(parseHunk());
285
- } else if (line) {
286
- throw new Error("Unknown line " + (i + 1) + " " + JSON.stringify(line));
287
- } else {
288
- i++;
289
- }
395
+ const windows = process.platform === "win32";
396
+ const url2 = windows ? source.windows : source.posix;
397
+ if (new URL(url2).protocol !== "https:")
398
+ throw new Error("Installer requires HTTPS");
399
+ const script = await fetchInstallationText(url2);
400
+ const directory = await mkdtemp(join(tmpdir(), "codexhost-installer-"));
401
+ try {
402
+ const file2 = join(directory, windows ? "install.ps1" : "install.sh");
403
+ await writeFile(file2, script, { mode: 384 });
404
+ await runInstallationCommand(windows ? "powershell.exe" : source.shell ?? "bash", windows ? ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file2] : [file2], env, 6e5);
405
+ } finally {
406
+ await rm(directory, { recursive: true, force: true });
290
407
  }
291
- }
292
- function parseFileHeader(index) {
293
- const fileHeader = /^(---|\+\+\+)\s+(.*)\r?$/.exec(diffstr[i]);
294
- if (fileHeader) {
295
- const data = fileHeader[2].split(" ", 2), header = (data[1] || "").trim();
296
- let fileName = data[0].replace(/\\\\/g, "\\");
297
- if (/^".*"$/.test(fileName)) {
298
- fileName = fileName.substr(1, fileName.length - 2);
299
- }
300
- if (fileHeader[1] === "---") {
301
- index.oldFileName = fileName;
302
- index.oldHeader = header;
303
- } else {
304
- index.newFileName = fileName;
305
- index.newHeader = header;
306
- }
307
- i++;
408
+ };
409
+ }
410
+
411
+ // ../../../node_modules/diff/libesm/diff/base.js
412
+ var Diff = class {
413
+ diff(oldStr, newStr, options = {}) {
414
+ let callback;
415
+ if (typeof options === "function") {
416
+ callback = options;
417
+ options = {};
418
+ } else if ("callback" in options) {
419
+ callback = options.callback;
308
420
  }
421
+ const oldString = this.castInput(oldStr, options);
422
+ const newString = this.castInput(newStr, options);
423
+ const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
424
+ const newTokens = this.removeEmpty(this.tokenize(newString, options));
425
+ return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
309
426
  }
310
- function parseHunk() {
427
+ diffWithOptionsObj(oldTokens, newTokens, options, callback) {
311
428
  var _a3;
312
- const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
313
- const hunk = {
314
- oldStart: +chunkHeader[1],
315
- oldLines: typeof chunkHeader[2] === "undefined" ? 1 : +chunkHeader[2],
316
- newStart: +chunkHeader[3],
317
- newLines: typeof chunkHeader[4] === "undefined" ? 1 : +chunkHeader[4],
318
- lines: []
429
+ const done = (value) => {
430
+ value = this.postProcess(value, options);
431
+ if (callback) {
432
+ setTimeout(function() {
433
+ callback(value);
434
+ }, 0);
435
+ return void 0;
436
+ } else {
437
+ return value;
438
+ }
319
439
  };
320
- if (hunk.oldLines === 0) {
321
- hunk.oldStart += 1;
440
+ const newLen = newTokens.length, oldLen = oldTokens.length;
441
+ let editLength = 1;
442
+ let maxEditLength = newLen + oldLen;
443
+ if (options.maxEditLength != null) {
444
+ maxEditLength = Math.min(maxEditLength, options.maxEditLength);
322
445
  }
323
- if (hunk.newLines === 0) {
324
- hunk.newStart += 1;
446
+ const maxExecutionTime = (_a3 = options.timeout) !== null && _a3 !== void 0 ? _a3 : Infinity;
447
+ const abortAfterTimestamp = Date.now() + maxExecutionTime;
448
+ const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
449
+ let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
450
+ if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
451
+ return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
325
452
  }
326
- let addCount = 0, removeCount = 0;
327
- for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a3 = diffstr[i]) === null || _a3 === void 0 ? void 0 : _a3.startsWith("\\"))); i++) {
328
- const operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? " " : diffstr[i][0];
329
- if (operation === "+" || operation === "-" || operation === " " || operation === "\\") {
330
- hunk.lines.push(diffstr[i]);
331
- if (operation === "+") {
332
- addCount++;
333
- } else if (operation === "-") {
334
- removeCount++;
335
- } else if (operation === " ") {
336
- addCount++;
337
- removeCount++;
453
+ let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
454
+ const execEditLength = () => {
455
+ for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
456
+ let basePath;
457
+ const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
458
+ if (removePath) {
459
+ bestPath[diagonalPath - 1] = void 0;
460
+ }
461
+ let canAdd = false;
462
+ if (addPath) {
463
+ const addPathNewPos = addPath.oldPos - diagonalPath;
464
+ canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
465
+ }
466
+ const canRemove = removePath && removePath.oldPos + 1 < oldLen;
467
+ if (!canAdd && !canRemove) {
468
+ bestPath[diagonalPath] = void 0;
469
+ continue;
470
+ }
471
+ if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
472
+ basePath = this.addToPath(addPath, true, false, 0, options);
473
+ } else {
474
+ basePath = this.addToPath(removePath, false, true, 1, options);
475
+ }
476
+ newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
477
+ if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
478
+ return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
479
+ } else {
480
+ bestPath[diagonalPath] = basePath;
481
+ if (basePath.oldPos + 1 >= oldLen) {
482
+ maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
483
+ }
484
+ if (newPos + 1 >= newLen) {
485
+ minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
486
+ }
487
+ }
488
+ }
489
+ editLength++;
490
+ };
491
+ if (callback) {
492
+ (function exec() {
493
+ setTimeout(function() {
494
+ if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
495
+ return callback(void 0);
496
+ }
497
+ if (!execEditLength()) {
498
+ exec();
499
+ }
500
+ }, 0);
501
+ })();
502
+ } else {
503
+ while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
504
+ const ret = execEditLength();
505
+ if (ret) {
506
+ return ret;
338
507
  }
339
- } else {
340
- throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`);
341
508
  }
342
509
  }
343
- if (!addCount && hunk.newLines === 1) {
344
- hunk.newLines = 0;
345
- }
346
- if (!removeCount && hunk.oldLines === 1) {
347
- hunk.oldLines = 0;
510
+ }
511
+ addToPath(path7, added, removed, oldPosInc, options) {
512
+ const last = path7.lastComponent;
513
+ if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
514
+ return {
515
+ oldPos: path7.oldPos + oldPosInc,
516
+ lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
517
+ };
518
+ } else {
519
+ return {
520
+ oldPos: path7.oldPos + oldPosInc,
521
+ lastComponent: { count: 1, added, removed, previousComponent: last }
522
+ };
348
523
  }
349
- if (addCount !== hunk.newLines) {
350
- throw new Error("Added line count did not match for hunk at line " + (chunkHeaderIndex + 1));
524
+ }
525
+ extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
526
+ const newLen = newTokens.length, oldLen = oldTokens.length;
527
+ let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
528
+ while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
529
+ newPos++;
530
+ oldPos++;
531
+ commonCount++;
532
+ if (options.oneChangePerToken) {
533
+ basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
534
+ }
351
535
  }
352
- if (removeCount !== hunk.oldLines) {
353
- throw new Error("Removed line count did not match for hunk at line " + (chunkHeaderIndex + 1));
536
+ if (commonCount && !options.oneChangePerToken) {
537
+ basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
354
538
  }
355
- return hunk;
539
+ basePath.oldPos = oldPos;
540
+ return newPos;
356
541
  }
357
- while (i < diffstr.length) {
358
- parseIndex();
542
+ equals(left, right, options) {
543
+ if (options.comparator) {
544
+ return options.comparator(left, right);
545
+ } else {
546
+ return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
547
+ }
359
548
  }
360
- return list;
361
- }
362
-
363
- // ../../../node_modules/diff/libesm/patch/create.js
364
- function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
365
- let optionsObj;
549
+ removeEmpty(array2) {
550
+ const ret = [];
551
+ for (let i = 0; i < array2.length; i++) {
552
+ if (array2[i]) {
553
+ ret.push(array2[i]);
554
+ }
555
+ }
556
+ return ret;
557
+ }
558
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
559
+ castInput(value, options) {
560
+ return value;
561
+ }
562
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
563
+ tokenize(value, options) {
564
+ return Array.from(value);
565
+ }
566
+ join(chars) {
567
+ return chars.join("");
568
+ }
569
+ postProcess(changeObjects, options) {
570
+ return changeObjects;
571
+ }
572
+ get useLongestToken() {
573
+ return false;
574
+ }
575
+ buildValues(lastComponent, newTokens, oldTokens) {
576
+ const components = [];
577
+ let nextComponent;
578
+ while (lastComponent) {
579
+ components.push(lastComponent);
580
+ nextComponent = lastComponent.previousComponent;
581
+ delete lastComponent.previousComponent;
582
+ lastComponent = nextComponent;
583
+ }
584
+ components.reverse();
585
+ const componentLen = components.length;
586
+ let componentPos = 0, newPos = 0, oldPos = 0;
587
+ for (; componentPos < componentLen; componentPos++) {
588
+ const component = components[componentPos];
589
+ if (!component.removed) {
590
+ if (!component.added && this.useLongestToken) {
591
+ let value = newTokens.slice(newPos, newPos + component.count);
592
+ value = value.map(function(value2, i) {
593
+ const oldValue = oldTokens[oldPos + i];
594
+ return oldValue.length > value2.length ? oldValue : value2;
595
+ });
596
+ component.value = this.join(value);
597
+ } else {
598
+ component.value = this.join(newTokens.slice(newPos, newPos + component.count));
599
+ }
600
+ newPos += component.count;
601
+ if (!component.added) {
602
+ oldPos += component.count;
603
+ }
604
+ } else {
605
+ component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
606
+ oldPos += component.count;
607
+ }
608
+ }
609
+ return components;
610
+ }
611
+ };
612
+
613
+ // ../../../node_modules/diff/libesm/diff/line.js
614
+ var LineDiff = class extends Diff {
615
+ constructor() {
616
+ super(...arguments);
617
+ this.tokenize = tokenize;
618
+ }
619
+ equals(left, right, options) {
620
+ if (options.ignoreWhitespace) {
621
+ if (!options.newlineIsToken || !left.includes("\n")) {
622
+ left = left.trim();
623
+ }
624
+ if (!options.newlineIsToken || !right.includes("\n")) {
625
+ right = right.trim();
626
+ }
627
+ } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
628
+ if (left.endsWith("\n")) {
629
+ left = left.slice(0, -1);
630
+ }
631
+ if (right.endsWith("\n")) {
632
+ right = right.slice(0, -1);
633
+ }
634
+ }
635
+ return super.equals(left, right, options);
636
+ }
637
+ };
638
+ var lineDiff = new LineDiff();
639
+ function diffLines(oldStr, newStr, options) {
640
+ return lineDiff.diff(oldStr, newStr, options);
641
+ }
642
+ function tokenize(value, options) {
643
+ if (options.stripTrailingCr) {
644
+ value = value.replace(/\r\n/g, "\n");
645
+ }
646
+ const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
647
+ if (!linesAndNewlines[linesAndNewlines.length - 1]) {
648
+ linesAndNewlines.pop();
649
+ }
650
+ for (let i = 0; i < linesAndNewlines.length; i++) {
651
+ const line = linesAndNewlines[i];
652
+ if (i % 2 && !options.newlineIsToken) {
653
+ retLines[retLines.length - 1] += line;
654
+ } else {
655
+ retLines.push(line);
656
+ }
657
+ }
658
+ return retLines;
659
+ }
660
+
661
+ // ../../../node_modules/diff/libesm/patch/parse.js
662
+ function parsePatch(uniDiff) {
663
+ const diffstr = uniDiff.split(/\n/), list = [];
664
+ let i = 0;
665
+ function parseIndex() {
666
+ const index = {};
667
+ list.push(index);
668
+ while (i < diffstr.length) {
669
+ const line = diffstr[i];
670
+ if (/^(---|\+\+\+|@@)\s/.test(line)) {
671
+ break;
672
+ }
673
+ const header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
674
+ if (header) {
675
+ index.index = header[1];
676
+ }
677
+ i++;
678
+ }
679
+ parseFileHeader(index);
680
+ parseFileHeader(index);
681
+ index.hunks = [];
682
+ while (i < diffstr.length) {
683
+ const line = diffstr[i];
684
+ if (/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/.test(line)) {
685
+ break;
686
+ } else if (/^@@/.test(line)) {
687
+ index.hunks.push(parseHunk());
688
+ } else if (line) {
689
+ throw new Error("Unknown line " + (i + 1) + " " + JSON.stringify(line));
690
+ } else {
691
+ i++;
692
+ }
693
+ }
694
+ }
695
+ function parseFileHeader(index) {
696
+ const fileHeader = /^(---|\+\+\+)\s+(.*)\r?$/.exec(diffstr[i]);
697
+ if (fileHeader) {
698
+ const data = fileHeader[2].split(" ", 2), header = (data[1] || "").trim();
699
+ let fileName = data[0].replace(/\\\\/g, "\\");
700
+ if (/^".*"$/.test(fileName)) {
701
+ fileName = fileName.substr(1, fileName.length - 2);
702
+ }
703
+ if (fileHeader[1] === "---") {
704
+ index.oldFileName = fileName;
705
+ index.oldHeader = header;
706
+ } else {
707
+ index.newFileName = fileName;
708
+ index.newHeader = header;
709
+ }
710
+ i++;
711
+ }
712
+ }
713
+ function parseHunk() {
714
+ var _a3;
715
+ const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
716
+ const hunk = {
717
+ oldStart: +chunkHeader[1],
718
+ oldLines: typeof chunkHeader[2] === "undefined" ? 1 : +chunkHeader[2],
719
+ newStart: +chunkHeader[3],
720
+ newLines: typeof chunkHeader[4] === "undefined" ? 1 : +chunkHeader[4],
721
+ lines: []
722
+ };
723
+ if (hunk.oldLines === 0) {
724
+ hunk.oldStart += 1;
725
+ }
726
+ if (hunk.newLines === 0) {
727
+ hunk.newStart += 1;
728
+ }
729
+ let addCount = 0, removeCount = 0;
730
+ for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a3 = diffstr[i]) === null || _a3 === void 0 ? void 0 : _a3.startsWith("\\"))); i++) {
731
+ const operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? " " : diffstr[i][0];
732
+ if (operation === "+" || operation === "-" || operation === " " || operation === "\\") {
733
+ hunk.lines.push(diffstr[i]);
734
+ if (operation === "+") {
735
+ addCount++;
736
+ } else if (operation === "-") {
737
+ removeCount++;
738
+ } else if (operation === " ") {
739
+ addCount++;
740
+ removeCount++;
741
+ }
742
+ } else {
743
+ throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`);
744
+ }
745
+ }
746
+ if (!addCount && hunk.newLines === 1) {
747
+ hunk.newLines = 0;
748
+ }
749
+ if (!removeCount && hunk.oldLines === 1) {
750
+ hunk.oldLines = 0;
751
+ }
752
+ if (addCount !== hunk.newLines) {
753
+ throw new Error("Added line count did not match for hunk at line " + (chunkHeaderIndex + 1));
754
+ }
755
+ if (removeCount !== hunk.oldLines) {
756
+ throw new Error("Removed line count did not match for hunk at line " + (chunkHeaderIndex + 1));
757
+ }
758
+ return hunk;
759
+ }
760
+ while (i < diffstr.length) {
761
+ parseIndex();
762
+ }
763
+ return list;
764
+ }
765
+
766
+ // ../../../node_modules/diff/libesm/patch/create.js
767
+ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
768
+ let optionsObj;
366
769
  if (!options) {
367
770
  optionsObj = {};
368
771
  } else if (typeof options === "function") {
@@ -15114,40 +15517,108 @@ var harnessDisplaySetSchema = external_exports.strictObject({
15114
15517
  initializeOnly: external_exports.boolean().optional()
15115
15518
  });
15116
15519
 
15117
- // ../../shared-contracts/dist/console.js
15118
- var consoleAnnouncementSchema = external_exports.strictObject({
15119
- title: external_exports.string().trim().min(1).max(200),
15120
- type: external_exports.enum(["info", "warning", "danger"]),
15121
- body: external_exports.string().trim().min(1).max(16 * 1024)
15122
- });
15123
- var consoleOpenParamsSchema = external_exports.strictObject({});
15124
- var consoleOpenResultSchema = external_exports.strictObject({
15125
- /** The console address. */
15126
- url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
15520
+ // ../../shared-contracts/dist/ids.js
15521
+ var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15522
+ message: "Identifier must not be empty or whitespace"
15127
15523
  });
15128
- var CONSOLE_HOST_METHODS = Object.freeze([
15129
- "codexhost/harness/plugins/list",
15130
- "codexhost/harness/display-settings/get",
15131
- "codexhost/harness/display-settings/set",
15132
- "codexhost/harness/inspect",
15133
- "codexhost/harness/launch-settings/get",
15134
- "codexhost/harness/launch-settings/set",
15135
- "codexhost/harness/web-ui/open",
15136
- "codexhost/harness/accounts/sources",
15137
- "codexhost/harness/accounts/list",
15138
- "codexhost/harness/accounts/inspect",
15139
- "codexhost/harness/credential-imports",
15140
- "codexhost/harness/session-import/sources",
15141
- "codexhost/harness/session-import/list",
15142
- "codexhost/harness/session-import/import",
15143
- "codexhost/account/list",
15144
- "codexhost/account/refresh",
15145
- "codexhost/account/usage/inspect",
15146
- "codexhost/update/check",
15147
- "codexhost/update/start",
15148
- "codexhost/update/status"
15149
- ]);
15150
-
15524
+ var harnessIdSchema = opaqueIdSchema.brand();
15525
+ var hostThreadIdSchema = opaqueIdSchema.brand();
15526
+ var hostTurnIdSchema = opaqueIdSchema.brand();
15527
+ var hostItemIdSchema = opaqueIdSchema.brand();
15528
+ var hostInteractionIdSchema = opaqueIdSchema.brand();
15529
+
15530
+ // ../../shared-contracts/dist/harness-plugins.js
15531
+ var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15532
+ var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15533
+ var HARNESS_PLUGIN_LIMIT = 128;
15534
+ var harnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).refine((id) => id !== "codex", "The official Codex identity is reserved").pipe(harnessIdSchema);
15535
+ var relativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
15536
+ var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15537
+ var pluginPresentationShape = {
15538
+ id: harnessPluginIdSchema,
15539
+ name: external_exports.string().trim().min(1).max(128),
15540
+ version: external_exports.string().min(1).max(128),
15541
+ /** The factory accepts a persisted local entrypoint through its construction context. */
15542
+ launchCommand: external_exports.literal(true).optional(),
15543
+ links: external_exports.object({
15544
+ documentation: documentationUrlSchema.optional(),
15545
+ installation: documentationUrlSchema.optional()
15546
+ }).strict().optional()
15547
+ };
15548
+ var harnessPluginManifestSchema = external_exports.object({
15549
+ manifestVersion: external_exports.literal(1),
15550
+ ...pluginPresentationShape,
15551
+ adapterApiVersion: external_exports.number().int().positive(),
15552
+ entry: relativeResourceSchema,
15553
+ icon: relativeResourceSchema.optional()
15554
+ }).strict();
15555
+ var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
15556
+ var harnessPluginDescriptorSchema = external_exports.object({
15557
+ ...pluginPresentationShape,
15558
+ icon: harnessPluginIconSchema.optional()
15559
+ }).strict();
15560
+ var harnessPluginListParamsSchema = external_exports.object({}).strict();
15561
+ var harnessPluginListResultSchema = external_exports.object({
15562
+ plugins: external_exports.array(harnessPluginDescriptorSchema).max(HARNESS_PLUGIN_LIMIT)
15563
+ }).strict();
15564
+ var harnessPluginConfigurationSchema = external_exports.object({
15565
+ version: external_exports.literal(1),
15566
+ enabled: external_exports.array(harnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15567
+ }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15568
+ message: "Enabled plugin IDs must be unique",
15569
+ path: ["enabled"]
15570
+ });
15571
+
15572
+ // ../../shared-contracts/dist/harness-long-context.js
15573
+ var HARNESS_LONG_CONTEXT_GET_METHOD = "codexhost/harness/long-context/get";
15574
+ var HARNESS_LONG_CONTEXT_SET_METHOD = "codexhost/harness/long-context/set";
15575
+ var harnessLongContextGetSchema = external_exports.object({
15576
+ harnessId: harnessPluginIdSchema
15577
+ }).strict();
15578
+ var harnessLongContextSetSchema = harnessLongContextGetSchema.extend({
15579
+ enabled: external_exports.boolean()
15580
+ });
15581
+ var harnessLongContextSchema = external_exports.object({
15582
+ enabled: external_exports.boolean()
15583
+ }).strict();
15584
+
15585
+ // ../../shared-contracts/dist/console.js
15586
+ var consoleAnnouncementSchema = external_exports.strictObject({
15587
+ title: external_exports.string().trim().min(1).max(200),
15588
+ type: external_exports.enum(["info", "warning", "danger"]),
15589
+ body: external_exports.string().trim().min(1).max(16 * 1024)
15590
+ });
15591
+ var consoleOpenParamsSchema = external_exports.strictObject({});
15592
+ var consoleOpenResultSchema = external_exports.strictObject({
15593
+ /** The console address. */
15594
+ url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
15595
+ });
15596
+ var CONSOLE_HOST_METHODS = Object.freeze([
15597
+ "codexhost/harness/plugins/list",
15598
+ "codexhost/harness/display-settings/get",
15599
+ "codexhost/harness/display-settings/set",
15600
+ "codexhost/harness/inspect",
15601
+ "codexhost/harness/installation",
15602
+ "codexhost/harness/launch-settings/get",
15603
+ "codexhost/harness/launch-settings/set",
15604
+ HARNESS_LONG_CONTEXT_GET_METHOD,
15605
+ HARNESS_LONG_CONTEXT_SET_METHOD,
15606
+ "codexhost/harness/web-ui/open",
15607
+ "codexhost/harness/accounts/sources",
15608
+ "codexhost/harness/accounts/list",
15609
+ "codexhost/harness/accounts/inspect",
15610
+ "codexhost/harness/credential-imports",
15611
+ "codexhost/harness/session-import/sources",
15612
+ "codexhost/harness/session-import/list",
15613
+ "codexhost/harness/session-import/import",
15614
+ "codexhost/account/list",
15615
+ "codexhost/account/refresh",
15616
+ "codexhost/account/usage/inspect",
15617
+ "codexhost/update/check",
15618
+ "codexhost/update/start",
15619
+ "codexhost/update/status"
15620
+ ]);
15621
+
15151
15622
  // ../../shared-contracts/dist/version.js
15152
15623
  var WORKSPACE_CONTRACT_VERSION = 1;
15153
15624
 
@@ -15191,16 +15662,6 @@ var loadedSessionsSchema = external_exports.array(external_exports.strictObject(
15191
15662
  inactiveMs: external_exports.number().nonnegative()
15192
15663
  }));
15193
15664
 
15194
- // ../../shared-contracts/dist/ids.js
15195
- var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15196
- message: "Identifier must not be empty or whitespace"
15197
- });
15198
- var harnessIdSchema = opaqueIdSchema.brand();
15199
- var hostThreadIdSchema = opaqueIdSchema.brand();
15200
- var hostTurnIdSchema = opaqueIdSchema.brand();
15201
- var hostItemIdSchema = opaqueIdSchema.brand();
15202
- var hostInteractionIdSchema = opaqueIdSchema.brand();
15203
-
15204
15665
  // ../../shared-contracts/dist/manual-compaction.js
15205
15666
  var threadManualCompactionStartedSchema = external_exports.strictObject({
15206
15667
  threadId: hostThreadIdSchema,
@@ -15730,48 +16191,6 @@ var threadOwnershipListResultSchema = external_exports.object({
15730
16191
  }
15731
16192
  });
15732
16193
 
15733
- // ../../shared-contracts/dist/harness-plugins.js
15734
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15735
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15736
- var HARNESS_PLUGIN_LIMIT = 128;
15737
- var harnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).refine((id) => id !== "codex", "The official Codex identity is reserved").pipe(harnessIdSchema);
15738
- var relativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
15739
- var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15740
- var pluginPresentationShape = {
15741
- id: harnessPluginIdSchema,
15742
- name: external_exports.string().trim().min(1).max(128),
15743
- version: external_exports.string().min(1).max(128),
15744
- /** The factory accepts a persisted local entrypoint through its construction context. */
15745
- launchCommand: external_exports.literal(true).optional(),
15746
- links: external_exports.object({
15747
- documentation: documentationUrlSchema.optional(),
15748
- installation: documentationUrlSchema.optional()
15749
- }).strict().optional()
15750
- };
15751
- var harnessPluginManifestSchema = external_exports.object({
15752
- manifestVersion: external_exports.literal(1),
15753
- ...pluginPresentationShape,
15754
- adapterApiVersion: external_exports.number().int().positive(),
15755
- entry: relativeResourceSchema,
15756
- icon: relativeResourceSchema.optional()
15757
- }).strict();
15758
- var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
15759
- var harnessPluginDescriptorSchema = external_exports.object({
15760
- ...pluginPresentationShape,
15761
- icon: harnessPluginIconSchema.optional()
15762
- }).strict();
15763
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
15764
- var harnessPluginListResultSchema = external_exports.object({
15765
- plugins: external_exports.array(harnessPluginDescriptorSchema).max(HARNESS_PLUGIN_LIMIT)
15766
- }).strict();
15767
- var harnessPluginConfigurationSchema = external_exports.object({
15768
- version: external_exports.literal(1),
15769
- enabled: external_exports.array(harnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15770
- }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15771
- message: "Enabled plugin IDs must be unique",
15772
- path: ["enabled"]
15773
- });
15774
-
15775
16194
  // ../../shared-contracts/dist/harness-route.js
15776
16195
  var harnessPluginRouteSchema = external_exports.object({
15777
16196
  harnessId: harnessPluginIdSchema,
@@ -15796,7 +16215,7 @@ var harnessLaunchSettingsSchema = external_exports.object({
15796
16215
  // ../../shared-contracts/dist/harness-installation.js
15797
16216
  var harnessInstallationParamsSchema = external_exports.object({
15798
16217
  harnessId: harnessIdSchema,
15799
- action: external_exports.enum(["check", "update"])
16218
+ action: external_exports.enum(["check", "update", "install"])
15800
16219
  }).strict();
15801
16220
  var harnessInstallationStateSchema = external_exports.object({
15802
16221
  currentVersion: external_exports.string().min(1).max(128),
@@ -16114,1229 +16533,895 @@ var updateStartResultSchema = external_exports.strictObject({
16114
16533
  status: updateStatusSchema
16115
16534
  });
16116
16535
  var updateStatusResultSchema = external_exports.strictObject({
16117
- status: updateStatusSchema.nullable()
16118
- });
16119
-
16120
- // ../../shared-contracts/dist/index.js
16121
- var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
16122
-
16123
- // ../../harness-adapter/dist/approval.js
16124
- function invalidRequest(message3) {
16125
- return { code: "invalidRequest", message: message3, retryable: false };
16126
- }
16127
- function validateHostApprovalResponse(interaction, response) {
16128
- return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
16129
- }
16130
-
16131
- // ../../harness-adapter/dist/question.js
16132
- function invalidRequest2(message3) {
16133
- return { code: "invalidRequest", message: message3, retryable: false };
16134
- }
16135
- function validateHostQuestionResponse(interaction, response) {
16136
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
16137
- if (response.cancelled) {
16138
- return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
16139
- }
16140
- for (const answerId of Object.keys(response.answers)) {
16141
- if (!questionIds.has(answerId)) {
16142
- return invalidRequest2("Question Response contains an unknown Question ID");
16143
- }
16144
- }
16145
- for (const question of interaction.questions) {
16146
- const answers = response.answers[question.id] ?? [];
16147
- if (!question.optional && answers.length === 0) {
16148
- return invalidRequest2("Question Response omits a required answer");
16149
- }
16150
- if (question.type === "text") {
16151
- if (answers.length > 1) {
16152
- return invalidRequest2("Text Question accepts at most one answer");
16153
- }
16154
- continue;
16155
- }
16156
- if (!question.multiple && answers.length > 1) {
16157
- return invalidRequest2("Single-choice Question accepts at most one answer");
16158
- }
16159
- const declared = new Set(question.options.map(({ value }) => value));
16160
- if (!question.allowOther && answers.some((answer) => !declared.has(answer))) {
16161
- return invalidRequest2("Question Response contains an undeclared choice");
16162
- }
16163
- }
16164
- return null;
16165
- }
16166
-
16167
- // ../../harness-adapter/dist/output-channel.js
16168
- var HarnessOutputChannel = class {
16169
- outputs;
16170
- #consumerCreated = false;
16171
- #ended = false;
16172
- #pending = [];
16173
- #values = [];
16174
- constructor() {
16175
- this.outputs = {
16176
- [Symbol.asyncIterator]: () => {
16177
- if (this.#consumerCreated) {
16178
- throw new Error("Harness outputs allow only one consumer");
16179
- }
16180
- this.#consumerCreated = true;
16181
- return {
16182
- next: () => this.#next()
16183
- };
16184
- }
16185
- };
16186
- }
16187
- emit(value) {
16188
- if (this.#ended)
16189
- return false;
16190
- const resolve = this.#pending.shift();
16191
- if (resolve)
16192
- resolve({ done: false, value });
16193
- else
16194
- this.#values.push(value);
16195
- return true;
16196
- }
16197
- end() {
16198
- if (this.#ended)
16199
- return;
16200
- this.#ended = true;
16201
- if (this.#values.length !== 0)
16202
- return;
16203
- for (const resolve of this.#pending.splice(0))
16204
- resolve({ done: true, value: void 0 });
16205
- }
16206
- #next() {
16207
- const value = this.#values.shift();
16208
- if (value !== void 0)
16209
- return Promise.resolve({ done: false, value });
16210
- if (this.#ended)
16211
- return Promise.resolve({ done: true, value: void 0 });
16212
- return new Promise((resolve) => this.#pending.push(resolve));
16213
- }
16214
- };
16215
-
16216
- // ../../harness-adapter/dist/diagnostics.js
16217
- var DIAGNOSTIC_TAIL_MAX_LENGTH = 8e3;
16218
- var SENSITIVE_VALUE_PATTERN = /(api[_-]?key|access[_-]?token|auth(?:orization)?|password|secret)(\s*[:=]\s*)([^\s,;]+)/giu;
16219
- var BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]+/giu;
16220
- function sanitizeDiagnosticTail(value) {
16221
- const redacted = value.replace(BEARER_PATTERN, "Bearer [redacted]").replace(SENSITIVE_VALUE_PATTERN, "$1$2[redacted]");
16222
- return redacted.length <= DIAGNOSTIC_TAIL_MAX_LENGTH ? redacted : redacted.slice(-DIAGNOSTIC_TAIL_MAX_LENGTH);
16223
- }
16224
-
16225
- // ../../harness-adapter/dist/usage.js
16226
- var tokenFields = [
16227
- "inputTokens",
16228
- "cachedInputTokens",
16229
- "cacheWriteInputTokens",
16230
- "outputTokens",
16231
- "outputTokensPerSecond",
16232
- "reasoningOutputTokens",
16233
- "totalTokens",
16234
- "contextWindowTokens",
16235
- "contextUsedTokens"
16236
- ];
16237
- var safeIntegerFields = [
16238
- "planFiveHourResetsAtUnix",
16239
- "planSevenDayResetsAtUnix"
16240
- ];
16241
- var percentFields = [
16242
- "cacheHitRatePercent",
16243
- "planFiveHourUsedPercent",
16244
- "planSevenDayUsedPercent"
16245
- ];
16246
- var usageFields = /* @__PURE__ */ new Set([
16247
- ...tokenFields,
16248
- ...safeIntegerFields,
16249
- ...percentFields,
16250
- "totalCostUsd",
16251
- "totalCredits",
16252
- "contextUsagePercent"
16253
- ]);
16254
- function isRecord(value) {
16255
- return typeof value === "object" && value !== null && !Array.isArray(value);
16256
- }
16257
- function parseHostUsage(value) {
16258
- if (!isRecord(value))
16259
- throw new Error("Harness Usage must be an object");
16260
- const keys = Object.keys(value);
16261
- if (keys.length === 0)
16262
- throw new Error("Harness Usage must contain a reliable field");
16263
- for (const key of keys) {
16264
- if (!usageFields.has(key)) {
16265
- throw new Error(`Harness Usage contains unknown field '${key}'`);
16266
- }
16267
- }
16268
- for (const field of ["totalCredits", "contextUsagePercent"]) {
16269
- const candidate = value[field];
16270
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16271
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
16272
- }
16273
- }
16274
- for (const field of tokenFields) {
16275
- const candidate = value[field];
16276
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16277
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
16278
- }
16279
- }
16280
- for (const field of safeIntegerFields) {
16281
- const candidate = value[field];
16282
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16283
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
16284
- }
16285
- }
16286
- if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
16287
- throw new Error("Harness Usage 'outputTokensPerSecond' must be a finite non-negative number");
16288
- }
16289
- if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
16290
- throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
16291
- }
16292
- for (const field of ["totalCredits", "contextUsagePercent"]) {
16293
- const candidate = value[field];
16294
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16295
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
16296
- }
16297
- }
16298
- for (const field of percentFields) {
16299
- const candidate = value[field];
16300
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
16301
- throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
16302
- }
16303
- }
16304
- const hasContextUsed = value.contextUsedTokens !== void 0;
16305
- const hasContextWindow = value.contextWindowTokens !== void 0;
16306
- if (hasContextUsed !== hasContextWindow) {
16307
- throw new Error("Harness Usage context fields must be provided together");
16308
- }
16309
- if (hasContextWindow && value.contextWindowTokens === 0) {
16310
- throw new Error("Harness Usage 'contextWindowTokens' must be greater than zero");
16311
- }
16312
- if (value.planFiveHourResetsAtUnix !== void 0 && value.planFiveHourUsedPercent === void 0) {
16313
- throw new Error("Harness Usage 'planFiveHourResetsAtUnix' must be provided with 'planFiveHourUsedPercent'");
16314
- }
16315
- if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
16316
- throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
16317
- }
16318
- return { ...value };
16319
- }
16320
-
16321
- // ../../harness-adapter/dist/live-command-catalog.js
16322
- var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
16323
- // Session lifecycle
16324
- "branch",
16325
- "clear",
16326
- "exit",
16327
- "fork",
16328
- "fresh",
16329
- "new",
16330
- "quit",
16331
- "rename",
16332
- "rename-chat",
16333
- "reset",
16334
- "resume",
16335
- "rewind",
16336
- "session",
16337
- "sessions",
16338
- // Desktop-owned configuration
16339
- "autocompact",
16340
- "color",
16341
- "config",
16342
- "effort",
16343
- "fast",
16344
- "keybindings",
16345
- "model",
16346
- "models",
16347
- "output-style",
16348
- "permissions",
16349
- "settings",
16350
- "statusline",
16351
- "terminal-setup",
16352
- "theme",
16353
- "vim",
16354
- // Trust and approval policy
16355
- "always-approve",
16356
- "auto-mode-setup",
16357
- // Native login
16358
- "login",
16359
- "logout",
16360
- // Work outliving the Turn
16361
- "autopilot",
16362
- "background",
16363
- "bg",
16364
- "goal",
16365
- "jobs",
16366
- "loop",
16367
- "multitask",
16368
- "queue",
16369
- "remote-control",
16370
- "schedule",
16371
- "steer",
16372
- // Native terminal UI
16373
- "copy",
16374
- "debug",
16375
- "feedback",
16376
- "heapdump",
16377
- "share",
16378
- "shell",
16379
- // Plugin and MCP management
16380
- "marketplace",
16381
- "mcp",
16382
- "plugins",
16383
- "reload-plugins"
16384
- ]);
16385
- var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
16386
- function isExcludedLiveCommand(name, kind, extra = {}) {
16387
- const normalized = name.trim().replace(/^\//u, "");
16388
- if (new Set(extra.names ?? []).has(normalized))
16389
- return true;
16390
- if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
16391
- return true;
16392
- if (kind === "skill")
16393
- return false;
16394
- return COMMON_EXCLUDED_LIVE_COMMANDS.has(normalized) || COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES.some((prefix) => normalized.startsWith(prefix));
16395
- }
16396
- function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
16397
- if (!commandId.startsWith(idPrefix))
16398
- return null;
16399
- const descriptor = catalog.commands.find(({ id }) => id === commandId);
16400
- if (!descriptor)
16401
- return null;
16402
- const text = typeof argumentText === "string" ? argumentText.trim() : "";
16403
- return text ? `${descriptor.invocation} ${text}` : descriptor.invocation;
16404
- }
16405
- function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
16406
- if (!live)
16407
- return builtIns;
16408
- const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
16409
- const ids = new Set(builtIns.commands.map(({ id }) => id));
16410
- const dynamic = [];
16411
- for (const command of live) {
16412
- const name = command.name.trim().replace(/^\//u, "");
16413
- if (!name || /\s/u.test(name))
16414
- continue;
16415
- if (isExcludedLiveCommand(name, command.kind, exclusions))
16416
- continue;
16417
- const invocation = `/${name}`;
16418
- const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
16419
- if (invocations.has(invocation) || ids.has(id))
16420
- continue;
16421
- const description = command.description?.trim().slice(0, 512);
16422
- const parsed = harnessCommandDescriptorSchema.safeParse({
16423
- id,
16424
- invocation,
16425
- label: name.slice(0, 128),
16426
- ...description ? { description } : {},
16427
- argumentMode: "text",
16428
- kind: command.kind
16429
- });
16430
- if (!parsed.success)
16431
- continue;
16432
- invocations.add(invocation);
16433
- ids.add(id);
16434
- dynamic.push(parsed.data);
16435
- }
16436
- return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
16437
- }
16438
-
16439
- // dist/omp-slash-commands.js
16440
- var OMP_LIVE_COMMAND_ID_PREFIX = "omp.slash.";
16441
- function isRecord2(value) {
16442
- return typeof value === "object" && value !== null && !Array.isArray(value);
16443
- }
16444
- function parseOmpAvailableCommands(value) {
16445
- if (!Array.isArray(value))
16446
- return [];
16447
- return value.flatMap((entry) => {
16448
- if (!isRecord2(entry))
16449
- return [];
16450
- const name = typeof entry.name === "string" ? entry.name.trim().replace(/^\//u, "") : "";
16451
- if (!name)
16452
- return [];
16453
- return [
16454
- {
16455
- name,
16456
- description: typeof entry.description === "string" ? entry.description : "",
16457
- source: typeof entry.source === "string" ? entry.source : null
16458
- }
16459
- ];
16460
- });
16461
- }
16462
- function ompLiveCommands(native) {
16463
- return native.filter(({ source }) => source !== "builtin").map((command) => ({
16464
- name: command.name,
16465
- description: command.description,
16466
- kind: command.source === "skill" ? "skill" : "command"
16467
- }));
16468
- }
16469
-
16470
- // dist/omp-model-catalog.js
16471
- var OMP_MODEL_REF_PREFIX = "omp-model-v1.";
16472
- var OMP_DRAFT_THINKING_OPTION_IDS = [
16473
- "off",
16474
- "minimal",
16475
- "low",
16476
- "medium",
16477
- "high",
16478
- "xhigh",
16479
- "max"
16480
- ].map((id) => harnessThinkingOptionIdSchema.parse(id));
16481
- var OMP_THINKING_LABELS = {
16482
- off: "Off",
16483
- minimal: "Minimal",
16484
- low: "Low",
16485
- medium: "Medium",
16486
- high: "High",
16487
- xhigh: "Extra High",
16488
- max: "Max"
16489
- };
16490
- function compareText(left, right) {
16491
- return left < right ? -1 : left > right ? 1 : 0;
16492
- }
16493
- function assertNativePart(value, name) {
16494
- if (value.trim().length === 0)
16495
- throw new Error(`Omp ${name} must not be empty`);
16496
- }
16497
- function encodeOmpModelRef(model) {
16498
- assertNativePart(model.provider, "Model provider");
16499
- assertNativePart(model.id, "Model id");
16500
- const encoded = Buffer.from(JSON.stringify([model.provider, model.id]), "utf8").toString("base64url");
16501
- return harnessModelRefSchema.parse({ id: `${OMP_MODEL_REF_PREFIX}${encoded}` });
16502
- }
16503
- function decodeOmpModelRef(ref) {
16504
- const parsedRef = harnessModelRefSchema.parse(ref);
16505
- if (!parsedRef.id.startsWith(OMP_MODEL_REF_PREFIX)) {
16506
- throw new Error("Model Ref does not belong to OmpAdapter");
16507
- }
16508
- const encoded = parsedRef.id.slice(OMP_MODEL_REF_PREFIX.length);
16509
- let decoded;
16510
- try {
16511
- decoded = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
16512
- } catch {
16513
- throw new Error("Omp Model Ref is malformed");
16514
- }
16515
- if (!Array.isArray(decoded) || decoded.length !== 2 || typeof decoded[0] !== "string" || typeof decoded[1] !== "string") {
16516
- throw new Error("Omp Model Ref has an invalid native identity");
16517
- }
16518
- const native = { provider: decoded[0], id: decoded[1] };
16519
- assertNativePart(native.provider, "Model provider");
16520
- assertNativePart(native.id, "Model id");
16521
- if (encodeOmpModelRef(native).id !== parsedRef.id) {
16522
- throw new Error("Omp Model Ref is not canonical");
16523
- }
16524
- return native;
16525
- }
16526
- function sameOmpModel(left, right) {
16527
- return left === null ? right === null : right !== null && left.provider === right.provider && left.id === right.id;
16536
+ status: updateStatusSchema.nullable()
16537
+ });
16538
+
16539
+ // ../../shared-contracts/dist/index.js
16540
+ var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
16541
+
16542
+ // ../../harness-adapter/dist/approval.js
16543
+ function invalidRequest(message3) {
16544
+ return { code: "invalidRequest", message: message3, retryable: false };
16528
16545
  }
16529
- function fallbackThinkingLabel(id) {
16530
- const label = id.split(/[._~-]+/u).filter((part) => part.length > 0).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
16531
- return label || id;
16546
+ function validateHostApprovalResponse(interaction, response) {
16547
+ return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
16532
16548
  }
16533
- function normalizeOmpThinkingOptions(levels) {
16534
- return levels.map((id) => harnessThinkingOptionSchema.parse({
16535
- id,
16536
- label: OMP_THINKING_LABELS[id] ?? fallbackThinkingLabel(id)
16537
- }));
16549
+
16550
+ // ../../harness-adapter/dist/question.js
16551
+ function invalidRequest2(message3) {
16552
+ return { code: "invalidRequest", message: message3, retryable: false };
16538
16553
  }
16539
- function normalizeOmpModelCatalog(nativeModels, effectiveModel, thinkingLevels, effectiveThinkingOptionId) {
16540
- const byRef = /* @__PURE__ */ new Map();
16541
- for (const native of nativeModels) {
16542
- const ref = encodeOmpModelRef(native);
16543
- const existing = byRef.get(ref.id);
16544
- if (existing) {
16545
- if (existing.reasoning !== native.reasoning) {
16546
- throw new Error("Omp duplicate Model entries disagree on reasoning capability");
16554
+ function validateHostQuestionResponse(interaction, response) {
16555
+ const questionIds = new Set(interaction.questions.map(({ id }) => id));
16556
+ if (response.cancelled) {
16557
+ return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
16558
+ }
16559
+ for (const answerId of Object.keys(response.answers)) {
16560
+ if (!questionIds.has(answerId)) {
16561
+ return invalidRequest2("Question Response contains an unknown Question ID");
16562
+ }
16563
+ }
16564
+ for (const question of interaction.questions) {
16565
+ const answers = response.answers[question.id] ?? [];
16566
+ if (!question.optional && answers.length === 0) {
16567
+ return invalidRequest2("Question Response omits a required answer");
16568
+ }
16569
+ if (question.type === "text") {
16570
+ if (answers.length > 1) {
16571
+ return invalidRequest2("Text Question accepts at most one answer");
16547
16572
  }
16548
16573
  continue;
16549
16574
  }
16550
- byRef.set(ref.id, {
16551
- model: {
16552
- ref,
16553
- label: `${native.provider} / ${native.id}`
16554
- },
16555
- reasoning: native.reasoning
16556
- });
16575
+ if (!question.multiple && answers.length > 1) {
16576
+ return invalidRequest2("Single-choice Question accepts at most one answer");
16577
+ }
16578
+ const declared = new Set(question.options.map(({ value }) => value));
16579
+ if (!question.allowOther && answers.some((answer) => !declared.has(answer))) {
16580
+ return invalidRequest2("Question Response contains an undeclared choice");
16581
+ }
16557
16582
  }
16558
- const defaultModel = effectiveModel ? encodeOmpModelRef(effectiveModel) : void 0;
16559
- if (defaultModel && !byRef.has(defaultModel.id)) {
16560
- throw new Error("Omp effective Model is absent from the available Model catalog");
16583
+ return null;
16584
+ }
16585
+
16586
+ // ../../harness-adapter/dist/output-channel.js
16587
+ var HarnessOutputChannel = class {
16588
+ outputs;
16589
+ #consumerCreated = false;
16590
+ #ended = false;
16591
+ #pending = [];
16592
+ #values = [];
16593
+ constructor() {
16594
+ this.outputs = {
16595
+ [Symbol.asyncIterator]: () => {
16596
+ if (this.#consumerCreated) {
16597
+ throw new Error("Harness outputs allow only one consumer");
16598
+ }
16599
+ this.#consumerCreated = true;
16600
+ return {
16601
+ next: () => this.#next()
16602
+ };
16603
+ }
16604
+ };
16561
16605
  }
16562
- if (thinkingLevels && effectiveThinkingOptionId && !thinkingLevels.includes(effectiveThinkingOptionId)) {
16563
- throw new Error("Omp effective Thinking option is absent from the available option catalog");
16606
+ emit(value) {
16607
+ if (this.#ended)
16608
+ return false;
16609
+ const resolve = this.#pending.shift();
16610
+ if (resolve)
16611
+ resolve({ done: false, value });
16612
+ else
16613
+ this.#values.push(value);
16614
+ return true;
16564
16615
  }
16565
- if (thinkingLevels && !effectiveThinkingOptionId) {
16566
- throw new Error("Omp did not report an effective Thinking option");
16616
+ end() {
16617
+ if (this.#ended)
16618
+ return;
16619
+ this.#ended = true;
16620
+ if (this.#values.length !== 0)
16621
+ return;
16622
+ for (const resolve of this.#pending.splice(0))
16623
+ resolve({ done: true, value: void 0 });
16567
16624
  }
16568
- const thinkingOptions = thinkingLevels ? normalizeOmpThinkingOptions(OMP_DRAFT_THINKING_OPTION_IDS) : [];
16569
- const allThinkingOptionIds = thinkingOptions.map(({ id }) => id);
16570
- const offThinkingOptionId = thinkingOptions.find(({ id }) => id === "off")?.id;
16571
- const models = [...byRef.values()].map(({ model, reasoning }) => ({
16572
- ...model,
16573
- supportedThinkingOptionIds: reasoning ? allThinkingOptionIds : offThinkingOptionId ? [offThinkingOptionId] : []
16574
- })).sort((left, right) => compareText(left.label, right.label) || compareText(left.ref.id, right.ref.id));
16575
- const defaultThinkingOptionId = thinkingOptions.find(({ id }) => id === effectiveThinkingOptionId)?.id;
16576
- return harnessModelCatalogSchema.parse({
16577
- models,
16578
- ...defaultModel ? { defaultModel } : {},
16579
- thinkingOptions,
16580
- ...defaultThinkingOptionId ? { defaultThinkingOptionId } : {}
16581
- });
16582
- }
16583
-
16584
- // dist/omp-tool-presentation.js
16585
- function isRecord3(value) {
16586
- return typeof value === "object" && value !== null && !Array.isArray(value);
16587
- }
16588
- function stringField(value, key) {
16589
- return isRecord3(value) && typeof value[key] === "string" ? value[key] : void 0;
16590
- }
16591
- function toolCommand(toolName, argumentsValue) {
16592
- if (toolName === "bash") {
16593
- const command = stringField(argumentsValue, "command");
16594
- if (command)
16595
- return command;
16625
+ #next() {
16626
+ const value = this.#values.shift();
16627
+ if (value !== void 0)
16628
+ return Promise.resolve({ done: false, value });
16629
+ if (this.#ended)
16630
+ return Promise.resolve({ done: true, value: void 0 });
16631
+ return new Promise((resolve) => this.#pending.push(resolve));
16596
16632
  }
16597
- const serializedArguments = JSON.stringify(argumentsValue);
16598
- return serializedArguments === "{}" ? toolName : `${toolName} ${serializedArguments}`;
16599
- }
16600
- function projectOmpToolItem(input) {
16601
- return {
16602
- type: "commandExecution",
16603
- itemId: input.itemId,
16604
- command: toolCommand(input.toolName, input.arguments),
16605
- ...input.cwd ? { cwd: input.cwd } : {}
16606
- };
16633
+ };
16634
+
16635
+ // ../../harness-adapter/dist/diagnostics.js
16636
+ var DIAGNOSTIC_TAIL_MAX_LENGTH = 8e3;
16637
+ var SENSITIVE_VALUE_PATTERN = /(api[_-]?key|access[_-]?token|auth(?:orization)?|password|secret)(\s*[:=]\s*)([^\s,;]+)/giu;
16638
+ var BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]+/giu;
16639
+ function sanitizeDiagnosticTail(value) {
16640
+ const redacted = value.replace(BEARER_PATTERN, "Bearer [redacted]").replace(SENSITIVE_VALUE_PATTERN, "$1$2[redacted]");
16641
+ return redacted.length <= DIAGNOSTIC_TAIL_MAX_LENGTH ? redacted : redacted.slice(-DIAGNOSTIC_TAIL_MAX_LENGTH);
16607
16642
  }
16608
16643
 
16609
- // dist/omp-history.js
16610
- var ompHarnessId = harnessIdSchema.parse("omp");
16611
- function isRecord4(value) {
16644
+ // ../../harness-adapter/dist/usage.js
16645
+ var tokenFields = [
16646
+ "inputTokens",
16647
+ "cachedInputTokens",
16648
+ "cacheWriteInputTokens",
16649
+ "outputTokens",
16650
+ "outputTokensPerSecond",
16651
+ "reasoningOutputTokens",
16652
+ "totalTokens",
16653
+ "contextWindowTokens",
16654
+ "contextUsedTokens"
16655
+ ];
16656
+ var safeIntegerFields = [
16657
+ "planFiveHourResetsAtUnix",
16658
+ "planSevenDayResetsAtUnix"
16659
+ ];
16660
+ var percentFields = [
16661
+ "cacheHitRatePercent",
16662
+ "planFiveHourUsedPercent",
16663
+ "planSevenDayUsedPercent"
16664
+ ];
16665
+ var usageFields = /* @__PURE__ */ new Set([
16666
+ ...tokenFields,
16667
+ ...safeIntegerFields,
16668
+ ...percentFields,
16669
+ "totalCostUsd",
16670
+ "totalCredits",
16671
+ "contextUsagePercent"
16672
+ ]);
16673
+ function isRecord(value) {
16612
16674
  return typeof value === "object" && value !== null && !Array.isArray(value);
16613
16675
  }
16614
- function textContent(value) {
16615
- if (typeof value === "string")
16616
- return value;
16617
- if (!Array.isArray(value))
16618
- return "";
16619
- return value.filter((part) => isRecord4(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
16620
- }
16621
- function thinkingContent(value) {
16622
- if (!Array.isArray(value))
16623
- return "";
16624
- return value.filter((part) => isRecord4(part) && part.type === "thinking" && typeof part.thinking === "string").map((part) => part.thinking).join("");
16625
- }
16626
- function validatedEntry(value) {
16627
- if (typeof value.id !== "string" || value.id.length === 0 || value.parentId !== null && typeof value.parentId !== "string" || typeof value.type !== "string") {
16628
- throw new Error("Omp history contains an invalid Entry identity");
16629
- }
16630
- return value;
16631
- }
16632
- function activeOmpEntries(history) {
16633
- if (history.leafId === null)
16634
- return [];
16635
- const byId = new Map(history.entries.map((value) => {
16636
- const entry = validatedEntry(value);
16637
- return [entry.id, entry];
16638
- }));
16639
- const reversed = [];
16640
- const visited = /* @__PURE__ */ new Set();
16641
- let current = history.leafId;
16642
- while (current !== null) {
16643
- if (visited.has(current))
16644
- throw new Error("Omp history active branch contains a cycle");
16645
- visited.add(current);
16646
- const entry = byId.get(current);
16647
- if (!entry)
16648
- throw new Error("Omp history active branch references a missing Entry");
16649
- reversed.push(entry);
16650
- current = entry.parentId;
16651
- }
16652
- return reversed.reverse();
16653
- }
16654
- function message(entry) {
16655
- return entry.type === "message" && isRecord4(entry.message) ? entry.message : null;
16656
- }
16657
- function messageRole(entry) {
16658
- const value = message(entry)?.role;
16659
- return typeof value === "string" ? value : null;
16660
- }
16661
- function itemId(entryId, kind, ordinal) {
16662
- return hostItemIdSchema.parse(`omp-item-v1-${entryId}-${kind}-${ordinal}`);
16663
- }
16664
- function assistantOutcome(entries) {
16665
- const assistants = entries.map((entry) => message(entry)).filter((value) => value?.role === "assistant");
16666
- const final = assistants.at(-1);
16667
- if (!final)
16668
- return { status: "unknown", reason: "Omp history has no Assistant terminal" };
16669
- const stopReason = final.stopReason;
16670
- if (stopReason === "aborted") {
16671
- return { status: "cancelled", reason: "Omp Assistant was aborted" };
16676
+ function parseHostUsage(value) {
16677
+ if (!isRecord(value))
16678
+ throw new Error("Harness Usage must be an object");
16679
+ const keys = Object.keys(value);
16680
+ if (keys.length === 0)
16681
+ throw new Error("Harness Usage must contain a reliable field");
16682
+ for (const key of keys) {
16683
+ if (!usageFields.has(key)) {
16684
+ throw new Error(`Harness Usage contains unknown field '${key}'`);
16685
+ }
16672
16686
  }
16673
- if (stopReason === "error") {
16674
- return {
16675
- status: "failed",
16676
- error: {
16677
- code: "nativeFailure",
16678
- message: typeof final.errorMessage === "string" && final.errorMessage.length > 0 ? final.errorMessage : "Omp Assistant failed",
16679
- retryable: false
16680
- }
16681
- };
16687
+ for (const field of ["totalCredits", "contextUsagePercent"]) {
16688
+ const candidate = value[field];
16689
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16690
+ throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
16691
+ }
16682
16692
  }
16683
- if (typeof stopReason === "string" || textContent(final.content).length > 0) {
16684
- return { status: "succeeded" };
16693
+ for (const field of tokenFields) {
16694
+ const candidate = value[field];
16695
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16696
+ throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
16697
+ }
16685
16698
  }
16686
- return { status: "unknown", reason: "Omp Assistant terminal is not classifiable" };
16687
- }
16688
- function itemOutcome(outcome) {
16689
- if (outcome.status === "failed")
16690
- return { status: "failed", error: outcome.error };
16691
- if (outcome.status === "cancelled") {
16692
- return {
16693
- status: "cancelled",
16694
- ...outcome.reason ? { reason: outcome.reason } : {}
16695
- };
16699
+ for (const field of safeIntegerFields) {
16700
+ const candidate = value[field];
16701
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16702
+ throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
16703
+ }
16696
16704
  }
16697
- return { status: "succeeded" };
16698
- }
16699
- function toolOutput(value) {
16700
- const text = textContent(value);
16701
- return text.length > 0 ? { content: [{ type: "text", text }] } : void 0;
16702
- }
16703
- function snapshotItems(entries, outcome) {
16704
- const snapshots = [];
16705
- const toolCalls = /* @__PURE__ */ new Map();
16706
- for (const entry of entries) {
16707
- const nativeMessage = message(entry);
16708
- if (!nativeMessage)
16709
- continue;
16710
- const content = Array.isArray(nativeMessage.content) ? nativeMessage.content : [];
16711
- if (nativeMessage.role === "assistant") {
16712
- const text = textContent(content);
16713
- const reasoning = thinkingContent(content);
16714
- let projectedText = false;
16715
- let projectedReasoning = false;
16716
- for (const [ordinal, part] of content.entries()) {
16717
- if (!isRecord4(part))
16718
- continue;
16719
- if (part.type === "thinking" && !projectedReasoning && reasoning.length > 0) {
16720
- const item2 = {
16721
- type: "reasoning",
16722
- itemId: itemId(entry.id, "reasoning", 0),
16723
- text: reasoning
16724
- };
16725
- snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
16726
- projectedReasoning = true;
16727
- continue;
16728
- }
16729
- if (part.type === "text" && !projectedText && text.length > 0) {
16730
- const item2 = {
16731
- type: "agentMessage",
16732
- itemId: itemId(entry.id, "assistant", 0),
16733
- text
16734
- };
16735
- snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
16736
- projectedText = true;
16737
- continue;
16738
- }
16739
- if (part.type !== "toolCall" || typeof part.id !== "string" || typeof part.name !== "string") {
16740
- continue;
16741
- }
16742
- const parsedArguments = jsonValueSchema.safeParse(part.arguments);
16743
- if (!parsedArguments.success)
16744
- continue;
16745
- toolCalls.set(part.id, {
16746
- entryId: entry.id,
16747
- ordinal,
16748
- name: part.name,
16749
- arguments: parsedArguments.data
16750
- });
16751
- }
16752
- continue;
16705
+ if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
16706
+ throw new Error("Harness Usage 'outputTokensPerSecond' must be a finite non-negative number");
16707
+ }
16708
+ if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
16709
+ throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
16710
+ }
16711
+ for (const field of ["totalCredits", "contextUsagePercent"]) {
16712
+ const candidate = value[field];
16713
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16714
+ throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
16753
16715
  }
16754
- if (nativeMessage.role !== "toolResult" || typeof nativeMessage.toolCallId !== "string" || typeof nativeMessage.toolName !== "string") {
16755
- continue;
16716
+ }
16717
+ for (const field of percentFields) {
16718
+ const candidate = value[field];
16719
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
16720
+ throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
16756
16721
  }
16757
- const call = toolCalls.get(nativeMessage.toolCallId);
16758
- if (!call || call.name !== nativeMessage.toolName)
16759
- continue;
16760
- const output = toolOutput(nativeMessage.content);
16761
- const item = {
16762
- ...projectOmpToolItem({
16763
- itemId: itemId(call.entryId, "tool", call.ordinal),
16764
- toolName: call.name,
16765
- arguments: call.arguments
16766
- }),
16767
- ...output ? { output: textContent(output.content) } : {}
16768
- };
16769
- const toolFailed = nativeMessage.isError === true;
16770
- snapshots.push({
16771
- item,
16772
- outcome: toolFailed ? {
16773
- status: "failed",
16774
- error: {
16775
- code: "nativeFailure",
16776
- message: `Omp Tool '${call.name}' failed`,
16777
- retryable: false
16778
- }
16779
- } : { status: "succeeded" }
16780
- });
16781
16722
  }
16782
- return snapshots;
16723
+ const hasContextUsed = value.contextUsedTokens !== void 0;
16724
+ const hasContextWindow = value.contextWindowTokens !== void 0;
16725
+ if (hasContextUsed !== hasContextWindow) {
16726
+ throw new Error("Harness Usage context fields must be provided together");
16727
+ }
16728
+ if (hasContextWindow && value.contextWindowTokens === 0) {
16729
+ throw new Error("Harness Usage 'contextWindowTokens' must be greater than zero");
16730
+ }
16731
+ if (value.planFiveHourResetsAtUnix !== void 0 && value.planFiveHourUsedPercent === void 0) {
16732
+ throw new Error("Harness Usage 'planFiveHourResetsAtUnix' must be provided with 'planFiveHourUsedPercent'");
16733
+ }
16734
+ if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
16735
+ throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
16736
+ }
16737
+ return { ...value };
16783
16738
  }
16784
- function modelChange(entry) {
16785
- return entry.type === "model_change" && typeof entry.provider === "string" && typeof entry.modelId === "string" ? { provider: entry.provider, id: entry.modelId } : null;
16739
+
16740
+ // ../../harness-adapter/dist/live-command-catalog.js
16741
+ var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
16742
+ // Session lifecycle
16743
+ "branch",
16744
+ "clear",
16745
+ "exit",
16746
+ "fork",
16747
+ "fresh",
16748
+ "new",
16749
+ "quit",
16750
+ "rename",
16751
+ "rename-chat",
16752
+ "reset",
16753
+ "resume",
16754
+ "rewind",
16755
+ "session",
16756
+ "sessions",
16757
+ // Desktop-owned configuration
16758
+ "autocompact",
16759
+ "color",
16760
+ "config",
16761
+ "effort",
16762
+ "fast",
16763
+ "keybindings",
16764
+ "model",
16765
+ "models",
16766
+ "output-style",
16767
+ "permissions",
16768
+ "settings",
16769
+ "statusline",
16770
+ "terminal-setup",
16771
+ "theme",
16772
+ "vim",
16773
+ // Trust and approval policy
16774
+ "always-approve",
16775
+ "auto-mode-setup",
16776
+ // Native login
16777
+ "login",
16778
+ "logout",
16779
+ // Work outliving the Turn
16780
+ "autopilot",
16781
+ "background",
16782
+ "bg",
16783
+ "goal",
16784
+ "jobs",
16785
+ "loop",
16786
+ "multitask",
16787
+ "queue",
16788
+ "remote-control",
16789
+ "schedule",
16790
+ "steer",
16791
+ // Native terminal UI
16792
+ "copy",
16793
+ "debug",
16794
+ "feedback",
16795
+ "heapdump",
16796
+ "share",
16797
+ "shell",
16798
+ // Plugin and MCP management
16799
+ "marketplace",
16800
+ "mcp",
16801
+ "plugins",
16802
+ "reload-plugins"
16803
+ ]);
16804
+ var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
16805
+ function isExcludedLiveCommand(name, kind, extra = {}) {
16806
+ const normalized = name.trim().replace(/^\//u, "");
16807
+ if (new Set(extra.names ?? []).has(normalized))
16808
+ return true;
16809
+ if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
16810
+ return true;
16811
+ if (kind === "skill")
16812
+ return false;
16813
+ return COMMON_EXCLUDED_LIVE_COMMANDS.has(normalized) || COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES.some((prefix) => normalized.startsWith(prefix));
16786
16814
  }
16787
- function mapOmpSnapshot(history, state) {
16788
- const active = activeOmpEntries(history);
16789
- const turns = [];
16790
- let effectiveModel = state.model;
16791
- for (let index = 0; index < active.length; ) {
16792
- const model = modelChange(active[index]);
16793
- if (model) {
16794
- effectiveModel = model;
16795
- index += 1;
16815
+ function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
16816
+ if (!commandId.startsWith(idPrefix))
16817
+ return null;
16818
+ const descriptor = catalog.commands.find(({ id }) => id === commandId);
16819
+ if (!descriptor)
16820
+ return null;
16821
+ const text = typeof argumentText === "string" ? argumentText.trim() : "";
16822
+ return text ? `${descriptor.invocation} ${text}` : descriptor.invocation;
16823
+ }
16824
+ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
16825
+ if (!live)
16826
+ return builtIns;
16827
+ const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
16828
+ const ids = new Set(builtIns.commands.map(({ id }) => id));
16829
+ const dynamic = [];
16830
+ for (const command of live) {
16831
+ const name = command.name.trim().replace(/^\//u, "");
16832
+ if (!name || /\s/u.test(name))
16796
16833
  continue;
16797
- }
16798
- const user = active[index];
16799
- if (messageRole(user) !== "user") {
16800
- index += 1;
16834
+ if (isExcludedLiveCommand(name, command.kind, exclusions))
16801
16835
  continue;
16802
- }
16803
- let end = index + 1;
16804
- while (end < active.length && messageRole(active[end]) !== "user")
16805
- end += 1;
16806
- const entries = active.slice(index, end);
16807
- const outcome = assistantOutcome(entries);
16808
- const userText = textContent(message(user)?.content);
16809
- const nativeTurnRef = nativeTurnRefSchema.parse({
16810
- harnessId: ompHarnessId,
16811
- nativeSessionId: state.sessionId,
16812
- nativeTurnKey: user.id,
16813
- formatVersion: 1
16814
- });
16815
- const checkpoint = nativeCheckpointRefSchema.parse({
16816
- harnessId: ompHarnessId,
16817
- nativeSessionId: state.sessionId,
16818
- checkpointId: user.id,
16819
- formatVersion: 1
16820
- });
16821
- turns.push({
16822
- nativeTurnRef,
16823
- checkpoint,
16824
- input: [{ type: "text", text: userText }],
16825
- items: snapshotItems(entries, outcome),
16826
- outcome,
16827
- ...effectiveModel ? { model: encodeOmpModelRef(effectiveModel) } : {}
16836
+ const invocation = `/${name}`;
16837
+ const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
16838
+ if (invocations.has(invocation) || ids.has(id))
16839
+ continue;
16840
+ const description = command.description?.trim().slice(0, 512);
16841
+ const parsed = harnessCommandDescriptorSchema.safeParse({
16842
+ id,
16843
+ invocation,
16844
+ label: name.slice(0, 128),
16845
+ ...description ? { description } : {},
16846
+ argumentMode: "text",
16847
+ kind: command.kind
16828
16848
  });
16829
- for (const entry of entries) {
16830
- const changed = modelChange(entry);
16831
- if (changed)
16832
- effectiveModel = changed;
16833
- }
16834
- index = end;
16849
+ if (!parsed.success)
16850
+ continue;
16851
+ invocations.add(invocation);
16852
+ ids.add(id);
16853
+ dynamic.push(parsed.data);
16835
16854
  }
16836
- return { turns };
16855
+ return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
16837
16856
  }
16838
- function resolveOmpLastTurnBoundary(history) {
16839
- const users = activeOmpEntries(history).filter((entry) => messageRole(entry) === "user");
16840
- const last = users.at(-1);
16841
- return last ? { lastUserEntryId: last.id, sourceTurnCount: users.length } : null;
16857
+
16858
+ // dist/omp-slash-commands.js
16859
+ var OMP_LIVE_COMMAND_ID_PREFIX = "omp.slash.";
16860
+ function isRecord2(value) {
16861
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16842
16862
  }
16843
- function resolveOmpForkBoundary(history, checkpointId) {
16844
- const active = activeOmpEntries(history);
16845
- const users = active.filter((entry) => messageRole(entry) === "user");
16846
- const targetTurnIndex = users.findIndex((entry) => entry.id === checkpointId);
16847
- if (targetTurnIndex < 0)
16848
- throw new Error("Omp Checkpoint is not on the active branch");
16849
- return {
16850
- targetTurnIndex,
16851
- nextUserEntryId: users[targetTurnIndex + 1]?.id ?? null
16852
- };
16863
+ function parseOmpAvailableCommands(value) {
16864
+ if (!Array.isArray(value))
16865
+ return [];
16866
+ return value.flatMap((entry) => {
16867
+ if (!isRecord2(entry))
16868
+ return [];
16869
+ const name = typeof entry.name === "string" ? entry.name.trim().replace(/^\//u, "") : "";
16870
+ if (!name)
16871
+ return [];
16872
+ return [
16873
+ {
16874
+ name,
16875
+ description: typeof entry.description === "string" ? entry.description : "",
16876
+ source: typeof entry.source === "string" ? entry.source : null
16877
+ }
16878
+ ];
16879
+ });
16880
+ }
16881
+ function ompLiveCommands(native) {
16882
+ return native.filter(({ source }) => source !== "builtin").map((command) => ({
16883
+ name: command.name,
16884
+ description: command.description,
16885
+ kind: command.source === "skill" ? "skill" : "command"
16886
+ }));
16853
16887
  }
16854
16888
 
16855
- // dist/omp-session-file.js
16856
- import { createReadStream } from "node:fs";
16857
- import { open, realpath } from "node:fs/promises";
16858
- import readline from "node:readline";
16859
- var MAX_SESSION_HEADER_BYTES = 64 * 1024;
16860
- var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
16861
- function isRecord5(value) {
16862
- return typeof value === "object" && value !== null && !Array.isArray(value);
16889
+ // dist/omp-model-catalog.js
16890
+ var OMP_MODEL_REF_PREFIX = "omp-model-v1.";
16891
+ var OMP_DRAFT_THINKING_OPTION_IDS = [
16892
+ "off",
16893
+ "minimal",
16894
+ "low",
16895
+ "medium",
16896
+ "high",
16897
+ "xhigh",
16898
+ "max"
16899
+ ].map((id) => harnessThinkingOptionIdSchema.parse(id));
16900
+ var OMP_THINKING_LABELS = {
16901
+ off: "Off",
16902
+ minimal: "Minimal",
16903
+ low: "Low",
16904
+ medium: "Medium",
16905
+ high: "High",
16906
+ xhigh: "Extra High",
16907
+ max: "Max"
16908
+ };
16909
+ function compareText(left, right) {
16910
+ return left < right ? -1 : left > right ? 1 : 0;
16863
16911
  }
16864
- function historyEntry(value) {
16865
- if (!isRecord5(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") {
16866
- return null;
16867
- }
16868
- return value;
16912
+ function assertNativePart(value, name) {
16913
+ if (value.trim().length === 0)
16914
+ throw new Error(`Omp ${name} must not be empty`);
16869
16915
  }
16870
- async function readOmpSessionHistory(sessionFile, maxBytes) {
16871
- const entries = [];
16872
- let leafId = null;
16873
- const lines = readline.createInterface({
16874
- input: createReadStream(sessionFile, {
16875
- encoding: "utf8",
16876
- ...maxBytes === void 0 ? {} : { end: maxBytes - 1 }
16877
- }),
16878
- crlfDelay: Number.POSITIVE_INFINITY
16879
- });
16916
+ function encodeOmpModelRef(model) {
16917
+ assertNativePart(model.provider, "Model provider");
16918
+ assertNativePart(model.id, "Model id");
16919
+ const encoded = Buffer.from(JSON.stringify([model.provider, model.id]), "utf8").toString("base64url");
16920
+ return harnessModelRefSchema.parse({ id: `${OMP_MODEL_REF_PREFIX}${encoded}` });
16921
+ }
16922
+ function decodeOmpModelRef(ref) {
16923
+ const parsedRef = harnessModelRefSchema.parse(ref);
16924
+ if (!parsedRef.id.startsWith(OMP_MODEL_REF_PREFIX)) {
16925
+ throw new Error("Model Ref does not belong to OmpAdapter");
16926
+ }
16927
+ const encoded = parsedRef.id.slice(OMP_MODEL_REF_PREFIX.length);
16928
+ let decoded;
16880
16929
  try {
16881
- for await (const line of lines) {
16882
- if (line.length === 0)
16883
- continue;
16884
- let parsed;
16885
- try {
16886
- parsed = JSON.parse(line);
16887
- } catch {
16888
- continue;
16889
- }
16890
- const entry = historyEntry(parsed);
16891
- if (!entry)
16892
- continue;
16893
- entries.push(entry);
16894
- leafId = entry.id;
16895
- }
16896
- } finally {
16897
- lines.close();
16930
+ decoded = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
16931
+ } catch {
16932
+ throw new Error("Omp Model Ref is malformed");
16898
16933
  }
16899
- return { entries, leafId };
16934
+ if (!Array.isArray(decoded) || decoded.length !== 2 || typeof decoded[0] !== "string" || typeof decoded[1] !== "string") {
16935
+ throw new Error("Omp Model Ref has an invalid native identity");
16936
+ }
16937
+ const native = { provider: decoded[0], id: decoded[1] };
16938
+ assertNativePart(native.provider, "Model provider");
16939
+ assertNativePart(native.id, "Model id");
16940
+ if (encodeOmpModelRef(native).id !== parsedRef.id) {
16941
+ throw new Error("Omp Model Ref is not canonical");
16942
+ }
16943
+ return native;
16900
16944
  }
16901
- async function readOmpSessionHeader(sessionFile) {
16902
- const handle = await open(sessionFile, "r");
16903
- try {
16904
- const buffer = Buffer.allocUnsafe(MAX_SESSION_HEADER_BYTES);
16905
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
16906
- const contents = buffer.subarray(0, bytesRead);
16907
- const newline = contents.indexOf(10);
16908
- if (newline < 0 && bytesRead === buffer.length) {
16909
- throw new Error("Omp Session header exceeds the supported size");
16910
- }
16911
- const contentsText = utf8Decoder.decode(contents);
16912
- for (const line of contentsText.split("\n")) {
16913
- if (line.length === 0)
16914
- continue;
16915
- let parsed;
16916
- try {
16917
- parsed = JSON.parse(line);
16918
- } catch {
16919
- continue;
16920
- }
16921
- if (!isRecord5(parsed) || parsed.type !== "session")
16922
- continue;
16923
- if (typeof parsed.id !== "string" || parsed.id.length === 0 || typeof parsed.cwd !== "string" || parsed.cwd.length === 0) {
16924
- throw new Error("Omp Session header is invalid");
16945
+ function sameOmpModel(left, right) {
16946
+ return left === null ? right === null : right !== null && left.provider === right.provider && left.id === right.id;
16947
+ }
16948
+ function fallbackThinkingLabel(id) {
16949
+ const label = id.split(/[._~-]+/u).filter((part) => part.length > 0).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
16950
+ return label || id;
16951
+ }
16952
+ function normalizeOmpThinkingOptions(levels) {
16953
+ return levels.map((id) => harnessThinkingOptionSchema.parse({
16954
+ id,
16955
+ label: OMP_THINKING_LABELS[id] ?? fallbackThinkingLabel(id)
16956
+ }));
16957
+ }
16958
+ function normalizeOmpModelCatalog(nativeModels, effectiveModel, thinkingLevels, effectiveThinkingOptionId) {
16959
+ const byRef = /* @__PURE__ */ new Map();
16960
+ for (const native of nativeModels) {
16961
+ const ref = encodeOmpModelRef(native);
16962
+ const existing = byRef.get(ref.id);
16963
+ if (existing) {
16964
+ if (existing.reasoning !== native.reasoning) {
16965
+ throw new Error("Omp duplicate Model entries disagree on reasoning capability");
16925
16966
  }
16926
- return { type: "session", id: parsed.id, cwd: parsed.cwd };
16967
+ continue;
16927
16968
  }
16928
- throw new Error("Omp Session header is invalid");
16929
- } finally {
16930
- await handle.close();
16969
+ byRef.set(ref.id, {
16970
+ model: {
16971
+ ref,
16972
+ label: `${native.provider} / ${native.id}`
16973
+ },
16974
+ reasoning: native.reasoning
16975
+ });
16976
+ }
16977
+ const defaultModel = effectiveModel ? encodeOmpModelRef(effectiveModel) : void 0;
16978
+ if (defaultModel && !byRef.has(defaultModel.id)) {
16979
+ throw new Error("Omp effective Model is absent from the available Model catalog");
16931
16980
  }
16932
- }
16933
- async function verifyOmpSessionCwd(input) {
16934
- if (!input.sessionFile)
16935
- throw new Error("Omp Fork Session has no persisted Session file");
16936
- const header = await readOmpSessionHeader(input.sessionFile);
16937
- if (header.id !== input.sessionId) {
16938
- throw new Error("Omp Fork Session header identity does not match RPC state");
16981
+ if (thinkingLevels && effectiveThinkingOptionId && !thinkingLevels.includes(effectiveThinkingOptionId)) {
16982
+ throw new Error("Omp effective Thinking option is absent from the available option catalog");
16939
16983
  }
16940
- const [actualCwd, expectedCwd] = await Promise.all([
16941
- realpath(header.cwd),
16942
- realpath(input.expectedCwd)
16943
- ]);
16944
- if (actualCwd !== expectedCwd) {
16945
- throw new Error("Omp Fork Session did not bind the requested cwd");
16984
+ if (thinkingLevels && !effectiveThinkingOptionId) {
16985
+ throw new Error("Omp did not report an effective Thinking option");
16946
16986
  }
16987
+ const thinkingOptions = thinkingLevels ? normalizeOmpThinkingOptions(OMP_DRAFT_THINKING_OPTION_IDS) : [];
16988
+ const allThinkingOptionIds = thinkingOptions.map(({ id }) => id);
16989
+ const offThinkingOptionId = thinkingOptions.find(({ id }) => id === "off")?.id;
16990
+ const models = [...byRef.values()].map(({ model, reasoning }) => ({
16991
+ ...model,
16992
+ supportedThinkingOptionIds: reasoning ? allThinkingOptionIds : offThinkingOptionId ? [offThinkingOptionId] : []
16993
+ })).sort((left, right) => compareText(left.label, right.label) || compareText(left.ref.id, right.ref.id));
16994
+ const defaultThinkingOptionId = thinkingOptions.find(({ id }) => id === effectiveThinkingOptionId)?.id;
16995
+ return harnessModelCatalogSchema.parse({
16996
+ models,
16997
+ ...defaultModel ? { defaultModel } : {},
16998
+ thinkingOptions,
16999
+ ...defaultThinkingOptionId ? { defaultThinkingOptionId } : {}
17000
+ });
16947
17001
  }
16948
17002
 
16949
- // dist/omp-last-turn-rollback.js
16950
- function modelFromState(state) {
16951
- if (state.provider === null && state.modelId === null)
16952
- return null;
16953
- if (state.provider === null || state.modelId === null) {
16954
- throw new Error("Omp state contains a partial Model identity");
17003
+ // dist/omp-tool-presentation.js
17004
+ function isRecord3(value) {
17005
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17006
+ }
17007
+ function stringField(value, key) {
17008
+ return isRecord3(value) && typeof value[key] === "string" ? value[key] : void 0;
17009
+ }
17010
+ function toolCommand(toolName, argumentsValue) {
17011
+ if (toolName === "bash") {
17012
+ const command = stringField(argumentsValue, "command");
17013
+ if (command)
17014
+ return command;
16955
17015
  }
16956
- return { provider: state.provider, id: state.modelId };
17016
+ const serializedArguments = JSON.stringify(argumentsValue);
17017
+ return serializedArguments === "{}" ? toolName : `${toolName} ${serializedArguments}`;
16957
17018
  }
16958
- async function rollbackOmpLastTurn(transport, sourceSessionId, cwd) {
16959
- const startupState = transport.state;
16960
- const startupSessionId = startupState.sessionId;
16961
- const currentModel = modelFromState(startupState);
16962
- const currentThinking = startupState.thinkingLevel;
16963
- const copiedHistory = await transport.getEntries();
16964
- const boundary = resolveOmpLastTurnBoundary(copiedHistory);
16965
- if (!boundary)
16966
- return { ok: false, reason: "empty" };
16967
- const sourceSnapshot = mapOmpSnapshot(copiedHistory, {
16968
- sessionId: startupSessionId,
16969
- model: currentModel
16970
- });
16971
- let state = await transport.fork(boundary.lastUserEntryId);
16972
- if (state.sessionId === sourceSessionId || state.sessionId === startupSessionId) {
16973
- throw new Error("Omp last-Turn rollback did not create a distinct Native Session");
17019
+ function projectOmpToolItem(input) {
17020
+ return {
17021
+ type: "commandExecution",
17022
+ itemId: input.itemId,
17023
+ command: toolCommand(input.toolName, input.arguments),
17024
+ ...input.cwd ? { cwd: input.cwd } : {}
17025
+ };
17026
+ }
17027
+
17028
+ // dist/omp-history.js
17029
+ var ompHarnessId = harnessIdSchema.parse("omp");
17030
+ function isRecord4(value) {
17031
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17032
+ }
17033
+ function textContent(value) {
17034
+ if (typeof value === "string")
17035
+ return value;
17036
+ if (!Array.isArray(value))
17037
+ return "";
17038
+ return value.filter((part) => isRecord4(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
17039
+ }
17040
+ function thinkingContent(value) {
17041
+ if (!Array.isArray(value))
17042
+ return "";
17043
+ return value.filter((part) => isRecord4(part) && part.type === "thinking" && typeof part.thinking === "string").map((part) => part.thinking).join("");
17044
+ }
17045
+ function validatedEntry(value) {
17046
+ if (typeof value.id !== "string" || value.id.length === 0 || value.parentId !== null && typeof value.parentId !== "string" || typeof value.type !== "string") {
17047
+ throw new Error("Omp history contains an invalid Entry identity");
16974
17048
  }
16975
- if (!sameOmpModel(modelFromState(state), currentModel)) {
16976
- if (!currentModel)
16977
- throw new Error("Omp last-Turn rollback changed the current Model");
16978
- state = await transport.selectModel(currentModel);
17049
+ return value;
17050
+ }
17051
+ function activeOmpEntries(history) {
17052
+ if (history.leafId === null)
17053
+ return [];
17054
+ const byId = new Map(history.entries.map((value) => {
17055
+ const entry = validatedEntry(value);
17056
+ return [entry.id, entry];
17057
+ }));
17058
+ const reversed = [];
17059
+ const visited = /* @__PURE__ */ new Set();
17060
+ let current = history.leafId;
17061
+ while (current !== null) {
17062
+ if (visited.has(current))
17063
+ throw new Error("Omp history active branch contains a cycle");
17064
+ visited.add(current);
17065
+ const entry = byId.get(current);
17066
+ if (!entry)
17067
+ throw new Error("Omp history active branch references a missing Entry");
17068
+ reversed.push(entry);
17069
+ current = entry.parentId;
16979
17070
  }
16980
- if (state.thinkingLevel !== currentThinking) {
16981
- if (!currentThinking)
16982
- throw new Error("Omp last-Turn rollback changed current Thinking");
16983
- state = await transport.selectThinkingOption(currentThinking);
17071
+ return reversed.reverse();
17072
+ }
17073
+ function message(entry) {
17074
+ return entry.type === "message" && isRecord4(entry.message) ? entry.message : null;
17075
+ }
17076
+ function messageRole(entry) {
17077
+ const value = message(entry)?.role;
17078
+ return typeof value === "string" ? value : null;
17079
+ }
17080
+ function itemId(entryId, kind, ordinal) {
17081
+ return hostItemIdSchema.parse(`omp-item-v1-${entryId}-${kind}-${ordinal}`);
17082
+ }
17083
+ function assistantOutcome(entries) {
17084
+ const assistants = entries.map((entry) => message(entry)).filter((value) => value?.role === "assistant");
17085
+ const final = assistants.at(-1);
17086
+ if (!final)
17087
+ return { status: "unknown", reason: "Omp history has no Assistant terminal" };
17088
+ const stopReason = final.stopReason;
17089
+ if (stopReason === "aborted") {
17090
+ return { status: "cancelled", reason: "Omp Assistant was aborted" };
16984
17091
  }
16985
- if (!sameOmpModel(modelFromState(state), currentModel) || state.thinkingLevel !== currentThinking) {
16986
- throw new Error("Omp last-Turn rollback could not restore current Model and Thinking");
17092
+ if (stopReason === "error") {
17093
+ return {
17094
+ status: "failed",
17095
+ error: {
17096
+ code: "nativeFailure",
17097
+ message: typeof final.errorMessage === "string" && final.errorMessage.length > 0 ? final.errorMessage : "Omp Assistant failed",
17098
+ retryable: false
17099
+ }
17100
+ };
16987
17101
  }
16988
- const snapshot = mapOmpSnapshot(await transport.getEntries(), {
16989
- sessionId: state.sessionId,
16990
- model: modelFromState(state)
16991
- });
16992
- const expectedTurnKeys = sourceSnapshot.turns.slice(0, -1).map((turn) => turn.nativeTurnRef.nativeTurnKey);
16993
- const actualTurnKeys = snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey);
16994
- if (snapshot.turns.length !== boundary.sourceTurnCount - 1 || actualTurnKeys.some((key, index) => key !== expectedTurnKeys[index])) {
16995
- throw new Error("Omp last-Turn rollback did not produce the exact retained history prefix");
17102
+ if (typeof stopReason === "string" || textContent(final.content).length > 0) {
17103
+ return { status: "succeeded" };
16996
17104
  }
16997
- await transport.verifySessionCwd(cwd);
16998
- return { ok: true };
17105
+ return { status: "unknown", reason: "Omp Assistant terminal is not classifiable" };
16999
17106
  }
17000
-
17001
- // dist/omp-rpc-session.js
17002
- import { spawn, spawnSync } from "node:child_process";
17003
- import { randomUUID } from "node:crypto";
17004
- import path4 from "node:path";
17005
-
17006
- // ../../harness-discovery/dist/environment.js
17007
- import fs from "node:fs";
17008
- import path from "node:path";
17009
- function targetPath(platform) {
17010
- return platform === "win32" ? path.win32 : path.posix;
17107
+ function itemOutcome(outcome) {
17108
+ if (outcome.status === "failed")
17109
+ return { status: "failed", error: outcome.error };
17110
+ if (outcome.status === "cancelled") {
17111
+ return {
17112
+ status: "cancelled",
17113
+ ...outcome.reason ? { reason: outcome.reason } : {}
17114
+ };
17115
+ }
17116
+ return { status: "succeeded" };
17011
17117
  }
17012
- function environmentValue(environment, name) {
17013
- const lowered = name.toLowerCase();
17014
- for (const [key, value] of Object.entries(environment)) {
17015
- if (key.toLowerCase() === lowered)
17016
- return value;
17118
+ function toolOutput(value) {
17119
+ const text = textContent(value);
17120
+ return text.length > 0 ? { content: [{ type: "text", text }] } : void 0;
17121
+ }
17122
+ function snapshotItems(entries, outcome) {
17123
+ const snapshots = [];
17124
+ const toolCalls = /* @__PURE__ */ new Map();
17125
+ for (const entry of entries) {
17126
+ const nativeMessage = message(entry);
17127
+ if (!nativeMessage)
17128
+ continue;
17129
+ const content = Array.isArray(nativeMessage.content) ? nativeMessage.content : [];
17130
+ if (nativeMessage.role === "assistant") {
17131
+ const text = textContent(content);
17132
+ const reasoning = thinkingContent(content);
17133
+ let projectedText = false;
17134
+ let projectedReasoning = false;
17135
+ for (const [ordinal, part] of content.entries()) {
17136
+ if (!isRecord4(part))
17137
+ continue;
17138
+ if (part.type === "thinking" && !projectedReasoning && reasoning.length > 0) {
17139
+ const item2 = {
17140
+ type: "reasoning",
17141
+ itemId: itemId(entry.id, "reasoning", 0),
17142
+ text: reasoning
17143
+ };
17144
+ snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
17145
+ projectedReasoning = true;
17146
+ continue;
17147
+ }
17148
+ if (part.type === "text" && !projectedText && text.length > 0) {
17149
+ const item2 = {
17150
+ type: "agentMessage",
17151
+ itemId: itemId(entry.id, "assistant", 0),
17152
+ text
17153
+ };
17154
+ snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
17155
+ projectedText = true;
17156
+ continue;
17157
+ }
17158
+ if (part.type !== "toolCall" || typeof part.id !== "string" || typeof part.name !== "string") {
17159
+ continue;
17160
+ }
17161
+ const parsedArguments = jsonValueSchema.safeParse(part.arguments);
17162
+ if (!parsedArguments.success)
17163
+ continue;
17164
+ toolCalls.set(part.id, {
17165
+ entryId: entry.id,
17166
+ ordinal,
17167
+ name: part.name,
17168
+ arguments: parsedArguments.data
17169
+ });
17170
+ }
17171
+ continue;
17172
+ }
17173
+ if (nativeMessage.role !== "toolResult" || typeof nativeMessage.toolCallId !== "string" || typeof nativeMessage.toolName !== "string") {
17174
+ continue;
17175
+ }
17176
+ const call = toolCalls.get(nativeMessage.toolCallId);
17177
+ if (!call || call.name !== nativeMessage.toolName)
17178
+ continue;
17179
+ const output = toolOutput(nativeMessage.content);
17180
+ const item = {
17181
+ ...projectOmpToolItem({
17182
+ itemId: itemId(call.entryId, "tool", call.ordinal),
17183
+ toolName: call.name,
17184
+ arguments: call.arguments
17185
+ }),
17186
+ ...output ? { output: textContent(output.content) } : {}
17187
+ };
17188
+ const toolFailed = nativeMessage.isError === true;
17189
+ snapshots.push({
17190
+ item,
17191
+ outcome: toolFailed ? {
17192
+ status: "failed",
17193
+ error: {
17194
+ code: "nativeFailure",
17195
+ message: `Omp Tool '${call.name}' failed`,
17196
+ retryable: false
17197
+ }
17198
+ } : { status: "succeeded" }
17199
+ });
17017
17200
  }
17018
- return void 0;
17019
- }
17020
- function pathDelimiter(platform) {
17021
- return platform === "win32" ? ";" : ":";
17022
- }
17023
- function pathDirectories(environment, platform) {
17024
- return (environmentValue(environment, "PATH") ?? "").split(pathDelimiter(platform)).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean);
17025
- }
17026
- function executableExtensions(command, platform, environment) {
17027
- if (platform !== "win32")
17028
- return [""];
17029
- if (targetPath(platform).extname(command) !== "")
17030
- return [""];
17031
- return (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean);
17201
+ return snapshots;
17032
17202
  }
17033
- function isExecutableFile(filePath, platform) {
17034
- try {
17035
- fs.accessSync(filePath, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
17036
- return fs.statSync(filePath).isFile();
17037
- } catch {
17038
- return false;
17039
- }
17203
+ function modelChange(entry) {
17204
+ return entry.type === "model_change" && typeof entry.provider === "string" && typeof entry.modelId === "string" ? { provider: entry.provider, id: entry.modelId } : null;
17040
17205
  }
17041
- function subdirectoryNames(directory) {
17042
- try {
17043
- return fs.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
17044
- } catch {
17045
- return [];
17206
+ function mapOmpSnapshot(history, state) {
17207
+ const active = activeOmpEntries(history);
17208
+ const turns = [];
17209
+ let effectiveModel = state.model;
17210
+ for (let index = 0; index < active.length; ) {
17211
+ const model = modelChange(active[index]);
17212
+ if (model) {
17213
+ effectiveModel = model;
17214
+ index += 1;
17215
+ continue;
17216
+ }
17217
+ const user = active[index];
17218
+ if (messageRole(user) !== "user") {
17219
+ index += 1;
17220
+ continue;
17221
+ }
17222
+ let end = index + 1;
17223
+ while (end < active.length && messageRole(active[end]) !== "user")
17224
+ end += 1;
17225
+ const entries = active.slice(index, end);
17226
+ const outcome = assistantOutcome(entries);
17227
+ const userText = textContent(message(user)?.content);
17228
+ const nativeTurnRef = nativeTurnRefSchema.parse({
17229
+ harnessId: ompHarnessId,
17230
+ nativeSessionId: state.sessionId,
17231
+ nativeTurnKey: user.id,
17232
+ formatVersion: 1
17233
+ });
17234
+ const checkpoint = nativeCheckpointRefSchema.parse({
17235
+ harnessId: ompHarnessId,
17236
+ nativeSessionId: state.sessionId,
17237
+ checkpointId: user.id,
17238
+ formatVersion: 1
17239
+ });
17240
+ turns.push({
17241
+ nativeTurnRef,
17242
+ checkpoint,
17243
+ input: [{ type: "text", text: userText }],
17244
+ items: snapshotItems(entries, outcome),
17245
+ outcome,
17246
+ ...effectiveModel ? { model: encodeOmpModelRef(effectiveModel) } : {}
17247
+ });
17248
+ for (const entry of entries) {
17249
+ const changed = modelChange(entry);
17250
+ if (changed)
17251
+ effectiveModel = changed;
17252
+ }
17253
+ index = end;
17046
17254
  }
17255
+ return { turns };
17047
17256
  }
17048
- function newestFirst(names) {
17049
- return [...names].sort((left, right) => right.localeCompare(left, void 0, { numeric: true }));
17257
+ function resolveOmpLastTurnBoundary(history) {
17258
+ const users = activeOmpEntries(history).filter((entry) => messageRole(entry) === "user");
17259
+ const last = users.at(-1);
17260
+ return last ? { lastUserEntryId: last.id, sourceTurnCount: users.length } : null;
17050
17261
  }
17051
-
17052
- // ../../harness-discovery/dist/invocation.js
17053
- import path2 from "node:path";
17054
- function commandInvocation(command, arguments_, environment, platform = process.platform) {
17055
- const extension = path2.win32.extname(command).toLowerCase();
17056
- if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
17057
- return { command, arguments: [...arguments_], windowsVerbatimArguments: false };
17058
- }
17059
- const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
17060
- const commandLine = [command, ...arguments_].map(quote).join(" ");
17262
+ function resolveOmpForkBoundary(history, checkpointId) {
17263
+ const active = activeOmpEntries(history);
17264
+ const users = active.filter((entry) => messageRole(entry) === "user");
17265
+ const targetTurnIndex = users.findIndex((entry) => entry.id === checkpointId);
17266
+ if (targetTurnIndex < 0)
17267
+ throw new Error("Omp Checkpoint is not on the active branch");
17061
17268
  return {
17062
- command: environmentValue(environment, "ComSpec") ?? "cmd.exe",
17063
- arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
17064
- windowsVerbatimArguments: true
17269
+ targetTurnIndex,
17270
+ nextUserEntryId: users[targetTurnIndex + 1]?.id ?? null
17065
17271
  };
17066
17272
  }
17067
17273
 
17068
- // ../../harness-discovery/dist/node-runtime.js
17069
- import path3 from "node:path";
17070
- function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath, platform = process.platform) {
17071
- const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
17072
- const delimiter = platform === "win32" ? ";" : ":";
17073
- const runtimeDirectory = path3.dirname(runtimeExecutable);
17074
- const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
17075
- const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
17076
- if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
17077
- directories.push(runtimeDirectory);
17078
- }
17079
- return { ...environment, [pathKey]: directories.join(delimiter) };
17274
+ // dist/omp-session-file.js
17275
+ import { createReadStream } from "node:fs";
17276
+ import { open, realpath } from "node:fs/promises";
17277
+ import readline from "node:readline";
17278
+ var MAX_SESSION_HEADER_BYTES = 64 * 1024;
17279
+ var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
17280
+ function isRecord5(value) {
17281
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17080
17282
  }
17081
-
17082
- // ../../harness-discovery/dist/resolve.js
17083
- import os from "node:os";
17084
-
17085
- // ../../harness-discovery/dist/version-managers.js
17086
- function versionManagerBinaryDirectories(context) {
17087
- const { platform, environment, home } = context;
17088
- const list = context.subdirectories ?? subdirectoryNames;
17089
- const pathFlavor = targetPath(platform);
17090
- const value = (name) => environmentValue(environment, name);
17091
- const directories = [];
17092
- const versioned = (root, ...tail) => {
17093
- for (const version2 of newestFirst(list(root))) {
17094
- directories.push(pathFlavor.join(root, version2, ...tail));
17095
- }
17096
- };
17097
- if (platform === "win32") {
17098
- const appData = value("APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming");
17099
- const localAppData = value("LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local");
17100
- versioned(pathFlavor.join(appData, "nvm"));
17101
- versioned(value("FNM_DIR") ?? pathFlavor.join(appData, "fnm", "node-versions"), "installation");
17102
- directories.push(pathFlavor.join(localAppData, "Volta", "bin"));
17103
- directories.push(pathFlavor.join(home, ".bun", "bin"));
17104
- const pnpmHome2 = value("PNPM_HOME");
17105
- if (pnpmHome2)
17106
- directories.push(pnpmHome2);
17107
- directories.push(pathFlavor.join(localAppData, "pnpm"));
17108
- return directories;
17109
- }
17110
- versioned(pathFlavor.join(value("NVM_DIR") ?? pathFlavor.join(home, ".nvm"), "versions", "node"), "bin");
17111
- const fnmRoots = [
17112
- value("FNM_DIR"),
17113
- pathFlavor.join(home, ".local", "share", "fnm"),
17114
- pathFlavor.join(home, "Library", "Application Support", "fnm")
17115
- ].filter((root) => root !== void 0);
17116
- for (const root of fnmRoots) {
17117
- versioned(pathFlavor.join(root, "node-versions"), "installation", "bin");
17118
- }
17119
- const voltaHome = value("VOLTA_HOME") ?? pathFlavor.join(home, ".volta");
17120
- versioned(pathFlavor.join(voltaHome, "tools", "image", "node"), "bin");
17121
- directories.push(pathFlavor.join(voltaHome, "bin"));
17122
- const asdfHome = value("ASDF_DATA_DIR") ?? pathFlavor.join(home, ".asdf");
17123
- versioned(pathFlavor.join(asdfHome, "installs", "nodejs"), "bin");
17124
- directories.push(pathFlavor.join(asdfHome, "shims"));
17125
- const nodenvHome = value("NODENV_ROOT") ?? pathFlavor.join(home, ".nodenv");
17126
- versioned(pathFlavor.join(nodenvHome, "versions"), "bin");
17127
- directories.push(pathFlavor.join(nodenvHome, "shims"));
17128
- versioned(pathFlavor.join(value("N_PREFIX") ?? "/usr/local", "n", "versions", "node"), "bin");
17129
- directories.push(pathFlavor.join(home, ".bun", "bin"));
17130
- const pnpmHome = value("PNPM_HOME");
17131
- if (pnpmHome)
17132
- directories.push(pnpmHome);
17133
- directories.push(pathFlavor.join(home, "Library", "pnpm"));
17134
- directories.push(pathFlavor.join(home, ".local", "share", "pnpm"));
17135
- for (const prefix of ["/opt/homebrew/opt", "/usr/local/opt"]) {
17136
- for (const formula of newestFirst(list(prefix).filter((name) => name.startsWith("node@")))) {
17137
- directories.push(pathFlavor.join(prefix, formula, "bin"));
17138
- }
17283
+ function historyEntry(value) {
17284
+ if (!isRecord5(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") {
17285
+ return null;
17139
17286
  }
17140
- return directories;
17141
- }
17142
-
17143
- // ../../harness-discovery/dist/resolve.js
17144
- var VERSION_MANAGER_ROOTS = "<version-managers>";
17145
- function installRootExtensions(platform) {
17146
- return platform === "win32" ? [".exe", ".cmd"] : [""];
17147
- }
17148
- function resolveHomeDirectory(input) {
17149
- return input.homeDirectory ?? environmentValue(input.environment, "HOME") ?? environmentValue(input.environment, "USERPROFILE") ?? os.homedir();
17150
- }
17151
- function templateVariables(environment, platform, home) {
17152
- const pathFlavor = targetPath(platform);
17153
- return {
17154
- HOME: home,
17155
- USERPROFILE: home,
17156
- APPDATA: environmentValue(environment, "APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming"),
17157
- LOCALAPPDATA: environmentValue(environment, "LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local")
17158
- };
17159
- }
17160
- function joinTemplate(platform, value) {
17161
- const pathFlavor = targetPath(platform);
17162
- const segments = value.split("/");
17163
- const head = segments[0] ?? "";
17164
- const tail = segments.slice(1);
17165
- if (head === "")
17166
- return pathFlavor.join(pathFlavor.sep, ...tail);
17167
- return tail.length === 0 ? head : pathFlavor.join(head, ...tail);
17287
+ return value;
17168
17288
  }
17169
- function expandInstallRoot(template, environment, platform, home) {
17170
- const variables = templateVariables(environment, platform, home);
17171
- let unresolved = false;
17172
- const substituted = template.replace(/^~(?=\/|$)/u, home).replace(/\$\{(\w+)\}/gu, (_match, name) => {
17173
- const value = variables[name] ?? environmentValue(environment, name);
17174
- if (value === void 0 || value === "") {
17175
- unresolved = true;
17176
- return "";
17177
- }
17178
- return value;
17289
+ async function readOmpSessionHistory(sessionFile, maxBytes) {
17290
+ const entries = [];
17291
+ let leafId = null;
17292
+ const lines = readline.createInterface({
17293
+ input: createReadStream(sessionFile, {
17294
+ encoding: "utf8",
17295
+ ...maxBytes === void 0 ? {} : { end: maxBytes - 1 }
17296
+ }),
17297
+ crlfDelay: Number.POSITIVE_INFINITY
17179
17298
  });
17180
- return unresolved ? void 0 : joinTemplate(platform, substituted);
17181
- }
17182
- function installRootDirectories(spec, input, dependencies, platform, home) {
17183
- const templates = (platform === "win32" ? spec.installRoots?.windows : spec.installRoots?.posix) ?? [];
17184
- const directories = [];
17185
- for (const template of templates) {
17186
- if (template === VERSION_MANAGER_ROOTS) {
17187
- directories.push(...versionManagerBinaryDirectories({
17188
- platform,
17189
- environment: input.environment,
17190
- home,
17191
- ...dependencies.subdirectories ? { subdirectories: dependencies.subdirectories } : {}
17192
- }));
17193
- continue;
17299
+ try {
17300
+ for await (const line of lines) {
17301
+ if (line.length === 0)
17302
+ continue;
17303
+ let parsed;
17304
+ try {
17305
+ parsed = JSON.parse(line);
17306
+ } catch {
17307
+ continue;
17308
+ }
17309
+ const entry = historyEntry(parsed);
17310
+ if (!entry)
17311
+ continue;
17312
+ entries.push(entry);
17313
+ leafId = entry.id;
17194
17314
  }
17195
- const directory = expandInstallRoot(template, input.environment, platform, home);
17196
- if (directory !== void 0)
17197
- directories.push(directory);
17315
+ } finally {
17316
+ lines.close();
17198
17317
  }
17199
- return directories;
17318
+ return { entries, leafId };
17200
17319
  }
17201
- function harnessCandidates(spec, input, dependencies = {}) {
17202
- const platform = input.platform ?? process.platform;
17203
- const pathFlavor = targetPath(platform);
17204
- const configured = input.command ?? (spec.commandEnvironmentVariable ? environmentValue(input.environment, spec.commandEnvironmentVariable) : void 0);
17205
- const command = configured ?? spec.command;
17206
- if (pathFlavor.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
17207
- return [{ candidate: command, source: "configured" }];
17208
- }
17209
- const candidates = [];
17210
- const extensions = executableExtensions(command, platform, input.environment);
17211
- for (const directory of pathDirectories(input.environment, platform)) {
17212
- for (const extension of extensions) {
17213
- candidates.push({
17214
- candidate: pathFlavor.join(directory, command + extension),
17215
- source: "path"
17216
- });
17320
+ async function readOmpSessionHeader(sessionFile) {
17321
+ const handle = await open(sessionFile, "r");
17322
+ try {
17323
+ const buffer = Buffer.allocUnsafe(MAX_SESSION_HEADER_BYTES);
17324
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
17325
+ const contents = buffer.subarray(0, bytesRead);
17326
+ const newline = contents.indexOf(10);
17327
+ if (newline < 0 && bytesRead === buffer.length) {
17328
+ throw new Error("Omp Session header exceeds the supported size");
17217
17329
  }
17218
- }
17219
- if (configured !== void 0)
17220
- return candidates;
17221
- const home = resolveHomeDirectory(input);
17222
- for (const directory of installRootDirectories(spec, input, dependencies, platform, home)) {
17223
- for (const extension of installRootExtensions(platform)) {
17224
- candidates.push({
17225
- candidate: pathFlavor.join(directory, spec.command + extension),
17226
- source: "install-root"
17227
- });
17330
+ const contentsText = utf8Decoder.decode(contents);
17331
+ for (const line of contentsText.split("\n")) {
17332
+ if (line.length === 0)
17333
+ continue;
17334
+ let parsed;
17335
+ try {
17336
+ parsed = JSON.parse(line);
17337
+ } catch {
17338
+ continue;
17339
+ }
17340
+ if (!isRecord5(parsed) || parsed.type !== "session")
17341
+ continue;
17342
+ if (typeof parsed.id !== "string" || parsed.id.length === 0 || typeof parsed.cwd !== "string" || parsed.cwd.length === 0) {
17343
+ throw new Error("Omp Session header is invalid");
17344
+ }
17345
+ return { type: "session", id: parsed.id, cwd: parsed.cwd };
17228
17346
  }
17347
+ throw new Error("Omp Session header is invalid");
17348
+ } finally {
17349
+ await handle.close();
17229
17350
  }
17230
- return candidates;
17231
17351
  }
17232
- function resolveHarnessExecutable(spec, input, dependencies = {}) {
17233
- const platform = input.platform ?? process.platform;
17234
- const isExecutable = dependencies.isExecutable ?? ((candidate) => isExecutableFile(candidate, platform));
17235
- const runnable = spec.runnableCandidate ?? ((candidate) => candidate);
17236
- const context = { platform, isExecutable };
17237
- for (const { candidate, source } of harnessCandidates(spec, input, dependencies)) {
17238
- const executable = runnable(candidate, context);
17239
- if (executable !== void 0 && isExecutable(executable))
17240
- return { executable, source };
17352
+ async function verifyOmpSessionCwd(input) {
17353
+ if (!input.sessionFile)
17354
+ throw new Error("Omp Fork Session has no persisted Session file");
17355
+ const header = await readOmpSessionHeader(input.sessionFile);
17356
+ if (header.id !== input.sessionId) {
17357
+ throw new Error("Omp Fork Session header identity does not match RPC state");
17358
+ }
17359
+ const [actualCwd, expectedCwd] = await Promise.all([
17360
+ realpath(header.cwd),
17361
+ realpath(input.expectedCwd)
17362
+ ]);
17363
+ if (actualCwd !== expectedCwd) {
17364
+ throw new Error("Omp Fork Session did not bind the requested cwd");
17241
17365
  }
17242
- return void 0;
17243
17366
  }
17244
17367
 
17245
- // ../../harness-discovery/dist/installation.js
17246
- import { execFile } from "node:child_process";
17247
- import { homedir } from "node:os";
17248
- function runInstallationCommand(command, args, environment, timeout = 3e4) {
17249
- const env = withNodeRuntimeOnPath(environment);
17250
- const invocation = /\.[cm]?js$/i.test(command) ? commandInvocation(process.execPath, [command, ...args], env) : commandInvocation(command, args, env);
17251
- return new Promise((resolve, reject) => {
17252
- const child = execFile(invocation.command, invocation.arguments, {
17253
- env,
17254
- cwd: env.HOME ?? env.USERPROFILE ?? homedir(),
17255
- encoding: "utf8",
17256
- timeout,
17257
- killSignal: "SIGKILL",
17258
- maxBuffer: 1024 * 1024,
17259
- windowsHide: true,
17260
- windowsVerbatimArguments: invocation.windowsVerbatimArguments
17261
- }, (error51, stdout, stderr) => {
17262
- if (error51)
17263
- reject(new Error(error51.killed ? "Harness command timed out" : "Harness command failed; check the native installation and retry"));
17264
- else
17265
- resolve((stdout || stderr).trim());
17266
- });
17267
- child.stdin?.end();
17268
- });
17269
- }
17270
- function installationVersion(value) {
17271
- if (typeof value !== "string" || !/^v?\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(value.trim()))
17272
- throw new Error("Harness returned an invalid version");
17273
- return value.trim().replace(/^v/, "");
17274
- }
17275
- function versionFromOutput(output) {
17276
- return installationVersion(output.match(/\b\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?\b/)?.[0]);
17368
+ // dist/omp-last-turn-rollback.js
17369
+ function modelFromState(state) {
17370
+ if (state.provider === null && state.modelId === null)
17371
+ return null;
17372
+ if (state.provider === null || state.modelId === null) {
17373
+ throw new Error("Omp state contains a partial Model identity");
17374
+ }
17375
+ return { provider: state.provider, id: state.modelId };
17277
17376
  }
17278
- function newerInstallationVersion(current, latest) {
17279
- const a = installationVersion(current).replace(/\+.*/, "");
17280
- const b = installationVersion(latest).replace(/\+.*/, "");
17281
- const coreA = a.replace(/-.*/, "").split(".").map(BigInt);
17282
- const coreB = b.replace(/-.*/, "").split(".").map(BigInt);
17283
- for (let i = 0; i < Math.max(coreA.length, coreB.length); i++) {
17284
- if ((coreA[i] ?? 0n) !== (coreB[i] ?? 0n))
17285
- return (coreB[i] ?? 0n) > (coreA[i] ?? 0n);
17377
+ async function rollbackOmpLastTurn(transport, sourceSessionId, cwd) {
17378
+ const startupState = transport.state;
17379
+ const startupSessionId = startupState.sessionId;
17380
+ const currentModel = modelFromState(startupState);
17381
+ const currentThinking = startupState.thinkingLevel;
17382
+ const copiedHistory = await transport.getEntries();
17383
+ const boundary = resolveOmpLastTurnBoundary(copiedHistory);
17384
+ if (!boundary)
17385
+ return { ok: false, reason: "empty" };
17386
+ const sourceSnapshot = mapOmpSnapshot(copiedHistory, {
17387
+ sessionId: startupSessionId,
17388
+ model: currentModel
17389
+ });
17390
+ let state = await transport.fork(boundary.lastUserEntryId);
17391
+ if (state.sessionId === sourceSessionId || state.sessionId === startupSessionId) {
17392
+ throw new Error("Omp last-Turn rollback did not create a distinct Native Session");
17286
17393
  }
17287
- const preA = a.includes("-") ? a.slice(a.indexOf("-") + 1).split(".") : [];
17288
- const preB = b.includes("-") ? b.slice(b.indexOf("-") + 1).split(".") : [];
17289
- if (!preA.length || !preB.length)
17290
- return !!preA.length && !preB.length;
17291
- for (let i = 0; i < Math.max(preA.length, preB.length); i++) {
17292
- const x = preA[i];
17293
- const y = preB[i];
17294
- if (x === y)
17295
- continue;
17296
- if (x === void 0 || y === void 0)
17297
- return x === void 0;
17298
- const numericX = /^\d+$/.test(x);
17299
- const numericY = /^\d+$/.test(y);
17300
- if (numericX && numericY) {
17301
- if (BigInt(x) === BigInt(y))
17302
- continue;
17303
- return BigInt(y) > BigInt(x);
17304
- }
17305
- if (numericX !== numericY)
17306
- return numericX;
17307
- return y > x;
17394
+ if (!sameOmpModel(modelFromState(state), currentModel)) {
17395
+ if (!currentModel)
17396
+ throw new Error("Omp last-Turn rollback changed the current Model");
17397
+ state = await transport.selectModel(currentModel);
17308
17398
  }
17309
- return false;
17310
- }
17311
- function createInstallationManager(options) {
17312
- let checking;
17313
- let updating;
17314
- const check2 = () => checking ??= options.check().finally(() => {
17315
- checking = void 0;
17399
+ if (state.thinkingLevel !== currentThinking) {
17400
+ if (!currentThinking)
17401
+ throw new Error("Omp last-Turn rollback changed current Thinking");
17402
+ state = await transport.selectThinkingOption(currentThinking);
17403
+ }
17404
+ if (!sameOmpModel(modelFromState(state), currentModel) || state.thinkingLevel !== currentThinking) {
17405
+ throw new Error("Omp last-Turn rollback could not restore current Model and Thinking");
17406
+ }
17407
+ const snapshot = mapOmpSnapshot(await transport.getEntries(), {
17408
+ sessionId: state.sessionId,
17409
+ model: modelFromState(state)
17316
17410
  });
17317
- return (action) => {
17318
- if (updating)
17319
- return updating;
17320
- if (action === "check")
17321
- return check2();
17322
- updating = (async () => {
17323
- const before = await check2();
17324
- if (!before.updateAvailable)
17325
- return before;
17326
- if (!before.canUpdate)
17327
- throw new Error(before.message ?? "This installation cannot be updated automatically");
17328
- await options.update(before);
17329
- const after = await check2();
17330
- if (after.currentVersion === before.currentVersion)
17331
- throw new Error("The Harness version did not change; check the native updater and retry");
17332
- return after;
17333
- })().finally(() => {
17334
- updating = void 0;
17335
- });
17336
- return updating;
17337
- };
17411
+ const expectedTurnKeys = sourceSnapshot.turns.slice(0, -1).map((turn) => turn.nativeTurnRef.nativeTurnKey);
17412
+ const actualTurnKeys = snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey);
17413
+ if (snapshot.turns.length !== boundary.sourceTurnCount - 1 || actualTurnKeys.some((key, index) => key !== expectedTurnKeys[index])) {
17414
+ throw new Error("Omp last-Turn rollback did not produce the exact retained history prefix");
17415
+ }
17416
+ await transport.verifySessionCwd(cwd);
17417
+ return { ok: true };
17338
17418
  }
17339
17419
 
17420
+ // dist/omp-rpc-session.js
17421
+ import { spawn, spawnSync } from "node:child_process";
17422
+ import { randomUUID } from "node:crypto";
17423
+ import path4 from "node:path";
17424
+
17340
17425
  // dist/command.js
17341
17426
  var ompDiscoverySpec = {
17342
17427
  id: "omp",
@@ -20980,7 +21065,14 @@ function createHarnessAdapter(context) {
20980
21065
  return Object.assign(new OmpAdapter({
20981
21066
  ...environment[OMP_COMMAND_ENV] ? { command: environment[OMP_COMMAND_ENV] } : {},
20982
21067
  environment
20983
- }), { installation: createOmpInstallation(environment, environment[OMP_COMMAND_ENV]) });
21068
+ }), {
21069
+ installation: createOmpInstallation(environment, environment[OMP_COMMAND_ENV]),
21070
+ install: createHarnessInstaller(environment, {
21071
+ posix: "https://omp.sh/install",
21072
+ windows: "https://omp.sh/install.ps1",
21073
+ shell: "sh"
21074
+ })
21075
+ });
20984
21076
  }
20985
21077
  export {
20986
21078
  OMP_COMMAND_ENV,