@orbit-build/cli 0.1.6 → 0.1.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.
Files changed (3) hide show
  1. package/README.md +33 -0
  2. package/dist/index.js +1215 -667
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -134,12 +134,12 @@ var require_isexe = __commonJS({
134
134
  if (typeof Promise !== "function") {
135
135
  throw new TypeError("callback not provided");
136
136
  }
137
- return new Promise(function(resolve13, reject) {
137
+ return new Promise(function(resolve15, reject) {
138
138
  isexe(path5, options || {}, function(er, is) {
139
139
  if (er) {
140
140
  reject(er);
141
141
  } else {
142
- resolve13(is);
142
+ resolve15(is);
143
143
  }
144
144
  });
145
145
  });
@@ -206,27 +206,27 @@ var require_which = __commonJS({
206
206
  opt = {};
207
207
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
208
208
  const found = [];
209
- const step = (i) => new Promise((resolve13, reject) => {
209
+ const step = (i) => new Promise((resolve15, reject) => {
210
210
  if (i === pathEnv.length)
211
- return opt.all && found.length ? resolve13(found) : reject(getNotFoundError(cmd));
211
+ return opt.all && found.length ? resolve15(found) : reject(getNotFoundError(cmd));
212
212
  const ppRaw = pathEnv[i];
213
213
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
214
214
  const pCmd = path5.join(pathPart, cmd);
215
215
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
216
- resolve13(subStep(p, i, 0));
216
+ resolve15(subStep(p, i, 0));
217
217
  });
218
- const subStep = (p, i, ii) => new Promise((resolve13, reject) => {
218
+ const subStep = (p, i, ii) => new Promise((resolve15, reject) => {
219
219
  if (ii === pathExt.length)
220
- return resolve13(step(i + 1));
220
+ return resolve15(step(i + 1));
221
221
  const ext = pathExt[ii];
222
222
  isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
223
223
  if (!er && is) {
224
224
  if (opt.all)
225
225
  found.push(p + ext);
226
226
  else
227
- return resolve13(p + ext);
227
+ return resolve15(p + ext);
228
228
  }
229
- return resolve13(subStep(p, i, ii + 1));
229
+ return resolve15(subStep(p, i, ii + 1));
230
230
  });
231
231
  });
232
232
  return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
@@ -438,7 +438,7 @@ var require_parse = __commonJS({
438
438
  }
439
439
  return parsed;
440
440
  }
441
- function parse5(command, args, options) {
441
+ function parse6(command, args, options) {
442
442
  if (args && !Array.isArray(args)) {
443
443
  options = args;
444
444
  args = null;
@@ -457,7 +457,7 @@ var require_parse = __commonJS({
457
457
  };
458
458
  return options.shell ? parsed : parseNonShell(parsed);
459
459
  }
460
- module.exports = parse5;
460
+ module.exports = parse6;
461
461
  }
462
462
  });
463
463
 
@@ -516,16 +516,16 @@ var require_cross_spawn = __commonJS({
516
516
  "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(exports, module) {
517
517
  "use strict";
518
518
  var cp = __require("child_process");
519
- var parse5 = require_parse();
519
+ var parse6 = require_parse();
520
520
  var enoent = require_enoent();
521
521
  function spawn4(command, args, options) {
522
- const parsed = parse5(command, args, options);
522
+ const parsed = parse6(command, args, options);
523
523
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
524
524
  enoent.hookChildProcess(spawned, parsed);
525
525
  return spawned;
526
526
  }
527
527
  function spawnSync(command, args, options) {
528
- const parsed = parse5(command, args, options);
528
+ const parsed = parse6(command, args, options);
529
529
  const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
530
530
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
531
531
  return result;
@@ -533,7 +533,7 @@ var require_cross_spawn = __commonJS({
533
533
  module.exports = spawn4;
534
534
  module.exports.spawn = spawn4;
535
535
  module.exports.sync = spawnSync;
536
- module.exports._parse = parse5;
536
+ module.exports._parse = parse6;
537
537
  module.exports._enoent = enoent;
538
538
  }
539
539
  });
@@ -9218,7 +9218,7 @@ ${lanes.join("\n")}
9218
9218
  return process.memoryUsage().heapUsed;
9219
9219
  },
9220
9220
  getFileSize(path5) {
9221
- const stat = statSync9(path5);
9221
+ const stat = statSync8(path5);
9222
9222
  if (stat == null ? void 0 : stat.isFile()) {
9223
9223
  return stat.size;
9224
9224
  }
@@ -9262,7 +9262,7 @@ ${lanes.join("\n")}
9262
9262
  }
9263
9263
  };
9264
9264
  return nodeSystem;
9265
- function statSync9(path5) {
9265
+ function statSync8(path5) {
9266
9266
  try {
9267
9267
  return _fs.statSync(path5, statSyncOptions);
9268
9268
  } catch {
@@ -9321,7 +9321,7 @@ ${lanes.join("\n")}
9321
9321
  activeSession.post("Profiler.stop", (err, { profile }) => {
9322
9322
  var _a;
9323
9323
  if (!err) {
9324
- if ((_a = statSync9(profilePath)) == null ? void 0 : _a.isDirectory()) {
9324
+ if ((_a = statSync8(profilePath)) == null ? void 0 : _a.isDirectory()) {
9325
9325
  profilePath = _path.join(profilePath, `${(/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-")}+P${process.pid}.cpuprofile`);
9326
9326
  }
9327
9327
  try {
@@ -9441,7 +9441,7 @@ ${lanes.join("\n")}
9441
9441
  let stat;
9442
9442
  if (typeof dirent === "string" || dirent.isSymbolicLink()) {
9443
9443
  const name = combinePaths(path5, entry);
9444
- stat = statSync9(name);
9444
+ stat = statSync8(name);
9445
9445
  if (!stat) {
9446
9446
  continue;
9447
9447
  }
@@ -9465,7 +9465,7 @@ ${lanes.join("\n")}
9465
9465
  return matchFiles(path5, extensions, excludes, includes, useCaseSensitiveFileNames2, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
9466
9466
  }
9467
9467
  function fileSystemEntryExists(path5, entryKind) {
9468
- const stat = statSync9(path5);
9468
+ const stat = statSync8(path5);
9469
9469
  if (!stat) {
9470
9470
  return false;
9471
9471
  }
@@ -9507,7 +9507,7 @@ ${lanes.join("\n")}
9507
9507
  }
9508
9508
  function getModifiedTime3(path5) {
9509
9509
  var _a;
9510
- return (_a = statSync9(path5)) == null ? void 0 : _a.mtime;
9510
+ return (_a = statSync8(path5)) == null ? void 0 : _a.mtime;
9511
9511
  }
9512
9512
  function setModifiedTime(path5, time) {
9513
9513
  try {
@@ -124293,7 +124293,7 @@ ${lanes.join("\n")}
124293
124293
  }
124294
124294
  }
124295
124295
  function createImportCallExpressionAMD(arg, containsLexicalThis) {
124296
- const resolve13 = factory2.createUniqueName("resolve");
124296
+ const resolve15 = factory2.createUniqueName("resolve");
124297
124297
  const reject = factory2.createUniqueName("reject");
124298
124298
  const parameters = [
124299
124299
  factory2.createParameterDeclaration(
@@ -124302,7 +124302,7 @@ ${lanes.join("\n")}
124302
124302
  /*dotDotDotToken*/
124303
124303
  void 0,
124304
124304
  /*name*/
124305
- resolve13
124305
+ resolve15
124306
124306
  ),
124307
124307
  factory2.createParameterDeclaration(
124308
124308
  /*modifiers*/
@@ -124319,7 +124319,7 @@ ${lanes.join("\n")}
124319
124319
  factory2.createIdentifier("require"),
124320
124320
  /*typeArguments*/
124321
124321
  void 0,
124322
- [factory2.createArrayLiteralExpression([arg || factory2.createOmittedExpression()]), resolve13, reject]
124322
+ [factory2.createArrayLiteralExpression([arg || factory2.createOmittedExpression()]), resolve15, reject]
124323
124323
  )
124324
124324
  )
124325
124325
  ]);
@@ -137129,9 +137129,9 @@ ${lanes.join("\n")}
137129
137129
  /*ignoreCase*/
137130
137130
  false
137131
137131
  )) {
137132
- const basename7 = getBaseFileName(a3.fileName);
137133
- if (basename7 === "lib.d.ts" || basename7 === "lib.es6.d.ts") return 0;
137134
- const name = removeSuffix(removePrefix(basename7, "lib."), ".d.ts");
137132
+ const basename8 = getBaseFileName(a3.fileName);
137133
+ if (basename8 === "lib.d.ts" || basename8 === "lib.es6.d.ts") return 0;
137134
+ const name = removeSuffix(removePrefix(basename8, "lib."), ".d.ts");
137135
137135
  const index = libs.indexOf(name);
137136
137136
  if (index !== -1) return index + 1;
137137
137137
  }
@@ -187467,7 +187467,7 @@ ${newComment.split("\n").map((c2) => ` * ${c2}`).join("\n")}
187467
187467
  return ts_textChanges_exports.ChangeTracker.with(
187468
187468
  { host, formatContext, preferences },
187469
187469
  (changeTracker) => {
187470
- const parsed = contents.map((c2) => parse5(sourceFile, c2));
187470
+ const parsed = contents.map((c2) => parse6(sourceFile, c2));
187471
187471
  const flattenedLocations = focusLocations && flatten(focusLocations);
187472
187472
  for (const nodes of parsed) {
187473
187473
  placeNodeGroup(
@@ -187480,7 +187480,7 @@ ${newComment.split("\n").map((c2) => ` * ${c2}`).join("\n")}
187480
187480
  }
187481
187481
  );
187482
187482
  }
187483
- function parse5(sourceFile, content) {
187483
+ function parse6(sourceFile, content) {
187484
187484
  const nodeKinds = [
187485
187485
  {
187486
187486
  parse: () => createSourceFile(
@@ -200877,8 +200877,8 @@ ${options.prefix}` : "\n" : options.prefix
200877
200877
  }
200878
200878
  };
200879
200879
  for (const file of files) {
200880
- const basename7 = getBaseFileName(file);
200881
- if (basename7 === "package.json" || basename7 === "bower.json") {
200880
+ const basename8 = getBaseFileName(file);
200881
+ if (basename8 === "package.json" || basename8 === "bower.json") {
200882
200882
  createProjectWatcher(
200883
200883
  file,
200884
200884
  "FileWatcher"
@@ -204550,8 +204550,8 @@ All files are: ${JSON.stringify(names)}`,
204550
204550
  var _a;
204551
204551
  const fileOrDirectoryPath = removeIgnoredPath(this.toPath(fileOrDirectory));
204552
204552
  if (!fileOrDirectoryPath) return;
204553
- const basename7 = getBaseFileName(fileOrDirectoryPath);
204554
- if (((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size) && (basename7 === "package.json" || basename7 === "node_modules")) {
204553
+ const basename8 = getBaseFileName(fileOrDirectoryPath);
204554
+ if (((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size) && (basename8 === "package.json" || basename8 === "node_modules")) {
204555
204555
  result.affectedModuleSpecifierCacheProjects.forEach((project) => {
204556
204556
  var _a2;
204557
204557
  (_a2 = project.getModuleSpecifierCache()) == null ? void 0 : _a2.clear();
@@ -211037,8 +211037,8 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
211037
211037
  installPackage(options) {
211038
211038
  this.packageInstallId++;
211039
211039
  const request = { kind: "installPackage", ...options, id: this.packageInstallId };
211040
- const promise = new Promise((resolve13, reject) => {
211041
- (this.packageInstalledPromise ?? (this.packageInstalledPromise = /* @__PURE__ */ new Map())).set(this.packageInstallId, { resolve: resolve13, reject });
211040
+ const promise = new Promise((resolve15, reject) => {
211041
+ (this.packageInstalledPromise ?? (this.packageInstalledPromise = /* @__PURE__ */ new Map())).set(this.packageInstallId, { resolve: resolve15, reject });
211042
211042
  });
211043
211043
  this.installer.send(request);
211044
211044
  return promise;
@@ -211378,7 +211378,7 @@ var require_src = __commonJS({
211378
211378
 
211379
211379
  // src/index.ts
211380
211380
  import { Command } from "commander";
211381
- import picocolors23 from "picocolors";
211381
+ import picocolors25 from "picocolors";
211382
211382
 
211383
211383
  // ../shared/dist/index.js
211384
211384
  import { randomUUID } from "crypto";
@@ -211661,7 +211661,7 @@ import { homedir as homedir3 } from "os";
211661
211661
  import { join as join3 } from "path";
211662
211662
  import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
211663
211663
  import { parse } from "yaml";
211664
- import { execFileSync } from "child_process";
211664
+ import { execFileSync as execFileSync2 } from "child_process";
211665
211665
  import {
211666
211666
  chmodSync,
211667
211667
  existsSync as existsSync4,
@@ -211674,6 +211674,8 @@ import {
211674
211674
  import { join as join2 } from "path";
211675
211675
  import { homedir } from "os";
211676
211676
  import crypto from "crypto";
211677
+ import { z as z3 } from "zod";
211678
+ import { execFileSync } from "child_process";
211677
211679
  import { z as z2 } from "zod";
211678
211680
  import crypto2 from "crypto";
211679
211681
  import {
@@ -211689,7 +211691,7 @@ import {
211689
211691
  } from "fs";
211690
211692
  import { homedir as homedir2 } from "os";
211691
211693
  import { join as join22 } from "path";
211692
- import { z as z3 } from "zod";
211694
+ import { z as z4 } from "zod";
211693
211695
  var ORBIT_CONFIG_SCHEMA_VERSION = 1;
211694
211696
  var ModelKindSchema = z.enum([
211695
211697
  "chat",
@@ -212068,15 +212070,85 @@ var DEFAULT_CONFIG = {
212068
212070
  scrollSpeed: 50
212069
212071
  }
212070
212072
  };
212071
- var CredentialKeySchema = z2.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/).refine(
212073
+ var EncodedCredentialKeySchema = z2.string().trim().refine((value) => Buffer.from(value, "base64").length === 32);
212074
+ var MacOSKeychainKeyStore = class {
212075
+ service;
212076
+ account;
212077
+ run;
212078
+ constructor(options = {}) {
212079
+ this.service = options.service ?? "dev.hephaestus.orbit.credentials";
212080
+ this.account = options.account ?? "master-key";
212081
+ this.run = options.run ?? runSecurityCommand;
212082
+ }
212083
+ load() {
212084
+ try {
212085
+ const encoded = EncodedCredentialKeySchema.parse(
212086
+ this.run("security", [
212087
+ "find-generic-password",
212088
+ "-a",
212089
+ this.account,
212090
+ "-s",
212091
+ this.service,
212092
+ "-w"
212093
+ ])
212094
+ );
212095
+ return Buffer.from(encoded, "base64");
212096
+ } catch (error) {
212097
+ if (isMissingKeychainItem(error)) return null;
212098
+ throw new Error("Unable to read the Orbit credential key from Keychain.");
212099
+ }
212100
+ }
212101
+ store(key) {
212102
+ if (key.length !== 32) {
212103
+ throw new Error("Credential key must contain exactly 32 bytes.");
212104
+ }
212105
+ this.run("security", [
212106
+ "add-generic-password",
212107
+ "-U",
212108
+ "-a",
212109
+ this.account,
212110
+ "-s",
212111
+ this.service,
212112
+ "-w",
212113
+ key.toString("base64")
212114
+ ]);
212115
+ }
212116
+ delete() {
212117
+ try {
212118
+ this.run("security", [
212119
+ "delete-generic-password",
212120
+ "-a",
212121
+ this.account,
212122
+ "-s",
212123
+ this.service
212124
+ ]);
212125
+ } catch (error) {
212126
+ if (!isMissingKeychainItem(error)) {
212127
+ throw new Error(
212128
+ "Unable to remove the Orbit credential key from Keychain."
212129
+ );
212130
+ }
212131
+ }
212132
+ }
212133
+ };
212134
+ function runSecurityCommand(executable, args) {
212135
+ return execFileSync(executable, args, {
212136
+ encoding: "utf8",
212137
+ stdio: ["ignore", "pipe", "ignore"]
212138
+ });
212139
+ }
212140
+ function isMissingKeychainItem(error) {
212141
+ return typeof error === "object" && error !== null && ("status" in error && error.status === 44 || "code" in error && error.code === "ENOENT");
212142
+ }
212143
+ var CredentialKeySchema = z3.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/).refine(
212072
212144
  (value) => value !== "__proto__" && value !== "constructor" && value !== "prototype"
212073
212145
  );
212074
- var CredentialValueSchema = z2.string().min(1).max(16384).refine((value) => !/[\r\n]/.test(value));
212075
- var SecretsFileSchema = z2.record(CredentialKeySchema, z2.string());
212076
- var EncryptedSecretSchema = z2.object({
212077
- iv: z2.string().regex(/^[0-9a-f]{24}$/i),
212078
- encrypted: z2.string().regex(/^[0-9a-f]*$/i),
212079
- tag: z2.string().regex(/^[0-9a-f]{32}$/i)
212146
+ var CredentialValueSchema = z3.string().min(1).max(16384).refine((value) => !/[\r\n]/.test(value));
212147
+ var SecretsFileSchema = z3.record(CredentialKeySchema, z3.string());
212148
+ var EncryptedSecretSchema = z3.object({
212149
+ iv: z3.string().regex(/^[0-9a-f]{24}$/i),
212150
+ encrypted: z3.string().regex(/^[0-9a-f]*$/i),
212151
+ tag: z3.string().regex(/^[0-9a-f]{32}$/i)
212080
212152
  });
212081
212153
  function windowsPowerShellEnvironment() {
212082
212154
  const environment = { ...process.env };
@@ -212092,12 +212164,15 @@ var CredentialsManager = class {
212092
212164
  secretsPath;
212093
212165
  masterKeyPath;
212094
212166
  isWindows;
212167
+ keyStore;
212095
212168
  fallbackKey;
212096
212169
  constructor(options = {}) {
212097
212170
  this.orbitDir = options.orbitDir ?? join2(homedir(), ".orbit");
212098
212171
  this.secretsPath = join2(this.orbitDir, "secrets.json");
212099
212172
  this.masterKeyPath = join2(this.orbitDir, "master.key");
212100
- this.isWindows = (options.platform ?? process.platform) === "win32";
212173
+ const platform = options.platform ?? process.platform;
212174
+ this.isWindows = platform === "win32";
212175
+ this.keyStore = options.keyStore === void 0 ? platform === "darwin" ? new MacOSKeychainKeyStore() : null : options.keyStore;
212101
212176
  this.fallbackKey = options.fallbackKey;
212102
212177
  }
212103
212178
  /**
@@ -212147,6 +212222,13 @@ var CredentialsManager = class {
212147
212222
  validatedKey.data
212148
212223
  );
212149
212224
  }
212225
+ /** Remove encrypted credentials and their platform key without revealing data. */
212226
+ purge() {
212227
+ this.keyStore?.delete();
212228
+ this.removeFileIfPresent(this.secretsPath);
212229
+ this.removeFileIfPresent(this.masterKeyPath);
212230
+ this.fallbackKey = void 0;
212231
+ }
212150
212232
  loadSecretsFile() {
212151
212233
  if (!existsSync4(this.secretsPath)) {
212152
212234
  return {};
@@ -212182,7 +212264,7 @@ var CredentialsManager = class {
212182
212264
  encryptWindows(plainText) {
212183
212265
  try {
212184
212266
  const script = "$plain = [Console]::In.ReadLine(); if ($plain) { $plain | ConvertTo-SecureString -AsPlainText -Force -ErrorAction Stop | ConvertFrom-SecureString -ErrorAction Stop }";
212185
- const stdout = execFileSync(
212267
+ const stdout = execFileSync2(
212186
212268
  "powershell.exe",
212187
212269
  ["-NoProfile", "-NonInteractive", "-Command", script],
212188
212270
  {
@@ -212202,7 +212284,7 @@ var CredentialsManager = class {
212202
212284
  decryptWindows(cipherText) {
212203
212285
  try {
212204
212286
  const script = "$cipher = [Console]::In.ReadLine(); if ($cipher) { $secure = ConvertTo-SecureString $cipher -ErrorAction Stop; $pointer = [IntPtr]::Zero; try { $pointer = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure); [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer) } finally { if ($pointer -ne [IntPtr]::Zero) { [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) } } }";
212205
- const stdout = execFileSync(
212287
+ const stdout = execFileSync2(
212206
212288
  "powershell.exe",
212207
212289
  ["-NoProfile", "-NonInteractive", "-Command", script],
212208
212290
  {
@@ -212262,19 +212344,30 @@ var CredentialsManager = class {
212262
212344
  }
212263
212345
  return this.fallbackKey;
212264
212346
  }
212265
- if (existsSync4(this.masterKeyPath)) {
212266
- const decoded = Buffer.from(
212267
- readFileSync(this.masterKeyPath, "utf8"),
212268
- "base64"
212269
- );
212270
- if (decoded.length !== 32) {
212271
- throw new Error("Credential master key is invalid.");
212347
+ const platformKey = this.keyStore?.load();
212348
+ if (platformKey) {
212349
+ this.fallbackKey = this.validateFallbackKey(platformKey);
212350
+ return this.fallbackKey;
212351
+ }
212352
+ const legacyKey = this.readMasterKeyFile();
212353
+ if (legacyKey) {
212354
+ if (this.keyStore) {
212355
+ this.keyStore.store(legacyKey);
212356
+ this.removeFileIfPresent(this.masterKeyPath);
212272
212357
  }
212273
- this.fallbackKey = decoded;
212274
- return decoded;
212358
+ this.fallbackKey = legacyKey;
212359
+ return legacyKey;
212275
212360
  }
212276
- this.ensureOrbitDir();
212277
212361
  const generated = crypto.randomBytes(32);
212362
+ if (this.keyStore) {
212363
+ try {
212364
+ this.keyStore.store(generated);
212365
+ this.fallbackKey = generated;
212366
+ return generated;
212367
+ } catch {
212368
+ }
212369
+ }
212370
+ this.ensureOrbitDir();
212278
212371
  writeFileSync2(this.masterKeyPath, generated.toString("base64"), {
212279
212372
  encoding: "utf8",
212280
212373
  mode: 384,
@@ -212284,23 +212377,44 @@ var CredentialsManager = class {
212284
212377
  this.fallbackKey = generated;
212285
212378
  return generated;
212286
212379
  }
212380
+ readMasterKeyFile() {
212381
+ if (!existsSync4(this.masterKeyPath)) return null;
212382
+ return this.validateFallbackKey(
212383
+ Buffer.from(readFileSync(this.masterKeyPath, "utf8"), "base64")
212384
+ );
212385
+ }
212386
+ validateFallbackKey(key) {
212387
+ if (key.length !== 32) {
212388
+ throw new Error("Credential master key is invalid.");
212389
+ }
212390
+ return key;
212391
+ }
212392
+ removeFileIfPresent(filePath) {
212393
+ try {
212394
+ unlinkSync(filePath);
212395
+ } catch (error) {
212396
+ if (typeof error !== "object" || error === null || !("code" in error) || error.code !== "ENOENT") {
212397
+ throw error;
212398
+ }
212399
+ }
212400
+ }
212287
212401
  restrictFilePermissions(filePath) {
212288
212402
  if (this.isWindows) return;
212289
212403
  chmodSync(filePath, 384);
212290
212404
  }
212291
212405
  };
212292
- var ProviderProfileIdSchema = z3.string().regex(/^[a-z0-9][a-z0-9._-]{0,63}$/);
212293
- var ProviderProfileSchema = z3.object({
212406
+ var ProviderProfileIdSchema = z4.string().regex(/^[a-z0-9][a-z0-9._-]{0,63}$/);
212407
+ var ProviderProfileSchema = z4.object({
212294
212408
  id: ProviderProfileIdSchema,
212295
- name: z3.string().trim().min(1).max(120),
212409
+ name: z4.string().trim().min(1).max(120),
212296
212410
  config: ProviderConfigSchema.omit({ apiKey: true }),
212297
- createdAt: z3.string().datetime(),
212298
- updatedAt: z3.string().datetime()
212411
+ createdAt: z4.string().datetime(),
212412
+ updatedAt: z4.string().datetime()
212299
212413
  });
212300
- var ProviderProfilesFileSchema = z3.object({
212301
- version: z3.literal(1).default(1),
212414
+ var ProviderProfilesFileSchema = z4.object({
212415
+ version: z4.literal(1).default(1),
212302
212416
  activeProvider: ProviderProfileIdSchema.optional(),
212303
- profiles: z3.array(ProviderProfileSchema).max(100)
212417
+ profiles: z4.array(ProviderProfileSchema).max(100)
212304
212418
  });
212305
212419
  var EMPTY_SNAPSHOT = {
212306
212420
  version: 1,
@@ -212863,10 +212977,10 @@ import { execSync as execSync2 } from "child_process";
212863
212977
  import { existsSync as existsSync8 } from "fs";
212864
212978
  import { basename, join as join7 } from "path";
212865
212979
  import picocolors5 from "picocolors";
212866
- import { z as z9 } from "zod";
212980
+ import { z as z10 } from "zod";
212867
212981
 
212868
212982
  // ../model-providers/dist/index.js
212869
- import { z as z4 } from "zod";
212983
+ import { z as z5 } from "zod";
212870
212984
  import { z as z22 } from "zod";
212871
212985
  var ProviderRegistry = class {
212872
212986
  providers = /* @__PURE__ */ new Map();
@@ -213097,11 +213211,11 @@ function modelFinishReasonError(reason) {
213097
213211
  return new Error(`Model generation stopped unexpectedly (${reason}).`);
213098
213212
  }
213099
213213
  function abortableDelay(delayMs, signal) {
213100
- return new Promise((resolve13, reject) => {
213214
+ return new Promise((resolve15, reject) => {
213101
213215
  const cleanup = () => signal?.removeEventListener("abort", onAbort);
213102
213216
  const timeoutId = setTimeout(() => {
213103
213217
  cleanup();
213104
- resolve13();
213218
+ resolve15();
213105
213219
  }, delayMs);
213106
213220
  timeoutId.unref?.();
213107
213221
  function onAbort() {
@@ -213188,52 +213302,52 @@ function getDeepSeekV4ModelProfile(model) {
213188
213302
  function getDeepSeekReasoningEffort(budgetTokens = 4096) {
213189
213303
  return budgetTokens >= 8192 ? "max" : "high";
213190
213304
  }
213191
- var AnthropicUsageSchema = z4.object({
213192
- input_tokens: z4.number().int().nonnegative().optional(),
213193
- output_tokens: z4.number().int().nonnegative().optional(),
213194
- cache_read_input_tokens: z4.number().int().nonnegative().optional(),
213195
- cache_creation_input_tokens: z4.number().int().nonnegative().optional()
213305
+ var AnthropicUsageSchema = z5.object({
213306
+ input_tokens: z5.number().int().nonnegative().optional(),
213307
+ output_tokens: z5.number().int().nonnegative().optional(),
213308
+ cache_read_input_tokens: z5.number().int().nonnegative().optional(),
213309
+ cache_creation_input_tokens: z5.number().int().nonnegative().optional()
213196
213310
  }).passthrough();
213197
- var AnthropicErrorSchema = z4.object({
213198
- message: z4.string(),
213199
- type: z4.string().optional()
213311
+ var AnthropicErrorSchema = z5.object({
213312
+ message: z5.string(),
213313
+ type: z5.string().optional()
213200
213314
  }).passthrough();
213201
- var AnthropicContentBlockSchema = z4.discriminatedUnion("type", [
213202
- z4.object({
213203
- type: z4.literal("text"),
213204
- text: z4.string()
213315
+ var AnthropicContentBlockSchema = z5.discriminatedUnion("type", [
213316
+ z5.object({
213317
+ type: z5.literal("text"),
213318
+ text: z5.string()
213205
213319
  }).passthrough(),
213206
- z4.object({
213207
- type: z4.literal("thinking"),
213208
- thinking: z4.string(),
213209
- signature: z4.string().optional()
213320
+ z5.object({
213321
+ type: z5.literal("thinking"),
213322
+ thinking: z5.string(),
213323
+ signature: z5.string().optional()
213210
213324
  }).passthrough(),
213211
- z4.object({
213212
- type: z4.literal("tool_use"),
213213
- id: z4.string().min(1),
213214
- name: z4.string().min(1),
213215
- input: z4.record(z4.unknown())
213325
+ z5.object({
213326
+ type: z5.literal("tool_use"),
213327
+ id: z5.string().min(1),
213328
+ name: z5.string().min(1),
213329
+ input: z5.record(z5.unknown())
213216
213330
  }).passthrough()
213217
213331
  ]);
213218
- var AnthropicMessageResponseSchema = z4.object({
213219
- content: z4.array(AnthropicContentBlockSchema),
213332
+ var AnthropicMessageResponseSchema = z5.object({
213333
+ content: z5.array(AnthropicContentBlockSchema),
213220
213334
  usage: AnthropicUsageSchema.optional(),
213221
- stop_reason: z4.string().nullable().optional()
213335
+ stop_reason: z5.string().nullable().optional()
213222
213336
  }).passthrough();
213223
- var OfficialDeepSeekUserIdSchema = z4.string().min(1).max(512).regex(/^[A-Za-z0-9_-]+$/);
213224
- var OfficialDeepSeekToolNameSchema = z4.string().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/);
213225
- var AnthropicStreamEventSchema = z4.object({
213226
- type: z4.string(),
213227
- index: z4.number().int().nonnegative().optional(),
213228
- message: z4.object({ usage: AnthropicUsageSchema.optional() }).passthrough().optional(),
213337
+ var OfficialDeepSeekUserIdSchema = z5.string().min(1).max(512).regex(/^[A-Za-z0-9_-]+$/);
213338
+ var OfficialDeepSeekToolNameSchema = z5.string().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/);
213339
+ var AnthropicStreamEventSchema = z5.object({
213340
+ type: z5.string(),
213341
+ index: z5.number().int().nonnegative().optional(),
213342
+ message: z5.object({ usage: AnthropicUsageSchema.optional() }).passthrough().optional(),
213229
213343
  content_block: AnthropicContentBlockSchema.optional(),
213230
- delta: z4.object({
213231
- type: z4.string().optional(),
213232
- text: z4.string().optional(),
213233
- thinking: z4.string().optional(),
213234
- signature: z4.string().optional(),
213235
- partial_json: z4.string().optional(),
213236
- stop_reason: z4.string().nullable().optional()
213344
+ delta: z5.object({
213345
+ type: z5.string().optional(),
213346
+ text: z5.string().optional(),
213347
+ thinking: z5.string().optional(),
213348
+ signature: z5.string().optional(),
213349
+ partial_json: z5.string().optional(),
213350
+ stop_reason: z5.string().nullable().optional()
213237
213351
  }).passthrough().optional(),
213238
213352
  usage: AnthropicUsageSchema.optional(),
213239
213353
  error: AnthropicErrorSchema.optional()
@@ -215015,22 +215129,22 @@ function normalizeOllamaOpenAiBaseUrl(baseUrl) {
215015
215129
  import { existsSync as existsSync5, readdirSync, readFileSync as readFileSync4 } from "fs";
215016
215130
  import { join as join4 } from "path";
215017
215131
  import picocolors3 from "picocolors";
215018
- import { z as z5 } from "zod";
215019
- var CacheTelemetrySampleSchema = z5.object({
215020
- recordedAt: z5.string(),
215021
- inputTokens: z5.number().nonnegative(),
215022
- hitTokens: z5.number().nonnegative(),
215023
- missTokens: z5.number().nonnegative(),
215024
- hitRate: z5.number().min(0).max(1),
215025
- degraded: z5.boolean()
215132
+ import { z as z6 } from "zod";
215133
+ var CacheTelemetrySampleSchema = z6.object({
215134
+ recordedAt: z6.string(),
215135
+ inputTokens: z6.number().nonnegative(),
215136
+ hitTokens: z6.number().nonnegative(),
215137
+ missTokens: z6.number().nonnegative(),
215138
+ hitRate: z6.number().min(0).max(1),
215139
+ degraded: z6.boolean()
215026
215140
  }).passthrough();
215027
- var CacheSlabMetadataSchema = z5.object({
215028
- hash: z5.string().optional(),
215029
- model: z5.string().optional(),
215030
- tokenEstimate: z5.number().nonnegative().optional(),
215141
+ var CacheSlabMetadataSchema = z6.object({
215142
+ hash: z6.string().optional(),
215143
+ model: z6.string().optional(),
215144
+ tokenEstimate: z6.number().nonnegative().optional(),
215031
215145
  /** Read-only compatibility with cache metadata from pre-V4 releases. */
215032
- lastPrimedAt: z5.string().optional(),
215033
- telemetry: z5.array(CacheTelemetrySampleSchema).optional()
215146
+ lastPrimedAt: z6.string().optional(),
215147
+ telemetry: z6.array(CacheTelemetrySampleSchema).optional()
215034
215148
  }).passthrough();
215035
215149
  function readMetadata(filePath) {
215036
215150
  try {
@@ -215108,32 +215222,32 @@ import {
215108
215222
  import { createHash } from "crypto";
215109
215223
  import { dirname as dirname2, join as join5 } from "path";
215110
215224
  import picocolors4 from "picocolors";
215111
- import { z as z6 } from "zod";
215112
- var ProviderBenchmarkResultSchema = z6.object({
215113
- providerId: z6.string().min(1),
215114
- model: z6.string().min(1),
215115
- checkedAt: z6.string().min(1),
215116
- promptHash: z6.string().min(1),
215117
- promptChars: z6.number().int().nonnegative(),
215118
- maxTokens: z6.number().int().positive(),
215119
- firstDeltaMs: z6.number().nonnegative().optional(),
215120
- firstThinkingMs: z6.number().nonnegative().optional(),
215121
- firstTextMs: z6.number().nonnegative().optional(),
215122
- totalMs: z6.number().positive(),
215123
- outputTokens: z6.number().int().nonnegative(),
215124
- reasoningTokens: z6.number().int().nonnegative().optional(),
215125
- textChars: z6.number().int().nonnegative(),
215126
- reasoningChars: z6.number().int().nonnegative().optional(),
215127
- throughputTokensPerSec: z6.number().nonnegative(),
215128
- endToEndTokensPerSec: z6.number().nonnegative().optional(),
215129
- thinkingMode: z6.enum(["disabled", "high", "max"]).optional(),
215130
- cacheReadTokens: z6.number().int().nonnegative(),
215131
- cacheInputTokens: z6.number().int().nonnegative(),
215132
- cacheHitRate: z6.number().min(0).max(1),
215133
- error: z6.string().optional()
215225
+ import { z as z7 } from "zod";
215226
+ var ProviderBenchmarkResultSchema = z7.object({
215227
+ providerId: z7.string().min(1),
215228
+ model: z7.string().min(1),
215229
+ checkedAt: z7.string().min(1),
215230
+ promptHash: z7.string().min(1),
215231
+ promptChars: z7.number().int().nonnegative(),
215232
+ maxTokens: z7.number().int().positive(),
215233
+ firstDeltaMs: z7.number().nonnegative().optional(),
215234
+ firstThinkingMs: z7.number().nonnegative().optional(),
215235
+ firstTextMs: z7.number().nonnegative().optional(),
215236
+ totalMs: z7.number().positive(),
215237
+ outputTokens: z7.number().int().nonnegative(),
215238
+ reasoningTokens: z7.number().int().nonnegative().optional(),
215239
+ textChars: z7.number().int().nonnegative(),
215240
+ reasoningChars: z7.number().int().nonnegative().optional(),
215241
+ throughputTokensPerSec: z7.number().nonnegative(),
215242
+ endToEndTokensPerSec: z7.number().nonnegative().optional(),
215243
+ thinkingMode: z7.enum(["disabled", "high", "max"]).optional(),
215244
+ cacheReadTokens: z7.number().int().nonnegative(),
215245
+ cacheInputTokens: z7.number().int().nonnegative(),
215246
+ cacheHitRate: z7.number().min(0).max(1),
215247
+ error: z7.string().optional()
215134
215248
  }).passthrough();
215135
- var ProviderBenchmarkStoreSchema = z6.object({
215136
- results: z6.array(ProviderBenchmarkResultSchema)
215249
+ var ProviderBenchmarkStoreSchema = z7.object({
215250
+ results: z7.array(ProviderBenchmarkResultSchema)
215137
215251
  });
215138
215252
  function providerBenchmarkPath(cwd) {
215139
215253
  return join5(cwd, ".orbit", "provider-benchmarks.json");
@@ -215401,33 +215515,33 @@ import {
215401
215515
  writeFileSync as writeFileSync4
215402
215516
  } from "fs";
215403
215517
  import { dirname as dirname3, join as join6 } from "path";
215404
- import { z as z7 } from "zod";
215518
+ import { z as z8 } from "zod";
215405
215519
  var DEFAULT_PROVIDER_PROBE_TIMEOUT_MS = 15e3;
215406
- var ModelCapabilitiesSchema = z7.object({
215407
- streaming: z7.boolean(),
215408
- toolCalls: z7.boolean(),
215409
- jsonMode: z7.boolean(),
215410
- thinking: z7.boolean(),
215411
- vision: z7.boolean(),
215412
- promptCaching: z7.boolean(),
215413
- maxContextTokens: z7.number().int().positive().optional(),
215414
- maxOutputTokens: z7.number().int().positive().optional()
215520
+ var ModelCapabilitiesSchema = z8.object({
215521
+ streaming: z8.boolean(),
215522
+ toolCalls: z8.boolean(),
215523
+ jsonMode: z8.boolean(),
215524
+ thinking: z8.boolean(),
215525
+ vision: z8.boolean(),
215526
+ promptCaching: z8.boolean(),
215527
+ maxContextTokens: z8.number().int().positive().optional(),
215528
+ maxOutputTokens: z8.number().int().positive().optional()
215415
215529
  }).passthrough();
215416
- var ProviderProbeResultSchema = z7.object({
215417
- providerId: z7.string().min(1),
215418
- model: z7.string().min(1),
215419
- checkedAt: z7.string().min(1),
215530
+ var ProviderProbeResultSchema = z8.object({
215531
+ providerId: z8.string().min(1),
215532
+ model: z8.string().min(1),
215533
+ checkedAt: z8.string().min(1),
215420
215534
  declared: ModelCapabilitiesSchema,
215421
- observed: z7.object({
215422
- streamStarted: z7.boolean(),
215423
- usageReturned: z7.boolean(),
215424
- cacheUsageReturned: z7.boolean().optional(),
215425
- totalTokensReturned: z7.boolean().optional(),
215426
- error: z7.string().optional(),
215427
- firstDeltaMs: z7.number().nonnegative().optional()
215535
+ observed: z8.object({
215536
+ streamStarted: z8.boolean(),
215537
+ usageReturned: z8.boolean(),
215538
+ cacheUsageReturned: z8.boolean().optional(),
215539
+ totalTokensReturned: z8.boolean().optional(),
215540
+ error: z8.string().optional(),
215541
+ firstDeltaMs: z8.number().nonnegative().optional()
215428
215542
  }).passthrough()
215429
215543
  }).passthrough();
215430
- var ProviderProbeCacheSchema = z7.object({ results: z7.array(z7.unknown()) }).passthrough();
215544
+ var ProviderProbeCacheSchema = z8.object({ results: z8.array(z8.unknown()) }).passthrough();
215431
215545
  function providerProbeCachePath(cwd) {
215432
215546
  return join6(cwd, ".orbit", "provider-capabilities.json");
215433
215547
  }
@@ -215619,9 +215733,9 @@ function createProviderFromConfig(config) {
215619
215733
 
215620
215734
  // src/runtime/CliVersion.ts
215621
215735
  import { readFileSync as readFileSync7 } from "fs";
215622
- import { z as z8 } from "zod";
215623
- var CliPackageManifestSchema = z8.object({
215624
- version: z8.string().trim().regex(
215736
+ import { z as z9 } from "zod";
215737
+ var CliPackageManifestSchema = z9.object({
215738
+ version: z9.string().trim().regex(
215625
215739
  /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,
215626
215740
  "expected a semantic version"
215627
215741
  )
@@ -215649,57 +215763,57 @@ function readCliVersion() {
215649
215763
  }
215650
215764
 
215651
215765
  // src/commands/doctor.ts
215652
- var DoctorIssueSchema = z9.object({
215653
- severity: z9.enum(["warning", "error"]),
215654
- code: z9.string().regex(/^[a-z0-9_.-]+$/),
215655
- message: z9.string().min(1).max(2e3),
215656
- remediation: z9.string().min(1).max(2e3)
215766
+ var DoctorIssueSchema = z10.object({
215767
+ severity: z10.enum(["warning", "error"]),
215768
+ code: z10.string().regex(/^[a-z0-9_.-]+$/),
215769
+ message: z10.string().min(1).max(2e3),
215770
+ remediation: z10.string().min(1).max(2e3)
215657
215771
  });
215658
- var DoctorSnapshotSchema = z9.object({
215659
- schemaVersion: z9.literal(1),
215660
- generatedAt: z9.string().datetime(),
215661
- status: z9.enum(["ok", "warning", "error"]),
215662
- orbit: z9.object({
215663
- version: z9.string(),
215664
- configSchemaVersion: z9.number().int()
215772
+ var DoctorSnapshotSchema = z10.object({
215773
+ schemaVersion: z10.literal(1),
215774
+ generatedAt: z10.string().datetime(),
215775
+ status: z10.enum(["ok", "warning", "error"]),
215776
+ orbit: z10.object({
215777
+ version: z10.string(),
215778
+ configSchemaVersion: z10.number().int()
215665
215779
  }),
215666
- runtime: z9.object({
215667
- node: z9.string(),
215668
- nodeSupported: z9.boolean(),
215669
- platform: z9.string(),
215670
- architecture: z9.string(),
215671
- packageManager: z9.string(),
215672
- gitVersion: z9.string().nullable(),
215673
- ripgrepVersion: z9.string().nullable(),
215674
- gitDirty: z9.boolean().nullable()
215780
+ runtime: z10.object({
215781
+ node: z10.string(),
215782
+ nodeSupported: z10.boolean(),
215783
+ platform: z10.string(),
215784
+ architecture: z10.string(),
215785
+ packageManager: z10.string(),
215786
+ gitVersion: z10.string().nullable(),
215787
+ ripgrepVersion: z10.string().nullable(),
215788
+ gitDirty: z10.boolean().nullable()
215675
215789
  }),
215676
- workspace: z9.object({ name: z9.string(), pathRedacted: z9.literal(true) }),
215677
- provider: z9.object({
215678
- id: z9.string(),
215679
- type: z9.string().nullable(),
215680
- baseUrl: z9.string().nullable(),
215681
- apiKeyLoaded: z9.boolean(),
215682
- apiKeySource: z9.string(),
215683
- deepSeekProfile: z9.boolean(),
215684
- models: z9.record(z9.string()),
215685
- probe: z9.string().nullable()
215790
+ workspace: z10.object({ name: z10.string(), pathRedacted: z10.literal(true) }),
215791
+ provider: z10.object({
215792
+ id: z10.string(),
215793
+ type: z10.string().nullable(),
215794
+ baseUrl: z10.string().nullable(),
215795
+ apiKeyLoaded: z10.boolean(),
215796
+ apiKeySource: z10.string(),
215797
+ deepSeekProfile: z10.boolean(),
215798
+ models: z10.record(z10.string()),
215799
+ probe: z10.string().nullable()
215686
215800
  }),
215687
- features: z9.object({
215688
- webSearch: z9.boolean(),
215689
- mcp: z9.boolean(),
215690
- mcpServerCount: z9.number().int().nonnegative(),
215691
- skills: z9.boolean(),
215692
- automaticCompaction: z9.boolean()
215801
+ features: z10.object({
215802
+ webSearch: z10.boolean(),
215803
+ mcp: z10.boolean(),
215804
+ mcpServerCount: z10.number().int().nonnegative(),
215805
+ skills: z10.boolean(),
215806
+ automaticCompaction: z10.boolean()
215693
215807
  }),
215694
- safety: z9.object({
215695
- permissionMode: z9.enum(["strict", "normal", "auto", "plan"]),
215696
- writeApproval: z9.boolean(),
215697
- commandApproval: z9.boolean(),
215698
- dangerousCommandBlocking: z9.boolean(),
215699
- secretProtection: z9.boolean(),
215700
- projectExecutablesTrusted: z9.boolean()
215808
+ safety: z10.object({
215809
+ permissionMode: z10.enum(["strict", "normal", "auto", "plan"]),
215810
+ writeApproval: z10.boolean(),
215811
+ commandApproval: z10.boolean(),
215812
+ dangerousCommandBlocking: z10.boolean(),
215813
+ secretProtection: z10.boolean(),
215814
+ projectExecutablesTrusted: z10.boolean()
215701
215815
  }),
215702
- issues: z9.array(DoctorIssueSchema)
215816
+ issues: z10.array(DoctorIssueSchema)
215703
215817
  });
215704
215818
  function defaultExec(command, options = {}) {
215705
215819
  return execSync2(command, {
@@ -216199,22 +216313,22 @@ async function runDoctor(cwd, options = {}) {
216199
216313
  import picocolors6 from "picocolors";
216200
216314
  import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
216201
216315
  import { resolve as resolve2 } from "path";
216202
- import { z as z10 } from "zod";
216203
- var BenchOptionsSchema = z10.object({
216204
- prompt: z10.string().optional(),
216205
- provider: z10.string().optional(),
216206
- model: z10.string().optional(),
216207
- models: z10.string().optional(),
216208
- repeat: z10.union([z10.number(), z10.string()]).optional(),
216209
- maxTokens: z10.union([z10.number(), z10.string()]).optional(),
216210
- cacheProfile: z10.boolean().optional(),
216211
- minCacheHit: z10.union([z10.number(), z10.string()]).optional(),
216212
- maxFirstDeltaMs: z10.union([z10.number(), z10.string()]).optional(),
216213
- maxFirstTextMs: z10.union([z10.number(), z10.string()]).optional(),
216214
- minThroughput: z10.union([z10.number(), z10.string()]).optional(),
216215
- maxErrorRate: z10.union([z10.number(), z10.string()]).optional(),
216216
- thinking: z10.string().optional(),
216217
- json: z10.boolean().optional()
216316
+ import { z as z11 } from "zod";
216317
+ var BenchOptionsSchema = z11.object({
216318
+ prompt: z11.string().optional(),
216319
+ provider: z11.string().optional(),
216320
+ model: z11.string().optional(),
216321
+ models: z11.string().optional(),
216322
+ repeat: z11.union([z11.number(), z11.string()]).optional(),
216323
+ maxTokens: z11.union([z11.number(), z11.string()]).optional(),
216324
+ cacheProfile: z11.boolean().optional(),
216325
+ minCacheHit: z11.union([z11.number(), z11.string()]).optional(),
216326
+ maxFirstDeltaMs: z11.union([z11.number(), z11.string()]).optional(),
216327
+ maxFirstTextMs: z11.union([z11.number(), z11.string()]).optional(),
216328
+ minThroughput: z11.union([z11.number(), z11.string()]).optional(),
216329
+ maxErrorRate: z11.union([z11.number(), z11.string()]).optional(),
216330
+ thinking: z11.string().optional(),
216331
+ json: z11.boolean().optional()
216218
216332
  });
216219
216333
  function parseBenchOptions(value) {
216220
216334
  return BenchOptionsSchema.parse(value);
@@ -216653,7 +216767,7 @@ import { z as z27 } from "zod";
216653
216767
  import { z as z28 } from "zod";
216654
216768
 
216655
216769
  // ../tools/dist/index.js
216656
- import { z as z11 } from "zod";
216770
+ import { z as z12 } from "zod";
216657
216771
  import { readFileSync as readFileSync9 } from "fs";
216658
216772
  import { z as z23 } from "zod";
216659
216773
  import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync5 } from "fs";
@@ -217583,7 +217697,7 @@ var setupTimeout = (spawned, { timeout, killSignal = "SIGTERM" }, spawnedPromise
217583
217697
  return spawnedPromise;
217584
217698
  }
217585
217699
  let timeoutId;
217586
- const timeoutPromise = new Promise((resolve13, reject) => {
217700
+ const timeoutPromise = new Promise((resolve15, reject) => {
217587
217701
  timeoutId = setTimeout(() => {
217588
217702
  timeoutKill(spawned, killSignal, reject);
217589
217703
  }, timeout);
@@ -217949,9 +218063,9 @@ var mergePromise = (spawned, promise) => {
217949
218063
  Reflect.defineProperty(spawned, property, { ...descriptor, value });
217950
218064
  }
217951
218065
  };
217952
- var getSpawnedPromise = (spawned) => new Promise((resolve13, reject) => {
218066
+ var getSpawnedPromise = (spawned) => new Promise((resolve15, reject) => {
217953
218067
  spawned.on("exit", (exitCode, signal) => {
217954
- resolve13({ exitCode, signal });
218068
+ resolve15({ exitCode, signal });
217955
218069
  });
217956
218070
  spawned.on("error", (error) => {
217957
218071
  reject(error);
@@ -218264,7 +218378,7 @@ import { join as join8 } from "path";
218264
218378
  import { z as z92 } from "zod";
218265
218379
  import { z as z102 } from "zod";
218266
218380
  import { z as z112 } from "zod";
218267
- import { z as z12 } from "zod";
218381
+ import { z as z122 } from "zod";
218268
218382
  import { z as z13 } from "zod";
218269
218383
  import { existsSync as existsSync23, readFileSync as readFileSync52 } from "fs";
218270
218384
  import { join as join23 } from "path";
@@ -218295,10 +218409,10 @@ var ToolRegistry = class {
218295
218409
  }
218296
218410
  };
218297
218411
  var toolRegistry = new ToolRegistry();
218298
- var ReadFileInputSchema = z11.object({
218299
- path: z11.string(),
218300
- startLine: z11.number().optional(),
218301
- endLine: z11.number().optional()
218412
+ var ReadFileInputSchema = z12.object({
218413
+ path: z12.string(),
218414
+ startLine: z12.number().optional(),
218415
+ endLine: z12.number().optional()
218302
218416
  });
218303
218417
  var ReadFileTool = class {
218304
218418
  name = "read_file";
@@ -219254,8 +219368,8 @@ ${stdout}`
219254
219368
  }
219255
219369
  }
219256
219370
  };
219257
- var GitRestoreInputSchema = z12.object({
219258
- paths: z12.array(z12.string())
219371
+ var GitRestoreInputSchema = z122.object({
219372
+ paths: z122.array(z122.string())
219259
219373
  });
219260
219374
  var GitRestoreTool = class {
219261
219375
  name = "git_restore";
@@ -220561,7 +220675,7 @@ import {
220561
220675
  } from "fs";
220562
220676
  import { join as join9 } from "path";
220563
220677
  import { existsSync as existsSync24, writeFileSync as writeFileSync24, unlinkSync as unlinkSync3 } from "fs";
220564
- import { execFileSync as execFileSync2 } from "child_process";
220678
+ import { execFileSync as execFileSync3 } from "child_process";
220565
220679
  import fs from "fs";
220566
220680
  import path3 from "path";
220567
220681
  var CheckpointManager = class {
@@ -220849,7 +220963,7 @@ var WorktreeManager = class {
220849
220963
  snapshotWorkingTree(worktreePath) {
220850
220964
  const patch = this.gitBuffer(["diff", "HEAD", "--binary", "--no-ext-diff"]);
220851
220965
  if (patch.length > 0) {
220852
- execFileSync2("git", ["apply", "--whitespace=nowarn", "-"], {
220966
+ execFileSync3("git", ["apply", "--whitespace=nowarn", "-"], {
220853
220967
  cwd: worktreePath,
220854
220968
  input: patch,
220855
220969
  stdio: ["pipe", "pipe", "pipe"],
@@ -220898,7 +221012,7 @@ var WorktreeManager = class {
220898
221012
  session.path
220899
221013
  );
220900
221014
  if (delta.length === 0) return;
220901
- execFileSync2("git", ["apply", "--whitespace=nowarn", "-"], {
221015
+ execFileSync3("git", ["apply", "--whitespace=nowarn", "-"], {
220902
221016
  cwd: this.cwd,
220903
221017
  input: delta,
220904
221018
  stdio: ["pipe", "pipe", "pipe"],
@@ -220906,14 +221020,14 @@ var WorktreeManager = class {
220906
221020
  });
220907
221021
  }
220908
221022
  git(args, cwd = this.cwd) {
220909
- return execFileSync2("git", args, {
221023
+ return execFileSync3("git", args, {
220910
221024
  cwd,
220911
221025
  encoding: "utf8",
220912
221026
  stdio: ["ignore", "pipe", "pipe"]
220913
221027
  });
220914
221028
  }
220915
221029
  gitBuffer(args, cwd = this.cwd) {
220916
- return execFileSync2("git", args, {
221030
+ return execFileSync3("git", args, {
220917
221031
  cwd,
220918
221032
  encoding: "buffer",
220919
221033
  stdio: ["ignore", "pipe", "pipe"],
@@ -224954,7 +225068,7 @@ var Prompt = class {
224954
225068
  });
224955
225069
  }
224956
225070
  static async askTextWithAutocomplete(message, completerFn, promptPrefix) {
224957
- return new Promise((resolve13) => {
225071
+ return new Promise((resolve15) => {
224958
225072
  const promptStr = promptPrefix !== void 0 ? promptPrefix : `${picocolors22.cyan("?")} ${message} \u203A `;
224959
225073
  const rl = readline.createInterface({
224960
225074
  input: process.stdin,
@@ -225021,7 +225135,7 @@ var Prompt = class {
225021
225135
  clearSuggestions();
225022
225136
  rl.close();
225023
225137
  process.stdout.write("\n");
225024
- resolve13(null);
225138
+ resolve15(null);
225025
225139
  return;
225026
225140
  }
225027
225141
  if (currentSuggestion && key && (key.name === "tab" || key.name === "right")) {
@@ -225049,12 +225163,12 @@ var Prompt = class {
225049
225163
  clearSuggestions();
225050
225164
  rl.close();
225051
225165
  process.stdout.write("\n");
225052
- resolve13(null);
225166
+ resolve15(null);
225053
225167
  });
225054
225168
  rl.on("line", (line) => {
225055
225169
  clearSuggestions();
225056
225170
  rl.close();
225057
- resolve13(line);
225171
+ resolve15(line);
225058
225172
  });
225059
225173
  });
225060
225174
  }
@@ -225576,7 +225690,7 @@ var MCPClient = class {
225576
225690
  return result.tools;
225577
225691
  }
225578
225692
  sendRequest(method, params) {
225579
- return new Promise((resolve13, reject) => {
225693
+ return new Promise((resolve15, reject) => {
225580
225694
  const stdin = this.child?.stdin;
225581
225695
  if (!this.isConnected || !stdin || !stdin.writable) {
225582
225696
  reject(new Error("MCP server process is not running."));
@@ -225591,7 +225705,7 @@ var MCPClient = class {
225591
225705
  )
225592
225706
  );
225593
225707
  }, MCP_REQUEST_TIMEOUT_MS);
225594
- this.pendingRequests.set(id, { resolve: resolve13, reject, timeout });
225708
+ this.pendingRequests.set(id, { resolve: resolve15, reject, timeout });
225595
225709
  stdin.write(
225596
225710
  `${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
225597
225711
  `,
@@ -229475,11 +229589,11 @@ ${stdout.substring(0, 2e4)}`
229475
229589
  \u25CF Auto-committing changes...`);
229476
229590
  try {
229477
229591
  const uniqueFiles = Array.from(new Set(modifiedFiles));
229478
- const { execFileSync: execFileSync5 } = await import("child_process");
229592
+ const { execFileSync: execFileSync7 } = await import("child_process");
229479
229593
  for (const file of uniqueFiles) {
229480
- execFileSync5("git", ["add", file], { cwd: this.cwd });
229594
+ execFileSync7("git", ["add", file], { cwd: this.cwd });
229481
229595
  }
229482
- const diff = execFileSync5("git", ["diff", "--cached"], {
229596
+ const diff = execFileSync7("git", ["diff", "--cached"], {
229483
229597
  cwd: this.cwd
229484
229598
  }).toString().trim();
229485
229599
  if (diff) {
@@ -229514,7 +229628,7 @@ ${diff.substring(0, 2e4)}`
229514
229628
  this.interaction.showText(
229515
229629
  `\u25CF Committing: "${picocolors8.green(finalMsg)}"`
229516
229630
  );
229517
- execFileSync5("git", ["commit", "-m", finalMsg], {
229631
+ execFileSync7("git", ["commit", "-m", finalMsg], {
229518
229632
  cwd: this.cwd
229519
229633
  });
229520
229634
  this.interaction.showText(
@@ -230794,12 +230908,12 @@ var AutocompleteEngine = class {
230794
230908
  this.activeRequests.set(windowId, controller);
230795
230909
  const signal = controller.signal;
230796
230910
  const debounceMs = config.autocomplete?.debounceMs !== void 0 ? config.autocomplete.debounceMs : 150;
230797
- return new Promise((resolve13) => {
230798
- this.debounceResolvers.set(windowId, resolve13);
230911
+ return new Promise((resolve15) => {
230912
+ this.debounceResolvers.set(windowId, resolve15);
230799
230913
  const timer = setTimeout(async () => {
230800
230914
  this.debounceResolvers.delete(windowId);
230801
230915
  if (signal.aborted) {
230802
- resolve13("");
230916
+ resolve15("");
230803
230917
  return;
230804
230918
  }
230805
230919
  const providerId = config.autocomplete.provider || "ollama";
@@ -230807,7 +230921,7 @@ var AutocompleteEngine = class {
230807
230921
  try {
230808
230922
  const provider = this.getCachedProvider(providerId, config);
230809
230923
  if (typeof provider.complete !== "function") {
230810
- resolve13("");
230924
+ resolve15("");
230811
230925
  return;
230812
230926
  }
230813
230927
  const header = getPathCommentHeader(windowId, this.cwd);
@@ -230909,21 +231023,21 @@ var AutocompleteEngine = class {
230909
231023
  timeoutPromise
230910
231024
  ]);
230911
231025
  if (winner !== "__TIMEOUT__" && winner.trim() !== "") {
230912
- resolve13(winner);
231026
+ resolve15(winner);
230913
231027
  } else {
230914
231028
  const localResult = await localPromise;
230915
231029
  if (localResult.trim() !== "") {
230916
- resolve13(localResult);
231030
+ resolve15(localResult);
230917
231031
  } else {
230918
- resolve13(await cloudPromise.catch(() => ""));
231032
+ resolve15(await cloudPromise.catch(() => ""));
230919
231033
  }
230920
231034
  }
230921
231035
  } else {
230922
231036
  const completed = await cloudPromise;
230923
- resolve13(completed);
231037
+ resolve15(completed);
230924
231038
  }
230925
231039
  } catch {
230926
- resolve13("");
231040
+ resolve15("");
230927
231041
  } finally {
230928
231042
  if (this.activeRequests.get(windowId) === controller) {
230929
231043
  this.activeRequests.delete(windowId);
@@ -230936,7 +231050,7 @@ var AutocompleteEngine = class {
230936
231050
  /** Cancel outstanding completions and release timers held by the engine. */
230937
231051
  dispose() {
230938
231052
  for (const timer of this.debounceTimers.values()) clearTimeout(timer);
230939
- for (const resolve13 of this.debounceResolvers.values()) resolve13("");
231053
+ for (const resolve15 of this.debounceResolvers.values()) resolve15("");
230940
231054
  for (const controller of this.activeRequests.values()) controller.abort();
230941
231055
  this.debounceTimers.clear();
230942
231056
  this.debounceResolvers.clear();
@@ -230946,20 +231060,14 @@ var AutocompleteEngine = class {
230946
231060
  };
230947
231061
 
230948
231062
  // src/commands/run.ts
230949
- import picocolors19 from "picocolors";
230950
- import { existsSync as existsSync29, readFileSync as readFileSync19 } from "fs";
230951
- import { join as join18 } from "path";
231063
+ import picocolors20 from "picocolors";
231064
+ import { existsSync as existsSync28, readFileSync as readFileSync19 } from "fs";
231065
+ import { join as join17 } from "path";
230952
231066
 
230953
231067
  // src/tui/FullscreenTui.ts
230954
231068
  import { join as join14 } from "path";
230955
231069
  import { homedir as homedir7 } from "os";
230956
- import {
230957
- existsSync as existsSync15,
230958
- readFileSync as readFileSync15,
230959
- writeFileSync as writeFileSync11,
230960
- mkdirSync as mkdirSync11,
230961
- statSync as statSync5
230962
- } from "fs";
231070
+ import { existsSync as existsSync15, readFileSync as readFileSync15, writeFileSync as writeFileSync11, mkdirSync as mkdirSync11 } from "fs";
230963
231071
  import { exec as exec3 } from "child_process";
230964
231072
  import readline3 from "readline";
230965
231073
 
@@ -231016,7 +231124,7 @@ function buildSlashCommandHelp(isZh) {
231016
231124
  ` ${picocolors9.green("/config")} ${picocolors9.cyan("[k=v]")} - \u67E5\u770B\u6216\u76F4\u63A5\u4FEE\u6539\u914D\u7F6E\u53C2\u6570`,
231017
231125
  ` ${picocolors9.green("/model")} ${picocolors9.cyan("[name]")} - \u52A8\u6001\u67E5\u8BE2\u6216\u5207\u6362\u6B63\u5728\u4F7F\u7528\u7684\u8BED\u8A00\u5927\u6A21\u578B`,
231018
231126
  ` ${picocolors9.green("/mode")} ${picocolors9.cyan("[mode]")} - \u5207\u6362\u5B89\u5168\u786E\u8BA4\u6A21\u5F0F (strict, normal, auto, plan)`,
231019
- ` ${picocolors9.green("/update")} - \u68C0\u6D4B\u5E76\u66F4\u65B0\u9879\u76EE\u4F9D\u8D56\u5305`,
231127
+ ` ${picocolors9.green("/update")} - \u68C0\u67E5\u5E76\u66F4\u65B0 Orbit \u5230\u6700\u65B0 npm \u7248\u672C`,
231020
231128
  ` ${picocolors9.green("/webui")} ${picocolors9.cyan("[port]")} - \u542F\u52A8\u5E76\u6253\u5F00 Orbit \u56FE\u5F62\u63A7\u5236\u53F0`,
231021
231129
  "",
231022
231130
  picocolors9.bold(picocolors9.yellow("[ Git \u63D0\u4EA4 (Git) ]")),
@@ -231051,7 +231159,7 @@ function buildSlashCommandHelp(isZh) {
231051
231159
  ` ${picocolors9.green("/config")} ${picocolors9.cyan("[k=v]")} - View or modify configurations`,
231052
231160
  ` ${picocolors9.green("/model")} ${picocolors9.cyan("[name]")} - Show or switch active model`,
231053
231161
  ` ${picocolors9.green("/mode")} ${picocolors9.cyan("[mode]")} - Switch permission mode (strict, normal, auto, plan)`,
231054
- ` ${picocolors9.green("/update")} - Check and update dependencies`,
231162
+ ` ${picocolors9.green("/update")} - Check and update Orbit from npm`,
231055
231163
  ` ${picocolors9.green("/webui")} ${picocolors9.cyan("[port]")} - Start and open the Orbit graphical console`,
231056
231164
  "",
231057
231165
  picocolors9.bold(picocolors9.yellow("[ Git Version Control ]")),
@@ -231673,7 +231781,7 @@ var TuiPromptSession = class {
231673
231781
  this.requestRender();
231674
231782
  const wasRaw = !!this.stdin.isRaw;
231675
231783
  if (this.stdin.setRawMode) this.stdin.setRawMode(true);
231676
- return new Promise((resolve13) => {
231784
+ return new Promise((resolve15) => {
231677
231785
  const listener = (str, key = {}) => {
231678
231786
  const state = this.promptState;
231679
231787
  if (!state) {
@@ -231691,7 +231799,7 @@ var TuiPromptSession = class {
231691
231799
  this.requestRender();
231692
231800
  }
231693
231801
  };
231694
- this.active = { resolve: resolve13, wasRaw, listener };
231802
+ this.active = { resolve: resolve15, wasRaw, listener };
231695
231803
  this.stdin.on("keypress", listener);
231696
231804
  this.stdin.resume();
231697
231805
  });
@@ -231891,6 +231999,158 @@ function renderPromptScreen(state, viewport, theme = MORANDI) {
231891
231999
  return "\x1B[?25l\x1B[H" + lines.map((line) => line + "\x1B[K").join("\n") + "\x1B[J" + cursorSequence;
231892
232000
  }
231893
232001
 
232002
+ // src/runtime/UpdateManager.ts
232003
+ import { execFile as execFile4, execFileSync as execFileSync4 } from "child_process";
232004
+ import { z as z30 } from "zod";
232005
+ var SemanticVersionSchema = z30.string().trim().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/);
232006
+ var UpdateCheckSchema = z30.object({
232007
+ currentVersion: SemanticVersionSchema,
232008
+ latestVersion: SemanticVersionSchema,
232009
+ updateAvailable: z30.boolean()
232010
+ });
232011
+ var UpdateManager = class {
232012
+ executable;
232013
+ argumentPrefix;
232014
+ run;
232015
+ runAsync;
232016
+ timeoutMs;
232017
+ constructor(options = {}) {
232018
+ const platform = options.platform ?? process.platform;
232019
+ this.executable = platform === "win32" ? options.windowsCommandShell ?? process.env.ComSpec ?? "cmd.exe" : "npm";
232020
+ this.argumentPrefix = platform === "win32" ? ["/d", "/s", "/c", "npm.cmd"] : [];
232021
+ this.run = options.run ?? runNpmCommand;
232022
+ this.runAsync = options.runAsync ?? runNpmCommandAsync;
232023
+ this.timeoutMs = options.timeoutMs ?? 15e3;
232024
+ }
232025
+ check(currentVersion) {
232026
+ const validatedCurrentVersion = SemanticVersionSchema.parse(currentVersion);
232027
+ const raw = this.run(this.executable, this.latestVersionArguments(), {
232028
+ timeoutMs: this.timeoutMs,
232029
+ inheritOutput: false
232030
+ });
232031
+ return this.createUpdateCheck(validatedCurrentVersion, raw);
232032
+ }
232033
+ async checkAsync(currentVersion) {
232034
+ const validatedCurrentVersion = SemanticVersionSchema.parse(currentVersion);
232035
+ const raw = await this.runAsync(
232036
+ this.executable,
232037
+ this.latestVersionArguments(),
232038
+ this.timeoutMs
232039
+ );
232040
+ return this.createUpdateCheck(validatedCurrentVersion, raw);
232041
+ }
232042
+ latestVersionArguments() {
232043
+ return [
232044
+ ...this.argumentPrefix,
232045
+ "view",
232046
+ "@orbit-build/cli",
232047
+ "dist-tags.latest",
232048
+ "--json"
232049
+ ];
232050
+ }
232051
+ createUpdateCheck(validatedCurrentVersion, raw) {
232052
+ const latestVersion = SemanticVersionSchema.parse(parseNpmJsonString(raw));
232053
+ return {
232054
+ currentVersion: validatedCurrentVersion,
232055
+ latestVersion,
232056
+ updateAvailable: compareSemanticVersions(latestVersion, validatedCurrentVersion) > 0
232057
+ };
232058
+ }
232059
+ install(version, inheritOutput = true) {
232060
+ const validatedVersion = SemanticVersionSchema.parse(version);
232061
+ this.run(
232062
+ this.executable,
232063
+ [
232064
+ ...this.argumentPrefix,
232065
+ "install",
232066
+ "--global",
232067
+ `@orbit-build/cli@${validatedVersion}`,
232068
+ "--no-audit",
232069
+ "--no-fund"
232070
+ ],
232071
+ { timeoutMs: Math.max(this.timeoutMs, 12e4), inheritOutput }
232072
+ );
232073
+ }
232074
+ };
232075
+ function parseNpmJsonString(raw) {
232076
+ try {
232077
+ return JSON.parse(raw);
232078
+ } catch (error) {
232079
+ throw new Error("npm returned an invalid latest-version response.", {
232080
+ cause: error
232081
+ });
232082
+ }
232083
+ }
232084
+ function compareSemanticVersions(left, right) {
232085
+ const parse6 = (version) => {
232086
+ const withoutBuild = version.split("+", 1)[0] ?? version;
232087
+ const prereleaseSeparator = withoutBuild.indexOf("-");
232088
+ const corePart = prereleaseSeparator === -1 ? withoutBuild : withoutBuild.slice(0, prereleaseSeparator);
232089
+ const prereleasePart = prereleaseSeparator === -1 ? void 0 : withoutBuild.slice(prereleaseSeparator + 1);
232090
+ return {
232091
+ core: corePart.split(".").map(Number),
232092
+ prerelease: prereleasePart ? prereleasePart.split(".") : []
232093
+ };
232094
+ };
232095
+ const leftVersion = parse6(left);
232096
+ const rightVersion = parse6(right);
232097
+ for (let index = 0; index < 3; index++) {
232098
+ const difference = (leftVersion.core[index] ?? 0) - (rightVersion.core[index] ?? 0);
232099
+ if (difference !== 0) return Math.sign(difference);
232100
+ }
232101
+ if (leftVersion.prerelease.length === 0) {
232102
+ return rightVersion.prerelease.length === 0 ? 0 : 1;
232103
+ }
232104
+ if (rightVersion.prerelease.length === 0) return -1;
232105
+ const length = Math.max(
232106
+ leftVersion.prerelease.length,
232107
+ rightVersion.prerelease.length
232108
+ );
232109
+ for (let index = 0; index < length; index++) {
232110
+ const leftPart = leftVersion.prerelease[index];
232111
+ const rightPart = rightVersion.prerelease[index];
232112
+ if (leftPart === void 0) return -1;
232113
+ if (rightPart === void 0) return 1;
232114
+ if (leftPart === rightPart) continue;
232115
+ const leftNumber = /^\d+$/.test(leftPart) ? Number(leftPart) : null;
232116
+ const rightNumber = /^\d+$/.test(rightPart) ? Number(rightPart) : null;
232117
+ if (leftNumber !== null && rightNumber !== null) {
232118
+ return Math.sign(leftNumber - rightNumber);
232119
+ }
232120
+ if (leftNumber !== null) return -1;
232121
+ if (rightNumber !== null) return 1;
232122
+ return leftPart.localeCompare(rightPart);
232123
+ }
232124
+ return 0;
232125
+ }
232126
+ function runNpmCommand(executable, args, options) {
232127
+ return execFileSync4(executable, args, {
232128
+ encoding: "utf8",
232129
+ timeout: options.timeoutMs,
232130
+ stdio: options.inheritOutput ? ["ignore", "inherit", "inherit"] : ["ignore", "pipe", "pipe"]
232131
+ });
232132
+ }
232133
+ function runNpmCommandAsync(executable, args, timeoutMs) {
232134
+ return new Promise((resolve15, reject) => {
232135
+ execFile4(
232136
+ executable,
232137
+ args,
232138
+ {
232139
+ encoding: "utf8",
232140
+ timeout: timeoutMs,
232141
+ windowsHide: true
232142
+ },
232143
+ (error, stdout) => {
232144
+ if (error) {
232145
+ reject(error);
232146
+ return;
232147
+ }
232148
+ resolve15(stdout);
232149
+ }
232150
+ );
232151
+ });
232152
+ }
232153
+
231894
232154
  // src/tui/TextPager.ts
231895
232155
  import readline2 from "readline";
231896
232156
  async function pageText(text) {
@@ -231911,11 +232171,11 @@ async function pageText(text) {
231911
232171
  process.stdin.setRawMode(true);
231912
232172
  process.stdin.resume();
231913
232173
  readline2.emitKeypressEvents(process.stdin);
231914
- const waitForKeypress = () => new Promise((resolve13) => {
232174
+ const waitForKeypress = () => new Promise((resolve15) => {
231915
232175
  const onKeypress = (str, key) => {
231916
232176
  process.stdin.removeListener("keypress", onKeypress);
231917
- if (key?.ctrl && key.name === "c") return resolve13("interrupt");
231918
- resolve13(key?.name || str);
232177
+ if (key?.ctrl && key.name === "c") return resolve15("interrupt");
232178
+ resolve15(key?.name || str);
231919
232179
  };
231920
232180
  process.stdin.on("keypress", onKeypress);
231921
232181
  });
@@ -231945,11 +232205,12 @@ async function pageText(text) {
231945
232205
  // src/tui/FullscreenTui.ts
231946
232206
  var INPUT_PREFIX_WIDTH = 12;
231947
232207
  var FullscreenTui = class {
231948
- constructor(cwd, modelName, version, config) {
232208
+ constructor(cwd, modelName, version, config, dependencies = {}) {
231949
232209
  this.cwd = cwd;
231950
232210
  this.modelName = modelName;
231951
232211
  this.version = version;
231952
232212
  this.config = config;
232213
+ this.checkOrbitUpdate = dependencies.checkOrbitUpdate ?? (async (currentVersion) => (await new UpdateManager().checkAsync(currentVersion)).updateAvailable);
231953
232214
  }
231954
232215
  cwd;
231955
232216
  modelName;
@@ -231981,9 +232242,9 @@ var FullscreenTui = class {
231981
232242
  promptSession = new TuiPromptSession(() => this.render());
231982
232243
  isThinking = false;
231983
232244
  sessionCost = 0;
231984
- lastNpmCheckTime = 0;
231985
- isCheckingNpm = false;
231986
- npmNeedsUpdate = false;
232245
+ hasCheckedOrbitUpdate = false;
232246
+ isCheckingOrbitUpdate = false;
232247
+ orbitUpdateAvailable = false;
231987
232248
  totalInputTokens = 0;
231988
232249
  totalCacheReadTokens = 0;
231989
232250
  totalOutputTokens = 0;
@@ -232020,6 +232281,7 @@ var FullscreenTui = class {
232020
232281
  hasNewOutputWhileScrolled = false;
232021
232282
  inputHistoryStore = new InputHistoryStore();
232022
232283
  terminalInitialized = false;
232284
+ checkOrbitUpdate;
232023
232285
  getPlanLines() {
232024
232286
  const now = Date.now();
232025
232287
  if (now - this.lastPlanReadTime < 2e3) {
@@ -232330,72 +232592,30 @@ var FullscreenTui = class {
232330
232592
  }
232331
232593
  this.terminalInitialized = false;
232332
232594
  }
232333
- getNpmNeedsUpdate() {
232334
- const now = Date.now();
232335
- if (now - this.lastNpmCheckTime > 8e3) {
232336
- this.refreshNpmStatusAsync().catch(() => {
232337
- });
232595
+ getOrbitUpdateAvailable() {
232596
+ if (!this.hasCheckedOrbitUpdate && !this.isCheckingOrbitUpdate) {
232597
+ void this.refreshOrbitUpdateStatus();
232338
232598
  }
232339
- return this.npmNeedsUpdate;
232599
+ return this.orbitUpdateAvailable;
232340
232600
  }
232341
- async refreshNpmStatusAsync() {
232342
- if (this.isCheckingNpm) return;
232343
- this.isCheckingNpm = true;
232344
- this.lastNpmCheckTime = Date.now();
232601
+ setOrbitUpdateAvailable(updateAvailable) {
232602
+ this.hasCheckedOrbitUpdate = true;
232603
+ this.orbitUpdateAvailable = updateAvailable;
232604
+ if (this.isActive) this.render();
232605
+ }
232606
+ async refreshOrbitUpdateStatus() {
232607
+ if (this.hasCheckedOrbitUpdate || this.isCheckingOrbitUpdate) return;
232608
+ this.isCheckingOrbitUpdate = true;
232609
+ this.hasCheckedOrbitUpdate = true;
232345
232610
  try {
232346
- const packageJsonPath = join14(this.cwd, "package.json");
232347
- if (!existsSync15(packageJsonPath)) {
232348
- this.npmNeedsUpdate = false;
232349
- this.isCheckingNpm = false;
232350
- return;
232351
- }
232352
- const nodeModulesPath = join14(this.cwd, "node_modules");
232353
- if (!existsSync15(nodeModulesPath)) {
232354
- this.npmNeedsUpdate = true;
232355
- this.isCheckingNpm = false;
232356
- this.render();
232357
- return;
232358
- }
232359
- const lockfiles = [
232360
- "package-lock.json",
232361
- "pnpm-lock.yaml",
232362
- "yarn.lock",
232363
- "bun.lockb"
232364
- ];
232365
- let maxLockfileMtime = 0;
232366
- let hasLockfile = false;
232367
- for (const lf of lockfiles) {
232368
- const lfPath = join14(this.cwd, lf);
232369
- if (existsSync15(lfPath)) {
232370
- hasLockfile = true;
232371
- const stat = statSync5(lfPath);
232372
- if (stat.mtimeMs > maxLockfileMtime) {
232373
- maxLockfileMtime = stat.mtimeMs;
232374
- }
232375
- }
232376
- }
232377
- const configMtimeToCheck = hasLockfile ? maxLockfileMtime : statSync5(packageJsonPath).mtimeMs;
232378
- let maxInstallStateMtime = statSync5(nodeModulesPath).mtimeMs;
232379
- const stateFiles = [
232380
- join14(nodeModulesPath, ".modules.yaml"),
232381
- // pnpm
232382
- join14(nodeModulesPath, ".package-lock.json")
232383
- // npm
232384
- ];
232385
- for (const sf of stateFiles) {
232386
- if (existsSync15(sf)) {
232387
- const stat = statSync5(sf);
232388
- if (stat.mtimeMs > maxInstallStateMtime) {
232389
- maxInstallStateMtime = stat.mtimeMs;
232390
- }
232391
- }
232392
- }
232393
- this.npmNeedsUpdate = configMtimeToCheck > maxInstallStateMtime;
232611
+ this.orbitUpdateAvailable = await this.checkOrbitUpdate(
232612
+ this.version.replace(/^v/i, "")
232613
+ );
232394
232614
  } catch {
232395
- this.npmNeedsUpdate = false;
232615
+ this.orbitUpdateAvailable = false;
232396
232616
  } finally {
232397
- this.isCheckingNpm = false;
232398
- this.render();
232617
+ this.isCheckingOrbitUpdate = false;
232618
+ if (this.isActive) this.render();
232399
232619
  }
232400
232620
  }
232401
232621
  getGitSummary() {
@@ -232426,20 +232646,20 @@ var FullscreenTui = class {
232426
232646
  modified: 0,
232427
232647
  deleted: 0
232428
232648
  };
232429
- const branchPromise = new Promise((resolve13) => {
232649
+ const branchPromise = new Promise((resolve15) => {
232430
232650
  exec3(
232431
232651
  "git rev-parse --abbrev-ref HEAD",
232432
232652
  { cwd: this.cwd },
232433
232653
  (err, stdout) => {
232434
- if (err) resolve13("no-git");
232435
- else resolve13(stdout.trim());
232654
+ if (err) resolve15("no-git");
232655
+ else resolve15(stdout.trim());
232436
232656
  }
232437
232657
  );
232438
232658
  });
232439
- const statusPromise = new Promise((resolve13) => {
232659
+ const statusPromise = new Promise((resolve15) => {
232440
232660
  exec3("git status --porcelain", { cwd: this.cwd }, (err, stdout) => {
232441
- if (err) resolve13("");
232442
- else resolve13(stdout);
232661
+ if (err) resolve15("");
232662
+ else resolve15(stdout);
232443
232663
  });
232444
232664
  });
232445
232665
  const [branch, statusOutput] = await Promise.all([
@@ -232917,8 +233137,8 @@ var FullscreenTui = class {
232917
233137
  this.start(this.budgetLimit);
232918
233138
  }
232919
233139
  process.stdout.write("\x1B[?25h");
232920
- return new Promise((resolve13) => {
232921
- this.resolveInput = resolve13;
233140
+ return new Promise((resolve15) => {
233141
+ this.resolveInput = resolve15;
232922
233142
  this.inputBuffer = "";
232923
233143
  this.cursorPosition = 0;
232924
233144
  this.hideAutocomplete = false;
@@ -232953,7 +233173,7 @@ var FullscreenTui = class {
232953
233173
  cleanup();
232954
233174
  process.stdout.write("\x1B[?25l");
232955
233175
  this.resolveInput = null;
232956
- resolve13(null);
233176
+ resolve15(null);
232957
233177
  } else {
232958
233178
  this.ctrlCPressedOnce = true;
232959
233179
  if (this.ctrlCTimeout) clearTimeout(this.ctrlCTimeout);
@@ -233007,7 +233227,7 @@ var FullscreenTui = class {
233007
233227
  this.inputBuffer = "";
233008
233228
  this.cursorPosition = 0;
233009
233229
  this.render();
233010
- resolve13(submitted);
233230
+ resolve15(submitted);
233011
233231
  return;
233012
233232
  }
233013
233233
  if (key && key.ctrl && key.name === "j") {
@@ -233447,7 +233667,7 @@ var FullscreenTui = class {
233447
233667
  "/mode": "\u52A8\u6001\u5207\u6362\u7CFB\u7EDF\u5B89\u5168\u786E\u8BA4\u6A21\u5F0F (strict, normal, auto, plan)",
233448
233668
  "/copy": "\u62F7\u8D1D AI \u7684\u4E0A\u4E00\u6761\u56DE\u590D\u5230\u7CFB\u7EDF\u526A\u8D34\u677F",
233449
233669
  "/run": "\u6267\u884C\u4E00\u6761\u672C\u673A Shell \u547D\u4EE4\uFF0C\u4F1A\u5148\u8D70\u6743\u9650\u68C0\u67E5",
233450
- "/update": "\u68C0\u6D4B\u5E76\u66F4\u65B0\u5F53\u524D\u9879\u76EE\u4F9D\u8D56",
233670
+ "/update": "\u68C0\u67E5\u5E76\u66F4\u65B0 Orbit \u5230\u6700\u65B0 npm \u7248\u672C",
233451
233671
  "/webui": "\u542F\u52A8\u5E76\u6253\u5F00 Orbit \u56FE\u5F62\u63A7\u5236\u53F0\u9875\u9762"
233452
233672
  } : {
233453
233673
  "/help": "Display detailed help and commands reference",
@@ -233473,7 +233693,7 @@ var FullscreenTui = class {
233473
233693
  "/mode": "Switch permission mode (strict, normal, auto, plan)",
233474
233694
  "/copy": "Copy last assistant response to clipboard",
233475
233695
  "/run": "Run one local shell command after permission checks",
233476
- "/update": "Detect and update current project dependencies",
233696
+ "/update": "Check and update Orbit from npm",
233477
233697
  "/webui": "Start and open the Orbit graphical console"
233478
233698
  };
233479
233699
  const maxVisible = 5;
@@ -233652,7 +233872,7 @@ var FullscreenTui = class {
233652
233872
  const cleanModel = displayedModel.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
233653
233873
  const gitSummary = this.getGitSummary();
233654
233874
  const gitBranch = gitSummary.branch;
233655
- const heartColor = this.getNpmNeedsUpdate() ? `\x1B[5m\x1B[38;2;230;190;80m` : `\x1B[38;2;230;110;110m`;
233875
+ const heartColor = this.getOrbitUpdateAvailable() ? `\x1B[5m\x1B[38;2;230;190;80m` : `\x1B[38;2;230;110;110m`;
233656
233876
  const logoLines = [
233657
233877
  `\x1B[38;2;158;184;196m /\\___/\\ \x1B[0m`,
233658
233878
  `\x1B[38;2;158;184;196m ( o.o ) \x1B[0m`,
@@ -234068,9 +234288,9 @@ var FullscreenTui = class {
234068
234288
  };
234069
234289
 
234070
234290
  // src/runtime/ReplController.ts
234071
- import picocolors18 from "picocolors";
234291
+ import picocolors19 from "picocolors";
234072
234292
  import {
234073
- existsSync as existsSync28,
234293
+ existsSync as existsSync21,
234074
234294
  mkdirSync as mkdirSync13,
234075
234295
  readFileSync as readFileSync18,
234076
234296
  renameSync as renameSync8,
@@ -234082,23 +234302,21 @@ import { dirname as dirname9, resolve as resolve10 } from "path";
234082
234302
  import { homedir as homedir10 } from "os";
234083
234303
  import http2 from "http";
234084
234304
  import { randomBytes as randomBytes2, randomUUID as randomUUID8, timingSafeEqual as timingSafeEqual2 } from "crypto";
234085
- import { z as z41 } from "zod";
234305
+ import { z as z46 } from "zod";
234086
234306
 
234087
234307
  // src/runtime/CommandRouter.ts
234088
- import picocolors17 from "picocolors";
234089
- import { existsSync as existsSync21 } from "fs";
234090
- import { join as join17 } from "path";
234308
+ import picocolors18 from "picocolors";
234091
234309
 
234092
234310
  // src/commands/customCommands.ts
234093
234311
  import { existsSync as existsSync16, readFileSync as readFileSync16, readdirSync as readdirSync5 } from "fs";
234094
234312
  import { basename as basename5, extname, join as join15 } from "path";
234095
234313
  import { homedir as homedir8 } from "os";
234096
234314
  import { parse as parse3 } from "yaml";
234097
- import { z as z30 } from "zod";
234098
- var CommandMetadataSchema = z30.object({
234099
- description: z30.string().max(240).optional(),
234100
- argumentHint: z30.string().max(120).optional(),
234101
- "argument-hint": z30.string().max(120).optional()
234315
+ import { z as z31 } from "zod";
234316
+ var CommandMetadataSchema = z31.object({
234317
+ description: z31.string().max(240).optional(),
234318
+ argumentHint: z31.string().max(120).optional(),
234319
+ "argument-hint": z31.string().max(120).optional()
234102
234320
  });
234103
234321
  var VALID_COMMAND_NAME = /^[a-z0-9][a-z0-9-_]{0,47}$/i;
234104
234322
  var MAX_COMMAND_FILE_BYTES = 256 * 1024;
@@ -234244,20 +234462,20 @@ import { spawn as spawn2 } from "child_process";
234244
234462
  // src/runtime/webui/WebUiRuntime.ts
234245
234463
  import http from "http";
234246
234464
  import { randomBytes, randomUUID as randomUUID6 } from "crypto";
234247
- import { z as z36 } from "zod";
234465
+ import { z as z37 } from "zod";
234248
234466
 
234249
234467
  // src/runtime/AutocompleteCandidates.ts
234250
234468
  import glob6 from "fast-glob";
234251
234469
  import { existsSync as existsSync17, readFileSync as readFileSync17, readdirSync as readdirSync6 } from "fs";
234252
234470
  import { homedir as homedir9 } from "os";
234253
234471
  import { dirname as dirname8, join as join16, resolve as resolve7 } from "path";
234254
- import { z as z31 } from "zod";
234255
- var symbolIndexSchema = z31.object({
234256
- files: z31.record(
234257
- z31.object({
234258
- symbols: z31.array(
234259
- z31.object({
234260
- name: z31.string().min(1)
234472
+ import { z as z35 } from "zod";
234473
+ var symbolIndexSchema = z35.object({
234474
+ files: z35.record(
234475
+ z35.object({
234476
+ symbols: z35.array(
234477
+ z35.object({
234478
+ name: z35.string().min(1)
234261
234479
  })
234262
234480
  ).optional()
234263
234481
  })
@@ -237748,7 +237966,7 @@ var WEB_UI_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4
237748
237966
 
237749
237967
  // src/runtime/webui/WebUiSecurity.ts
237750
237968
  import { timingSafeEqual } from "crypto";
237751
- import { z as z35 } from "zod";
237969
+ import { z as z36 } from "zod";
237752
237970
  function sanitizeWebEventPayload(type, payload) {
237753
237971
  if (!isRecord3(payload)) return void 0;
237754
237972
  switch (type) {
@@ -237941,7 +238159,7 @@ function sanitizeBaseUrl(value) {
237941
238159
  }
237942
238160
  }
237943
238161
  function webRequestErrorStatus(error) {
237944
- if (error instanceof z35.ZodError) return 400;
238162
+ if (error instanceof z36.ZodError) return 400;
237945
238163
  if (error instanceof Error && error.message === "Request body too large.") {
237946
238164
  return 413;
237947
238165
  }
@@ -238049,12 +238267,12 @@ function normalizeSafeWebUiPath(value) {
238049
238267
  }
238050
238268
  function completionFileScore(file, query) {
238051
238269
  const lower = file.toLocaleLowerCase();
238052
- const basename7 = lower.slice(lower.lastIndexOf("/") + 1);
238270
+ const basename8 = lower.slice(lower.lastIndexOf("/") + 1);
238053
238271
  const depth = file.split("/").length - 1;
238054
238272
  if (!query) return depth * 100 + file.length;
238055
- if (basename7 === query) return 0;
238056
- if (basename7.startsWith(query)) return 100 + depth * 4 + file.length;
238057
- if (basename7.includes(query)) return 200 + depth * 4 + file.length;
238273
+ if (basename8 === query) return 0;
238274
+ if (basename8.startsWith(query)) return 100 + depth * 4 + file.length;
238275
+ if (basename8.includes(query)) return 200 + depth * 4 + file.length;
238058
238276
  if (lower.startsWith(query)) return 300 + depth * 4 + file.length;
238059
238277
  return 400 + lower.indexOf(query) + depth * 4 + file.length;
238060
238278
  }
@@ -244008,45 +244226,45 @@ var WEB_UI_STYLE_SECTIONS = [
244008
244226
  var WEB_UI_STYLES = WEB_UI_STYLE_SECTIONS.join("");
244009
244227
 
244010
244228
  // src/runtime/webui/WebUiRuntime.ts
244011
- var WebTurnIdSchema = z36.string().trim().min(8).max(100).regex(/^[a-zA-Z0-9_-]+$/);
244012
- var ChatRequestSchema = z36.object({
244013
- prompt: z36.string().trim().min(1).max(1e5),
244229
+ var WebTurnIdSchema = z37.string().trim().min(8).max(100).regex(/^[a-zA-Z0-9_-]+$/);
244230
+ var ChatRequestSchema = z37.object({
244231
+ prompt: z37.string().trim().min(1).max(1e5),
244014
244232
  turnId: WebTurnIdSchema.optional()
244015
244233
  }).strict();
244016
- var CancelRequestSchema = z36.object({ turnId: WebTurnIdSchema.nullish() }).strict();
244017
- var ApprovalDecisionSchema = z36.object({
244234
+ var CancelRequestSchema = z37.object({ turnId: WebTurnIdSchema.nullish() }).strict();
244235
+ var ApprovalDecisionSchema = z37.object({
244018
244236
  id: WebTurnIdSchema,
244019
- approved: z36.boolean()
244237
+ approved: z37.boolean()
244020
244238
  }).strict();
244021
- var SettingsPatchSchema = z36.object({
244022
- provider: z36.string().trim().min(1).max(256).optional(),
244023
- model: z36.string().trim().min(1).max(200).optional(),
244024
- permissionMode: z36.enum(["strict", "normal", "auto", "plan"]).optional(),
244025
- webSearchEnabled: z36.boolean().optional(),
244026
- webSearchProvider: z36.enum(["auto", "searxng", "tavily", "bing", "duckduckgo"]).optional(),
244027
- webSearchMaxResults: z36.number().int().min(1).max(20).optional()
244239
+ var SettingsPatchSchema = z37.object({
244240
+ provider: z37.string().trim().min(1).max(256).optional(),
244241
+ model: z37.string().trim().min(1).max(200).optional(),
244242
+ permissionMode: z37.enum(["strict", "normal", "auto", "plan"]).optional(),
244243
+ webSearchEnabled: z37.boolean().optional(),
244244
+ webSearchProvider: z37.enum(["auto", "searxng", "tavily", "bing", "duckduckgo"]).optional(),
244245
+ webSearchMaxResults: z37.number().int().min(1).max(20).optional()
244028
244246
  }).strict();
244029
- var SessionActionSchema = z36.discriminatedUnion("action", [
244030
- z36.object({ action: z36.literal("new") }).strict(),
244247
+ var SessionActionSchema = z37.discriminatedUnion("action", [
244248
+ z37.object({ action: z37.literal("new") }).strict(),
244031
244249
  ...["resume", "archive", "restore", "delete"].map(
244032
- (action) => z36.object({
244033
- action: z36.literal(action),
244034
- sessionId: z36.string().trim().min(1).max(200).regex(/^[a-zA-Z0-9_-]+$/)
244250
+ (action) => z37.object({
244251
+ action: z37.literal(action),
244252
+ sessionId: z37.string().trim().min(1).max(200).regex(/^[a-zA-Z0-9_-]+$/)
244035
244253
  }).strict()
244036
244254
  )
244037
244255
  ]);
244038
- var ProjectActionSchema = z36.discriminatedUnion("action", [
244039
- z36.object({ action: z36.literal("pick") }).strict(),
244040
- z36.object({
244041
- action: z36.enum(["open", "create"]),
244042
- path: z36.string().trim().min(1).max(4096)
244256
+ var ProjectActionSchema = z37.discriminatedUnion("action", [
244257
+ z37.object({ action: z37.literal("pick") }).strict(),
244258
+ z37.object({
244259
+ action: z37.enum(["open", "create"]),
244260
+ path: z37.string().trim().min(1).max(4096)
244043
244261
  }).strict(),
244044
- z36.object({
244045
- action: z36.literal("remove"),
244046
- projectId: z36.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9_-]+$/)
244262
+ z37.object({
244263
+ action: z37.literal("remove"),
244264
+ projectId: z37.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9_-]+$/)
244047
244265
  }).strict()
244048
244266
  ]);
244049
- var CompletionQuerySchema = z36.string().trim().max(200);
244267
+ var CompletionQuerySchema = z37.string().trim().max(200);
244050
244268
  function safeCall2(fn) {
244051
244269
  try {
244052
244270
  return fn();
@@ -244614,13 +244832,13 @@ var WebUiApprovalBroker = class {
244614
244832
  throw new Error("Another Web UI approval is already pending.");
244615
244833
  }
244616
244834
  const snapshot = sanitizeApprovalRequest(request);
244617
- return new Promise((resolve13) => {
244835
+ return new Promise((resolve15) => {
244618
244836
  const timeout = setTimeout(
244619
244837
  () => this.settle(false),
244620
244838
  WEB_APPROVAL_TIMEOUT_MS
244621
244839
  );
244622
244840
  timeout.unref();
244623
- this.pending = { snapshot, resolve: resolve13, timeout };
244841
+ this.pending = { snapshot, resolve: resolve15, timeout };
244624
244842
  eventBus.emitEvent("web_approval_requested", {
244625
244843
  approvalId: snapshot.id,
244626
244844
  kind: snapshot.kind,
@@ -245077,7 +245295,7 @@ async function handleWorkspaceConfigCommand(configArgument, dependencies) {
245077
245295
 
245078
245296
  // src/runtime/commands/ContextCommandHandler.ts
245079
245297
  import glob7 from "fast-glob";
245080
- import { existsSync as existsSync18, statSync as statSync6 } from "fs";
245298
+ import { existsSync as existsSync18, statSync as statSync5 } from "fs";
245081
245299
  import { isAbsolute as isAbsolute5, relative as relative3, resolve as resolve8 } from "path";
245082
245300
  import picocolors12 from "picocolors";
245083
245301
  function parseAddArgument(argument) {
@@ -245265,7 +245483,7 @@ ${matched.map((file) => ` \u2022 ${file}`).join("\n")}`
245265
245483
  }
245266
245484
  const relativePath = toWorkspaceRelative(cwd, absolutePath);
245267
245485
  try {
245268
- if (statSync6(absolutePath).isDirectory()) {
245486
+ if (statSync5(absolutePath).isDirectory()) {
245269
245487
  const files = await glob7("**/*", {
245270
245488
  cwd: absolutePath,
245271
245489
  onlyFiles: true,
@@ -245429,20 +245647,20 @@ async function handleContextCommand(command, argument, dependencies) {
245429
245647
  }
245430
245648
 
245431
245649
  // src/runtime/commands/RollbackCommandHandler.ts
245432
- import { execFileSync as execFileSync3 } from "child_process";
245650
+ import { execFileSync as execFileSync5 } from "child_process";
245433
245651
  import { existsSync as existsSync19, rmSync as rmSync5 } from "fs";
245434
245652
  import picocolors13 from "picocolors";
245435
- import { z as z37 } from "zod";
245436
- var GitStatusCodeSchema = z37.string().length(2).regex(/^[ MADRCU?!]{2}$/);
245437
- var GitStatusPathSchema = z37.string().min(1).max(32768);
245653
+ import { z as z38 } from "zod";
245654
+ var GitStatusCodeSchema = z38.string().length(2).regex(/^[ MADRCU?!]{2}$/);
245655
+ var GitStatusPathSchema = z38.string().min(1).max(32768);
245438
245656
  var defaultGitAdapter = {
245439
- status: (cwd) => execFileSync3("git", ["status", "--porcelain=v1", "-z"], {
245657
+ status: (cwd) => execFileSync5("git", ["status", "--porcelain=v1", "-z"], {
245440
245658
  cwd,
245441
245659
  encoding: "utf8",
245442
245660
  stdio: ["ignore", "pipe", "ignore"]
245443
245661
  }),
245444
245662
  checkout: (cwd, filePath) => {
245445
- execFileSync3("git", ["checkout", "--", filePath], {
245663
+ execFileSync5("git", ["checkout", "--", filePath], {
245446
245664
  cwd,
245447
245665
  stdio: "ignore"
245448
245666
  });
@@ -245865,32 +246083,32 @@ function ensureSessionTitle(loop, prompt) {
245865
246083
  }
245866
246084
 
245867
246085
  // src/runtime/ModelDiscovery.ts
245868
- import { z as z38 } from "zod";
245869
- var ModelEntrySchema = z38.object({
245870
- id: z38.unknown().optional(),
245871
- model: z38.unknown().optional(),
245872
- context_length: z38.unknown().optional(),
245873
- context_window: z38.unknown().optional(),
245874
- max_context_tokens: z38.unknown().optional(),
245875
- max_output_tokens: z38.unknown().optional(),
245876
- input_modalities: z38.unknown().optional(),
245877
- output_modalities: z38.unknown().optional(),
245878
- modalities: z38.unknown().optional(),
245879
- architecture: z38.unknown().optional(),
245880
- capabilities: z38.unknown().optional(),
245881
- supported_parameters: z38.unknown().optional(),
245882
- type: z38.unknown().optional(),
245883
- kind: z38.unknown().optional(),
245884
- task: z38.unknown().optional(),
245885
- endpoint: z38.unknown().optional(),
245886
- details: z38.unknown().optional()
246086
+ import { z as z39 } from "zod";
246087
+ var ModelEntrySchema = z39.object({
246088
+ id: z39.unknown().optional(),
246089
+ model: z39.unknown().optional(),
246090
+ context_length: z39.unknown().optional(),
246091
+ context_window: z39.unknown().optional(),
246092
+ max_context_tokens: z39.unknown().optional(),
246093
+ max_output_tokens: z39.unknown().optional(),
246094
+ input_modalities: z39.unknown().optional(),
246095
+ output_modalities: z39.unknown().optional(),
246096
+ modalities: z39.unknown().optional(),
246097
+ architecture: z39.unknown().optional(),
246098
+ capabilities: z39.unknown().optional(),
246099
+ supported_parameters: z39.unknown().optional(),
246100
+ type: z39.unknown().optional(),
246101
+ kind: z39.unknown().optional(),
246102
+ task: z39.unknown().optional(),
246103
+ endpoint: z39.unknown().optional(),
246104
+ details: z39.unknown().optional()
245887
246105
  }).passthrough();
245888
- var ModelListSchema = z38.union([
245889
- z38.object({ data: z38.array(ModelEntrySchema).max(1e3) }),
245890
- z38.object({ models: z38.array(ModelEntrySchema).max(1e3) }),
245891
- z38.array(ModelEntrySchema).max(1e3)
246106
+ var ModelListSchema = z39.union([
246107
+ z39.object({ data: z39.array(ModelEntrySchema).max(1e3) }),
246108
+ z39.object({ models: z39.array(ModelEntrySchema).max(1e3) }),
246109
+ z39.array(ModelEntrySchema).max(1e3)
245892
246110
  ]);
245893
- var DiscoveryUrlSchema = z38.string().url().max(4096).transform((value) => new URL(value));
246111
+ var DiscoveryUrlSchema = z39.string().url().max(4096).transform((value) => new URL(value));
245894
246112
  var MAX_MODEL_RESPONSE_BYTES = 2 * 1024 * 1024;
245895
246113
  async function discoverProviderModels(options) {
245896
246114
  const base = DiscoveryUrlSchema.parse(options.baseUrl.trim());
@@ -246057,9 +246275,9 @@ function normalizeModelEntries(entries) {
246057
246275
  }
246058
246276
  return { models, modelCapabilities };
246059
246277
  }
246060
- var OllamaShowSchema = z38.object({
246061
- capabilities: z38.array(z38.string().max(128)).max(64).optional(),
246062
- model_info: z38.record(z38.unknown()).optional()
246278
+ var OllamaShowSchema = z39.object({
246279
+ capabilities: z39.array(z39.string().max(128)).max(64).optional(),
246280
+ model_info: z39.record(z39.unknown()).optional()
246063
246281
  }).passthrough();
246064
246282
  async function enrichOllamaCapabilities(base, models, target, fetchImpl, signal) {
246065
246283
  const endpoint = new URL(base);
@@ -246197,7 +246415,7 @@ function copyBooleanCapability(source, sourceKey, target, targetKey) {
246197
246415
 
246198
246416
  // src/runtime/ProjectLauncher.ts
246199
246417
  import { spawn as spawn3 } from "child_process";
246200
- import { existsSync as existsSync20, mkdirSync as mkdirSync12, realpathSync as realpathSync3, statSync as statSync7 } from "fs";
246418
+ import { existsSync as existsSync20, mkdirSync as mkdirSync12, realpathSync as realpathSync3, statSync as statSync6 } from "fs";
246201
246419
  import { isAbsolute as isAbsolute6, parse as parse4, resolve as resolve9 } from "path";
246202
246420
  function launchOrbitProject(request, options = {}) {
246203
246421
  if (!isAbsolute6(request.path)) {
@@ -246213,7 +246431,7 @@ function launchOrbitProject(request, options = {}) {
246213
246431
  }
246214
246432
  mkdirSync12(requestedPath, { recursive: true });
246215
246433
  }
246216
- if (!statSync7(requestedPath).isDirectory()) {
246434
+ if (!statSync6(requestedPath).isDirectory()) {
246217
246435
  throw new Error("Project path must point to a directory.");
246218
246436
  }
246219
246437
  const projectPath = realpathSync3(requestedPath);
@@ -246238,9 +246456,9 @@ function launchOrbitProject(request, options = {}) {
246238
246456
  }
246239
246457
 
246240
246458
  // src/runtime/ProjectFolderPicker.ts
246241
- import { execFile as execFile4 } from "child_process";
246459
+ import { execFile as execFile5 } from "child_process";
246242
246460
  import { promisify as promisify4 } from "util";
246243
- var execFileAsync = promisify4(execFile4);
246461
+ var execFileAsync = promisify4(execFile5);
246244
246462
  async function selectOrbitProjectFolder(options = {}) {
246245
246463
  const platform = options.platform ?? process.platform;
246246
246464
  const run = options.run ?? (async (executable, args) => execFileAsync(executable, args, {
@@ -246306,9 +246524,9 @@ function isPickerCancellation(error) {
246306
246524
 
246307
246525
  // src/runtime/commands/SessionMetadataCommandHandler.ts
246308
246526
  import picocolors15 from "picocolors";
246309
- import { z as z39 } from "zod";
246310
- var GoalSchema = z39.string().trim().min(1).max(4e3);
246311
- var SessionTitleSchema = z39.string().trim().min(1).max(160);
246527
+ import { z as z40 } from "zod";
246528
+ var GoalSchema = z40.string().trim().min(1).max(4e3);
246529
+ var SessionTitleSchema = z40.string().trim().min(1).max(160);
246312
246530
  function handleSessionMetadataCommand(command, argument, dependencies) {
246313
246531
  if (command === "/goal") {
246314
246532
  handleGoal(argument, dependencies);
@@ -246373,9 +246591,9 @@ function handleRename(argument, { loop, isZh, printOutput }) {
246373
246591
 
246374
246592
  // src/runtime/commands/WorkspaceStateCommandHandler.ts
246375
246593
  import picocolors16 from "picocolors";
246376
- import { z as z40 } from "zod";
246377
- var TextSchema = z40.string().trim().min(1).max(2e3);
246378
- var ItemReferenceSchema = z40.string().trim().min(1).max(100);
246594
+ import { z as z41 } from "zod";
246595
+ var TextSchema = z41.string().trim().min(1).max(2e3);
246596
+ var ItemReferenceSchema = z41.string().trim().min(1).max(100);
246379
246597
  function handleWorkspaceStateCommand(command, argument, dependencies) {
246380
246598
  if (command === "/memory") {
246381
246599
  handleMemory(argument, dependencies);
@@ -246548,13 +246766,90 @@ function resolveItemId(reference, items) {
246548
246766
  return items.find((item) => item.id === parsed.data)?.id;
246549
246767
  }
246550
246768
 
246769
+ // src/commands/update.ts
246770
+ import readline4 from "readline";
246771
+ import picocolors17 from "picocolors";
246772
+ import { z as z45 } from "zod";
246773
+ var UpdateCommandOptionsSchema = z45.object({
246774
+ check: z45.boolean().default(false),
246775
+ yes: z45.boolean().default(false),
246776
+ json: z45.boolean().default(false)
246777
+ }).strict();
246778
+ async function runUpdate(currentVersion, rawOptions, dependencies = {}) {
246779
+ const options = UpdateCommandOptionsSchema.parse(rawOptions);
246780
+ const manager = dependencies.manager ?? new UpdateManager();
246781
+ const write = dependencies.write ?? ((text) => console.log(text));
246782
+ const check = manager.check(currentVersion);
246783
+ if (!check.updateAvailable) {
246784
+ const result2 = { check, installed: false };
246785
+ write(
246786
+ options.json ? JSON.stringify({ schemaVersion: 1, ...result2 }) : picocolors17.green(
246787
+ `\u2714 Orbit ${check.currentVersion} is already up to date.`
246788
+ )
246789
+ );
246790
+ return result2;
246791
+ }
246792
+ if (options.check || options.json && !options.yes) {
246793
+ const result2 = { check, installed: false };
246794
+ write(
246795
+ options.json ? JSON.stringify({ schemaVersion: 1, ...result2 }) : `${picocolors17.yellow("\u25CF Update available:")} ${check.currentVersion} \u2192 ${check.latestVersion}
246796
+ Run ${picocolors17.cyan("orbit update --yes")} to install it.`
246797
+ );
246798
+ return result2;
246799
+ }
246800
+ let confirmed = options.yes;
246801
+ if (!confirmed) {
246802
+ const interactive = dependencies.interactive ?? Boolean(process.stdin.isTTY);
246803
+ if (!interactive) {
246804
+ throw new Error(
246805
+ "Updating requires an interactive confirmation or the explicit --yes flag."
246806
+ );
246807
+ }
246808
+ const confirm = dependencies.confirm ?? confirmUpdate;
246809
+ confirmed = await confirm(
246810
+ `Update Orbit ${check.currentVersion} \u2192 ${check.latestVersion}? [y/N] `
246811
+ );
246812
+ }
246813
+ if (!confirmed) {
246814
+ write(picocolors17.yellow("\u26A0 Update cancelled."));
246815
+ return { check, installed: false };
246816
+ }
246817
+ dependencies.beforeInstall?.();
246818
+ try {
246819
+ manager.install(check.latestVersion, !options.json);
246820
+ } finally {
246821
+ dependencies.afterInstall?.();
246822
+ }
246823
+ const result = { check, installed: true };
246824
+ write(
246825
+ options.json ? JSON.stringify({ schemaVersion: 1, ...result }) : picocolors17.green(
246826
+ `\u2714 Orbit ${check.latestVersion} installed. Restart Orbit to use the new version.`
246827
+ )
246828
+ );
246829
+ return result;
246830
+ }
246831
+ async function confirmUpdate(prompt) {
246832
+ const interfaceInstance = readline4.createInterface({
246833
+ input: process.stdin,
246834
+ output: process.stdout
246835
+ });
246836
+ try {
246837
+ const answer = await new Promise(
246838
+ (resolve15) => interfaceInstance.question(prompt, resolve15)
246839
+ );
246840
+ return /^(?:y|yes)$/i.test(answer.trim());
246841
+ } finally {
246842
+ interfaceInstance.close();
246843
+ }
246844
+ }
246845
+
246551
246846
  // src/runtime/CommandRouter.ts
246552
246847
  var require2 = createRequire2(import.meta.url);
246553
246848
  function stripAnsi4(value) {
246554
246849
  return value.replace(/\u001b\[[0-9;]*m/g, "");
246555
246850
  }
246556
246851
  var CommandRouter = class {
246557
- constructor(cwd, config, providerInstance, setProviderInstance, loop, tui, useFullscreenTui, getCandidates, setCandidates, getLocalState2, saveLocalState, tuiInteraction, multi) {
246852
+ constructor(cwd, config, providerInstance, setProviderInstance, loop, tui, useFullscreenTui, getCandidates, setCandidates, getLocalState2, saveLocalState, tuiInteraction, multi, updateOrbit = runUpdate) {
246558
246853
  this.cwd = cwd;
246559
246854
  this.config = config;
246560
246855
  this.providerInstance = providerInstance;
@@ -246568,6 +246863,7 @@ var CommandRouter = class {
246568
246863
  this.saveLocalState = saveLocalState;
246569
246864
  this.tuiInteraction = tuiInteraction;
246570
246865
  this.multi = multi;
246866
+ this.updateOrbit = updateOrbit;
246571
246867
  }
246572
246868
  cwd;
246573
246869
  config;
@@ -246582,6 +246878,7 @@ var CommandRouter = class {
246582
246878
  saveLocalState;
246583
246879
  tuiInteraction;
246584
246880
  multi;
246881
+ updateOrbit;
246585
246882
  runCoordinator = new RunCoordinator();
246586
246883
  webApprovalBroker = new WebUiApprovalBroker();
246587
246884
  webUiRunnable = null;
@@ -246674,7 +246971,7 @@ var CommandRouter = class {
246674
246971
  }
246675
246972
  if (command === "/exit" || command === "/quit") {
246676
246973
  this.printOutput(
246677
- picocolors17.yellow("Exiting Orbit Interactive Shell. Goodbye!")
246974
+ picocolors18.yellow("Exiting Orbit Interactive Shell. Goodbye!")
246678
246975
  );
246679
246976
  return { shouldExit: true, processed: true };
246680
246977
  }
@@ -246730,12 +247027,12 @@ var CommandRouter = class {
246730
247027
  const displayUrl = new URL(handle.url);
246731
247028
  displayUrl.hash = "";
246732
247029
  this.printOutput(
246733
- isZh ? picocolors17.green(`\u2714 Orbit Web UI \u5DF2\u542F\u52A8: ${displayUrl.href}`) : picocolors17.green(`\u2714 Orbit Web UI running: ${displayUrl.href}`)
247030
+ isZh ? picocolors18.green(`\u2714 Orbit Web UI \u5DF2\u542F\u52A8: ${displayUrl.href}`) : picocolors18.green(`\u2714 Orbit Web UI running: ${displayUrl.href}`)
246734
247031
  );
246735
247032
  } catch (error) {
246736
247033
  const message = error instanceof Error ? error.message : String(error);
246737
247034
  this.printOutput(
246738
- isZh ? picocolors17.red(`\u2716 \u65E0\u6CD5\u542F\u52A8 Orbit Web UI: ${message}`) : picocolors17.red(`\u2716 Failed to start Orbit Web UI: ${message}`)
247035
+ isZh ? picocolors18.red(`\u2716 \u65E0\u6CD5\u542F\u52A8 Orbit Web UI: ${message}`) : picocolors18.red(`\u2716 Failed to start Orbit Web UI: ${message}`)
246739
247036
  );
246740
247037
  }
246741
247038
  return { shouldExit: false, processed: true };
@@ -246743,53 +247040,32 @@ var CommandRouter = class {
246743
247040
  if (command === "/update") {
246744
247041
  const isZh = config.language === "zh";
246745
247042
  const wasActive = useFullscreenTui && tui.isActive;
246746
- const packageJsonPath = join17(cwd, "package.json");
246747
- if (!existsSync21(packageJsonPath)) {
247043
+ const requestedFromWebUi = this.runCoordinator.isActive("web");
247044
+ try {
247045
+ const updateResult = await this.updateOrbit(
247046
+ readCliVersion(),
247047
+ { check: requestedFromWebUi },
247048
+ {
247049
+ interactive: true,
247050
+ confirm: (prompt) => Prompt.askApproval(prompt),
247051
+ write: (text) => this.printOutput(text),
247052
+ beforeInstall: () => {
247053
+ if (wasActive) tui.stop();
247054
+ },
247055
+ afterInstall: () => {
247056
+ tui.syncFromLoop(loop);
247057
+ if (wasActive) tui.start(config.budgetLimit);
247058
+ }
247059
+ }
247060
+ );
247061
+ tui.setOrbitUpdateAvailable?.(
247062
+ updateResult.installed ? false : updateResult.check.updateAvailable
247063
+ );
247064
+ } catch (error) {
247065
+ const message = error instanceof Error ? error.message : String(error);
246748
247066
  this.printOutput(
246749
- isZh ? picocolors17.yellow(
246750
- "\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u68C0\u6D4B\u5230 package.json\uFF0C\u4E0D\u652F\u6301 npm \u66F4\u65B0\u3002"
246751
- ) : picocolors17.yellow(
246752
- "No package.json found in the workspace. npm update not supported."
246753
- )
247067
+ isZh ? picocolors18.red(`\u2716 Orbit \u66F4\u65B0\u5931\u8D25: ${message}`) : picocolors18.red(`\u2716 Orbit update failed: ${message}`)
246754
247068
  );
246755
- return { shouldExit: false, processed: true };
246756
- }
246757
- let installCmd = "npm install";
246758
- if (existsSync21(join17(cwd, "pnpm-lock.yaml"))) {
246759
- installCmd = "pnpm install";
246760
- } else if (existsSync21(join17(cwd, "yarn.lock"))) {
246761
- installCmd = "yarn install";
246762
- } else if (existsSync21(join17(cwd, "bun.lockb"))) {
246763
- installCmd = "bun install";
246764
- }
246765
- if (wasActive) tui.stop();
246766
- try {
246767
- const approved = await Prompt.askApproval(
246768
- isZh ? `\u68C0\u6D4B\u5230\u9879\u76EE\u4F9D\u8D56\u9700\u8981\u66F4\u65B0\uFF0C\u662F\u5426\u8FD0\u884C "${installCmd}"\uFF1F` : `NPM dependencies need update. Run "${installCmd}"?`
246769
- );
246770
- if (approved) {
246771
- console.log(picocolors17.cyan(`
246772
- \u25CF Running "${installCmd}"...`));
246773
- const { execSync: execSync3 } = await import("child_process");
246774
- execSync3(installCmd, { cwd, stdio: "inherit" });
246775
- console.log(
246776
- picocolors17.green(`\u2714 Dependencies updated successfully.
246777
- `)
246778
- );
246779
- tui.npmNeedsUpdate = false;
246780
- tui.lastNpmCheckTime = Date.now();
246781
- } else {
246782
- console.log(picocolors17.yellow(`
246783
- \u2716 Update cancelled by user.
246784
- `));
246785
- }
246786
- } catch (err) {
246787
- console.log(picocolors17.red(`
246788
- \u2716 Update failed: ${err.message}
246789
- `));
246790
- } finally {
246791
- tui.syncFromLoop(loop);
246792
- if (wasActive) tui.start(config.budgetLimit);
246793
247069
  }
246794
247070
  return { shouldExit: false, processed: true };
246795
247071
  }
@@ -246811,42 +247087,42 @@ var CommandRouter = class {
246811
247087
  const costPct = budgetLimit > 0 ? Math.min(100, currentCost / budgetLimit * 100).toFixed(1) : "N/A";
246812
247088
  const barLen = 24;
246813
247089
  const filledLen = budgetLimit > 0 ? Math.round(currentCost / budgetLimit * barLen) : 0;
246814
- const bar = picocolors17.green("\u2588".repeat(filledLen)) + picocolors17.gray("\u2591".repeat(Math.max(0, barLen - filledLen)));
247090
+ const bar = picocolors18.green("\u2588".repeat(filledLen)) + picocolors18.gray("\u2591".repeat(Math.max(0, barLen - filledLen)));
246815
247091
  const statusLines = isZh ? [
246816
- picocolors17.bold("\u4F1A\u8BDD\u6982\u51B5"),
247092
+ picocolors18.bold("\u4F1A\u8BDD\u6982\u51B5"),
246817
247093
  "",
246818
- ` \u{1F194} ${picocolors17.gray("\u4F1A\u8BDD")} ${picocolors17.cyan(loop.getSessionId())}`,
246819
- ` \u{1F50C} ${picocolors17.gray("\u63D0\u4F9B\u5546")} ${picocolors17.cyan(this.providerInstance.id)}`,
246820
- ` \u{1F916} ${picocolors17.gray("\u5F53\u524D\u6A21\u578B")} ${picocolors17.cyan(activeModel2)}`,
246821
- ` \u21AF ${picocolors17.gray("\u6A21\u578B\u8DEF\u7531")} ${picocolors17.cyan(routingMode)}`,
246822
- ` \u{1F6E1}\uFE0F ${picocolors17.gray("\u6743\u9650\u6A21\u5F0F")} ${picocolors17.green(mode.toUpperCase())}`,
246823
- ` \u25EB ${picocolors17.gray("\u8BA1\u5212/\u8BB0\u5FC6")} ${picocolors17.cyan(`${plan?.items.length || 0} / ${memory?.entries.length || 0}`)}`,
247094
+ ` \u{1F194} ${picocolors18.gray("\u4F1A\u8BDD")} ${picocolors18.cyan(loop.getSessionId())}`,
247095
+ ` \u{1F50C} ${picocolors18.gray("\u63D0\u4F9B\u5546")} ${picocolors18.cyan(this.providerInstance.id)}`,
247096
+ ` \u{1F916} ${picocolors18.gray("\u5F53\u524D\u6A21\u578B")} ${picocolors18.cyan(activeModel2)}`,
247097
+ ` \u21AF ${picocolors18.gray("\u6A21\u578B\u8DEF\u7531")} ${picocolors18.cyan(routingMode)}`,
247098
+ ` \u{1F6E1}\uFE0F ${picocolors18.gray("\u6743\u9650\u6A21\u5F0F")} ${picocolors18.green(mode.toUpperCase())}`,
247099
+ ` \u25EB ${picocolors18.gray("\u8BA1\u5212/\u8BB0\u5FC6")} ${picocolors18.cyan(`${plan?.items.length || 0} / ${memory?.entries.length || 0}`)}`,
246824
247100
  ...loop.getGoal() ? [
246825
- ` \u{1F3AF} ${picocolors17.gray("\u804A\u5929\u76EE\u6807")} ${picocolors17.cyan(loop.getGoal() || "")}`
247101
+ ` \u{1F3AF} ${picocolors18.gray("\u804A\u5929\u76EE\u6807")} ${picocolors18.cyan(loop.getGoal() || "")}`
246826
247102
  ] : [],
246827
- ` \u{1F9E0} ${picocolors17.gray("\u4E0A\u4E0B\u6587")} ${picocolors17.cyan(`~${contextStatus.estimatedHistoryTokens.toLocaleString()}`)} / ${contextStatus.maxContextTokens.toLocaleString()} tokens\uFF08${contextPct}% \u81EA\u52A8\u538B\u7F29\u7EBF\uFF09`,
247103
+ ` \u{1F9E0} ${picocolors18.gray("\u4E0A\u4E0B\u6587")} ${picocolors18.cyan(`~${contextStatus.estimatedHistoryTokens.toLocaleString()}`)} / ${contextStatus.maxContextTokens.toLocaleString()} tokens\uFF08${contextPct}% \u81EA\u52A8\u538B\u7F29\u7EBF\uFF09`,
246828
247104
  "",
246829
- picocolors17.bold("\u8D39\u7528\u4E0E\u9884\u7B97"),
247105
+ picocolors18.bold("\u8D39\u7528\u4E0E\u9884\u7B97"),
246830
247106
  "",
246831
- ` \u{1F4B0} $${picocolors17.yellow(currentCost.toFixed(4))} / $${picocolors17.gray(budgetLimit.toFixed(2))} (${costPct}%)`,
247107
+ ` \u{1F4B0} $${picocolors18.yellow(currentCost.toFixed(4))} / $${picocolors18.gray(budgetLimit.toFixed(2))} (${costPct}%)`,
246832
247108
  ` ${bar}`
246833
247109
  ] : [
246834
- picocolors17.bold("Session Overview"),
247110
+ picocolors18.bold("Session Overview"),
246835
247111
  "",
246836
- ` \u{1F194} ${picocolors17.gray("Session ID")} ${picocolors17.cyan(loop.getSessionId())}`,
246837
- ` \u{1F50C} ${picocolors17.gray("Provider")} ${picocolors17.cyan(this.providerInstance.id)}`,
246838
- ` \u{1F916} ${picocolors17.gray("Active Model")} ${picocolors17.cyan(activeModel2)}`,
246839
- ` \u21AF ${picocolors17.gray("Model Routing")} ${picocolors17.cyan(routingMode)}`,
246840
- ` \u{1F6E1}\uFE0F ${picocolors17.gray("Security Mode")} ${picocolors17.green(mode.toUpperCase())}`,
246841
- ` \u25EB ${picocolors17.gray("Plan / Memory")} ${picocolors17.cyan(`${plan?.items.length || 0} / ${memory?.entries.length || 0}`)}`,
247112
+ ` \u{1F194} ${picocolors18.gray("Session ID")} ${picocolors18.cyan(loop.getSessionId())}`,
247113
+ ` \u{1F50C} ${picocolors18.gray("Provider")} ${picocolors18.cyan(this.providerInstance.id)}`,
247114
+ ` \u{1F916} ${picocolors18.gray("Active Model")} ${picocolors18.cyan(activeModel2)}`,
247115
+ ` \u21AF ${picocolors18.gray("Model Routing")} ${picocolors18.cyan(routingMode)}`,
247116
+ ` \u{1F6E1}\uFE0F ${picocolors18.gray("Security Mode")} ${picocolors18.green(mode.toUpperCase())}`,
247117
+ ` \u25EB ${picocolors18.gray("Plan / Memory")} ${picocolors18.cyan(`${plan?.items.length || 0} / ${memory?.entries.length || 0}`)}`,
246842
247118
  ...loop.getGoal() ? [
246843
- ` \u{1F3AF} ${picocolors17.gray("Chat Goal")} ${picocolors17.cyan(loop.getGoal() || "")}`
247119
+ ` \u{1F3AF} ${picocolors18.gray("Chat Goal")} ${picocolors18.cyan(loop.getGoal() || "")}`
246844
247120
  ] : [],
246845
- ` \u{1F9E0} ${picocolors17.gray("Context")} ${picocolors17.cyan(`~${contextStatus.estimatedHistoryTokens.toLocaleString()}`)} / ${contextStatus.maxContextTokens.toLocaleString()} tokens (${contextPct}% of auto-compact threshold)`,
247121
+ ` \u{1F9E0} ${picocolors18.gray("Context")} ${picocolors18.cyan(`~${contextStatus.estimatedHistoryTokens.toLocaleString()}`)} / ${contextStatus.maxContextTokens.toLocaleString()} tokens (${contextPct}% of auto-compact threshold)`,
246846
247122
  "",
246847
- picocolors17.bold("Budget & Cost"),
247123
+ picocolors18.bold("Budget & Cost"),
246848
247124
  "",
246849
- ` \u{1F4B0} $${picocolors17.yellow(currentCost.toFixed(4))} / $${picocolors17.gray(budgetLimit.toFixed(2))} (${costPct}%)`,
247125
+ ` \u{1F4B0} $${picocolors18.yellow(currentCost.toFixed(4))} / $${picocolors18.gray(budgetLimit.toFixed(2))} (${costPct}%)`,
246850
247126
  ` ${bar}`
246851
247127
  ];
246852
247128
  this.printOutput(statusLines.join("\n"));
@@ -246868,7 +247144,7 @@ var CommandRouter = class {
246868
247144
  const isZh = activeConfig.language === "zh";
246869
247145
  const announceModel = (model) => {
246870
247146
  this.printOutput(
246871
- `${picocolors17.green("\u2714")} ${isZh ? `\u5F53\u524D\u6A21\u578B\u5DF2\u5207\u6362\u4E3A\uFF1A${picocolors17.green(model)}` : `Active model: ${picocolors17.green(model)}`}`
247147
+ `${picocolors18.green("\u2714")} ${isZh ? `\u5F53\u524D\u6A21\u578B\u5DF2\u5207\u6362\u4E3A\uFF1A${picocolors18.green(model)}` : `Active model: ${picocolors18.green(model)}`}`
246872
247148
  );
246873
247149
  };
246874
247150
  if (!modelArg) {
@@ -246930,7 +247206,7 @@ var CommandRouter = class {
246930
247206
  "__auto__"
246931
247207
  );
246932
247208
  if (!switched.ok) {
246933
- this.printOutput(picocolors17.red(`\u2716 ${switched.message}`));
247209
+ this.printOutput(picocolors18.red(`\u2716 ${switched.message}`));
246934
247210
  return { shouldExit: false, processed: true };
246935
247211
  }
246936
247212
  } else {
@@ -246939,7 +247215,7 @@ var CommandRouter = class {
246939
247215
  this.saveLocalState({ lastModel: "" });
246940
247216
  }
246941
247217
  this.printOutput(
246942
- picocolors17.green(
247218
+ picocolors18.green(
246943
247219
  isZh ? "\u2714 \u5DF2\u542F\u7528\u81EA\u52A8\u6A21\u578B\u8DEF\u7531\u3002" : "\u2714 Automatic model routing enabled."
246944
247220
  )
246945
247221
  );
@@ -246958,7 +247234,7 @@ var CommandRouter = class {
246958
247234
  allowUnlistedModel: selectedModel === "custom"
246959
247235
  });
246960
247236
  if (!switched.ok) {
246961
- this.printOutput(picocolors17.red(`\u2716 ${switched.message}`));
247237
+ this.printOutput(picocolors18.red(`\u2716 ${switched.message}`));
246962
247238
  return { shouldExit: false, processed: true };
246963
247239
  }
246964
247240
  } else {
@@ -246973,7 +247249,7 @@ var CommandRouter = class {
246973
247249
  loop.clearModelOverride();
246974
247250
  this.tui.syncFromLoop(loop);
246975
247251
  this.printOutput(
246976
- picocolors17.green(
247252
+ picocolors18.green(
246977
247253
  isZh ? "\u2714 \u5DF2\u542F\u7528\u81EA\u52A8\u6A21\u578B\u8DEF\u7531\u3002" : "\u2714 Automatic model routing enabled."
246978
247254
  )
246979
247255
  );
@@ -246989,14 +247265,14 @@ var CommandRouter = class {
246989
247265
  if (command === "/commit") {
246990
247266
  const commitMsg = parts.slice(1).join(" ").trim();
246991
247267
  const isZh = config.language === "zh";
246992
- const { execFileSync: execFileSync5, execSync: execSync3 } = await import("child_process");
247268
+ const { execFileSync: execFileSync7, execSync: execSync3 } = await import("child_process");
246993
247269
  try {
246994
247270
  let diff = execSync3("git diff --cached", { cwd }).toString().trim();
246995
247271
  if (!diff) {
246996
247272
  const unstaged = execSync3("git status --porcelain", { cwd }).toString().trim();
246997
247273
  if (!unstaged) {
246998
247274
  this.printOutput(
246999
- picocolors17.yellow(
247275
+ picocolors18.yellow(
247000
247276
  isZh ? "\u5DE5\u4F5C\u533A\u5E72\u51C0\uFF0C\u6CA1\u6709\u68C0\u6D4B\u5230\u4EFB\u4F55\u5DF2\u6682\u5B58\u6216\u672A\u6682\u5B58\u7684\u66F4\u6539\u3002" : "Workspace clean. No staged or unstaged changes found to commit."
247001
247277
  )
247002
247278
  );
@@ -247007,7 +247283,7 @@ var CommandRouter = class {
247007
247283
  );
247008
247284
  if (!autoStage) {
247009
247285
  this.printOutput(
247010
- picocolors17.yellow(
247286
+ picocolors18.yellow(
247011
247287
  isZh ? "\u64CD\u4F5C\u5DF2\u53D6\u6D88\u3002\u8BF7\u5148\u8FD0\u884C 'git add' \u6682\u5B58\u4F60\u7684\u4FEE\u6539\u3002" : "Operation cancelled. Please run 'git add' to stage your changes first."
247012
247288
  )
247013
247289
  );
@@ -247020,7 +247296,7 @@ var CommandRouter = class {
247020
247296
  diff = execSync3("git diff --cached", { cwd }).toString().trim();
247021
247297
  if (!diff) {
247022
247298
  this.printOutput(
247023
- picocolors17.red(
247299
+ picocolors18.red(
247024
247300
  isZh ? "\u2716 \u6682\u5B58\u5931\u8D25\u6216\u6682\u5B58\u540E\u4ECD\u65E0\u53D8\u66F4\u3002" : "\u2716 Staging failed or resulted in no diff."
247025
247301
  )
247026
247302
  );
@@ -247062,14 +247338,14 @@ ${diff.substring(0, 2e4)}`
247062
247338
  }
247063
247339
  }
247064
247340
  this.printOutput(
247065
- `Committing changes with message: "${picocolors17.green(finalMsg)}"`
247341
+ `Committing changes with message: "${picocolors18.green(finalMsg)}"`
247066
247342
  );
247067
- execFileSync5("git", ["commit", "-m", finalMsg], { cwd });
247343
+ execFileSync7("git", ["commit", "-m", finalMsg], { cwd });
247068
247344
  this.printOutput(
247069
- picocolors17.green("\u2714 Git commit created successfully.")
247345
+ picocolors18.green("\u2714 Git commit created successfully.")
247070
247346
  );
247071
247347
  } catch (err) {
247072
- this.printOutput(picocolors17.red(`\u2716 Commit failed: ${err.message}`));
247348
+ this.printOutput(picocolors18.red(`\u2716 Commit failed: ${err.message}`));
247073
247349
  }
247074
247350
  return { shouldExit: false, processed: true };
247075
247351
  }
@@ -247105,9 +247381,9 @@ ${diff.substring(0, 2e4)}`
247105
247381
  };
247106
247382
  if (!targetMode) {
247107
247383
  if (useFullscreenTui && tui.isActive) {
247108
- const question = isZh ? `\u5F53\u524D\u6A21\u5F0F: ${picocolors17.cyan(currentMode.toUpperCase())}
247384
+ const question = isZh ? `\u5F53\u524D\u6A21\u5F0F: ${picocolors18.cyan(currentMode.toUpperCase())}
247109
247385
 
247110
- \u9009\u62E9\u65B0\u7684\u5B89\u5168\u6A21\u5F0F:` : `Current mode: ${picocolors17.cyan(currentMode.toUpperCase())}
247386
+ \u9009\u62E9\u65B0\u7684\u5B89\u5168\u6A21\u5F0F:` : `Current mode: ${picocolors18.cyan(currentMode.toUpperCase())}
247111
247387
 
247112
247388
  Select a security mode:`;
247113
247389
  const choice = await Prompt.askSelect(question, [
@@ -247122,7 +247398,7 @@ Select a security mode:`;
247122
247398
  }
247123
247399
  } else {
247124
247400
  this.printOutput(
247125
- isZh ? picocolors17.yellow("\u7528\u6CD5: /mode <strict|normal|auto|plan>") : picocolors17.yellow("Usage: /mode <strict|normal|auto|plan>")
247401
+ isZh ? picocolors18.yellow("\u7528\u6CD5: /mode <strict|normal|auto|plan>") : picocolors18.yellow("Usage: /mode <strict|normal|auto|plan>")
247126
247402
  );
247127
247403
  }
247128
247404
  return { shouldExit: false, processed: true };
@@ -247130,9 +247406,9 @@ Select a security mode:`;
247130
247406
  const validModes = ["strict", "normal", "auto", "plan"];
247131
247407
  if (!validModes.includes(targetMode)) {
247132
247408
  this.printOutput(
247133
- isZh ? picocolors17.red(
247409
+ isZh ? picocolors18.red(
247134
247410
  `\u2716 \u65E0\u6548\u7684\u5B89\u5168\u6A21\u5F0F: ${targetMode}\u3002\u53EF\u9009\u6A21\u5F0F: ${validModes.join(", ")}`
247135
- ) : picocolors17.red(
247411
+ ) : picocolors18.red(
247136
247412
  `\u2716 Invalid security mode: ${targetMode}. Valid modes: ${validModes.join(", ")}`
247137
247413
  )
247138
247414
  );
@@ -247141,19 +247417,19 @@ Select a security mode:`;
247141
247417
  loop.getConfig().permissions.mode = targetMode;
247142
247418
  tui.syncFromLoop(loop);
247143
247419
  if (useFullscreenTui && tui.isActive) {
247144
- const msg = isZh ? `\u5F53\u524D\u6A21\u5F0F: ${picocolors17.cyan(currentMode.toUpperCase())}
247420
+ const msg = isZh ? `\u5F53\u524D\u6A21\u5F0F: ${picocolors18.cyan(currentMode.toUpperCase())}
247145
247421
 
247146
- ${picocolors17.green("\u2714")} \u5DF2\u5207\u6362\u5B89\u5168\u6A21\u5F0F\u81F3: ${picocolors17.green(targetMode.toUpperCase())}` : `Previous mode: ${picocolors17.cyan(currentMode.toUpperCase())}
247422
+ ${picocolors18.green("\u2714")} \u5DF2\u5207\u6362\u5B89\u5168\u6A21\u5F0F\u81F3: ${picocolors18.green(targetMode.toUpperCase())}` : `Previous mode: ${picocolors18.cyan(currentMode.toUpperCase())}
247147
247423
 
247148
- ${picocolors17.green("\u2714")} Switched security mode to: ${picocolors17.green(targetMode.toUpperCase())}`;
247424
+ ${picocolors18.green("\u2714")} Switched security mode to: ${picocolors18.green(targetMode.toUpperCase())}`;
247149
247425
  await Prompt.askSelect(msg, [
247150
247426
  { value: "ok", label: isZh ? "\u8FD4\u56DE\u5BF9\u8BDD" : "Return to Chat" }
247151
247427
  ]);
247152
247428
  } else {
247153
247429
  this.printOutput(
247154
- isZh ? picocolors17.green(
247430
+ isZh ? picocolors18.green(
247155
247431
  `\u2714 \u5DF2\u5207\u6362\u5B89\u5168\u6A21\u5F0F\u81F3: ${targetMode.toUpperCase()}`
247156
- ) : picocolors17.green(
247432
+ ) : picocolors18.green(
247157
247433
  `\u2714 Switched security mode to: ${targetMode.toUpperCase()}`
247158
247434
  )
247159
247435
  );
@@ -247166,7 +247442,7 @@ ${picocolors17.green("\u2714")} Switched security mode to: ${picocolors17.green(
247166
247442
  const lastAssistantMsg = [...history].reverse().find((msg) => msg.role === "assistant");
247167
247443
  if (!lastAssistantMsg) {
247168
247444
  this.printOutput(
247169
- isZh ? picocolors17.yellow("\u6CA1\u6709\u627E\u5230 AI \u7684\u6700\u8FD1\u56DE\u590D\u3002") : picocolors17.yellow(
247445
+ isZh ? picocolors18.yellow("\u6CA1\u6709\u627E\u5230 AI \u7684\u6700\u8FD1\u56DE\u590D\u3002") : picocolors18.yellow(
247170
247446
  "No recent assistant response found to copy."
247171
247447
  )
247172
247448
  );
@@ -247180,22 +247456,22 @@ ${picocolors17.green("\u2714")} Switched security mode to: ${picocolors17.green(
247180
247456
  }
247181
247457
  if (!textToCopy) {
247182
247458
  this.printOutput(
247183
- isZh ? picocolors17.yellow("AI \u7684\u6700\u8FD1\u56DE\u590D\u5185\u5BB9\u4E3A\u7A7A\u3002") : picocolors17.yellow("Recent assistant response is empty.")
247459
+ isZh ? picocolors18.yellow("AI \u7684\u6700\u8FD1\u56DE\u590D\u5185\u5BB9\u4E3A\u7A7A\u3002") : picocolors18.yellow("Recent assistant response is empty.")
247184
247460
  );
247185
247461
  return { shouldExit: false, processed: true };
247186
247462
  }
247187
247463
  const copied = this.copyToClipboard(textToCopy);
247188
247464
  if (copied) {
247189
247465
  this.printOutput(
247190
- isZh ? picocolors17.green("\u2714 \u5DF2\u6210\u529F\u590D\u5236 AI \u6700\u8FD1\u56DE\u590D\u5230\u526A\u8D34\u677F\uFF01") : picocolors17.green(
247466
+ isZh ? picocolors18.green("\u2714 \u5DF2\u6210\u529F\u590D\u5236 AI \u6700\u8FD1\u56DE\u590D\u5230\u526A\u8D34\u677F\uFF01") : picocolors18.green(
247191
247467
  "\u2714 Successfully copied recent AI response to clipboard!"
247192
247468
  )
247193
247469
  );
247194
247470
  } else {
247195
247471
  this.printOutput(
247196
- isZh ? picocolors17.red(
247472
+ isZh ? picocolors18.red(
247197
247473
  "\u2716 \u590D\u5236\u5230\u526A\u8D34\u677F\u5931\u8D25\uFF0C\u7CFB\u7EDF\u672A\u914D\u7F6E\u526A\u8D34\u677F\u5DE5\u5177\uFF08\u5982 pbcopy/clip/xclip\uFF09\u3002"
247198
- ) : picocolors17.red(
247474
+ ) : picocolors18.red(
247199
247475
  "\u2716 Failed to copy to clipboard. Ensure pbcopy/clip/xclip is installed."
247200
247476
  )
247201
247477
  );
@@ -247203,7 +247479,7 @@ ${picocolors17.green("\u2714")} Switched security mode to: ${picocolors17.green(
247203
247479
  return { shouldExit: false, processed: true };
247204
247480
  }
247205
247481
  this.printOutput(
247206
- picocolors17.red(
247482
+ picocolors18.red(
247207
247483
  `Unknown command: ${trimmed}. Type /help for available commands.`
247208
247484
  )
247209
247485
  );
@@ -247237,7 +247513,7 @@ ${picocolors17.green("\u2714")} Switched security mode to: ${picocolors17.green(
247237
247513
  if (this.tui.isActive) {
247238
247514
  this.tui.addUserMessage(trimmed);
247239
247515
  } else {
247240
- console.log(picocolors17.cyan(`web \u203A ${trimmed}`));
247516
+ console.log(picocolors18.cyan(`web \u203A ${trimmed}`));
247241
247517
  }
247242
247518
  this.loop.prepareUserTurn(trimmed);
247243
247519
  ensureSessionTitle(this.loop, trimmed);
@@ -247541,20 +247817,20 @@ ${picocolors17.green("\u2714")} Switched security mode to: ${picocolors17.green(
247541
247817
  };
247542
247818
 
247543
247819
  // src/runtime/ReplController.ts
247544
- var AutocompleteRequestSchema = z41.object({
247545
- prefix: z41.string().max(2e4),
247546
- suffix: z41.string().max(2e4),
247547
- windowId: z41.string().max(1e3).optional()
247820
+ var AutocompleteRequestSchema = z46.object({
247821
+ prefix: z46.string().max(2e4),
247822
+ suffix: z46.string().max(2e4),
247823
+ windowId: z46.string().max(1e3).optional()
247548
247824
  });
247549
247825
  var AUTOCOMPLETE_BODY_LIMIT_BYTES = 1e5;
247550
247826
  var AUTOCOMPLETE_MAX_CONCURRENCY = 4;
247551
- var LocalStateSchema = z41.object({
247552
- lastSessionId: z41.string().optional(),
247553
- lastModel: z41.string().optional()
247827
+ var LocalStateSchema = z46.object({
247828
+ lastSessionId: z46.string().optional(),
247829
+ lastModel: z46.string().optional()
247554
247830
  });
247555
- var AutocompleteEndpointSchema = z41.object({
247556
- port: z41.number().int().min(1).max(65535),
247557
- token: z41.string().min(32).max(256)
247831
+ var AutocompleteEndpointSchema = z46.object({
247832
+ port: z46.number().int().min(1).max(65535),
247833
+ token: z46.string().min(32).max(256)
247558
247834
  });
247559
247835
  function getRunOutcomeMessage(outcome) {
247560
247836
  if (!outcome || outcome.status === "completed") return void 0;
@@ -247585,7 +247861,7 @@ var ReplController = class {
247585
247861
  getLocalState() {
247586
247862
  try {
247587
247863
  const statePath = resolveSafePath(this.cwd, ".orbit/state.json");
247588
- if (!existsSync28(statePath)) return {};
247864
+ if (!existsSync21(statePath)) return {};
247589
247865
  const parsed = LocalStateSchema.safeParse(
247590
247866
  JSON.parse(readFileSync18(statePath, "utf8"))
247591
247867
  );
@@ -247598,7 +247874,7 @@ var ReplController = class {
247598
247874
  try {
247599
247875
  const statePath = resolveSafePath(this.cwd, ".orbit/state.json");
247600
247876
  const dir = dirname9(statePath);
247601
- if (!existsSync28(dir)) {
247877
+ if (!existsSync21(dir)) {
247602
247878
  mkdirSync13(dir, { recursive: true });
247603
247879
  }
247604
247880
  const current = this.getLocalState();
@@ -247742,7 +248018,7 @@ Confirm action?`;
247742
248018
  console.log(`
247743
248019
  Risk Warning: ${reason}`);
247744
248020
  if (preview) {
247745
- console.log(picocolors18.gray(`Parameters: ${preview}`));
248021
+ console.log(picocolors19.gray(`Parameters: ${preview}`));
247746
248022
  }
247747
248023
  const approved = await Prompt.askApproval("Confirm action?");
247748
248024
  if (wasActive) tui.start(this.config.budgetLimit);
@@ -247841,7 +248117,7 @@ Risk Warning: ${reason}`);
247841
248117
  if (useFullscreenTui) {
247842
248118
  tui.handleThinkingDelta(payload.text);
247843
248119
  } else {
247844
- process.stdout.write(picocolors18.gray(payload.text));
248120
+ process.stdout.write(picocolors19.gray(payload.text));
247845
248121
  }
247846
248122
  };
247847
248123
  eventBus.on("model_delta", onModelDelta);
@@ -247940,7 +248216,7 @@ Risk Warning: ${reason}`);
247940
248216
  input = await Prompt.askTextWithAutocomplete(
247941
248217
  "Type your task or command...",
247942
248218
  this.makeCompleter(),
247943
- `${picocolors18.bold(picocolors18.magenta("orbit"))}${picocolors18.gray(" \u276F ")}`
248219
+ `${picocolors19.bold(picocolors19.magenta("orbit"))}${picocolors19.gray(" \u276F ")}`
247944
248220
  );
247945
248221
  }
247946
248222
  if (input === null) {
@@ -247948,7 +248224,7 @@ Risk Warning: ${reason}`);
247948
248224
  tui.stop();
247949
248225
  } else {
247950
248226
  console.log(
247951
- picocolors18.yellow("Exiting Orbit Interactive Shell. Goodbye!")
248227
+ picocolors19.yellow("Exiting Orbit Interactive Shell. Goodbye!")
247952
248228
  );
247953
248229
  }
247954
248230
  break;
@@ -248157,8 +248433,8 @@ async function readLimitedBody(req, limitBytes) {
248157
248433
 
248158
248434
  // src/commands/run.ts
248159
248435
  function getLocalState(cwd) {
248160
- const statePath = join18(cwd, ".orbit", "state.json");
248161
- if (!existsSync29(statePath)) return {};
248436
+ const statePath = join17(cwd, ".orbit", "state.json");
248437
+ if (!existsSync28(statePath)) return {};
248162
248438
  try {
248163
248439
  return JSON.parse(readFileSync19(statePath, "utf8"));
248164
248440
  } catch {
@@ -248223,7 +248499,7 @@ async function runAgent(cwd, task, cliOverrides, multi, options) {
248223
248499
  const message = redactSecrets(
248224
248500
  error instanceof Error ? error.message : "Failed to create provider instance."
248225
248501
  );
248226
- console.error(picocolors19.red(message));
248502
+ console.error(picocolors20.red(message));
248227
248503
  const outcome = {
248228
248504
  status: "failed",
248229
248505
  sessionId: "",
@@ -248243,7 +248519,7 @@ async function runAgent(cwd, task, cliOverrides, multi, options) {
248243
248519
  console.error(`
248244
248520
  Risk Warning [Non-Interactive Mode]: ${reason}`);
248245
248521
  if (preview) {
248246
- console.error(picocolors19.gray(`Parameters: ${preview}`));
248522
+ console.error(picocolors20.gray(`Parameters: ${preview}`));
248247
248523
  }
248248
248524
  console.error(
248249
248525
  "Automatically denying action in non-interactive mode."
@@ -248263,7 +248539,7 @@ Risk Warning [Non-Interactive Mode]: ${reason}`);
248263
248539
  console.log(`
248264
248540
  Risk Warning: ${reason}`);
248265
248541
  if (preview) {
248266
- console.log(picocolors19.gray(`Parameters: ${preview}`));
248542
+ console.log(picocolors20.gray(`Parameters: ${preview}`));
248267
248543
  }
248268
248544
  return await Prompt.askApproval("Confirm action?");
248269
248545
  },
@@ -248412,36 +248688,36 @@ function isRecord6(value) {
248412
248688
  }
248413
248689
 
248414
248690
  // src/commands/LSPServer.ts
248415
- import { z as z45 } from "zod";
248691
+ import { z as z47 } from "zod";
248416
248692
  var MAX_LSP_HEADER_BYTES = 8 * 1024;
248417
248693
  var MAX_LSP_BODY_BYTES = 8 * 1024 * 1024;
248418
- var JsonRpcIdSchema = z45.union([z45.string(), z45.number(), z45.null()]);
248419
- var JSONRPCMessageSchema = z45.object({
248420
- jsonrpc: z45.literal("2.0"),
248694
+ var JsonRpcIdSchema = z47.union([z47.string(), z47.number(), z47.null()]);
248695
+ var JSONRPCMessageSchema = z47.object({
248696
+ jsonrpc: z47.literal("2.0"),
248421
248697
  id: JsonRpcIdSchema.optional(),
248422
- method: z45.string().min(1).max(512),
248423
- params: z45.unknown().optional()
248698
+ method: z47.string().min(1).max(512),
248699
+ params: z47.unknown().optional()
248424
248700
  }).strict();
248425
- var TextDocumentIdentifierSchema = z45.object({
248426
- uri: z45.string().min(1).max(16384)
248701
+ var TextDocumentIdentifierSchema = z47.object({
248702
+ uri: z47.string().min(1).max(16384)
248427
248703
  });
248428
- var DidOpenParamsSchema = z45.object({
248704
+ var DidOpenParamsSchema = z47.object({
248429
248705
  textDocument: TextDocumentIdentifierSchema.extend({
248430
- text: z45.string().max(MAX_LSP_BODY_BYTES)
248706
+ text: z47.string().max(MAX_LSP_BODY_BYTES)
248431
248707
  }).passthrough()
248432
248708
  });
248433
- var DidChangeParamsSchema = z45.object({
248709
+ var DidChangeParamsSchema = z47.object({
248434
248710
  textDocument: TextDocumentIdentifierSchema,
248435
- contentChanges: z45.array(z45.object({ text: z45.string().max(MAX_LSP_BODY_BYTES) }).passthrough()).min(1).max(100)
248711
+ contentChanges: z47.array(z47.object({ text: z47.string().max(MAX_LSP_BODY_BYTES) }).passthrough()).min(1).max(100)
248436
248712
  });
248437
- var DidCloseParamsSchema = z45.object({
248713
+ var DidCloseParamsSchema = z47.object({
248438
248714
  textDocument: TextDocumentIdentifierSchema
248439
248715
  });
248440
- var CompletionParamsSchema = z45.object({
248716
+ var CompletionParamsSchema = z47.object({
248441
248717
  textDocument: TextDocumentIdentifierSchema,
248442
- position: z45.object({
248443
- line: z45.number().int().nonnegative(),
248444
- character: z45.number().int().nonnegative()
248718
+ position: z47.object({
248719
+ line: z47.number().int().nonnegative(),
248720
+ character: z47.number().int().nonnegative()
248445
248721
  })
248446
248722
  });
248447
248723
  var JSONRPCReader = class {
@@ -248575,7 +248851,7 @@ async function runLSPServer(cwd) {
248575
248851
  const autocompleteEngine = new AutocompleteEngine(cwd);
248576
248852
  const documentCache = /* @__PURE__ */ new Map();
248577
248853
  let shutdownRequested = false;
248578
- await new Promise((resolve13) => {
248854
+ await new Promise((resolve15) => {
248579
248855
  let settled = false;
248580
248856
  const finish = () => {
248581
248857
  if (settled) return;
@@ -248584,7 +248860,7 @@ async function runLSPServer(cwd) {
248584
248860
  process.stdin.off("end", onEnd);
248585
248861
  autocompleteEngine.dispose();
248586
248862
  documentCache.clear();
248587
- resolve13();
248863
+ resolve15();
248588
248864
  };
248589
248865
  const handleMessage = async (message) => {
248590
248866
  try {
@@ -248687,7 +248963,7 @@ ${completion}
248687
248963
  );
248688
248964
  }
248689
248965
  } catch (error) {
248690
- if (error instanceof z45.ZodError) {
248966
+ if (error instanceof z47.ZodError) {
248691
248967
  sendError(message.id, -32602, "Invalid method parameters.");
248692
248968
  return;
248693
248969
  }
@@ -248709,8 +248985,8 @@ ${completion}
248709
248985
  }
248710
248986
 
248711
248987
  // src/commands/login.ts
248712
- import readline4 from "readline";
248713
- import picocolors20 from "picocolors";
248988
+ import readline5 from "readline";
248989
+ import picocolors21 from "picocolors";
248714
248990
  var PROVIDER_TEMPLATES = [
248715
248991
  {
248716
248992
  id: "ollama",
@@ -248763,19 +249039,19 @@ var PROVIDER_TEMPLATES = [
248763
249039
  }
248764
249040
  ];
248765
249041
  function askQuestion(query, defaultValue = "") {
248766
- const rl = readline4.createInterface({
249042
+ const rl = readline5.createInterface({
248767
249043
  input: process.stdin,
248768
249044
  output: process.stdout
248769
249045
  });
248770
- return new Promise((resolve13) => {
249046
+ return new Promise((resolve15) => {
248771
249047
  rl.question(query, (answer) => {
248772
249048
  rl.close();
248773
- resolve13(answer.trim() || defaultValue);
249049
+ resolve15(answer.trim() || defaultValue);
248774
249050
  });
248775
249051
  });
248776
249052
  }
248777
249053
  function askSecret(query) {
248778
- return new Promise((resolve13, reject) => {
249054
+ return new Promise((resolve15, reject) => {
248779
249055
  const stdin = process.stdin;
248780
249056
  const stdout = process.stdout;
248781
249057
  if (!stdin.isTTY || !stdout.isTTY || typeof stdin.setRawMode !== "function") {
@@ -248809,13 +249085,13 @@ function askSecret(query) {
248809
249085
  case "":
248810
249086
  cleanup();
248811
249087
  stdout.write("\n");
248812
- resolve13(input.trim());
249088
+ resolve15(input.trim());
248813
249089
  break;
248814
249090
  case "":
248815
249091
  cleanup();
248816
249092
  stdout.write("\n");
248817
249093
  process.exitCode = 130;
248818
- resolve13("");
249094
+ resolve15("");
248819
249095
  break;
248820
249096
  case "\b":
248821
249097
  case "\x7F":
@@ -248844,20 +249120,20 @@ function slugifyProviderId(value) {
248844
249120
  }
248845
249121
  function printProfiles(store, credentials) {
248846
249122
  const snapshot = store.read();
248847
- console.log(picocolors20.bold("\nSaved provider logins\n"));
249123
+ console.log(picocolors21.bold("\nSaved provider logins\n"));
248848
249124
  if (snapshot.profiles.length === 0) {
248849
- console.log(picocolors20.gray(" No saved provider profiles."));
249125
+ console.log(picocolors21.gray(" No saved provider profiles."));
248850
249126
  return;
248851
249127
  }
248852
249128
  for (const profile of snapshot.profiles) {
248853
249129
  const active = snapshot.activeProvider === profile.id ? "\u25CF" : "\u25CB";
248854
249130
  const credential = profile.config.apiKeyEnv ? credentials.hasSecret(profile.config.apiKeyEnv) : false;
248855
- const credentialStatus = profile.config.type === "ollama" ? picocolors20.cyan("local \xB7 no credential") : credential ? picocolors20.green("credential saved") : picocolors20.yellow("credential missing");
249131
+ const credentialStatus = profile.config.type === "ollama" ? picocolors21.cyan("local \xB7 no credential") : credential ? picocolors21.green("credential saved") : picocolors21.yellow("credential missing");
248856
249132
  console.log(
248857
- ` ${active} ${picocolors20.bold(profile.name)} ${picocolors20.gray(`(${profile.id})`)} ${credentialStatus}`
249133
+ ` ${active} ${picocolors21.bold(profile.name)} ${picocolors21.gray(`(${profile.id})`)} ${credentialStatus}`
248858
249134
  );
248859
249135
  console.log(
248860
- ` ${picocolors20.gray(profile.config.baseUrl || "default endpoint")} \xB7 ${profile.config.models?.length || 0} models`
249136
+ ` ${picocolors21.gray(profile.config.baseUrl || "default endpoint")} \xB7 ${profile.config.models?.length || 0} models`
248861
249137
  );
248862
249138
  }
248863
249139
  }
@@ -248874,14 +249150,14 @@ async function configureProvider(template, options, store, credentials) {
248874
249150
  const requiresApiKey = template.requiresApiKey !== false;
248875
249151
  const apiKey = requiresApiKey ? await askSecret("API key (input hidden): ") : void 0;
248876
249152
  if (requiresApiKey && !apiKey) {
248877
- console.log(picocolors20.yellow("\u26A0 Provider login cancelled."));
249153
+ console.log(picocolors21.yellow("\u26A0 Provider login cancelled."));
248878
249154
  return;
248879
249155
  }
248880
249156
  const baseUrl = requestedBaseUrl.replace(/\/$/, "");
248881
249157
  let models = existing?.config.models;
248882
249158
  let modelCapabilities = existing?.config.modelCapabilities;
248883
249159
  if (template.discoverModels || template.type.includes("openai")) {
248884
- console.log(picocolors20.cyan("\u25CF Scanning the provider model catalog\u2026"));
249160
+ console.log(picocolors21.cyan("\u25CF Scanning the provider model catalog\u2026"));
248885
249161
  const discovered = await discoverProviderModels({
248886
249162
  baseUrl: requestedBaseUrl,
248887
249163
  apiKey,
@@ -248890,7 +249166,7 @@ async function configureProvider(template, options, store, credentials) {
248890
249166
  models = discovered.models;
248891
249167
  modelCapabilities = discovered.modelCapabilities;
248892
249168
  console.log(
248893
- picocolors20.green(
249169
+ picocolors21.green(
248894
249170
  `\u2714 Found ${discovered.models.length} models at ${discovered.modelsEndpoint}`
248895
249171
  )
248896
249172
  );
@@ -248910,7 +249186,7 @@ async function configureProvider(template, options, store, credentials) {
248910
249186
  });
248911
249187
  if (options.activate !== false) store.setActive(template.id);
248912
249188
  console.log(
248913
- picocolors20.green(
249189
+ picocolors21.green(
248914
249190
  `\u2714 ${requestedName} ${requiresApiKey ? "saved securely" : "saved"}${options.activate === false ? "." : " and selected as the active provider."}`
248915
249191
  )
248916
249192
  );
@@ -248949,7 +249225,7 @@ async function chooseSavedProvider(profiles, prompt) {
248949
249225
  if (profiles.length === 0) return void 0;
248950
249226
  profiles.forEach((profile, index) => {
248951
249227
  console.log(
248952
- ` ${picocolors20.cyan(String(index + 1))}) ${profile.name} (${profile.id})`
249228
+ ` ${picocolors21.cyan(String(index + 1))}) ${profile.name} (${profile.id})`
248953
249229
  );
248954
249230
  });
248955
249231
  const selected = Number(await askQuestion(prompt));
@@ -248970,9 +249246,9 @@ async function runLogin(options = {}) {
248970
249246
  credentials
248971
249247
  );
248972
249248
  console.log(
248973
- deleted ? picocolors20.green(
249249
+ deleted ? picocolors21.green(
248974
249250
  `\u2714 Deleted provider login: ${options.deleteProvider}`
248975
- ) : picocolors20.yellow(
249251
+ ) : picocolors21.yellow(
248976
249252
  `\u26A0 Provider login not found: ${options.deleteProvider}`
248977
249253
  )
248978
249254
  );
@@ -248989,7 +249265,7 @@ async function runLogin(options = {}) {
248989
249265
  }
248990
249266
  return;
248991
249267
  }
248992
- console.log(picocolors20.bold("\nOrbit provider logins"));
249268
+ console.log(picocolors21.bold("\nOrbit provider logins"));
248993
249269
  printProfiles(store, credentials);
248994
249270
  console.log("\n 1) Scan or update local Ollama");
248995
249271
  console.log(" 2) Add or update TokenDance");
@@ -249030,7 +249306,7 @@ async function runLogin(options = {}) {
249030
249306
  );
249031
249307
  if (selected) {
249032
249308
  store.setActive(selected.id);
249033
- console.log(picocolors20.green(`\u2714 Active provider: ${selected.name}`));
249309
+ console.log(picocolors21.green(`\u2714 Active provider: ${selected.name}`));
249034
249310
  }
249035
249311
  } else if (action === "6") {
249036
249312
  const selected = await chooseSavedProvider(
@@ -249039,20 +249315,20 @@ async function runLogin(options = {}) {
249039
249315
  );
249040
249316
  if (selected && deleteProviderLogin(selected.id, store, credentials)) {
249041
249317
  console.log(
249042
- picocolors20.green(`\u2714 Deleted provider login: ${selected.name}`)
249318
+ picocolors21.green(`\u2714 Deleted provider login: ${selected.name}`)
249043
249319
  );
249044
249320
  }
249045
249321
  }
249046
249322
  } catch (error) {
249047
249323
  const message = error instanceof Error ? error.message : String(error);
249048
- console.log(picocolors20.red(`
249324
+ console.log(picocolors21.red(`
249049
249325
  \u2716 Provider login failed: ${message}`));
249050
249326
  }
249051
249327
  }
249052
249328
 
249053
249329
  // src/commands/trace.ts
249054
249330
  import {
249055
- existsSync as existsSync30,
249331
+ existsSync as existsSync29,
249056
249332
  lstatSync as lstatSync3,
249057
249333
  mkdirSync as mkdirSync14,
249058
249334
  renameSync as renameSync9,
@@ -249060,10 +249336,10 @@ import {
249060
249336
  writeFileSync as writeFileSync13
249061
249337
  } from "fs";
249062
249338
  import { dirname as dirname10, resolve as resolve11 } from "path";
249063
- import { z as z46 } from "zod";
249064
- var TraceOptionsSchema = z46.object({
249065
- full: z46.boolean().default(false),
249066
- out: z46.string().trim().min(1).max(4096).optional()
249339
+ import { z as z48 } from "zod";
249340
+ var TraceOptionsSchema = z48.object({
249341
+ full: z48.boolean().default(false),
249342
+ out: z48.string().trim().min(1).max(4096).optional()
249067
249343
  });
249068
249344
  function runTraceExport(cwd, sessionId, options = {}) {
249069
249345
  const value = TraceOptionsSchema.parse(options);
@@ -249079,7 +249355,7 @@ function runTraceExport(cwd, sessionId, options = {}) {
249079
249355
  }
249080
249356
  const outputPath = resolveSafePath(cwd, value.out);
249081
249357
  const directory = dirname10(outputPath);
249082
- if (existsSync30(directory)) {
249358
+ if (existsSync29(directory)) {
249083
249359
  const stats = lstatSync3(directory);
249084
249360
  if (stats.isSymbolicLink() || !stats.isDirectory()) {
249085
249361
  throw new Error("Trace output directory must be a real directory.");
@@ -249094,7 +249370,7 @@ function runTraceExport(cwd, sessionId, options = {}) {
249094
249370
  flag: "wx",
249095
249371
  mode: 384
249096
249372
  });
249097
- if (existsSync30(outputPath)) rmSync7(outputPath, { force: true });
249373
+ if (existsSync29(outputPath)) rmSync7(outputPath, { force: true });
249098
249374
  renameSync9(temporaryPath, outputPath);
249099
249375
  } finally {
249100
249376
  rmSync7(temporaryPath, { force: true });
@@ -249103,10 +249379,10 @@ function runTraceExport(cwd, sessionId, options = {}) {
249103
249379
  }
249104
249380
 
249105
249381
  // src/commands/eval.ts
249106
- import { exec as execCallback, execFileSync as execFileSync4 } from "child_process";
249382
+ import { exec as execCallback, execFileSync as execFileSync6 } from "child_process";
249107
249383
  import {
249108
249384
  copyFileSync as copyFileSync4,
249109
- existsSync as existsSync31,
249385
+ existsSync as existsSync30,
249110
249386
  lstatSync as lstatSync4,
249111
249387
  mkdirSync as mkdirSync15,
249112
249388
  readFileSync as readFileSync20,
@@ -249114,20 +249390,20 @@ import {
249114
249390
  rmSync as rmSync8,
249115
249391
  writeFileSync as writeFileSync14
249116
249392
  } from "fs";
249117
- import { basename as basename6, dirname as dirname11, join as join19 } from "path";
249393
+ import { basename as basename6, dirname as dirname11, join as join18 } from "path";
249118
249394
  import { promisify as promisify5 } from "util";
249119
- import picocolors21 from "picocolors";
249395
+ import picocolors23 from "picocolors";
249120
249396
  import { parse as parseYaml } from "yaml";
249121
- import { z as z47 } from "zod";
249397
+ import { z as z49 } from "zod";
249122
249398
  var exec4 = promisify5(execCallback);
249123
249399
  var MAX_SUITE_BYTES = 1024 * 1024;
249124
249400
  var MAX_VERIFICATION_OUTPUT = 4e3;
249125
- var EvalOptionsSchema = z47.object({
249126
- provider: z47.string().trim().min(1).optional(),
249127
- model: z47.string().trim().min(1).optional(),
249128
- task: z47.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
249129
- allowCommands: z47.boolean().default(false),
249130
- json: z47.boolean().default(false)
249401
+ var EvalOptionsSchema = z49.object({
249402
+ provider: z49.string().trim().min(1).optional(),
249403
+ model: z49.string().trim().min(1).optional(),
249404
+ task: z49.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
249405
+ allowCommands: z49.boolean().default(false),
249406
+ json: z49.boolean().default(false)
249131
249407
  });
249132
249408
  async function runEval(cwd, suiteFile, options = {}) {
249133
249409
  const value = EvalOptionsSchema.parse(options);
@@ -249150,7 +249426,7 @@ async function runEval(cwd, suiteFile, options = {}) {
249150
249426
  const results = [];
249151
249427
  for (const task of tasks) {
249152
249428
  if (!value.json) {
249153
- console.log(picocolors21.cyan(`\u25CF Evaluating ${task.id}...`));
249429
+ console.log(picocolors23.cyan(`\u25CF Evaluating ${task.id}...`));
249154
249430
  }
249155
249431
  let worktree;
249156
249432
  const taskStartedAt = Date.now();
@@ -249249,13 +249525,13 @@ async function runEval(cwd, suiteFile, options = {}) {
249249
249525
  console.log(JSON.stringify(report, null, 2));
249250
249526
  } else {
249251
249527
  console.log(
249252
- report.passed ? picocolors21.green(
249528
+ report.passed ? picocolors23.green(
249253
249529
  `\u2714 Acceptance passed: ${passedTasks}/${results.length} tasks.`
249254
- ) : picocolors21.red(
249530
+ ) : picocolors23.red(
249255
249531
  `\u2716 Acceptance failed: ${passedTasks}/${results.length} tasks passed.`
249256
249532
  )
249257
249533
  );
249258
- console.log(picocolors21.gray(`Report: ${reportPath}`));
249534
+ console.log(picocolors23.gray(`Report: ${reportPath}`));
249259
249535
  }
249260
249536
  if (!report.passed) process.exitCode = 1;
249261
249537
  return report;
@@ -249307,7 +249583,7 @@ ${result.stderr}`)
249307
249583
  }
249308
249584
  function readChangedFiles(cwd) {
249309
249585
  try {
249310
- const output = execFileSync4(
249586
+ const output = execFileSync6(
249311
249587
  "git",
249312
249588
  ["status", "--porcelain=v1", "-z", "--untracked-files=all"],
249313
249589
  { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }
@@ -249318,7 +249594,7 @@ function readChangedFiles(cwd) {
249318
249594
  }
249319
249595
  }
249320
249596
  function snapshotWorkspaceIntoWorktree(sourceCwd, worktreeCwd) {
249321
- const patch = execFileSync4(
249597
+ const patch = execFileSync6(
249322
249598
  "git",
249323
249599
  ["diff", "HEAD", "--binary", "--no-ext-diff"],
249324
249600
  {
@@ -249329,14 +249605,14 @@ function snapshotWorkspaceIntoWorktree(sourceCwd, worktreeCwd) {
249329
249605
  }
249330
249606
  );
249331
249607
  if (patch.length > 0) {
249332
- execFileSync4("git", ["apply", "--whitespace=nowarn", "-"], {
249608
+ execFileSync6("git", ["apply", "--whitespace=nowarn", "-"], {
249333
249609
  cwd: worktreeCwd,
249334
249610
  input: patch,
249335
249611
  stdio: ["pipe", "pipe", "pipe"],
249336
249612
  maxBuffer: 64 * 1024 * 1024
249337
249613
  });
249338
249614
  }
249339
- const untracked = execFileSync4(
249615
+ const untracked = execFileSync6(
249340
249616
  "git",
249341
249617
  ["ls-files", "--others", "--exclude-standard", "-z"],
249342
249618
  {
@@ -249355,17 +249631,17 @@ function snapshotWorkspaceIntoWorktree(sourceCwd, worktreeCwd) {
249355
249631
  mkdirSync15(dirname11(targetPath), { recursive: true });
249356
249632
  copyFileSync4(sourcePath, targetPath);
249357
249633
  }
249358
- execFileSync4("git", ["add", "-A"], {
249634
+ execFileSync6("git", ["add", "-A"], {
249359
249635
  cwd: worktreeCwd,
249360
249636
  stdio: ["ignore", "pipe", "pipe"]
249361
249637
  });
249362
- const dirty = execFileSync4("git", ["status", "--porcelain"], {
249638
+ const dirty = execFileSync6("git", ["status", "--porcelain"], {
249363
249639
  cwd: worktreeCwd,
249364
249640
  encoding: "utf8",
249365
249641
  stdio: ["ignore", "pipe", "pipe"]
249366
249642
  }).trim();
249367
249643
  if (!dirty) return;
249368
- execFileSync4(
249644
+ execFileSync6(
249369
249645
  "git",
249370
249646
  [
249371
249647
  "-c",
@@ -249390,7 +249666,7 @@ function isSensitiveSnapshotPath2(filePath) {
249390
249666
  return normalized.startsWith(".orbit/") || normalized.includes("/.ssh/") || name === "id_rsa" || name === "id_ed25519" || name === ".npmrc" || name === ".pypirc" || name === ".env" || name.startsWith(".env.");
249391
249667
  }
249392
249668
  function writeEvaluationTrace(cwd, runId, taskId, trace) {
249393
- const relativePath = join19(
249669
+ const relativePath = join18(
249394
249670
  ".orbit",
249395
249671
  "evaluations",
249396
249672
  runId,
@@ -249402,14 +249678,14 @@ function writeEvaluationTrace(cwd, runId, taskId, trace) {
249402
249678
  function writeEvaluationReport(cwd, runId, report) {
249403
249679
  const filePath = resolveSafePath(
249404
249680
  cwd,
249405
- join19(".orbit", "evaluations", `${runId}.json`)
249681
+ join18(".orbit", "evaluations", `${runId}.json`)
249406
249682
  );
249407
249683
  writeJsonAtomically2(filePath, report);
249408
249684
  return filePath;
249409
249685
  }
249410
249686
  function writeJsonAtomically2(filePath, value) {
249411
249687
  const directory = dirname11(filePath);
249412
- if (existsSync31(directory)) {
249688
+ if (existsSync30(directory)) {
249413
249689
  const stats = lstatSync4(directory);
249414
249690
  if (stats.isSymbolicLink() || !stats.isDirectory()) {
249415
249691
  throw new Error("Evaluation output directory must be a real directory.");
@@ -249424,7 +249700,7 @@ function writeJsonAtomically2(filePath, value) {
249424
249700
  flag: "wx",
249425
249701
  mode: 384
249426
249702
  });
249427
- if (existsSync31(filePath)) rmSync8(filePath, { force: true });
249703
+ if (existsSync30(filePath)) rmSync8(filePath, { force: true });
249428
249704
  renameSync10(temporaryPath, filePath);
249429
249705
  } finally {
249430
249706
  rmSync8(temporaryPath, { force: true });
@@ -249435,9 +249711,262 @@ function safeSummary(value) {
249435
249711
  return redactSecrets(raw || "unknown error").replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").replace(/\s+/g, " ").trim().slice(-MAX_VERIFICATION_OUTPUT);
249436
249712
  }
249437
249713
 
249714
+ // src/commands/clean.ts
249715
+ import readline6 from "readline";
249716
+ import picocolors24 from "picocolors";
249717
+ import { resolve as resolve13 } from "path";
249718
+ import { z as z51 } from "zod";
249719
+
249720
+ // src/runtime/CleanupManager.ts
249721
+ import { lstatSync as lstatSync5, readdirSync as readdirSync7, rmSync as rmSync9 } from "fs";
249722
+ import { homedir as homedir11 } from "os";
249723
+ import { basename as basename7, join as join19, parse as parse5, resolve as resolve12 } from "path";
249724
+ import { z as z50 } from "zod";
249725
+ var CleanupScopeSchema = z50.enum(["user", "project"]);
249726
+ function buildCleanupPlan(options) {
249727
+ const scopes = z50.array(CleanupScopeSchema).min(1).parse(options.scopes);
249728
+ const homeDirectory = resolve12(options.homeDirectory ?? homedir11());
249729
+ const projectDirectory = resolve12(options.projectDirectory ?? options.cwd);
249730
+ const candidates = scopes.map((scope) => ({
249731
+ scope,
249732
+ path: scope === "user" ? join19(homeDirectory, ".orbit") : join19(projectDirectory, ".orbit")
249733
+ }));
249734
+ const grouped = /* @__PURE__ */ new Map();
249735
+ for (const candidate of candidates) {
249736
+ assertSafeOrbitDataPath(candidate.path);
249737
+ const key = pathIdentity(candidate.path);
249738
+ const existing = grouped.get(key);
249739
+ if (existing) {
249740
+ if (!existing.scopes.includes(candidate.scope)) {
249741
+ existing.scopes.push(candidate.scope);
249742
+ }
249743
+ } else {
249744
+ grouped.set(key, { path: candidate.path, scopes: [candidate.scope] });
249745
+ }
249746
+ }
249747
+ const targets = [...grouped.values()].map((candidate) => ({
249748
+ ...candidate,
249749
+ ...inspectPath(candidate.path)
249750
+ }));
249751
+ return {
249752
+ targets,
249753
+ totals: targets.reduce(
249754
+ (totals, target) => ({
249755
+ files: totals.files + target.files,
249756
+ directories: totals.directories + target.directories,
249757
+ bytes: totals.bytes + target.bytes
249758
+ }),
249759
+ { files: 0, directories: 0, bytes: 0 }
249760
+ )
249761
+ };
249762
+ }
249763
+ function executeCleanupPlan(plan) {
249764
+ const result = { removed: [], skipped: [] };
249765
+ for (const target of plan.targets) {
249766
+ assertSafeOrbitDataPath(target.path);
249767
+ if (!pathExists(target.path)) {
249768
+ result.skipped.push(target.path);
249769
+ continue;
249770
+ }
249771
+ rmSync9(target.path, { recursive: true, force: true, maxRetries: 3 });
249772
+ result.removed.push(target.path);
249773
+ }
249774
+ return result;
249775
+ }
249776
+ function inspectPath(targetPath) {
249777
+ if (!pathExists(targetPath)) {
249778
+ return {
249779
+ exists: false,
249780
+ files: 0,
249781
+ directories: 0,
249782
+ bytes: 0,
249783
+ warnings: []
249784
+ };
249785
+ }
249786
+ const totals = { files: 0, directories: 0, bytes: 0 };
249787
+ const warnings = [];
249788
+ const visit = (currentPath) => {
249789
+ let stat;
249790
+ try {
249791
+ stat = lstatSync5(currentPath);
249792
+ } catch (error) {
249793
+ warnings.push(safeInventoryWarning(currentPath, error));
249794
+ return;
249795
+ }
249796
+ if (stat.isSymbolicLink()) {
249797
+ totals.files++;
249798
+ totals.bytes += stat.size;
249799
+ return;
249800
+ }
249801
+ if (!stat.isDirectory()) {
249802
+ totals.files++;
249803
+ totals.bytes += stat.size;
249804
+ return;
249805
+ }
249806
+ totals.directories++;
249807
+ try {
249808
+ for (const entry of readdirSync7(currentPath)) {
249809
+ visit(join19(currentPath, entry));
249810
+ }
249811
+ } catch (error) {
249812
+ warnings.push(safeInventoryWarning(currentPath, error));
249813
+ }
249814
+ };
249815
+ visit(targetPath);
249816
+ return { exists: true, ...totals, warnings };
249817
+ }
249818
+ function assertSafeOrbitDataPath(targetPath) {
249819
+ const absolutePath = resolve12(targetPath);
249820
+ if (absolutePath === parse5(absolutePath).root) {
249821
+ throw new Error("Refusing to clean a filesystem root.");
249822
+ }
249823
+ if (basename7(absolutePath).toLowerCase() !== ".orbit") {
249824
+ throw new Error("Cleanup targets must be an Orbit data directory.");
249825
+ }
249826
+ if (resolve12(absolutePath, "..") === parse5(absolutePath).root) {
249827
+ throw new Error(
249828
+ "Refusing to clean an Orbit directory directly under a filesystem root."
249829
+ );
249830
+ }
249831
+ }
249832
+ function pathIdentity(targetPath) {
249833
+ const normalized = resolve12(targetPath).replace(/\\/g, "/");
249834
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
249835
+ }
249836
+ function pathExists(targetPath) {
249837
+ try {
249838
+ lstatSync5(targetPath);
249839
+ return true;
249840
+ } catch {
249841
+ return false;
249842
+ }
249843
+ }
249844
+ function safeInventoryWarning(targetPath, error) {
249845
+ const code = typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "unreadable";
249846
+ return `${code}: ${targetPath}`;
249847
+ }
249848
+
249849
+ // src/commands/clean.ts
249850
+ var CleanCommandOptionsSchema = z51.object({
249851
+ user: z51.boolean().default(false),
249852
+ project: z51.union([z51.boolean(), z51.string().min(1).max(4096)]).optional(),
249853
+ all: z51.boolean().default(false),
249854
+ yes: z51.boolean().default(false),
249855
+ json: z51.boolean().default(false)
249856
+ }).strict();
249857
+ async function runClean(cwd, rawOptions, dependencies = {}) {
249858
+ const options = CleanCommandOptionsSchema.parse(rawOptions);
249859
+ const scopes = resolveScopes(options);
249860
+ const projectDirectory = typeof options.project === "string" ? resolve13(cwd, options.project) : cwd;
249861
+ const plan = buildCleanupPlan({
249862
+ cwd,
249863
+ scopes,
249864
+ homeDirectory: dependencies.homeDirectory,
249865
+ projectDirectory
249866
+ });
249867
+ const write = dependencies.write ?? ((text) => console.log(text));
249868
+ if (options.json && !options.yes) {
249869
+ write(JSON.stringify({ schemaVersion: 1, applied: false, plan }));
249870
+ return { applied: false, plan, removed: [], skipped: [] };
249871
+ }
249872
+ if (!options.json) {
249873
+ printCleanupPlan(plan, write);
249874
+ }
249875
+ if (plan.targets.every((target) => !target.exists)) {
249876
+ return { applied: false, plan, removed: [], skipped: [] };
249877
+ }
249878
+ let confirmed = options.yes;
249879
+ if (!confirmed) {
249880
+ const interactive = dependencies.interactive ?? Boolean(process.stdin.isTTY);
249881
+ if (!interactive) {
249882
+ throw new Error(
249883
+ "Cleanup requires an interactive confirmation or the explicit --yes flag."
249884
+ );
249885
+ }
249886
+ const confirm = dependencies.confirm ?? confirmDeletion;
249887
+ confirmed = await confirm(
249888
+ "Type DELETE to permanently remove the listed Orbit data: "
249889
+ );
249890
+ }
249891
+ if (!confirmed) {
249892
+ if (!options.json) write(picocolors24.yellow("\u26A0 Cleanup cancelled."));
249893
+ return { applied: false, plan, removed: [], skipped: [] };
249894
+ }
249895
+ const userTarget = plan.targets.find(
249896
+ (target) => target.scopes.includes("user")
249897
+ );
249898
+ if (userTarget?.exists) {
249899
+ const purgeUserCredentials = dependencies.purgeUserCredentials ?? ((orbitDirectory) => new CredentialsManager({ orbitDir: orbitDirectory }).purge());
249900
+ purgeUserCredentials(userTarget.path);
249901
+ }
249902
+ const result = executeCleanupPlan(plan);
249903
+ if (options.json) {
249904
+ write(
249905
+ JSON.stringify({
249906
+ schemaVersion: 1,
249907
+ applied: true,
249908
+ plan,
249909
+ ...result
249910
+ })
249911
+ );
249912
+ } else {
249913
+ write(
249914
+ picocolors24.green(
249915
+ `\u2714 Removed ${result.removed.length} Orbit data director${result.removed.length === 1 ? "y" : "ies"}.`
249916
+ )
249917
+ );
249918
+ }
249919
+ return { applied: true, plan, ...result };
249920
+ }
249921
+ function resolveScopes(options) {
249922
+ const scopes = [];
249923
+ if (options.all || options.user) scopes.push("user");
249924
+ if (options.all || options.project !== void 0) scopes.push("project");
249925
+ if (scopes.length === 0) {
249926
+ throw new Error("Choose --user, --project [path], or --all.");
249927
+ }
249928
+ return scopes;
249929
+ }
249930
+ function printCleanupPlan(plan, write) {
249931
+ write(picocolors24.bold("\nOrbit cleanup preview\n"));
249932
+ for (const target of plan.targets) {
249933
+ const scope = target.scopes.join(" + ");
249934
+ const status = target.exists ? `${target.files} files \xB7 ${target.directories} directories \xB7 ${formatBytes(target.bytes)}` : "not present";
249935
+ write(` ${target.exists ? "\u25CF" : "\u25CB"} ${scope}: ${target.path}`);
249936
+ write(` ${picocolors24.gray(status)}`);
249937
+ for (const warning of target.warnings) {
249938
+ write(` ${picocolors24.yellow(`\u26A0 ${warning}`)}`);
249939
+ }
249940
+ }
249941
+ write(
249942
+ picocolors24.gray(
249943
+ "\nOnly .orbit data directories are included. Project source, ORBIT.md, and orbit.config.yaml are preserved."
249944
+ )
249945
+ );
249946
+ }
249947
+ function formatBytes(bytes) {
249948
+ if (bytes < 1024) return `${bytes} B`;
249949
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
249950
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
249951
+ }
249952
+ async function confirmDeletion(prompt) {
249953
+ const interfaceInstance = readline6.createInterface({
249954
+ input: process.stdin,
249955
+ output: process.stdout
249956
+ });
249957
+ try {
249958
+ const answer = await new Promise(
249959
+ (resolve15) => interfaceInstance.question(prompt, resolve15)
249960
+ );
249961
+ return answer.trim() === "DELETE";
249962
+ } finally {
249963
+ interfaceInstance.close();
249964
+ }
249965
+ }
249966
+
249438
249967
  // src/index.ts
249439
- import { existsSync as existsSync35, realpathSync as realpathSync4, statSync as statSync8 } from "fs";
249440
- import { resolve as resolve12 } from "path";
249968
+ import { existsSync as existsSync31, realpathSync as realpathSync4, statSync as statSync7 } from "fs";
249969
+ import { resolve as resolve14 } from "path";
249441
249970
  var program = new Command();
249442
249971
  function applyOutcomeExitCode(outcome) {
249443
249972
  const currentExitCode = typeof process.exitCode === "number" ? process.exitCode : 0;
@@ -249467,6 +249996,25 @@ program.command("init").description("initialize ORBIT.md guidelines file").actio
249467
249996
  program.command("config").description("show resolved configurations").action(() => {
249468
249997
  runConfig(process.cwd());
249469
249998
  });
249999
+ program.command("clean").description("preview and remove Orbit-owned user or project data").option("--user", "include user data under ~/.orbit").option(
250000
+ "--project [path]",
250001
+ "include project data under <path>/.orbit (default: current directory)"
250002
+ ).option("--all", "include both user and current-project Orbit data").option("--yes", "apply without an interactive DELETE confirmation").option("--json", "print the versioned cleanup plan and result as JSON").action(async (options) => {
250003
+ await runClean(process.cwd(), {
250004
+ user: !!options.user,
250005
+ project: options.project,
250006
+ all: !!options.all,
250007
+ yes: !!options.yes,
250008
+ json: !!options.json
250009
+ });
250010
+ });
250011
+ program.command("update").description("check for and install the latest published Orbit CLI").option("--check", "check for an update without installing it").option("--yes", "install an available update without prompting").option("--json", "print a versioned machine-readable result").action(async (options) => {
250012
+ await runUpdate(readCliVersion(), {
250013
+ check: !!options.check,
250014
+ yes: !!options.yes,
250015
+ json: !!options.json
250016
+ });
250017
+ });
249470
250018
  program.command("login").description("manage secure provider logins and model catalogs").option("--list", "list saved provider logins").option("--delete <provider>", "delete a saved provider login").option("--service <provider>", "configure a provider profile").option("--name <name>", "set the provider display name").option(
249471
250019
  "--base-url <url>",
249472
250020
  "set the exact API base URL (include /v1 when required)"
@@ -249579,8 +250127,8 @@ program.command("webui").description("start Orbit as a browser-first local codin
249579
250127
  if (options.yes) {
249580
250128
  overrides.permissions = { mode: "auto" };
249581
250129
  }
249582
- const requestedCwd = resolve12(localOptions.cwd || process.cwd());
249583
- if (!existsSync35(requestedCwd) || !statSync8(requestedCwd).isDirectory()) {
250130
+ const requestedCwd = resolve14(localOptions.cwd || process.cwd());
250131
+ if (!existsSync31(requestedCwd) || !statSync7(requestedCwd).isDirectory()) {
249584
250132
  throw new Error(
249585
250133
  `Web UI project directory does not exist: ${requestedCwd}`
249586
250134
  );
@@ -249613,7 +250161,7 @@ try {
249613
250161
  } catch (error) {
249614
250162
  const message = error instanceof Error ? error.message : String(error);
249615
250163
  console.error(
249616
- picocolors23.red(`\u2716 Orbit command failed: ${redactSecrets(message)}`)
250164
+ picocolors25.red(`\u2716 Orbit command failed: ${redactSecrets(message)}`)
249617
250165
  );
249618
250166
  process.exitCode = 1;
249619
250167
  }