@orbit-build/cli 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -238208,6 +238208,81 @@ function generateId(prefix) {
238208
238208
  var HIDDEN_CHILD_PROCESS_OPTIONS = Object.freeze({
238209
238209
  windowsHide: true
238210
238210
  });
238211
+ var SAFE_CHILD_ENV_NAMES = new Set(
238212
+ [
238213
+ "ALLUSERSPROFILE",
238214
+ "APPDATA",
238215
+ "CI",
238216
+ "COLORTERM",
238217
+ "COMSPEC",
238218
+ "HOME",
238219
+ "HOMEDRIVE",
238220
+ "HOMEPATH",
238221
+ "LANG",
238222
+ "LOCALAPPDATA",
238223
+ "LOGNAME",
238224
+ "NUMBER_OF_PROCESSORS",
238225
+ "OS",
238226
+ "PATH",
238227
+ "PATHEXT",
238228
+ "PROCESSOR_ARCHITECTURE",
238229
+ "PROGRAMDATA",
238230
+ "PROGRAMFILES",
238231
+ "PROGRAMFILES(X86)",
238232
+ "PROGRAMW6432",
238233
+ "PUBLIC",
238234
+ "SYSTEMDRIVE",
238235
+ "SYSTEMROOT",
238236
+ "TEMP",
238237
+ "TERM",
238238
+ "TMP",
238239
+ "TMPDIR",
238240
+ "USER",
238241
+ "USERDOMAIN",
238242
+ "USERNAME",
238243
+ "USERPROFILE",
238244
+ "WINDIR",
238245
+ "XDG_CACHE_HOME",
238246
+ "XDG_CONFIG_HOME",
238247
+ "XDG_DATA_HOME"
238248
+ ].map((name) => name.toUpperCase())
238249
+ );
238250
+ var SENSITIVE_CHILD_ENV_NAME = /(?:^|_)(?:API_?KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|PRIVATE_?KEY|ACCESS_?KEY|AUTH(?:ORIZATION)?|COOKIE|SESSION_?ID)(?:$|_)/i;
238251
+ var SENSITIVE_CHILD_ENV_EXACT = /* @__PURE__ */ new Set([
238252
+ "AWS_WEB_IDENTITY_TOKEN_FILE",
238253
+ "AZURE_CONFIG_DIR",
238254
+ "GOOGLE_APPLICATION_CREDENTIALS",
238255
+ "GIT_ASKPASS",
238256
+ "GIT_SSH",
238257
+ "GIT_SSH_COMMAND",
238258
+ "KUBECONFIG",
238259
+ "SSH_AGENT_PID",
238260
+ "SSH_AUTH_SOCK"
238261
+ ]);
238262
+ function containsUrlCredential(name, value) {
238263
+ if (!/(?:^|_)(?:HTTP|HTTPS|ALL)_PROXY$/i.test(name)) return false;
238264
+ try {
238265
+ const url = new URL(value);
238266
+ return Boolean(url.username || url.password);
238267
+ } catch {
238268
+ return true;
238269
+ }
238270
+ }
238271
+ function buildSanitizedChildEnvironment(options = {}) {
238272
+ const source = options.source ?? process.env;
238273
+ const environment = {};
238274
+ for (const [name, value] of Object.entries(source)) {
238275
+ const upperName = name.toUpperCase();
238276
+ if (value !== void 0 && !upperName.startsWith("ORBIT_") && !SENSITIVE_CHILD_ENV_NAME.test(upperName) && !SENSITIVE_CHILD_ENV_EXACT.has(upperName) && !containsUrlCredential(upperName, value) && (options.mode !== "minimal" || SAFE_CHILD_ENV_NAMES.has(upperName) || upperName.startsWith("LC_"))) {
238277
+ environment[name] = value;
238278
+ }
238279
+ }
238280
+ for (const [name, value] of Object.entries(options.extra ?? {})) {
238281
+ if (value !== void 0) environment[name] = value;
238282
+ }
238283
+ environment.ORBIT_CHILD_PROCESS = "1";
238284
+ return environment;
238285
+ }
238211
238286
  function normalizePath(p) {
238212
238287
  return normalize(p).replace(/\\/g, "/");
238213
238288
  }
@@ -238388,14 +238463,59 @@ var SECRET_PATTERNS = [
238388
238463
  replacement: "$1$2$3***REDACTED***$3"
238389
238464
  }
238390
238465
  ];
238466
+ var REGISTERED_SECRET_LIMIT = 256;
238467
+ var registeredSecrets = /* @__PURE__ */ new Map();
238468
+ function registerSecretForRedaction(secret) {
238469
+ const normalized = secret.trim();
238470
+ if (normalized.length < 6) return;
238471
+ const references = registeredSecrets.get(normalized);
238472
+ if (references !== void 0) {
238473
+ registeredSecrets.set(normalized, references + 1);
238474
+ return;
238475
+ }
238476
+ if (registeredSecrets.size >= REGISTERED_SECRET_LIMIT) {
238477
+ const oldest = registeredSecrets.keys().next().value;
238478
+ if (typeof oldest === "string") registeredSecrets.delete(oldest);
238479
+ }
238480
+ registeredSecrets.set(normalized, 1);
238481
+ }
238482
+ function unregisterSecretForRedaction(secret) {
238483
+ const normalized = secret.trim();
238484
+ const references = registeredSecrets.get(normalized);
238485
+ if (references === void 0) return;
238486
+ if (references <= 1) registeredSecrets.delete(normalized);
238487
+ else registeredSecrets.set(normalized, references - 1);
238488
+ }
238391
238489
  function redactSecrets(text2) {
238392
238490
  if (!text2) return text2;
238393
238491
  let redacted = text2;
238492
+ for (const secret of [...registeredSecrets.keys()].sort(
238493
+ (left, right) => right.length - left.length
238494
+ )) {
238495
+ redacted = redacted.split(secret).join("***REDACTED***");
238496
+ }
238394
238497
  for (const { pattern, replacement } of SECRET_PATTERNS) {
238395
238498
  redacted = redacted.replace(pattern, replacement);
238396
238499
  }
238397
238500
  return redacted;
238398
238501
  }
238502
+ function redactSensitiveValue(value) {
238503
+ return redactUnknown(value, /* @__PURE__ */ new WeakSet());
238504
+ }
238505
+ function redactUnknown(value, seen) {
238506
+ if (typeof value === "string") return redactSecrets(value);
238507
+ if (Array.isArray(value))
238508
+ return value.map((item) => redactUnknown(item, seen));
238509
+ if (!value || typeof value !== "object") return value;
238510
+ if (seen.has(value)) return "[Circular]";
238511
+ seen.add(value);
238512
+ const redacted = {};
238513
+ for (const [key, item] of Object.entries(value)) {
238514
+ redacted[key] = redactUnknown(item, seen);
238515
+ }
238516
+ seen.delete(value);
238517
+ return redacted;
238518
+ }
238399
238519
  var ANSI_ESCAPE_PATTERN = /\u001b\[[0-?]*[ -/]*[@-~]/g;
238400
238520
  var CONTROL_CHARACTER_PATTERN = /[\u0000-\u0009\u000b\u000c\u000e-\u001f\u007f]+/g;
238401
238521
  function sanitizeExternalErrorMessage(value, options = {}) {
@@ -238808,7 +238928,7 @@ import { join as join4 } from "path";
238808
238928
  import { existsSync as existsSync22 } from "fs";
238809
238929
  import { parse } from "yaml";
238810
238930
  import { execFileSync as execFileSync2 } from "child_process";
238811
- import { chmodSync as chmodSync2, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
238931
+ import { chmodSync as chmodSync2, closeSync as closeSync2, openSync as openSync2, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
238812
238932
  import { join as join2 } from "path";
238813
238933
  import { homedir } from "os";
238814
238934
  import crypto from "crypto";
@@ -239074,9 +239194,20 @@ var ConfigSchema = z2.object({
239074
239194
  protectedPaths: z2.array(z2.string().min(1).max(4096)).max(1e3).default([
239075
239195
  ".env",
239076
239196
  ".env.*",
239197
+ ".git/**",
239198
+ ".orbit/**",
239199
+ ".npmrc",
239200
+ ".pypirc",
239201
+ ".netrc",
239077
239202
  "id_rsa",
239078
239203
  "id_ed25519",
239079
239204
  ".ssh/**",
239205
+ ".gnupg/**",
239206
+ ".aws/**",
239207
+ ".azure/**",
239208
+ ".config/gcloud/**",
239209
+ ".kube/**",
239210
+ "**/*.{key,pem,p12,pfx}",
239080
239211
  "**/*secret*",
239081
239212
  "**/*token*",
239082
239213
  "**/*credential*"
@@ -239277,9 +239408,20 @@ var DEFAULT_CONFIG = {
239277
239408
  protectedPaths: [
239278
239409
  ".env",
239279
239410
  ".env.*",
239411
+ ".git/**",
239412
+ ".orbit/**",
239413
+ ".npmrc",
239414
+ ".pypirc",
239415
+ ".netrc",
239280
239416
  "id_rsa",
239281
239417
  "id_ed25519",
239282
239418
  ".ssh/**",
239419
+ ".gnupg/**",
239420
+ ".aws/**",
239421
+ ".azure/**",
239422
+ ".config/gcloud/**",
239423
+ ".kube/**",
239424
+ "**/*.{key,pem,p12,pfx}",
239283
239425
  "**/*secret*",
239284
239426
  "**/*token*",
239285
239427
  "**/*credential*"
@@ -239568,25 +239710,22 @@ var EncryptedSecretSchema = z4.object({
239568
239710
  var MAX_SECRETS_FILE_BYTES = 2 * 1024 * 1024;
239569
239711
  var MAX_MASTER_KEY_FILE_BYTES = 1024;
239570
239712
  function windowsPowerShellEnvironment() {
239571
- const environment = { ...process.env };
239572
- for (const key of Object.keys(environment)) {
239573
- if (key.toLowerCase() === "psmodulepath") {
239574
- delete environment[key];
239575
- }
239576
- }
239577
- return environment;
239713
+ return buildSanitizedChildEnvironment({ mode: "minimal" });
239578
239714
  }
239579
239715
  var CredentialsManager = class {
239580
239716
  orbitDir;
239581
239717
  secretsPath;
239582
239718
  masterKeyPath;
239719
+ mutationLockPath;
239583
239720
  isWindows;
239584
239721
  keyStore;
239585
239722
  fallbackKey;
239723
+ registeredSecrets = /* @__PURE__ */ new Set();
239586
239724
  constructor(options = {}) {
239587
239725
  this.orbitDir = options.orbitDir ?? join2(homedir(), ".orbit");
239588
239726
  this.secretsPath = join2(this.orbitDir, "secrets.json");
239589
239727
  this.masterKeyPath = join2(this.orbitDir, "master.key");
239728
+ this.mutationLockPath = join2(this.orbitDir, "secrets.lock");
239590
239729
  const platform = options.platform ?? process.platform;
239591
239730
  this.isWindows = platform === "win32";
239592
239731
  this.keyStore = options.keyStore === void 0 ? platform === "darwin" ? new MacOSKeychainKeyStore() : platform === "linux" ? new LinuxSecretServiceKeyStore() : null : options.keyStore;
@@ -239598,10 +239737,16 @@ var CredentialsManager = class {
239598
239737
  storeSecret(key, value) {
239599
239738
  const validatedKey = CredentialKeySchema.parse(key);
239600
239739
  const validatedValue = CredentialValueSchema.parse(value);
239601
- const secrets = this.loadSecretsFile();
239602
- const encrypted = this.isWindows ? this.encryptWindows(validatedValue) : this.encryptFallback(validatedValue);
239603
- secrets[validatedKey] = encrypted;
239604
- this.saveSecretsFile(secrets);
239740
+ const previous = this.withMutationLock(() => {
239741
+ const secrets = this.loadSecretsFile();
239742
+ const previousValue = secrets[validatedKey] ? this.decryptStoredSecret(secrets[validatedKey]) : null;
239743
+ const encrypted = this.isWindows ? this.encryptWindows(validatedValue) : this.encryptFallback(validatedValue);
239744
+ secrets[validatedKey] = encrypted;
239745
+ this.saveSecretsFile(secrets);
239746
+ return previousValue;
239747
+ });
239748
+ if (previous && previous !== validatedValue) this.forgetSecret(previous);
239749
+ this.rememberSecret(validatedValue);
239605
239750
  }
239606
239751
  /**
239607
239752
  * Retrieve a securely stored secret value.
@@ -239613,7 +239758,9 @@ var CredentialsManager = class {
239613
239758
  const encrypted = secrets[validatedKey.data];
239614
239759
  if (!encrypted) return null;
239615
239760
  try {
239616
- return this.isWindows ? this.decryptWindows(encrypted) : this.decryptFallback(encrypted);
239761
+ const value = this.isWindows ? this.decryptWindows(encrypted) : this.decryptFallback(encrypted);
239762
+ this.rememberSecret(value);
239763
+ return value;
239617
239764
  } catch {
239618
239765
  return null;
239619
239766
  }
@@ -239622,13 +239769,17 @@ var CredentialsManager = class {
239622
239769
  deleteSecret(key) {
239623
239770
  const validatedKey = CredentialKeySchema.safeParse(key);
239624
239771
  if (!validatedKey.success) return false;
239625
- const secrets = this.loadSecretsFile();
239626
- if (!Object.prototype.hasOwnProperty.call(secrets, validatedKey.data)) {
239627
- return false;
239628
- }
239629
- delete secrets[validatedKey.data];
239630
- this.saveSecretsFile(secrets);
239631
- return true;
239772
+ return this.withMutationLock(() => {
239773
+ const secrets = this.loadSecretsFile();
239774
+ if (!Object.prototype.hasOwnProperty.call(secrets, validatedKey.data)) {
239775
+ return false;
239776
+ }
239777
+ const previous = this.decryptStoredSecret(secrets[validatedKey.data]);
239778
+ delete secrets[validatedKey.data];
239779
+ this.saveSecretsFile(secrets);
239780
+ if (previous) this.forgetSecret(previous);
239781
+ return true;
239782
+ });
239632
239783
  }
239633
239784
  /** Report whether a named secret exists without decrypting it. */
239634
239785
  hasSecret(key) {
@@ -239641,9 +239792,16 @@ var CredentialsManager = class {
239641
239792
  }
239642
239793
  /** Remove encrypted credentials and their platform key without revealing data. */
239643
239794
  purge() {
239644
- this.keyStore?.delete();
239645
- this.removeFileIfPresent(this.secretsPath);
239646
- this.removeFileIfPresent(this.masterKeyPath);
239795
+ this.withMutationLock(() => {
239796
+ this.keyStore?.delete();
239797
+ this.removeFileIfPresent(this.secretsPath);
239798
+ this.removeFileIfPresent(this.masterKeyPath);
239799
+ });
239800
+ for (const secret of this.registeredSecrets) {
239801
+ unregisterSecretForRedaction(secret);
239802
+ }
239803
+ this.registeredSecrets.clear();
239804
+ this.fallbackKey?.fill(0);
239647
239805
  this.fallbackKey = void 0;
239648
239806
  }
239649
239807
  loadSecretsFile() {
@@ -239654,9 +239812,16 @@ var CredentialsManager = class {
239654
239812
  );
239655
239813
  if (raw === void 0) return {};
239656
239814
  const parsed = SecretsFileSchema.safeParse(JSON.parse(raw));
239657
- return parsed.success ? parsed.data : {};
239658
- } catch {
239659
- return {};
239815
+ if (!parsed.success) {
239816
+ throw new Error("Credential store has an invalid schema.");
239817
+ }
239818
+ return parsed.data;
239819
+ } catch (error) {
239820
+ const detail = error instanceof Error ? error.message : String(error);
239821
+ throw new Error(
239822
+ `Orbit credential store is unreadable; it was preserved and will not be overwritten. Repair or restore ${this.secretsPath}. ${detail}`,
239823
+ { cause: error }
239824
+ );
239660
239825
  }
239661
239826
  }
239662
239827
  saveSecretsFile(secrets) {
@@ -239668,6 +239833,77 @@ var CredentialsManager = class {
239668
239833
  );
239669
239834
  this.restrictFilePermissions(this.secretsPath);
239670
239835
  }
239836
+ withMutationLock(operation, retried = false) {
239837
+ this.ensureOrbitDir();
239838
+ let descriptor;
239839
+ try {
239840
+ descriptor = openSync2(this.mutationLockPath, "wx", 384);
239841
+ } catch (error) {
239842
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST") {
239843
+ if (!retried && this.removeStaleMutationLock()) {
239844
+ return this.withMutationLock(operation, true);
239845
+ }
239846
+ throw new Error(
239847
+ "Orbit credential store is busy in another process. Retry after that credential operation completes.",
239848
+ { cause: error }
239849
+ );
239850
+ }
239851
+ throw error;
239852
+ }
239853
+ try {
239854
+ writeFileSync3(
239855
+ descriptor,
239856
+ `${JSON.stringify({ pid: process.pid, createdAt: (/* @__PURE__ */ new Date()).toISOString() })}
239857
+ `,
239858
+ "utf8"
239859
+ );
239860
+ return operation();
239861
+ } finally {
239862
+ try {
239863
+ closeSync2(descriptor);
239864
+ } finally {
239865
+ this.removeFileIfPresent(this.mutationLockPath);
239866
+ }
239867
+ }
239868
+ }
239869
+ removeStaleMutationLock() {
239870
+ try {
239871
+ const raw = readBoundedRegularFile(this.mutationLockPath, 4096);
239872
+ if (raw === void 0) return true;
239873
+ const payload = z4.object({
239874
+ pid: z4.number().int().positive(),
239875
+ createdAt: z4.string().datetime()
239876
+ }).parse(JSON.parse(raw));
239877
+ let processAlive = true;
239878
+ try {
239879
+ process.kill(payload.pid, 0);
239880
+ } catch (error) {
239881
+ processAlive = !(typeof error === "object" && error !== null && "code" in error && error.code === "ESRCH");
239882
+ }
239883
+ if (processAlive) return false;
239884
+ this.removeFileIfPresent(this.mutationLockPath);
239885
+ return true;
239886
+ } catch {
239887
+ return false;
239888
+ }
239889
+ }
239890
+ decryptStoredSecret(encrypted) {
239891
+ try {
239892
+ return this.isWindows ? this.decryptWindows(encrypted) : this.decryptFallback(encrypted);
239893
+ } catch {
239894
+ return null;
239895
+ }
239896
+ }
239897
+ rememberSecret(secret) {
239898
+ const normalized = secret.trim();
239899
+ if (normalized.length < 6 || this.registeredSecrets.has(normalized)) return;
239900
+ registerSecretForRedaction(normalized);
239901
+ this.registeredSecrets.add(normalized);
239902
+ }
239903
+ forgetSecret(secret) {
239904
+ unregisterSecretForRedaction(secret);
239905
+ this.registeredSecrets.delete(secret.trim());
239906
+ }
239671
239907
  // Windows DPAPI Encryption using PowerShell over stdin
239672
239908
  encryptWindows(plainText) {
239673
239909
  try {
@@ -239781,11 +240017,24 @@ var CredentialsManager = class {
239781
240017
  }
239782
240018
  }
239783
240019
  this.ensureOrbitDir();
239784
- writeFileSync3(this.masterKeyPath, generated.toString("base64"), {
239785
- encoding: "utf8",
239786
- mode: 384,
239787
- flag: "wx"
239788
- });
240020
+ try {
240021
+ writeFileSync3(this.masterKeyPath, generated.toString("base64"), {
240022
+ encoding: "utf8",
240023
+ mode: 384,
240024
+ flag: "wx"
240025
+ });
240026
+ } catch (error) {
240027
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST") {
240028
+ generated.fill(0);
240029
+ const concurrentKey = this.readMasterKeyFile();
240030
+ if (concurrentKey) {
240031
+ this.fallbackKey = concurrentKey;
240032
+ return concurrentKey;
240033
+ }
240034
+ }
240035
+ generated.fill(0);
240036
+ throw error;
240037
+ }
239789
240038
  this.restrictFilePermissions(this.masterKeyPath);
239790
240039
  this.fallbackKey = generated;
239791
240040
  return generated;
@@ -243058,10 +243307,10 @@ var DeepSeekAnthropicProvider = class {
243058
243307
  readLoop: while (true) {
243059
243308
  const { done, value } = await reader.read();
243060
243309
  resetStreamTimeout();
243061
- if (done) break;
243062
243310
  let accumulatedText = "";
243063
243311
  let accumulatedThinking = "";
243064
- const decoded = decoder.decode(value, { stream: true });
243312
+ const decoded = done ? `${decoder.decode()}${buffer.trim() ? "\n" : ""}` : decoder.decode(value, { stream: true });
243313
+ if (done && !decoded) break;
243065
243314
  totalStreamChars += decoded.length;
243066
243315
  if (totalStreamChars > MAX_STREAM_TOTAL_CHARS) {
243067
243316
  throw new Error(
@@ -243213,6 +243462,7 @@ var DeepSeekAnthropicProvider = class {
243213
243462
  if (accumulatedThinking) {
243214
243463
  yield { type: "thinking_delta", text: accumulatedThinking };
243215
243464
  }
243465
+ if (done) break;
243216
243466
  }
243217
243467
  if (isDeepSeekV4 && stopReason === null) {
243218
243468
  throw new Error(
@@ -243590,6 +243840,9 @@ async function* parseStreamingResponse(input, options, response, controller) {
243590
243840
  const { done, value } = await reader.read();
243591
243841
  resetTimeout();
243592
243842
  if (done) {
243843
+ const tail = decoder.decode().replace(/\r\n/g, "\n");
243844
+ totalChars += tail.length;
243845
+ buffer += tail;
243593
243846
  if (buffer.trim()) buffer += "\n\n";
243594
243847
  } else {
243595
243848
  const decoded = decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
@@ -244079,7 +244332,7 @@ var StreamingThinkParser = class {
244079
244332
  return events;
244080
244333
  }
244081
244334
  };
244082
- var DeepSeekOpenAIProvider = class {
244335
+ var DeepSeekOpenAIProvider = class _DeepSeekOpenAIProvider {
244083
244336
  constructor(apiKey, baseUrl = "https://api.deepseek.com", options = {}) {
244084
244337
  this.apiKey = apiKey;
244085
244338
  this.baseUrl = baseUrl;
@@ -244091,6 +244344,8 @@ var DeepSeekOpenAIProvider = class {
244091
244344
  apiKey;
244092
244345
  baseUrl;
244093
244346
  options;
244347
+ static RESPONSES_CIRCUIT_TTL_MS = 5 * 60 * 1e3;
244348
+ responsesEndpointCircuit;
244094
244349
  id = "deepseek-openai";
244095
244350
  type = "openai-compatible";
244096
244351
  capabilities = {
@@ -244238,17 +244493,9 @@ var DeepSeekOpenAIProvider = class {
244238
244493
  return;
244239
244494
  }
244240
244495
  const requestedApiFormat = this.options.deepSeekApiFormat ?? "chat-completions";
244241
- if (deepSeekV4Profile && requestedApiFormat === "responses" && !deepSeekV4Profile.supportsResponses) {
244242
- yield {
244243
- type: "error",
244244
- error: new Error(
244245
- `${deepSeekV4Profile.canonicalModel} does not yet support the DeepSeek Responses API. Use deepSeekApiFormat: chat-completions until official support is available.`
244246
- )
244247
- };
244248
- return;
244249
- }
244250
- const useResponses = deepSeekV4Profile?.supportsResponses === true && requestedApiFormat !== "chat-completions";
244251
- let responsesFallbackStatus;
244496
+ const circuitOpen = requestedApiFormat === "auto" && this.responsesEndpointCircuit !== void 0 && this.responsesEndpointCircuit.unavailableUntil > Date.now();
244497
+ const useResponses = deepSeekV4Profile?.supportsResponses === true && requestedApiFormat !== "chat-completions" && !circuitOpen;
244498
+ let responsesFallbackStatus = circuitOpen ? this.responsesEndpointCircuit?.status : void 0;
244252
244499
  if (useResponses && deepSeekV4Profile) {
244253
244500
  try {
244254
244501
  const responsesInput = {
@@ -244266,6 +244513,7 @@ var DeepSeekOpenAIProvider = class {
244266
244513
  profile: deepSeekV4Profile,
244267
244514
  requestModel: isOfficialDeepSeek ? deepSeekV4Profile.canonicalModel : input.model
244268
244515
  });
244516
+ this.responsesEndpointCircuit = void 0;
244269
244517
  return;
244270
244518
  } catch (error) {
244271
244519
  if (requestedApiFormat !== "auto" || !(error instanceof DeepSeekResponsesUnavailableError)) {
@@ -244276,6 +244524,10 @@ var DeepSeekOpenAIProvider = class {
244276
244524
  return;
244277
244525
  }
244278
244526
  responsesFallbackStatus = error.status;
244527
+ this.responsesEndpointCircuit = {
244528
+ status: error.status,
244529
+ unavailableUntil: Date.now() + _DeepSeekOpenAIProvider.RESPONSES_CIRCUIT_TTL_MS
244530
+ };
244279
244531
  }
244280
244532
  }
244281
244533
  let openaiMessages;
@@ -244561,10 +244813,10 @@ var DeepSeekOpenAIProvider = class {
244561
244813
  readLoop: while (true) {
244562
244814
  const { done, value } = await reader.read();
244563
244815
  resetStreamTimeout();
244564
- if (done) break;
244565
244816
  let accumulatedText = "";
244566
244817
  let accumulatedThinking = "";
244567
- const decoded = decoder.decode(value, { stream: true });
244818
+ const decoded = done ? `${decoder.decode()}${buffer.trim() ? "\n" : ""}` : decoder.decode(value, { stream: true });
244819
+ if (done && !decoded) break;
244568
244820
  totalStreamChars += decoded.length;
244569
244821
  if (totalStreamChars > MAX_STREAM_TOTAL_CHARS3) {
244570
244822
  throw new Error(
@@ -244712,6 +244964,7 @@ var DeepSeekOpenAIProvider = class {
244712
244964
  if (accumulatedThinking) {
244713
244965
  yield { type: "thinking_delta", text: accumulatedThinking };
244714
244966
  }
244967
+ if (done) break;
244715
244968
  }
244716
244969
  if (isDeepSeekV4 && finishReason === null) {
244717
244970
  throw new Error(
@@ -244951,11 +245204,11 @@ import { z as z10 } from "zod";
244951
245204
  import { z as z23 } from "zod";
244952
245205
  import { randomUUID as randomUUID3 } from "crypto";
244953
245206
  import {
244954
- closeSync as closeSync2,
245207
+ closeSync as closeSync3,
244955
245208
  existsSync as existsSync5,
244956
245209
  fsyncSync as fsyncSync2,
244957
245210
  mkdirSync as mkdirSync2,
244958
- openSync as openSync2,
245211
+ openSync as openSync3,
244959
245212
  renameSync as renameSync2,
244960
245213
  unlinkSync as unlinkSync2,
244961
245214
  writeFileSync as writeFileSync4
@@ -246637,10 +246890,10 @@ function atomicWriteWorkspaceFile(cwd, requestedPath, content, expectedCurrentCo
246637
246890
  const temporaryPath = join5(parent, `.orbit-write-${randomUUID3()}.tmp`);
246638
246891
  let descriptor;
246639
246892
  try {
246640
- descriptor = openSync2(temporaryPath, "wx", 384);
246893
+ descriptor = openSync3(temporaryPath, "wx", 384);
246641
246894
  writeFileSync4(descriptor, content, "utf8");
246642
246895
  fsyncSync2(descriptor);
246643
- closeSync2(descriptor);
246896
+ closeSync3(descriptor);
246644
246897
  descriptor = void 0;
246645
246898
  const revalidatedPath = resolveSafePath(cwd, requestedPath);
246646
246899
  if (revalidatedPath !== safePath) {
@@ -246649,7 +246902,7 @@ function atomicWriteWorkspaceFile(cwd, requestedPath, content, expectedCurrentCo
246649
246902
  assertExpectedContent(revalidatedPath, expectedCurrentContent);
246650
246903
  renameSync2(temporaryPath, revalidatedPath);
246651
246904
  } finally {
246652
- if (descriptor !== void 0) closeSync2(descriptor);
246905
+ if (descriptor !== void 0) closeSync3(descriptor);
246653
246906
  if (existsSync5(temporaryPath)) unlinkSync2(temporaryPath);
246654
246907
  }
246655
246908
  }
@@ -247756,13 +248009,14 @@ var GitCommitTool = class {
247756
248009
  const { stdout: stdout2 } = await execa("git", ["commit", "-m", commitMessage], {
247757
248010
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
247758
248011
  cwd: ctx.cwd,
248012
+ env: buildSanitizedChildEnvironment(),
247759
248013
  signal: ctx.abortSignal
247760
248014
  });
247761
248015
  return {
247762
248016
  ok: true,
247763
- data: stdout2,
248017
+ data: redactSecrets(stdout2),
247764
248018
  display: `Staged changes committed:
247765
- ${stdout2}`
248019
+ ${redactSecrets(stdout2)}`
247766
248020
  };
247767
248021
  } catch (error) {
247768
248022
  return {
@@ -247789,9 +248043,10 @@ var GitDiffTool = class {
247789
248043
  const { stdout: stdout2 } = await execa("git", args, {
247790
248044
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
247791
248045
  cwd: ctx.cwd,
248046
+ env: buildSanitizedChildEnvironment(),
247792
248047
  signal: ctx.abortSignal
247793
248048
  });
247794
- const bounded = LogTruncator.truncate(stdout2, 300, 4e4);
248049
+ const bounded = redactSecrets(LogTruncator.truncate(stdout2, 300, 4e4));
247795
248050
  return {
247796
248051
  ok: true,
247797
248052
  data: bounded,
@@ -247828,6 +248083,7 @@ var GitRestoreTool = class {
247828
248083
  {
247829
248084
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
247830
248085
  cwd: ctx.cwd,
248086
+ env: buildSanitizedChildEnvironment(),
247831
248087
  signal: ctx.abortSignal
247832
248088
  }
247833
248089
  );
@@ -247855,12 +248111,13 @@ var GitStatusTool = class {
247855
248111
  const { stdout: stdout2 } = await execa("git", ["status", "--short"], {
247856
248112
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
247857
248113
  cwd: ctx.cwd,
248114
+ env: buildSanitizedChildEnvironment(),
247858
248115
  signal: ctx.abortSignal
247859
248116
  });
247860
248117
  return {
247861
248118
  ok: true,
247862
- data: stdout2,
247863
- display: stdout2 ? stdout2 : "Working tree clean."
248119
+ data: redactSecrets(stdout2),
248120
+ display: stdout2 ? redactSecrets(stdout2) : "Working tree clean."
247864
248121
  };
247865
248122
  } catch (error) {
247866
248123
  return {
@@ -248383,6 +248640,7 @@ var BashTool = class {
248383
248640
  const result = await execa(invocation.file, invocation.args, {
248384
248641
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
248385
248642
  cwd: ctx.cwd,
248643
+ env: buildSanitizedChildEnvironment(),
248386
248644
  timeout,
248387
248645
  reject: false,
248388
248646
  signal: ctx.abortSignal,
@@ -248399,8 +248657,12 @@ var BashTool = class {
248399
248657
  const failureMessage = readProcessFailureMessage(result);
248400
248658
  const outputLimitExceeded = result.failed && /maxBuffer exceeded/i.test(failureMessage);
248401
248659
  const exitCode = result.exitCode ?? (result.failed ? 1 : 0);
248402
- const displayStdout = LogTruncator.truncate(stdout2, 150, 2e4);
248403
- const displayStderr = LogTruncator.truncate(stderr, 150, 2e4);
248660
+ const displayStdout = redactSecrets(
248661
+ LogTruncator.truncate(stdout2, 150, 2e4)
248662
+ );
248663
+ const displayStderr = redactSecrets(
248664
+ LogTruncator.truncate(stderr, 150, 2e4)
248665
+ );
248404
248666
  const truncated = outputLimitExceeded || stdout2.length !== displayStdout.length || stderr.length !== displayStderr.length;
248405
248667
  const display = [
248406
248668
  displayStdout ? `Stdout:
@@ -248508,6 +248770,7 @@ var RunTestsTool = class {
248508
248770
  const result = await execa(invocation.file, invocation.args, {
248509
248771
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
248510
248772
  cwd: ctx.cwd,
248773
+ env: buildSanitizedChildEnvironment(),
248511
248774
  reject: false,
248512
248775
  signal: ctx.abortSignal,
248513
248776
  timeout,
@@ -248524,8 +248787,12 @@ var RunTestsTool = class {
248524
248787
  const failureMessage = readProcessFailureMessage(result);
248525
248788
  const outputLimitExceeded = result.failed && /maxBuffer exceeded/i.test(failureMessage);
248526
248789
  const exitCode = result.exitCode ?? (result.failed ? 1 : 0);
248527
- const displayStdout = LogTruncator.truncate(stdout2, 150, 2e4);
248528
- const displayStderr = LogTruncator.truncate(stderr, 150, 2e4);
248790
+ const displayStdout = redactSecrets(
248791
+ LogTruncator.truncate(stdout2, 150, 2e4)
248792
+ );
248793
+ const displayStderr = redactSecrets(
248794
+ LogTruncator.truncate(stderr, 150, 2e4)
248795
+ );
248529
248796
  const truncated = outputLimitExceeded || displayStdout.length !== stdout2.length || displayStderr.length !== stderr.length;
248530
248797
  return {
248531
248798
  ok: !result.failed && exitCode === 0,
@@ -250091,6 +250358,7 @@ var BackgroundTaskRuntime = class {
250091
250358
  child = spawn(invocation.file, invocation.args, {
250092
250359
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
250093
250360
  cwd: safeCwd,
250361
+ env: buildSanitizedChildEnvironment(),
250094
250362
  detached: process.platform !== "win32",
250095
250363
  stdio: ["ignore", "pipe", "pipe"]
250096
250364
  });
@@ -250776,7 +251044,7 @@ var JSVectorStore = class {
250776
251044
  loaded = false;
250777
251045
  loading = null;
250778
251046
  cacheState = "uninitialized";
250779
- async addDocuments(docs) {
251047
+ async addDocuments(docs, persist = true) {
250780
251048
  if (!this.loaded) {
250781
251049
  await this.load();
250782
251050
  }
@@ -250813,9 +251081,9 @@ var JSVectorStore = class {
250813
251081
  );
250814
251082
  }
250815
251083
  this.documents = Array.from(docMap.values());
250816
- await this.save();
251084
+ if (persist) await this.save();
250817
251085
  }
250818
- async deleteByFilePath(filePath) {
251086
+ async deleteByFilePath(filePath, persist = true) {
250819
251087
  if (!this.loaded) {
250820
251088
  await this.load();
250821
251089
  }
@@ -250823,7 +251091,7 @@ var JSVectorStore = class {
250823
251091
  this.documents = this.documents.filter(
250824
251092
  (doc) => doc.metadata.filePath !== filePath
250825
251093
  );
250826
- if (this.documents.length !== originalLength) {
251094
+ if (persist && this.documents.length !== originalLength) {
250827
251095
  await this.save();
250828
251096
  }
250829
251097
  }
@@ -251068,7 +251336,7 @@ var BM25Store = class {
251068
251336
  loaded = false;
251069
251337
  loading = null;
251070
251338
  cacheState = "uninitialized";
251071
- async addDocuments(documents) {
251339
+ async addDocuments(documents, persist = true) {
251072
251340
  if (!this.loaded) {
251073
251341
  await this.load();
251074
251342
  }
@@ -251100,9 +251368,9 @@ var BM25Store = class {
251100
251368
  };
251101
251369
  }
251102
251370
  this.recalculateStats();
251103
- await this.save();
251371
+ if (persist) await this.save();
251104
251372
  }
251105
- async deleteByFilePath(filePath) {
251373
+ async deleteByFilePath(filePath, persist = true) {
251106
251374
  if (!this.loaded) {
251107
251375
  await this.load();
251108
251376
  }
@@ -251121,7 +251389,7 @@ var BM25Store = class {
251121
251389
  }
251122
251390
  if (changed) {
251123
251391
  this.recalculateStats();
251124
- await this.save();
251392
+ if (persist) await this.save();
251125
251393
  }
251126
251394
  }
251127
251395
  async search(query, limit) {
@@ -251286,6 +251554,8 @@ var HybridSearch = class {
251286
251554
  cwd;
251287
251555
  vectorStore;
251288
251556
  bm25Store;
251557
+ batchDepth = 0;
251558
+ batchChanged = false;
251289
251559
  /**
251290
251560
  * Load stores from disk.
251291
251561
  */
@@ -251306,17 +251576,32 @@ var HybridSearch = class {
251306
251576
  * Add documents to both vector and BM25 stores.
251307
251577
  */
251308
251578
  async addDocuments(docs) {
251309
- await this.vectorStore.addDocuments(docs);
251310
- await this.bm25Store.addDocuments(docs);
251579
+ const persist = this.batchDepth === 0;
251580
+ await this.vectorStore.addDocuments(docs, persist);
251581
+ await this.bm25Store.addDocuments(docs, persist);
251582
+ if (!persist) this.batchChanged = true;
251311
251583
  }
251312
251584
  /**
251313
251585
  * Incremental clean: delete old indices for a file path.
251314
251586
  */
251315
251587
  async deleteByFilePath(filePath) {
251588
+ const persist = this.batchDepth === 0;
251316
251589
  await Promise.all([
251317
- this.vectorStore.deleteByFilePath(filePath),
251318
- this.bm25Store.deleteByFilePath(filePath)
251590
+ this.vectorStore.deleteByFilePath(filePath, persist),
251591
+ this.bm25Store.deleteByFilePath(filePath, persist)
251319
251592
  ]);
251593
+ if (!persist) this.batchChanged = true;
251594
+ }
251595
+ /** Defer persistence so one indexing generation performs one save per store. */
251596
+ beginBatch() {
251597
+ this.batchDepth += 1;
251598
+ }
251599
+ async commitBatch() {
251600
+ if (this.batchDepth === 0) return;
251601
+ this.batchDepth -= 1;
251602
+ if (this.batchDepth > 0 || !this.batchChanged) return;
251603
+ this.batchChanged = false;
251604
+ await Promise.all([this.vectorStore.save(), this.bm25Store.save()]);
251320
251605
  }
251321
251606
  /**
251322
251607
  * Performs hybrid search using Reciprocal Rank Fusion (RRF).
@@ -251380,7 +251665,31 @@ var HybridSearch = class {
251380
251665
  var TYPESCRIPT_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".tsx", ".mts", ".cts"]);
251381
251666
  var JAVASCRIPT_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".jsx", ".mjs", ".cjs"]);
251382
251667
  var PYTHON_EXTENSIONS = /* @__PURE__ */ new Set([".py", ".pyw"]);
251383
- var INDEXED_SOURCE_GLOB = "**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,py,pyw}";
251668
+ var GENERIC_LANGUAGE_BY_EXTENSION = {
251669
+ ".go": "go",
251670
+ ".rs": "rust",
251671
+ ".java": "java",
251672
+ ".cs": "csharp",
251673
+ ".c": "cpp",
251674
+ ".h": "cpp",
251675
+ ".cc": "cpp",
251676
+ ".cpp": "cpp",
251677
+ ".cxx": "cpp",
251678
+ ".hpp": "cpp",
251679
+ ".sql": "sql",
251680
+ ".md": "text",
251681
+ ".mdx": "text",
251682
+ ".json": "text",
251683
+ ".yaml": "text",
251684
+ ".yml": "text",
251685
+ ".toml": "text",
251686
+ ".sh": "text",
251687
+ ".bash": "text",
251688
+ ".ps1": "text",
251689
+ ".css": "text",
251690
+ ".scss": "text"
251691
+ };
251692
+ var INDEXED_SOURCE_GLOB = "**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,py,pyw,go,rs,java,cs,c,h,cc,cpp,cxx,hpp,sql,md,mdx,sh,bash,ps1,css,scss}";
251384
251693
  function parseSourceFile(content, filePath) {
251385
251694
  const extension = extname22(filePath).toLowerCase();
251386
251695
  if (PYTHON_EXTENSIONS.has(extension)) {
@@ -251393,8 +251702,64 @@ function parseSourceFile(content, filePath) {
251393
251702
  TYPESCRIPT_EXTENSIONS.has(extension) ? "typescript" : "javascript"
251394
251703
  );
251395
251704
  }
251705
+ const genericLanguage = GENERIC_LANGUAGE_BY_EXTENSION[extension];
251706
+ if (genericLanguage) return parseGenericSource(content, genericLanguage);
251396
251707
  throw new Error(`Unsupported source extension "${extension}".`);
251397
251708
  }
251709
+ function parseGenericSource(content, language) {
251710
+ if (language === "text") return { language, symbols: [], imports: [] };
251711
+ const symbols = [];
251712
+ const imports = [];
251713
+ const declarationPatterns = language === "go" ? [
251714
+ ["function", /^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)\s*\(/],
251715
+ ["type", /^\s*type\s+([A-Za-z_]\w*)\s+/],
251716
+ ["constant", /^\s*const\s+([A-Za-z_]\w*)\b/]
251717
+ ] : language === "rust" ? [
251718
+ ["function", /^\s*(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)\b/],
251719
+ ["class", /^\s*(?:pub\s+)?struct\s+([A-Za-z_]\w*)\b/],
251720
+ ["type", /^\s*(?:pub\s+)?(?:enum|type)\s+([A-Za-z_]\w*)\b/],
251721
+ ["interface", /^\s*(?:pub\s+)?trait\s+([A-Za-z_]\w*)\b/],
251722
+ ["constant", /^\s*(?:pub\s+)?const\s+([A-Za-z_]\w*)\b/]
251723
+ ] : language === "sql" ? [
251724
+ [
251725
+ "type",
251726
+ /^\s*create\s+(?:or\s+replace\s+)?(?:table|view)\s+([\w.]+)/i
251727
+ ],
251728
+ [
251729
+ "function",
251730
+ /^\s*create\s+(?:or\s+replace\s+)?(?:function|procedure)\s+([\w.]+)/i
251731
+ ]
251732
+ ] : [
251733
+ [
251734
+ "class",
251735
+ /^\s*(?:public\s+|private\s+|protected\s+|internal\s+|static\s+|abstract\s+|final\s+)*class\s+([A-Za-z_]\w*)\b/
251736
+ ],
251737
+ [
251738
+ "interface",
251739
+ /^\s*(?:public\s+|private\s+|protected\s+|internal\s+)*interface\s+([A-Za-z_]\w*)\b/
251740
+ ],
251741
+ [
251742
+ "type",
251743
+ /^\s*(?:public\s+|private\s+|protected\s+|internal\s+)*(?:enum|record|struct)\s+([A-Za-z_]\w*)\b/
251744
+ ]
251745
+ ];
251746
+ for (const [index, line] of content.split(/\r?\n/).entries()) {
251747
+ for (const [type, pattern] of declarationPatterns) {
251748
+ const match = pattern.exec(line);
251749
+ if (match?.[1]) {
251750
+ symbols.push({ name: match[1], type, line: index + 1 });
251751
+ break;
251752
+ }
251753
+ }
251754
+ const importMatch = language === "go" ? /^\s*import\s+(?:[A-Za-z_]+\s+)?["`]([^"`]+)["`]/.exec(line) : language === "rust" ? /^\s*use\s+([^;]+);/.exec(line) : /^\s*(?:import|using|#include)\s+[<"]?([^;>"]+)/.exec(line);
251755
+ if (importMatch?.[1]) imports.push(importMatch[1].trim());
251756
+ }
251757
+ return {
251758
+ language,
251759
+ symbols: deduplicateSymbols(symbols),
251760
+ imports: Array.from(new Set(imports))
251761
+ };
251762
+ }
251398
251763
  function parseTypeScriptSource(content, filePath, language) {
251399
251764
  const symbols = [];
251400
251765
  const imports = [];
@@ -251555,6 +251920,24 @@ function deduplicateSymbols(symbols) {
251555
251920
  });
251556
251921
  }
251557
251922
  var inFlightIndexes = /* @__PURE__ */ new Map();
251923
+ var EMBEDDING_BATCH_MAX_ITEMS = 64;
251924
+ var EMBEDDING_BATCH_MAX_CHARS = 12e4;
251925
+ function embeddingBatches(texts) {
251926
+ const batches = [];
251927
+ let current = [];
251928
+ let characters = 0;
251929
+ for (const text2 of texts) {
251930
+ if (current.length > 0 && (current.length >= EMBEDDING_BATCH_MAX_ITEMS || characters + text2.length > EMBEDDING_BATCH_MAX_CHARS)) {
251931
+ batches.push(current);
251932
+ current = [];
251933
+ characters = 0;
251934
+ }
251935
+ current.push(text2);
251936
+ characters += text2.length;
251937
+ }
251938
+ if (current.length > 0) batches.push(current);
251939
+ return batches;
251940
+ }
251558
251941
  function workspaceIndexKey(cwd) {
251559
251942
  const absolute = resolve3(cwd).replace(/\\/g, "/");
251560
251943
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
@@ -251625,7 +252008,18 @@ var FileIndexSchema = z43.object({
251625
252008
  size: z43.number().int().nonnegative().optional(),
251626
252009
  symbols: z43.array(SymbolEntrySchema).max(5e4),
251627
252010
  imports: z43.array(z43.string().max(4096)).max(2e4).optional(),
251628
- language: z43.enum(["typescript", "javascript", "python"]).optional()
252011
+ language: z43.enum([
252012
+ "typescript",
252013
+ "javascript",
252014
+ "python",
252015
+ "go",
252016
+ "rust",
252017
+ "java",
252018
+ "csharp",
252019
+ "cpp",
252020
+ "sql",
252021
+ "text"
252022
+ ]).optional()
251629
252023
  });
251630
252024
  var SymbolIndexSchema2 = z43.object({
251631
252025
  version: z43.number().int().positive().default(1),
@@ -251648,6 +252042,7 @@ var PackageJsonSchema = z43.object({
251648
252042
  });
251649
252043
  var SYMBOL_INDEX_MAX_BYTES = 256 * 1024 * 1024;
251650
252044
  var EMBEDDING_CACHE_MAX_BYTES = 256 * 1024 * 1024;
252045
+ var EMBEDDING_CACHE_MAX_ENTRIES = 5e4;
251651
252046
  var SYMBOL_INDEX_VERSION = 2;
251652
252047
  var EmbeddingCache = class {
251653
252048
  constructor(cwd, modelName) {
@@ -251673,6 +252068,7 @@ var EmbeddingCache = class {
251673
252068
  const parsed = EmbeddingCacheFileSchema.safeParse(JSON.parse(raw));
251674
252069
  if (parsed.success && parsed.data.model === this.modelName) {
251675
252070
  this.cache = parsed.data.cache;
252071
+ this.trim();
251676
252072
  } else {
251677
252073
  this.cache = {};
251678
252074
  }
@@ -251708,14 +252104,28 @@ var EmbeddingCache = class {
251708
252104
  }
251709
252105
  get(text2) {
251710
252106
  const hash2 = createHash3("sha256").update(text2).digest("hex");
251711
- return this.cache[hash2];
252107
+ const vector = this.cache[hash2];
252108
+ if (vector) {
252109
+ delete this.cache[hash2];
252110
+ this.cache[hash2] = vector;
252111
+ }
252112
+ return vector;
251712
252113
  }
251713
252114
  set(text2, vector) {
251714
252115
  if (vector.length === 0 || vector.length > 32768 || vector.some((value) => !Number.isFinite(value))) {
251715
252116
  return;
251716
252117
  }
251717
252118
  const hash2 = createHash3("sha256").update(text2).digest("hex");
252119
+ delete this.cache[hash2];
251718
252120
  this.cache[hash2] = vector;
252121
+ this.trim();
252122
+ }
252123
+ trim() {
252124
+ const hashes = Object.keys(this.cache);
252125
+ const excess = hashes.length - EMBEDDING_CACHE_MAX_ENTRIES;
252126
+ for (let index = 0; index < excess; index += 1) {
252127
+ delete this.cache[hashes[index]];
252128
+ }
251719
252129
  }
251720
252130
  };
251721
252131
  function getEmbeddingProvider(config) {
@@ -251845,6 +252255,7 @@ var SymbolIndexer = class {
251845
252255
  const maxFileBytes = config.context.maxFileSizeKb * 1024;
251846
252256
  let changed = false;
251847
252257
  let i2 = 0;
252258
+ hybridSearch.beginBatch();
251848
252259
  for (const relativePath of slicedFiles) {
251849
252260
  i2++;
251850
252261
  if (i2 % 50 === 0) {
@@ -251885,9 +252296,14 @@ var SymbolIndexer = class {
251885
252296
  try {
251886
252297
  const embeddingModel2 = config.models?.embedding || "text-embedding-3-small";
251887
252298
  const embed = provider.embed.bind(provider);
251888
- const vectors = await embed(uncachedTexts, {
251889
- model: embeddingModel2
251890
- });
252299
+ const vectors = [];
252300
+ for (const batch of embeddingBatches(uncachedTexts)) {
252301
+ vectors.push(
252302
+ ...await embed(batch, {
252303
+ model: embeddingModel2
252304
+ })
252305
+ );
252306
+ }
251891
252307
  let vectorIdx = 0;
251892
252308
  for (const chunk of chunks) {
251893
252309
  if (!chunk.vector) {
@@ -251942,6 +252358,7 @@ var SymbolIndexer = class {
251942
252358
  }
251943
252359
  embedCache.save();
251944
252360
  }
252361
+ await hybridSearch.commitBatch();
251945
252362
  } catch {
251946
252363
  }
251947
252364
  }
@@ -252123,7 +252540,7 @@ var SymbolIndexer = class {
252123
252540
  if (!currentOutput) {
252124
252541
  currentOutput = buildOutput();
252125
252542
  }
252126
- return currentOutput;
252543
+ return truncateTextToTokenBudget(currentOutput, tokenLimit);
252127
252544
  } catch {
252128
252545
  return "";
252129
252546
  }
@@ -252869,11 +253286,11 @@ function selectSkills(skills, userQuery, config) {
252869
253286
  const query = normalize2(userQuery || "");
252870
253287
  if (!query || config.maxActive <= 0) return [];
252871
253288
  const queryTerms = terms(query);
252872
- return skills.filter((skill) => !skill.disabled).map((skill) => {
253289
+ const ranked = skills.filter((skill) => !skill.disabled).map((skill) => {
252873
253290
  const name = skill.name.toLowerCase();
252874
- const explicit = hasExplicitMarker(query, name);
252875
- let score = explicit ? EXPLICIT_SCORE : 0;
252876
- if (!explicit && config.activation === "auto" && skill.allowImplicitInvocation) {
253291
+ const explicit2 = hasExplicitMarker(query, name);
253292
+ let score = explicit2 ? EXPLICIT_SCORE : 0;
253293
+ if (!explicit2 && config.activation === "auto" && skill.allowImplicitInvocation) {
252877
253294
  const metadata = normalize2(`${skill.name} ${skill.description}`);
252878
253295
  const metadataTerms = new Set(terms(metadata));
252879
253296
  for (const term of queryTerms) {
@@ -252884,18 +253301,23 @@ function selectSkills(skills, userQuery, config) {
252884
253301
  if (mentionsName(query, name)) score += NAME_MENTION_SCORE;
252885
253302
  if (score < MIN_AUTO_SCORE) score = 0;
252886
253303
  }
252887
- return { skill, explicit, score };
253304
+ return { skill, explicit: explicit2, score };
252888
253305
  }).filter(({ score }) => score > 0).sort(
252889
253306
  (left, right) => right.score - left.score || left.skill.name.localeCompare(right.skill.name)
252890
- ).slice(0, config.maxActive).map(({ skill, explicit }) => {
252891
- const limit = explicit ? config.maxSkillBytes : Math.min(config.maxAutoSkillBytes, config.maxSkillBytes);
253307
+ );
253308
+ const explicit = ranked.filter((candidate) => candidate.explicit);
253309
+ const automatic = ranked.filter((candidate) => !candidate.explicit).slice(0, Math.max(0, config.maxActive - explicit.length));
253310
+ return [...explicit, ...automatic].sort(
253311
+ (left, right) => right.score - left.score || left.skill.name.localeCompare(right.skill.name)
253312
+ ).map(({ skill, explicit: explicit2 }) => {
253313
+ const limit = explicit2 ? config.maxSkillBytes : Math.min(config.maxAutoSkillBytes, config.maxSkillBytes);
252892
253314
  const bounded = truncateUtf8(skill.content, limit);
252893
253315
  return {
252894
253316
  name: skill.name,
252895
253317
  description: skill.description,
252896
253318
  path: skill.path,
252897
253319
  content: bounded.text,
252898
- activation: explicit ? "explicit" : "auto",
253320
+ activation: explicit2 ? "explicit" : "auto",
252899
253321
  loadedBytes: bounded.bytes,
252900
253322
  truncated: skill.truncated || bounded.truncated,
252901
253323
  rootDir: skill.rootDir
@@ -253179,6 +253601,8 @@ function describe2(error) {
253179
253601
  }
253180
253602
  var SKILLS_CACHE_TTL_MS = 3e4;
253181
253603
  var PROJECT_INSTRUCTIONS_MAX_BYTES = 1024 * 1024;
253604
+ var MAX_RELEVANT_FILES = 64;
253605
+ var FILE_SUMMARY_CONCURRENCY = 8;
253182
253606
  var ContextPackBuilder = class {
253183
253607
  constructor(cwd) {
253184
253608
  this.cwd = cwd;
@@ -253211,8 +253635,10 @@ var ContextPackBuilder = class {
253211
253635
  this.retrieval
253212
253636
  ).retrieve(userQuery, config, retrievalMode);
253213
253637
  }
253214
- const packedFilesPromise = Promise.all(
253215
- relevantFiles.map(async (f) => {
253638
+ const packedFilesPromise = mapWithConcurrency(
253639
+ relevantFiles.slice(0, MAX_RELEVANT_FILES),
253640
+ FILE_SUMMARY_CONCURRENCY,
253641
+ async (f) => {
253216
253642
  const { summary, excerpt } = await this.summarizer.summarize(f.path);
253217
253643
  return {
253218
253644
  path: f.path,
@@ -253221,7 +253647,7 @@ var ContextPackBuilder = class {
253221
253647
  excerpt,
253222
253648
  readOnly: f.readOnly
253223
253649
  };
253224
- })
253650
+ }
253225
253651
  );
253226
253652
  const [
253227
253653
  projectIndex,
@@ -253239,17 +253665,19 @@ var ContextPackBuilder = class {
253239
253665
  const maxTokens = Math.max(256, Math.floor(options.maxTokens ?? 128e3));
253240
253666
  const fitted = this.fitContextToBudget(
253241
253667
  {
253668
+ projectIndex,
253669
+ skillsIndex: skills.index,
253242
253670
  projectInstructions,
253243
253671
  codebaseContext,
253244
253672
  packedFiles,
253245
253673
  activeSkills: skills.active
253246
253674
  },
253247
- { projectIndex, skillsIndex: skills.index, maxTokens }
253675
+ { maxTokens }
253248
253676
  );
253249
253677
  return {
253250
253678
  projectInstructions: fitted.projectInstructions,
253251
- projectIndex,
253252
- skillsIndex: skills.index,
253679
+ projectIndex: fitted.projectIndex,
253680
+ skillsIndex: fitted.skillsIndex,
253253
253681
  activeSkills: fitted.activeSkills,
253254
253682
  skillDiagnostics: skills.diagnostics,
253255
253683
  relevantFiles: fitted.packedFiles,
@@ -253279,11 +253707,11 @@ var ContextPackBuilder = class {
253279
253707
  const fitted = structuredClone(source);
253280
253708
  const estimate = () => estimateTokenCount(
253281
253709
  JSON.stringify({
253282
- projectIndex: metadata.projectIndex,
253710
+ projectIndex: fitted.projectIndex,
253283
253711
  projectInstructions: fitted.projectInstructions,
253284
253712
  packedFiles: fitted.packedFiles,
253285
253713
  codebaseContext: fitted.codebaseContext,
253286
- skillsIndex: metadata.skillsIndex,
253714
+ skillsIndex: fitted.skillsIndex,
253287
253715
  activeSkills: fitted.activeSkills
253288
253716
  })
253289
253717
  );
@@ -253327,6 +253755,39 @@ var ContextPackBuilder = class {
253327
253755
  if (nextEstimate >= usedEstimate) break;
253328
253756
  usedEstimate = nextEstimate;
253329
253757
  }
253758
+ while (usedEstimate > metadata.maxTokens && fitted.packedFiles.length > 0) {
253759
+ fitted.packedFiles.pop();
253760
+ usedEstimate = estimate();
253761
+ }
253762
+ while (usedEstimate > metadata.maxTokens) {
253763
+ const automaticIndex = fitted.activeSkills.findIndex(
253764
+ (skill) => skill.activation === "auto"
253765
+ );
253766
+ if (automaticIndex < 0) break;
253767
+ fitted.activeSkills.splice(automaticIndex, 1);
253768
+ usedEstimate = estimate();
253769
+ }
253770
+ while (usedEstimate > metadata.maxTokens && fitted.skillsIndex.length > 0) {
253771
+ fitted.skillsIndex.pop();
253772
+ usedEstimate = estimate();
253773
+ }
253774
+ if (usedEstimate > metadata.maxTokens) {
253775
+ fitted.codebaseContext = void 0;
253776
+ fitted.projectInstructions = "";
253777
+ fitted.projectIndex = {
253778
+ ...fitted.projectIndex,
253779
+ root: ".",
253780
+ entrypoints: fitted.projectIndex.entrypoints.slice(0, 8),
253781
+ importantFiles: fitted.projectIndex.importantFiles.slice(0, 8),
253782
+ ignoredFiles: []
253783
+ };
253784
+ usedEstimate = estimate();
253785
+ }
253786
+ if (usedEstimate > metadata.maxTokens) {
253787
+ throw new Error(
253788
+ `Context metadata requires ${usedEstimate} estimated tokens, exceeding the hard budget of ${metadata.maxTokens}.`
253789
+ );
253790
+ }
253330
253791
  return { ...fitted, usedEstimate };
253331
253792
  }
253332
253793
  async loadInstructions() {
@@ -253387,6 +253848,19 @@ var ContextPackBuilder = class {
253387
253848
  };
253388
253849
  }
253389
253850
  };
253851
+ async function mapWithConcurrency(values, concurrency, mapper) {
253852
+ const results = new Array(values.length);
253853
+ let next = 0;
253854
+ await Promise.all(
253855
+ Array.from({ length: Math.min(concurrency, values.length) }, async () => {
253856
+ while (next < values.length) {
253857
+ const index = next++;
253858
+ results[index] = await mapper(values[index]);
253859
+ }
253860
+ })
253861
+ );
253862
+ return results;
253863
+ }
253390
253864
 
253391
253865
  // ../core/dist/index.js
253392
253866
  import { randomUUID as randomUUID7 } from "crypto";
@@ -253399,7 +253873,7 @@ import fs32 from "fs";
253399
253873
  import { randomUUID as randomUUID52 } from "crypto";
253400
253874
  import { exec as exec2, execFile as execFile3 } from "child_process";
253401
253875
  import { promisify as promisify3 } from "util";
253402
- import { z as z45 } from "zod";
253876
+ import { z as z46 } from "zod";
253403
253877
  import fs5 from "fs";
253404
253878
  import path5 from "path";
253405
253879
  import { exec, execFile as execFile4 } from "child_process";
@@ -255359,6 +255833,10 @@ var NETWORK_COMMAND_REGEXES = [
255359
255833
  /\bwget\b/i,
255360
255834
  /\binvoke-webrequest\b/i,
255361
255835
  /\binvoke-restmethod\b/i,
255836
+ /\b(?:iwr|irm)\b/i,
255837
+ /\bnpx\b/i,
255838
+ /\bpnpm\s+dlx\b/i,
255839
+ /\bbunx\b/i,
255362
255840
  /\bnpm\s+install\b/i,
255363
255841
  /\bnpm\s+publish\b/i,
255364
255842
  /\bpnpm\s+install\b/i,
@@ -255367,10 +255845,16 @@ var NETWORK_COMMAND_REGEXES = [
255367
255845
  /\byarn\s+install\b/i,
255368
255846
  /\byarn\s+add\b/i,
255369
255847
  /\byarn\s+publish\b/i,
255370
- /\bpip\s+install\b/i,
255848
+ /\b(?:pip|pip3|uv\s+pip)\s+install\b/i,
255849
+ /\buv\s+(?:tool\s+install|runx|x)\b/i,
255850
+ /\bcargo\s+install\b/i,
255851
+ /\bgo\s+install\b/i,
255371
255852
  /\bgo\s+get\b/i,
255372
- /\bgit\s+(?:fetch|pull|push|clone)\b/i,
255373
- /\bgh\s+(?:api|pr|issue|release|repo|workflow|run)\b/i
255853
+ /\bgit\s+(?:fetch|pull|push|clone|ls-remote|submodule\s+(?:add|update))\b/i,
255854
+ /\bgh\s+(?:api|auth|pr|issue|release|repo|workflow|run)\b/i,
255855
+ /\bdocker\s+(?:pull|push|login|buildx)\b/i,
255856
+ /\bpodman\s+(?:pull|push|login)\b/i,
255857
+ /\b(?:ssh|scp|sftp|rsync)\b/i
255374
255858
  ];
255375
255859
  var RiskClassifier = class {
255376
255860
  static isProtectedPath(filePath, protectedPaths) {
@@ -255909,12 +256393,12 @@ import { createCipheriv, createDecipheriv, randomBytes as randomBytes2 } from "c
255909
256393
  import { z as z28 } from "zod";
255910
256394
  import { randomBytes as randomBytes22 } from "crypto";
255911
256395
  import {
255912
- closeSync as closeSync3,
256396
+ closeSync as closeSync4,
255913
256397
  existsSync as existsSync25,
255914
256398
  fsyncSync as fsyncSync3,
255915
256399
  lstatSync as lstatSync22,
255916
256400
  mkdirSync as mkdirSync22,
255917
- openSync as openSync3,
256401
+ openSync as openSync4,
255918
256402
  renameSync as renameSync22,
255919
256403
  rmSync as rmSync22,
255920
256404
  statSync,
@@ -256298,30 +256782,30 @@ var RollbackManager = class {
256298
256782
  const existingMode = existsSync25(path24) ? statSync(path24).mode : void 0;
256299
256783
  let descriptor;
256300
256784
  try {
256301
- descriptor = openSync3(
256785
+ descriptor = openSync4(
256302
256786
  temporaryPath,
256303
256787
  "wx",
256304
256788
  existingMode === void 0 ? 438 : existingMode
256305
256789
  );
256306
256790
  writeFileSync6(descriptor, content);
256307
256791
  fsyncSync3(descriptor);
256308
- closeSync3(descriptor);
256792
+ closeSync4(descriptor);
256309
256793
  descriptor = void 0;
256310
256794
  renameSync22(temporaryPath, path24);
256311
256795
  this.fsyncParentDirectory(dirname7(path24));
256312
256796
  } finally {
256313
- if (descriptor !== void 0) closeSync3(descriptor);
256797
+ if (descriptor !== void 0) closeSync4(descriptor);
256314
256798
  rmSync22(temporaryPath, { force: true });
256315
256799
  }
256316
256800
  }
256317
256801
  fsyncParentDirectory(directory) {
256318
256802
  let descriptor;
256319
256803
  try {
256320
- descriptor = openSync3(directory, "r");
256804
+ descriptor = openSync4(directory, "r");
256321
256805
  fsyncSync3(descriptor);
256322
256806
  } catch {
256323
256807
  } finally {
256324
- if (descriptor !== void 0) closeSync3(descriptor);
256808
+ if (descriptor !== void 0) closeSync4(descriptor);
256325
256809
  }
256326
256810
  }
256327
256811
  };
@@ -256605,30 +257089,31 @@ import { z as z29 } from "zod";
256605
257089
  import { createHash as createHash5, randomUUID as randomUUID6 } from "crypto";
256606
257090
  import { dirname as dirname8, isAbsolute as isAbsolute4, join as join9, relative as relative4, resolve as resolve7, sep } from "path";
256607
257091
  import {
256608
- appendFileSync,
256609
- closeSync as closeSync4,
257092
+ closeSync as closeSync5,
256610
257093
  existsSync as existsSync10,
256611
257094
  fsyncSync as fsyncSync4,
256612
257095
  lstatSync as lstatSync5,
256613
257096
  mkdirSync as mkdirSync5,
256614
- openSync as openSync4,
257097
+ openSync as openSync5,
256615
257098
  readdirSync as readdirSync3,
256616
257099
  renameSync as renameSync5,
256617
257100
  rmSync as rmSync4,
257101
+ statSync as statSync2,
256618
257102
  writeFileSync as writeFileSync7
256619
257103
  } from "fs";
257104
+ import { z as z210 } from "zod";
256620
257105
  import { createHash as createHash23 } from "crypto";
256621
257106
  import {
256622
257107
  closeSync as closeSync22,
256623
257108
  lstatSync as lstatSync23,
256624
257109
  openSync as openSync22,
256625
257110
  realpathSync as realpathSync2,
256626
- statSync as statSync2,
257111
+ statSync as statSync22,
256627
257112
  unlinkSync as unlinkSync4
256628
257113
  } from "fs";
256629
257114
  import { homedir as homedir5 } from "os";
256630
257115
  import { basename as basename2, dirname as dirname23, isAbsolute as isAbsolute23, join as join25, parse as parse2, resolve as resolve24 } from "path";
256631
- import { z as z210 } from "zod";
257116
+ import { z as z37 } from "zod";
256632
257117
  import {
256633
257118
  closeSync as closeSync32,
256634
257119
  existsSync as existsSync26,
@@ -256639,7 +257124,7 @@ import {
256639
257124
  unlinkSync as unlinkSync22
256640
257125
  } from "fs";
256641
257126
  import { basename as basename22, join as join34, resolve as resolve32 } from "path";
256642
- import { z as z37 } from "zod";
257127
+ import { z as z45 } from "zod";
256643
257128
  var SafeObjectKeySchema = z29.string().refine(
256644
257129
  (key) => !["__proto__", "constructor", "prototype"].includes(key),
256645
257130
  "Unsafe object key."
@@ -256954,6 +257439,13 @@ var PRIVATE_DIRECTORY_MODE2 = 448;
256954
257439
  var PRIVATE_FILE_MODE2 = 384;
256955
257440
  var SESSION_SNAPSHOT_MAX_BYTES = 256 * 1024 * 1024;
256956
257441
  var SESSION_LOG_MAX_BYTES = 256 * 1024 * 1024;
257442
+ var HISTORY_JOURNAL_COMPACT_BYTES = 1024 * 1024;
257443
+ var HISTORY_JOURNAL_COMPACT_RECORDS = 32;
257444
+ var HistoryJournalRecordSchema = z210.object({
257445
+ schemaVersion: z210.literal(1),
257446
+ startIndex: z210.number().int().min(0).max(1e5),
257447
+ messages: StoredHistorySchema
257448
+ });
256957
257449
  var SessionCreationInputSchema = SessionSchema.pick({
256958
257450
  provider: true,
256959
257451
  model: true
@@ -256976,10 +257468,10 @@ function writeJsonAtomically(filePath, value, schema) {
256976
257468
  const temporaryPath = `${filePath}.${process.pid}.${randomUUID6()}.tmp`;
256977
257469
  let temporaryFd;
256978
257470
  try {
256979
- temporaryFd = openSync4(temporaryPath, "wx", PRIVATE_FILE_MODE2);
257471
+ temporaryFd = openSync5(temporaryPath, "wx", PRIVATE_FILE_MODE2);
256980
257472
  writeFileSync7(temporaryFd, serialized, { encoding: "utf8" });
256981
257473
  fsyncSync4(temporaryFd);
256982
- closeSync4(temporaryFd);
257474
+ closeSync5(temporaryFd);
256983
257475
  temporaryFd = void 0;
256984
257476
  preserveLastKnownGoodFile(filePath, schema);
256985
257477
  replaceFileAtomically(temporaryPath, filePath);
@@ -256987,7 +257479,7 @@ function writeJsonAtomically(filePath, value, schema) {
256987
257479
  } finally {
256988
257480
  if (temporaryFd !== void 0) {
256989
257481
  try {
256990
- closeSync4(temporaryFd);
257482
+ closeSync5(temporaryFd);
256991
257483
  } catch {
256992
257484
  }
256993
257485
  }
@@ -257001,13 +257493,13 @@ function syncParentDirectory(filePath) {
257001
257493
  if (process.platform === "win32") return;
257002
257494
  let directoryFd;
257003
257495
  try {
257004
- directoryFd = openSync4(dirname8(filePath), "r");
257496
+ directoryFd = openSync5(dirname8(filePath), "r");
257005
257497
  fsyncSync4(directoryFd);
257006
257498
  } catch {
257007
257499
  } finally {
257008
257500
  if (directoryFd !== void 0) {
257009
257501
  try {
257010
- closeSync4(directoryFd);
257502
+ closeSync5(directoryFd);
257011
257503
  } catch {
257012
257504
  }
257013
257505
  }
@@ -257020,16 +257512,16 @@ function preserveLastKnownGoodFile(filePath, schema) {
257020
257512
  const temporaryBackupPath = `${backupPath}.${process.pid}.${randomUUID6()}.tmp`;
257021
257513
  let descriptor;
257022
257514
  try {
257023
- descriptor = openSync4(temporaryBackupPath, "wx", PRIVATE_FILE_MODE2);
257515
+ descriptor = openSync5(temporaryBackupPath, "wx", PRIVATE_FILE_MODE2);
257024
257516
  writeFileSync7(descriptor, JSON.stringify(previous, null, 2), "utf8");
257025
257517
  fsyncSync4(descriptor);
257026
- closeSync4(descriptor);
257518
+ closeSync5(descriptor);
257027
257519
  descriptor = void 0;
257028
257520
  replaceFileAtomically(temporaryBackupPath, backupPath);
257029
257521
  } finally {
257030
257522
  if (descriptor !== void 0) {
257031
257523
  try {
257032
- closeSync4(descriptor);
257524
+ closeSync5(descriptor);
257033
257525
  } catch {
257034
257526
  }
257035
257527
  }
@@ -257079,12 +257571,14 @@ function replaceFileAtomically(temporaryPath, destinationPath) {
257079
257571
  }
257080
257572
  }
257081
257573
  function appendJsonLine(filePath, value) {
257082
- appendFileSync(filePath, `${JSON.stringify(value)}
257083
- `, {
257084
- encoding: "utf8",
257085
- flag: "a",
257086
- mode: PRIVATE_FILE_MODE2
257087
- });
257574
+ const descriptor = openSync5(filePath, "a", PRIVATE_FILE_MODE2);
257575
+ try {
257576
+ writeFileSync7(descriptor, `${JSON.stringify(value)}
257577
+ `, "utf8");
257578
+ fsyncSync4(descriptor);
257579
+ } finally {
257580
+ closeSync5(descriptor);
257581
+ }
257088
257582
  }
257089
257583
  function replaceWorkspacePath(text2, cwd) {
257090
257584
  const escaped = cwd.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -257127,6 +257621,7 @@ function normalizeTracePath(filePath, cwd) {
257127
257621
  var SessionStore = class {
257128
257622
  cwd;
257129
257623
  sessionRootPath;
257624
+ historyJournalWrites = /* @__PURE__ */ new Map();
257130
257625
  constructor(cwd, sessionRootPath = ".orbit/sessions") {
257131
257626
  this.cwd = resolve7(cwd);
257132
257627
  this.sessionRootPath = sessionRootPath.trim();
@@ -257501,7 +257996,36 @@ var SessionStore = class {
257501
257996
  const validated = StoredHistorySchema.parse(history);
257502
257997
  const dir = this.resolveSessionDirectory(sessionId);
257503
257998
  const historyPath = join9(dir, "history.json");
257504
- writeJsonAtomically(historyPath, validated, StoredHistorySchema);
257999
+ const journalPath = join9(dir, "history.jsonl");
258000
+ const previous = this.readHistoryFiles(historyPath, journalPath);
258001
+ let startIndex = 0;
258002
+ while (startIndex < previous.length && startIndex < validated.length && JSON.stringify(previous[startIndex]) === JSON.stringify(validated[startIndex])) {
258003
+ startIndex += 1;
258004
+ }
258005
+ if (startIndex === previous.length && startIndex === validated.length)
258006
+ return;
258007
+ const priorWrites = this.historyJournalWrites.get(sessionId) ?? 0;
258008
+ if (!existsSync10(historyPath) || priorWrites < 2) {
258009
+ writeJsonAtomically(historyPath, validated, StoredHistorySchema);
258010
+ rmSync4(journalPath, { force: true });
258011
+ this.historyJournalWrites.set(sessionId, priorWrites + 1);
258012
+ return;
258013
+ }
258014
+ appendJsonLine(
258015
+ journalPath,
258016
+ HistoryJournalRecordSchema.parse({
258017
+ schemaVersion: 1,
258018
+ startIndex,
258019
+ messages: validated.slice(startIndex)
258020
+ })
258021
+ );
258022
+ const writes = priorWrites + 1;
258023
+ this.historyJournalWrites.set(sessionId, writes);
258024
+ if (writes >= HISTORY_JOURNAL_COMPACT_RECORDS || statSync2(journalPath).size >= HISTORY_JOURNAL_COMPACT_BYTES) {
258025
+ writeJsonAtomically(historyPath, validated, StoredHistorySchema);
258026
+ rmSync4(journalPath, { force: true });
258027
+ this.historyJournalWrites.set(sessionId, 0);
258028
+ }
257505
258029
  }
257506
258030
  getHistory(sessionId) {
257507
258031
  let file;
@@ -257510,12 +258034,37 @@ var SessionStore = class {
257510
258034
  } catch {
257511
258035
  return [];
257512
258036
  }
257513
- for (const candidate of [file, `${file}.bak`]) {
258037
+ return this.readHistoryFiles(file, join9(dirname8(file), "history.jsonl"));
258038
+ }
258039
+ readHistoryFiles(snapshotPath, journalPath) {
258040
+ let history = [];
258041
+ for (const candidate of [snapshotPath, `${snapshotPath}.bak`]) {
257514
258042
  if (!existsSync10(candidate)) continue;
257515
258043
  const parsed = readValidatedSnapshot(candidate, StoredHistorySchema);
257516
- if (parsed) return parsed;
258044
+ if (parsed) {
258045
+ history = parsed;
258046
+ break;
258047
+ }
257517
258048
  }
257518
- return [];
258049
+ if (!existsSync10(journalPath)) return history;
258050
+ try {
258051
+ const journal = readBoundedRegularFile(
258052
+ journalPath,
258053
+ SESSION_LOG_MAX_BYTES
258054
+ );
258055
+ if (journal === void 0) return history;
258056
+ for (const line of journal.split("\n")) {
258057
+ if (!line.trim()) continue;
258058
+ const parsed = HistoryJournalRecordSchema.safeParse(JSON.parse(line));
258059
+ if (!parsed.success || parsed.data.startIndex > history.length) break;
258060
+ history = StoredHistorySchema.parse([
258061
+ ...history.slice(0, parsed.data.startIndex),
258062
+ ...parsed.data.messages
258063
+ ]);
258064
+ }
258065
+ } catch {
258066
+ }
258067
+ return history;
257519
258068
  }
257520
258069
  deleteSession(id) {
257521
258070
  SessionIdSchema.parse(id);
@@ -257970,21 +258519,21 @@ var PROJECT_REGISTRY_LOCK_RETRIES = 50;
257970
258519
  var PROJECT_REGISTRY_LOCK_WAIT_MS = 10;
257971
258520
  var PROJECT_REGISTRY_STALE_LOCK_MS = 1e4;
257972
258521
  var PROJECT_REGISTRY_LOCK_WAIT = new Int32Array(new SharedArrayBuffer(4));
257973
- var ProjectRecordSchema = z210.object({
257974
- id: z210.string().regex(/^proj_[a-f0-9]{16}$/),
257975
- path: z210.string().min(1).max(4096).refine((value) => !/[\u0000-\u001f\u007f]/.test(value)),
257976
- name: z210.string().trim().min(1).max(200),
257977
- createdAt: z210.string().datetime(),
257978
- lastOpenedAt: z210.string().datetime(),
257979
- lastSessionId: z210.string().min(1).max(1e3).optional(),
257980
- archivedAt: z210.string().datetime().optional()
258522
+ var ProjectRecordSchema = z37.object({
258523
+ id: z37.string().regex(/^proj_[a-f0-9]{16}$/),
258524
+ path: z37.string().min(1).max(4096).refine((value) => !/[\u0000-\u001f\u007f]/.test(value)),
258525
+ name: z37.string().trim().min(1).max(200),
258526
+ createdAt: z37.string().datetime(),
258527
+ lastOpenedAt: z37.string().datetime(),
258528
+ lastSessionId: z37.string().min(1).max(1e3).optional(),
258529
+ archivedAt: z37.string().datetime().optional()
257981
258530
  });
257982
- var ProjectRegistrySnapshotSchema = z210.object({
257983
- schemaVersion: z210.literal(1),
257984
- projects: z210.array(ProjectRecordSchema).max(MAX_PROJECTS)
258531
+ var ProjectRegistrySnapshotSchema = z37.object({
258532
+ schemaVersion: z37.literal(1),
258533
+ projects: z37.array(ProjectRecordSchema).max(MAX_PROJECTS)
257985
258534
  });
257986
- var LegacyProjectRegistrySnapshotSchema = z210.object({
257987
- projects: z210.array(ProjectRecordSchema).max(MAX_PROJECTS)
258535
+ var LegacyProjectRegistrySnapshotSchema = z37.object({
258536
+ projects: z37.array(ProjectRecordSchema).max(MAX_PROJECTS)
257988
258537
  });
257989
258538
  function parseProjectRegistrySnapshot(value) {
257990
258539
  const current = ProjectRegistrySnapshotSchema.safeParse(value);
@@ -258179,7 +258728,7 @@ function projectIdentity(projectPath) {
258179
258728
  }
258180
258729
  function isDirectory(targetPath) {
258181
258730
  try {
258182
- return statSync2(targetPath).isDirectory();
258731
+ return statSync22(targetPath).isDirectory();
258183
258732
  } catch {
258184
258733
  return false;
258185
258734
  }
@@ -258205,20 +258754,20 @@ var AGENT_RUN_LOCK_RETRIES = 50;
258205
258754
  var AGENT_RUN_LOCK_WAIT_MS = 10;
258206
258755
  var AGENT_RUN_STALE_LOCK_MS = 1e4;
258207
258756
  var AGENT_RUN_LOCK_WAIT = new Int32Array(new SharedArrayBuffer(4));
258208
- var AgentIdSchema = z37.string().regex(/^agent_[a-z0-9-]+$/, "Invalid agent id.");
258209
- var AgentRunIdSchema = z37.string().regex(/^run_[a-z0-9-]+$/, "Invalid agent run id.");
258210
- var AgentRunOwnerSchema = z37.object({
258211
- instanceId: z37.string().regex(/^orbit_[a-z0-9-]+$/, "Invalid Orbit instance id."),
258212
- pid: z37.number().int().positive(),
258213
- processStartedAt: z37.string().datetime(),
258214
- heartbeatAt: z37.string().datetime(),
258215
- expiresAt: z37.string().datetime()
258757
+ var AgentIdSchema = z45.string().regex(/^agent_[a-z0-9-]+$/, "Invalid agent id.");
258758
+ var AgentRunIdSchema = z45.string().regex(/^run_[a-z0-9-]+$/, "Invalid agent run id.");
258759
+ var AgentRunOwnerSchema = z45.object({
258760
+ instanceId: z45.string().regex(/^orbit_[a-z0-9-]+$/, "Invalid Orbit instance id."),
258761
+ pid: z45.number().int().positive(),
258762
+ processStartedAt: z45.string().datetime(),
258763
+ heartbeatAt: z45.string().datetime(),
258764
+ expiresAt: z45.string().datetime()
258216
258765
  });
258217
- var DurableAgentStateSchema = z37.object({
258766
+ var DurableAgentStateSchema = z45.object({
258218
258767
  id: AgentIdSchema,
258219
- role: z37.string().min(1).max(80),
258220
- task: z37.string().min(1).max(8e3),
258221
- status: z37.enum([
258768
+ role: z45.string().min(1).max(80),
258769
+ task: z45.string().min(1).max(8e3),
258770
+ status: z45.enum([
258222
258771
  "pending",
258223
258772
  "running",
258224
258773
  "completed",
@@ -258226,35 +258775,35 @@ var DurableAgentStateSchema = z37.object({
258226
258775
  "aborted",
258227
258776
  "blocked"
258228
258777
  ]),
258229
- model: z37.string().min(1).max(200),
258778
+ model: z45.string().min(1).max(200),
258230
258779
  sessionId: SessionIdSchema.optional(),
258231
- budgetUsd: z37.number().finite().nonnegative(),
258232
- costUsd: z37.number().finite().nonnegative().default(0),
258233
- access: z37.object({
258234
- mode: z37.enum(["read", "write"]),
258235
- scopes: z37.array(z37.string().min(1).max(1e3)).min(1).max(100)
258780
+ budgetUsd: z45.number().finite().nonnegative(),
258781
+ costUsd: z45.number().finite().nonnegative().default(0),
258782
+ access: z45.object({
258783
+ mode: z45.enum(["read", "write"]),
258784
+ scopes: z45.array(z45.string().min(1).max(1e3)).min(1).max(100)
258236
258785
  }),
258237
- steering: z37.object({
258238
- count: z37.number().int().nonnegative().max(1e4),
258239
- lastAt: z37.string().datetime().optional()
258786
+ steering: z45.object({
258787
+ count: z45.number().int().nonnegative().max(1e4),
258788
+ lastAt: z45.string().datetime().optional()
258240
258789
  }).default({ count: 0 }),
258241
- startedAt: z37.string().datetime().optional(),
258242
- endedAt: z37.string().datetime().optional(),
258243
- error: z37.string().max(4e3).optional()
258790
+ startedAt: z45.string().datetime().optional(),
258791
+ endedAt: z45.string().datetime().optional(),
258792
+ error: z45.string().max(4e3).optional()
258244
258793
  });
258245
- var AgentRunSchema = z37.object({
258246
- schemaVersion: z37.literal(1),
258794
+ var AgentRunSchema = z45.object({
258795
+ schemaVersion: z45.literal(1),
258247
258796
  id: AgentRunIdSchema,
258248
- task: z37.string().min(1).max(2e4),
258249
- status: z37.enum(["running", "completed", "failed", "aborted"]),
258250
- budgetUsd: z37.number().finite().nonnegative(),
258251
- costUsd: z37.number().finite().nonnegative().default(0),
258252
- createdAt: z37.string().datetime(),
258253
- updatedAt: z37.string().datetime(),
258797
+ task: z45.string().min(1).max(2e4),
258798
+ status: z45.enum(["running", "completed", "failed", "aborted"]),
258799
+ budgetUsd: z45.number().finite().nonnegative(),
258800
+ costUsd: z45.number().finite().nonnegative().default(0),
258801
+ createdAt: z45.string().datetime(),
258802
+ updatedAt: z45.string().datetime(),
258254
258803
  owner: AgentRunOwnerSchema.optional(),
258255
258804
  /** Legacy field retained while schema-version 1 records are migrated lazily. */
258256
- ownerPid: z37.number().int().positive().optional(),
258257
- agents: z37.array(DurableAgentStateSchema).max(128)
258805
+ ownerPid: z45.number().int().positive().optional(),
258806
+ agents: z45.array(DurableAgentStateSchema).max(128)
258258
258807
  });
258259
258808
  var AgentRunStore = class {
258260
258809
  constructor(cwd, options = {}) {
@@ -259316,7 +259865,10 @@ var RoutingInputSchema = z211.object({
259316
259865
  fallbackModel: z211.string().min(1).optional(),
259317
259866
  activeModel: z211.string().min(1).optional(),
259318
259867
  repairTurn: z211.boolean().default(false),
259319
- hasWrittenFiles: z211.boolean().default(false)
259868
+ hasWrittenFiles: z211.boolean().default(false),
259869
+ affectedFileCount: z211.number().int().min(0).max(1e5).default(0),
259870
+ verificationFailureCount: z211.number().int().min(0).max(1e3).default(0),
259871
+ estimatedContextTokens: z211.number().int().min(0).optional()
259320
259872
  });
259321
259873
  var COMPLEX_SIGNALS = [
259322
259874
  "debug",
@@ -259373,11 +259925,19 @@ var SIMPLE_SIGNALS = [
259373
259925
  "\u7EE7\u7EED"
259374
259926
  ];
259375
259927
  function classifyTaskComplexity(input) {
259376
- if (input.repairTurn || input.hasWrittenFiles) return "complex";
259928
+ if (input.repairTurn || (input.verificationFailureCount ?? 0) > 0 || (input.affectedFileCount ?? 0) >= 3 || (input.estimatedContextTokens ?? 0) >= 64e3) {
259929
+ return "complex";
259930
+ }
259377
259931
  const query = input.query.toLowerCase().trim();
259378
259932
  const complex = COMPLEX_SIGNALS.some((signal) => query.includes(signal));
259379
- if (complex) return "complex";
259380
- if (query.length < 50 || SIMPLE_SIGNALS.some((signal) => query.includes(signal))) {
259933
+ const referencedFiles = new Set(
259934
+ query.match(/[\w@.-]+(?:\/[\w@.-]+)+\.[a-z0-9]+/gi) ?? []
259935
+ ).size;
259936
+ const structuralComplexity = referencedFiles >= 3 || query.length >= 600 || (query.match(/(?:^|\n)\s*(?:[-*]|\d+[.)])\s+/g) ?? []).length >= 4 || /```[\s\S]*```/.test(query);
259937
+ if (complex || structuralComplexity) return "complex";
259938
+ const simpleSignal = SIMPLE_SIGNALS.some((signal) => query.includes(signal));
259939
+ const wordCount = query.split(/\s+/u).filter(Boolean).length;
259940
+ if (!input.hasWrittenFiles && (simpleSignal || wordCount <= 8 && query.length <= 80)) {
259381
259941
  return "simple";
259382
259942
  }
259383
259943
  return "balanced";
@@ -259403,11 +259963,11 @@ function routeModel(input) {
259403
259963
  const complex = complexity === "complex";
259404
259964
  const simple = complexity === "simple";
259405
259965
  if (value.activeModel) {
259406
- if (value.activeModel === value.fastModel && (complex || value.hasWrittenFiles)) {
259966
+ if (value.activeModel === value.fastModel && (complex || value.affectedFileCount >= 2)) {
259407
259967
  return decision(
259408
259968
  qualityModel,
259409
259969
  "quality",
259410
- value.hasWrittenFiles ? "write_escalation" : "complex_request",
259970
+ value.affectedFileCount >= 2 ? "write_escalation" : "complex_request",
259411
259971
  "high"
259412
259972
  );
259413
259973
  }
@@ -260221,21 +260781,21 @@ function countRepairAttemptsForCurrentTask(history) {
260221
260781
  var execPromise = promisify(exec);
260222
260782
  var execFilePromise = promisify(execFile4);
260223
260783
  var VERIFICATION_CONTRACT_MAX_BYTES = 1048576;
260224
- var VerificationSuitesSchema = z45.record(z45.string().min(1).max(200), z45.string().max(2e4)).refine((suites) => Object.keys(suites).length <= 100, {
260784
+ var VerificationSuitesSchema = z46.record(z46.string().min(1).max(200), z46.string().max(2e4)).refine((suites) => Object.keys(suites).length <= 100, {
260225
260785
  message: "Verification contracts may define at most 100 suites."
260226
260786
  });
260227
- var VerificationFileListSchema = z45.array(z45.string().min(1).max(4096)).max(1e4);
260787
+ var VerificationFileListSchema = z46.array(z46.string().min(1).max(4096)).max(1e4);
260228
260788
  function safeFailureOutput(error) {
260229
260789
  const record = typeof error === "object" && error !== null ? error : {};
260230
260790
  const output = [record.stdout, record.stderr].filter((value) => typeof value === "string" && !!value).join("\n").trim();
260231
260791
  const message2 = error instanceof Error ? error.message : String(error);
260232
260792
  return LogTruncator.truncate(redactSecrets(output || message2), 80, 8e3);
260233
260793
  }
260234
- var VerificationContractSchema = z45.object({
260794
+ var VerificationContractSchema = z46.object({
260235
260795
  suites: VerificationSuitesSchema.default({}),
260236
260796
  allowedModifiedFiles: VerificationFileListSchema.optional(),
260237
260797
  requiredFiles: VerificationFileListSchema.optional(),
260238
- maxRepairAttempts: z45.number().int().min(0).max(10).default(3)
260798
+ maxRepairAttempts: z46.number().int().min(0).max(10).default(3)
260239
260799
  });
260240
260800
  var VerificationContractManager = class {
260241
260801
  constructor(cwd, sessionId, checkpointManager, trusted = false, commandTimeoutMs = 12e4) {
@@ -260542,6 +261102,7 @@ function readGitOutput(cwd, args) {
260542
261102
  const child = spawn3("git", args, {
260543
261103
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
260544
261104
  cwd,
261105
+ env: buildSanitizedChildEnvironment(),
260545
261106
  stdio: ["ignore", "pipe", "ignore"]
260546
261107
  });
260547
261108
  const chunks = [];
@@ -260568,6 +261129,7 @@ function hashGitOutput(cwd, args) {
260568
261129
  const child = spawn3("git", args, {
260569
261130
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
260570
261131
  cwd,
261132
+ env: buildSanitizedChildEnvironment(),
260571
261133
  stdio: ["ignore", "pipe", "ignore"]
260572
261134
  });
260573
261135
  child.stdout.on("data", (chunk) => hash2.update(chunk));
@@ -260654,10 +261216,9 @@ function prepareIsolatedGitCommit(cwd, requestedPaths) {
260654
261216
  path32.dirname(gitIndexPath),
260655
261217
  `orbit-index-${randomUUID24()}`
260656
261218
  );
260657
- const isolatedEnvironment = {
260658
- ...process.env,
260659
- GIT_INDEX_FILE: temporaryIndexPath
260660
- };
261219
+ const isolatedEnvironment = buildSanitizedChildEnvironment({
261220
+ extra: { GIT_INDEX_FILE: temporaryIndexPath }
261221
+ });
260661
261222
  let disposed = false;
260662
261223
  try {
260663
261224
  try {
@@ -262126,11 +262687,25 @@ Note: To find where a symbol (class, function, etc.) is declared or referenced,
262126
262687
  );
262127
262688
  const userQueryText = (currentUserMessage?.content.filter((block2) => block2.type === "text").map((block2) => block2.type === "text" ? block2.text : "").join("\n") || this.state.task).toLowerCase();
262128
262689
  const currentTurnStartIndex = currentUserMessage ? this.state.history.lastIndexOf(currentUserMessage) : 0;
262129
- const hasWrittenFiles = this.state.history.slice(Math.max(0, currentTurnStartIndex)).some(
262130
- (msg) => msg.role === "assistant" && msg.content.some(
262131
- (b) => b.type === "tool_call" && (b.toolCall.name === "write_file" || b.toolCall.name === "edit_file")
262132
- )
262690
+ const writeCalls = this.state.history.slice(Math.max(0, currentTurnStartIndex)).flatMap(
262691
+ (message2) => message2.role === "assistant" ? message2.content.filter(
262692
+ (block2) => block2.type === "tool_call" && (block2.toolCall.name === "write_file" || block2.toolCall.name === "edit_file")
262693
+ ) : []
262133
262694
  );
262695
+ const hasWrittenFiles = writeCalls.length > 0;
262696
+ const affectedFileCount = new Set(
262697
+ writeCalls.map((block2) => {
262698
+ if (block2.type !== "tool_call") return "";
262699
+ try {
262700
+ const pathValue = toUnknownRecord(
262701
+ JSON.parse(block2.toolCall.arguments)
262702
+ ).path;
262703
+ return typeof pathValue === "string" ? pathValue : "";
262704
+ } catch {
262705
+ return "";
262706
+ }
262707
+ }).filter(Boolean)
262708
+ ).size;
262134
262709
  const routingDecision = routeModel({
262135
262710
  query: userQueryText,
262136
262711
  defaultModel: this.config.models.default,
@@ -262140,12 +262715,14 @@ Note: To find where a symbol (class, function, etc.) is declared or referenced,
262140
262715
  fallbackModel: this.fallbackModelForRun || void 0,
262141
262716
  activeModel: this.activeModelForRun || void 0,
262142
262717
  repairTurn: isRepairTurn,
262143
- hasWrittenFiles
262718
+ hasWrittenFiles,
262719
+ affectedFileCount
262144
262720
  });
262145
262721
  const isComplexTask = classifyTaskComplexity({
262146
262722
  query: userQueryText,
262147
262723
  repairTurn: isRepairTurn,
262148
- hasWrittenFiles
262724
+ hasWrittenFiles,
262725
+ affectedFileCount
262149
262726
  }) === "complex";
262150
262727
  nextModel = routingDecision.model;
262151
262728
  if (!this.options?.modelOverride && !this.fallbackModelForRun) {
@@ -264016,9 +264593,9 @@ ${stdout2.substring(0, 2e4)}`
264016
264593
  eventBus.emitEvent("tool_result", {
264017
264594
  toolCallId: tc.id,
264018
264595
  toolName: tc.name,
264019
- result: finalResult.ok ? finalResult.data : void 0,
264020
- display: finalResult.ok ? finalResult.display : void 0,
264021
- error: finalResult.ok ? void 0 : finalResult.error || "Unknown error"
264596
+ result: finalResult.ok ? redactSensitiveValue(finalResult.data) : void 0,
264597
+ display: finalResult.ok ? redactSecrets(finalResult.display || "") : void 0,
264598
+ error: finalResult.ok ? void 0 : redactSecrets(finalResult.error || "Unknown error")
264022
264599
  });
264023
264600
  const guardNudge = this.progressGuard.record({
264024
264601
  name: tc.name,
@@ -264309,7 +264886,10 @@ ${diff.substring(0, 2e4)}`
264309
264886
  const { stdout: stdout2, stderr } = await execPromise2(hookCommand, {
264310
264887
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
264311
264888
  cwd: this.cwd,
264312
- env: { ...process.env, ORBIT_FILE: relativePath },
264889
+ env: buildSanitizedChildEnvironment({
264890
+ mode: "minimal",
264891
+ extra: { ORBIT_FILE: relativePath }
264892
+ }),
264313
264893
  timeout: this.config.tools.bash.timeoutMs,
264314
264894
  signal: this.abortController?.signal
264315
264895
  });
@@ -267728,22 +268308,22 @@ async function runDoctor(cwd, options = {}) {
267728
268308
  import picocolors7 from "picocolors";
267729
268309
  import { createHash as createHash8, randomUUID as randomUUID8 } from "crypto";
267730
268310
  import { resolve as resolve8 } from "path";
267731
- import { z as z46 } from "zod";
267732
- var BenchOptionsSchema = z46.object({
267733
- prompt: z46.string().optional(),
267734
- provider: z46.string().optional(),
267735
- model: z46.string().optional(),
267736
- models: z46.string().optional(),
267737
- repeat: z46.union([z46.number(), z46.string()]).optional(),
267738
- maxTokens: z46.union([z46.number(), z46.string()]).optional(),
267739
- cacheProfile: z46.boolean().optional(),
267740
- minCacheHit: z46.union([z46.number(), z46.string()]).optional(),
267741
- maxFirstDeltaMs: z46.union([z46.number(), z46.string()]).optional(),
267742
- maxFirstTextMs: z46.union([z46.number(), z46.string()]).optional(),
267743
- minThroughput: z46.union([z46.number(), z46.string()]).optional(),
267744
- maxErrorRate: z46.union([z46.number(), z46.string()]).optional(),
267745
- thinking: z46.string().optional(),
267746
- json: z46.boolean().optional()
268311
+ import { z as z47 } from "zod";
268312
+ var BenchOptionsSchema = z47.object({
268313
+ prompt: z47.string().optional(),
268314
+ provider: z47.string().optional(),
268315
+ model: z47.string().optional(),
268316
+ models: z47.string().optional(),
268317
+ repeat: z47.union([z47.number(), z47.string()]).optional(),
268318
+ maxTokens: z47.union([z47.number(), z47.string()]).optional(),
268319
+ cacheProfile: z47.boolean().optional(),
268320
+ minCacheHit: z47.union([z47.number(), z47.string()]).optional(),
268321
+ maxFirstDeltaMs: z47.union([z47.number(), z47.string()]).optional(),
268322
+ maxFirstTextMs: z47.union([z47.number(), z47.string()]).optional(),
268323
+ minThroughput: z47.union([z47.number(), z47.string()]).optional(),
268324
+ maxErrorRate: z47.union([z47.number(), z47.string()]).optional(),
268325
+ thinking: z47.string().optional(),
268326
+ json: z47.boolean().optional()
267747
268327
  });
267748
268328
  function parseBenchOptions(value) {
267749
268329
  return BenchOptionsSchema.parse(value);
@@ -270970,6 +271550,33 @@ function buildSlashCommandHelp(language) {
270970
271550
  // src/tui/TerminalText.ts
270971
271551
  var TERMINAL_CONTROL_PATTERN = /(?:[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;;[^\u0007]*(?:\u0007|\u001b\\))/g;
270972
271552
  var HYPERLINK_CLOSE = "\x1B]8;;\x07";
271553
+ var GRAPHEME_SEGMENTER = new Intl.Segmenter(void 0, {
271554
+ granularity: "grapheme"
271555
+ });
271556
+ var ZERO_WIDTH_FORMAT_CHARACTERS = /* @__PURE__ */ new Set([
271557
+ "\u200C",
271558
+ "\u200D",
271559
+ "\uFE0E",
271560
+ "\uFE0F"
271561
+ ]);
271562
+ function graphemeEntries(value) {
271563
+ return [...GRAPHEME_SEGMENTER.segment(value)].map(({ segment, index }) => ({
271564
+ segment,
271565
+ index
271566
+ }));
271567
+ }
271568
+ function graphemes(value) {
271569
+ return graphemeEntries(value).map((entry) => entry.segment);
271570
+ }
271571
+ function graphemeWidth(grapheme) {
271572
+ if (!grapheme || [...grapheme].every(
271573
+ (character) => /^\p{Mark}$/u.test(character) || ZERO_WIDTH_FORMAT_CHARACTERS.has(character)
271574
+ )) {
271575
+ return 0;
271576
+ }
271577
+ const codePoints = [...grapheme].map((character) => character.codePointAt(0)).filter((codePoint) => codePoint !== void 0);
271578
+ return grapheme.includes("\u200D") || codePoints.some((codePoint) => isFullWidth2(codePoint)) ? 2 : 1;
271579
+ }
270973
271580
  function stripAnsiCodes(str) {
270974
271581
  return str.replace(TERMINAL_CONTROL_PATTERN, "");
270975
271582
  }
@@ -270983,10 +271590,8 @@ function isFullWidth2(codePoint) {
270983
271590
  function truncateToWidth(str, maxWidth) {
270984
271591
  let width = 0;
270985
271592
  let result = "";
270986
- for (const char of str) {
270987
- const code = char.codePointAt(0);
270988
- if (code === void 0) continue;
270989
- const charWidth = isFullWidth2(code) ? 2 : 1;
271593
+ for (const char of graphemes(str)) {
271594
+ const charWidth = graphemeWidth(char);
270990
271595
  if (width + charWidth > maxWidth) break;
270991
271596
  width += charWidth;
270992
271597
  result += char;
@@ -270997,10 +271602,8 @@ function truncateFromEndToWidth(str, maxWidth) {
270997
271602
  if (maxWidth <= 0) return "";
270998
271603
  let width = 0;
270999
271604
  const result = [];
271000
- for (const char of Array.from(str).reverse()) {
271001
- const code = char.codePointAt(0);
271002
- if (code === void 0) continue;
271003
- const charWidth = isFullWidth2(code) ? 2 : 1;
271605
+ for (const char of graphemes(str).reverse()) {
271606
+ const charWidth = graphemeWidth(char);
271004
271607
  if (width + charWidth > maxWidth) break;
271005
271608
  width += charWidth;
271006
271609
  result.push(char);
@@ -271032,9 +271635,8 @@ function truncatePathToWidth(path9, maxWidth) {
271032
271635
  }
271033
271636
  function getStringWidth(str) {
271034
271637
  let width = 0;
271035
- for (const char of stripAnsiCodes(str)) {
271036
- const code = char.codePointAt(0);
271037
- if (code !== void 0) width += isFullWidth2(code) ? 2 : 1;
271638
+ for (const char of graphemes(stripAnsiCodes(str))) {
271639
+ width += graphemeWidth(char);
271038
271640
  }
271039
271641
  return width;
271040
271642
  }
@@ -271069,21 +271671,22 @@ function wrapAnsiLine(line, maxWidth) {
271069
271671
  index += controlSequence.length;
271070
271672
  continue;
271071
271673
  }
271072
- const code = line.codePointAt(index) ?? 0;
271073
- const charLength = code > 65535 ? 2 : 1;
271074
- const char = line.substring(index, index + charLength);
271075
- const charWidth = isFullWidth2(code) ? 2 : 1;
271076
- if (currentWidth + charWidth > maxWidth) {
271077
- if (activeColor) currentLine += "\x1B[0m";
271078
- if (activeHyperlink) currentLine += HYPERLINK_CLOSE;
271079
- lines.push(currentLine);
271080
- currentLine = activeColor + activeHyperlink + char;
271081
- currentWidth = charWidth;
271082
- } else {
271083
- currentLine += char;
271084
- currentWidth += charWidth;
271674
+ const plainEnd = match?.index ?? line.length;
271675
+ const plainChunk = line.slice(index, plainEnd);
271676
+ for (const char of graphemes(plainChunk)) {
271677
+ const charWidth = graphemeWidth(char);
271678
+ if (currentWidth + charWidth > maxWidth) {
271679
+ if (activeColor) currentLine += "\x1B[0m";
271680
+ if (activeHyperlink) currentLine += HYPERLINK_CLOSE;
271681
+ lines.push(currentLine);
271682
+ currentLine = activeColor + activeHyperlink + char;
271683
+ currentWidth = charWidth;
271684
+ } else {
271685
+ currentLine += char;
271686
+ currentWidth += charWidth;
271687
+ }
271085
271688
  }
271086
- index += charLength;
271689
+ index = plainEnd;
271087
271690
  }
271088
271691
  if (currentLine) lines.push(currentLine);
271089
271692
  return lines;
@@ -271093,23 +271696,17 @@ function wrapInputText(str, maxWidth) {
271093
271696
  let currentLine = "";
271094
271697
  let currentWidth = 0;
271095
271698
  let currentStart = 0;
271096
- for (let index = 0; index < str.length; ) {
271097
- const code = str.codePointAt(index);
271098
- if (!code) {
271099
- index++;
271100
- continue;
271101
- }
271102
- if (code === 10) {
271699
+ for (const entry of graphemeEntries(str)) {
271700
+ const index = entry.index;
271701
+ const char = entry.segment;
271702
+ if (char === "\n") {
271103
271703
  lines.push({ text: currentLine, start: currentStart, end: index });
271104
- index++;
271105
271704
  currentLine = "";
271106
271705
  currentWidth = 0;
271107
- currentStart = index;
271706
+ currentStart = index + char.length;
271108
271707
  continue;
271109
271708
  }
271110
- const charLength = code > 65535 ? 2 : 1;
271111
- const char = str.substring(index, index + charLength);
271112
- const charWidth = isFullWidth2(code) ? 2 : 1;
271709
+ const charWidth = graphemeWidth(char);
271113
271710
  if (currentLine && currentWidth + charWidth > maxWidth) {
271114
271711
  lines.push({ text: currentLine, start: currentStart, end: index });
271115
271712
  currentLine = "";
@@ -271118,7 +271715,6 @@ function wrapInputText(str, maxWidth) {
271118
271715
  }
271119
271716
  currentLine += char;
271120
271717
  currentWidth += charWidth;
271121
- index += charLength;
271122
271718
  }
271123
271719
  lines.push({ text: currentLine, start: currentStart, end: str.length });
271124
271720
  return lines;
@@ -271146,7 +271742,7 @@ function formatWrappedLines(wrappedLines, inputLength) {
271146
271742
  let charIndex = 0;
271147
271743
  return wrappedLines.map((line) => {
271148
271744
  let formattedLine = "";
271149
- for (const char of line) {
271745
+ for (const char of graphemes(line)) {
271150
271746
  const color = charIndex < inputLength ? "\x1B[1;38;2;245;242;232m" : "\x1B[38;2;148;146;138m";
271151
271747
  formattedLine += `${color}${char}\x1B[0m`;
271152
271748
  charIndex += char.length;
@@ -271273,11 +271869,11 @@ function findPreviousHistoryEntry(history, query, startIndex = history.length) {
271273
271869
  // src/tui/InputHistoryStore.ts
271274
271870
  import { join as join14 } from "path";
271275
271871
  import { homedir as homedir6 } from "os";
271276
- import { z as z47 } from "zod";
271872
+ import { z as z48 } from "zod";
271277
271873
  var INPUT_HISTORY_MAX_BYTES = 1048576;
271278
271874
  var INPUT_HISTORY_MAX_ENTRIES = 500;
271279
271875
  var INPUT_HISTORY_ENTRY_MAX_CHARS = 2e4;
271280
- var inputHistorySchema = z47.array(z47.string().max(INPUT_HISTORY_ENTRY_MAX_CHARS)).max(INPUT_HISTORY_MAX_ENTRIES);
271876
+ var inputHistorySchema = z48.array(z48.string().max(INPUT_HISTORY_ENTRY_MAX_CHARS)).max(INPUT_HISTORY_MAX_ENTRIES);
271281
271877
  var InputHistoryStore = class {
271282
271878
  constructor(filePath = join14(homedir6(), ".orbit", "input_history.json")) {
271283
271879
  this.filePath = filePath;
@@ -271848,13 +272444,13 @@ function renderPromptScreen(state, viewport, theme = MORANDI) {
271848
272444
 
271849
272445
  // src/runtime/UpdateManager.ts
271850
272446
  import { execFile as execFile5, execFileSync as execFileSync6 } from "child_process";
271851
- import { z as z48 } from "zod";
271852
- var SemanticVersionSchema = z48.string().trim().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/);
271853
- var UpdateChannelSchema = z48.enum(["stable", "beta"]);
271854
- var UpdateCheckSchema = z48.object({
272447
+ import { z as z49 } from "zod";
272448
+ var SemanticVersionSchema = z49.string().trim().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/);
272449
+ var UpdateChannelSchema = z49.enum(["stable", "beta"]);
272450
+ var UpdateCheckSchema = z49.object({
271855
272451
  currentVersion: SemanticVersionSchema,
271856
272452
  latestVersion: SemanticVersionSchema,
271857
- updateAvailable: z48.boolean()
272453
+ updateAvailable: z49.boolean()
271858
272454
  });
271859
272455
  var UpdateManager = class {
271860
272456
  executable;
@@ -271938,9 +272534,9 @@ var UpdateManager = class {
271938
272534
  ],
271939
272535
  { timeoutMs: this.timeoutMs, inheritOutput: false }
271940
272536
  );
271941
- const parsed = z48.object({
271942
- dependencies: z48.object({
271943
- "@orbit-build/cli": z48.object({ version: SemanticVersionSchema })
272537
+ const parsed = z49.object({
272538
+ dependencies: z49.object({
272539
+ "@orbit-build/cli": z49.object({ version: SemanticVersionSchema })
271944
272540
  })
271945
272541
  }).parse(JSON.parse(raw));
271946
272542
  return parsed.dependencies["@orbit-build/cli"].version;
@@ -273549,10 +274145,10 @@ var FullscreenTui = class {
273549
274145
  if (this.thoughtTimer) clearInterval(this.thoughtTimer);
273550
274146
  this.thoughtTimer = setInterval(() => {
273551
274147
  if (this.isThinking) {
273552
- this.thoughtElapsed += 100;
274148
+ this.thoughtElapsed += 250;
273553
274149
  this.render();
273554
274150
  }
273555
- }, 100);
274151
+ }, 250);
273556
274152
  this.render();
273557
274153
  }
273558
274154
  handleModelDelta(text2) {
@@ -273930,7 +274526,8 @@ var FullscreenTui = class {
273930
274526
  headerLines = [headerLine1, headerLine2, headerLine3, headerLine4];
273931
274527
  }
273932
274528
  const renderedLines = [];
273933
- const conversation = buildTuiConversationViewModel(this.history);
274529
+ const renderHistory = this.history.length > 800 ? this.history.slice(-800) : this.history;
274530
+ const conversation = buildTuiConversationViewModel(renderHistory);
273934
274531
  const turns = conversation.turns;
273935
274532
  const lastAsst = conversation.lastAssistant;
273936
274533
  const uBorder = " ";
@@ -274247,7 +274844,7 @@ import { dirname as dirname13, resolve as resolve14 } from "path";
274247
274844
  import { homedir as homedir10 } from "os";
274248
274845
  import http3 from "http";
274249
274846
  import { randomBytes as randomBytes4, randomUUID as randomUUID12, timingSafeEqual as timingSafeEqual2 } from "crypto";
274250
- import { z as z66 } from "zod";
274847
+ import { z as z67 } from "zod";
274251
274848
 
274252
274849
  // src/runtime/CommandRouter.ts
274253
274850
  import picocolors18 from "picocolors";
@@ -274258,11 +274855,11 @@ import { basename as basename4, extname as extname3, join as join16 } from "path
274258
274855
  import { homedir as homedir8 } from "os";
274259
274856
  import { fileURLToPath as fileURLToPath3 } from "url";
274260
274857
  import { parse as parse3 } from "yaml";
274261
- import { z as z49 } from "zod";
274262
- var CommandMetadataSchema = z49.object({
274263
- description: z49.string().max(240).optional(),
274264
- argumentHint: z49.string().max(120).optional(),
274265
- "argument-hint": z49.string().max(120).optional()
274858
+ import { z as z50 } from "zod";
274859
+ var CommandMetadataSchema = z50.object({
274860
+ description: z50.string().max(240).optional(),
274861
+ argumentHint: z50.string().max(120).optional(),
274862
+ "argument-hint": z50.string().max(120).optional()
274266
274863
  });
274267
274864
  var VALID_COMMAND_NAME = /^[a-z0-9][a-z0-9-_]{0,47}$/i;
274268
274865
  var MAX_COMMAND_FILE_BYTES = 256 * 1024;
@@ -274466,21 +275063,21 @@ import { createRequire as createRequire2 } from "module";
274466
275063
  import http2 from "http";
274467
275064
  import { randomBytes as randomBytes3, randomUUID as randomUUID9 } from "crypto";
274468
275065
  import { isAbsolute as isAbsolute5, relative as relative7, resolve as resolve11 } from "path";
274469
- import { z as z55 } from "zod";
275066
+ import { z as z56 } from "zod";
274470
275067
 
274471
275068
  // src/runtime/AutocompleteCandidates.ts
274472
275069
  import glob4 from "fast-glob";
274473
275070
  import { existsSync as existsSync17, readdirSync as readdirSync8 } from "fs";
274474
275071
  import { homedir as homedir9 } from "os";
274475
275072
  import { dirname as dirname10, join as join17, resolve as resolve9 } from "path";
274476
- import { z as z50 } from "zod";
275073
+ import { z as z51 } from "zod";
274477
275074
  var AUTOCOMPLETE_SYMBOL_INDEX_MAX_BYTES = 256 * 1024 * 1024;
274478
- var symbolIndexSchema = z50.object({
274479
- files: z50.record(
274480
- z50.object({
274481
- symbols: z50.array(
274482
- z50.object({
274483
- name: z50.string().min(1)
275075
+ var symbolIndexSchema = z51.object({
275076
+ files: z51.record(
275077
+ z51.object({
275078
+ symbols: z51.array(
275079
+ z51.object({
275080
+ name: z51.string().min(1)
274484
275081
  })
274485
275082
  ).optional()
274486
275083
  })
@@ -278798,7 +279395,7 @@ var WEB_UI_CLIENT_SELECT_SCRIPT = String.raw` const selectControls = new Map();
278798
279395
  searchInput.className = 'select-search';
278799
279396
  searchInput.autocomplete = 'off';
278800
279397
  searchInput.spellcheck = false;
278801
- searchInput.placeholder = document.documentElement.lang === 'zh-CN' ? '搜索模型…' : 'Search models…';
279398
+ searchInput.placeholder = document.documentElement.lang.startsWith('zh') ? '搜索模型…' : 'Search models…';
278802
279399
  searchInput.setAttribute('aria-label', searchInput.placeholder);
278803
279400
  searchWrap.append(searchInput);
278804
279401
  entry.menu.append(searchWrap);
@@ -278842,7 +279439,7 @@ var WEB_UI_CLIENT_SELECT_SCRIPT = String.raw` const selectControls = new Map();
278842
279439
  if (searchInput) {
278843
279440
  const empty = document.createElement('div');
278844
279441
  empty.className = 'select-empty';
278845
- empty.textContent = document.documentElement.lang === 'zh-CN' ? '没有匹配的模型' : 'No matching models';
279442
+ empty.textContent = document.documentElement.lang.startsWith('zh') ? '没有匹配的模型' : 'No matching models';
278846
279443
  empty.hidden = true;
278847
279444
  entry.menu.append(empty);
278848
279445
  searchInput.addEventListener('input', () => {
@@ -280537,7 +281134,7 @@ import { relative as relative5 } from "path";
280537
281134
 
280538
281135
  // src/runtime/webui/WebUiSecurity.ts
280539
281136
  import { timingSafeEqual } from "crypto";
280540
- import { z as z51 } from "zod";
281137
+ import { z as z55 } from "zod";
280541
281138
 
280542
281139
  // src/runtime/webui/WebUiErrors.ts
280543
281140
  var WebUiRequestError = class extends Error {
@@ -280857,7 +281454,7 @@ function sanitizeBaseUrl(value) {
280857
281454
  }
280858
281455
  }
280859
281456
  function webRequestErrorStatus(error) {
280860
- if (error instanceof z51.ZodError) return 400;
281457
+ if (error instanceof z55.ZodError) return 400;
280861
281458
  if (error instanceof WebUiRequestError) return error.statusCode;
280862
281459
  return 500;
280863
281460
  }
@@ -288013,6 +288610,36 @@ var WEB_UI_RESPONSIVE_STYLES = String.raw`
288013
288610
  transition-duration: 0.01ms !important;
288014
288611
  }
288015
288612
  }
288613
+
288614
+ @media (forced-colors: active) {
288615
+ button,
288616
+ input,
288617
+ select,
288618
+ textarea,
288619
+ .message.user .message-content,
288620
+ .tool-card,
288621
+ .code-block,
288622
+ .composer-shell,
288623
+ .inspector,
288624
+ .sidebar {
288625
+ forced-color-adjust: auto;
288626
+ border-color: CanvasText;
288627
+ }
288628
+
288629
+ button:focus-visible,
288630
+ input:focus-visible,
288631
+ select:focus-visible,
288632
+ textarea:focus-visible,
288633
+ summary:focus-visible {
288634
+ outline: 3px solid Highlight;
288635
+ }
288636
+
288637
+ .tool-status,
288638
+ .control-turn-indicator,
288639
+ .message-progress-indicator {
288640
+ border: 2px solid CanvasText;
288641
+ }
288642
+ }
288016
288643
  `;
288017
288644
 
288018
288645
  // src/runtime/webui/styles/WebUiSelectStyles.ts
@@ -289452,137 +290079,137 @@ function normalizePath4(path9) {
289452
290079
  }
289453
290080
 
289454
290081
  // src/runtime/webui/WebUiRuntime.ts
289455
- var WebTurnIdSchema = z55.string().trim().min(8).max(100).regex(/^[a-zA-Z0-9_-]+$/);
289456
- var AttachmentIdsSchema = z55.array(WebTurnIdSchema).max(4).refine((ids) => new Set(ids).size === ids.length, {
290082
+ var WebTurnIdSchema = z56.string().trim().min(8).max(100).regex(/^[a-zA-Z0-9_-]+$/);
290083
+ var AttachmentIdsSchema = z56.array(WebTurnIdSchema).max(4).refine((ids) => new Set(ids).size === ids.length, {
289457
290084
  message: "Attachment IDs must be unique."
289458
290085
  });
289459
- var MessagePageQuerySchema = z55.object({
289460
- before: z55.coerce.number().int().min(1).max(1e7).optional(),
289461
- limit: z55.coerce.number().int().min(20).max(100).optional()
290086
+ var MessagePageQuerySchema = z56.object({
290087
+ before: z56.coerce.number().int().min(1).max(1e7).optional(),
290088
+ limit: z56.coerce.number().int().min(20).max(100).optional()
289462
290089
  }).strict();
289463
- var ChatRequestSchema = z55.object({
289464
- prompt: z55.string().trim().min(1).max(1e5),
290090
+ var ChatRequestSchema = z56.object({
290091
+ prompt: z56.string().trim().min(1).max(1e5),
289465
290092
  turnId: WebTurnIdSchema.optional(),
289466
290093
  attachmentIds: AttachmentIdsSchema.optional()
289467
290094
  }).strict();
289468
- var InputQueueIdSchema = z55.string().trim().regex(/^input_[a-zA-Z0-9_-]+$/).max(200);
289469
- var InputQueueActionSchema = z55.discriminatedUnion("action", [
289470
- z55.object({
289471
- action: z55.literal("enqueue"),
289472
- prompt: z55.string().trim().min(1).max(1e5),
289473
- mode: z55.enum(["follow_up", "steer"]).default("follow_up"),
290095
+ var InputQueueIdSchema = z56.string().trim().regex(/^input_[a-zA-Z0-9_-]+$/).max(200);
290096
+ var InputQueueActionSchema = z56.discriminatedUnion("action", [
290097
+ z56.object({
290098
+ action: z56.literal("enqueue"),
290099
+ prompt: z56.string().trim().min(1).max(1e5),
290100
+ mode: z56.enum(["follow_up", "steer"]).default("follow_up"),
289474
290101
  attachmentIds: AttachmentIdsSchema.optional()
289475
290102
  }).strict(),
289476
- z55.object({
289477
- action: z55.literal("update"),
290103
+ z56.object({
290104
+ action: z56.literal("update"),
289478
290105
  inputId: InputQueueIdSchema,
289479
- prompt: z55.string().trim().min(1).max(1e5).optional(),
289480
- mode: z55.enum(["follow_up", "steer"]).optional()
290106
+ prompt: z56.string().trim().min(1).max(1e5).optional(),
290107
+ mode: z56.enum(["follow_up", "steer"]).optional()
289481
290108
  }).strict(),
289482
- z55.object({
289483
- action: z55.literal("move"),
290109
+ z56.object({
290110
+ action: z56.literal("move"),
289484
290111
  inputId: InputQueueIdSchema,
289485
- direction: z55.enum(["up", "down"])
290112
+ direction: z56.enum(["up", "down"])
289486
290113
  }).strict(),
289487
- z55.object({
289488
- action: z55.literal("remove"),
290114
+ z56.object({
290115
+ action: z56.literal("remove"),
289489
290116
  inputId: InputQueueIdSchema
289490
290117
  }).strict(),
289491
- z55.object({ action: z55.literal("clear") }).strict()
290118
+ z56.object({ action: z56.literal("clear") }).strict()
289492
290119
  ]).superRefine((action, context) => {
289493
290120
  if (action.action === "update" && action.prompt === void 0 && action.mode === void 0) {
289494
290121
  context.addIssue({
289495
- code: z55.ZodIssueCode.custom,
290122
+ code: z56.ZodIssueCode.custom,
289496
290123
  message: "A queued-input update must change the prompt or mode."
289497
290124
  });
289498
290125
  }
289499
290126
  });
289500
- var CancelRequestSchema = z55.object({ turnId: WebTurnIdSchema.nullish() }).strict();
289501
- var ApprovalDecisionSchema = z55.object({
290127
+ var CancelRequestSchema = z56.object({ turnId: WebTurnIdSchema.nullish() }).strict();
290128
+ var ApprovalDecisionSchema = z56.object({
289502
290129
  id: WebTurnIdSchema,
289503
- approved: z55.boolean()
290130
+ approved: z56.boolean()
289504
290131
  }).strict();
289505
- var SettingsPatchSchema = z55.object({
290132
+ var SettingsPatchSchema = z56.object({
289506
290133
  language: OrbitLanguageSchema.optional(),
289507
- provider: z55.string().trim().min(1).max(256).optional(),
289508
- model: z55.string().trim().min(1).max(200).optional(),
289509
- permissionMode: z55.enum(["strict", "normal", "auto", "plan"]).optional(),
289510
- webSearchEnabled: z55.boolean().optional(),
289511
- webSearchProvider: z55.enum(["auto", "searxng", "tavily", "bing", "duckduckgo"]).optional(),
289512
- webSearchMaxResults: z55.number().int().min(1).max(20).optional(),
289513
- skillsEnabled: z55.boolean().optional(),
289514
- skillsActivation: z55.enum(["auto", "explicit"]).optional(),
289515
- skillsMaxActive: z55.number().int().min(0).max(8).optional(),
289516
- skillsDisabled: z55.array(z55.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)).max(200).optional()
290134
+ provider: z56.string().trim().min(1).max(256).optional(),
290135
+ model: z56.string().trim().min(1).max(200).optional(),
290136
+ permissionMode: z56.enum(["strict", "normal", "auto", "plan"]).optional(),
290137
+ webSearchEnabled: z56.boolean().optional(),
290138
+ webSearchProvider: z56.enum(["auto", "searxng", "tavily", "bing", "duckduckgo"]).optional(),
290139
+ webSearchMaxResults: z56.number().int().min(1).max(20).optional(),
290140
+ skillsEnabled: z56.boolean().optional(),
290141
+ skillsActivation: z56.enum(["auto", "explicit"]).optional(),
290142
+ skillsMaxActive: z56.number().int().min(0).max(8).optional(),
290143
+ skillsDisabled: z56.array(z56.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)).max(200).optional()
289517
290144
  }).strict();
289518
- var CapabilityNameSchema = z55.string().trim().min(1).max(48).regex(/^[a-z0-9][a-z0-9-]*$/);
289519
- var CapabilityCreateSchema = z55.discriminatedUnion("kind", [
289520
- z55.object({
289521
- kind: z55.literal("skill"),
290145
+ var CapabilityNameSchema = z56.string().trim().min(1).max(48).regex(/^[a-z0-9][a-z0-9-]*$/);
290146
+ var CapabilityCreateSchema = z56.discriminatedUnion("kind", [
290147
+ z56.object({
290148
+ kind: z56.literal("skill"),
289522
290149
  name: CapabilityNameSchema,
289523
- description: z55.string().trim().min(1).max(2e3),
289524
- instructions: z55.string().trim().min(1).max(24e3),
289525
- scope: z55.enum(["local", "versioned"]).optional()
290150
+ description: z56.string().trim().min(1).max(2e3),
290151
+ instructions: z56.string().trim().min(1).max(24e3),
290152
+ scope: z56.enum(["local", "versioned"]).optional()
289526
290153
  }).strict(),
289527
- z55.object({
289528
- kind: z55.literal("workflow"),
290154
+ z56.object({
290155
+ kind: z56.literal("workflow"),
289529
290156
  name: CapabilityNameSchema,
289530
- description: z55.string().trim().min(1).max(240),
289531
- instructions: z55.string().trim().min(1).max(24e3),
289532
- skills: z55.array(CapabilityNameSchema).max(8),
289533
- argumentHint: z55.string().trim().min(1).max(160).optional()
290157
+ description: z56.string().trim().min(1).max(240),
290158
+ instructions: z56.string().trim().min(1).max(24e3),
290159
+ skills: z56.array(CapabilityNameSchema).max(8),
290160
+ argumentHint: z56.string().trim().min(1).max(160).optional()
289534
290161
  }).strict()
289535
290162
  ]);
289536
- var SessionActionSchema = z55.discriminatedUnion("action", [
289537
- z55.object({ action: z55.literal("new") }).strict(),
290163
+ var SessionActionSchema = z56.discriminatedUnion("action", [
290164
+ z56.object({ action: z56.literal("new") }).strict(),
289538
290165
  ...["resume", "archive", "restore", "delete"].map(
289539
- (action) => z55.object({
289540
- action: z55.literal(action),
289541
- sessionId: z55.string().trim().min(1).max(200).regex(/^[a-zA-Z0-9_-]+$/)
290166
+ (action) => z56.object({
290167
+ action: z56.literal(action),
290168
+ sessionId: z56.string().trim().min(1).max(200).regex(/^[a-zA-Z0-9_-]+$/)
289542
290169
  }).strict()
289543
290170
  )
289544
290171
  ]);
289545
- var ProjectActionSchema = z55.discriminatedUnion("action", [
289546
- z55.object({ action: z55.literal("pick") }).strict(),
289547
- z55.object({
289548
- action: z55.enum(["open", "create"]),
289549
- path: z55.string().trim().min(1).max(4096)
290172
+ var ProjectActionSchema = z56.discriminatedUnion("action", [
290173
+ z56.object({ action: z56.literal("pick") }).strict(),
290174
+ z56.object({
290175
+ action: z56.enum(["open", "create"]),
290176
+ path: z56.string().trim().min(1).max(4096)
289550
290177
  }).strict(),
289551
- z55.object({
289552
- action: z55.literal("remove"),
289553
- projectId: z55.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9_-]+$/)
290178
+ z56.object({
290179
+ action: z56.literal("remove"),
290180
+ projectId: z56.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9_-]+$/)
289554
290181
  }).strict()
289555
290182
  ]);
289556
- var ReviewActionSchema = z55.discriminatedUnion("action", [
289557
- z55.object({
289558
- action: z55.literal("rollback-file"),
289559
- path: z55.string().trim().min(1).max(4096)
290183
+ var ReviewActionSchema = z56.discriminatedUnion("action", [
290184
+ z56.object({
290185
+ action: z56.literal("rollback-file"),
290186
+ path: z56.string().trim().min(1).max(4096)
289560
290187
  }).strict(),
289561
- z55.object({
289562
- action: z55.literal("rewind"),
289563
- checkpointId: z55.string().trim().min(1).max(200).regex(/^[a-zA-Z0-9_-]+$/)
290188
+ z56.object({
290189
+ action: z56.literal("rewind"),
290190
+ checkpointId: z56.string().trim().min(1).max(200).regex(/^[a-zA-Z0-9_-]+$/)
289564
290191
  }).strict()
289565
290192
  ]);
289566
- var WebAgentIdSchema = z55.string().regex(/^agent_[a-z0-9-]+$/).max(128);
289567
- var WebAgentRunIdSchema = z55.string().regex(/^run_[a-z0-9-]+$/).max(128);
289568
- var AgentActionSchema = z55.discriminatedUnion("action", [
289569
- z55.object({ action: z55.literal("abort"), agentId: WebAgentIdSchema }).strict(),
289570
- z55.object({
289571
- action: z55.literal("steer"),
290193
+ var WebAgentIdSchema = z56.string().regex(/^agent_[a-z0-9-]+$/).max(128);
290194
+ var WebAgentRunIdSchema = z56.string().regex(/^run_[a-z0-9-]+$/).max(128);
290195
+ var AgentActionSchema = z56.discriminatedUnion("action", [
290196
+ z56.object({ action: z56.literal("abort"), agentId: WebAgentIdSchema }).strict(),
290197
+ z56.object({
290198
+ action: z56.literal("steer"),
289572
290199
  agentId: WebAgentIdSchema,
289573
- prompt: z55.string().trim().min(1).max(8e3)
290200
+ prompt: z56.string().trim().min(1).max(8e3)
289574
290201
  }).strict(),
289575
- z55.object({
289576
- action: z55.literal("resume"),
290202
+ z56.object({
290203
+ action: z56.literal("resume"),
289577
290204
  runId: WebAgentRunIdSchema,
289578
290205
  agentId: WebAgentIdSchema
289579
290206
  }).strict()
289580
290207
  ]);
289581
- var TaskActionSchema = z55.object({
289582
- action: z55.enum(["plan", "parallel-improve"]),
290208
+ var TaskActionSchema = z56.object({
290209
+ action: z56.enum(["plan", "parallel-improve"]),
289583
290210
  turnId: WebTurnIdSchema.optional()
289584
290211
  }).strict();
289585
- var CompletionQuerySchema = z55.string().trim().max(200);
290212
+ var CompletionQuerySchema = z56.string().trim().max(200);
289586
290213
  var IMAGE_ATTACHMENT_LIMIT_BYTES = 5 * 1024 * 1024;
289587
290214
  var IMAGE_ATTACHMENT_STORE_LIMIT = 16;
289588
290215
  var COMPLETION_CACHE_TTL_MS = 2e3;
@@ -291342,9 +291969,9 @@ import { execFileSync as execFileSync7 } from "child_process";
291342
291969
  import { existsSync as existsSync19, lstatSync as lstatSync7, mkdirSync as mkdirSync6, rmSync as rmSync5, writeFileSync as writeFileSync8 } from "fs";
291343
291970
  import { dirname as dirname11 } from "path";
291344
291971
  import picocolors13 from "picocolors";
291345
- import { z as z56 } from "zod";
291346
- var GitStatusCodeSchema = z56.string().length(2).regex(/^[ MADRCU?!]{2}$/);
291347
- var GitStatusPathSchema = z56.string().min(1).max(32768);
291972
+ import { z as z57 } from "zod";
291973
+ var GitStatusCodeSchema = z57.string().length(2).regex(/^[ MADRCU?!]{2}$/);
291974
+ var GitStatusPathSchema = z57.string().min(1).max(32768);
291348
291975
  var ROLLBACK_SNAPSHOT_FILE_MAX_BYTES = 16 * 1024 * 1024;
291349
291976
  var ROLLBACK_SNAPSHOT_TOTAL_MAX_BYTES = 128 * 1024 * 1024;
291350
291977
  var ROLLBACK_SNAPSHOT_MAX_PATHS = 1e4;
@@ -292115,32 +292742,32 @@ function ensureSessionTitle(loop, prompt) {
292115
292742
  }
292116
292743
 
292117
292744
  // src/runtime/ModelDiscovery.ts
292118
- import { z as z57 } from "zod";
292119
- var ModelEntrySchema = z57.object({
292120
- id: z57.unknown().optional(),
292121
- model: z57.unknown().optional(),
292122
- context_length: z57.unknown().optional(),
292123
- context_window: z57.unknown().optional(),
292124
- max_context_tokens: z57.unknown().optional(),
292125
- max_output_tokens: z57.unknown().optional(),
292126
- input_modalities: z57.unknown().optional(),
292127
- output_modalities: z57.unknown().optional(),
292128
- modalities: z57.unknown().optional(),
292129
- architecture: z57.unknown().optional(),
292130
- capabilities: z57.unknown().optional(),
292131
- supported_parameters: z57.unknown().optional(),
292132
- type: z57.unknown().optional(),
292133
- kind: z57.unknown().optional(),
292134
- task: z57.unknown().optional(),
292135
- endpoint: z57.unknown().optional(),
292136
- details: z57.unknown().optional()
292745
+ import { z as z58 } from "zod";
292746
+ var ModelEntrySchema = z58.object({
292747
+ id: z58.unknown().optional(),
292748
+ model: z58.unknown().optional(),
292749
+ context_length: z58.unknown().optional(),
292750
+ context_window: z58.unknown().optional(),
292751
+ max_context_tokens: z58.unknown().optional(),
292752
+ max_output_tokens: z58.unknown().optional(),
292753
+ input_modalities: z58.unknown().optional(),
292754
+ output_modalities: z58.unknown().optional(),
292755
+ modalities: z58.unknown().optional(),
292756
+ architecture: z58.unknown().optional(),
292757
+ capabilities: z58.unknown().optional(),
292758
+ supported_parameters: z58.unknown().optional(),
292759
+ type: z58.unknown().optional(),
292760
+ kind: z58.unknown().optional(),
292761
+ task: z58.unknown().optional(),
292762
+ endpoint: z58.unknown().optional(),
292763
+ details: z58.unknown().optional()
292137
292764
  }).passthrough();
292138
- var ModelListSchema = z57.union([
292139
- z57.object({ data: z57.array(ModelEntrySchema).max(1e3) }),
292140
- z57.object({ models: z57.array(ModelEntrySchema).max(1e3) }),
292141
- z57.array(ModelEntrySchema).max(1e3)
292765
+ var ModelListSchema = z58.union([
292766
+ z58.object({ data: z58.array(ModelEntrySchema).max(1e3) }),
292767
+ z58.object({ models: z58.array(ModelEntrySchema).max(1e3) }),
292768
+ z58.array(ModelEntrySchema).max(1e3)
292142
292769
  ]);
292143
- var DiscoveryUrlSchema = z57.string().url().max(4096).transform((value) => new URL(value));
292770
+ var DiscoveryUrlSchema = z58.string().url().max(4096).transform((value) => new URL(value));
292144
292771
  var MAX_MODEL_RESPONSE_BYTES = 2 * 1024 * 1024;
292145
292772
  async function discoverProviderModels(options) {
292146
292773
  const base = DiscoveryUrlSchema.parse(options.baseUrl.trim());
@@ -292305,9 +292932,9 @@ function normalizeModelEntries(entries) {
292305
292932
  }
292306
292933
  return { models, modelCapabilities };
292307
292934
  }
292308
- var OllamaShowSchema = z57.object({
292309
- capabilities: z57.array(z57.string().max(128)).max(64).optional(),
292310
- model_info: z57.record(z57.unknown()).optional()
292935
+ var OllamaShowSchema = z58.object({
292936
+ capabilities: z58.array(z58.string().max(128)).max(64).optional(),
292937
+ model_info: z58.record(z58.unknown()).optional()
292311
292938
  }).passthrough();
292312
292939
  async function enrichOllamaCapabilities(base, models, target, fetchImpl, signal) {
292313
292940
  const endpoint = new URL(base);
@@ -292788,9 +293415,9 @@ function isPickerCancellation(error) {
292788
293415
 
292789
293416
  // src/runtime/commands/SessionMetadataCommandHandler.ts
292790
293417
  import picocolors15 from "picocolors";
292791
- import { z as z58 } from "zod";
292792
- var GoalSchema = z58.string().trim().min(1).max(4e3);
292793
- var SessionTitleSchema = z58.string().trim().min(1).max(160);
293418
+ import { z as z59 } from "zod";
293419
+ var GoalSchema = z59.string().trim().min(1).max(4e3);
293420
+ var SessionTitleSchema = z59.string().trim().min(1).max(160);
292794
293421
  function handleSessionMetadataCommand(command, argument, dependencies) {
292795
293422
  if (command === "/goal") {
292796
293423
  handleGoal(argument, dependencies);
@@ -292855,9 +293482,9 @@ function handleRename(argument, { loop, isZh, printOutput }) {
292855
293482
 
292856
293483
  // src/runtime/commands/WorkspaceStateCommandHandler.ts
292857
293484
  import picocolors16 from "picocolors";
292858
- import { z as z59 } from "zod";
292859
- var TextSchema = z59.string().trim().min(1).max(2e3);
292860
- var ItemReferenceSchema = z59.string().trim().min(1).max(100);
293485
+ import { z as z60 } from "zod";
293486
+ var TextSchema = z60.string().trim().min(1).max(2e3);
293487
+ var ItemReferenceSchema = z60.string().trim().min(1).max(100);
292861
293488
  function handleWorkspaceStateCommand(command, argument, dependencies) {
292862
293489
  if (command === "/memory") {
292863
293490
  handleMemory(argument, dependencies);
@@ -293139,11 +293766,11 @@ ${usage(false)}`
293139
293766
  // src/commands/update.ts
293140
293767
  import readline4 from "readline";
293141
293768
  import picocolors17 from "picocolors";
293142
- import { z as z60 } from "zod";
293143
- var UpdateCommandOptionsSchema = z60.object({
293144
- check: z60.boolean().default(false),
293145
- yes: z60.boolean().default(false),
293146
- json: z60.boolean().default(false),
293769
+ import { z as z61 } from "zod";
293770
+ var UpdateCommandOptionsSchema = z61.object({
293771
+ check: z61.boolean().default(false),
293772
+ yes: z61.boolean().default(false),
293773
+ json: z61.boolean().default(false),
293147
293774
  channel: UpdateChannelSchema.default("stable")
293148
293775
  }).strict();
293149
293776
  async function runUpdate(currentVersion, rawOptions, dependencies = {}) {
@@ -293276,18 +293903,18 @@ async function confirmUpdate(prompt) {
293276
293903
  }
293277
293904
 
293278
293905
  // src/runtime/review/ReviewCommand.ts
293279
- import { z as z61 } from "zod";
293280
- var ReviewPresetSchema = z61.enum([
293906
+ import { z as z65 } from "zod";
293907
+ var ReviewPresetSchema = z65.enum([
293281
293908
  "comprehensive",
293282
293909
  "security",
293283
293910
  "tests",
293284
293911
  "performance",
293285
293912
  "accessibility"
293286
293913
  ]);
293287
- var ReviewScopeSchema = z61.discriminatedUnion("kind", [
293288
- z61.object({ kind: z61.literal("working-tree") }),
293289
- z61.object({ kind: z61.literal("commit"), ref: z61.string().min(1).max(200) }),
293290
- z61.object({ kind: z61.literal("branch"), ref: z61.string().min(1).max(200) })
293914
+ var ReviewScopeSchema = z65.discriminatedUnion("kind", [
293915
+ z65.object({ kind: z65.literal("working-tree") }),
293916
+ z65.object({ kind: z65.literal("commit"), ref: z65.string().min(1).max(200) }),
293917
+ z65.object({ kind: z65.literal("branch"), ref: z65.string().min(1).max(200) })
293291
293918
  ]);
293292
293919
  var SAFE_GIT_REF = /^[A-Za-z0-9][A-Za-z0-9._/@{}~^:+-]{0,199}$/;
293293
293920
  function parseReviewCommand(rawArguments) {
@@ -293366,6 +293993,32 @@ ${request.customInstructions}` : "";
293366
293993
 
293367
293994
  // src/runtime/CommandRouter.ts
293368
293995
  import { randomUUID as randomUUID11 } from "crypto";
293996
+
293997
+ // src/runtime/CommitSafety.ts
293998
+ var SENSITIVE_DIFF_PATH = /(?:^|\/)(?:\.env(?:\.|$)|\.npmrc$|\.pypirc$|\.netrc$|\.ssh\/|\.gnupg\/|\.aws\/|\.azure\/|\.kube\/|\.git\/|\.orbit\/)|\.(?:key|pem|p12|pfx)$/i;
293999
+ var CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/g;
294000
+ var MAX_COMMIT_SUBJECT_LENGTH = 120;
294001
+ function buildCommitDiffForModel(diff, maxChars = 2e4) {
294002
+ const blocks = diff.split(/(?=^diff --git )/m);
294003
+ const visible = blocks.map((block2) => {
294004
+ const path9 = block2.match(/^diff --git a\/(.+?) b\/(.+)$/m)?.[2];
294005
+ if (path9 && SENSITIVE_DIFF_PATH.test(path9)) {
294006
+ return `diff --git a/${path9} b/${path9}
294007
+ [Orbit omitted protected file contents]`;
294008
+ }
294009
+ return redactSecrets(block2);
294010
+ });
294011
+ return visible.join("").slice(0, Math.max(0, maxChars));
294012
+ }
294013
+ function normalizeCommitMessage(message2) {
294014
+ const subject = redactSecrets(message2).replace(CONTROL_CHARACTERS, " ").replace(/^\s*["'`]+|["'`]+\s*$/g, "").replace(/\s+/g, " ").trim().slice(0, MAX_COMMIT_SUBJECT_LENGTH).trim();
294015
+ if (!subject) return "chore: update project";
294016
+ return /^(?:feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\([a-z0-9._/-]+\))?!?:\s+\S/i.test(
294017
+ subject
294018
+ ) ? subject : `chore: ${subject}`.slice(0, MAX_COMMIT_SUBJECT_LENGTH).trim();
294019
+ }
294020
+
294021
+ // src/runtime/CommandRouter.ts
293369
294022
  var require2 = createRequire2(import.meta.url);
293370
294023
  function stripAnsi4(value) {
293371
294024
  return value.replace(/\u001b\[[0-9;]*m/g, "");
@@ -294141,12 +294794,14 @@ var CommandRouter = class {
294141
294794
  try {
294142
294795
  let diff = execSync3("git diff --cached", {
294143
294796
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
294144
- cwd
294797
+ cwd,
294798
+ env: buildSanitizedChildEnvironment()
294145
294799
  }).toString().trim();
294146
294800
  if (!diff) {
294147
294801
  const unstaged = execSync3("git status --porcelain", {
294148
294802
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
294149
- cwd
294803
+ cwd,
294804
+ env: buildSanitizedChildEnvironment()
294150
294805
  }).toString().trim();
294151
294806
  if (!unstaged) {
294152
294807
  this.printOutput(
@@ -294172,11 +294827,13 @@ var CommandRouter = class {
294172
294827
  );
294173
294828
  execSync3("git add -A", {
294174
294829
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
294175
- cwd
294830
+ cwd,
294831
+ env: buildSanitizedChildEnvironment()
294176
294832
  });
294177
294833
  diff = execSync3("git diff --cached", {
294178
294834
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
294179
- cwd
294835
+ cwd,
294836
+ env: buildSanitizedChildEnvironment()
294180
294837
  }).toString().trim();
294181
294838
  if (!diff) {
294182
294839
  this.printOutput(
@@ -294201,9 +294858,9 @@ var CommandRouter = class {
294201
294858
  content: [
294202
294859
  {
294203
294860
  type: "text",
294204
- text: `Generate a concise, high-quality conventional git commit message (e.g. feat(cli): add autocomplete) for the following git diff. Output ONLY the commit message, no formatting, no markdown, no quotes, just the text:
294861
+ text: `Generate a concise, high-quality conventional git commit message (e.g. feat(cli): add autocomplete) for the following redacted git diff. Output ONLY the commit message, no formatting, no markdown, no quotes, just the text:
294205
294862
 
294206
- ${diff.substring(0, 2e4)}`
294863
+ ${buildCommitDiffForModel(diff)}`
294207
294864
  }
294208
294865
  ]
294209
294866
  }
@@ -294216,17 +294873,16 @@ ${diff.substring(0, 2e4)}`
294216
294873
  generatedMessage += event.text;
294217
294874
  }
294218
294875
  }
294219
- finalMsg = generatedMessage.trim().replace(/^["']|["']$/g, "");
294220
- if (!finalMsg) {
294221
- finalMsg = "chore: auto-commit";
294222
- }
294876
+ finalMsg = normalizeCommitMessage(generatedMessage);
294223
294877
  }
294878
+ finalMsg = normalizeCommitMessage(finalMsg);
294224
294879
  this.printOutput(
294225
294880
  `Committing changes with message: "${picocolors18.green(finalMsg)}"`
294226
294881
  );
294227
294882
  execFileSync9("git", ["commit", "-m", finalMsg], {
294228
294883
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
294229
- cwd
294884
+ cwd,
294885
+ env: buildSanitizedChildEnvironment()
294230
294886
  });
294231
294887
  this.printOutput(
294232
294888
  picocolors18.green("\u2714 Git commit created successfully.")
@@ -295224,20 +295880,20 @@ ${picocolors18.green("\u2714")} Switched security mode to: ${picocolors18.green(
295224
295880
  };
295225
295881
 
295226
295882
  // src/runtime/LocalRuntimeState.ts
295227
- import { z as z65 } from "zod";
295883
+ import { z as z66 } from "zod";
295228
295884
  var LOCAL_RUNTIME_STATE_MAX_BYTES = 1048576;
295229
- var LocalSkillsStateSchema = z65.object({
295230
- enabled: z65.boolean().optional(),
295231
- activation: z65.enum(["auto", "explicit"]).optional(),
295232
- maxActive: z65.number().int().min(0).max(8).optional(),
295233
- disabled: z65.array(z65.string().min(1).max(128)).max(1e3).optional()
295885
+ var LocalSkillsStateSchema = z66.object({
295886
+ enabled: z66.boolean().optional(),
295887
+ activation: z66.enum(["auto", "explicit"]).optional(),
295888
+ maxActive: z66.number().int().min(0).max(8).optional(),
295889
+ disabled: z66.array(z66.string().min(1).max(128)).max(1e3).optional()
295234
295890
  });
295235
- var LocalRuntimeStateSchema = z65.object({
295236
- lastSessionId: z65.string().min(1).max(1e3).optional(),
295237
- lastProvider: z65.string().min(1).max(256).optional(),
295238
- lastModel: z65.string().max(512).optional(),
295891
+ var LocalRuntimeStateSchema = z66.object({
295892
+ lastSessionId: z66.string().min(1).max(1e3).optional(),
295893
+ lastProvider: z66.string().min(1).max(256).optional(),
295894
+ lastModel: z66.string().max(512).optional(),
295239
295895
  language: OrbitLanguageSchema.optional(),
295240
- permissionMode: z65.enum(["strict", "normal", "auto", "plan"]).optional(),
295896
+ permissionMode: z66.enum(["strict", "normal", "auto", "plan"]).optional(),
295241
295897
  skills: LocalSkillsStateSchema.optional()
295242
295898
  });
295243
295899
  function readLocalRuntimeState(cwd) {
@@ -295268,16 +295924,16 @@ function writeLocalRuntimeState(cwd, patch) {
295268
295924
  }
295269
295925
 
295270
295926
  // src/runtime/ReplController.ts
295271
- var AutocompleteRequestSchema = z66.object({
295272
- prefix: z66.string().max(2e4),
295273
- suffix: z66.string().max(2e4),
295274
- windowId: z66.string().max(1e3).optional()
295927
+ var AutocompleteRequestSchema = z67.object({
295928
+ prefix: z67.string().max(2e4),
295929
+ suffix: z67.string().max(2e4),
295930
+ windowId: z67.string().max(1e3).optional()
295275
295931
  });
295276
295932
  var AUTOCOMPLETE_BODY_LIMIT_BYTES = 1e5;
295277
295933
  var AUTOCOMPLETE_MAX_CONCURRENCY = 4;
295278
- var AutocompleteEndpointSchema = z66.object({
295279
- port: z66.number().int().min(1).max(65535),
295280
- token: z66.string().min(32).max(256)
295934
+ var AutocompleteEndpointSchema = z67.object({
295935
+ port: z67.number().int().min(1).max(65535),
295936
+ token: z67.string().min(32).max(256)
295281
295937
  });
295282
295938
  function getRunOutcomeMessage2(outcome) {
295283
295939
  if (!outcome || outcome.status === "completed") return void 0;
@@ -296299,36 +296955,36 @@ function isRecord8(value) {
296299
296955
  }
296300
296956
 
296301
296957
  // src/commands/LSPServer.ts
296302
- import { z as z67 } from "zod";
296958
+ import { z as z68 } from "zod";
296303
296959
  var MAX_LSP_HEADER_BYTES = 8 * 1024;
296304
296960
  var MAX_LSP_BODY_BYTES = 8 * 1024 * 1024;
296305
- var JsonRpcIdSchema = z67.union([z67.string(), z67.number(), z67.null()]);
296306
- var JSONRPCMessageSchema = z67.object({
296307
- jsonrpc: z67.literal("2.0"),
296961
+ var JsonRpcIdSchema = z68.union([z68.string(), z68.number(), z68.null()]);
296962
+ var JSONRPCMessageSchema = z68.object({
296963
+ jsonrpc: z68.literal("2.0"),
296308
296964
  id: JsonRpcIdSchema.optional(),
296309
- method: z67.string().min(1).max(512),
296310
- params: z67.unknown().optional()
296965
+ method: z68.string().min(1).max(512),
296966
+ params: z68.unknown().optional()
296311
296967
  }).strict();
296312
- var TextDocumentIdentifierSchema = z67.object({
296313
- uri: z67.string().min(1).max(16384)
296968
+ var TextDocumentIdentifierSchema = z68.object({
296969
+ uri: z68.string().min(1).max(16384)
296314
296970
  });
296315
- var DidOpenParamsSchema = z67.object({
296971
+ var DidOpenParamsSchema = z68.object({
296316
296972
  textDocument: TextDocumentIdentifierSchema.extend({
296317
- text: z67.string().max(MAX_LSP_BODY_BYTES)
296973
+ text: z68.string().max(MAX_LSP_BODY_BYTES)
296318
296974
  }).passthrough()
296319
296975
  });
296320
- var DidChangeParamsSchema = z67.object({
296976
+ var DidChangeParamsSchema = z68.object({
296321
296977
  textDocument: TextDocumentIdentifierSchema,
296322
- contentChanges: z67.array(z67.object({ text: z67.string().max(MAX_LSP_BODY_BYTES) }).passthrough()).min(1).max(100)
296978
+ contentChanges: z68.array(z68.object({ text: z68.string().max(MAX_LSP_BODY_BYTES) }).passthrough()).min(1).max(100)
296323
296979
  });
296324
- var DidCloseParamsSchema = z67.object({
296980
+ var DidCloseParamsSchema = z68.object({
296325
296981
  textDocument: TextDocumentIdentifierSchema
296326
296982
  });
296327
- var CompletionParamsSchema = z67.object({
296983
+ var CompletionParamsSchema = z68.object({
296328
296984
  textDocument: TextDocumentIdentifierSchema,
296329
- position: z67.object({
296330
- line: z67.number().int().nonnegative(),
296331
- character: z67.number().int().nonnegative()
296985
+ position: z68.object({
296986
+ line: z68.number().int().nonnegative(),
296987
+ character: z68.number().int().nonnegative()
296332
296988
  })
296333
296989
  });
296334
296990
  var JSONRPCReader = class {
@@ -296574,7 +297230,7 @@ ${completion}
296574
297230
  );
296575
297231
  }
296576
297232
  } catch (error) {
296577
- if (error instanceof z67.ZodError) {
297233
+ if (error instanceof z68.ZodError) {
296578
297234
  sendError(message2.id, -32602, "Invalid method parameters.");
296579
297235
  return;
296580
297236
  }
@@ -297100,10 +297756,10 @@ import {
297100
297756
  } from "fs";
297101
297757
  import { dirname as dirname14, resolve as resolve15 } from "path";
297102
297758
  import { randomUUID as randomUUID13 } from "crypto";
297103
- import { z as z68 } from "zod";
297104
- var TraceOptionsSchema = z68.object({
297105
- full: z68.boolean().default(false),
297106
- out: z68.string().trim().min(1).max(4096).optional()
297759
+ import { z as z69 } from "zod";
297760
+ var TraceOptionsSchema = z69.object({
297761
+ full: z69.boolean().default(false),
297762
+ out: z69.string().trim().min(1).max(4096).optional()
297107
297763
  });
297108
297764
  function runTraceExport(cwd, sessionId, options = {}) {
297109
297765
  const value = TraceOptionsSchema.parse(options);
@@ -297158,16 +297814,16 @@ import { randomUUID as randomUUID14 } from "crypto";
297158
297814
  import { promisify as promisify5 } from "util";
297159
297815
  import picocolors25 from "picocolors";
297160
297816
  import { parse as parseYaml4 } from "yaml";
297161
- import { z as z69 } from "zod";
297817
+ import { z as z70 } from "zod";
297162
297818
  var exec5 = promisify5(execCallback);
297163
297819
  var MAX_SUITE_BYTES = 1024 * 1024;
297164
297820
  var MAX_VERIFICATION_OUTPUT = 4e3;
297165
- var EvalOptionsSchema = z69.object({
297166
- provider: z69.string().trim().min(1).optional(),
297167
- model: z69.string().trim().min(1).optional(),
297168
- task: z69.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
297169
- allowCommands: z69.boolean().default(false),
297170
- json: z69.boolean().default(false)
297821
+ var EvalOptionsSchema = z70.object({
297822
+ provider: z70.string().trim().min(1).optional(),
297823
+ model: z70.string().trim().min(1).optional(),
297824
+ task: z70.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
297825
+ allowCommands: z70.boolean().default(false),
297826
+ json: z70.boolean().default(false)
297171
297827
  });
297172
297828
  async function runEval(cwd, suiteFile, options = {}) {
297173
297829
  const value = EvalOptionsSchema.parse(options);
@@ -297515,7 +298171,7 @@ function safeSummary(value) {
297515
298171
  import readline6 from "readline";
297516
298172
  import picocolors26 from "picocolors";
297517
298173
  import { resolve as resolve17 } from "path";
297518
- import { z as z71 } from "zod";
298174
+ import { z as z74 } from "zod";
297519
298175
 
297520
298176
  // src/runtime/CleanupManager.ts
297521
298177
  import {
@@ -297527,10 +298183,10 @@ import {
297527
298183
  } from "fs";
297528
298184
  import { homedir as homedir11 } from "os";
297529
298185
  import { basename as basename6, join as join20, parse as parse5, resolve as resolve16 } from "path";
297530
- import { z as z70 } from "zod";
297531
- var CleanupScopeSchema = z70.enum(["user", "project"]);
298186
+ import { z as z71 } from "zod";
298187
+ var CleanupScopeSchema = z71.enum(["user", "project"]);
297532
298188
  function buildCleanupPlan(options) {
297533
- const scopes = z70.array(CleanupScopeSchema).min(1).parse(options.scopes);
298189
+ const scopes = z71.array(CleanupScopeSchema).min(1).parse(options.scopes);
297534
298190
  const homeDirectory = resolve16(options.homeDirectory ?? homedir11());
297535
298191
  const projectDirectory = resolve16(options.projectDirectory ?? options.cwd);
297536
298192
  const candidates = scopes.map((scope) => ({
@@ -297688,12 +298344,12 @@ function safeInventoryWarning(targetPath, error) {
297688
298344
  }
297689
298345
 
297690
298346
  // src/commands/clean.ts
297691
- var CleanCommandOptionsSchema = z71.object({
297692
- user: z71.boolean().default(false),
297693
- project: z71.union([z71.boolean(), z71.string().min(1).max(4096)]).optional(),
297694
- all: z71.boolean().default(false),
297695
- yes: z71.boolean().default(false),
297696
- json: z71.boolean().default(false)
298347
+ var CleanCommandOptionsSchema = z74.object({
298348
+ user: z74.boolean().default(false),
298349
+ project: z74.union([z74.boolean(), z74.string().min(1).max(4096)]).optional(),
298350
+ all: z74.boolean().default(false),
298351
+ yes: z74.boolean().default(false),
298352
+ json: z74.boolean().default(false)
297697
298353
  }).strict();
297698
298354
  async function runClean(cwd, rawOptions, dependencies = {}) {
297699
298355
  const options = CleanCommandOptionsSchema.parse(rawOptions);
@@ -297808,7 +298464,7 @@ async function confirmDeletion(prompt) {
297808
298464
  // src/commands/backup.ts
297809
298465
  import { basename as basename7, resolve as resolve19 } from "path";
297810
298466
  import picocolors27 from "picocolors";
297811
- import { z as z75 } from "zod";
298467
+ import { z as z76 } from "zod";
297812
298468
 
297813
298469
  // src/runtime/ProjectBackup.ts
297814
298470
  import {
@@ -297822,25 +298478,25 @@ import {
297822
298478
  } from "fs";
297823
298479
  import { createHash as createHash9, randomUUID as randomUUID15 } from "crypto";
297824
298480
  import { dirname as dirname16, isAbsolute as isAbsolute8, join as join21, relative as relative9, resolve as resolve18, sep as sep2 } from "path";
297825
- import { z as z74 } from "zod";
298481
+ import { z as z75 } from "zod";
297826
298482
  var MAX_BACKUP_BYTES = 64 * 1024 * 1024;
297827
298483
  var MAX_SERIALIZED_BACKUP_BYTES = 96 * 1024 * 1024;
297828
298484
  var MAX_BACKUP_FILES = 1e4;
297829
298485
  var MAX_BACKUP_TREE_ENTRIES = 5e4;
297830
298486
  var MAX_BACKUP_TREE_DEPTH = 64;
297831
298487
  var SHA256_PATTERN = /^[a-f0-9]{64}$/;
297832
- var BackupFileSchema = z74.object({
297833
- path: z74.string().min(1).max(4096),
297834
- size: z74.number().int().min(0).max(MAX_BACKUP_BYTES),
297835
- sha256: z74.string().regex(SHA256_PATTERN),
297836
- content: z74.string().max(Math.ceil(MAX_BACKUP_BYTES * 4 / 3) + 8)
298488
+ var BackupFileSchema = z75.object({
298489
+ path: z75.string().min(1).max(4096),
298490
+ size: z75.number().int().min(0).max(MAX_BACKUP_BYTES),
298491
+ sha256: z75.string().regex(SHA256_PATTERN),
298492
+ content: z75.string().max(Math.ceil(MAX_BACKUP_BYTES * 4 / 3) + 8)
297837
298493
  });
297838
- var ProjectBackupBundleSchema = z74.object({
297839
- schemaVersion: z74.literal(1),
297840
- kind: z74.literal("orbit-project-backup"),
297841
- createdAt: z74.string().datetime(),
297842
- sourceName: z74.string().min(1).max(512),
297843
- files: z74.array(BackupFileSchema).max(MAX_BACKUP_FILES)
298494
+ var ProjectBackupBundleSchema = z75.object({
298495
+ schemaVersion: z75.literal(1),
298496
+ kind: z75.literal("orbit-project-backup"),
298497
+ createdAt: z75.string().datetime(),
298498
+ sourceName: z75.string().min(1).max(512),
298499
+ files: z75.array(BackupFileSchema).max(MAX_BACKUP_FILES)
297844
298500
  }).superRefine((bundle, context) => {
297845
298501
  let totalBytes = 0;
297846
298502
  const seen = /* @__PURE__ */ new Set();
@@ -297848,7 +298504,7 @@ var ProjectBackupBundleSchema = z74.object({
297848
298504
  totalBytes += file.size;
297849
298505
  if (totalBytes > MAX_BACKUP_BYTES) {
297850
298506
  context.addIssue({
297851
- code: z74.ZodIssueCode.custom,
298507
+ code: z75.ZodIssueCode.custom,
297852
298508
  message: `Backup exceeds ${MAX_BACKUP_BYTES} bytes.`
297853
298509
  });
297854
298510
  break;
@@ -297856,14 +298512,14 @@ var ProjectBackupBundleSchema = z74.object({
297856
298512
  const normalized = normalizeBundlePath(file.path);
297857
298513
  if (!normalized || normalized !== file.path) {
297858
298514
  context.addIssue({
297859
- code: z74.ZodIssueCode.custom,
298515
+ code: z75.ZodIssueCode.custom,
297860
298516
  message: `Unsafe backup path: ${file.path}`
297861
298517
  });
297862
298518
  continue;
297863
298519
  }
297864
298520
  if (seen.has(normalized.toLowerCase())) {
297865
298521
  context.addIssue({
297866
- code: z74.ZodIssueCode.custom,
298522
+ code: z75.ZodIssueCode.custom,
297867
298523
  message: `Duplicate backup path: ${file.path}`
297868
298524
  });
297869
298525
  }
@@ -298096,9 +298752,9 @@ function formatBytes2(bytes) {
298096
298752
  }
298097
298753
 
298098
298754
  // src/commands/backup.ts
298099
- var BackupOptionsSchema = z75.object({
298100
- output: z75.string().min(1).max(4096).optional(),
298101
- json: z75.boolean().default(false)
298755
+ var BackupOptionsSchema = z76.object({
298756
+ output: z76.string().min(1).max(4096).optional(),
298757
+ json: z76.boolean().default(false)
298102
298758
  }).strict();
298103
298759
  function runBackupCreate(cwd, rawOptions = {}) {
298104
298760
  const options = BackupOptionsSchema.parse(rawOptions);
@@ -298198,21 +298854,21 @@ import {
298198
298854
  import { randomUUID as randomUUID16 } from "crypto";
298199
298855
  import { dirname as dirname17, isAbsolute as isAbsolute9, join as join26, relative as relative10, resolve as resolve20, sep as sep3 } from "path";
298200
298856
  import { homedir as homedir12 } from "os";
298201
- import { z as z76 } from "zod";
298202
- var InstalledExtensionSchema2 = z76.object({
298857
+ import { z as z77 } from "zod";
298858
+ var InstalledExtensionSchema2 = z77.object({
298203
298859
  id: InstalledExtensionIdSchema,
298204
- displayName: z76.string().min(1).max(256),
298205
- version: z76.string().min(1).max(128),
298206
- digest: z76.string().regex(/^[a-f0-9]{64}$/),
298860
+ displayName: z77.string().min(1).max(256),
298861
+ version: z77.string().min(1).max(128),
298862
+ digest: z77.string().regex(/^[a-f0-9]{64}$/),
298207
298863
  digestAlgorithm: ExtensionDigestAlgorithmSchema.default("sha256-v1"),
298208
- installedAt: z76.string().datetime(),
298209
- trusted: z76.boolean(),
298210
- path: z76.string().min(1).max(4096),
298211
- manifestFile: z76.string().min(1).max(4096).default("extension.yaml")
298864
+ installedAt: z77.string().datetime(),
298865
+ trusted: z77.boolean(),
298866
+ path: z77.string().min(1).max(4096),
298867
+ manifestFile: z77.string().min(1).max(4096).default("extension.yaml")
298212
298868
  });
298213
- var ExtensionRegistrySchema2 = z76.object({
298214
- schemaVersion: z76.literal(1),
298215
- extensions: z76.array(InstalledExtensionSchema2).max(500).default([])
298869
+ var ExtensionRegistrySchema2 = z77.object({
298870
+ schemaVersion: z77.literal(1),
298871
+ extensions: z77.array(InstalledExtensionSchema2).max(500).default([])
298216
298872
  });
298217
298873
  var ExtensionManager = class {
298218
298874
  orbitDir;
@@ -298824,7 +299480,7 @@ program.command("bench").description(
298824
299480
  "run a repeated stable-prefix DeepSeek cache profile (minimum 3 samples)"
298825
299481
  ).option(
298826
299482
  "--thinking <mode>",
298827
- "thinking mode: disabled, high, or max (legacy low maps to high; DeepSeek V4 defaults to high)"
299483
+ "thinking mode: disabled, low, high, or max (provider default: high; Orbit Auto may select low for simple Flash turns)"
298828
299484
  ).option(
298829
299485
  "--min-cache-hit <ratio>",
298830
299486
  "fail when repeated-sample average cache hit is below ratio, e.g. 0.75 or 75"