@scalequality/cli 0.4.41 → 0.4.42

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/connect.cjs CHANGED
@@ -34,9 +34,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
34
34
  mod
35
35
  ));
36
36
 
37
- // node_modules/ws/lib/constants.js
37
+ // ../aig-folder-scope/node_modules/ws/lib/constants.js
38
38
  var require_constants = __commonJS({
39
- "node_modules/ws/lib/constants.js"(exports2, module2) {
39
+ "../aig-folder-scope/node_modules/ws/lib/constants.js"(exports2, module2) {
40
40
  "use strict";
41
41
  var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
42
42
  var hasBlob = typeof Blob !== "undefined";
@@ -57,9 +57,9 @@ var require_constants = __commonJS({
57
57
  }
58
58
  });
59
59
 
60
- // node_modules/ws/lib/buffer-util.js
60
+ // ../aig-folder-scope/node_modules/ws/lib/buffer-util.js
61
61
  var require_buffer_util = __commonJS({
62
- "node_modules/ws/lib/buffer-util.js"(exports2, module2) {
62
+ "../aig-folder-scope/node_modules/ws/lib/buffer-util.js"(exports2, module2) {
63
63
  "use strict";
64
64
  var { EMPTY_BUFFER } = require_constants();
65
65
  var FastBuffer = Buffer[Symbol.species];
@@ -132,9 +132,9 @@ var require_buffer_util = __commonJS({
132
132
  }
133
133
  });
134
134
 
135
- // node_modules/ws/lib/limiter.js
135
+ // ../aig-folder-scope/node_modules/ws/lib/limiter.js
136
136
  var require_limiter = __commonJS({
137
- "node_modules/ws/lib/limiter.js"(exports2, module2) {
137
+ "../aig-folder-scope/node_modules/ws/lib/limiter.js"(exports2, module2) {
138
138
  "use strict";
139
139
  var kDone = /* @__PURE__ */ Symbol("kDone");
140
140
  var kRun = /* @__PURE__ */ Symbol("kRun");
@@ -182,9 +182,9 @@ var require_limiter = __commonJS({
182
182
  }
183
183
  });
184
184
 
185
- // node_modules/ws/lib/permessage-deflate.js
185
+ // ../aig-folder-scope/node_modules/ws/lib/permessage-deflate.js
186
186
  var require_permessage_deflate = __commonJS({
187
- "node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
187
+ "../aig-folder-scope/node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
188
188
  "use strict";
189
189
  var zlib = require("zlib");
190
190
  var bufferUtil = require_buffer_util();
@@ -565,9 +565,9 @@ var require_permessage_deflate = __commonJS({
565
565
  }
566
566
  });
567
567
 
568
- // node_modules/ws/lib/validation.js
568
+ // ../aig-folder-scope/node_modules/ws/lib/validation.js
569
569
  var require_validation = __commonJS({
570
- "node_modules/ws/lib/validation.js"(exports2, module2) {
570
+ "../aig-folder-scope/node_modules/ws/lib/validation.js"(exports2, module2) {
571
571
  "use strict";
572
572
  var { isUtf8 } = require("buffer");
573
573
  var { hasBlob } = require_constants();
@@ -766,9 +766,9 @@ var require_validation = __commonJS({
766
766
  }
767
767
  });
768
768
 
769
- // node_modules/ws/lib/receiver.js
769
+ // ../aig-folder-scope/node_modules/ws/lib/receiver.js
770
770
  var require_receiver = __commonJS({
771
- "node_modules/ws/lib/receiver.js"(exports2, module2) {
771
+ "../aig-folder-scope/node_modules/ws/lib/receiver.js"(exports2, module2) {
772
772
  "use strict";
773
773
  var { Writable } = require("stream");
774
774
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -1389,9 +1389,9 @@ var require_receiver = __commonJS({
1389
1389
  }
1390
1390
  });
1391
1391
 
1392
- // node_modules/ws/lib/sender.js
1392
+ // ../aig-folder-scope/node_modules/ws/lib/sender.js
1393
1393
  var require_sender = __commonJS({
1394
- "node_modules/ws/lib/sender.js"(exports2, module2) {
1394
+ "../aig-folder-scope/node_modules/ws/lib/sender.js"(exports2, module2) {
1395
1395
  "use strict";
1396
1396
  var { Duplex } = require("stream");
1397
1397
  var { randomFillSync } = require("crypto");
@@ -1882,9 +1882,9 @@ var require_sender = __commonJS({
1882
1882
  }
1883
1883
  });
1884
1884
 
1885
- // node_modules/ws/lib/event-target.js
1885
+ // ../aig-folder-scope/node_modules/ws/lib/event-target.js
1886
1886
  var require_event_target = __commonJS({
1887
- "node_modules/ws/lib/event-target.js"(exports2, module2) {
1887
+ "../aig-folder-scope/node_modules/ws/lib/event-target.js"(exports2, module2) {
1888
1888
  "use strict";
1889
1889
  var { kForOnEventAttribute, kListener } = require_constants();
1890
1890
  var kCode = /* @__PURE__ */ Symbol("kCode");
@@ -2111,9 +2111,9 @@ var require_event_target = __commonJS({
2111
2111
  }
2112
2112
  });
2113
2113
 
2114
- // node_modules/ws/lib/extension.js
2114
+ // ../aig-folder-scope/node_modules/ws/lib/extension.js
2115
2115
  var require_extension = __commonJS({
2116
- "node_modules/ws/lib/extension.js"(exports2, module2) {
2116
+ "../aig-folder-scope/node_modules/ws/lib/extension.js"(exports2, module2) {
2117
2117
  "use strict";
2118
2118
  var { tokenChars } = require_validation();
2119
2119
  function push(dest, name, elem) {
@@ -2264,9 +2264,9 @@ var require_extension = __commonJS({
2264
2264
  }
2265
2265
  });
2266
2266
 
2267
- // node_modules/ws/lib/websocket.js
2267
+ // ../aig-folder-scope/node_modules/ws/lib/websocket.js
2268
2268
  var require_websocket = __commonJS({
2269
- "node_modules/ws/lib/websocket.js"(exports2, module2) {
2269
+ "../aig-folder-scope/node_modules/ws/lib/websocket.js"(exports2, module2) {
2270
2270
  "use strict";
2271
2271
  var EventEmitter = require("events");
2272
2272
  var https = require("https");
@@ -3160,9 +3160,9 @@ var require_websocket = __commonJS({
3160
3160
  }
3161
3161
  });
3162
3162
 
3163
- // node_modules/ws/lib/stream.js
3163
+ // ../aig-folder-scope/node_modules/ws/lib/stream.js
3164
3164
  var require_stream = __commonJS({
3165
- "node_modules/ws/lib/stream.js"(exports2, module2) {
3165
+ "../aig-folder-scope/node_modules/ws/lib/stream.js"(exports2, module2) {
3166
3166
  "use strict";
3167
3167
  var WebSocket2 = require_websocket();
3168
3168
  var { Duplex } = require("stream");
@@ -3258,9 +3258,9 @@ var require_stream = __commonJS({
3258
3258
  }
3259
3259
  });
3260
3260
 
3261
- // node_modules/ws/lib/subprotocol.js
3261
+ // ../aig-folder-scope/node_modules/ws/lib/subprotocol.js
3262
3262
  var require_subprotocol = __commonJS({
3263
- "node_modules/ws/lib/subprotocol.js"(exports2, module2) {
3263
+ "../aig-folder-scope/node_modules/ws/lib/subprotocol.js"(exports2, module2) {
3264
3264
  "use strict";
3265
3265
  var { tokenChars } = require_validation();
3266
3266
  function parse2(header) {
@@ -3303,9 +3303,9 @@ var require_subprotocol = __commonJS({
3303
3303
  }
3304
3304
  });
3305
3305
 
3306
- // node_modules/ws/lib/websocket-server.js
3306
+ // ../aig-folder-scope/node_modules/ws/lib/websocket-server.js
3307
3307
  var require_websocket_server = __commonJS({
3308
- "node_modules/ws/lib/websocket-server.js"(exports2, module2) {
3308
+ "../aig-folder-scope/node_modules/ws/lib/websocket-server.js"(exports2, module2) {
3309
3309
  "use strict";
3310
3310
  var EventEmitter = require("events");
3311
3311
  var http = require("http");
@@ -3705,9 +3705,9 @@ var require_websocket_server = __commonJS({
3705
3705
  });
3706
3706
 
3707
3707
  // src/main/workspace-connect.ts
3708
- var import_fs13 = require("fs");
3708
+ var import_fs14 = require("fs");
3709
3709
  var import_os7 = require("os");
3710
- var import_path19 = require("path");
3710
+ var import_path20 = require("path");
3711
3711
  var import_url2 = require("url");
3712
3712
 
3713
3713
  // src/application/services/workspaceSandbox/importers.ts
@@ -3732,6 +3732,22 @@ function formatUserCode(code) {
3732
3732
  var MAX_MACHINE_FOLDERS = 50;
3733
3733
  var MAX_PATH_LENGTH = 1024;
3734
3734
  var WINDOWS_ABS = /^[A-Za-z]:[\\/]/;
3735
+ var WINDOWS_SYSTEM_FOLDERS = /* @__PURE__ */ new Set([
3736
+ "windows",
3737
+ "program files",
3738
+ "program files (x86)",
3739
+ "programdata",
3740
+ "recovery",
3741
+ "perflogs",
3742
+ "boot",
3743
+ "documents and settings",
3744
+ "system volume information",
3745
+ "$recycle.bin",
3746
+ "$windows.~bt",
3747
+ "$windows.~ws",
3748
+ "config.msi",
3749
+ "msocache"
3750
+ ]);
3735
3751
  function segments(path) {
3736
3752
  return path.replace(/^[A-Za-z]:/, "").split(/[\\/]+/).filter(Boolean);
3737
3753
  }
@@ -3748,12 +3764,24 @@ function folderPathProblem(path, home) {
3748
3764
  if (!homeParts.length) return "HOME_UNKNOWN";
3749
3765
  const same = (a, b) => windows ? a.toLowerCase() === b.toLowerCase() : a === b;
3750
3766
  if (windows !== WINDOWS_ABS.test(home)) return "PATH_OUTSIDE_HOME";
3751
- if (windows && path[0].toLowerCase() !== home[0].toLowerCase()) return "PATH_OUTSIDE_HOME";
3752
- if (parts.length <= homeParts.length || !homeParts.every((h, i) => same(h, parts[i]))) {
3753
- return parts.length === homeParts.length && homeParts.every((h, i) => same(h, parts[i])) ? "PATH_IS_HOME" : "PATH_OUTSIDE_HOME";
3767
+ const sameDrive = !windows || path[0].toLowerCase() === home[0].toLowerCase();
3768
+ if (sameDrive && parts.length >= homeParts.length && homeParts.every((h, i) => same(h, parts[i]))) {
3769
+ return parts.length === homeParts.length ? "PATH_IS_HOME" : null;
3754
3770
  }
3771
+ if (!windows) return "PATH_OUTSIDE_HOME";
3772
+ if (WINDOWS_SYSTEM_FOLDERS.has(parts[0].toLowerCase())) return "PATH_IS_SYSTEM";
3773
+ if (sameDrive && parts.every((p, i) => same(homeParts[i], p))) return "PATH_CONTAINS_HOME";
3755
3774
  return null;
3756
3775
  }
3776
+ function folderBrowseProblem(path, home) {
3777
+ const problem = folderPathProblem(path, home);
3778
+ if (problem === "PATH_IS_HOME" || problem === "PATH_CONTAINS_HOME") return null;
3779
+ if (problem === "PATH_IS_ROOT" && typeof path === "string" && WINDOWS_ABS.test(path) && typeof home === "string" && WINDOWS_ABS.test(home) && segments(home).length) return null;
3780
+ return problem;
3781
+ }
3782
+ function chosenRealPath(chosen, real) {
3783
+ return WINDOWS_ABS.test(chosen) && real.startsWith("\\\\") ? chosen : real;
3784
+ }
3757
3785
  function folderDisplayName(path) {
3758
3786
  const parts = segments(path);
3759
3787
  return parts[parts.length - 1] ?? path;
@@ -3809,7 +3837,7 @@ var RULES = [
3809
3837
  { kind: "PRIVATE_KEY", re: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|$)/g },
3810
3838
  { kind: "CONNECTION_STRING", re: /\b([a-z][a-z0-9+.-]{1,30}:\/\/)([^\s:@/'"]{1,200}):([^\s@/'"]{1,300})@/gi, replace: (_m, scheme, user) => `${scheme}${user}:${R("PASSWORD")}@` },
3811
3839
  { kind: "AWS_ACCESS_KEY", re: /\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA|ABIA|ACCA)[A-Z0-9]{16}\b/g },
3812
- { kind: "AWS_SECRET_KEY", re: /\b(aws_?secret_?access_?key|aws_?secret|secretAccessKey)(["']?\s*[:=]\s*["']?)([A-Za-z0-9/+=]{40})\b/gi, replace: (_m, k, sep12) => `${k}${sep12}${R("AWS_SECRET_KEY")}` },
3840
+ { kind: "AWS_SECRET_KEY", re: /\b(aws_?secret_?access_?key|aws_?secret|secretAccessKey)(["']?\s*[:=]\s*["']?)([A-Za-z0-9/+=]{40})\b/gi, replace: (_m, k, sep13) => `${k}${sep13}${R("AWS_SECRET_KEY")}` },
3813
3841
  { kind: "ANTHROPIC_KEY", re: /\bsk-ant-[a-z]{2,10}\d{0,3}-[A-Za-z0-9_-]{20,}/g },
3814
3842
  { kind: "OPENAI_KEY", re: /\bsk-(?:proj-|svcacct-|admin-|None-)?[A-Za-z0-9_-]{20,}/g },
3815
3843
  { kind: "GITHUB_TOKEN", re: /\b(?:gh[pousr]_[A-Za-z0-9]{30,255}|github_pat_[A-Za-z0-9_]{22,255})\b/g },
@@ -3825,7 +3853,7 @@ var RULES = [
3825
3853
  kind: "ASSIGNED_SECRET",
3826
3854
  // password=..., "api_key": "...", SECRET_TOKEN: ..., --token ... (key names that say "secret").
3827
3855
  re: /\b([A-Za-z0-9_.-]*(?:passw(?:or)?d|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|private[_-]?key|client[_-]?secret|credential|auth[_-]?key)[A-Za-z0-9_-]*)(["']?\s*(?:=|:|\s)\s*)(["']?)([^\s"'`,;)}\]]{8,500})\3/gi,
3828
- replace: (_m, key, sep12, quote, value) => looksLikeSecretValue(value) ? `${key}${sep12}${quote}${R("SECRET")}${quote}` : null
3856
+ replace: (_m, key, sep13, quote, value) => looksLikeSecretValue(value) ? `${key}${sep13}${quote}${R("SECRET")}${quote}` : null
3829
3857
  }
3830
3858
  ];
3831
3859
  function scrubSecrets(input) {
@@ -4384,6 +4412,7 @@ var import_path2 = require("path");
4384
4412
  // src/application/services/workspaceSandbox/checkpointMap.ts
4385
4413
  var CHECKPOINT_MAP_VERSION = 2;
4386
4414
  var LOCAL_FOLDER_KEY = ".";
4415
+ var WORKSPACE_FILES_KEY = "/";
4387
4416
  function parseCheckpoints(raw, legacyRepo) {
4388
4417
  const out2 = /* @__PURE__ */ new Map();
4389
4418
  if (!raw) return out2;
@@ -5813,6 +5842,12 @@ var HttpSessionTransport = class {
5813
5842
  async saveDesignVersion(v) {
5814
5843
  await this.post("/design-versions", v, this.opts.requestTimeoutMs ?? 6e4);
5815
5844
  }
5845
+ async keptDesign(path) {
5846
+ const raw = await this.get(`/design-versions/kept?path=${encodeURIComponent(path)}`, this.opts.requestTimeoutMs ?? 6e4);
5847
+ if (!Number.isInteger(raw?.n) || !Array.isArray(raw?.files)) return null;
5848
+ const files = raw.files.filter((f) => typeof f?.name === "string" && typeof f?.data === "string");
5849
+ return { n: raw.n, files };
5850
+ }
5816
5851
  async reply(commandId, reply) {
5817
5852
  if (!/^[A-Za-z0-9-]{1,80}$/.test(commandId)) throw new TransportError("invalid command id", null, false);
5818
5853
  await this.post(`/replies/${commandId}`, reply, this.opts.requestTimeoutMs ?? 3e4);
@@ -6007,6 +6042,7 @@ function toSessionBootstrap(raw) {
6007
6042
  designCanvas: raw?.designCanvas === true,
6008
6043
  designVersions: raw?.designVersions === true,
6009
6044
  designDiagrams: raw?.designDiagrams === true,
6045
+ keptDesigns: Array.isArray(raw?.keptDesigns) ? raw.keptDesigns.filter((d) => typeof d?.path === "string" && Number.isInteger(d?.n)).map((d) => ({ path: d.path, n: d.n })) : [],
6010
6046
  askQuestions: raw?.askQuestions === true,
6011
6047
  terminalOrigins: Array.isArray(raw?.terminalOrigins) ? raw.terminalOrigins.filter((o) => typeof o === "string" && /^https?:\/\/[^/\s]+$/.test(o)).slice(0, 4) : [],
6012
6048
  transcript: transcriptOf(raw?.transcript),
@@ -6450,7 +6486,8 @@ async function enclosingRepository(root) {
6450
6486
  const inHead = (await git(["ls-tree", "-d", "--name-only", "HEAD", "--", prefix], { cwd: realTop, env }).catch(() => "")).trim().length > 0;
6451
6487
  if (inHead) return { top: realTop, prefix };
6452
6488
  const home = await (0, import_promises6.realpath)((0, import_os3.homedir)()).catch(() => (0, import_os3.homedir)());
6453
- if (realTop === home || (0, import_path5.relative)(realTop, home).split(import_path5.sep)[0] !== "..") return null;
6489
+ const toHome = (0, import_path5.relative)(realTop, home);
6490
+ if (realTop === home || !(0, import_path5.isAbsolute)(toHome) && toHome.split(import_path5.sep)[0] !== "..") return null;
6454
6491
  const ignored = await git(["check-ignore", "-q", "--", prefix], { cwd: realTop, env }).then(() => true, () => false);
6455
6492
  return ignored ? null : { top: realTop, prefix };
6456
6493
  }
@@ -7222,8 +7259,10 @@ var MACHINE_USAGE = {
7222
7259
  "Usage: scalequality add [PATH] [--api URL]",
7223
7260
  "",
7224
7261
  "Adds a folder (default: the current one) to the folders the AI Workspace",
7225
- "can use on this computer: any folder, a git repository or not. It must be",
7226
- "inside your home folder, and never the home folder itself."
7262
+ "can use on this computer: any folder, a git repository or not. On macOS",
7263
+ "and Linux it must be inside your home folder; on Windows it can be on any",
7264
+ "drive. Never the home folder itself, the root of a disk or a folder of",
7265
+ "Windows itself."
7227
7266
  ].join("\n"),
7228
7267
  logout: [
7229
7268
  "Usage: scalequality logout [--api URL]",
@@ -7863,7 +7902,7 @@ var import_crypto5 = require("crypto");
7863
7902
  var import_fs6 = require("fs");
7864
7903
  var import_http = require("http");
7865
7904
 
7866
- // node_modules/ws/wrapper.mjs
7905
+ // ../aig-folder-scope/node_modules/ws/wrapper.mjs
7867
7906
  var import_stream = __toESM(require_stream(), 1);
7868
7907
  var import_extension = __toESM(require_extension(), 1);
7869
7908
  var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
@@ -8184,7 +8223,10 @@ var SUGGEST_DEPTH = 3;
8184
8223
  var MAX_REMOTE = 1024;
8185
8224
  var MAX_ANSWER_BYTES = 900 * 1024;
8186
8225
  var CONCURRENCY = 24;
8187
- var DEV_ROOTS = ["GIT", "git", "code", "Code", "projects", "Projects", "dev", "src", "workspace", "repos", "Developer", "Documents/GitHub", "go/src"];
8226
+ var DEV_ROOTS = ["GIT", "git", "code", "Code", "projects", "Projects", "dev", "src", "workspace", "repos", "Developer", "Documents/GitHub", "go/src", "source/repos"];
8227
+ var DRIVE_DEV_ROOTS = ["dev", "git", "code", "projects", "projetos", "proyectos", "repos", "repositorios", "src", "source", "workspace", "work", "www"];
8228
+ var DRIVE_PROBE_MS = 1500;
8229
+ var DRIVES_TTL_MS = 3e4;
8188
8230
  var SKIP_ANYWHERE = /* @__PURE__ */ new Set(["node_modules", "bower_components", "jspm_packages", "__pycache__", "Caches", "CachedData", "DerivedData", "Pods"]);
8189
8231
  var SKIP_AT_HOME = /* @__PURE__ */ new Set([
8190
8232
  "Library",
@@ -8213,21 +8255,46 @@ var FolderBrowseError = class extends Error {
8213
8255
  code;
8214
8256
  };
8215
8257
  var hidden = (name) => name.startsWith(".") || name.startsWith("$");
8216
- var skipped = (name, atHome) => hidden(name) || SKIP_ANYWHERE.has(name) || atHome && SKIP_AT_HOME.has(name);
8217
- function insideOrHome(path, home) {
8218
- const problem = folderPathProblem(path, home);
8219
- return problem === null || problem === "PATH_IS_HOME";
8258
+ var skipped = (name, level) => hidden(name) || SKIP_ANYWHERE.has(name) || level === "home" && SKIP_AT_HOME.has(name) || level === "drive" && WINDOWS_SYSTEM_FOLDERS.has(name.toLowerCase());
8259
+ var isDriveRoot = (path) => /^[A-Za-z]:[\\/]*$/.test(path);
8260
+ function browsable(path, home) {
8261
+ return folderBrowseProblem(path, home) === null;
8220
8262
  }
8221
8263
  function logical(home, real) {
8222
8264
  if (home.logical === home.real) return real;
8223
8265
  const rel = (0, import_path7.relative)(home.real, real);
8266
+ if (rel.startsWith("..") || (0, import_path7.isAbsolute)(rel)) return real;
8224
8267
  return rel ? (0, import_path7.join)(home.logical, rel) : home.logical;
8225
8268
  }
8226
- async function realInside(home, path) {
8227
- const real = await (0, import_promises7.realpath)(path).catch(() => null);
8228
- if (!real || !insideOrHome(real, home.real)) return null;
8269
+ async function realBrowsable(home, path) {
8270
+ const found = await (0, import_promises7.realpath)(path).catch(() => null);
8271
+ const real = found && chosenRealPath(path, found);
8272
+ if (!real || !browsable(real, home.real)) return null;
8229
8273
  return real;
8230
8274
  }
8275
+ async function realConnectable(home, path) {
8276
+ const real = await realBrowsable(home, path);
8277
+ return real && folderPathProblem(real, home.real) === null ? real : null;
8278
+ }
8279
+ var windowsHome = (home) => /^[A-Za-z]:[\\/]/.test(home.logical);
8280
+ var drivesCache = null;
8281
+ var probing = /* @__PURE__ */ new Map();
8282
+ async function windowsDrives(probe = async (root) => !!(await (0, import_promises7.stat)(root).catch(() => null))?.isDirectory()) {
8283
+ if (drivesCache && Date.now() - drivesCache.at < DRIVES_TTL_MS) return drivesCache.drives;
8284
+ const letters = "CDEFGHIJKLMNOPQRSTUVWXYZ".split("");
8285
+ const answers = await Promise.all(letters.map((letter) => {
8286
+ const root = `${letter}:\\`;
8287
+ let pending = probing.get(root);
8288
+ if (!pending) {
8289
+ pending = probe(root).catch(() => false).finally(() => probing.delete(root));
8290
+ probing.set(root, pending);
8291
+ }
8292
+ return Promise.race([pending, new Promise((done) => setTimeout(done, DRIVE_PROBE_MS, false).unref?.())]);
8293
+ }));
8294
+ const drives = letters.map((letter) => `${letter}:\\`).filter((_, i) => answers[i]);
8295
+ drivesCache = { at: Date.now(), drives };
8296
+ return drives;
8297
+ }
8231
8298
  async function resolveBrowsePath(raw, home) {
8232
8299
  if (raw !== void 0 && raw !== null && typeof raw !== "string") throw new FolderBrowseError("INVALID_PATH");
8233
8300
  const text3 = (raw ?? "").trim();
@@ -8239,12 +8306,16 @@ async function resolveBrowsePath(raw, home) {
8239
8306
  const rest = text3.startsWith("~/") || text3.startsWith("~\\") ? text3.slice(2) : text3;
8240
8307
  if (rest.split(/[\\/]+/).some((part) => part === ".." || part === ".")) throw new FolderBrowseError("INVALID_PATH");
8241
8308
  target = (0, import_path7.isAbsolute)(rest) && rest === text3 ? rest : (0, import_path7.resolve)(home.logical, rest);
8242
- if (!insideOrHome(target, home.logical)) throw new FolderBrowseError("PATH_OUTSIDE_HOME");
8309
+ const problem2 = folderBrowseProblem(target, home.logical);
8310
+ if (problem2) throw new FolderBrowseError(problem2);
8243
8311
  }
8244
8312
  const st = await (0, import_promises7.stat)(target).catch(() => null);
8245
8313
  if (!st?.isDirectory()) throw new FolderBrowseError("FOLDER_NOT_FOUND");
8246
- const real = await realInside(home, target);
8247
- if (!real) throw new FolderBrowseError("PATH_OUTSIDE_HOME");
8314
+ const found = await (0, import_promises7.realpath)(target).catch(() => null);
8315
+ if (!found) throw new FolderBrowseError("FOLDER_NOT_FOUND");
8316
+ const real = chosenRealPath(target, found);
8317
+ const problem = folderBrowseProblem(real, home.real);
8318
+ if (problem) throw new FolderBrowseError(problem === "PATH_IS_SYSTEM" ? problem : "PATH_OUTSIDE_HOME");
8248
8319
  return real;
8249
8320
  }
8250
8321
  async function originRemote(repo2) {
@@ -8291,7 +8362,7 @@ async function hasVisibleChild(dir) {
8291
8362
  try {
8292
8363
  for await (const d of handle) {
8293
8364
  if (++seen > CHILD_PROBE) return false;
8294
- if ((d.isDirectory() || d.isSymbolicLink()) && !skipped(d.name, false)) return true;
8365
+ if ((d.isDirectory() || d.isSymbolicLink()) && !skipped(d.name, isDriveRoot(dir) ? "drive" : null)) return true;
8295
8366
  }
8296
8367
  return false;
8297
8368
  } catch {
@@ -8300,7 +8371,7 @@ async function hasVisibleChild(dir) {
8300
8371
  await handle.close().catch(() => void 0);
8301
8372
  }
8302
8373
  }
8303
- async function subfolderNames(dir, atHome) {
8374
+ async function subfolderNames(dir, level) {
8304
8375
  const names = [];
8305
8376
  let handle;
8306
8377
  try {
@@ -8315,7 +8386,7 @@ async function subfolderNames(dir, atHome) {
8315
8386
  cut = true;
8316
8387
  break;
8317
8388
  }
8318
- if (skipped(d.name, atHome)) continue;
8389
+ if (skipped(d.name, level)) continue;
8319
8390
  if (d.isDirectory()) names.push({ name: d.name, link: false });
8320
8391
  else if (d.isSymbolicLink()) names.push({ name: d.name, link: true });
8321
8392
  }
@@ -8349,7 +8420,7 @@ async function listFolders(homePath, rawPath, opts = {}) {
8349
8420
  const home = await homeOf(homePath);
8350
8421
  const real = await resolveBrowsePath(rawPath, home);
8351
8422
  const atHome = real === home.real;
8352
- const { names, cut } = await subfolderNames(real, atHome);
8423
+ const { names, cut } = await subfolderNames(real, atHome ? "home" : isDriveRoot(real) ? "drive" : null);
8353
8424
  let truncated = cut;
8354
8425
  const found = [];
8355
8426
  const seen = /* @__PURE__ */ new Set();
@@ -8358,7 +8429,7 @@ async function listFolders(homePath, rawPath, opts = {}) {
8358
8429
  if (link) {
8359
8430
  const st = await (0, import_promises7.stat)(target).catch(() => null);
8360
8431
  if (!st?.isDirectory()) return;
8361
- const inside3 = await realInside(home, target);
8432
+ const inside3 = await realBrowsable(home, target);
8362
8433
  if (!inside3 || inside3 === home.real) return;
8363
8434
  target = inside3;
8364
8435
  }
@@ -8376,9 +8447,11 @@ async function listFolders(homePath, rawPath, opts = {}) {
8376
8447
  }) || truncated;
8377
8448
  const path = logical(home, real);
8378
8449
  const rel = (0, import_path7.relative)(home.logical, path);
8379
- const parentReal = atHome ? null : (0, import_path7.resolve)(real, "..");
8380
- const parent = parentReal && insideOrHome(parentReal, home.real) ? logical(home, parentReal) : null;
8381
- return fit({ home: "~", homePath: home.logical, path, relative: rel.split(import_path7.sep).join("/"), parent, entries: entries.filter((e) => !!e), truncated });
8450
+ const parentReal = (0, import_path7.resolve)(real, "..");
8451
+ const parent = parentReal !== real && browsable(parentReal, home.real) ? logical(home, parentReal) : null;
8452
+ const inHome = !rel.startsWith("..") && !(0, import_path7.isAbsolute)(rel);
8453
+ const drives = windowsHome(home) ? { drives: await windowsDrives() } : {};
8454
+ return fit({ home: "~", homePath: home.logical, path, relative: inHome ? rel.split(import_path7.sep).join("/") : null, parent, entries: entries.filter((e) => !!e), truncated, ...drives });
8382
8455
  }
8383
8456
  async function suggestFolders(homePath, sources, opts = {}) {
8384
8457
  const started = Date.now();
@@ -8405,8 +8478,8 @@ async function suggestFolders(homePath, sources, opts = {}) {
8405
8478
  break;
8406
8479
  }
8407
8480
  if (typeof folder !== "string" || folderPathProblem(folder, home.logical) && folderPathProblem(folder, home.real)) continue;
8408
- let dir = await realInside(home, folder);
8409
- while (dir && dir !== home.real) {
8481
+ let dir = await realConnectable(home, folder);
8482
+ while (dir && folderPathProblem(dir, home.real) === null) {
8410
8483
  if (await isGitRepo(dir)) {
8411
8484
  add(dir, "CONVERSATION");
8412
8485
  break;
@@ -8417,10 +8490,16 @@ async function suggestFolders(homePath, sources, opts = {}) {
8417
8490
  }
8418
8491
  }
8419
8492
  const roots = [];
8420
- for (const root of DEV_ROOTS) {
8421
- const real = await realInside(home, (0, import_path7.join)(home.logical, root));
8493
+ const candidates = DEV_ROOTS.map((root) => (0, import_path7.join)(home.logical, root));
8494
+ if (windowsHome(home)) for (const drive of await windowsDrives()) for (const root of DRIVE_DEV_ROOTS) candidates.push(drive + root);
8495
+ for (const candidate of candidates) {
8496
+ if (Date.now() > deadline) {
8497
+ truncated = true;
8498
+ break;
8499
+ }
8500
+ const real = await realConnectable(home, candidate);
8422
8501
  const st = real ? await (0, import_promises7.stat)(real).catch(() => null) : null;
8423
- if (real && real !== home.real && st?.isDirectory() && !roots.includes(real)) roots.push(real);
8502
+ if (real && st?.isDirectory() && !roots.includes(real)) roots.push(real);
8424
8503
  }
8425
8504
  const devFound = [];
8426
8505
  let level = [];
@@ -8431,11 +8510,11 @@ async function suggestFolders(homePath, sources, opts = {}) {
8431
8510
  for (let depth = 1; depth <= SUGGEST_DEPTH && level.length && !truncated; depth++) {
8432
8511
  const next = [];
8433
8512
  const finished = await eachUntil(level, deadline, async (dir) => {
8434
- const { names } = await subfolderNames(dir, false);
8513
+ const { names } = await subfolderNames(dir, null);
8435
8514
  for (const { name, link } of names) {
8436
8515
  const child = (0, import_path7.join)(dir, name);
8437
- const real = link ? await realInside(home, child) : child;
8438
- if (!real || real === home.real) continue;
8516
+ const real = link ? await realConnectable(home, child) : child;
8517
+ if (!real) continue;
8439
8518
  if (await isGitRepo(real)) devFound.push(real);
8440
8519
  else if (depth < SUGGEST_DEPTH) next.push(real);
8441
8520
  }
@@ -8447,7 +8526,7 @@ async function suggestFolders(homePath, sources, opts = {}) {
8447
8526
  }
8448
8527
  level = next;
8449
8528
  }
8450
- devFound.sort((a, b) => (0, import_path7.relative)(home.real, a).localeCompare((0, import_path7.relative)(home.real, b), void 0, { sensitivity: "base", numeric: true }));
8529
+ devFound.sort((a, b) => logical(home, a).localeCompare(logical(home, b), void 0, { sensitivity: "base", numeric: true }));
8451
8530
  for (const real of devFound) add(real, "DEV_ROOT");
8452
8531
  const entries = out2.map(() => null);
8453
8532
  const done = await eachUntil(out2.map((f, i) => ({ f, i })), deadline + 1e3, async ({ f, i }) => {
@@ -8615,6 +8694,8 @@ var FOLDER_MESSAGES = {
8615
8694
  PATH_IS_ROOT: "The root of the disk cannot be connected.",
8616
8695
  PATH_IS_HOME: "Your whole home folder cannot be connected. Choose a project folder inside it.",
8617
8696
  PATH_OUTSIDE_HOME: "Only folders inside your home folder can be connected.",
8697
+ PATH_IS_SYSTEM: "A folder of Windows itself cannot be connected.",
8698
+ PATH_CONTAINS_HOME: "This folder holds your home folder and cannot be connected. Choose a project folder.",
8618
8699
  INVALID_PATH: "That folder path is not valid.",
8619
8700
  HOME_UNKNOWN: "Your home folder could not be determined.",
8620
8701
  FOLDER_NOT_FOUND: "That folder does not exist.",
@@ -8625,7 +8706,7 @@ async function checkFolder(path, home) {
8625
8706
  if (shape) throw new FolderError(shape, FOLDER_MESSAGES[shape] ?? "That folder cannot be connected.");
8626
8707
  const st = await (0, import_promises8.stat)(path).catch(() => null);
8627
8708
  if (!st?.isDirectory()) throw new FolderError("FOLDER_NOT_FOUND", FOLDER_MESSAGES.FOLDER_NOT_FOUND);
8628
- const real = await (0, import_promises8.realpath)(path);
8709
+ const real = chosenRealPath(path, await (0, import_promises8.realpath)(path));
8629
8710
  const realHome = await (0, import_promises8.realpath)(home).catch(() => home);
8630
8711
  const problem = folderPathProblem(real, realHome);
8631
8712
  if (problem) throw new FolderError(problem, FOLDER_MESSAGES[problem] ?? "That folder cannot be connected.");
@@ -8956,11 +9037,11 @@ async function addFolder(credentials2, api, path, home) {
8956
9037
 
8957
9038
  // src/application/services/workspaceSandbox/WorkspaceEngine.ts
8958
9039
  var import_child_process5 = require("child_process");
8959
- var import_promises16 = require("fs/promises");
8960
- var import_fs11 = require("fs");
9040
+ var import_promises17 = require("fs/promises");
9041
+ var import_fs12 = require("fs");
8961
9042
  var import_os6 = require("os");
8962
9043
  var import_crypto9 = require("crypto");
8963
- var import_path17 = require("path");
9044
+ var import_path18 = require("path");
8964
9045
 
8965
9046
  // src/application/services/execution/LanguageAdapter.ts
8966
9047
  var import_async_hooks = require("async_hooks");
@@ -9148,7 +9229,7 @@ var import_os5 = require("os");
9148
9229
  var import_path10 = require("path");
9149
9230
  var import_url = require("url");
9150
9231
 
9151
- // node_modules/zod/v3/external.js
9232
+ // ../aig-folder-scope/node_modules/zod/v3/external.js
9152
9233
  var external_exports = {};
9153
9234
  __export(external_exports, {
9154
9235
  BRAND: () => BRAND,
@@ -9260,7 +9341,7 @@ __export(external_exports, {
9260
9341
  void: () => voidType
9261
9342
  });
9262
9343
 
9263
- // node_modules/zod/v3/helpers/util.js
9344
+ // ../aig-folder-scope/node_modules/zod/v3/helpers/util.js
9264
9345
  var util;
9265
9346
  (function(util2) {
9266
9347
  util2.assertEqual = (_) => {
@@ -9394,7 +9475,7 @@ var getParsedType = (data) => {
9394
9475
  }
9395
9476
  };
9396
9477
 
9397
- // node_modules/zod/v3/ZodError.js
9478
+ // ../aig-folder-scope/node_modules/zod/v3/ZodError.js
9398
9479
  var ZodIssueCode = util.arrayToEnum([
9399
9480
  "invalid_type",
9400
9481
  "invalid_literal",
@@ -9512,7 +9593,7 @@ ZodError.create = (issues) => {
9512
9593
  return error;
9513
9594
  };
9514
9595
 
9515
- // node_modules/zod/v3/locales/en.js
9596
+ // ../aig-folder-scope/node_modules/zod/v3/locales/en.js
9516
9597
  var errorMap = (issue, _ctx) => {
9517
9598
  let message;
9518
9599
  switch (issue.code) {
@@ -9615,7 +9696,7 @@ var errorMap = (issue, _ctx) => {
9615
9696
  };
9616
9697
  var en_default = errorMap;
9617
9698
 
9618
- // node_modules/zod/v3/errors.js
9699
+ // ../aig-folder-scope/node_modules/zod/v3/errors.js
9619
9700
  var overrideErrorMap = en_default;
9620
9701
  function setErrorMap(map) {
9621
9702
  overrideErrorMap = map;
@@ -9624,7 +9705,7 @@ function getErrorMap() {
9624
9705
  return overrideErrorMap;
9625
9706
  }
9626
9707
 
9627
- // node_modules/zod/v3/helpers/parseUtil.js
9708
+ // ../aig-folder-scope/node_modules/zod/v3/helpers/parseUtil.js
9628
9709
  var makeIssue = (params) => {
9629
9710
  const { data, path, errorMaps, issueData } = params;
9630
9711
  const fullPath = [...path, ...issueData.path || []];
@@ -9734,14 +9815,14 @@ var isDirty = (x) => x.status === "dirty";
9734
9815
  var isValid = (x) => x.status === "valid";
9735
9816
  var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
9736
9817
 
9737
- // node_modules/zod/v3/helpers/errorUtil.js
9818
+ // ../aig-folder-scope/node_modules/zod/v3/helpers/errorUtil.js
9738
9819
  var errorUtil;
9739
9820
  (function(errorUtil2) {
9740
9821
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
9741
9822
  errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
9742
9823
  })(errorUtil || (errorUtil = {}));
9743
9824
 
9744
- // node_modules/zod/v3/types.js
9825
+ // ../aig-folder-scope/node_modules/zod/v3/types.js
9745
9826
  var ParseInputLazyPath = class {
9746
9827
  constructor(parent, value, path, key) {
9747
9828
  this._cachedPath = [];
@@ -13496,6 +13577,115 @@ function designReport(path, manifest, checks) {
13496
13577
  }
13497
13578
  var designPath = (root, absManifest) => (0, import_path10.relative)(root, absManifest).split(import_path10.sep).join("/");
13498
13579
 
13580
+ // src/application/services/workspaceSandbox/rootFiles.ts
13581
+ var import_promises11 = require("fs/promises");
13582
+ var import_fs9 = require("fs");
13583
+ var import_path11 = require("path");
13584
+ var ROOT_FILE_MAX_BYTES = 5 * 1024 * 1024;
13585
+ var ROOT_FILES_MAX_BYTES = 24 * 1024 * 1024;
13586
+ var ROOT_FILES_MAX_COUNT = 2e3;
13587
+ var ROOT_FILES_SCAN_MAX = 2e4;
13588
+ var posix3 = (p) => p.split(import_path11.sep).join("/");
13589
+ async function listRootFiles(root, excluded) {
13590
+ const skip = new Set(excluded.map((d) => d.replace(/[\\/]+$/, "")));
13591
+ const found = [];
13592
+ const walk = async (dir) => {
13593
+ const handle = await (0, import_promises11.opendir)(dir).catch(() => null);
13594
+ if (!handle) return;
13595
+ for await (const entry of handle) {
13596
+ if (found.length >= ROOT_FILES_SCAN_MAX) break;
13597
+ const abs = (0, import_path11.join)(dir, entry.name);
13598
+ if (entry.isSymbolicLink()) continue;
13599
+ if (entry.isDirectory()) {
13600
+ if (entry.name.startsWith(".") || DISCOVERY_SKIP.has(entry.name) || skip.has(abs)) continue;
13601
+ if ((0, import_fs9.existsSync)((0, import_path11.join)(abs, ".git"))) continue;
13602
+ await walk(abs);
13603
+ } else if (entry.isFile()) {
13604
+ const st = await (0, import_promises11.lstat)(abs).catch(() => null);
13605
+ if (st?.isFile()) found.push({ path: posix3((0, import_path11.relative)(root, abs)), size: st.size, mtimeMs: st.mtimeMs });
13606
+ }
13607
+ }
13608
+ };
13609
+ await walk(root);
13610
+ found.sort((a, b) => b.mtimeMs - a.mtimeMs || a.path.localeCompare(b.path));
13611
+ const files = [];
13612
+ let total = 0;
13613
+ for (const f of found) {
13614
+ if (f.size > ROOT_FILE_MAX_BYTES || total + f.size > ROOT_FILES_MAX_BYTES || files.length >= ROOT_FILES_MAX_COUNT) continue;
13615
+ files.push(f);
13616
+ total += f.size;
13617
+ }
13618
+ return { files: files.sort((a, b) => a.path.localeCompare(b.path)), leftOut: found.length - files.length };
13619
+ }
13620
+ async function withScratchGit(scratch, workTree, fn) {
13621
+ await (0, import_promises11.mkdir)(scratch, { recursive: true });
13622
+ const gitDir = await (0, import_promises11.mkdtemp)((0, import_path11.join)(scratch, "root-files-"));
13623
+ try {
13624
+ await git(["init", "-q", "--bare", gitDir], { cwd: scratch });
13625
+ for (const [k, v] of [["core.bare", "false"], ["core.autocrlf", "false"], ["core.safecrlf", "false"], ["gc.auto", "0"]]) {
13626
+ await git(["config", k, v], { cwd: scratch, env: { GIT_DIR: gitDir } });
13627
+ }
13628
+ return await fn({ GIT_DIR: gitDir, GIT_WORK_TREE: workTree });
13629
+ } finally {
13630
+ await (0, import_promises11.rm)(gitDir, { recursive: true, force: true }).catch(() => void 0);
13631
+ }
13632
+ }
13633
+ async function rootFilesCheckpoint(root, scratch, files) {
13634
+ if (!files.length) return "";
13635
+ return withScratchGit(scratch, root, (env) => checkpointPatch(root, EMPTY_TREE.sha1, { env, index: null, paths: files.map((f) => f.path) }));
13636
+ }
13637
+ async function restoreRootFiles(root, scratch, patch) {
13638
+ if (!patch.includes("diff --git ")) return { restored: 0, kept: 0 };
13639
+ await (0, import_promises11.mkdir)(scratch, { recursive: true });
13640
+ const out2 = await (0, import_promises11.mkdtemp)((0, import_path11.join)(scratch, "root-restore-"));
13641
+ try {
13642
+ const patchFile = (0, import_path11.join)(scratch, `${Date.now().toString(36)}-root-files.patch`);
13643
+ await (0, import_promises11.writeFile)(patchFile, patch, "utf8");
13644
+ try {
13645
+ await withScratchGit(scratch, out2, (env) => git(["apply", "--binary", "--whitespace=nowarn", patchFile], { cwd: out2, env, timeoutMs: 5 * 6e4 }));
13646
+ } finally {
13647
+ await (0, import_promises11.rm)(patchFile, { force: true }).catch(() => void 0);
13648
+ }
13649
+ const { files } = await listRootFiles(out2, []);
13650
+ let restored = 0;
13651
+ let kept = 0;
13652
+ for (const f of files) {
13653
+ const target = await resolveInside(root, f.path);
13654
+ if (!target) continue;
13655
+ if ((0, import_fs9.existsSync)(target)) {
13656
+ kept++;
13657
+ continue;
13658
+ }
13659
+ await (0, import_promises11.mkdir)((0, import_path11.dirname)(target), { recursive: true });
13660
+ const from = (0, import_path11.join)(out2, f.path);
13661
+ await (0, import_promises11.copyFile)(from, target);
13662
+ const mode = (await (0, import_promises11.stat)(from)).mode & 511;
13663
+ await (0, import_promises11.chmod)(target, mode).catch(() => void 0);
13664
+ restored++;
13665
+ }
13666
+ return { restored, kept };
13667
+ } finally {
13668
+ await (0, import_promises11.rm)(out2, { recursive: true, force: true }).catch(() => void 0);
13669
+ }
13670
+ }
13671
+ var DESIGN_FILE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}(\/[A-Za-z0-9][A-Za-z0-9._-]{0,99})?$/;
13672
+ async function restoreKeptDesign(root, path, files) {
13673
+ if (!/(^|\/)design\.json$/.test(path) || !files.some((f) => f.name === "design.json")) return 0;
13674
+ const folder = path.replace(/design\.json$/, "");
13675
+ const manifest = await resolveInside(root, `${folder}design.json`);
13676
+ if (!manifest || (0, import_fs9.existsSync)(manifest)) return 0;
13677
+ let written = 0;
13678
+ for (const f of files) {
13679
+ if (!DESIGN_FILE.test(f.name) || typeof f.data !== "string") continue;
13680
+ const target = await resolveInside(root, `${folder}${f.name}`);
13681
+ if (!target || (0, import_fs9.existsSync)(target)) continue;
13682
+ await (0, import_promises11.mkdir)((0, import_path11.dirname)(target), { recursive: true });
13683
+ await (0, import_promises11.writeFile)(target, Buffer.from(f.data, "base64"));
13684
+ written++;
13685
+ }
13686
+ return written;
13687
+ }
13688
+
13499
13689
  // src/application/services/workspaceSandbox/engineMessages.ts
13500
13690
  var ENGINE_MESSAGES = {
13501
13691
  // Start and preparation.
@@ -13993,24 +14183,24 @@ function buildScaleQualityServer(sdk, host) {
13993
14183
  }
13994
14184
 
13995
14185
  // src/application/services/workspaceSandbox/projectConventions.ts
13996
- var import_promises11 = require("fs/promises");
13997
- var import_path11 = require("path");
14186
+ var import_promises12 = require("fs/promises");
14187
+ var import_path12 = require("path");
13998
14188
  var CONVENTION_FILES = ["CLAUDE.md", "AGENTS.md", ".claude/CLAUDE.md"];
13999
14189
  var CONVENTION_CAPS = { perFileBytes: 24 * 1024, totalBytes: 64 * 1024 };
14000
14190
  async function readConventions(repos, caps = CONVENTION_CAPS) {
14001
14191
  const out2 = [];
14002
14192
  let total = 0;
14003
14193
  for (const repo2 of repos) {
14004
- const realRoot = await (0, import_promises11.realpath)(repo2.root).catch(() => null);
14194
+ const realRoot = await (0, import_promises12.realpath)(repo2.root).catch(() => null);
14005
14195
  if (!realRoot) continue;
14006
14196
  for (const name of CONVENTION_FILES) {
14007
14197
  if (total >= caps.totalBytes) return out2;
14008
- const abs = (0, import_path11.join)(repo2.root, name);
14009
- const st = await (0, import_promises11.lstat)(abs).catch(() => null);
14198
+ const abs = (0, import_path12.join)(repo2.root, name);
14199
+ const st = await (0, import_promises12.lstat)(abs).catch(() => null);
14010
14200
  if (!st?.isFile()) continue;
14011
- const real = await (0, import_promises11.realpath)(abs).catch(() => null);
14012
- if (!real || (0, import_path11.relative)(realRoot, real).startsWith("..") || (0, import_path11.relative)(realRoot, real).split(import_path11.sep).includes("..")) continue;
14013
- const buf = await (0, import_promises11.readFile)(abs).catch(() => null);
14201
+ const real = await (0, import_promises12.realpath)(abs).catch(() => null);
14202
+ if (!real || (0, import_path12.relative)(realRoot, real).startsWith("..") || (0, import_path12.relative)(realRoot, real).split(import_path12.sep).includes("..")) continue;
14203
+ const buf = await (0, import_promises12.readFile)(abs).catch(() => null);
14014
14204
  if (!buf || buf.includes(0)) continue;
14015
14205
  const room = Math.min(caps.perFileBytes, caps.totalBytes - total);
14016
14206
  let text3 = buf.toString("utf8");
@@ -14036,7 +14226,7 @@ ${f.text.replace(/<\/project_conventions>/g, "")}
14036
14226
  }
14037
14227
 
14038
14228
  // src/application/services/workspaceSandbox/sdkEventMapper.ts
14039
- var import_path12 = require("path");
14229
+ var import_path13 = require("path");
14040
14230
  var TERMINAL_TAIL_BYTES = 64 * 1024;
14041
14231
  var FILE_CHANGING = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit", "Bash", "Agent", "Task"]);
14042
14232
  var SUBAGENT_NAMES = /* @__PURE__ */ new Set(["Agent", "Task"]);
@@ -14457,8 +14647,8 @@ function describeTool(name, input, root) {
14457
14647
  const s = (k) => typeof input[k] === "string" ? input[k] : "";
14458
14648
  const rel = (p) => {
14459
14649
  if (!p) return "";
14460
- if (!(0, import_path12.isAbsolute)(p)) return p;
14461
- const r = (0, import_path12.relative)(root, p);
14650
+ if (!(0, import_path13.isAbsolute)(p)) return p;
14651
+ const r = (0, import_path13.relative)(root, p);
14462
14652
  return r && !r.startsWith("..") ? r : p;
14463
14653
  };
14464
14654
  switch (name) {
@@ -14472,10 +14662,10 @@ function describeTool(name, input, root) {
14472
14662
  return { kind: "search", label: `Searching for "${clip(s("pattern"), 80)}"`, detail: s("pattern"), code: "STEP_SEARCH", params: { pattern: clip(s("pattern"), 80) } };
14473
14663
  case "Edit":
14474
14664
  case "MultiEdit":
14475
- if (/[\\/]plans[\\/][^\\/]+\.md$/.test(s("file_path")) && (0, import_path12.isAbsolute)(rel(s("file_path")))) return { kind: "think", label: "Writing the plan", code: "STEP_PLAN_WRITE" };
14665
+ if (/[\\/]plans[\\/][^\\/]+\.md$/.test(s("file_path")) && (0, import_path13.isAbsolute)(rel(s("file_path")))) return { kind: "think", label: "Writing the plan", code: "STEP_PLAN_WRITE" };
14476
14666
  return { kind: "edit", label: `Editing ${rel(s("file_path"))}`, detail: rel(s("file_path")), code: "STEP_EDIT", params: { path: rel(s("file_path")) } };
14477
14667
  case "Write":
14478
- if (/[\\/]plans[\\/][^\\/]+\.md$/.test(s("file_path")) && (0, import_path12.isAbsolute)(rel(s("file_path")))) return { kind: "think", label: "Writing the plan", code: "STEP_PLAN_WRITE" };
14668
+ if (/[\\/]plans[\\/][^\\/]+\.md$/.test(s("file_path")) && (0, import_path13.isAbsolute)(rel(s("file_path")))) return { kind: "think", label: "Writing the plan", code: "STEP_PLAN_WRITE" };
14479
14669
  return { kind: "edit", label: `Writing ${rel(s("file_path"))}`, detail: rel(s("file_path")), code: "STEP_WRITE", params: { path: rel(s("file_path")) } };
14480
14670
  case "NotebookEdit":
14481
14671
  return { kind: "edit", label: `Editing ${rel(s("notebook_path"))}`, detail: rel(s("notebook_path")), code: "STEP_EDIT", params: { path: rel(s("notebook_path")) } };
@@ -14932,9 +15122,9 @@ function buildSystemAppend(c) {
14932
15122
  }
14933
15123
 
14934
15124
  // src/application/services/workspaceSandbox/testCommand.ts
14935
- var import_fs9 = require("fs");
14936
- var import_promises12 = require("fs/promises");
14937
- var import_path13 = require("path");
15125
+ var import_fs10 = require("fs");
15126
+ var import_promises13 = require("fs/promises");
15127
+ var import_path14 = require("path");
14938
15128
  function commandForFramework(framework, dir, pkgTestScript) {
14939
15129
  switch (framework) {
14940
15130
  case "jest":
@@ -14946,13 +15136,13 @@ function commandForFramework(framework, dir, pkgTestScript) {
14946
15136
  case "go-test":
14947
15137
  return "go test ./...";
14948
15138
  case "junit":
14949
- return (0, import_fs9.existsSync)((0, import_path13.join)(dir, "gradlew")) ? "./gradlew test" : (0, import_fs9.existsSync)((0, import_path13.join)(dir, "build.gradle")) || (0, import_fs9.existsSync)((0, import_path13.join)(dir, "build.gradle.kts")) ? "gradle test" : "mvn -q test";
15139
+ return (0, import_fs10.existsSync)((0, import_path14.join)(dir, "gradlew")) ? "./gradlew test" : (0, import_fs10.existsSync)((0, import_path14.join)(dir, "build.gradle")) || (0, import_fs10.existsSync)((0, import_path14.join)(dir, "build.gradle.kts")) ? "gradle test" : "mvn -q test";
14950
15140
  case "xunit":
14951
15141
  case "nunit":
14952
15142
  case "mstest":
14953
15143
  return "dotnet test";
14954
15144
  case "phpunit":
14955
- return (0, import_fs9.existsSync)((0, import_path13.join)(dir, "vendor", "bin", "phpunit")) ? "vendor/bin/phpunit" : "phpunit";
15145
+ return (0, import_fs10.existsSync)((0, import_path14.join)(dir, "vendor", "bin", "phpunit")) ? "vendor/bin/phpunit" : "phpunit";
14956
15146
  case "rspec":
14957
15147
  return "bundle exec rspec";
14958
15148
  case "cargo-test":
@@ -14960,7 +15150,7 @@ function commandForFramework(framework, dir, pkgTestScript) {
14960
15150
  case "exunit":
14961
15151
  return "mix test";
14962
15152
  case "dart-test":
14963
- return (0, import_fs9.existsSync)((0, import_path13.join)(dir, "pubspec.yaml")) && /flutter:/.test(safeRead((0, import_path13.join)(dir, "pubspec.yaml"))) ? "flutter test" : "dart test";
15153
+ return (0, import_fs10.existsSync)((0, import_path14.join)(dir, "pubspec.yaml")) && /flutter:/.test(safeRead((0, import_path14.join)(dir, "pubspec.yaml"))) ? "flutter test" : "dart test";
14964
15154
  case "xctest":
14965
15155
  return "swift test";
14966
15156
  case "scalatest":
@@ -14973,13 +15163,13 @@ function commandForFramework(framework, dir, pkgTestScript) {
14973
15163
  }
14974
15164
  function safeRead(p) {
14975
15165
  try {
14976
- return (0, import_fs9.readFileSync)(p, "utf8");
15166
+ return (0, import_fs10.readFileSync)(p, "utf8");
14977
15167
  } catch {
14978
15168
  return "";
14979
15169
  }
14980
15170
  }
14981
15171
  async function hasTestScript(dir) {
14982
- const raw = await (0, import_promises12.readFile)((0, import_path13.join)(dir, "package.json"), "utf8").catch(() => null);
15172
+ const raw = await (0, import_promises13.readFile)((0, import_path14.join)(dir, "package.json"), "utf8").catch(() => null);
14983
15173
  if (!raw) return false;
14984
15174
  try {
14985
15175
  const script = JSON.parse(raw).scripts?.test;
@@ -14989,7 +15179,7 @@ async function hasTestScript(dir) {
14989
15179
  }
14990
15180
  }
14991
15181
  async function detectTestCommandFromManifests(dir) {
14992
- const has = (f) => (0, import_fs9.existsSync)((0, import_path13.join)(dir, f));
15182
+ const has = (f) => (0, import_fs10.existsSync)((0, import_path14.join)(dir, f));
14993
15183
  const pkgScript = await hasTestScript(dir);
14994
15184
  if (pkgScript) return { command: "npm test --silent", framework: "npm-script", source: "manifest" };
14995
15185
  const checks = [
@@ -15014,9 +15204,9 @@ async function detectTestCommandFromManifests(dir) {
15014
15204
 
15015
15205
  // src/application/services/workspaceSandbox/transcript.ts
15016
15206
  var import_crypto8 = require("crypto");
15017
- var import_fs10 = require("fs");
15018
- var import_promises13 = require("fs/promises");
15019
- var import_path14 = require("path");
15207
+ var import_fs11 = require("fs");
15208
+ var import_promises14 = require("fs/promises");
15209
+ var import_path15 = require("path");
15020
15210
  var import_zlib2 = require("zlib");
15021
15211
  var TRANSCRIPT_CAPS = { maxRawBytes: 64 * 1024 * 1024, maxCompressedBytes: 4 * 1024 * 1024 };
15022
15212
  function engineProjectDir(cwd) {
@@ -15025,10 +15215,10 @@ function engineProjectDir(cwd) {
15025
15215
  var SESSION_ID = /^[A-Za-z0-9-]{8,80}$/;
15026
15216
  async function findTranscript(configDir, sessionId) {
15027
15217
  if (!SESSION_ID.test(sessionId)) return null;
15028
- const projects = (0, import_path14.join)(configDir, "projects");
15029
- for (const dir of await (0, import_promises13.readdir)(projects).catch(() => [])) {
15030
- const file = (0, import_path14.join)(projects, dir, `${sessionId}.jsonl`);
15031
- const st = await (0, import_promises13.stat)(file).catch(() => null);
15218
+ const projects = (0, import_path15.join)(configDir, "projects");
15219
+ for (const dir of await (0, import_promises14.readdir)(projects).catch(() => [])) {
15220
+ const file = (0, import_path15.join)(projects, dir, `${sessionId}.jsonl`);
15221
+ const st = await (0, import_promises14.stat)(file).catch(() => null);
15032
15222
  if (st?.isFile()) return file;
15033
15223
  }
15034
15224
  return null;
@@ -15036,9 +15226,9 @@ async function findTranscript(configDir, sessionId) {
15036
15226
  async function packTranscript(configDir, sessionId, redactor, caps = TRANSCRIPT_CAPS) {
15037
15227
  const file = await findTranscript(configDir, sessionId);
15038
15228
  if (!file) return null;
15039
- const st = await (0, import_promises13.stat)(file);
15229
+ const st = await (0, import_promises14.stat)(file);
15040
15230
  if (st.size > caps.maxRawBytes) return { tooLarge: true, bytes: st.size };
15041
- const raw = await (0, import_promises13.readFile)(file, "utf8");
15231
+ const raw = await (0, import_promises14.readFile)(file, "utf8");
15042
15232
  let removed = 0;
15043
15233
  const lines2 = [];
15044
15234
  for (const line of raw.split("\n")) {
@@ -15073,19 +15263,19 @@ async function restoreTranscript(configDir, cwd, t) {
15073
15263
  return false;
15074
15264
  }
15075
15265
  if (t.sha256 && (0, import_crypto8.createHash)("sha256").update(text3).digest("hex") !== t.sha256) return false;
15076
- const dir = (0, import_path14.join)(configDir, "projects", engineProjectDir(cwd));
15077
- await (0, import_promises13.mkdir)(dir, { recursive: true, mode: 448 });
15078
- const target = (0, import_path14.join)(dir, `${t.sdkSessionId}.jsonl`);
15266
+ const dir = (0, import_path15.join)(configDir, "projects", engineProjectDir(cwd));
15267
+ await (0, import_promises14.mkdir)(dir, { recursive: true, mode: 448 });
15268
+ const target = (0, import_path15.join)(dir, `${t.sdkSessionId}.jsonl`);
15079
15269
  const partial = `${target}.${process.pid}.partial`;
15080
15270
  try {
15081
- await (0, import_promises13.writeFile)(partial, text3, { mode: 384 });
15082
- await (0, import_promises13.chmod)(partial, 384).catch(() => void 0);
15083
- await (0, import_promises13.rename)(partial, target);
15271
+ await (0, import_promises14.writeFile)(partial, text3, { mode: 384 });
15272
+ await (0, import_promises14.chmod)(partial, 384).catch(() => void 0);
15273
+ await (0, import_promises14.rename)(partial, target);
15084
15274
  } catch {
15085
- await (0, import_promises13.rm)(partial, { force: true }).catch(() => void 0);
15275
+ await (0, import_promises14.rm)(partial, { force: true }).catch(() => void 0);
15086
15276
  return false;
15087
15277
  }
15088
- return (0, import_fs10.existsSync)(target);
15278
+ return (0, import_fs11.existsSync)(target);
15089
15279
  }
15090
15280
 
15091
15281
  // src/application/services/workspaceSandbox/askQuestion.ts
@@ -15185,8 +15375,8 @@ function questionResult(o, input) {
15185
15375
  }
15186
15376
 
15187
15377
  // src/application/services/workspaceSandbox/workspaceFiles.ts
15188
- var import_promises14 = require("fs/promises");
15189
- var import_path15 = require("path");
15378
+ var import_promises15 = require("fs/promises");
15379
+ var import_path16 = require("path");
15190
15380
  var FILE_CAPS = { maxEntries: 500, maxReadBytes: 256 * 1024, maxFileBytes: 20 * 1024 * 1024, maxLines: 5e3, maxImageBytes: 6 * 1024 * 1024 };
15191
15381
  var FileRequestError = class extends Error {
15192
15382
  constructor(code) {
@@ -15201,36 +15391,36 @@ async function fenced(root, rel, denied) {
15201
15391
  if (clean.split(/[\\/]/).includes("..")) throw new FileRequestError("PATH_OUTSIDE_WORKSPACE");
15202
15392
  const abs = await resolveInside(root, clean || ".");
15203
15393
  if (!abs) throw new FileRequestError("PATH_OUTSIDE_WORKSPACE");
15204
- const realRoot = await (0, import_promises14.realpath)(root).catch(() => (0, import_path15.resolve)(root));
15205
- const r = (0, import_path15.relative)(realRoot, abs);
15206
- if (r.split(import_path15.sep).includes(".git")) throw new FileRequestError("PATH_OUTSIDE_WORKSPACE");
15394
+ const realRoot = await (0, import_promises15.realpath)(root).catch(() => (0, import_path16.resolve)(root));
15395
+ const r = (0, import_path16.relative)(realRoot, abs);
15396
+ if (r.split(import_path16.sep).includes(".git")) throw new FileRequestError("PATH_OUTSIDE_WORKSPACE");
15207
15397
  for (const d of denied) {
15208
- const realDenied = await (0, import_promises14.realpath)(d).catch(() => (0, import_path15.resolve)(d));
15209
- if (abs === realDenied || abs.startsWith(realDenied + import_path15.sep)) throw new FileRequestError("PATH_OUTSIDE_WORKSPACE");
15398
+ const realDenied = await (0, import_promises15.realpath)(d).catch(() => (0, import_path16.resolve)(d));
15399
+ if (abs === realDenied || abs.startsWith(realDenied + import_path16.sep)) throw new FileRequestError("PATH_OUTSIDE_WORKSPACE");
15210
15400
  }
15211
- return { abs, rel: r.split(import_path15.sep).join("/") };
15401
+ return { abs, rel: r.split(import_path16.sep).join("/") };
15212
15402
  }
15213
15403
  async function listFiles(root, rel, denied = []) {
15214
15404
  const { abs, rel: clean } = await fenced(root, rel, denied);
15215
- const st = await (0, import_promises14.stat)(abs).catch(() => null);
15405
+ const st = await (0, import_promises15.stat)(abs).catch(() => null);
15216
15406
  if (!st) throw new FileRequestError("NOT_FOUND");
15217
15407
  if (!st.isDirectory()) throw new FileRequestError("NOT_A_DIRECTORY");
15218
- const deniedReal = await Promise.all(denied.map((d) => (0, import_promises14.realpath)(d).catch(() => (0, import_path15.resolve)(d))));
15219
- const dirents = await (0, import_promises14.readdir)(abs, { withFileTypes: true });
15408
+ const deniedReal = await Promise.all(denied.map((d) => (0, import_promises15.realpath)(d).catch(() => (0, import_path16.resolve)(d))));
15409
+ const dirents = await (0, import_promises15.readdir)(abs, { withFileTypes: true });
15220
15410
  const entries = [];
15221
15411
  for (const d of dirents) {
15222
15412
  if (d.name === ".git") continue;
15223
- const child = (0, import_path15.join)(abs, d.name);
15224
- if (deniedReal.some((x) => child === x || child.startsWith(x + import_path15.sep))) continue;
15413
+ const child = (0, import_path16.join)(abs, d.name);
15414
+ if (deniedReal.some((x) => child === x || child.startsWith(x + import_path16.sep))) continue;
15225
15415
  let type = d.isDirectory() ? "dir" : d.isFile() ? "file" : null;
15226
15416
  let size2;
15227
15417
  if (d.isSymbolicLink()) {
15228
- const inside3 = await resolveInside(root, (0, import_path15.relative)(root, child)).catch(() => null);
15229
- const target = inside3 ? await (0, import_promises14.stat)(child).catch(() => null) : null;
15418
+ const inside3 = await resolveInside(root, (0, import_path16.relative)(root, child)).catch(() => null);
15419
+ const target = inside3 ? await (0, import_promises15.stat)(child).catch(() => null) : null;
15230
15420
  type = target?.isDirectory() ? "dir" : target?.isFile() ? "file" : null;
15231
15421
  size2 = target?.isFile() ? target.size : void 0;
15232
15422
  } else if (type === "file") {
15233
- size2 = (await (0, import_promises14.stat)(child).catch(() => null))?.size;
15423
+ size2 = (await (0, import_promises15.stat)(child).catch(() => null))?.size;
15234
15424
  }
15235
15425
  if (!type) continue;
15236
15426
  entries.push({ name: d.name, path: clean ? `${clean}/${d.name}` : d.name, type, ...size2 !== void 0 ? { size: size2 } : {} });
@@ -15240,11 +15430,11 @@ async function listFiles(root, rel, denied = []) {
15240
15430
  }
15241
15431
  async function readTextFile(root, rel, range = {}, denied = []) {
15242
15432
  const { abs, rel: clean } = await fenced(root, rel, denied);
15243
- const st = await (0, import_promises14.stat)(abs).catch(() => null);
15433
+ const st = await (0, import_promises15.stat)(abs).catch(() => null);
15244
15434
  if (!st) throw new FileRequestError("NOT_FOUND");
15245
15435
  if (!st.isFile()) throw new FileRequestError("NOT_A_FILE");
15246
15436
  if (st.size > FILE_CAPS.maxFileBytes) throw new FileRequestError("FILE_TOO_LARGE");
15247
- const fh = await (0, import_promises14.open)(abs, "r");
15437
+ const fh = await (0, import_promises15.open)(abs, "r");
15248
15438
  let buf;
15249
15439
  try {
15250
15440
  buf = Buffer.alloc(st.size);
@@ -15283,23 +15473,23 @@ function imageMime(buf) {
15283
15473
  }
15284
15474
  async function insideRelative(path, bases) {
15285
15475
  const clean = (path ?? "").trim().replace(/^file:\/\//i, "");
15286
- if (!(0, import_path15.isAbsolute)(clean)) return clean.replace(/^\.\//, "");
15476
+ if (!(0, import_path16.isAbsolute)(clean)) return clean.replace(/^\.\//, "");
15287
15477
  for (const base of bases) {
15288
- for (const root of [(0, import_path15.resolve)(base), await (0, import_promises14.realpath)(base).catch(() => (0, import_path15.resolve)(base))]) {
15289
- const rel = (0, import_path15.relative)(root, (0, import_path15.resolve)(clean));
15478
+ for (const root of [(0, import_path16.resolve)(base), await (0, import_promises15.realpath)(base).catch(() => (0, import_path16.resolve)(base))]) {
15479
+ const rel = (0, import_path16.relative)(root, (0, import_path16.resolve)(clean));
15290
15480
  if (!rel) return "";
15291
- if (rel !== ".." && !rel.startsWith(`..${import_path15.sep}`) && !(0, import_path15.isAbsolute)(rel)) return rel.split(import_path15.sep).join("/");
15481
+ if (rel !== ".." && !rel.startsWith(`..${import_path16.sep}`) && !(0, import_path16.isAbsolute)(rel)) return rel.split(import_path16.sep).join("/");
15292
15482
  }
15293
15483
  }
15294
15484
  throw new FileRequestError("PATH_OUTSIDE_WORKSPACE");
15295
15485
  }
15296
15486
  async function readWholeFile(root, rel, denied = []) {
15297
15487
  const { abs, rel: clean } = await fenced(root, rel, denied);
15298
- const st = await (0, import_promises14.stat)(abs).catch(() => null);
15488
+ const st = await (0, import_promises15.stat)(abs).catch(() => null);
15299
15489
  if (!st) throw new FileRequestError("NOT_FOUND");
15300
15490
  if (!st.isFile()) throw new FileRequestError("NOT_A_FILE");
15301
15491
  if (st.size > FILE_CAPS.maxImageBytes) throw new FileRequestError("FILE_TOO_LARGE");
15302
- const fh = await (0, import_promises14.open)(abs, "r");
15492
+ const fh = await (0, import_promises15.open)(abs, "r");
15303
15493
  try {
15304
15494
  const buf = Buffer.alloc(st.size);
15305
15495
  await fh.read(buf, 0, st.size, 0);
@@ -15310,11 +15500,11 @@ async function readWholeFile(root, rel, denied = []) {
15310
15500
  }
15311
15501
  async function readImageFile(root, rel, denied = []) {
15312
15502
  const { abs, rel: clean } = await fenced(root, rel, denied);
15313
- const st = await (0, import_promises14.stat)(abs).catch(() => null);
15503
+ const st = await (0, import_promises15.stat)(abs).catch(() => null);
15314
15504
  if (!st) throw new FileRequestError("NOT_FOUND");
15315
15505
  if (!st.isFile()) throw new FileRequestError("NOT_A_FILE");
15316
15506
  if (st.size > FILE_CAPS.maxImageBytes) throw new FileRequestError("FILE_TOO_LARGE");
15317
- const fh = await (0, import_promises14.open)(abs, "r");
15507
+ const fh = await (0, import_promises15.open)(abs, "r");
15318
15508
  let buf;
15319
15509
  try {
15320
15510
  buf = Buffer.alloc(st.size);
@@ -15394,8 +15584,8 @@ async function callOrgTool(host, server, tool, args) {
15394
15584
  }
15395
15585
 
15396
15586
  // src/application/services/workspaceSandbox/workspaceSkills.ts
15397
- var import_promises15 = require("fs/promises");
15398
- var import_path16 = require("path");
15587
+ var import_promises16 = require("fs/promises");
15588
+ var import_path17 = require("path");
15399
15589
  var SKILLS_PLUGIN = "sq";
15400
15590
  var BUILTIN_SKILLS = ["code-review", "simplify", "debug", "verify"];
15401
15591
  var SKILL_CAPS = { fileBytes: 256 * 1024, skillBytes: 2 * 1024 * 1024, skillFiles: 200, totalBytes: 16 * 1024 * 1024, skills: 200 };
@@ -15439,29 +15629,29 @@ ${lines2.join("\n")}
15439
15629
  ${neutralize(body)}`;
15440
15630
  }
15441
15631
  async function regularFile(abs, realRoot) {
15442
- const st = await (0, import_promises15.lstat)(abs).catch(() => null);
15632
+ const st = await (0, import_promises16.lstat)(abs).catch(() => null);
15443
15633
  if (!st?.isFile()) return false;
15444
- const real = await (0, import_promises15.realpath)(abs).catch(() => null);
15445
- return !!real && !(0, import_path16.relative)(realRoot, real).split(import_path16.sep).includes("..");
15634
+ const real = await (0, import_promises16.realpath)(abs).catch(() => null);
15635
+ return !!real && !(0, import_path17.relative)(realRoot, real).split(import_path17.sep).includes("..");
15446
15636
  }
15447
15637
  async function copySkillDir(src, dest, realRoot, budget) {
15448
15638
  let files = 0, bytes = 0;
15449
15639
  const walk = async (rel) => {
15450
- const entries = await (0, import_promises15.readdir)((0, import_path16.join)(src, rel), { withFileTypes: true }).catch(() => []);
15640
+ const entries = await (0, import_promises16.readdir)((0, import_path17.join)(src, rel), { withFileTypes: true }).catch(() => []);
15451
15641
  for (const e of entries) {
15452
15642
  if (files >= SKILL_CAPS.skillFiles || bytes >= SKILL_CAPS.skillBytes) return;
15453
- const r = rel ? (0, import_path16.join)(rel, e.name) : e.name;
15643
+ const r = rel ? (0, import_path17.join)(rel, e.name) : e.name;
15454
15644
  if (e.isDirectory()) {
15455
15645
  if (!SKIP_DIRS.has(e.name)) await walk(r);
15456
15646
  continue;
15457
15647
  }
15458
15648
  if (!e.isFile() || r === "SKILL.md") continue;
15459
- const abs = (0, import_path16.join)(src, r);
15649
+ const abs = (0, import_path17.join)(src, r);
15460
15650
  if (!await regularFile(abs, realRoot)) continue;
15461
- const buf = await (0, import_promises15.readFile)(abs).catch(() => null);
15651
+ const buf = await (0, import_promises16.readFile)(abs).catch(() => null);
15462
15652
  if (!buf || buf.length > SKILL_CAPS.fileBytes || bytes + buf.length > SKILL_CAPS.skillBytes || budget.bytes < buf.length) continue;
15463
- await (0, import_promises15.mkdir)((0, import_path16.join)(dest, rel), { recursive: true });
15464
- await (0, import_promises15.writeFile)((0, import_path16.join)(dest, r), buf, { mode: 384 });
15653
+ await (0, import_promises16.mkdir)((0, import_path17.join)(dest, rel), { recursive: true });
15654
+ await (0, import_promises16.writeFile)((0, import_path17.join)(dest, r), buf, { mode: 384 });
15465
15655
  files++;
15466
15656
  bytes += buf.length;
15467
15657
  budget.bytes -= buf.length;
@@ -15470,9 +15660,9 @@ async function copySkillDir(src, dest, realRoot, budget) {
15470
15660
  await walk("");
15471
15661
  }
15472
15662
  async function buildSkillsPlugin(opts) {
15473
- await (0, import_promises15.rm)(opts.dir, { recursive: true, force: true });
15474
- await (0, import_promises15.mkdir)((0, import_path16.join)(opts.dir, ".claude-plugin"), { recursive: true, mode: 448 });
15475
- await (0, import_promises15.writeFile)((0, import_path16.join)(opts.dir, ".claude-plugin", "plugin.json"), JSON.stringify({ name: SKILLS_PLUGIN, description: "Skills and commands of this ScaleQuality workspace" }));
15663
+ await (0, import_promises16.rm)(opts.dir, { recursive: true, force: true });
15664
+ await (0, import_promises16.mkdir)((0, import_path17.join)(opts.dir, ".claude-plugin"), { recursive: true, mode: 448 });
15665
+ await (0, import_promises16.writeFile)((0, import_path17.join)(opts.dir, ".claude-plugin", "plugin.json"), JSON.stringify({ name: SKILLS_PLUGIN, description: "Skills and commands of this ScaleQuality workspace" }));
15476
15666
  const out2 = [];
15477
15667
  const taken = new Set(BUILTIN_SKILLS);
15478
15668
  const budget = { bytes: SKILL_CAPS.totalBytes };
@@ -15483,31 +15673,31 @@ async function buildSkillsPlugin(opts) {
15483
15673
  const meta = { description: s.description ?? "", ...s.argumentHint ? { "argument-hint": s.argumentHint } : {} };
15484
15674
  const text3 = rebuild(meta, name, s.body);
15485
15675
  if (Buffer.byteLength(text3) > SKILL_CAPS.fileBytes) continue;
15486
- await (0, import_promises15.mkdir)((0, import_path16.join)(opts.dir, "skills", name), { recursive: true });
15487
- await (0, import_promises15.writeFile)((0, import_path16.join)(opts.dir, "skills", name, "SKILL.md"), text3, { mode: 384 });
15676
+ await (0, import_promises16.mkdir)((0, import_path17.join)(opts.dir, "skills", name), { recursive: true });
15677
+ await (0, import_promises16.writeFile)((0, import_path17.join)(opts.dir, "skills", name, "SKILL.md"), text3, { mode: 384 });
15488
15678
  budget.bytes -= Buffer.byteLength(text3);
15489
15679
  taken.add(name);
15490
15680
  out2.push({ name, description: meta.description.slice(0, 300), kind: "skill", source: "organization", ...s.argumentHint ? { argumentHint: s.argumentHint.slice(0, 120) } : {} });
15491
15681
  }
15492
15682
  for (const repo2 of opts.repos) {
15493
- const realRoot = await (0, import_promises15.realpath)(repo2.root).catch(() => null);
15683
+ const realRoot = await (0, import_promises16.realpath)(repo2.root).catch(() => null);
15494
15684
  if (!realRoot) continue;
15495
- const skillsDir = (0, import_path16.join)(repo2.root, ".claude", "skills");
15496
- for (const e of (await (0, import_promises15.readdir)(skillsDir, { withFileTypes: true }).catch(() => [])).sort((a, b) => a.name.localeCompare(b.name))) {
15685
+ const skillsDir = (0, import_path17.join)(repo2.root, ".claude", "skills");
15686
+ for (const e of (await (0, import_promises16.readdir)(skillsDir, { withFileTypes: true }).catch(() => [])).sort((a, b) => a.name.localeCompare(b.name))) {
15497
15687
  if (!room() || !e.isDirectory()) continue;
15498
- const file = (0, import_path16.join)(skillsDir, e.name, "SKILL.md");
15688
+ const file = (0, import_path17.join)(skillsDir, e.name, "SKILL.md");
15499
15689
  if (!await regularFile(file, realRoot)) continue;
15500
- const buf = await (0, import_promises15.readFile)(file).catch(() => null);
15690
+ const buf = await (0, import_promises16.readFile)(file).catch(() => null);
15501
15691
  if (!buf || buf.length > SKILL_CAPS.fileBytes || buf.includes(0)) continue;
15502
15692
  const { meta, body } = parseSkillFile(buf.toString("utf8"));
15503
15693
  const name = (meta.name || e.name).toLowerCase();
15504
15694
  if (!NAME.test(name) || taken.has(name)) continue;
15505
- const dest = (0, import_path16.join)(opts.dir, "skills", name);
15506
- await (0, import_promises15.mkdir)(dest, { recursive: true });
15695
+ const dest = (0, import_path17.join)(opts.dir, "skills", name);
15696
+ await (0, import_promises16.mkdir)(dest, { recursive: true });
15507
15697
  const text3 = rebuild(meta, name, body);
15508
- await (0, import_promises15.writeFile)((0, import_path16.join)(dest, "SKILL.md"), text3, { mode: 384 });
15698
+ await (0, import_promises16.writeFile)((0, import_path17.join)(dest, "SKILL.md"), text3, { mode: 384 });
15509
15699
  budget.bytes -= Buffer.byteLength(text3);
15510
- await copySkillDir((0, import_path16.join)(skillsDir, e.name), dest, realRoot, budget);
15700
+ await copySkillDir((0, import_path17.join)(skillsDir, e.name), dest, realRoot, budget);
15511
15701
  taken.add(name);
15512
15702
  out2.push({
15513
15703
  name,
@@ -15518,12 +15708,12 @@ async function buildSkillsPlugin(opts) {
15518
15708
  ...meta["argument-hint"] ? { argumentHint: meta["argument-hint"].slice(0, 120) } : {}
15519
15709
  });
15520
15710
  }
15521
- const commandsDir = (0, import_path16.join)(repo2.root, ".claude", "commands");
15522
- for (const e of (await (0, import_promises15.readdir)(commandsDir, { withFileTypes: true }).catch(() => [])).sort((a, b) => a.name.localeCompare(b.name))) {
15711
+ const commandsDir = (0, import_path17.join)(repo2.root, ".claude", "commands");
15712
+ for (const e of (await (0, import_promises16.readdir)(commandsDir, { withFileTypes: true }).catch(() => [])).sort((a, b) => a.name.localeCompare(b.name))) {
15523
15713
  if (!room() || !e.isFile() || !e.name.endsWith(".md")) continue;
15524
- const file = (0, import_path16.join)(commandsDir, e.name);
15714
+ const file = (0, import_path17.join)(commandsDir, e.name);
15525
15715
  if (!await regularFile(file, realRoot)) continue;
15526
- const buf = await (0, import_promises15.readFile)(file).catch(() => null);
15716
+ const buf = await (0, import_promises16.readFile)(file).catch(() => null);
15527
15717
  if (!buf || buf.length > SKILL_CAPS.fileBytes || buf.includes(0)) continue;
15528
15718
  const name = e.name.slice(0, -3).toLowerCase();
15529
15719
  if (!NAME.test(name) || taken.has(name)) continue;
@@ -15534,8 +15724,8 @@ ${lines2.join("\n")}
15534
15724
  ---
15535
15725
 
15536
15726
  ` : ""}${neutralize(body)}`;
15537
- await (0, import_promises15.mkdir)((0, import_path16.join)(opts.dir, "commands"), { recursive: true });
15538
- await (0, import_promises15.writeFile)((0, import_path16.join)(opts.dir, "commands", `${name}.md`), text3, { mode: 384 });
15727
+ await (0, import_promises16.mkdir)((0, import_path17.join)(opts.dir, "commands"), { recursive: true });
15728
+ await (0, import_promises16.writeFile)((0, import_path17.join)(opts.dir, "commands", `${name}.md`), text3, { mode: 384 });
15539
15729
  budget.bytes -= Buffer.byteLength(text3);
15540
15730
  taken.add(name);
15541
15731
  out2.push({
@@ -15574,19 +15764,19 @@ ${lines2.join("\n")}
15574
15764
  ${neutralize(body)}`;
15575
15765
  }
15576
15766
  async function buildOrganizationPlugins(opts) {
15577
- await (0, import_promises15.rm)(opts.dir, { recursive: true, force: true });
15767
+ await (0, import_promises16.rm)(opts.dir, { recursive: true, force: true });
15578
15768
  const entries = [], dirs = [];
15579
15769
  for (const p of opts.plugins) {
15580
15770
  const plugin = p.name.toLowerCase();
15581
15771
  if (!/^[a-z0-9][a-z0-9-]{0,39}$/.test(plugin) || plugin === SKILLS_PLUGIN || dirs.some((d) => d.endsWith(`/${plugin}`))) continue;
15582
- const root = (0, import_path16.join)(opts.dir, plugin);
15583
- await (0, import_promises15.mkdir)((0, import_path16.join)(root, ".claude-plugin"), { recursive: true, mode: 448 });
15584
- await (0, import_promises15.writeFile)((0, import_path16.join)(root, ".claude-plugin", "plugin.json"), JSON.stringify({ name: plugin }));
15772
+ const root = (0, import_path17.join)(opts.dir, plugin);
15773
+ await (0, import_promises16.mkdir)((0, import_path17.join)(root, ".claude-plugin"), { recursive: true, mode: 448 });
15774
+ await (0, import_promises16.writeFile)((0, import_path17.join)(root, ".claude-plugin", "plugin.json"), JSON.stringify({ name: plugin }));
15585
15775
  const write = async (rel, text3) => {
15586
- const abs = (0, import_path16.join)(root, rel);
15587
- if ((0, import_path16.relative)(root, abs).split(import_path16.sep).includes("..")) return;
15588
- await (0, import_promises15.mkdir)((0, import_path16.join)(abs, ".."), { recursive: true });
15589
- await (0, import_promises15.writeFile)(abs, text3, { mode: 384 });
15776
+ const abs = (0, import_path17.join)(root, rel);
15777
+ if ((0, import_path17.relative)(root, abs).split(import_path17.sep).includes("..")) return;
15778
+ await (0, import_promises16.mkdir)((0, import_path17.join)(abs, ".."), { recursive: true });
15779
+ await (0, import_promises16.writeFile)(abs, text3, { mode: 384 });
15590
15780
  };
15591
15781
  for (const f of p.files) {
15592
15782
  if (typeof f?.path !== "string" || typeof f.content !== "string" || f.path.split("/").some((x) => x === ".." || x === "")) continue;
@@ -15713,7 +15903,7 @@ function turnOffering(raw, loaded) {
15713
15903
  mcpCatalog: loaded.catalog ? { ...loaded.catalog, servers: loaded.catalog.servers.filter((sv) => !connectors.has(sv.server.toLowerCase())) } : null,
15714
15904
  mcpServers: Object.fromEntries(Object.entries(loaded.servers).filter(([key]) => !connectors.has(key.slice(ORG_MCP_PREFIX.length).toLowerCase()))),
15715
15905
  skillEntries: loaded.skillEntries.filter((e) => !(e.source === "plugin" && e.plugin && plugins.has(e.plugin))),
15716
- pluginDirs: loaded.pluginDirs.filter((d) => !plugins.has((0, import_path17.basename)(d).toLowerCase()))
15906
+ pluginDirs: loaded.pluginDirs.filter((d) => !plugins.has((0, import_path18.basename)(d).toLowerCase()))
15717
15907
  };
15718
15908
  }
15719
15909
  function sameModel(a, b) {
@@ -15836,6 +16026,11 @@ var WorkspaceEngine = class {
15836
16026
  opening = /* @__PURE__ */ new Map();
15837
16027
  /** Saved changes of repositories not open in this run: never dropped from the checkpoint. */
15838
16028
  pendingCheckpoints = /* @__PURE__ */ new Map();
16029
+ /**
16030
+ * The cloud workspace's own files go in the checkpoint (rootFiles.ts). Off on a computer (its folder keeps them),
16031
+ * and while the saved ones could not be put back on this machine: they are then kept as saved.
16032
+ */
16033
+ workspaceFiles = false;
15839
16034
  sdk = null;
15840
16035
  mcpServer = null;
15841
16036
  sdkSessionId = null;
@@ -16076,7 +16271,7 @@ var WorkspaceEngine = class {
16076
16271
  }
16077
16272
  if (this.deps.clone && !this.local) {
16078
16273
  for (const name of [...this.pendingCheckpoints.keys()]) {
16079
- if (name === LOCAL_FOLDER_KEY || !this.inScope(name) || this.repoNamed(name)) continue;
16274
+ if (name === LOCAL_FOLDER_KEY || name === WORKSPACE_FILES_KEY || !this.inScope(name) || this.repoNamed(name)) continue;
16080
16275
  const r = await this.openRepository(name);
16081
16276
  if (r.isError) this.error("REPOSITORY_CHECKPOINT_NOT_RESTORED", { repoFullName: name });
16082
16277
  }
@@ -16087,6 +16282,7 @@ var WorkspaceEngine = class {
16087
16282
  if (opened.isError) this.deps.log.warn("scope repository not opened at start", { repo: r.repoFullName });
16088
16283
  }
16089
16284
  }
16285
+ await this.restoreWorkspaceFiles(boot);
16090
16286
  }
16091
16287
  this.phase("ENGINE");
16092
16288
  try {
@@ -16105,7 +16301,7 @@ var WorkspaceEngine = class {
16105
16301
  }
16106
16302
  await this.backgroundOutputDir();
16107
16303
  if (boot.plugins?.length) {
16108
- this.orgPlugins = await buildOrganizationPlugins({ dir: (0, import_path17.join)(this.deps.configDir, "sq-org-plugins"), plugins: boot.plugins }).catch((e) => {
16304
+ this.orgPlugins = await buildOrganizationPlugins({ dir: (0, import_path18.join)(this.deps.configDir, "sq-org-plugins"), plugins: boot.plugins }).catch((e) => {
16109
16305
  this.deps.log.warn("organization plugins unavailable", { error: this.redactor.text(e.message) });
16110
16306
  return { entries: [], dirs: [] };
16111
16307
  });
@@ -16132,8 +16328,8 @@ var WorkspaceEngine = class {
16132
16328
  }
16133
16329
  /** Where a background command writes its output: inside the config dir, which Read may read. */
16134
16330
  async backgroundOutputDir() {
16135
- await (0, import_promises16.mkdir)((0, import_path17.join)(this.deps.configDir, "tmp"), { recursive: true, mode: 448 }).catch(() => void 0);
16136
- await (0, import_promises16.mkdir)((0, import_path17.join)(this.deps.configDir, "plans"), { recursive: true, mode: 448 }).catch(() => void 0);
16331
+ await (0, import_promises17.mkdir)((0, import_path18.join)(this.deps.configDir, "tmp"), { recursive: true, mode: 448 }).catch(() => void 0);
16332
+ await (0, import_promises17.mkdir)((0, import_path18.join)(this.deps.configDir, "plans"), { recursive: true, mode: 448 }).catch(() => void 0);
16137
16333
  }
16138
16334
  /** Runs until shutdown. */
16139
16335
  async run() {
@@ -16162,7 +16358,7 @@ var WorkspaceEngine = class {
16162
16358
  const repo2 = {
16163
16359
  ...r,
16164
16360
  tracker: r.tracker ?? gitTracker(r.root, r.prepared.baseRevision, r.prefix),
16165
- measurer: this.deps.createMeasurer && !this.local ? this.deps.createMeasurer(r.repoFullName ?? (0, import_path17.basename)(r.root), r.root, this.baseStore(r.repoFullName), r.repoFullName) : null,
16361
+ measurer: this.deps.createMeasurer && !this.local ? this.deps.createMeasurer(r.repoFullName ?? (0, import_path18.basename)(r.root), r.root, this.baseStore(r.repoFullName), r.repoFullName) : null,
16166
16362
  lastDiff: null
16167
16363
  };
16168
16364
  this.repos.set(r.root, repo2);
@@ -16191,14 +16387,14 @@ var WorkspaceEngine = class {
16191
16387
  const short = folderName(lastSegment(repoFullName));
16192
16388
  const full = folderName(repoFullName.split("/").filter(Boolean).join("__"));
16193
16389
  const clash = this.scope.repos.some((r) => r.repoFullName !== repoFullName && folderName(lastSegment(r.repoFullName)) === short);
16194
- const privateDirs = (this.deps.privateDirs ?? []).map((d) => (0, import_path17.resolve)(d));
16390
+ const privateDirs = (this.deps.privateDirs ?? []).map((d) => (0, import_path18.resolve)(d));
16195
16391
  const taken = (name2) => {
16196
- const dir = (0, import_path17.resolve)(this.deps.root, name2);
16197
- return this.repos.has(dir) || privateDirs.includes(dir) || (0, import_fs11.existsSync)(dir);
16392
+ const dir = (0, import_path18.resolve)(this.deps.root, name2);
16393
+ return this.repos.has(dir) || privateDirs.includes(dir) || (0, import_fs12.existsSync)(dir);
16198
16394
  };
16199
16395
  let name = clash || taken(short) ? full : short;
16200
16396
  for (let n = 2; taken(name); n++) name = `${full}-${n}`;
16201
- return (0, import_path17.join)(this.deps.root, name);
16397
+ return (0, import_path18.join)(this.deps.root, name);
16202
16398
  }
16203
16399
  /** Clones one repository into its folder and registers it. The token is dropped either way. */
16204
16400
  async cloneInto(access, onStep) {
@@ -16208,7 +16404,7 @@ var WorkspaceEngine = class {
16208
16404
  try {
16209
16405
  prepared = await this.deps.clone(access, dir, saved, onStep);
16210
16406
  } catch (e) {
16211
- await (0, import_promises16.rm)(dir, { recursive: true, force: true }).catch(() => void 0);
16407
+ await (0, import_promises17.rm)(dir, { recursive: true, force: true }).catch(() => void 0);
16212
16408
  throw e;
16213
16409
  } finally {
16214
16410
  access.token = "";
@@ -16245,7 +16441,7 @@ var WorkspaceEngine = class {
16245
16441
  }
16246
16442
  if (open2.length === 1) return { repo: open2[0] };
16247
16443
  if (!open2.length) return { error: "No repository is open in this workspace. Call list_repositories, then open_repository." };
16248
- return { error: `Several repositories are open (${open2.map((o) => o.repoFullName ?? (0, import_path17.basename)(o.root)).join(", ")}). Pass repoFullName.` };
16444
+ return { error: `Several repositories are open (${open2.map((o) => o.repoFullName ?? (0, import_path18.basename)(o.root)).join(", ")}). Pass repoFullName.` };
16249
16445
  }
16250
16446
  notInScope(repo2, target) {
16251
16447
  const loose = repo2.localId === LOOSE_REPO_ID;
@@ -16518,7 +16714,7 @@ var WorkspaceEngine = class {
16518
16714
  PUB_CACHE: ".pub-cache",
16519
16715
  BUNDLE_PATH: ".bundle"
16520
16716
  };
16521
- for (const [k, rel] of Object.entries(caches)) if (env[k] !== void 0) env[k] = (0, import_path17.join)(user.home, rel);
16717
+ for (const [k, rel] of Object.entries(caches)) if (env[k] !== void 0) env[k] = (0, import_path18.join)(user.home, rel);
16522
16718
  return {
16523
16719
  file: user.shell,
16524
16720
  args: ["-l"],
@@ -16533,9 +16729,9 @@ var WorkspaceEngine = class {
16533
16729
  * (default ACL), never the engine's own folders (its state and transcripts stay root's, 0700).
16534
16730
  */
16535
16731
  async shareWithTerminal(uid) {
16536
- const root = (0, import_path17.resolve)(this.deps.root);
16537
- const own = new Set((this.deps.privateDirs ?? []).map((d) => (0, import_path17.resolve)(d)));
16538
- for (const dir of own) await (0, import_promises16.chmod)(dir, 448).catch(() => void 0);
16732
+ const root = (0, import_path18.resolve)(this.deps.root);
16733
+ const own = new Set((this.deps.privateDirs ?? []).map((d) => (0, import_path18.resolve)(d)));
16734
+ for (const dir of own) await (0, import_promises17.chmod)(dir, 448).catch(() => void 0);
16539
16735
  const acl = (args) => new Promise((done) => {
16540
16736
  const child = (0, import_child_process5.spawn)("setfacl", args, { stdio: "ignore" });
16541
16737
  child.on("error", () => done(false));
@@ -16545,9 +16741,9 @@ var WorkspaceEngine = class {
16545
16741
  if (!await acl(["-m", `u:${uid}:rwx`, "-m", `d:u:${uid}:rwX`, root])) this.deps.log.warn("terminal: the workspace folder could not be shared with its user");
16546
16742
  this.terminalShared.add(root);
16547
16743
  }
16548
- const sweep = Promise.all((await (0, import_promises16.readdir)(root).catch(() => [])).map(async (name) => {
16549
- const path = (0, import_path17.join)(root, name);
16550
- if (this.terminalShared.has(path) || own.has(path) || [...own].some((d) => d.startsWith(path + import_path17.sep))) return;
16744
+ const sweep = Promise.all((await (0, import_promises17.readdir)(root).catch(() => [])).map(async (name) => {
16745
+ const path = (0, import_path18.join)(root, name);
16746
+ if (this.terminalShared.has(path) || own.has(path) || [...own].some((d) => d.startsWith(path + import_path18.sep))) return;
16551
16747
  if (await acl(["-R", "-m", `u:${uid}:rwX`, "-m", `d:u:${uid}:rwX`, path])) this.terminalShared.add(path);
16552
16748
  }));
16553
16749
  await Promise.race([sweep, new Promise((r) => setTimeout(r, TERMINAL_SHARE_WAIT_MS).unref?.())]);
@@ -16864,7 +17060,7 @@ ${String(item.content)}` : String(item.content);
16864
17060
  askQuestions: !!this.boot?.askQuestions
16865
17061
  });
16866
17062
  const conventions = await readConventions([...this.repos.values()].filter((r) => !r.dormant).flatMap((r) => {
16867
- const label = r.repoFullName ?? r.localId ?? (0, import_path17.basename)(r.root);
17063
+ const label = r.repoFullName ?? r.localId ?? (0, import_path18.basename)(r.root);
16868
17064
  return r.fence && r.fence !== r.root ? [{ label, root: r.root }, { label: `${label} (${r.prefix})`, root: r.fence }] : [{ label, root: r.root }];
16869
17065
  })).catch(() => []);
16870
17066
  return base + conventionsSection(conventions);
@@ -16958,7 +17154,7 @@ ${String(item.content)}` : String(item.content);
16958
17154
  return {
16959
17155
  registry: this.registry,
16960
17156
  currentBranch: async () => (await git(["rev-parse", "--abbrev-ref", "HEAD"], { cwd: this.deps.root, timeoutMs: 3e3 })).trim() || null,
16961
- installedLocally: (name) => [this.deps.root, ...[...this.repos.values()].map((r) => r.root)].some((dir) => (0, import_fs11.existsSync)((0, import_path17.join)(dir, "node_modules", name, "package.json")) || (0, import_fs11.existsSync)((0, import_path17.join)(dir, "node_modules", ".bin", name)))
17157
+ installedLocally: (name) => [this.deps.root, ...[...this.repos.values()].map((r) => r.root)].some((dir) => (0, import_fs12.existsSync)((0, import_path18.join)(dir, "node_modules", name, "package.json")) || (0, import_fs12.existsSync)((0, import_path18.join)(dir, "node_modules", ".bin", name)))
16962
17158
  };
16963
17159
  }
16964
17160
  /**
@@ -17065,7 +17261,7 @@ ${String(item.content)}` : String(item.content);
17065
17261
  for (const repo2 of this.repos.values()) {
17066
17262
  const tree = cp.trees.get(repo2.root);
17067
17263
  if (!tree) {
17068
- if (!repo2.dormant) untouched.push(repo2.repoFullName ?? repo2.localId ?? (0, import_path17.basename)(repo2.root));
17264
+ if (!repo2.dormant) untouched.push(repo2.repoFullName ?? repo2.localId ?? (0, import_path18.basename)(repo2.root));
17069
17265
  continue;
17070
17266
  }
17071
17267
  try {
@@ -17101,7 +17297,7 @@ ${String(item.content)}` : String(item.content);
17101
17297
  return;
17102
17298
  }
17103
17299
  const repo2 = picked.repo;
17104
- const label = repo2.repoFullName ?? repo2.localId ?? (0, import_path17.basename)(repo2.root);
17300
+ const label = repo2.repoFullName ?? repo2.localId ?? (0, import_path18.basename)(repo2.root);
17105
17301
  const cwd = repo2.fence ?? repo2.root;
17106
17302
  const detected = (this.deps.detectTests ? await this.deps.detectTests(cwd).catch(() => null) : null) ?? await detectTestCommandFromManifests(cwd).catch(() => null);
17107
17303
  if (!detected) {
@@ -17198,10 +17394,10 @@ ${String(item.content)}` : String(item.content);
17198
17394
  }
17199
17395
  /** A file the person attached, saved whole in the engine's own folder (the file tools read there, nothing writes there). */
17200
17396
  async saveAttachment(name, bytes) {
17201
- const dir = (0, import_path17.join)(this.deps.configDir, "attachments", (0, import_crypto9.randomUUID)());
17202
- await (0, import_promises16.mkdir)(dir, { recursive: true });
17203
- const path = (0, import_path17.join)(dir, (0, import_path17.basename)(name ?? "").replace(/[\u0000-\u001f\\/:]/g, "_").replace(/^\.+/, "") || "attachment");
17204
- await (0, import_promises16.writeFile)(path, bytes);
17397
+ const dir = (0, import_path18.join)(this.deps.configDir, "attachments", (0, import_crypto9.randomUUID)());
17398
+ await (0, import_promises17.mkdir)(dir, { recursive: true });
17399
+ const path = (0, import_path18.join)(dir, (0, import_path18.basename)(name ?? "").replace(/[\u0000-\u001f\\/:]/g, "_").replace(/^\.+/, "") || "attachment");
17400
+ await (0, import_promises17.writeFile)(path, bytes);
17205
17401
  return path;
17206
17402
  }
17207
17403
  /**
@@ -17339,7 +17535,7 @@ ${json}
17339
17535
  }
17340
17536
  /** The plugin with the repositories' and the organization's skills, rebuilt; the list goes to the screen when it changed. */
17341
17537
  async refreshSkills() {
17342
- const repos = [...this.repos.values()].filter((r) => !r.dormant).map((r) => ({ label: r.repoFullName ?? r.localId ?? (0, import_path17.basename)(r.root), root: r.fence ?? r.root }));
17538
+ const repos = [...this.repos.values()].filter((r) => !r.dormant).map((r) => ({ label: r.repoFullName ?? r.localId ?? (0, import_path18.basename)(r.root), root: r.fence ?? r.root }));
17343
17539
  try {
17344
17540
  this.skillEntries = [...await buildSkillsPlugin({ dir: this.skillsDir(), repos, organization: this.boot?.skills ?? [] }), ...this.orgPlugins.entries];
17345
17541
  } catch (e) {
@@ -17352,7 +17548,7 @@ ${json}
17352
17548
  this.emit({ type: "skills", data: { skills: this.skillEntries } });
17353
17549
  }
17354
17550
  skillsDir() {
17355
- return (0, import_path17.join)(this.deps.configDir, "sq-plugin");
17551
+ return (0, import_path18.join)(this.deps.configDir, "sq-plugin");
17356
17552
  }
17357
17553
  /**
17358
17554
  * The organization's MCP servers (their tools, from the API): one in-process server each, forwarding calls to
@@ -17403,7 +17599,7 @@ ${json}
17403
17599
  }
17404
17600
  }
17405
17601
  async runEnvSetup(repo2, command, secrets) {
17406
- const label = repo2.repoFullName ?? (0, import_path17.basename)(repo2.root);
17602
+ const label = repo2.repoFullName ?? (0, import_path18.basename)(repo2.root);
17407
17603
  const step = this.ownStep("setup", "command", `Preparing the environment of ${label}`, "STEP_ENV_SETUP", { repoFullName: label }, this.redactor.text(command));
17408
17604
  const started = Date.now();
17409
17605
  const { exitCode, output } = await this.runStreaming(command, repo2.fence ?? repo2.root, step.id, this.envAbort.signal, secrets);
@@ -17910,7 +18106,7 @@ ${text3}`;
17910
18106
  deniedRoots: this.deps.privateDirs,
17911
18107
  local: this.local,
17912
18108
  plan: t.planMode,
17913
- planDir: (0, import_path17.join)(this.deps.configDir, "plans"),
18109
+ planDir: (0, import_path18.join)(this.deps.configDir, "plans"),
17914
18110
  orgMcpTools: orgMcpToolNames(org ? t.off.mcpCatalog : null)
17915
18111
  },
17916
18112
  plan: t.planMode,
@@ -18101,6 +18297,34 @@ ${text3}`;
18101
18297
  });
18102
18298
  return this.diffChain;
18103
18299
  }
18300
+ /**
18301
+ * The workspace's own files back on this machine before the conversation goes on (rootFiles.ts), then the designs
18302
+ * the API kept that are still missing (a session saved before its files went in the checkpoint): its newest version.
18303
+ * A design inside a repository comes back with the repository's own change.
18304
+ */
18305
+ async restoreWorkspaceFiles(boot) {
18306
+ const saved = this.pendingCheckpoints.get(WORKSPACE_FILES_KEY) ?? null;
18307
+ try {
18308
+ if (saved) this.deps.log.info("workspace files restored", await restoreRootFiles(this.deps.root, this.deps.scratch, saved));
18309
+ this.pendingCheckpoints.delete(WORKSPACE_FILES_KEY);
18310
+ this.workspaceFiles = true;
18311
+ } catch (e) {
18312
+ this.deps.log.warn("workspace files not restored", { error: this.redactor.text(e.message) });
18313
+ }
18314
+ const keptDesign = this.deps.transport.keptDesign?.bind(this.deps.transport);
18315
+ if (!keptDesign) return;
18316
+ for (const d of boot.keptDesigns ?? []) {
18317
+ if (!/^design\/[^/]+\/design\.json$/.test(d.path) || this.repos.has((0, import_path18.join)(this.deps.root, "design"))) continue;
18318
+ if ((0, import_fs12.existsSync)((0, import_path18.join)(this.deps.root, d.path))) continue;
18319
+ try {
18320
+ const kept = await keptDesign(d.path);
18321
+ const written = kept ? await restoreKeptDesign(this.deps.root, d.path, kept.files) : 0;
18322
+ if (written) this.deps.log.info("design restored from its kept version", { path: d.path, n: kept?.n, files: written });
18323
+ } catch (e) {
18324
+ this.deps.log.warn("kept design not restored", { path: d.path, error: this.redactor.text(e.message) });
18325
+ }
18326
+ }
18327
+ }
18104
18328
  /**
18105
18329
  * The checkpoint: every open repository's change against its base, plus the
18106
18330
  * saved changes of repositories not open in this run, as one map. In the
@@ -18118,6 +18342,14 @@ ${text3}`;
18118
18342
  }
18119
18343
  async saveChange() {
18120
18344
  const map = new Map(this.pendingCheckpoints);
18345
+ if (this.workspaceFiles) {
18346
+ const excluded = [...[...this.repos.values()].map((r) => r.root), ...this.deps.privateDirs ?? [], this.deps.scratch, this.deps.configDir];
18347
+ const { files, leftOut } = await listRootFiles(this.deps.root, excluded);
18348
+ if (leftOut) this.deps.log.warn("workspace files left out of the checkpoint", { kept: files.length, leftOut });
18349
+ const patch2 = await rootFilesCheckpoint(this.deps.root, this.deps.scratch, files);
18350
+ if (patch2) map.set(WORKSPACE_FILES_KEY, patch2);
18351
+ else map.delete(WORKSPACE_FILES_KEY);
18352
+ }
18121
18353
  for (const repo2 of this.repos.values()) {
18122
18354
  const key2 = repo2.repoFullName ?? repo2.localId ?? LOCAL_FOLDER_KEY;
18123
18355
  if (repo2.dormant) {
@@ -18223,7 +18455,7 @@ ${patch}`;
18223
18455
  this.pendingCheckpoints.delete(repo2.localId);
18224
18456
  repo2.dormant = !repo2.unsaved;
18225
18457
  }
18226
- const stateDir = this.deps.stateDir ?? (0, import_path17.join)(this.deps.scratch, `folder-${(0, import_crypto9.createHash)("sha256").update(local.root).digest("hex").slice(0, 16)}`);
18458
+ const stateDir = this.deps.stateDir ?? (0, import_path18.join)(this.deps.scratch, `folder-${(0, import_crypto9.createHash)("sha256").update(local.root).digest("hex").slice(0, 16)}`);
18227
18459
  const tracker = new LooseFileTracker({ root: local.root, stateDir, excluded: () => local.repos.map((r) => r.root) });
18228
18460
  const tracked = local.gitAvailable && await tracker.init().then(() => true, (e) => {
18229
18461
  this.deps.log.warn("loose files not tracked", { error: e.message });
@@ -18275,7 +18507,7 @@ ${patch}`;
18275
18507
  let owner = null;
18276
18508
  for (const r of this.repos.values()) {
18277
18509
  if (r.localId === LOOSE_REPO_ID) continue;
18278
- if ((abs === r.root || abs.startsWith(r.root + import_path17.sep)) && (!owner || r.root.length > owner.root.length)) owner = r;
18510
+ if ((abs === r.root || abs.startsWith(r.root + import_path18.sep)) && (!owner || r.root.length > owner.root.length)) owner = r;
18279
18511
  }
18280
18512
  if (owner) {
18281
18513
  if (owner.dormant) await this.wake(owner, true);
@@ -18314,7 +18546,7 @@ ${patch}`;
18314
18546
  if (!f || f.kind === "repo") return void 0;
18315
18547
  if (f.kind === "subfolder") return { kind: "subfolder", repoRoot: f.repoRoot ?? "", prefix: f.prefix };
18316
18548
  const repos = [...this.repos.values()].filter((r) => r.localId && r.localId !== LOOSE_REPO_ID).map((r) => ({
18317
- path: (0, import_path17.relative)(f.root, r.root).split(import_path17.sep).join("/"),
18549
+ path: (0, import_path18.relative)(f.root, r.root).split(import_path18.sep).join("/"),
18318
18550
  id: r.repoFullName ?? r.localId,
18319
18551
  repoFullName: r.repoFullName,
18320
18552
  projectId: r.repoFullName ? this.scope.repos.find((x) => x.repoFullName === r.repoFullName)?.projectId ?? null : null,
@@ -18390,14 +18622,14 @@ ${patch}`;
18390
18622
  const files = [];
18391
18623
  let bytes = 0;
18392
18624
  const NAME2 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
18393
- const top = await (0, import_promises16.readdir)(folder, { withFileTypes: true }).catch(() => []);
18394
- const nested = await Promise.all(top.filter((e) => e.isDirectory() && NAME2.test(e.name)).slice(0, 10).map(async (d) => (await (0, import_promises16.readdir)((0, import_path17.join)(folder, d.name), { withFileTypes: true }).catch(() => [])).filter((e) => e.isFile() && NAME2.test(e.name)).map((e) => `${d.name}/${e.name}`)));
18625
+ const top = await (0, import_promises17.readdir)(folder, { withFileTypes: true }).catch(() => []);
18626
+ const nested = await Promise.all(top.filter((e) => e.isDirectory() && NAME2.test(e.name)).slice(0, 10).map(async (d) => (await (0, import_promises17.readdir)((0, import_path18.join)(folder, d.name), { withFileTypes: true }).catch(() => [])).filter((e) => e.isFile() && NAME2.test(e.name)).map((e) => `${d.name}/${e.name}`)));
18395
18627
  const rank = (n) => n === "design.json" ? 0 : n.includes("/") ? 2 : 1;
18396
18628
  const names = [...top.filter((e) => e.isFile() && NAME2.test(e.name)).map((e) => e.name), ...nested.flat()].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b)).slice(0, 60);
18397
18629
  for (const name of names) {
18398
- const st = await (0, import_promises16.stat)((0, import_path17.join)(folder, name)).catch(() => null);
18630
+ const st = await (0, import_promises17.stat)((0, import_path18.join)(folder, name)).catch(() => null);
18399
18631
  if (!st || st.size > 4 * 1024 * 1024 || bytes + st.size > 6 * 1024 * 1024) continue;
18400
- const data = await (0, import_promises16.readFile)((0, import_path17.join)(folder, name)).catch(() => null);
18632
+ const data = await (0, import_promises17.readFile)((0, import_path18.join)(folder, name)).catch(() => null);
18401
18633
  if (!data) continue;
18402
18634
  bytes += data.length;
18403
18635
  files.push({ name, data: data.toString("base64") });
@@ -18424,7 +18656,7 @@ ${patch}`;
18424
18656
  const chrome = findChrome();
18425
18657
  if (!chrome) return text("No Chrome or Chromium is installed here, so the screens could not be opened in a browser. Review them by reading the files, and tell the user in one sentence that they were not checked in a browser.", true);
18426
18658
  const checks = await checkDesign(chrome, design.folder, design.manifest);
18427
- const rel = designPath(await (0, import_promises16.realpath)(this.deps.root).catch(() => this.deps.root), abs);
18659
+ const rel = designPath(await (0, import_promises17.realpath)(this.deps.root).catch(() => this.deps.root), abs);
18428
18660
  this.designsChecked.set(rel, design.folder);
18429
18661
  this.emit({ type: "design", data: { path: rel, title: design.manifest.title, ...designSummary(checks), checkedAt: (/* @__PURE__ */ new Date()).toISOString() } });
18430
18662
  const content = [{ type: "text", text: designReport(rel, design.manifest, checks) }];
@@ -18447,14 +18679,14 @@ ${patch}`;
18447
18679
  const chrome = findChrome();
18448
18680
  if (!chrome) return text("No Chrome or Chromium is installed here, so no screenshot was taken. The user sees the app in the conversation when you write ![App](its address); say so in one sentence.", true);
18449
18681
  try {
18450
- await (0, import_promises16.mkdir)((0, import_path17.dirname)(target), { recursive: true });
18682
+ await (0, import_promises17.mkdir)((0, import_path18.dirname)(target), { recursive: true });
18451
18683
  await screenshotPage(chrome, args.url, target, { width: args.width ?? 1280, height: args.height ?? 800 });
18452
18684
  } catch (e) {
18453
18685
  this.deps.log.warn("app screenshot failed", { error: this.redactor.text(e.message) });
18454
18686
  return text(`The screenshot of ${args.url} failed: is the app running there? Start it in the background and try again.`, true);
18455
18687
  }
18456
18688
  this.scheduleDiff();
18457
- const rel = (0, import_path17.relative)(await (0, import_promises16.realpath)(this.deps.root).catch(() => this.deps.root), target).split(import_path17.sep).join("/");
18689
+ const rel = (0, import_path18.relative)(await (0, import_promises17.realpath)(this.deps.root).catch(() => this.deps.root), target).split(import_path18.sep).join("/");
18458
18690
  return text(`Saved the screenshot to ${rel}. Read it to see the app, and show it as ![short description](${rel}) when it helps the user.`);
18459
18691
  }
18460
18692
  async searchWeb(query) {
@@ -18492,7 +18724,7 @@ ${sources}` : ""}`);
18492
18724
  try {
18493
18725
  const image = await readImageFile(root, await insideRelative(args.editPath, [root]), this.deps.privateDirs ?? []);
18494
18726
  if (!["image/png", "image/jpeg", "image/webp"].includes(image.mime)) return text(`${args.editPath} is not a PNG, JPEG or WebP image, so it cannot be changed. Nothing was created.`, true);
18495
- reference = { name: (0, import_path17.basename)(image.path), mimeType: image.mime, sizeBytes: image.size, dataBase64: image.data };
18727
+ reference = { name: (0, import_path18.basename)(image.path), mimeType: image.mime, sizeBytes: image.size, dataBase64: image.data };
18496
18728
  } catch (e) {
18497
18729
  return text(`Could not read ${args.editPath} to change it (${e instanceof FileRequestError ? e.code : "UNREADABLE"}). Nothing was created.`, true);
18498
18730
  }
@@ -18507,10 +18739,10 @@ ${sources}` : ""}`);
18507
18739
  if ("refused" in created) return text(`The image could not be created (${created.refused}). Tell the user plainly in one sentence; do not claim an image was made and do not offer a prompt for another tool instead.`, true);
18508
18740
  const bytes = Buffer.from(created.dataBase64, "base64");
18509
18741
  if (!bytes.length || !imageMime(bytes)) return text("The image model returned something that is not an image. Nothing was saved.", true);
18510
- await (0, import_promises16.mkdir)((0, import_path17.dirname)(target), { recursive: true });
18511
- await (0, import_promises16.writeFile)(target, bytes);
18742
+ await (0, import_promises17.mkdir)((0, import_path18.dirname)(target), { recursive: true });
18743
+ await (0, import_promises17.writeFile)(target, bytes);
18512
18744
  this.scheduleDiff();
18513
- const rel = (0, import_path17.relative)(await (0, import_promises16.realpath)(root).catch(() => root), target).split(import_path17.sep).join("/");
18745
+ const rel = (0, import_path18.relative)(await (0, import_promises17.realpath)(root).catch(() => root), target).split(import_path18.sep).join("/");
18514
18746
  return text(`Saved the image to ${rel}. Show it to the user in your answer as ![short description](${rel}) and say in one or two sentences what you made.`);
18515
18747
  }
18516
18748
  listRepositories() {
@@ -18589,7 +18821,7 @@ ${JSON.stringify(data, null, 1)}`);
18589
18821
  const repo2 = picked.repo;
18590
18822
  const refused = this.notInScope(repo2);
18591
18823
  if (refused) {
18592
- say2("REPOSITORY_NOT_IN_SCOPE", { repoFullName: repo2.repoFullName ?? (0, import_path17.basename)(repo2.root) });
18824
+ say2("REPOSITORY_NOT_IN_SCOPE", { repoFullName: repo2.repoFullName ?? (0, import_path18.basename)(repo2.root) });
18593
18825
  return text(refused, true);
18594
18826
  }
18595
18827
  if (!repo2.measurer) {
@@ -18610,7 +18842,7 @@ ${JSON.stringify(data, null, 1)}`);
18610
18842
  return text("The measurement did not finish in time. Say it was not measured; do not estimate.", true);
18611
18843
  }
18612
18844
  if ("empty" in r) {
18613
- say2("NOTHING_TO_MEASURE", { repoFullName: repo2.repoFullName ?? (0, import_path17.basename)(repo2.root) });
18845
+ say2("NOTHING_TO_MEASURE", { repoFullName: repo2.repoFullName ?? (0, import_path18.basename)(repo2.root) });
18614
18846
  return text(`There is no change in ${repo2.repoFullName} to measure.`);
18615
18847
  }
18616
18848
  this.emit({ type: "measurement", data: { ...r.data, ...repo2.repoFullName ? { repoFullName: repo2.repoFullName } : {} } });
@@ -18832,7 +19064,7 @@ function buildEngineEnv(boot, configDir, model, opts = {}) {
18832
19064
  Object.assign(env, {
18833
19065
  CLAUDE_CONFIG_DIR: configDir,
18834
19066
  // Background command output lands here, inside the config dir the policy lets Read read.
18835
- CLAUDE_CODE_TMPDIR: (0, import_path17.join)(configDir, "tmp"),
19067
+ CLAUDE_CODE_TMPDIR: (0, import_path18.join)(configDir, "tmp"),
18836
19068
  CLAUDE_AGENT_SDK_CLIENT_APP: opts.local ? "scalequality-cli-connect/1.0" : "scalequality-workspace/1.0",
18837
19069
  DISABLE_TELEMETRY: "1",
18838
19070
  DISABLE_ERROR_REPORTING: "1",
@@ -18868,7 +19100,7 @@ function buildQueryOptions(o) {
18868
19100
  const dir = o.policy.planDir;
18869
19101
  if (!file || !dir || !file.endsWith(".md")) return "";
18870
19102
  const abs = await resolveInside(dir, file);
18871
- return abs ? (0, import_promises16.readFile)(abs, "utf8").catch(() => "") : "";
19103
+ return abs ? (0, import_promises17.readFile)(abs, "utf8").catch(() => "") : "";
18872
19104
  };
18873
19105
  const preToolUse = async (input) => {
18874
19106
  if (input.hook_event_name !== "PreToolUse") return {};
@@ -18933,7 +19165,7 @@ function buildQueryOptions(o) {
18933
19165
  const changes = !o.plan && toolName in WRITE_TOOL_PATHS;
18934
19166
  const changePath = () => {
18935
19167
  const field = WRITE_TOOL_PATHS[toolName];
18936
- return typeof d.updatedInput[field] === "string" ? (0, import_path17.relative)(o.root, d.updatedInput[field]) || String(d.updatedInput[field]) : "";
19168
+ return typeof d.updatedInput[field] === "string" ? (0, import_path18.relative)(o.root, d.updatedInput[field]) || String(d.updatedInput[field]) : "";
18937
19169
  };
18938
19170
  if (changes && protections.toolApproval) {
18939
19171
  const path = changePath(), askEdit = o.protection?.approver?.askEdit;
@@ -19010,15 +19242,15 @@ function timedGate(gate, took) {
19010
19242
  }
19011
19243
  async function hasLocalTranscript(configDir, sessionId) {
19012
19244
  if (!/^[A-Za-z0-9-]{8,80}$/.test(sessionId)) return false;
19013
- const projects = (0, import_path17.join)(configDir, "projects");
19014
- const dirs = await (0, import_promises16.readdir)(projects).catch(() => []);
19015
- return dirs.some((d) => (0, import_fs11.existsSync)((0, import_path17.join)(projects, d, `${sessionId}.jsonl`)));
19245
+ const projects = (0, import_path18.join)(configDir, "projects");
19246
+ const dirs = await (0, import_promises17.readdir)(projects).catch(() => []);
19247
+ return dirs.some((d) => (0, import_fs12.existsSync)((0, import_path18.join)(projects, d, `${sessionId}.jsonl`)));
19016
19248
  }
19017
19249
 
19018
19250
  // src/application/services/workspaceSandbox/selfUpdate.ts
19019
19251
  var import_crypto10 = require("crypto");
19020
- var import_fs12 = require("fs");
19021
- var import_path18 = require("path");
19252
+ var import_fs13 = require("fs");
19253
+ var import_path19 = require("path");
19022
19254
  var REGISTRY_LATEST = "https://registry.npmjs.org/@scalequality%2fcli/latest";
19023
19255
  var UPDATE_FIRST_CHECK_MS = 2 * 6e4;
19024
19256
  var UPDATE_INTERVAL_MS = 6 * 36e5;
@@ -19027,10 +19259,10 @@ var UPDATE_RETRY_MS = 15 * 6e4;
19027
19259
  var CONFIRM_AFTER_MS = 9e4;
19028
19260
  var RESTART_EXIT_CODE = 75;
19029
19261
  var MAX_START_ATTEMPTS = 3;
19030
- var cliDir = (home) => (0, import_path18.join)(sqHome(home), "cli");
19031
- var launcherPath = (home) => (0, import_path18.join)(cliDir(home), "launcher.mjs");
19032
- var currentPath = (home) => (0, import_path18.join)(cliDir(home), "current.json");
19033
- var autoUpdateOffPath = (home) => (0, import_path18.join)(cliDir(home), "auto-update-off");
19262
+ var cliDir = (home) => (0, import_path19.join)(sqHome(home), "cli");
19263
+ var launcherPath = (home) => (0, import_path19.join)(cliDir(home), "launcher.mjs");
19264
+ var currentPath = (home) => (0, import_path19.join)(cliDir(home), "current.json");
19265
+ var autoUpdateOffPath = (home) => (0, import_path19.join)(cliDir(home), "auto-update-off");
19034
19266
  var VERSION = /^(\d{1,5})\.(\d{1,5})\.(\d{1,5})$/;
19035
19267
  function isNewer(candidate, current) {
19036
19268
  const a = VERSION.exec(candidate), b = VERSION.exec(current);
@@ -19043,18 +19275,18 @@ function isNewer(candidate, current) {
19043
19275
  }
19044
19276
  function readJson2(file) {
19045
19277
  try {
19046
- const v = JSON.parse((0, import_fs12.readFileSync)(file, "utf8"));
19278
+ const v = JSON.parse((0, import_fs13.readFileSync)(file, "utf8"));
19047
19279
  return v && typeof v === "object" ? v : null;
19048
19280
  } catch {
19049
19281
  return null;
19050
19282
  }
19051
19283
  }
19052
19284
  function writeJsonAtomic(file, value) {
19053
- (0, import_fs12.mkdirSync)((0, import_path18.dirname)(file), { recursive: true, mode: 448 });
19285
+ (0, import_fs13.mkdirSync)((0, import_path19.dirname)(file), { recursive: true, mode: 448 });
19054
19286
  const tmp = `${file}.${process.pid}.tmp`;
19055
- (0, import_fs12.writeFileSync)(tmp, `${JSON.stringify(value, null, 2)}
19287
+ (0, import_fs13.writeFileSync)(tmp, `${JSON.stringify(value, null, 2)}
19056
19288
  `, { mode: 384 });
19057
- (0, import_fs12.renameSync)(tmp, file);
19289
+ (0, import_fs13.renameSync)(tmp, file);
19058
19290
  }
19059
19291
  var installed = (v) => {
19060
19292
  const r = v;
@@ -19110,8 +19342,8 @@ function installLauncher(home, copy) {
19110
19342
  writeJsonAtomic(currentPath(home), { version: copy.version, bin: copy.bin, previous: null, pending: false, attempts: 0, rejected: current?.rejected ?? [] });
19111
19343
  const file = launcherPath(home);
19112
19344
  const tmp = `${file}.${process.pid}.tmp`;
19113
- (0, import_fs12.writeFileSync)(tmp, launcherSource(copy.bin), { mode: 420 });
19114
- (0, import_fs12.renameSync)(tmp, file);
19345
+ (0, import_fs13.writeFileSync)(tmp, launcherSource(copy.bin), { mode: 420 });
19346
+ (0, import_fs13.renameSync)(tmp, file);
19115
19347
  return file;
19116
19348
  }
19117
19349
  function confirmCurrent(home, version) {
@@ -19123,17 +19355,17 @@ function confirmCurrent(home, version) {
19123
19355
  }
19124
19356
  function behindCurrent(home, version) {
19125
19357
  const current = readCurrent(home);
19126
- if (!current || current.pending || current.version === version || !isNewer(current.version, version) || !(0, import_fs12.existsSync)(current.bin)) return null;
19358
+ if (!current || current.pending || current.version === version || !isNewer(current.version, version) || !(0, import_fs13.existsSync)(current.bin)) return null;
19127
19359
  return current.version;
19128
19360
  }
19129
19361
  function autoUpdateEnabled(home, env) {
19130
- return env.SCALEQUALITY_NO_AUTO_UPDATE !== "1" && !(0, import_fs12.existsSync)(autoUpdateOffPath(home));
19362
+ return env.SCALEQUALITY_NO_AUTO_UPDATE !== "1" && !(0, import_fs13.existsSync)(autoUpdateOffPath(home));
19131
19363
  }
19132
19364
  function setAutoUpdate(home, on) {
19133
- if (on) (0, import_fs12.rmSync)(autoUpdateOffPath(home), { force: true });
19365
+ if (on) (0, import_fs13.rmSync)(autoUpdateOffPath(home), { force: true });
19134
19366
  else {
19135
- (0, import_fs12.mkdirSync)(cliDir(home), { recursive: true, mode: 448 });
19136
- (0, import_fs12.writeFileSync)(autoUpdateOffPath(home), `${(/* @__PURE__ */ new Date()).toISOString()}
19367
+ (0, import_fs13.mkdirSync)(cliDir(home), { recursive: true, mode: 448 });
19368
+ (0, import_fs13.writeFileSync)(autoUpdateOffPath(home), `${(/* @__PURE__ */ new Date()).toISOString()}
19137
19369
  `, { mode: 384 });
19138
19370
  }
19139
19371
  }
@@ -19147,20 +19379,20 @@ async function latestVersion(fetchImpl = fetch) {
19147
19379
  return null;
19148
19380
  }
19149
19381
  }
19150
- function npmCli(nodePath, exists = import_fs12.existsSync, resolve8 = realOrNull, pathEnv = process.env.PATH ?? "") {
19151
- const dir = (0, import_path18.dirname)(nodePath);
19382
+ function npmCli(nodePath, exists = import_fs13.existsSync, resolve8 = realOrNull, pathEnv = process.env.PATH ?? "") {
19383
+ const dir = (0, import_path19.dirname)(nodePath);
19152
19384
  const script = (p) => p && /npm-cli\.js$/.test(p) && exists(p) ? p : null;
19153
19385
  const linked = (p) => exists(p) ? script(resolve8(p)) : null;
19154
19386
  const layouts = [
19155
- (0, import_path18.join)(dir, "node_modules", "npm", "bin", "npm-cli.js"),
19156
- (0, import_path18.join)(dir, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js"),
19157
- (0, import_path18.join)(dir, "..", "libexec", "lib", "node_modules", "npm", "bin", "npm-cli.js")
19387
+ (0, import_path19.join)(dir, "node_modules", "npm", "bin", "npm-cli.js"),
19388
+ (0, import_path19.join)(dir, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js"),
19389
+ (0, import_path19.join)(dir, "..", "libexec", "lib", "node_modules", "npm", "bin", "npm-cli.js")
19158
19390
  ];
19159
- return linked((0, import_path18.join)(dir, "npm")) ?? layouts.map(script).find(Boolean) ?? pathEnv.split(import_path18.delimiter).filter(Boolean).map((d) => linked((0, import_path18.join)(d, "npm"))).find(Boolean) ?? null;
19391
+ return linked((0, import_path19.join)(dir, "npm")) ?? layouts.map(script).find(Boolean) ?? pathEnv.split(import_path19.delimiter).filter(Boolean).map((d) => linked((0, import_path19.join)(d, "npm"))).find(Boolean) ?? null;
19160
19392
  }
19161
19393
  function realOrNull(p) {
19162
19394
  try {
19163
- return (0, import_fs12.realpathSync)(p);
19395
+ return (0, import_fs13.realpathSync)(p);
19164
19396
  } catch {
19165
19397
  return null;
19166
19398
  }
@@ -19180,11 +19412,11 @@ function npmReason(output) {
19180
19412
  async function installVersion(o) {
19181
19413
  const npm = o.npm === void 0 ? npmCli(o.nodePath) : o.npm;
19182
19414
  if (!npm) throw new UpdateError("NPM_NOT_FOUND", `npm was not found next to ${o.nodePath}.`);
19183
- const staging = (0, import_path18.join)(cliDir(o.home), `.update-${o.version}`);
19184
- (0, import_fs12.rmSync)(staging, { recursive: true, force: true });
19185
- (0, import_fs12.mkdirSync)(staging, { recursive: true, mode: 448 });
19415
+ const staging = (0, import_path19.join)(cliDir(o.home), `.update-${o.version}`);
19416
+ (0, import_fs13.rmSync)(staging, { recursive: true, force: true });
19417
+ (0, import_fs13.mkdirSync)(staging, { recursive: true, mode: 448 });
19186
19418
  try {
19187
- (0, import_fs12.writeFileSync)((0, import_path18.join)(staging, "package.json"), '{ "private": true }\n');
19419
+ (0, import_fs13.writeFileSync)((0, import_path19.join)(staging, "package.json"), '{ "private": true }\n');
19188
19420
  const r = await o.run(o.nodePath, [
19189
19421
  npm,
19190
19422
  "install",
@@ -19199,12 +19431,12 @@ async function installVersion(o) {
19199
19431
  `@scalequality/cli@${o.version}`
19200
19432
  ]);
19201
19433
  if (r.code !== 0) throw new UpdateError("NPM_INSTALL_FAILED", `npm could not install @scalequality/cli@${o.version}: ${npmReason(`${r.stderr || r.stdout}`) || r.code}`);
19202
- const root = (0, import_path18.join)(staging, "node_modules", "@scalequality", "cli");
19203
- const pkg = readJson2((0, import_path18.join)(root, "package.json"));
19434
+ const root = (0, import_path19.join)(staging, "node_modules", "@scalequality", "cli");
19435
+ const pkg = readJson2((0, import_path19.join)(root, "package.json"));
19204
19436
  if (pkg?.name !== "@scalequality/cli" || pkg?.version !== o.version) throw new UpdateError("WRONG_PACKAGE", `npm installed ${String(pkg?.name)}@${String(pkg?.version)} instead of ${o.version}.`);
19205
- const build = readJson2((0, import_path18.join)(root, "dist", "connect.build.json"));
19206
- const bundle = (0, import_path18.join)(root, "dist", "connect.cjs");
19207
- const sha = (0, import_fs12.existsSync)(bundle) ? (0, import_crypto10.createHash)("sha256").update((0, import_fs12.readFileSync)(bundle)).digest("hex") : null;
19437
+ const build = readJson2((0, import_path19.join)(root, "dist", "connect.build.json"));
19438
+ const bundle = (0, import_path19.join)(root, "dist", "connect.cjs");
19439
+ const sha = (0, import_fs13.existsSync)(bundle) ? (0, import_crypto10.createHash)("sha256").update((0, import_fs13.readFileSync)(bundle)).digest("hex") : null;
19208
19440
  if (!sha || typeof build?.sha256 !== "string" || build.sha256 !== sha) throw new UpdateError("BUNDLE_MISMATCH", `The engine of ${o.version} does not match the sha256 it declares.`);
19209
19441
  let copy;
19210
19442
  try {
@@ -19214,7 +19446,7 @@ async function installVersion(o) {
19214
19446
  }
19215
19447
  return { version: copy.version, bin: copy.bin };
19216
19448
  } finally {
19217
- (0, import_fs12.rmSync)(staging, { recursive: true, force: true });
19449
+ (0, import_fs13.rmSync)(staging, { recursive: true, force: true });
19218
19450
  }
19219
19451
  }
19220
19452
  function stageVersion(home, next, running) {
@@ -19261,9 +19493,9 @@ var say = (line = "") => {
19261
19493
  var cliVersion = process.env.SCALEQUALITY_CLI_VERSION || "dev";
19262
19494
  var userAgent = (mode) => `scalequality-cli/${cliVersion} (${mode}; node ${process.versions.node}; ${process.platform})`;
19263
19495
  var HOME = (0, import_os7.homedir)();
19264
- var SQ_HOME = (0, import_path19.join)(HOME, ".scalequality");
19265
- var ENGINE_HOME = (0, import_path19.join)(SQ_HOME, "workspace");
19266
- var credentials = new CredentialStore((0, import_path19.join)(SQ_HOME, "credentials.json"));
19496
+ var SQ_HOME = (0, import_path20.join)(HOME, ".scalequality");
19497
+ var ENGINE_HOME = (0, import_path20.join)(SQ_HOME, "workspace");
19498
+ var credentials = new CredentialStore((0, import_path20.join)(SQ_HOME, "credentials.json"));
19267
19499
  function startFailure(e, api) {
19268
19500
  if (e instanceof NotLocalSessionError) return 'This code belongs to a cloud workspace session. In the AI Workspace, choose "Use a folder on your computer" to get a code for this command.';
19269
19501
  if (e instanceof SessionGoneError) {
@@ -19276,16 +19508,16 @@ function startFailure(e, api) {
19276
19508
  return "ScaleQuality could not start this session. Try again in a moment, or get a new code from the AI Workspace.";
19277
19509
  }
19278
19510
  function engineDirs() {
19279
- const configDir = (0, import_path19.join)(ENGINE_HOME, "claude-home");
19280
- const scratch = (0, import_path19.join)(ENGINE_HOME, "tmp");
19281
- (0, import_fs13.mkdirSync)(configDir, { recursive: true, mode: 448 });
19282
- (0, import_fs13.mkdirSync)(scratch, { recursive: true, mode: 448 });
19511
+ const configDir = (0, import_path20.join)(ENGINE_HOME, "claude-home");
19512
+ const scratch = (0, import_path20.join)(ENGINE_HOME, "tmp");
19513
+ (0, import_fs14.mkdirSync)(configDir, { recursive: true, mode: 448 });
19514
+ (0, import_fs14.mkdirSync)(scratch, { recursive: true, mode: 448 });
19283
19515
  return { configDir, scratch };
19284
19516
  }
19285
19517
  function createLocalEngine(o) {
19286
19518
  const { configDir, scratch } = engineDirs();
19287
- const sessions = (0, import_path19.join)(ENGINE_HOME, "sessions");
19288
- const stateDir = (0, import_path19.join)(sessions, o.sessionId);
19519
+ const sessions = (0, import_path20.join)(ENGINE_HOME, "sessions");
19520
+ const stateDir = (0, import_path20.join)(sessions, o.sessionId);
19289
19521
  void pruneSessionStates(sessions, stateDir).catch(() => void 0);
19290
19522
  const log = {
19291
19523
  info: (msg, ctx) => {
@@ -19588,7 +19820,7 @@ async function upMain(api, verbose, service) {
19588
19820
  let shuttingDown = false;
19589
19821
  let agent;
19590
19822
  const startSession = ({ sessionId, secret, root }) => {
19591
- const label = (0, import_path19.basename)(root);
19823
+ const label = (0, import_path20.basename)(root);
19592
19824
  const prefix = style.dim(`[${label}] `);
19593
19825
  const consoleLog = new ConsoleLog(style);
19594
19826
  let resolveDone = () => void 0;
@@ -19732,7 +19964,7 @@ function startSelfUpdate(api, busy, restart) {
19732
19964
  }
19733
19965
  async function addMain(api, path) {
19734
19966
  try {
19735
- const real = await addFolder(credentials, api, (0, import_path19.resolve)(path ?? process.cwd()), HOME);
19967
+ const real = await addFolder(credentials, api, (0, import_path20.resolve)(path ?? process.cwd()), HOME);
19736
19968
  say(style.green(`Added ${real}.`));
19737
19969
  const credential = credentials.get(api);
19738
19970
  const client = new MachineClient(api, { token: credential.machineToken, userAgent: userAgent("add") });