@scalequality/cli 0.4.31 → 0.4.33

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.
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "sdkVersion": "0.3.281",
3
- "sha256": "5abc2b162faedfd1883ea9e6e2c35a2e8f985547caf2bad4fb4cfdd27d965d71",
4
- "sourceCommit": "2d63196a4d5e04470ecb561004b9e956b1cf55fb"
3
+ "sha256": "9df603c14a8411fc0bd67b9845763888a736d40d91718e584e5cfcc692c0aaf1",
4
+ "sourceCommit": "ef04cd0080b6e3a35119bf03ac6128cd671b0f5d"
5
5
  }
package/dist/connect.cjs CHANGED
@@ -4425,6 +4425,24 @@ function checkpointPartsOf(raw) {
4425
4425
  var run = (0, import_util.promisify)(import_child_process.execFile);
4426
4426
  var CHECKPOINT_BASE_HEADER = "ScaleQuality-Base:";
4427
4427
  var DIFF_CAPS = { perFileBytes: 200 * 1024, totalBytes: 2 * 1024 * 1024, maxFiles: 500 };
4428
+ var DIFF_EVENT_BYTES = 448 * 1024;
4429
+ function fitDiff(files, budget = DIFF_EVENT_BYTES) {
4430
+ const bytes = (f) => Buffer.byteLength(JSON.stringify(f)) + 1;
4431
+ const sizes = files.map(bytes);
4432
+ let total = sizes.reduce((a, b) => a + b, 2);
4433
+ if (total <= budget) return files;
4434
+ const out2 = [...files];
4435
+ const largest = out2.map((_, i) => i).filter((i) => out2[i].patch).sort((a, b) => sizes[b] - sizes[a]);
4436
+ for (const i of largest) {
4437
+ const { hunks: _h, ...rest } = out2[i];
4438
+ out2[i] = { ...rest, patch: "", truncated: true };
4439
+ const size2 = bytes(out2[i]);
4440
+ total -= sizes[i] - size2;
4441
+ sizes[i] = size2;
4442
+ if (total <= budget) break;
4443
+ }
4444
+ return out2;
4445
+ }
4428
4446
  async function git(args, opts) {
4429
4447
  const { stdout } = await run("git", args, {
4430
4448
  cwd: opts.cwd,
@@ -5803,7 +5821,7 @@ var HttpSessionTransport = class {
5803
5821
  const raw = await this.post("/command-approvals", body, this.opts.requestTimeoutMs ?? 3e4);
5804
5822
  const approvalId = typeof raw?.approvalId === "string" ? raw.approvalId : "";
5805
5823
  if (!approvalId) throw new TransportError("invalid command approval response", 502, false);
5806
- return { approvalId };
5824
+ return { approvalId, ...raw?.approved === true ? { approved: true } : {} };
5807
5825
  }
5808
5826
  async cancelCommandApproval(approvalId, reason) {
5809
5827
  await this.post(`/command-approvals/${encodeURIComponent(approvalId)}/cancel`, { reason }, this.opts.requestTimeoutMs ?? 3e4);
@@ -6785,6 +6803,8 @@ var CommandDecisions = class {
6785
6803
  });
6786
6804
  }
6787
6805
  };
6806
+ var MAX_CARD_COMMAND = 1e5;
6807
+ var TOO_LONG_FOR_A_CARD = (length, max) => `This command is ${length.toLocaleString("en-US")} characters, more than the ${max.toLocaleString("en-US")} an approval card takes, so it did not run. Write long content to files with the Write tool, then run a short command that uses them.`;
6788
6808
  var CommandApprovalError = class extends Error {
6789
6809
  constructor(status, code) {
6790
6810
  super(`command approval ${status ?? "unreachable"}${code ? ` ${code}` : ""}`);
@@ -6876,6 +6896,7 @@ var BrowserCommandGate = class {
6876
6896
  }
6877
6897
  async ask(command, opts) {
6878
6898
  const protection = opts.protection;
6899
+ if (command.length > MAX_CARD_COMMAND) return { allow: false, message: TOO_LONG_FOR_A_CARD(command.length, MAX_CARD_COMMAND) };
6879
6900
  if (!opts.edit && !protection && matchingRule(command, this.allRules())) return { allow: true };
6880
6901
  if (opts.signal?.aborted) return { allow: false, message: STOPPED };
6881
6902
  let approvalId;
@@ -6893,6 +6914,7 @@ var BrowserCommandGate = class {
6893
6914
  } catch (e) {
6894
6915
  this.o.log?.(`command approval could not be requested: ${e.message}`);
6895
6916
  const code = e instanceof CommandApprovalError ? e.code : null;
6917
+ if (e instanceof CommandApprovalError && e.status === 400 && command.length > 1e4) return { allow: false, message: TOO_LONG_FOR_A_CARD(command.length, 1e4) };
6896
6918
  if (protection && opts.edit) return { allow: false, message: PROTECTION_MESSAGES.editUnavailable(opts.edit.path) };
6897
6919
  if (protection && code !== "COMMAND_NOT_ALLOWED") return { allow: false, message: PROTECTION_MESSAGES.unavailable };
6898
6920
  return {
@@ -7858,6 +7880,9 @@ var HELLO_MS = 5e3;
7858
7880
  var MAX_TABS = 8;
7859
7881
  var MAX_INPUT = 64 * 1024;
7860
7882
  var MAX_TOKENS = 64;
7883
+ var MAX_PENDING = 1024 * 1024;
7884
+ var CATCH_UP_MS = 250;
7885
+ var STOP_WAIT_MS = 2e3;
7861
7886
  function loadPty() {
7862
7887
  try {
7863
7888
  const mod = require("@lydell/node-pty");
@@ -7906,6 +7931,8 @@ var TerminalHost = class {
7906
7931
  tabs = /* @__PURE__ */ new Map();
7907
7932
  /** When the person last typed in any tab (the cloud counts it as activity, so the machine does not idle away). */
7908
7933
  lastInputAt = 0;
7934
+ /** When a shell last wrote: a long build or test run with no typing is still the person's work in progress. */
7935
+ lastOutputAt = 0;
7909
7936
  get open() {
7910
7937
  return this.tabs.size;
7911
7938
  }
@@ -7951,32 +7978,12 @@ var TerminalHost = class {
7951
7978
  if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(m));
7952
7979
  };
7953
7980
  socket.on("message", (raw) => {
7954
- const m = parse(raw);
7955
- if (!m) return;
7956
- if (!tab) {
7957
- if (m.t !== "hello") return;
7958
- clearTimeout(hello);
7959
- if (!this.known(m.token)) {
7960
- socket.close(4401, "token");
7961
- return;
7962
- }
7963
- if (!TAB_ID.test(m.tab)) {
7964
- socket.close(4400, "tab");
7965
- return;
7966
- }
7967
- tab = this.attach(m.tab, socket, size(m.cols, 80, 500), size(m.rows, 24, 200), send);
7968
- return;
7969
- }
7970
- if (m.t === "in") {
7971
- this.lastInputAt = (this.o.now ?? Date.now)();
7972
- tab.pty.write(m.d.slice(0, MAX_INPUT));
7973
- } else if (m.t === "resize") {
7974
- try {
7975
- tab.pty.resize(size(m.cols, 80, 500), size(m.rows, 24, 200));
7976
- } catch {
7977
- }
7978
- } else if (m.t === "close") {
7979
- this.end(tab.id);
7981
+ try {
7982
+ this.received(raw, socket, () => tab, (t) => {
7983
+ tab = t;
7984
+ }, hello, send);
7985
+ } catch (e) {
7986
+ this.o.log.warn("terminal message not handled", { error: e.message });
7980
7987
  }
7981
7988
  });
7982
7989
  socket.on("close", () => {
@@ -7985,6 +7992,37 @@ var TerminalHost = class {
7985
7992
  });
7986
7993
  socket.on("error", () => void 0);
7987
7994
  }
7995
+ /** One message of a page: the hello first (its token, its tab), then what it types, its size, or the tab's end. */
7996
+ received(raw, socket, current, set, hello, send) {
7997
+ const m = parse(raw);
7998
+ if (!m) return;
7999
+ const tab = current();
8000
+ if (!tab) {
8001
+ if (m.t !== "hello") return;
8002
+ clearTimeout(hello);
8003
+ if (!this.known(m.token)) {
8004
+ socket.close(4401, "token");
8005
+ return;
8006
+ }
8007
+ if (!TAB_ID.test(m.tab)) {
8008
+ socket.close(4400, "tab");
8009
+ return;
8010
+ }
8011
+ set(this.attach(m.tab, socket, size(m.cols, 80, 500), size(m.rows, 24, 200), send));
8012
+ return;
8013
+ }
8014
+ if (m.t === "in") {
8015
+ this.lastInputAt = (this.o.now ?? Date.now)();
8016
+ tab.pty.write(m.d.slice(0, MAX_INPUT));
8017
+ } else if (m.t === "resize") {
8018
+ try {
8019
+ tab.pty.resize(size(m.cols, 80, 500), size(m.rows, 24, 200));
8020
+ } catch {
8021
+ }
8022
+ } else if (m.t === "close") {
8023
+ this.end(tab.id);
8024
+ }
8025
+ }
7988
8026
  /** The tab this page opens: its shell again (the screen it had, then what comes), or a new shell. */
7989
8027
  attach(id, socket, cols, rows, send) {
7990
8028
  const existing = this.tabs.get(id);
@@ -8020,24 +8058,63 @@ var TerminalHost = class {
8020
8058
  socket.close(4500, "start");
8021
8059
  return null;
8022
8060
  }
8023
- const tab = { id, shell, pty, buffer: "", socket, detachTimer: null };
8061
+ const tab = { id, shell, pty, buffer: "", socket, detachTimer: null, behind: null };
8024
8062
  this.tabs.set(id, tab);
8025
8063
  pty.onData((d) => {
8026
- tab.buffer = (tab.buffer + d).slice(-MAX_BUFFER);
8027
- if (tab.socket?.readyState === tab.socket?.OPEN) tab.socket.send(JSON.stringify({ t: "out", d }));
8064
+ try {
8065
+ tab.buffer = (tab.buffer + d).slice(-MAX_BUFFER);
8066
+ this.lastOutputAt = (this.o.now ?? Date.now)();
8067
+ const s = tab.socket;
8068
+ if (!s || s.readyState !== s.OPEN || tab.behind) return;
8069
+ if (s.bufferedAmount > MAX_PENDING) {
8070
+ this.catchUp(tab, s);
8071
+ return;
8072
+ }
8073
+ s.send(JSON.stringify({ t: "out", d }));
8074
+ } catch (e) {
8075
+ this.o.log.warn("terminal output not sent", { error: e.message });
8076
+ }
8028
8077
  });
8029
8078
  pty.onExit(({ exitCode }) => {
8030
- if (tab.socket?.readyState === tab.socket?.OPEN) {
8031
- tab.socket.send(JSON.stringify({ t: "exit", code: exitCode }));
8032
- tab.socket.close(1e3, "exited");
8079
+ try {
8080
+ const s = tab.socket;
8081
+ if (s && s.readyState === s.OPEN) {
8082
+ s.send(JSON.stringify({ t: "exit", code: exitCode }));
8083
+ s.close(1e3, "exited");
8084
+ }
8085
+ if (this.tabs.get(id) === tab) this.tabs.delete(id);
8086
+ if (tab.detachTimer) clearTimeout(tab.detachTimer);
8087
+ } catch (e) {
8088
+ this.o.log.warn("terminal exit not sent", { error: e.message });
8033
8089
  }
8034
- if (this.tabs.get(id) === tab) this.tabs.delete(id);
8035
- if (tab.detachTimer) clearTimeout(tab.detachTimer);
8036
8090
  });
8037
8091
  send({ t: "ready", tab: id, shell, replay: "" });
8038
8092
  return tab;
8039
8093
  }
8094
+ /** A socket that fell behind: once it drains, the page's screen is reset and drawn again from the tab's own screen. */
8095
+ catchUp(tab, socket) {
8096
+ const check = () => {
8097
+ tab.behind = null;
8098
+ try {
8099
+ if (tab.socket !== socket || socket.readyState !== socket.OPEN) return;
8100
+ if (socket.bufferedAmount > MAX_PENDING / 4) {
8101
+ tab.behind = setTimeout(check, CATCH_UP_MS);
8102
+ tab.behind.unref?.();
8103
+ return;
8104
+ }
8105
+ socket.send(JSON.stringify({ t: "out", d: `\x1Bc${tab.buffer}` }));
8106
+ } catch (e) {
8107
+ this.o.log.warn("terminal output not sent", { error: e.message });
8108
+ }
8109
+ };
8110
+ tab.behind = setTimeout(check, CATCH_UP_MS);
8111
+ tab.behind.unref?.();
8112
+ }
8040
8113
  detach(tab) {
8114
+ if (tab.behind) {
8115
+ clearTimeout(tab.behind);
8116
+ tab.behind = null;
8117
+ }
8041
8118
  tab.socket = null;
8042
8119
  if (tab.detachTimer) clearTimeout(tab.detachTimer);
8043
8120
  tab.detachTimer = setTimeout(() => this.end(tab.id), DETACH_MS);
@@ -8049,6 +8126,7 @@ var TerminalHost = class {
8049
8126
  if (!tab) return;
8050
8127
  this.tabs.delete(id);
8051
8128
  if (tab.detachTimer) clearTimeout(tab.detachTimer);
8129
+ if (tab.behind) clearTimeout(tab.behind);
8052
8130
  try {
8053
8131
  tab.pty.kill();
8054
8132
  } catch {
@@ -8064,7 +8142,10 @@ var TerminalHost = class {
8064
8142
  this.port = null;
8065
8143
  for (const client of wss?.clients ?? []) client.terminate();
8066
8144
  wss?.close();
8067
- if (server) await new Promise((resolve8) => server.close(() => resolve8()));
8145
+ if (!server) return;
8146
+ const closed = new Promise((resolve8) => server.close(() => resolve8()));
8147
+ server.closeAllConnections?.();
8148
+ await Promise.race([closed, new Promise((resolve8) => setTimeout(resolve8, STOP_WAIT_MS).unref?.())]);
8068
8149
  }
8069
8150
  };
8070
8151
 
@@ -8937,8 +9018,11 @@ function sandboxTestEnv() {
8937
9018
  var ApprovalBroker = class {
8938
9019
  waiting = /* @__PURE__ */ new Map();
8939
9020
  early = /* @__PURE__ */ new Map();
9021
+ /** Decisions already known from the request's answer: their copy on the poll is dropped, never kept. */
9022
+ settled = /* @__PURE__ */ new Set();
8940
9023
  /** True when a call was waiting for this decision (it returns now); false when it is kept for a later wait. */
8941
9024
  resolve(approvalId, decision) {
9025
+ if (this.settled.delete(approvalId)) return false;
8942
9026
  const w = this.waiting.get(approvalId);
8943
9027
  if (w) {
8944
9028
  this.waiting.delete(approvalId);
@@ -8967,6 +9051,12 @@ var ApprovalBroker = class {
8967
9051
  });
8968
9052
  });
8969
9053
  }
9054
+ /** The API answered this approval with the request itself: its decision arriving on the poll later is dropped. */
9055
+ settle(approvalId) {
9056
+ if (this.early.delete(approvalId)) return;
9057
+ this.settled.add(approvalId);
9058
+ while (this.settled.size > 500) this.settled.delete(this.settled.values().next().value);
9059
+ }
8970
9060
  get pending() {
8971
9061
  return this.waiting.size;
8972
9062
  }
@@ -9004,6 +9094,7 @@ function chromeCandidates(env = process.env, platform2 = process.platform) {
9004
9094
  }
9005
9095
  return [...own, "/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/snap/bin/chromium"];
9006
9096
  }
9097
+ var chromeSandboxArgs = (uid = process.getuid?.()) => uid === 0 ? ["--no-sandbox"] : [];
9007
9098
  function findChrome(candidates = chromeCandidates()) {
9008
9099
  return candidates.find((path) => (0, import_fs8.existsSync)(path)) ?? null;
9009
9100
  }
@@ -9014,7 +9105,7 @@ async function screenshotPage(chrome, url, target, size2) {
9014
9105
  (0, import_child_process3.execFile)(chrome, [
9015
9106
  "--headless=new",
9016
9107
  "--disable-gpu",
9017
- "--no-sandbox",
9108
+ ...chromeSandboxArgs(),
9018
9109
  "--disable-dev-shm-usage",
9019
9110
  "--hide-scrollbars",
9020
9111
  "--no-first-run",
@@ -13167,48 +13258,58 @@ function readReport(dom) {
13167
13258
  var run2 = (chrome, args, timeoutMs) => new Promise((resolve8, reject) => {
13168
13259
  (0, import_child_process4.execFile)(chrome, args, { timeout: timeoutMs, windowsHide: true, maxBuffer: 32 * 1024 * 1024 }, (error, stdout) => error ? reject(error) : resolve8(String(stdout)));
13169
13260
  });
13261
+ var SCREENS_AT_ONCE = 3;
13170
13262
  async function checkDesign(chrome, folder, manifest, opts = {}) {
13171
13263
  const runner = opts.runner ?? run2;
13172
13264
  const work = await (0, import_promises10.mkdtemp)((0, import_path10.join)((0, import_os5.tmpdir)(), "sq-design-"));
13173
- const out2 = [];
13174
- try {
13175
- for (const [i, b] of manifest.boards.entries()) {
13176
- const page = (0, import_path10.join)(work, `screen-${i}.html`);
13177
- await (0, import_promises10.writeFile)(page, checkedPage(await (0, import_promises10.readFile)((0, import_path10.join)(folder, b.file), "utf8"), folder));
13178
- const url = (0, import_url.pathToFileURL)(page).href;
13179
- const base = [
13180
- "--headless=new",
13181
- "--disable-gpu",
13182
- "--no-sandbox",
13183
- "--disable-dev-shm-usage",
13184
- "--hide-scrollbars",
13185
- "--no-first-run",
13186
- "--no-default-browser-check",
13187
- `--user-data-dir=${(0, import_path10.join)(work, `profile-${i}`)}`,
13188
- `--window-size=${b.width},${b.height}`,
13189
- "--virtual-time-budget=6000"
13190
- ];
13191
- const check = { file: b.file, title: b.title, errors: [], contrast: [], overflow: false, unread: true };
13265
+ const one = async (b, i) => {
13266
+ const page = (0, import_path10.join)(work, `screen-${i}.html`);
13267
+ await (0, import_promises10.writeFile)(page, checkedPage(await (0, import_promises10.readFile)((0, import_path10.join)(folder, b.file), "utf8"), folder));
13268
+ const url = (0, import_url.pathToFileURL)(page).href;
13269
+ const base = (profile) => [
13270
+ "--headless=new",
13271
+ "--disable-gpu",
13272
+ ...chromeSandboxArgs(),
13273
+ "--disable-dev-shm-usage",
13274
+ "--hide-scrollbars",
13275
+ "--no-first-run",
13276
+ "--no-default-browser-check",
13277
+ `--user-data-dir=${(0, import_path10.join)(work, profile)}`,
13278
+ `--window-size=${b.width},${b.height}`,
13279
+ "--virtual-time-budget=6000"
13280
+ ];
13281
+ const check = { file: b.file, title: b.title, errors: [], contrast: [], overflow: false, unread: true };
13282
+ const measured = (async () => {
13192
13283
  try {
13193
- const report = readReport(await runner(chrome, [...base, "--dump-dom", url], 45e3));
13284
+ const report = readReport(await runner(chrome, [...base(`profile-${i}-dom`), "--dump-dom", url], 45e3));
13194
13285
  if (report) Object.assign(check, report, { unread: false });
13195
13286
  } catch {
13196
13287
  }
13197
- if (i < MAX_PICTURES) {
13198
- const shot = (0, import_path10.join)(work, `screen-${i}.png`);
13199
- try {
13200
- await runner(chrome, [...base, `--screenshot=${shot}`, url], 45e3);
13201
- const png = await (0, import_promises10.readFile)(shot);
13202
- if (png.length) check.picture = png.toString("base64");
13203
- } catch {
13204
- }
13288
+ })();
13289
+ const pictured = (async () => {
13290
+ if (i >= MAX_PICTURES) return;
13291
+ const shot = (0, import_path10.join)(work, `screen-${i}.png`);
13292
+ try {
13293
+ await runner(chrome, [...base(`profile-${i}-shot`), `--screenshot=${shot}`, url], 45e3);
13294
+ const png = await (0, import_promises10.readFile)(shot);
13295
+ if (png.length) check.picture = png.toString("base64");
13296
+ } catch {
13205
13297
  }
13206
- out2.push(check);
13207
- }
13298
+ })();
13299
+ await Promise.all([measured, pictured]);
13300
+ return check;
13301
+ };
13302
+ try {
13303
+ const out2 = new Array(manifest.boards.length);
13304
+ let next = 0;
13305
+ const lane = async () => {
13306
+ for (let i = next++; i < manifest.boards.length; i = next++) out2[i] = await one(manifest.boards[i], i);
13307
+ };
13308
+ await Promise.all(Array.from({ length: Math.min(SCREENS_AT_ONCE, manifest.boards.length) }, lane));
13309
+ return out2;
13208
13310
  } finally {
13209
13311
  await (0, import_promises10.rm)(work, { recursive: true, force: true }).catch(() => void 0);
13210
13312
  }
13211
- return out2;
13212
13313
  }
13213
13314
  function designSummary(checks) {
13214
13315
  return {
@@ -13469,7 +13570,16 @@ var EventSink = class {
13469
13570
  for (let i = 0; i < batch.length; i += max) {
13470
13571
  const part = batch.slice(i, i + max);
13471
13572
  this.chain = this.chain.then(
13472
- () => this.opts.post(part).catch((err) => {
13573
+ () => this.opts.post(part).catch(async (err) => {
13574
+ if (part.length > 1 && err.status === 400) {
13575
+ for (const e of part) {
13576
+ await this.opts.post([e]).catch((one) => {
13577
+ this.dropped += 1;
13578
+ this.opts.log?.("workspace event not delivered", { type: e.type, totalDropped: this.dropped, error: one.message });
13579
+ });
13580
+ }
13581
+ return;
13582
+ }
13473
13583
  this.dropped += part.length;
13474
13584
  this.opts.log?.("workspace events not delivered", { count: part.length, totalDropped: this.dropped, error: err.message });
13475
13585
  })
@@ -13837,7 +13947,7 @@ var SdkEventMapper = class {
13837
13947
  switch (m.type) {
13838
13948
  case "system":
13839
13949
  if (m.subtype === "init") {
13840
- if (typeof m.session_id === "string") this.cb.sessionId(m.session_id);
13950
+ if (typeof m.session_id === "string" && m.session_id) this.cb.sessionId(m.session_id);
13841
13951
  if (typeof m.model === "string" && m.model) this.model = m.model;
13842
13952
  } else if (m.subtype === "compact_boundary") {
13843
13953
  const meta = m.compact_metadata ?? {};
@@ -14429,8 +14539,9 @@ function cloudProtectionApprover(o) {
14429
14539
  const edit = check.edit;
14430
14540
  if (check.signal?.aborted) return { allow: false, message: edit ? PROTECTION_MESSAGES.editStopped : PROTECTION_MESSAGES.stopped };
14431
14541
  let approvalId;
14542
+ let approved = false;
14432
14543
  try {
14433
- ({ approvalId } = await o.calls.requestCommandApproval({
14544
+ ({ approvalId, approved = false } = await o.calls.requestCommandApproval({
14434
14545
  command,
14435
14546
  cwd: o.cwd,
14436
14547
  ...check.description ? { description: check.description.slice(0, 1e3) } : {},
@@ -14443,6 +14554,10 @@ function cloudProtectionApprover(o) {
14443
14554
  o.log?.(`protection approval could not be requested: ${e.message}`);
14444
14555
  return { allow: false, message: edit ? PROTECTION_MESSAGES.editUnavailable(edit.path) : PROTECTION_MESSAGES.unavailable };
14445
14556
  }
14557
+ if (approved) {
14558
+ o.broker.settle(approvalId);
14559
+ return { allow: true };
14560
+ }
14446
14561
  const timeoutMs = o.timeoutMs ?? COMMAND_APPROVAL_TIMEOUT_MS;
14447
14562
  const timer = new AbortController();
14448
14563
  const t = setTimeout(() => timer.abort(), timeoutMs);
@@ -15314,6 +15429,7 @@ ${lines2.join("\n")}
15314
15429
  var WARM_IDLE_MS = 15 * 6e4;
15315
15430
  var TERMINAL_PULSE_MS = 4 * 6e4;
15316
15431
  var TERMINAL_IDLE_MS = 20 * 6e4;
15432
+ var TERMINAL_SHARE_WAIT_MS = 3e3;
15317
15433
  var TERMINAL_LOCAL_ENV = ["SSH_AUTH_SOCK", "EDITOR", "VISUAL", "PAGER", "LC_CTYPE"];
15318
15434
  function localLoginShell() {
15319
15435
  if (process.platform === "win32") return process.env.COMSPEC || "powershell.exe";
@@ -15543,6 +15659,8 @@ var WorkspaceEngine = class {
15543
15659
  orgPlugins = { entries: [], dirs: [] };
15544
15660
  /** The conversation's name was asked for (once, on its first turn). */
15545
15661
  titled = false;
15662
+ /** The first message, named once the model has started answering it (two calls at once slowed the first answer). */
15663
+ titleWaiting = null;
15546
15664
  /** The project environment's setup, once per open repository (cloud only), and why the last one failed. */
15547
15665
  envSetups = /* @__PURE__ */ new Map();
15548
15666
  envAbort = new AbortController();
@@ -16153,14 +16271,15 @@ var WorkspaceEngine = class {
16153
16271
  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");
16154
16272
  this.terminalShared.add(root);
16155
16273
  }
16156
- for (const name of await (0, import_promises16.readdir)(root).catch(() => [])) {
16274
+ const sweep = Promise.all((await (0, import_promises16.readdir)(root).catch(() => [])).map(async (name) => {
16157
16275
  const path = (0, import_path17.join)(root, name);
16158
- if (this.terminalShared.has(path) || own.has(path) || [...own].some((d) => d.startsWith(path + import_path17.sep))) continue;
16276
+ if (this.terminalShared.has(path) || own.has(path) || [...own].some((d) => d.startsWith(path + import_path17.sep))) return;
16159
16277
  if (await acl(["-R", "-m", `u:${uid}:rwX`, "-m", `d:u:${uid}:rwX`, path])) this.terminalShared.add(path);
16160
- }
16278
+ }));
16279
+ await Promise.race([sweep, new Promise((r) => setTimeout(r, TERMINAL_SHARE_WAIT_MS).unref?.())]);
16161
16280
  }
16162
16281
  /**
16163
- * While a terminal is open on the person's computer, or typed into in the last minutes in the cloud, the session
16282
+ * While a terminal is open on the person's computer, or typed into (or writing) in the last minutes in the cloud, the session
16164
16283
  * is in use: a small event every few minutes keeps it from going idle (the cloud machine, so it does not stop
16165
16284
  * under the person's hands; the computer, so its shells live as long as they are open).
16166
16285
  */
@@ -16169,7 +16288,7 @@ var WorkspaceEngine = class {
16169
16288
  this.terminalPulse = setInterval(() => {
16170
16289
  const t = this.terminal;
16171
16290
  if (!t || !t.open) return;
16172
- if (!this.local && Date.now() - t.lastInputAt > TERMINAL_IDLE_MS) return;
16291
+ if (!this.local && Date.now() - Math.max(t.lastInputAt, t.lastOutputAt) > TERMINAL_IDLE_MS) return;
16173
16292
  this.emit({ type: "terminal_activity", data: { open: t.open } });
16174
16293
  }, TERMINAL_PULSE_MS);
16175
16294
  this.terminalPulse.unref?.();
@@ -16188,10 +16307,12 @@ var WorkspaceEngine = class {
16188
16307
  repo2 = [...this.repos.values()][0];
16189
16308
  }
16190
16309
  const denied = this.deps.privateDirs ?? [];
16191
- const path = typeof p.path === "string" ? p.path : "";
16310
+ const bases = [repo2?.fence ?? repo2?.root ?? this.deps.root];
16311
+ const asked = typeof p.path === "string" ? p.path : "";
16312
+ const path = kind === "read_file" && p.as !== "image" ? await insideRelative(asked, bases) : asked;
16192
16313
  const range = { from: typeof p.from === "number" ? p.from : void 0, to: typeof p.to === "number" ? p.to : void 0 };
16193
16314
  if (kind === "read_file" && p.as === "image") {
16194
- const rel = await insideRelative(path, [repo2?.root ?? this.deps.root]);
16315
+ const rel = await insideRelative(path, bases);
16195
16316
  const image = await this.fencedFiles(repo2, rel, (root, r) => readImageFile(root, r, denied));
16196
16317
  const { data, ...meta } = image;
16197
16318
  await this.deps.transport.reply(commandId, { ok: true, result: { ...repoFullName ? { repoFullName } : {}, ...this.redactor.deep(meta), data } }).catch((e) => this.deps.log.warn("file request not answered", { error: e.message }));
@@ -16460,6 +16581,12 @@ ${String(item.content)}` : String(item.content);
16460
16581
  * A short name for a new conversation, from its first message: one small request to the session's fast model on
16461
16582
  * the gateway (measured like every other). Anything that fails leaves the conversation as it was.
16462
16583
  */
16584
+ /** Names the conversation from its first message now (the model answered it, or the turn ended without an answer). */
16585
+ nameNow() {
16586
+ const content = this.titleWaiting;
16587
+ this.titleWaiting = null;
16588
+ if (content !== null) void this.nameConversation(content);
16589
+ }
16463
16590
  async nameConversation(content) {
16464
16591
  const runtime = this.boot?.runtime;
16465
16592
  const model = runtime?.titleModel || runtime?.fastModel || runtime?.primaryModel || this.boot?.model;
@@ -16634,7 +16761,7 @@ ${String(item.content)}` : String(item.content);
16634
16761
  if (files === "unavailable") this.error("REWIND_FAILED", { turnId });
16635
16762
  this.emit({ type: "rewind", data: { turnId, files, conversation, ...untouched.length ? { untouched } : {} } });
16636
16763
  await this.diffNow();
16637
- await this.saveCheckpoint().catch((e) => this.deps.log.warn("checkpoint failed", { error: this.redactor.text(e.message) }));
16764
+ await this.saveCheckpoint().catch((e) => this.deps.log.warn("checkpoint failed", this.whyFailed(e)));
16638
16765
  this.setState("READY", "REWOUND");
16639
16766
  await this.sink.flush();
16640
16767
  }
@@ -16932,6 +17059,9 @@ ${json}
16932
17059
  return out2;
16933
17060
  }
16934
17061
  /** Starts the setup of each open repository that has one and did not run it yet. */
17062
+ setupToStart() {
17063
+ return [...this.repos.values()].some((repo2) => !repo2.dormant && !this.envSetups.has(repo2.root) && !!this.environmentOf(repo2)?.setupCommand);
17064
+ }
16935
17065
  startEnvSetups() {
16936
17066
  for (const repo2 of this.repos.values()) {
16937
17067
  if (repo2.dormant || this.envSetups.has(repo2.root)) continue;
@@ -17022,7 +17152,7 @@ ${json}
17022
17152
  this.toolGate = saved;
17023
17153
  if (!compact) {
17024
17154
  await this.refreshSkills();
17025
- if (!this.local) await saved;
17155
+ if (!this.local && this.setupToStart()) await saved;
17026
17156
  this.startEnvSetups();
17027
17157
  await Promise.all(this.envSetups.values());
17028
17158
  }
@@ -17035,7 +17165,7 @@ ${json}
17035
17165
  const sdk = this.sdk;
17036
17166
  if (!compact && !this.sdkSessionId && !this.titled) {
17037
17167
  this.titled = true;
17038
- void this.nameConversation(String(payload.content));
17168
+ this.titleWaiting = String(payload.content);
17039
17169
  }
17040
17170
  const primary = boot.runtime.primaryModel || (!this.deps.transport.refreshRuntime && typeof payload.model === "string" && payload.model ? payload.model : boot.model);
17041
17171
  if (isReasoningLevel(payload.reasoning)) this.reasoningLevel = effectiveReasoning(payload.reasoning, this.reasoningCapability);
@@ -17238,6 +17368,7 @@ ${text3}`;
17238
17368
  }
17239
17369
  } finally {
17240
17370
  const stopped = ac.signal.aborted || live.interrupted;
17371
+ this.nameNow();
17241
17372
  await saved;
17242
17373
  live.timing.end(this.deps.log, stopped ? "stopped" : "failed");
17243
17374
  this.live = null;
@@ -17247,7 +17378,7 @@ ${text3}`;
17247
17378
  this.turnWatch = null;
17248
17379
  this.previousTrouble = stopped || !watch ? null : watch.errored ? "follows a request that ended with an error" : watch.lastExit !== null && watch.lastExit !== 0 ? "follows a failed verification" : null;
17249
17380
  await this.diffNow();
17250
- await this.saveCheckpoint().catch((e) => this.deps.log.warn("checkpoint failed", { error: this.redactor.text(e.message) }));
17381
+ await this.saveCheckpoint().catch((e) => this.deps.log.warn("checkpoint failed", this.whyFailed(e)));
17251
17382
  await this.saveDesignVersions();
17252
17383
  this.setState("READY", stopped ? "STOPPED" : void 0);
17253
17384
  await this.sink.flush();
@@ -17261,6 +17392,7 @@ ${text3}`;
17261
17392
  }
17262
17393
  /** What a frame of the main conversation says about the turn: its model calls, foreground work, and the messages it read. */
17263
17394
  observeFrame(live, f) {
17395
+ if ((f.type === "stream_event" || f.type === "assistant") && this.titleWaiting !== null) this.nameNow();
17264
17396
  if (f.type === "stream_event") {
17265
17397
  live.timing.modelEvent();
17266
17398
  const ev = f.event ?? {};
@@ -17617,7 +17749,7 @@ ${text3}`;
17617
17749
  for (const repo2 of [...this.repos.values()]) {
17618
17750
  if (repo2.dormant) continue;
17619
17751
  try {
17620
- const files = await repo2.tracker.diff();
17752
+ const files = fitDiff(await repo2.tracker.diff());
17621
17753
  const id = repo2.repoFullName ?? repo2.localId ?? null;
17622
17754
  const key = JSON.stringify([id, files]);
17623
17755
  if (key === repo2.lastDiff) continue;
@@ -17691,6 +17823,11 @@ ${patch}`;
17691
17823
  get busy() {
17692
17824
  return !!this.turnRunning;
17693
17825
  }
17826
+ /** A failed call as the log keeps it: the API's code and status with the message, never a credential. */
17827
+ whyFailed(e) {
17828
+ const t = e;
17829
+ return { error: this.redactor.text(String(t?.message ?? e)), ...typeof t?.code === "string" ? { code: t.code } : {}, ...typeof t?.status === "number" ? { status: t.status } : {} };
17830
+ }
17694
17831
  /**
17695
17832
  * Stops the engine. A clean stop (asked by the API, the person's Ctrl+C or
17696
17833
  * the computer's service) saves the change and says PAUSED, so the session
@@ -17710,9 +17847,13 @@ ${patch}`;
17710
17847
  const running = this.turnRunning;
17711
17848
  if (running) await Promise.race([running, new Promise((r) => setTimeout(r, 2e4))]);
17712
17849
  if (opts.checkpoint) {
17713
- await this.saveCheckpoint().catch((e) => {
17714
- this.deps.log.warn("checkpoint failed", { error: this.redactor.text(e.message) });
17715
- });
17850
+ for (let attempt = 1; ; attempt++) {
17851
+ const failed2 = await this.saveCheckpoint().then(() => null, (e) => e);
17852
+ if (!failed2) break;
17853
+ this.deps.log.warn("checkpoint failed", { ...this.whyFailed(failed2), attempt });
17854
+ if (attempt >= 3 || failed2.retryable !== true) break;
17855
+ await new Promise((r) => setTimeout(r, attempt * 1e3));
17856
+ }
17716
17857
  }
17717
17858
  if (reason === "shutdown" && this.state && this.state !== "FAILED") this.setState("PAUSED", pausedCode);
17718
17859
  await this.sink.flush();
@@ -17870,8 +18011,7 @@ ${patch}`;
17870
18011
  if (!repo2) return read(this.deps.root, path);
17871
18012
  if (!repo2.fence || !repo2.prefix) return read(repo2.root, path);
17872
18013
  const clean = path.replace(/^\/+/, "").replace(/\/+$/, "");
17873
- const rel = !clean || clean === "." ? "" : clean === repo2.prefix ? "" : clean.startsWith(`${repo2.prefix}/`) ? clean.slice(repo2.prefix.length + 1) : null;
17874
- if (rel === null) throw new FileRequestError("PATH_OUTSIDE_WORKSPACE");
18014
+ const rel = !clean || clean === "." ? "" : clean === repo2.prefix ? "" : clean.startsWith(`${repo2.prefix}/`) ? clean.slice(repo2.prefix.length + 1) : clean;
17875
18015
  const r = await read(repo2.fence, rel);
17876
18016
  const back = (p) => p ? `${repo2.prefix}/${p}` : repo2.prefix;
17877
18017
  return { ...r, path: back(r.path), ...r.entries ? { entries: r.entries.map((e) => ({ ...e, path: back(e.path) })) } : {} };
@@ -17898,8 +18038,9 @@ ${patch}`;
17898
18038
  }
17899
18039
  /**
17900
18040
  * The designs this turn checked, each kept as a version (Erik, 24/10/2026: the canvas's version menu opens earlier
17901
- * ones): the files of its folder, up to 1 MB each and 3 MB in all, with what the person asked. Only with an API that
17902
- * keeps them; a version that fails to save is only logged.
18041
+ * ones): the files of its folder and of its subfolders one level down (assets/), screens first, up to 4 MB each and
18042
+ * 6 MB in all, with what the person asked. A screen over 1 MB (an inlined picture) was left out before, and then the
18043
+ * whole version failed to open. Only with an API that keeps them; a version that fails to save is only logged.
17903
18044
  */
17904
18045
  async saveDesignVersions() {
17905
18046
  const transport = this.deps.transport;
@@ -17909,10 +18050,14 @@ ${patch}`;
17909
18050
  for (const [path, folder] of checked) {
17910
18051
  const files = [];
17911
18052
  let bytes = 0;
17912
- const names = (await (0, import_promises16.readdir)(folder, { withFileTypes: true }).catch(() => [])).filter((e) => e.isFile() && /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(e.name)).map((e) => e.name).sort((a, b) => Number(b === "design.json") - Number(a === "design.json") || a.localeCompare(b)).slice(0, 60);
18053
+ const NAME2 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
18054
+ const top = await (0, import_promises16.readdir)(folder, { withFileTypes: true }).catch(() => []);
18055
+ 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}`)));
18056
+ const rank = (n) => n === "design.json" ? 0 : n.includes("/") ? 2 : 1;
18057
+ 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);
17913
18058
  for (const name of names) {
17914
18059
  const st = await (0, import_promises16.stat)((0, import_path17.join)(folder, name)).catch(() => null);
17915
- if (!st || st.size > 1024 * 1024 || bytes + st.size > 3 * 1024 * 1024) continue;
18060
+ if (!st || st.size > 4 * 1024 * 1024 || bytes + st.size > 6 * 1024 * 1024) continue;
17916
18061
  const data = await (0, import_promises16.readFile)((0, import_path17.join)(folder, name)).catch(() => null);
17917
18062
  if (!data) continue;
17918
18063
  bytes += data.length;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalequality/cli",
3
- "version": "0.4.31",
3
+ "version": "0.4.33",
4
4
  "description": "ScaleQuality CLI. Connect your computer to the ScaleQuality AI Workspace (`scalequality login`), run its coding engine in any folder of your computer, and import your Claude Code and Codex conversations.",
5
5
  "type": "module",
6
6
  "bin": {