codeam-cli 2.76.14 → 2.76.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/index.js +503 -326
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -128,11 +128,11 @@ var init_stdio_proxy = __esm({
128
128
  rl.on("close", () => this.child?.stdin?.end());
129
129
  const timer = setInterval(() => this.checkRestart(stdout), RESTART_CHECK_INTERVAL_MS);
130
130
  timer.unref();
131
- return new Promise((resolve14) => {
131
+ return new Promise((resolve13) => {
132
132
  this.ended = (code) => {
133
133
  clearInterval(timer);
134
134
  process.exitCode = code;
135
- resolve14();
135
+ resolve13();
136
136
  };
137
137
  });
138
138
  }
@@ -313,14 +313,14 @@ function deploymentNameFromKey(key) {
313
313
  return null;
314
314
  }
315
315
  function defaultSpawn(timeoutMs) {
316
- return (cmd, args2, opts) => new Promise((resolve14) => {
316
+ return (cmd, args2, opts) => new Promise((resolve13) => {
317
317
  let out2 = "";
318
318
  let err = "";
319
319
  let done = false;
320
320
  const finish = (code) => {
321
321
  if (done) return;
322
322
  done = true;
323
- resolve14({ code, stdout: out2, stderr: err });
323
+ resolve13({ code, stdout: out2, stderr: err });
324
324
  };
325
325
  let child;
326
326
  try {
@@ -656,7 +656,7 @@ async function runHttpRelay(delivery, client3, id) {
656
656
  requestInit: { headers: buildHttpHeaders(delivery.httpHeaders, token) }
657
657
  });
658
658
  const stdioTransport = new StdioServerTransport();
659
- await new Promise((resolve14, reject) => {
659
+ await new Promise((resolve13, reject) => {
660
660
  let done = false;
661
661
  const watchdog = createToolCallWatchdog({
662
662
  timeoutMs: TOOL_CALL_TIMEOUT_MS,
@@ -670,7 +670,7 @@ async function runHttpRelay(delivery, client3, id) {
670
670
  void httpTransport.close().catch(() => void 0);
671
671
  void stdioTransport.close().catch(() => void 0);
672
672
  if (err) reject(err);
673
- else resolve14();
673
+ else resolve13();
674
674
  };
675
675
  stdioTransport.onmessage = (msg) => {
676
676
  watchdog.onClientMessage(msg);
@@ -4726,11 +4726,11 @@ async function raceWithTimeout(promise, timeoutMs, onTimeout) {
4726
4726
  try {
4727
4727
  return await Promise.race([
4728
4728
  promise,
4729
- new Promise((resolve14, reject) => {
4729
+ new Promise((resolve13, reject) => {
4730
4730
  timeoutHandle = safeSetTimeout(() => {
4731
4731
  try {
4732
4732
  onTimeout?.();
4733
- resolve14();
4733
+ resolve13();
4734
4734
  } catch (error) {
4735
4735
  reject(error);
4736
4736
  }
@@ -7804,13 +7804,13 @@ async function getContextLinesFromFile(path114, ranges, output, cacheKey, openSo
7804
7804
  const fileHandle = await openRegularSourceFile(path114, openSourceFile, logger);
7805
7805
  if (void 0 === fileHandle) return void LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
7806
7806
  const openedFileHandle = fileHandle;
7807
- return new Promise((resolve14) => {
7807
+ return new Promise((resolve13) => {
7808
7808
  let finished = false;
7809
7809
  function destroyStreamAndResolve(stream2) {
7810
7810
  if (finished) return;
7811
7811
  finished = true;
7812
7812
  stream2?.destroy();
7813
- openedFileHandle.close().then(resolve14, resolve14);
7813
+ openedFileHandle.close().then(resolve13, resolve13);
7814
7814
  }
7815
7815
  let stream;
7816
7816
  try {
@@ -8999,7 +8999,7 @@ var V1CaptureSender = class {
8999
8999
  this.fetchFn = hooks.fetch;
9000
9000
  this.onError = hooks.onError;
9001
9001
  this.now = hooks.now ?? Date.now;
9002
- this.sleep = hooks.sleep ?? ((ms) => new Promise((resolve14) => safeSetTimeout(resolve14, ms)));
9002
+ this.sleep = hooks.sleep ?? ((ms) => new Promise((resolve13) => safeSetTimeout(resolve13, ms)));
9003
9003
  this.generateRequestId = hooks.generateRequestId ?? uuidv7;
9004
9004
  this.compress = hooks.compress ?? gzipCompress;
9005
9005
  }
@@ -9363,9 +9363,9 @@ var PostHogBackendClient = class extends PostHogCoreStateless {
9363
9363
  if (!waitUntil) return;
9364
9364
  if (this.disabled || this.optedOut) return;
9365
9365
  if (!this._waitUntilCycle) {
9366
- let resolve14;
9366
+ let resolve13;
9367
9367
  const promise = new Promise((r) => {
9368
- resolve14 = r;
9368
+ resolve13 = r;
9369
9369
  });
9370
9370
  try {
9371
9371
  waitUntil(promise);
@@ -9373,7 +9373,7 @@ var PostHogBackendClient = class extends PostHogCoreStateless {
9373
9373
  return;
9374
9374
  }
9375
9375
  this._waitUntilCycle = {
9376
- resolve: resolve14,
9376
+ resolve: resolve13,
9377
9377
  startedAt: Date.now(),
9378
9378
  timer: void 0
9379
9379
  };
@@ -9397,12 +9397,12 @@ var PostHogBackendClient = class extends PostHogCoreStateless {
9397
9397
  return cycle?.resolve;
9398
9398
  }
9399
9399
  async resolveWaitUntilFlush() {
9400
- const resolve14 = this._consumeWaitUntilCycle();
9400
+ const resolve13 = this._consumeWaitUntilCycle();
9401
9401
  try {
9402
9402
  await this.flushWithPendingPromises();
9403
9403
  } catch {
9404
9404
  } finally {
9405
- resolve14?.();
9405
+ resolve13?.();
9406
9406
  }
9407
9407
  }
9408
9408
  getPersistedProperty(key) {
@@ -9660,15 +9660,15 @@ var PostHogBackendClient = class extends PostHogCoreStateless {
9660
9660
  async waitForLocalEvaluationReady(timeoutMs = THIRTY_SECONDS) {
9661
9661
  if (this.isLocalEvaluationReady()) return true;
9662
9662
  if (void 0 === this.featureFlagsPoller) return false;
9663
- return new Promise((resolve14) => {
9663
+ return new Promise((resolve13) => {
9664
9664
  const timeout = setTimeout(() => {
9665
9665
  cleanup();
9666
- resolve14(false);
9666
+ resolve13(false);
9667
9667
  }, timeoutMs);
9668
9668
  const cleanup = this._events.on("localEvaluationFlagsLoaded", (count) => {
9669
9669
  clearTimeout(timeout);
9670
9670
  cleanup();
9671
- resolve14(count > 0);
9671
+ resolve13(count > 0);
9672
9672
  });
9673
9673
  });
9674
9674
  }
@@ -10172,7 +10172,7 @@ var PostHogBackendClient = class extends PostHogCoreStateless {
10172
10172
  }
10173
10173
  async _shutdown(shutdownTimeoutMs) {
10174
10174
  const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 3e4);
10175
- const resolve14 = this._consumeWaitUntilCycle();
10175
+ const resolve13 = this._consumeWaitUntilCycle();
10176
10176
  await this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);
10177
10177
  this.errorTracking.shutdown();
10178
10178
  if (this._metrics) {
@@ -10184,7 +10184,7 @@ var PostHogBackendClient = class extends PostHogCoreStateless {
10184
10184
  return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));
10185
10185
  } finally {
10186
10186
  this.distinctIdHasSentFlagCalls = {};
10187
- resolve14?.();
10187
+ resolve13?.();
10188
10188
  }
10189
10189
  }
10190
10190
  async _requestRemoteConfigPayload(flagKey) {
@@ -10579,7 +10579,7 @@ function readAnonId() {
10579
10579
  }
10580
10580
  function superProperties() {
10581
10581
  return {
10582
- cliVersion: true ? "2.76.14" : "0.0.0-dev",
10582
+ cliVersion: true ? "2.76.16" : "0.0.0-dev",
10583
10583
  nodeVersion: process.version,
10584
10584
  platform: process.platform,
10585
10585
  arch: process.arch,
@@ -10726,10 +10726,10 @@ var _execSeam = {
10726
10726
  }
10727
10727
  };
10728
10728
  var _execSeamAsync = {
10729
- exec: (file, args2, opts) => new Promise((resolve14, reject) => {
10729
+ exec: (file, args2, opts) => new Promise((resolve13, reject) => {
10730
10730
  (0, import_child_process.execFile)(file, args2, opts, (err, stdout) => {
10731
10731
  if (err) reject(err);
10732
- else resolve14(typeof stdout === "string" ? stdout : stdout.toString("utf8"));
10732
+ else resolve13(typeof stdout === "string" ? stdout : stdout.toString("utf8"));
10733
10733
  });
10734
10734
  })
10735
10735
  };
@@ -10753,6 +10753,10 @@ var os4 = __toESM(require("os"));
10753
10753
  var path4 = __toESM(require("path"));
10754
10754
  var import_child_process2 = require("child_process");
10755
10755
  var WRAPPER_REPO_NAME = "codeam-codespace";
10756
+ function isWrapperCheckout(dir) {
10757
+ const resolved = path4.posix.normalize(dir.replace(/\\/g, "/")).replace(/\/+$/, "");
10758
+ return resolved === `/workspaces/${WRAPPER_REPO_NAME}`;
10759
+ }
10756
10760
  function resolveSessionHostname(cwd = process.cwd()) {
10757
10761
  if (process.env.CODESPACES !== "true") {
10758
10762
  const label = process.env.CODEAM_HOST_LABEL?.trim();
@@ -10824,7 +10828,7 @@ var http = __toESM(require("http"));
10824
10828
  // package.json
10825
10829
  var package_default = {
10826
10830
  name: "codeam-cli",
10827
- version: "2.76.14",
10831
+ version: "2.76.16",
10828
10832
  description: "Workflow-continuity bridge for AI coding agents. Wrap Claude Code or Codex in a PTY and supervise, approve, and redirect the session from any device \u2014 async. The terminal companion for CodeAgent Mobile.",
10829
10833
  type: "commonjs",
10830
10834
  main: "dist/index.js",
@@ -10958,8 +10962,8 @@ async function requestCode(pluginId, pluginSecretHash) {
10958
10962
  });
10959
10963
  let timer;
10960
10964
  const timeoutSentinel = /* @__PURE__ */ Symbol("request-code-timeout");
10961
- const timeoutPromise = new Promise((resolve14) => {
10962
- timer = setTimeout(() => resolve14(timeoutSentinel), REQUEST_CODE_TIMEOUT_MS);
10965
+ const timeoutPromise = new Promise((resolve13) => {
10966
+ timer = setTimeout(() => resolve13(timeoutSentinel), REQUEST_CODE_TIMEOUT_MS);
10963
10967
  });
10964
10968
  const result = await Promise.race([post3, timeoutPromise]);
10965
10969
  clearTimeout(timer);
@@ -11413,7 +11417,7 @@ async function postBeadsProvisioning(input) {
11413
11417
  }
11414
11418
  }
11415
11419
  async function _postJsonAuthed(url2, body, pluginAuthToken) {
11416
- return new Promise((resolve14, reject) => {
11420
+ return new Promise((resolve13, reject) => {
11417
11421
  const data = JSON.stringify(body);
11418
11422
  const u2 = new URL(url2);
11419
11423
  const transport = u2.protocol === "https:" ? https : http;
@@ -11443,9 +11447,9 @@ async function _postJsonAuthed(url2, body, pluginAuthToken) {
11443
11447
  return;
11444
11448
  }
11445
11449
  try {
11446
- resolve14(JSON.parse(responseBody));
11450
+ resolve13(JSON.parse(responseBody));
11447
11451
  } catch {
11448
- resolve14(null);
11452
+ resolve13(null);
11449
11453
  }
11450
11454
  });
11451
11455
  }
@@ -11471,7 +11475,7 @@ function makeHttpError(statusCode, retryAfterHeader, responseBody) {
11471
11475
  return err;
11472
11476
  }
11473
11477
  async function _postJson(url2, body, extraHeaders) {
11474
- return new Promise((resolve14, reject) => {
11478
+ return new Promise((resolve13, reject) => {
11475
11479
  const data = JSON.stringify(body);
11476
11480
  const u2 = new URL(url2);
11477
11481
  const transport = u2.protocol === "https:" ? https : http;
@@ -11501,9 +11505,9 @@ async function _postJson(url2, body, extraHeaders) {
11501
11505
  return;
11502
11506
  }
11503
11507
  try {
11504
- resolve14(JSON.parse(body2));
11508
+ resolve13(JSON.parse(body2));
11505
11509
  } catch {
11506
- resolve14(null);
11510
+ resolve13(null);
11507
11511
  }
11508
11512
  });
11509
11513
  }
@@ -11518,7 +11522,7 @@ async function _postJson(url2, body, extraHeaders) {
11518
11522
  });
11519
11523
  }
11520
11524
  async function _getJson(url2, extraHeaders) {
11521
- return new Promise((resolve14, reject) => {
11525
+ return new Promise((resolve13, reject) => {
11522
11526
  const u2 = new URL(url2);
11523
11527
  const transport = u2.protocol === "https:" ? https : http;
11524
11528
  const req = transport.request(
@@ -11542,9 +11546,9 @@ async function _getJson(url2, extraHeaders) {
11542
11546
  return;
11543
11547
  }
11544
11548
  try {
11545
- resolve14(JSON.parse(body));
11549
+ resolve13(JSON.parse(body));
11546
11550
  } catch {
11547
- resolve14(null);
11551
+ resolve13(null);
11548
11552
  }
11549
11553
  });
11550
11554
  }
@@ -12160,7 +12164,7 @@ var CommandRelayService = class _CommandRelayService {
12160
12164
  // fresh + clear the "CLI update available" banner after a self-update
12161
12165
  // (a codespace that reinstalls @latest reconnects via heartbeat, not
12162
12166
  // pair/reconnect). Older backends ignore the extra field.
12163
- ..."2.76.14" ? { ideVersion: "2.76.14" } : {}
12167
+ ..."2.76.16" ? { ideVersion: "2.76.16" } : {}
12164
12168
  };
12165
12169
  try {
12166
12170
  const res = await _postJson(`${API_BASE2}/api/plugin/heartbeat`, body);
@@ -12305,8 +12309,8 @@ async function stopRelayWithGoodbye(relay, timeoutMs = RELAY_GOODBYE_TIMEOUT_MS)
12305
12309
  try {
12306
12310
  await Promise.race([
12307
12311
  relay.stopAndFlush(),
12308
- new Promise((resolve14) => {
12309
- timer = setTimeout(resolve14, timeoutMs);
12312
+ new Promise((resolve13) => {
12313
+ timer = setTimeout(resolve13, timeoutMs);
12310
12314
  })
12311
12315
  ]);
12312
12316
  } catch {
@@ -12415,7 +12419,7 @@ var _transport2 = {
12415
12419
  post: _post
12416
12420
  };
12417
12421
  function _post(url2, headers, payload) {
12418
- return new Promise((resolve14, reject) => {
12422
+ return new Promise((resolve13, reject) => {
12419
12423
  let settled = false;
12420
12424
  const u2 = new URL(url2);
12421
12425
  const lib = u2.protocol === "https:" ? https3 : http3;
@@ -12440,7 +12444,7 @@ function _post(url2, headers, payload) {
12440
12444
  res.on("end", () => {
12441
12445
  if (settled) return;
12442
12446
  settled = true;
12443
- resolve14({ statusCode: res.statusCode ?? 0, body });
12447
+ resolve13({ statusCode: res.statusCode ?? 0, body });
12444
12448
  });
12445
12449
  }
12446
12450
  );
@@ -13139,12 +13143,12 @@ var _gitSeam = {
13139
13143
  run: _runGitImpl
13140
13144
  };
13141
13145
  async function _runGitImpl(cwd, args2, opts = {}) {
13142
- return new Promise((resolve14) => {
13146
+ return new Promise((resolve13) => {
13143
13147
  let proc;
13144
13148
  try {
13145
13149
  proc = (0, import_child_process3.spawn)("git", args2, { cwd, env: process.env });
13146
13150
  } catch {
13147
- resolve14(null);
13151
+ resolve13(null);
13148
13152
  return;
13149
13153
  }
13150
13154
  let stdout = "";
@@ -13155,13 +13159,13 @@ async function _runGitImpl(cwd, args2, opts = {}) {
13155
13159
  proc.stderr?.on("data", (c2) => {
13156
13160
  stderr += c2.toString();
13157
13161
  });
13158
- proc.on("error", () => resolve14(null));
13162
+ proc.on("error", () => resolve13(null));
13159
13163
  proc.on("close", (code) => {
13160
13164
  if (code === 0 || opts.allowNonZeroExit) {
13161
- resolve14(stdout);
13165
+ resolve13(stdout);
13162
13166
  } else {
13163
13167
  log.trace("fileWatcher", `git ${args2.join(" ")} exited ${code} stderr=${stderr.slice(0, 200)}`);
13164
- resolve14(null);
13168
+ resolve13(null);
13165
13169
  }
13166
13170
  });
13167
13171
  });
@@ -13247,7 +13251,7 @@ var ChunkEmitter = class {
13247
13251
  if (this.pairingInvalid) {
13248
13252
  return Promise.resolve({ dead: true });
13249
13253
  }
13250
- return new Promise((resolve14) => {
13254
+ return new Promise((resolve13) => {
13251
13255
  let refreshedOnce = false;
13252
13256
  const attempt = (attemptsLeft) => {
13253
13257
  _transport3.post(this.url, this.headers, payload).then(({ statusCode, body: resBody }) => {
@@ -13255,13 +13259,13 @@ var ChunkEmitter = class {
13255
13259
  if (statusCode === 410 || statusCode === 404 && /SESSION_NOT_FOUND|SESSION_GONE/.test(resBody)) {
13256
13260
  process.stderr.write("[codeam] session was deleted/disconnected \u2014 stopping output stream.\n");
13257
13261
  log.info("chunkEmitter", `dead status=${statusCode} took=${tookMs}ms`);
13258
- resolve14({ dead: true });
13262
+ resolve13({ dead: true });
13259
13263
  return;
13260
13264
  }
13261
13265
  if (statusCode === 401 || statusCode === 403) {
13262
13266
  if (refreshedOnce) {
13263
13267
  this.markPairingInvalid(statusCode, tookMs);
13264
- resolve14({ dead: true });
13268
+ resolve13({ dead: true });
13265
13269
  return;
13266
13270
  }
13267
13271
  log.warn("chunkEmitter", `auth ${statusCode} took=${tookMs}ms \u2014 attempting silent refresh`);
@@ -13277,10 +13281,10 @@ var ChunkEmitter = class {
13277
13281
  }
13278
13282
  if (refresh.kind === "gone") {
13279
13283
  this.markPairingInvalid(statusCode, tookMs);
13280
- resolve14({ dead: true });
13284
+ resolve13({ dead: true });
13281
13285
  return;
13282
13286
  }
13283
- resolve14({ dead: false });
13287
+ resolve13({ dead: false });
13284
13288
  })();
13285
13289
  return;
13286
13290
  }
@@ -13291,7 +13295,7 @@ var ChunkEmitter = class {
13291
13295
  } else {
13292
13296
  log.info("chunkEmitter", `ok status=${statusCode} took=${tookMs}ms`);
13293
13297
  }
13294
- resolve14({ dead: false });
13298
+ resolve13({ dead: false });
13295
13299
  }).catch((err) => {
13296
13300
  log.warn(
13297
13301
  "chunkEmitter",
@@ -13302,7 +13306,7 @@ var ChunkEmitter = class {
13302
13306
  const delay = 200 * (maxRetries - attemptsLeft + 1);
13303
13307
  setTimeout(() => attempt(attemptsLeft - 1), delay);
13304
13308
  } else {
13305
- resolve14({ dead: false });
13309
+ resolve13({ dead: false });
13306
13310
  }
13307
13311
  });
13308
13312
  };
@@ -13325,7 +13329,7 @@ var _transport3 = {
13325
13329
  post: _post2
13326
13330
  };
13327
13331
  function _post2(url2, headers, payload) {
13328
- return new Promise((resolve14, reject) => {
13332
+ return new Promise((resolve13, reject) => {
13329
13333
  let settled = false;
13330
13334
  const u2 = new URL(url2);
13331
13335
  const transport = u2.protocol === "https:" ? https4 : http4;
@@ -13349,7 +13353,7 @@ function _post2(url2, headers, payload) {
13349
13353
  res.on("end", () => {
13350
13354
  if (settled) return;
13351
13355
  settled = true;
13352
- resolve14({ statusCode: res.statusCode ?? 0, body: resData });
13356
+ resolve13({ statusCode: res.statusCode ?? 0, body: resData });
13353
13357
  });
13354
13358
  }
13355
13359
  );
@@ -14443,12 +14447,12 @@ async function applyFileReview(workingDir, filePath, action) {
14443
14447
  return { ok: true, action, filePath, repoRoot };
14444
14448
  }
14445
14449
  function runGit2(cwd, args2) {
14446
- return new Promise((resolve14) => {
14450
+ return new Promise((resolve13) => {
14447
14451
  let proc;
14448
14452
  try {
14449
14453
  proc = (0, import_child_process6.spawn)("git", args2, { cwd, env: process.env });
14450
14454
  } catch (err) {
14451
- resolve14({ ok: false, code: -1, stdout: "", stderr: err.message });
14455
+ resolve13({ ok: false, code: -1, stdout: "", stderr: err.message });
14452
14456
  return;
14453
14457
  }
14454
14458
  let stdout = "";
@@ -14461,11 +14465,11 @@ function runGit2(cwd, args2) {
14461
14465
  });
14462
14466
  proc.on(
14463
14467
  "error",
14464
- (err) => resolve14({ ok: false, code: -1, stdout, stderr: stderr + err.message })
14468
+ (err) => resolve13({ ok: false, code: -1, stdout, stderr: stderr + err.message })
14465
14469
  );
14466
14470
  proc.on(
14467
14471
  "close",
14468
- (code) => resolve14({ ok: code === 0, code: code ?? -1, stdout, stderr })
14472
+ (code) => resolve13({ ok: code === 0, code: code ?? -1, stdout, stderr })
14469
14473
  );
14470
14474
  });
14471
14475
  }
@@ -16804,13 +16808,13 @@ var UnixPtyStrategy = class {
16804
16808
  this.proc = null;
16805
16809
  if (proc) {
16806
16810
  proc.removeAllListeners("exit");
16807
- const exited = new Promise((resolve14) => {
16808
- if (proc.exitCode !== null || proc.signalCode !== null) return resolve14();
16809
- proc.once("exit", () => resolve14());
16811
+ const exited = new Promise((resolve13) => {
16812
+ if (proc.exitCode !== null || proc.signalCode !== null) return resolve13();
16813
+ proc.once("exit", () => resolve13());
16810
16814
  });
16811
16815
  proc.kill("SIGTERM");
16812
- const timer = new Promise((resolve14) => {
16813
- const t2 = setTimeout(() => resolve14("timeout"), timeoutMs);
16816
+ const timer = new Promise((resolve13) => {
16817
+ const t2 = setTimeout(() => resolve13("timeout"), timeoutMs);
16814
16818
  void exited.then(() => clearTimeout(t2));
16815
16819
  });
16816
16820
  if (await Promise.race([exited, timer]) === "timeout") {
@@ -17284,15 +17288,15 @@ function runInstaller() {
17284
17288
  "-Command",
17285
17289
  "irm https://claude.ai/install.ps1 | iex"
17286
17290
  ] : ["-c", "curl -fsSL https://claude.ai/install.sh | bash"];
17287
- return new Promise((resolve14) => {
17291
+ return new Promise((resolve13) => {
17288
17292
  const proc = (0, import_child_process9.spawn)(cmd, args2, { stdio: "inherit" });
17289
17293
  proc.on("error", (err) => {
17290
17294
  console.error(`
17291
17295
  \u2717 Installer failed to launch: ${err.message}`);
17292
- resolve14(false);
17296
+ resolve13(false);
17293
17297
  });
17294
17298
  proc.on("exit", (code) => {
17295
- resolve14(code === 0);
17299
+ resolve13(code === 0);
17296
17300
  });
17297
17301
  });
17298
17302
  }
@@ -17427,7 +17431,7 @@ function extractSetupTokenFromOutput(output) {
17427
17431
  return m ? m[0] : null;
17428
17432
  }
17429
17433
  function captureClaudeSetupToken() {
17430
- return new Promise((resolve14, reject) => {
17434
+ return new Promise((resolve13, reject) => {
17431
17435
  const child = (0, import_node_child_process2.spawn)("claude", ["setup-token"], {
17432
17436
  stdio: ["inherit", "pipe", "inherit"]
17433
17437
  });
@@ -17441,7 +17445,7 @@ function captureClaudeSetupToken() {
17441
17445
  child.on("exit", (code) => {
17442
17446
  const token = extractSetupTokenFromOutput(out2);
17443
17447
  if (token) {
17444
- resolve14({ method: "setup_token", credential: token, source: "setup-token" });
17448
+ resolve13({ method: "setup_token", credential: token, source: "setup-token" });
17445
17449
  return;
17446
17450
  }
17447
17451
  reject(
@@ -17527,17 +17531,17 @@ function parseUsageOutput(raw) {
17527
17531
  return { percent, resetAt };
17528
17532
  }
17529
17533
  async function fetchClaudeQuota() {
17530
- return new Promise((resolve14) => {
17534
+ return new Promise((resolve13) => {
17531
17535
  const claudeCmd = findInPath("claude") ? "claude" : "claude-code";
17532
17536
  if (!claudeCmd) {
17533
- resolve14(null);
17537
+ resolve13(null);
17534
17538
  return;
17535
17539
  }
17536
17540
  const helperPath = path17.join(os11.tmpdir(), "codeam-quota-helper.py");
17537
17541
  fs13.writeFileSync(helperPath, HELPER_SCRIPT, { mode: 420 });
17538
17542
  const python = findInPath("python3") ?? findInPath("python");
17539
17543
  if (!python) {
17540
- resolve14(null);
17544
+ resolve13(null);
17541
17545
  return;
17542
17546
  }
17543
17547
  const proc = (0, import_child_process10.spawn)(python, [helperPath, claudeCmd, "--tools", ""], {
@@ -17564,13 +17568,13 @@ async function fetchClaudeQuota() {
17564
17568
  fs13.unlinkSync(helperPath);
17565
17569
  } catch {
17566
17570
  }
17567
- resolve14(result);
17571
+ resolve13(result);
17568
17572
  }, 5e3);
17569
17573
  }, 8e3);
17570
17574
  setTimeout(() => {
17571
17575
  if (!resolved) {
17572
17576
  resolved = true;
17573
- resolve14(null);
17577
+ resolve13(null);
17574
17578
  }
17575
17579
  try {
17576
17580
  proc.kill();
@@ -17609,12 +17613,12 @@ function killActiveSpawnAndCaptureChildren() {
17609
17613
  }
17610
17614
  async function spawnAndCapture(cmd, args2, opts = {}) {
17611
17615
  const timeoutMs = opts.timeoutMs ?? 6e4;
17612
- return new Promise((resolve14) => {
17616
+ return new Promise((resolve13) => {
17613
17617
  let settled = false;
17614
17618
  const settle = (value) => {
17615
17619
  if (settled) return;
17616
17620
  settled = true;
17617
- resolve14(value);
17621
+ resolve13(value);
17618
17622
  };
17619
17623
  let child;
17620
17624
  try {
@@ -19065,7 +19069,7 @@ function newestRolloutIdSince(sessionsRoot, resolvedCwd, floorMs) {
19065
19069
  return bestId;
19066
19070
  }
19067
19071
  function sleep2(ms) {
19068
- return new Promise((resolve14) => setTimeout(resolve14, ms));
19072
+ return new Promise((resolve13) => setTimeout(resolve13, ms));
19069
19073
  }
19070
19074
  function getCurrentUsage2(historyDir) {
19071
19075
  if (!import_node_fs4.default.existsSync(historyDir)) return null;
@@ -19176,7 +19180,13 @@ function codexLoginLauncher() {
19176
19180
  };
19177
19181
  }
19178
19182
 
19183
+ // src/agents/codex/state-runtime-race.ts
19184
+ var CODEX_STATE_RUNTIME_RACE_RE = /failed to initialize (sqlite )?state runtime/i;
19185
+
19179
19186
  // src/agents/codex/runtime.ts
19187
+ var _codexOneShotSeam = {
19188
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms))
19189
+ };
19180
19190
  var CODEX_CONTEXT_WINDOW = 272e3;
19181
19191
  var CODEX_MODELS = [
19182
19192
  { id: "gpt-5.5", label: "GPT-5.5", contextWindow: CODEX_CONTEXT_WINDOW },
@@ -19295,24 +19305,34 @@ var CodexRuntimeStrategy = class {
19295
19305
  const binary = this.os.findInPath("codex");
19296
19306
  if (!binary) return null;
19297
19307
  const launch = this.os.buildLaunch(binary, ["exec", prompt]);
19298
- return spawnAndCapture(launch.cmd, launch.args, {
19299
- onStderr: opts?.onStderr,
19300
- onFailedOutput: opts?.onFailedOutput,
19301
- cwd: opts?.cwd,
19302
- timeoutMs: opts?.timeoutMs
19303
- });
19308
+ const runOnce = () => {
19309
+ let stderr = "";
19310
+ return spawnAndCapture(launch.cmd, launch.args, {
19311
+ onStderr: (chunk) => {
19312
+ stderr += chunk;
19313
+ opts?.onStderr?.(chunk);
19314
+ },
19315
+ onFailedOutput: opts?.onFailedOutput,
19316
+ cwd: opts?.cwd,
19317
+ timeoutMs: opts?.timeoutMs
19318
+ }).then((text) => ({ text, stderr }));
19319
+ };
19320
+ const first = await runOnce();
19321
+ if (first.text !== null || !CODEX_STATE_RUNTIME_RACE_RE.test(first.stderr)) return first.text;
19322
+ await _codexOneShotSeam.sleep(1e3);
19323
+ return (await runOnce()).text;
19304
19324
  }
19305
19325
  };
19306
19326
  function resolveNpm(os74) {
19307
19327
  return os74.id === "win32" ? "npm.cmd" : "npm";
19308
19328
  }
19309
19329
  async function installCodexViaNpm(os74) {
19310
- return new Promise((resolve14, reject) => {
19330
+ return new Promise((resolve13, reject) => {
19311
19331
  const proc = (0, import_node_child_process4.spawn)(resolveNpm(os74), ["install", "-g", "@openai/codex"], {
19312
19332
  stdio: "inherit"
19313
19333
  });
19314
19334
  proc.on("close", (code) => {
19315
- if (code === 0) resolve14();
19335
+ if (code === 0) resolve13();
19316
19336
  else reject(new Error(`npm install -g @openai/codex exited ${code}`));
19317
19337
  });
19318
19338
  proc.on("error", (err) => {
@@ -19432,7 +19452,7 @@ var defaultOsRunner = {
19432
19452
  }
19433
19453
  },
19434
19454
  run(cmd, args2, opts = {}) {
19435
- return new Promise((resolve14) => {
19455
+ return new Promise((resolve13) => {
19436
19456
  const spawnEnv = opts.env ?? process.env;
19437
19457
  const child = (0, import_node_child_process5.spawn)(cmd, args2, { stdio: ["ignore", "pipe", "pipe"], env: spawnEnv });
19438
19458
  let stderrBuf = "";
@@ -19441,7 +19461,7 @@ var defaultOsRunner = {
19441
19461
  const done = (code) => {
19442
19462
  if (settled) return;
19443
19463
  settled = true;
19444
- resolve14({ code, stderr: stderrBuf, stdout: stdoutBuf });
19464
+ resolve13({ code, stderr: stderrBuf, stdout: stdoutBuf });
19445
19465
  };
19446
19466
  child.stdout?.on("data", (b) => {
19447
19467
  const chunk = b.toString();
@@ -19590,7 +19610,7 @@ async function ensureInstallPrerequisites(os74, deps = {}) {
19590
19610
  };
19591
19611
  }
19592
19612
  function defaultRunInstallScript(env) {
19593
- return new Promise((resolve14) => {
19613
+ return new Promise((resolve13) => {
19594
19614
  const proc = (0, import_node_child_process6.spawn)(
19595
19615
  "sh",
19596
19616
  ["-c", `curl -fsSL --connect-timeout 15 --max-time 120 ${INSTALL_URL} | sh`],
@@ -19602,7 +19622,7 @@ function defaultRunInstallScript(env) {
19602
19622
  if (settled) return;
19603
19623
  settled = true;
19604
19624
  clearTimeout(timer);
19605
- resolve14({ code, output });
19625
+ resolve13({ code, output });
19606
19626
  };
19607
19627
  const onData = (b) => {
19608
19628
  const chunk = b.toString();
@@ -19976,7 +19996,7 @@ var CoderabbitRuntimeStrategy = class {
19976
19996
  }
19977
19997
  async runOneShot(input) {
19978
19998
  const launch = await this.prepareInvocation(input);
19979
- return new Promise((resolve14, reject) => {
19999
+ return new Promise((resolve13, reject) => {
19980
20000
  const stdoutBuf = [];
19981
20001
  const stderrBuf = [];
19982
20002
  const proc = (0, import_node_child_process8.spawn)(launch.cmd, launch.args, {
@@ -19988,7 +20008,7 @@ var CoderabbitRuntimeStrategy = class {
19988
20008
  if (settled) return;
19989
20009
  settled = true;
19990
20010
  clearTimeout(timer);
19991
- resolve14(out2);
20011
+ resolve13(out2);
19992
20012
  };
19993
20013
  const timer = setTimeout(() => {
19994
20014
  if (settled) return;
@@ -20608,7 +20628,7 @@ function resolveClaudeNativeBinary(deps = {}) {
20608
20628
  const candidate = import_path4.default.join(scopeDir, `claude-agent-sdk-${platformKey}`, binName);
20609
20629
  return existsSync35(candidate) ? candidate : null;
20610
20630
  }
20611
- var realSleep = (ms) => new Promise((resolve14) => setTimeout(resolve14, ms));
20631
+ var realSleep = (ms) => new Promise((resolve13) => setTimeout(resolve13, ms));
20612
20632
  async function waitForClaudeNativeBinary(opts = {}) {
20613
20633
  const timeoutMs = opts.timeoutMs ?? 18e4;
20614
20634
  const pollMs = opts.pollMs ?? 500;
@@ -20729,7 +20749,7 @@ var PERMANENT_ADAPTER_STARTUP_RE = /IneligibleTierError|UNSUPPORTED_CLIENT|no lo
20729
20749
  function probeAdapterModuleGraph(command2, args2, opts = {}) {
20730
20750
  const livenessMs = opts.livenessMs ?? 400;
20731
20751
  const spawnFn = opts.spawnFn ?? import_child_process13.spawn;
20732
- return new Promise((resolve14) => {
20752
+ return new Promise((resolve13) => {
20733
20753
  let settled = false;
20734
20754
  let stderr = "";
20735
20755
  let timer;
@@ -20742,12 +20762,12 @@ function probeAdapterModuleGraph(command2, args2, opts = {}) {
20742
20762
  child?.kill("SIGKILL");
20743
20763
  } catch {
20744
20764
  }
20745
- resolve14(r);
20765
+ resolve13(r);
20746
20766
  };
20747
20767
  try {
20748
20768
  child = spawnFn(command2, [...args2], { stdio: ["pipe", "ignore", "pipe"] });
20749
20769
  } catch {
20750
- resolve14("ok");
20770
+ resolve13("ok");
20751
20771
  return;
20752
20772
  }
20753
20773
  child.stderr?.on("data", (d3) => {
@@ -21336,7 +21356,7 @@ function newestSessionSince(bucket, floorMs) {
21336
21356
  return bestId;
21337
21357
  }
21338
21358
  function sleep3(ms) {
21339
- return new Promise((resolve14) => setTimeout(resolve14, ms));
21359
+ return new Promise((resolve13) => setTimeout(resolve13, ms));
21340
21360
  }
21341
21361
  function joinTextParts(parts) {
21342
21362
  if (!Array.isArray(parts)) return "";
@@ -21787,7 +21807,7 @@ async function link(args2 = []) {
21787
21807
  waitSpin.start(waitMsg());
21788
21808
  const countdown = setInterval(() => waitSpin.message(waitMsg()), 1e3);
21789
21809
  countdown.unref?.();
21790
- const paired = await new Promise((resolve14, reject) => {
21810
+ const paired = await new Promise((resolve13, reject) => {
21791
21811
  let stopPoll = null;
21792
21812
  const sigint = () => {
21793
21813
  clearInterval(countdown);
@@ -21800,7 +21820,7 @@ async function link(args2 = []) {
21800
21820
  process.removeListener("SIGINT", sigint);
21801
21821
  clearInterval(countdown);
21802
21822
  waitSpin.stop("Paired");
21803
- resolve14(info);
21823
+ resolve13(info);
21804
21824
  },
21805
21825
  () => {
21806
21826
  clearInterval(countdown);
@@ -21958,14 +21978,14 @@ async function captureFreshCredentials(ctx) {
21958
21978
  }
21959
21979
  };
21960
21980
  try {
21961
- const token = await new Promise((resolve14, reject) => {
21981
+ const token = await new Promise((resolve13, reject) => {
21962
21982
  let settled = false;
21963
21983
  const tryExtract = async () => {
21964
21984
  if (settled) return;
21965
21985
  const t2 = await ctx.locator.extract();
21966
21986
  if (t2 && !settled) {
21967
21987
  settled = true;
21968
- resolve14(t2);
21988
+ resolve13(t2);
21969
21989
  }
21970
21990
  };
21971
21991
  watcher.on("add", () => void tryExtract());
@@ -22209,7 +22229,7 @@ function deliverPendingCoderabbitCallback(callbackUrl) {
22209
22229
  function runCoderabbitOAuthLogin(deps) {
22210
22230
  const timeoutMs = deps.timeoutMs ?? 18e4;
22211
22231
  const spawnProc = deps.spawn ?? spawnCoderabbitLoginProc;
22212
- return new Promise((resolve14) => {
22232
+ return new Promise((resolve13) => {
22213
22233
  let settled = false;
22214
22234
  let stdout = "";
22215
22235
  let last = null;
@@ -22222,13 +22242,13 @@ function runCoderabbitOAuthLogin(deps) {
22222
22242
  child.kill("SIGKILL");
22223
22243
  } catch {
22224
22244
  }
22225
- resolve14(r);
22245
+ resolve13(r);
22226
22246
  };
22227
22247
  let child;
22228
22248
  try {
22229
22249
  child = spawnProc("coderabbit", ["auth", "login", "--agent"]);
22230
22250
  } catch (err) {
22231
- resolve14({ ok: false, error: err instanceof Error ? err.message : "spawn failed" });
22251
+ resolve13({ ok: false, error: err instanceof Error ? err.message : "spawn failed" });
22232
22252
  return;
22233
22253
  }
22234
22254
  const timer = setTimeout(
@@ -22701,23 +22721,23 @@ async function reviewPullRequest(params, deps) {
22701
22721
  return report;
22702
22722
  }
22703
22723
  function defaultRunGh(args2) {
22704
- return new Promise((resolve14) => {
22724
+ return new Promise((resolve13) => {
22705
22725
  const stdout = [];
22706
22726
  const stderr = [];
22707
22727
  let proc;
22708
22728
  try {
22709
22729
  proc = (0, import_node_child_process17.spawn)("gh", args2, { stdio: ["ignore", "pipe", "pipe"] });
22710
22730
  } catch (err) {
22711
- resolve14({ code: -1, stdout: "", stderr: err instanceof Error ? err.message : String(err) });
22731
+ resolve13({ code: -1, stdout: "", stderr: err instanceof Error ? err.message : String(err) });
22712
22732
  return;
22713
22733
  }
22714
22734
  proc.stdout?.on("data", (b) => stdout.push(b));
22715
22735
  proc.stderr?.on("data", (b) => stderr.push(b));
22716
22736
  proc.on("error", (err) => {
22717
- resolve14({ code: -1, stdout: "", stderr: err.message });
22737
+ resolve13({ code: -1, stdout: "", stderr: err.message });
22718
22738
  });
22719
22739
  proc.on("close", (code) => {
22720
- resolve14({
22740
+ resolve13({
22721
22741
  code: code ?? 0,
22722
22742
  stdout: Buffer.concat(stdout).toString("utf8"),
22723
22743
  stderr: Buffer.concat(stderr).toString("utf8")
@@ -23037,7 +23057,7 @@ var import_node_fs11 = __toESM(require("fs"));
23037
23057
  var import_node_path9 = __toESM(require("path"));
23038
23058
  var import_yazl = require("yazl");
23039
23059
  function buildZip(cwd, list, outFile) {
23040
- return new Promise((resolve14, reject) => {
23060
+ return new Promise((resolve13, reject) => {
23041
23061
  const zip = new import_yazl.ZipFile();
23042
23062
  for (const f of list.files) {
23043
23063
  const abs = import_node_path9.default.join(cwd, f.rel);
@@ -23047,7 +23067,7 @@ function buildZip(cwd, list, outFile) {
23047
23067
  if (list.envExample) zip.addBuffer(Buffer.from(list.envExample), ".env.example");
23048
23068
  const out2 = import_node_fs11.default.createWriteStream(outFile, { mode: 384 });
23049
23069
  zip.outputStream.pipe(out2);
23050
- out2.on("close", () => resolve14(import_node_fs11.default.statSync(outFile).size));
23070
+ out2.on("close", () => resolve13(import_node_fs11.default.statSync(outFile).size));
23051
23071
  out2.on("error", reject);
23052
23072
  zip.outputStream.on("error", reject);
23053
23073
  zip.end();
@@ -23239,12 +23259,12 @@ async function isExecutableBinary(p2) {
23239
23259
  }
23240
23260
  }
23241
23261
  function extractTgz(tgzPath, destDir) {
23242
- return new Promise((resolve14, reject) => {
23262
+ return new Promise((resolve13, reject) => {
23243
23263
  const child = (0, import_child_process14.spawn)("tar", ["-xzf", tgzPath, "-C", destDir], { stdio: "ignore" });
23244
23264
  child.on("error", (err) => reject(err));
23245
23265
  child.on(
23246
23266
  "exit",
23247
- (code) => code === 0 ? resolve14() : reject(new Error(`tar exited with code ${code} while extracting cloudflared`))
23267
+ (code) => code === 0 ? resolve13() : reject(new Error(`tar exited with code ${code} while extracting cloudflared`))
23248
23268
  );
23249
23269
  });
23250
23270
  }
@@ -23825,17 +23845,17 @@ function expoGoDeepLink(publicUrl) {
23825
23845
  return `exps://${new URL(publicUrl).host}`;
23826
23846
  }
23827
23847
  function isExpoManifestServed(port, host2 = "127.0.0.1") {
23828
- return new Promise((resolve14) => {
23848
+ return new Promise((resolve13) => {
23829
23849
  const req = http6.get(
23830
23850
  { host: host2, port, path: "/", headers: { "expo-platform": "ios" }, timeout: 1500 },
23831
23851
  (res) => {
23832
23852
  const ok = res.statusCode !== void 0 && res.statusCode >= 200 && res.statusCode < 300;
23833
23853
  res.resume();
23834
- resolve14(ok);
23854
+ resolve13(ok);
23835
23855
  }
23836
23856
  );
23837
23857
  req.once("timeout", () => req.destroy());
23838
- req.once("error", () => resolve14(false));
23858
+ req.once("error", () => resolve13(false));
23839
23859
  });
23840
23860
  }
23841
23861
  async function waitForExpoManifest(port, opts) {
@@ -23983,12 +24003,12 @@ function describeDetectionFailure(raw) {
23983
24003
  // src/services/preview/port-ready.ts
23984
24004
  var net = __toESM(require("net"));
23985
24005
  function isPortListening(port, host2 = "127.0.0.1") {
23986
- return new Promise((resolve14) => {
24006
+ return new Promise((resolve13) => {
23987
24007
  const socket = new net.Socket();
23988
24008
  const done = (result) => {
23989
24009
  socket.removeAllListeners();
23990
24010
  socket.destroy();
23991
- resolve14(result);
24011
+ resolve13(result);
23992
24012
  };
23993
24013
  socket.setTimeout(1e3);
23994
24014
  socket.once("connect", () => done(true));
@@ -24026,14 +24046,14 @@ const { PGLiteSocketServer } = require('@electric-sql/pglite-socket');
24026
24046
  })().catch((e) => { console.error(String(e && e.message)); process.exit(1); });
24027
24047
  `;
24028
24048
  function isListening(port) {
24029
- return new Promise((resolve14) => {
24049
+ return new Promise((resolve13) => {
24030
24050
  const s = net2.connect({ host: "127.0.0.1", port }, () => {
24031
24051
  s.destroy();
24032
- resolve14(true);
24033
- }).on("error", () => resolve14(false));
24052
+ resolve13(true);
24053
+ }).on("error", () => resolve13(false));
24034
24054
  s.setTimeout(1e3, () => {
24035
24055
  s.destroy();
24036
- resolve14(false);
24056
+ resolve13(false);
24037
24057
  });
24038
24058
  });
24039
24059
  }
@@ -24081,7 +24101,7 @@ function stopChild(child) {
24081
24101
  // src/services/preview/run-setup.ts
24082
24102
  var import_child_process18 = require("child_process");
24083
24103
  function runSetupCommand(cmd, args2, cwd, env, opts) {
24084
- return new Promise((resolve14) => {
24104
+ return new Promise((resolve13) => {
24085
24105
  const child = (0, import_child_process18.spawn)(cmd, args2, {
24086
24106
  cwd,
24087
24107
  env: { ...process.env, ...env ?? {} },
@@ -24101,20 +24121,20 @@ function runSetupCommand(cmd, args2, cwd, env, opts) {
24101
24121
  settled = true;
24102
24122
  log.info("preview", `${tag}: timed out after ${opts.timeoutMs}ms \u2014 killing`);
24103
24123
  killQuiet(child);
24104
- resolve14({ status: "timeout", code: null });
24124
+ resolve13({ status: "timeout", code: null });
24105
24125
  }, opts.timeoutMs);
24106
24126
  child.once("exit", (code) => {
24107
24127
  if (settled) return;
24108
24128
  settled = true;
24109
24129
  clearTimeout(timer);
24110
- if (code === 0) resolve14({ status: "ok", code: 0 });
24111
- else resolve14({ status: "failed", code });
24130
+ if (code === 0) resolve13({ status: "ok", code: 0 });
24131
+ else resolve13({ status: "failed", code });
24112
24132
  });
24113
24133
  child.once("error", () => {
24114
24134
  if (settled) return;
24115
24135
  settled = true;
24116
24136
  clearTimeout(timer);
24117
- resolve14({ status: "failed", code: null });
24137
+ resolve13({ status: "failed", code: null });
24118
24138
  });
24119
24139
  });
24120
24140
  }
@@ -24570,23 +24590,23 @@ async function awaitTunnelRegistered(candidate, hostname3, deadlineMs) {
24570
24590
  ac.signal.addEventListener("abort", detach, { once: true });
24571
24591
  };
24572
24592
  try {
24573
- return await new Promise((resolve14) => {
24593
+ return await new Promise((resolve13) => {
24574
24594
  const onChunk = (chunk) => {
24575
24595
  const s = chunk.toString();
24576
24596
  if (!url2) url2 = parseCloudflaredUrl(s);
24577
24597
  if (TUNNEL_REGISTERED_RE.test(s)) registered = true;
24578
24598
  const trimmed = s.replace(/\n+$/g, "");
24579
24599
  if (trimmed.length > 0) log.info("preview", `cloudflared: ${trimmed}`);
24580
- if (url2 && registered) resolve14({ kind: "registered", url: url2 });
24600
+ if (url2 && registered) resolve13({ kind: "registered", url: url2 });
24581
24601
  };
24582
24602
  const onExit = (code) => {
24583
- resolve14({ kind: "exited", sawUrl: url2 != null, code });
24603
+ resolve13({ kind: "exited", sawUrl: url2 != null, code });
24584
24604
  };
24585
24605
  const { stdout, stderr } = candidate;
24586
24606
  if (stdout) scoped(() => stdout.on("data", onChunk), () => stdout.off("data", onChunk));
24587
24607
  if (stderr) scoped(() => stderr.on("data", onChunk), () => stderr.off("data", onChunk));
24588
24608
  scoped(() => candidate.on("exit", onExit), () => candidate.off("exit", onExit));
24589
- timer = setTimeout(() => resolve14({ kind: "timeout", sawUrl: url2 != null }), deadlineMs);
24609
+ timer = setTimeout(() => resolve13({ kind: "timeout", sawUrl: url2 != null }), deadlineMs);
24590
24610
  });
24591
24611
  } finally {
24592
24612
  ac.abort();
@@ -24609,7 +24629,7 @@ function verdictFor(res) {
24609
24629
  }
24610
24630
  return { adopt: true };
24611
24631
  }
24612
- var probePort = (port) => new Promise((resolve14) => {
24632
+ var probePort = (port) => new Promise((resolve13) => {
24613
24633
  const req = http7.get(
24614
24634
  { host: "127.0.0.1", port, path: "/", timeout: PROBE_TIMEOUT_MS },
24615
24635
  (res) => {
@@ -24620,16 +24640,16 @@ var probePort = (port) => new Promise((resolve14) => {
24620
24640
  });
24621
24641
  res.on(
24622
24642
  "end",
24623
- () => resolve14({ contentType: res.headers["content-type"], bodyStart: body })
24643
+ () => resolve13({ contentType: res.headers["content-type"], bodyStart: body })
24624
24644
  );
24625
- res.on("error", () => resolve14(null));
24645
+ res.on("error", () => resolve13(null));
24626
24646
  }
24627
24647
  );
24628
24648
  req.on("timeout", () => {
24629
24649
  req.destroy();
24630
- resolve14(null);
24650
+ resolve13(null);
24631
24651
  });
24632
- req.on("error", () => resolve14(null));
24652
+ req.on("error", () => resolve13(null));
24633
24653
  });
24634
24654
  async function canAdoptPort(port, probe = probePort) {
24635
24655
  try {
@@ -26044,18 +26064,18 @@ async function startInspectorProxy(opts) {
26044
26064
  clientSocket.on("error", drop2);
26045
26065
  clientSocket.on("close", drop2);
26046
26066
  });
26047
- await new Promise((resolve14, reject) => {
26067
+ await new Promise((resolve13, reject) => {
26048
26068
  server.once("error", reject);
26049
- server.listen(0, "127.0.0.1", () => resolve14());
26069
+ server.listen(0, "127.0.0.1", () => resolve13());
26050
26070
  });
26051
26071
  const port = server.address().port;
26052
26072
  return {
26053
26073
  port,
26054
- close: () => new Promise((resolve14) => {
26074
+ close: () => new Promise((resolve13) => {
26055
26075
  for (const socket of upgraded) socket.destroy();
26056
26076
  upgraded.clear();
26057
26077
  server.closeAllConnections?.();
26058
- server.close(() => resolve14());
26078
+ server.close(() => resolve13());
26059
26079
  })
26060
26080
  };
26061
26081
  }
@@ -27139,12 +27159,12 @@ var _spawnSeam = {
27139
27159
  run: _defaultSpawn
27140
27160
  };
27141
27161
  function _defaultSpawn(binaryPath, args2, opts) {
27142
- return new Promise((resolve14) => {
27162
+ return new Promise((resolve13) => {
27143
27163
  let proc;
27144
27164
  try {
27145
27165
  proc = (0, import_child_process21.spawn)(binaryPath, args2, { cwd: opts.cwd, env: opts.env });
27146
27166
  } catch (err) {
27147
- resolve14({ code: -1, stdout: "", stderr: err.message });
27167
+ resolve13({ code: -1, stdout: "", stderr: err.message });
27148
27168
  return;
27149
27169
  }
27150
27170
  let stdout = "";
@@ -27155,8 +27175,8 @@ function _defaultSpawn(binaryPath, args2, opts) {
27155
27175
  proc.stderr?.on("data", (c2) => {
27156
27176
  stderr += c2.toString();
27157
27177
  });
27158
- proc.on("error", (err) => resolve14({ code: -1, stdout, stderr: err.message }));
27159
- proc.on("close", (code) => resolve14({ code: code ?? -1, stdout, stderr }));
27178
+ proc.on("error", (err) => resolve13({ code: -1, stdout, stderr: err.message }));
27179
+ proc.on("close", (code) => resolve13({ code: code ?? -1, stdout, stderr }));
27160
27180
  });
27161
27181
  }
27162
27182
  var _adapterSeam = {
@@ -27200,7 +27220,7 @@ var BdAdapter = class {
27200
27220
  * exit codes — note bd exits 0 even for some error states (e.g. "no beads
27201
27221
  * database found"), so JSON-parsing callers must also inspect the payload.
27202
27222
  */
27203
- async run(args2) {
27223
+ async run(args2, runOpts = {}) {
27204
27224
  const binary = this.resolveBinary();
27205
27225
  if (!binary) {
27206
27226
  return { code: -1, stdout: "", stderr: "bd binary not resolved" };
@@ -27215,16 +27235,14 @@ var BdAdapter = class {
27215
27235
  }
27216
27236
  env.BEADS_DOLT_SHARED_SERVER = "1";
27217
27237
  delete env.BEADS_DIR;
27218
- log.trace(
27219
- "beads",
27220
- `bd ${args2.join(" ")} (cwd=${this.opts.cwd ?? process.cwd()}, shared-server)`
27221
- );
27222
- let res = await _spawnSeam.run(binary, args2, { cwd: this.opts.cwd, env });
27238
+ const cwd = runOpts.cwd ?? this.opts.cwd;
27239
+ log.trace("beads", `bd ${args2.join(" ")} (cwd=${cwd ?? process.cwd()}, shared-server)`);
27240
+ let res = await _spawnSeam.run(binary, args2, { cwd, env });
27223
27241
  const TRANSIENT_SPAWN = /ENOENT|ETXTBSY/;
27224
27242
  for (let attempt = 1; attempt <= 5 && res.code === -1 && TRANSIENT_SPAWN.test(res.stderr); attempt++) {
27225
27243
  log.info("beads", `bd ${args2[0]} transient spawn failure (binary busy) \u2014 retry ${attempt}/5`);
27226
27244
  await _adapterSeam.sleep(750 * attempt);
27227
- res = await _spawnSeam.run(binary, args2, { cwd: this.opts.cwd, env });
27245
+ res = await _spawnSeam.run(binary, args2, { cwd, env });
27228
27246
  }
27229
27247
  return res;
27230
27248
  }
@@ -27333,22 +27351,22 @@ var _installSpawnSeam = {
27333
27351
  run: _defaultInstallSpawn
27334
27352
  };
27335
27353
  function _defaultInstallSpawn(strategy) {
27336
- return new Promise((resolve14) => {
27354
+ return new Promise((resolve13) => {
27337
27355
  let proc;
27338
27356
  try {
27339
27357
  proc = (0, import_child_process22.spawn)(strategy.command, strategy.args, { env: process.env });
27340
27358
  } catch (err) {
27341
- resolve14({ ok: false, code: -1, stderr: err.message });
27359
+ resolve13({ ok: false, code: -1, stderr: err.message });
27342
27360
  return;
27343
27361
  }
27344
27362
  let stderr = "";
27345
27363
  proc.stderr?.on("data", (c2) => {
27346
27364
  stderr += c2.toString();
27347
27365
  });
27348
- proc.on("error", (err) => resolve14({ ok: false, code: -1, stderr: err.message }));
27366
+ proc.on("error", (err) => resolve13({ ok: false, code: -1, stderr: err.message }));
27349
27367
  proc.on(
27350
27368
  "close",
27351
- (code) => resolve14({ ok: code === 0, code: code ?? -1, stderr })
27369
+ (code) => resolve13({ ok: code === 0, code: code ?? -1, stderr })
27352
27370
  );
27353
27371
  });
27354
27372
  }
@@ -27517,14 +27535,14 @@ var _doltInstallSpawnSeam = {
27517
27535
  };
27518
27536
  var DOLT_INSTALL_TIMEOUT_MS = 12e4;
27519
27537
  function _defaultDoltInstallSpawn(strategy) {
27520
- return new Promise((resolve14) => {
27538
+ return new Promise((resolve13) => {
27521
27539
  let settled = false;
27522
27540
  let timer;
27523
27541
  const finish = (r) => {
27524
27542
  if (settled) return;
27525
27543
  settled = true;
27526
27544
  if (timer) clearTimeout(timer);
27527
- resolve14(r);
27545
+ resolve13(r);
27528
27546
  };
27529
27547
  let proc;
27530
27548
  try {
@@ -27667,7 +27685,15 @@ var _provisionSeam = {
27667
27685
  /** Silence bd's `beads.role not configured` warning. */
27668
27686
  setGitBeadsRole,
27669
27687
  /** Does the project's git remote carry Dolt data (`refs/dolt/data`)? */
27670
- remoteHasDoltData
27688
+ remoteHasDoltData,
27689
+ /** Throwaway cwd for a user-level-only `bd setup` (see GLOBAL_ONLY_RECIPES). */
27690
+ makeSetupCwd: () => fs59.mkdtempSync(path67.join(os41.tmpdir(), "codeam-bd-setup-")),
27691
+ removeSetupCwd: (dir) => {
27692
+ try {
27693
+ fs59.rmSync(dir, { recursive: true, force: true });
27694
+ } catch {
27695
+ }
27696
+ }
27671
27697
  };
27672
27698
  function remoteHasDoltData(cwd) {
27673
27699
  try {
@@ -27944,15 +27970,17 @@ async function projectDbReachable(bd) {
27944
27970
  async function setupAgents(bd, agents) {
27945
27971
  const wired = [];
27946
27972
  for (const recipe of dedupeRecipes(agents)) {
27973
+ const scratchCwd = GLOBAL_ONLY_RECIPES.has(recipe) ? _provisionSeam.makeSetupCwd() : null;
27974
+ const runOpts = scratchCwd ? { cwd: scratchCwd } : {};
27947
27975
  try {
27948
- const check = await bd.run(["setup", recipe, "--global", "--check"]);
27976
+ const check = await bd.run(["setup", recipe, "--global", "--check"], runOpts);
27949
27977
  if (check.code === 0) {
27950
27978
  log.trace("beads", `bd setup ${recipe} --global already installed \u2014 skipping`);
27951
27979
  wired.push(recipe);
27952
27980
  continue;
27953
27981
  }
27954
27982
  log.info("beads", `wiring agent natively: bd setup ${recipe} --global`);
27955
- const setup = await bd.run(["setup", recipe, "--global"]);
27983
+ const setup = await bd.run(["setup", recipe, "--global"], runOpts);
27956
27984
  if (setup.code === 0) {
27957
27985
  wired.push(recipe);
27958
27986
  } else {
@@ -27963,10 +27991,13 @@ async function setupAgents(bd, agents) {
27963
27991
  }
27964
27992
  } catch (err) {
27965
27993
  log.warn("beads", `bd setup ${recipe} --global threw (non-fatal)`, err);
27994
+ } finally {
27995
+ if (scratchCwd) _provisionSeam.removeSetupCwd(scratchCwd);
27966
27996
  }
27967
27997
  }
27968
27998
  return wired;
27969
27999
  }
28000
+ var GLOBAL_ONLY_RECIPES = /* @__PURE__ */ new Set(["claude", "codex", "gemini"]);
27970
28001
  function dedupeRecipes(agents) {
27971
28002
  const seen2 = /* @__PURE__ */ new Set();
27972
28003
  for (const agent of agents) {
@@ -29372,7 +29403,7 @@ function sweepStaleCliStagingDirs(nodeModulesDir, now = Date.now(), deps) {
29372
29403
  if (!nodeModulesDir) return 0;
29373
29404
  const readdirSync18 = deps?.readdirSync ?? fs65.readdirSync;
29374
29405
  const statSync17 = deps?.statSync ?? fs65.statSync;
29375
- const rmSync14 = deps?.rmSync ?? fs65.rmSync;
29406
+ const rmSync15 = deps?.rmSync ?? fs65.rmSync;
29376
29407
  let removed = 0;
29377
29408
  let entries2;
29378
29409
  try {
@@ -29386,7 +29417,7 @@ function sweepStaleCliStagingDirs(nodeModulesDir, now = Date.now(), deps) {
29386
29417
  try {
29387
29418
  const st3 = statSync17(full);
29388
29419
  if (now - st3.mtimeMs < STALE_STAGING_AGE_MS) continue;
29389
- rmSync14(full, { recursive: true, force: true });
29420
+ rmSync15(full, { recursive: true, force: true });
29390
29421
  removed++;
29391
29422
  } catch {
29392
29423
  }
@@ -29407,16 +29438,16 @@ async function runNpmInstallLatest() {
29407
29438
  const invocation = buildNpmInstallInvocation({ sudo: useSudo });
29408
29439
  const useShell = process.platform === "win32";
29409
29440
  const command2 = useShell && invocation.command.includes(" ") ? `"${invocation.command}"` : invocation.command;
29410
- const result = await new Promise((resolve14) => {
29441
+ const result = await new Promise((resolve13) => {
29411
29442
  (0, import_child_process25.execFile)(
29412
29443
  command2,
29413
29444
  invocation.args,
29414
29445
  { timeout: CLI_UPDATE_INSTALL_TIMEOUT_MS, shell: useShell },
29415
29446
  (err, _stdout, stderr) => {
29416
29447
  if (!err) {
29417
- resolve14({ ok: true });
29448
+ resolve13({ ok: true });
29418
29449
  } else {
29419
- resolve14({ ok: false, error: (stderr || err.message).slice(0, 300) });
29450
+ resolve13({ ok: false, error: (stderr || err.message).slice(0, 300) });
29420
29451
  }
29421
29452
  }
29422
29453
  );
@@ -29769,8 +29800,8 @@ async function runDetectOneShot(generate, timeoutMs = PREVIEW_DETECT_TIMEOUT_MS)
29769
29800
  };
29770
29801
  const onFailedOutput = (stdout) => onStderr(`
29771
29802
  ${stdout}`);
29772
- const deadline = new Promise((resolve14) => {
29773
- timer = setTimeout(() => resolve14({ raw: null, timedOut: true, stderr }), timeoutMs);
29803
+ const deadline = new Promise((resolve13) => {
29804
+ timer = setTimeout(() => resolve13({ raw: null, timedOut: true, stderr }), timeoutMs);
29774
29805
  timer.unref?.();
29775
29806
  });
29776
29807
  const oneShot = generate(PREVIEW_DETECT_PROMPT, { timeoutMs, onStderr, onFailedOutput }).then(
@@ -30238,7 +30269,7 @@ function buildKeepAlive(ctx) {
30238
30269
  let timer = null;
30239
30270
  async function setIdleTimeout(minutes) {
30240
30271
  if (!ctx.inCodespace || !ctx.codespaceName) return;
30241
- await new Promise((resolve14) => {
30272
+ await new Promise((resolve13) => {
30242
30273
  const proc = (0, import_child_process26.spawn)(
30243
30274
  "gh",
30244
30275
  [
@@ -30252,8 +30283,8 @@ function buildKeepAlive(ctx) {
30252
30283
  { stdio: "ignore", detached: true }
30253
30284
  );
30254
30285
  proc.unref();
30255
- proc.on("exit", () => resolve14());
30256
- proc.on("error", () => resolve14());
30286
+ proc.on("exit", () => resolve13());
30287
+ proc.on("error", () => resolve13());
30257
30288
  });
30258
30289
  }
30259
30290
  return {
@@ -31210,10 +31241,10 @@ function augmentKimiPath() {
31210
31241
  }
31211
31242
  var augmentPath2 = augmentKimiPath;
31212
31243
  async function runInstaller2() {
31213
- return new Promise((resolve14) => {
31244
+ return new Promise((resolve13) => {
31214
31245
  const proc = (0, import_node_child_process25.spawn)("sh", ["-c", `curl -fsSL ${INSTALL_URL2} | bash`], { stdio: "inherit" });
31215
- proc.on("close", (code) => resolve14(code === 0));
31216
- proc.on("error", () => resolve14(false));
31246
+ proc.on("close", (code) => resolve13(code === 0));
31247
+ proc.on("error", () => resolve13(false));
31217
31248
  });
31218
31249
  }
31219
31250
  async function ensureKimiInstalled() {
@@ -31263,10 +31294,10 @@ function augmentOpencodePath() {
31263
31294
  }
31264
31295
  var augmentPath3 = augmentOpencodePath;
31265
31296
  async function runInstaller3() {
31266
- return new Promise((resolve14) => {
31297
+ return new Promise((resolve13) => {
31267
31298
  const proc = (0, import_node_child_process26.spawn)("sh", ["-c", `curl -fsSL ${INSTALL_URL3} | bash`], { stdio: "inherit" });
31268
- proc.on("close", (code) => resolve14(code === 0));
31269
- proc.on("error", () => resolve14(false));
31299
+ proc.on("close", (code) => resolve13(code === 0));
31300
+ proc.on("error", () => resolve13(false));
31270
31301
  });
31271
31302
  }
31272
31303
  async function ensureOpencodeInstalled() {
@@ -31474,11 +31505,11 @@ async function resolveAcpAdapterWithRetry(agent, opts = {}) {
31474
31505
  const timeoutMs = opts.timeoutMs ?? DEFAULT_ADAPTER_RETRY_TIMEOUT_MS;
31475
31506
  const pollMs = opts.pollMs ?? DEFAULT_ADAPTER_RETRY_POLL_MS;
31476
31507
  const now = opts.now ?? Date.now;
31477
- const sleep5 = opts.sleep ?? ((ms) => new Promise((resolve15) => setTimeout(resolve15, ms)));
31478
- const resolve14 = opts.resolve ?? getAcpAdapter;
31508
+ const sleep5 = opts.sleep ?? ((ms) => new Promise((resolve14) => setTimeout(resolve14, ms)));
31509
+ const resolve13 = opts.resolve ?? getAcpAdapter;
31479
31510
  const attempt = () => {
31480
31511
  try {
31481
- return resolve14(agent);
31512
+ return resolve13(agent);
31482
31513
  } catch {
31483
31514
  return null;
31484
31515
  }
@@ -31709,7 +31740,7 @@ function parseJsonl(filePath) {
31709
31740
  return messages;
31710
31741
  }
31711
31742
  function postWithStatus(endpoint, body, pluginAuthToken) {
31712
- return new Promise((resolve14) => {
31743
+ return new Promise((resolve13) => {
31713
31744
  const payload = JSON.stringify(body);
31714
31745
  const u2 = new URL(`${API_BASE7}${endpoint}`);
31715
31746
  const transport = u2.protocol === "https:" ? https6 : http10;
@@ -31740,17 +31771,17 @@ function postWithStatus(endpoint, body, pluginAuthToken) {
31740
31771
  const ra = Number(res.headers["retry-after"]);
31741
31772
  retryAfterMs = Number.isFinite(ra) && ra > 0 ? ra * 1e3 : 2e4;
31742
31773
  }
31743
- resolve14({ ok, status: status2, retryAfterMs });
31774
+ resolve13({ ok, status: status2, retryAfterMs });
31744
31775
  }
31745
31776
  );
31746
31777
  req.on("error", (err) => {
31747
31778
  log.warn("history:post", `${endpoint} network error`, err);
31748
- resolve14({ ok: false, status: null, retryAfterMs: null });
31779
+ resolve13({ ok: false, status: null, retryAfterMs: null });
31749
31780
  });
31750
31781
  req.on("timeout", () => {
31751
31782
  log.warn("history:post", `${endpoint} timeout after 15s`);
31752
31783
  req.destroy();
31753
- resolve14({ ok: false, status: null, retryAfterMs: null });
31784
+ resolve13({ ok: false, status: null, retryAfterMs: null });
31754
31785
  });
31755
31786
  req.write(payload);
31756
31787
  req.end();
@@ -34324,12 +34355,12 @@ var Connection = class {
34324
34355
  const id = this.nextRequestId++;
34325
34356
  let cancel = () => {
34326
34357
  };
34327
- const responsePromise = new Promise((resolve14, reject) => {
34358
+ const responsePromise = new Promise((resolve13, reject) => {
34328
34359
  const pendingResponse = {
34329
34360
  resolve: (response) => {
34330
34361
  try {
34331
34362
  const value = mapResponse ? mapResponse(response) : response;
34332
- resolve14(value);
34363
+ resolve13(value);
34333
34364
  } catch (error) {
34334
34365
  reject(error);
34335
34366
  }
@@ -34407,8 +34438,8 @@ var Connection = class {
34407
34438
  initialize(stream, handlers2) {
34408
34439
  this.stream = stream;
34409
34440
  this.staticHandlers = handlers2;
34410
- this.closedPromise = new Promise((resolve14) => {
34411
- this.abortController.signal.addEventListener("abort", () => resolve14());
34441
+ this.closedPromise = new Promise((resolve13) => {
34442
+ this.abortController.signal.addEventListener("abort", () => resolve13());
34412
34443
  });
34413
34444
  void this.receive();
34414
34445
  }
@@ -35196,8 +35227,8 @@ var AsyncQueue = class {
35196
35227
  if (this.failed) {
35197
35228
  return Promise.reject(this.failure);
35198
35229
  }
35199
- return new Promise((resolve14, reject) => {
35200
- this.waiters.push({ resolve: resolve14, reject });
35230
+ return new Promise((resolve13, reject) => {
35231
+ this.waiters.push({ resolve: resolve13, reject });
35201
35232
  });
35202
35233
  }
35203
35234
  };
@@ -36637,7 +36668,10 @@ var AcpClient = class {
36637
36668
  const joined = parts.join(" ");
36638
36669
  return TRANSIENT_ADAPTER_SPAWN_RE.test(joined) || ADAPTER_MODULE_LOAD_ERROR_RE.test(joined) || // The transport dying mid-handshake = the adapter crashed starting up,
36639
36670
  // even when the child-exit handler lost the race (see the RE's doc).
36640
- TRANSPORT_DOWN_DURING_START_RE.test(joined);
36671
+ TRANSPORT_DOWN_DURING_START_RE.test(joined) || // codex-acp stays up but its `codex app-server` child lost the first-run
36672
+ // ~/.codex SQLite migration race to another codex process; a respawn
36673
+ // opens the DBs the winner migrated (see state-runtime-race.ts).
36674
+ CODEX_STATE_RUNTIME_RACE_RE.test(joined);
36641
36675
  }
36642
36676
  async startOnce() {
36643
36677
  if (this.child) throw new Error("AcpClient already started");
@@ -36889,7 +36923,7 @@ var AcpClient = class {
36889
36923
  this.pendingToolCalls.clear();
36890
36924
  try {
36891
36925
  const result = await Promise.race([send, idle.promise]);
36892
- await new Promise((resolve14) => setImmediate(resolve14));
36926
+ await new Promise((resolve13) => setImmediate(resolve13));
36893
36927
  log.info(
36894
36928
  "acpClient",
36895
36929
  `prompt \u2190 ok stopReason=${result.stopReason ?? "?"} elapsedMs=${Date.now() - t0}`
@@ -37105,8 +37139,8 @@ var AcpClient = class {
37105
37139
  if (!this.connection || !this.sessionId) return "deferred";
37106
37140
  this.mcpReprovisionPending = servers;
37107
37141
  if (this.mcpDebounceTimer) clearTimeout(this.mcpDebounceTimer);
37108
- const settled = new Promise((resolve14) => {
37109
- this.mcpDebounceWaiters.push(resolve14);
37142
+ const settled = new Promise((resolve13) => {
37143
+ this.mcpDebounceWaiters.push(resolve13);
37110
37144
  });
37111
37145
  this.mcpDebounceTimer = setTimeout(() => {
37112
37146
  this.mcpDebounceTimer = null;
@@ -37350,15 +37384,15 @@ var AcpClient = class {
37350
37384
  } else {
37351
37385
  child.kill("SIGTERM");
37352
37386
  }
37353
- const grace = new Promise((resolve14) => {
37387
+ const grace = new Promise((resolve13) => {
37354
37388
  const t2 = setTimeout(() => {
37355
37389
  if (process.platform !== "win32" && pid) killQuiet(-pid, "SIGKILL");
37356
37390
  else killQuiet(child, "SIGKILL");
37357
- resolve14();
37391
+ resolve13();
37358
37392
  }, 2e3);
37359
37393
  child.once("exit", () => {
37360
37394
  clearTimeout(t2);
37361
- resolve14();
37395
+ resolve13();
37362
37396
  });
37363
37397
  });
37364
37398
  await grace;
@@ -37587,7 +37621,7 @@ var os52 = __toESM(require("os"));
37587
37621
  function runAgentInstallScript(script, opts = {}) {
37588
37622
  const timeoutMs = opts.timeoutMs ?? 18e4;
37589
37623
  const scope = opts.logScope ?? "agent-install";
37590
- return new Promise((resolve14) => {
37624
+ return new Promise((resolve13) => {
37591
37625
  const home = process.env.HOME || os52.homedir();
37592
37626
  const child = (0, import_child_process27.spawn)("sh", ["-c", script], {
37593
37627
  env: { ...process.env, HOME: home },
@@ -37603,7 +37637,7 @@ function runAgentInstallScript(script, opts = {}) {
37603
37637
  const done = (result) => {
37604
37638
  if (settled) return;
37605
37639
  settled = true;
37606
- resolve14(result);
37640
+ resolve13(result);
37607
37641
  };
37608
37642
  const timer = setTimeout(() => {
37609
37643
  log.warn(scope, `agent install timed out (${Math.round(timeoutMs / 1e3)}s)`);
@@ -38216,7 +38250,7 @@ var _transport4 = {
38216
38250
  get: _get
38217
38251
  };
38218
38252
  function _post3(url2, headers, payload) {
38219
- return new Promise((resolve14, reject) => {
38253
+ return new Promise((resolve13, reject) => {
38220
38254
  let settled = false;
38221
38255
  const u2 = new URL(url2);
38222
38256
  const lib = u2.protocol === "https:" ? https7 : http11;
@@ -38241,7 +38275,7 @@ function _post3(url2, headers, payload) {
38241
38275
  res.on("end", () => {
38242
38276
  if (settled) return;
38243
38277
  settled = true;
38244
- resolve14({ statusCode: res.statusCode ?? 0, body });
38278
+ resolve13({ statusCode: res.statusCode ?? 0, body });
38245
38279
  });
38246
38280
  }
38247
38281
  );
@@ -38258,7 +38292,7 @@ function _post3(url2, headers, payload) {
38258
38292
  });
38259
38293
  }
38260
38294
  function _get(url2, headers) {
38261
- return new Promise((resolve14, reject) => {
38295
+ return new Promise((resolve13, reject) => {
38262
38296
  let settled = false;
38263
38297
  const u2 = new URL(url2);
38264
38298
  const lib = u2.protocol === "https:" ? https7 : http11;
@@ -38282,7 +38316,7 @@ function _get(url2, headers) {
38282
38316
  res.on("end", () => {
38283
38317
  if (settled) return;
38284
38318
  settled = true;
38285
- resolve14({ statusCode: res.statusCode ?? 0, body });
38319
+ resolve13({ statusCode: res.statusCode ?? 0, body });
38286
38320
  });
38287
38321
  }
38288
38322
  );
@@ -39513,12 +39547,12 @@ function runGit3(cwd, args2) {
39513
39547
  return _runGitImpl2.run(cwd, args2);
39514
39548
  }
39515
39549
  function defaultRunGit(cwd, args2) {
39516
- return new Promise((resolve14) => {
39550
+ return new Promise((resolve13) => {
39517
39551
  let proc;
39518
39552
  try {
39519
39553
  proc = (0, import_child_process29.spawn)("git", args2, { cwd, env: process.env });
39520
39554
  } catch {
39521
- resolve14(null);
39555
+ resolve13(null);
39522
39556
  return;
39523
39557
  }
39524
39558
  let stdout = "";
@@ -39529,16 +39563,16 @@ function defaultRunGit(cwd, args2) {
39529
39563
  proc.stderr?.on("data", (c2) => {
39530
39564
  stderr += c2.toString();
39531
39565
  });
39532
- proc.on("error", () => resolve14(null));
39566
+ proc.on("error", () => resolve13(null));
39533
39567
  proc.on("close", (code) => {
39534
39568
  if (code === 0) {
39535
- resolve14(stdout);
39569
+ resolve13(stdout);
39536
39570
  } else {
39537
39571
  log.trace(
39538
39572
  "turnFiles",
39539
39573
  `git ${args2.join(" ")} exited ${code} stderr=${stderr.slice(0, 200)}`
39540
39574
  );
39541
- resolve14(null);
39575
+ resolve13(null);
39542
39576
  }
39543
39577
  });
39544
39578
  });
@@ -39955,25 +39989,25 @@ function baselineKey(entry) {
39955
39989
 
39956
39990
  // src/agents/acp/withTimeout.ts
39957
39991
  function withTimeout(p2, ms) {
39958
- return new Promise((resolve14) => {
39992
+ return new Promise((resolve13) => {
39959
39993
  let settled = false;
39960
39994
  const timer = setTimeout(() => {
39961
39995
  if (settled) return;
39962
39996
  settled = true;
39963
- resolve14(void 0);
39997
+ resolve13(void 0);
39964
39998
  }, ms);
39965
39999
  p2.then(
39966
40000
  (v) => {
39967
40001
  if (settled) return;
39968
40002
  settled = true;
39969
40003
  clearTimeout(timer);
39970
- resolve14(v);
40004
+ resolve13(v);
39971
40005
  },
39972
40006
  () => {
39973
40007
  if (settled) return;
39974
40008
  settled = true;
39975
40009
  clearTimeout(timer);
39976
- resolve14(void 0);
40010
+ resolve13(void 0);
39977
40011
  }
39978
40012
  );
39979
40013
  });
@@ -40142,7 +40176,7 @@ function isProcessMidTurn(pid, home) {
40142
40176
  var import_node_child_process28 = require("child_process");
40143
40177
  var fs80 = __toESM(require("fs"));
40144
40178
  var path90 = __toESM(require("path"));
40145
- var defaultCommandRunner = (file, args2, cwd, timeoutMs, env) => new Promise((resolve14) => {
40179
+ var defaultCommandRunner = (file, args2, cwd, timeoutMs, env) => new Promise((resolve13) => {
40146
40180
  (0, import_node_child_process28.execFile)(
40147
40181
  file,
40148
40182
  args2,
@@ -40158,7 +40192,7 @@ var defaultCommandRunner = (file, args2, cwd, timeoutMs, env) => new Promise((re
40158
40192
  const rawCode = err.code;
40159
40193
  code = typeof rawCode === "number" ? rawCode : 1;
40160
40194
  }
40161
- resolve14({ code, stdout: stdout ?? "", stderr: stderr ?? "" });
40195
+ resolve13({ code, stdout: stdout ?? "", stderr: stderr ?? "" });
40162
40196
  }
40163
40197
  );
40164
40198
  });
@@ -41800,24 +41834,24 @@ var AgentPreviewBridge = class {
41800
41834
  * preview tools are then simply absent, never a failed session. */
41801
41835
  listen() {
41802
41836
  if (this.listening) return this.listening;
41803
- this.listening = new Promise((resolve14) => {
41837
+ this.listening = new Promise((resolve13) => {
41804
41838
  const server = http12.createServer((req, res) => {
41805
41839
  void this.handle(req, res);
41806
41840
  });
41807
41841
  server.on("error", (err) => {
41808
41842
  log.warn("agent-preview", `bridge failed to listen: ${String(err)}`);
41809
- resolve14(null);
41843
+ resolve13(null);
41810
41844
  });
41811
41845
  server.listen(0, "127.0.0.1", () => {
41812
41846
  const addr = server.address();
41813
41847
  if (!addr || typeof addr === "string") {
41814
- resolve14(null);
41848
+ resolve13(null);
41815
41849
  return;
41816
41850
  }
41817
41851
  server.unref();
41818
41852
  this.server = server;
41819
41853
  this.bound = { url: `http://127.0.0.1:${addr.port}`, token: this.token };
41820
- resolve14(this.bound);
41854
+ resolve13(this.bound);
41821
41855
  });
41822
41856
  });
41823
41857
  return this.listening;
@@ -41854,9 +41888,9 @@ var AgentPreviewBridge = class {
41854
41888
  }
41855
41889
  const inflight = this.inflight;
41856
41890
  let timer;
41857
- const pending2 = new Promise((resolve14) => {
41891
+ const pending2 = new Promise((resolve13) => {
41858
41892
  timer = setTimeout(
41859
- () => resolve14({
41893
+ () => resolve13({
41860
41894
  status: "starting",
41861
41895
  message: "The preview is still coming up (dependencies or a slow dev server). It keeps going in the background \u2014 call preview_status in a minute."
41862
41896
  }),
@@ -42059,7 +42093,7 @@ function authorized(header, token) {
42059
42093
  return presented.length === expected.length && (0, import_node_crypto14.timingSafeEqual)(presented, expected);
42060
42094
  }
42061
42095
  function readJson(req) {
42062
- return new Promise((resolve14, reject) => {
42096
+ return new Promise((resolve13, reject) => {
42063
42097
  let raw = "";
42064
42098
  req.setEncoding("utf8");
42065
42099
  req.on("data", (chunk) => {
@@ -42070,10 +42104,10 @@ function readJson(req) {
42070
42104
  }
42071
42105
  });
42072
42106
  req.on("end", () => {
42073
- if (!raw) return resolve14({});
42107
+ if (!raw) return resolve13({});
42074
42108
  try {
42075
42109
  const parsed = JSON.parse(raw);
42076
- resolve14(parsed && typeof parsed === "object" ? parsed : {});
42110
+ resolve13(parsed && typeof parsed === "object" ? parsed : {});
42077
42111
  } catch {
42078
42112
  reject(new Error("invalid JSON"));
42079
42113
  }
@@ -42270,6 +42304,28 @@ function buildAcpPromptBlocks(payload) {
42270
42304
  return blocks;
42271
42305
  }
42272
42306
 
42307
+ // src/agents/acp/reply-language.ts
42308
+ var hinted = /* @__PURE__ */ new Set();
42309
+ function replyLanguageName(locale) {
42310
+ if (typeof locale !== "string" || locale.trim().length === 0) return null;
42311
+ try {
42312
+ const language = new Intl.Locale(locale.trim().replace(/_/g, "-")).language;
42313
+ if (!language || language === "en" || language === "und") return null;
42314
+ const name = new Intl.DisplayNames(["en"], { type: "language" }).of(language);
42315
+ return name && name.toLowerCase() !== language ? name : null;
42316
+ } catch {
42317
+ return null;
42318
+ }
42319
+ }
42320
+ function replyLanguageContextOnce(locale, sessionId, agent) {
42321
+ const language = replyLanguageName(locale);
42322
+ if (!language) return null;
42323
+ const key = `${sessionId}:${agent}`;
42324
+ if (hinted.has(key)) return null;
42325
+ hinted.add(key);
42326
+ return `The user's device language is ${language}. Reply in ${language} unless the user writes in another language.`;
42327
+ }
42328
+
42273
42329
  // src/agents/acp/promptEcho.ts
42274
42330
  var MAX_PROMPT_CHARS = 200;
42275
42331
  var MAX_AGENT_REPLY_CHARS = 280;
@@ -42300,7 +42356,20 @@ function formatAgentReplyLine(text) {
42300
42356
  function assembleAcpCommandContext(session, cmd) {
42301
42357
  return { ...session, cmd };
42302
42358
  }
42303
- var ACP_QUICK_REPLIES = ["Continue", "Yes, go ahead", "Explain"];
42359
+ function quickRepliesForTurn(replyText, stopReason) {
42360
+ if (stopReason === "max_tokens" || stopReason === "max_turn_requests") return ["Continue"];
42361
+ return endsWithYesNoQuestion(replyText) ? ["Yes, go ahead", "No"] : [];
42362
+ }
42363
+ var YES_NO_LEAD_RE = /^(?:so|ok(?:ay)?|great|alright|then|now)?[,\s]*(?:shall|should|do|does|did|would|will|can|could|may|is|are|was|want|ready|sound|sounds|ok(?:ay)?|proceed|go ahead)\b/i;
42364
+ function endsWithYesNoQuestion(replyText) {
42365
+ const text = replyText.replace(/[*_`]/g, "").trimEnd();
42366
+ if (!text.endsWith("?")) return false;
42367
+ const body = text.slice(0, -1);
42368
+ const start2 = Math.max(body.lastIndexOf("\n"), body.lastIndexOf(". "), body.lastIndexOf("! "), body.lastIndexOf("? "));
42369
+ const question = body.slice(start2 + 1).trim();
42370
+ if (/\bor\b/i.test(question)) return false;
42371
+ return YES_NO_LEAD_RE.test(question);
42372
+ }
42304
42373
  async function recoverFromFailedTurn(client3, streaming) {
42305
42374
  await cancelStuckTurn(client3);
42306
42375
  await streaming.closeAll();
@@ -42600,6 +42669,8 @@ async function startTaskH(ctx) {
42600
42669
  ctx.history.appendUserPrompt(promptText);
42601
42670
  maybePrefaceAgentStandard(blocks, opts.agent, opts.sessionId);
42602
42671
  const squadContext = collectSquadContext(ctx);
42672
+ const languageContext = replyLanguageContextOnce(payload?.locale, opts.sessionId, opts.agent);
42673
+ if (languageContext) squadContext.push(languageContext);
42603
42674
  applySquadContext(blocks, squadContext, squadContextMode(ctx));
42604
42675
  ctx.squad?.resetHops();
42605
42676
  let turnBlocks = blocks;
@@ -42728,7 +42799,7 @@ async function startTaskH(ctx) {
42728
42799
  }
42729
42800
  void publisher.publishOutput({
42730
42801
  type: "input_suggestion",
42731
- content: ACP_QUICK_REPLIES,
42802
+ content: quickRepliesForTurn(cleanText, reply.stopReason),
42732
42803
  done: true
42733
42804
  });
42734
42805
  log.info(
@@ -43200,15 +43271,15 @@ async function prewarmNewMcpEntries(manifest, previousIds) {
43200
43271
  );
43201
43272
  await Promise.all(
43202
43273
  fresh.map(
43203
- (e) => new Promise((resolve14) => {
43274
+ (e) => new Promise((resolve13) => {
43204
43275
  const mcp = e.delivery.mcp;
43205
43276
  const child = (0, import_node_child_process29.execFile)(
43206
43277
  mcp.command,
43207
43278
  [...mcp.args, "--help"],
43208
43279
  { timeout: 9e4 },
43209
- () => resolve14()
43280
+ () => resolve13()
43210
43281
  );
43211
- child.on("error", () => resolve14());
43282
+ child.on("error", () => resolve13());
43212
43283
  })
43213
43284
  )
43214
43285
  );
@@ -43475,7 +43546,7 @@ var StreamingState = class {
43475
43546
  * protested "J'ai rien refusé". The line is the user's evidence.
43476
43547
  */
43477
43548
  registerPermission(args2) {
43478
- return new Promise((resolve14) => {
43549
+ return new Promise((resolve13) => {
43479
43550
  const timeoutTimer = setTimeout(() => {
43480
43551
  if (this.pending?.kind === "permission" && this.pending.questionId === args2.questionId) {
43481
43552
  log.warn(
@@ -43488,14 +43559,14 @@ var StreamingState = class {
43488
43559
  content: permissionExpiredNotice(),
43489
43560
  done: true
43490
43561
  });
43491
- resolve14({ outcome: { outcome: "cancelled" } });
43562
+ resolve13({ outcome: { outcome: "cancelled" } });
43492
43563
  }
43493
43564
  }, PERMISSION_TIMEOUT_MS);
43494
43565
  this.setPending({
43495
43566
  kind: "permission",
43496
43567
  questionId: args2.questionId,
43497
43568
  options: args2.options,
43498
- resolve: resolve14,
43569
+ resolve: resolve13,
43499
43570
  timeoutTimer
43500
43571
  });
43501
43572
  });
@@ -43532,14 +43603,14 @@ var StreamingState = class {
43532
43603
  const byId = optionId ? this.pending.options.find((o) => o.optionId === optionId) : void 0;
43533
43604
  const picked = byId ?? this.pending.options[index];
43534
43605
  clearTimeout(this.pending.timeoutTimer);
43535
- const resolve14 = this.pending.resolve;
43606
+ const resolve13 = this.pending.resolve;
43536
43607
  this.setPending(null);
43537
43608
  if (!picked) {
43538
43609
  log.warn("acpRunner", `select_option index=${index} out of bounds \u2014 cancel`);
43539
- resolve14({ outcome: { outcome: "cancelled" } });
43610
+ resolve13({ outcome: { outcome: "cancelled" } });
43540
43611
  return { kind: "resolved", optionId: null };
43541
43612
  }
43542
- resolve14({ outcome: { outcome: "selected", optionId: picked.optionId } });
43613
+ resolve13({ outcome: { outcome: "selected", optionId: picked.optionId } });
43543
43614
  return { kind: "resolved", optionId: picked.optionId };
43544
43615
  }
43545
43616
  const text = this.pending.options[index];
@@ -46140,10 +46211,10 @@ var NativeTuiDriver = class _NativeTuiDriver {
46140
46211
  this.lastOutput = this.now();
46141
46212
  }
46142
46213
  whenSafeToYield() {
46143
- return new Promise((resolve14) => {
46214
+ return new Promise((resolve13) => {
46144
46215
  const tick = () => {
46145
46216
  const quietFor = this.now() - this.lastOutput;
46146
- if (quietFor >= this.idleMs) resolve14();
46217
+ if (quietFor >= this.idleMs) resolve13();
46147
46218
  else setTimeout(tick, this.idleMs - quietFor);
46148
46219
  };
46149
46220
  tick();
@@ -46206,10 +46277,10 @@ var AcpDriver = class {
46206
46277
  * one ever is, assume resumable so behaviour is unchanged.
46207
46278
  */
46208
46279
  hasTranscript(conversationId) {
46209
- const resolve14 = this.deps.runtime.resolveHistoryFile;
46210
- if (typeof resolve14 !== "function") return true;
46280
+ const resolve13 = this.deps.runtime.resolveHistoryFile;
46281
+ if (typeof resolve13 !== "function") return true;
46211
46282
  try {
46212
- return resolve14.call(this.deps.runtime, this.deps.opts.cwd, conversationId) !== null;
46283
+ return resolve13.call(this.deps.runtime, this.deps.opts.cwd, conversationId) !== null;
46213
46284
  } catch {
46214
46285
  return true;
46215
46286
  }
@@ -46273,11 +46344,11 @@ var AcpDriver = class {
46273
46344
  this.turnActive = false;
46274
46345
  const waiters = this.waiters;
46275
46346
  this.waiters = [];
46276
- waiters.forEach((resolve14) => resolve14());
46347
+ waiters.forEach((resolve13) => resolve13());
46277
46348
  }
46278
46349
  whenSafeToYield() {
46279
46350
  if (!this.turnActive) return Promise.resolve();
46280
- return new Promise((resolve14) => this.waiters.push(resolve14));
46351
+ return new Promise((resolve13) => this.waiters.push(resolve13));
46281
46352
  }
46282
46353
  };
46283
46354
 
@@ -46870,8 +46941,8 @@ async function start(requestedAgent, presetSession) {
46870
46941
  const releaseStartupMark = markAgentStarting();
46871
46942
  process.once("exit", releaseStartupMark);
46872
46943
  let settleOwnHandshake = () => void 0;
46873
- const ownHandshakeSettled = new Promise((resolve14) => {
46874
- settleOwnHandshake = resolve14;
46944
+ const ownHandshakeSettled = new Promise((resolve13) => {
46945
+ settleOwnHandshake = resolve13;
46875
46946
  });
46876
46947
  const releaseBeads = () => {
46877
46948
  releaseStartupMark();
@@ -46881,7 +46952,7 @@ async function start(requestedAgent, presetSession) {
46881
46952
  ownHandshakeSettled.then(
46882
46953
  () => waitForNoAgentStarting({ timeoutMs: BEADS_AFTER_HANDSHAKE_CAP_MS })
46883
46954
  ),
46884
- new Promise((resolve14) => setTimeout(resolve14, BEADS_AFTER_HANDSHAKE_CAP_MS).unref())
46955
+ new Promise((resolve13) => setTimeout(resolve13, BEADS_AFTER_HANDSHAKE_CAP_MS).unref())
46885
46956
  ]);
46886
46957
  const beadsReady = provisionBeadsForStart({
46887
46958
  sessionId: session.id,
@@ -46953,8 +47024,8 @@ async function start(requestedAgent, presetSession) {
46953
47024
  let gateTimer;
46954
47025
  await Promise.race([
46955
47026
  Promise.all([depsReady, agentBinaryReady]),
46956
- new Promise((resolve14) => {
46957
- gateTimer = setTimeout(resolve14, GATE_TIMEOUT_MS);
47027
+ new Promise((resolve13) => {
47028
+ gateTimer = setTimeout(resolve13, GATE_TIMEOUT_MS);
46958
47029
  })
46959
47030
  ]);
46960
47031
  if (gateTimer) clearTimeout(gateTimer);
@@ -47338,7 +47409,7 @@ async function pair(args2 = []) {
47338
47409
  waitSpin.message(waitMessage());
47339
47410
  }, 1e3);
47340
47411
  countdownInterval.unref?.();
47341
- await new Promise((resolve14) => {
47412
+ await new Promise((resolve13) => {
47342
47413
  let stopPolling = null;
47343
47414
  function sigintHandler() {
47344
47415
  clearInterval(countdownInterval);
@@ -47389,7 +47460,7 @@ async function pair(args2 = []) {
47389
47460
  pluginAuthToken: info.pluginAuthToken
47390
47461
  });
47391
47462
  }
47392
- resolve14();
47463
+ resolve13();
47393
47464
  },
47394
47465
  () => {
47395
47466
  clearInterval(countdownInterval);
@@ -47618,12 +47689,12 @@ var GitHubCodespacesProvider = class {
47618
47689
  }
47619
47690
  if (!isAuthed) {
47620
47691
  resetStdinForChild();
47621
- await new Promise((resolve14, reject) => {
47692
+ await new Promise((resolve13, reject) => {
47622
47693
  const proc = (0, import_child_process30.spawn)("gh", ["auth", "login", "-s", "codespace,repo,read:user"], {
47623
47694
  stdio: "inherit"
47624
47695
  });
47625
47696
  proc.on("exit", (code) => {
47626
- if (code === 0) resolve14();
47697
+ if (code === 0) resolve13();
47627
47698
  else reject(new Error("gh auth login failed."));
47628
47699
  });
47629
47700
  proc.on("error", reject);
@@ -47652,13 +47723,13 @@ var GitHubCodespacesProvider = class {
47652
47723
  }
47653
47724
  wt(noteLines.join("\n"), "One more permission needed");
47654
47725
  resetStdinForChild();
47655
- const refreshCode = await new Promise((resolve14, reject) => {
47726
+ const refreshCode = await new Promise((resolve13, reject) => {
47656
47727
  const proc = (0, import_child_process30.spawn)(
47657
47728
  "gh",
47658
47729
  ["auth", "refresh", "-h", "github.com", "-s", "codespace"],
47659
47730
  { stdio: "inherit" }
47660
47731
  );
47661
- proc.on("exit", (code) => resolve14(code ?? 1));
47732
+ proc.on("exit", (code) => resolve13(code ?? 1));
47662
47733
  proc.on("error", reject);
47663
47734
  });
47664
47735
  if (refreshCode !== 0) {
@@ -47802,10 +47873,10 @@ var GitHubCodespacesProvider = class {
47802
47873
  if (q(proceed) || !proceed) return;
47803
47874
  O2.step(`Installing gh via ${installCmd.describe}\u2026`);
47804
47875
  resetStdinForChild();
47805
- const ok = await new Promise((resolve14) => {
47876
+ const ok = await new Promise((resolve13) => {
47806
47877
  const proc = (0, import_child_process30.spawn)(installCmd.exe, installCmd.args, { stdio: "inherit" });
47807
- proc.on("exit", (code) => resolve14(code === 0));
47808
- proc.on("error", () => resolve14(false));
47878
+ proc.on("exit", (code) => resolve13(code === 0));
47879
+ proc.on("error", () => resolve13(false));
47809
47880
  });
47810
47881
  if (ok) O2.success("gh installed");
47811
47882
  else O2.error("gh install failed");
@@ -47829,14 +47900,14 @@ var GitHubCodespacesProvider = class {
47829
47900
  "Expanding GitHub scopes"
47830
47901
  );
47831
47902
  resetStdinForChild();
47832
- await new Promise((resolve14, reject) => {
47903
+ await new Promise((resolve13, reject) => {
47833
47904
  const proc = (0, import_child_process30.spawn)(
47834
47905
  "gh",
47835
47906
  ["auth", "refresh", "-h", "github.com", "-s", "repo,read:org"],
47836
47907
  { stdio: "inherit" }
47837
47908
  );
47838
47909
  proc.on("exit", (code) => {
47839
- if (code === 0) resolve14();
47910
+ if (code === 0) resolve13();
47840
47911
  else reject(new Error(
47841
47912
  "gh auth refresh failed. Re-run `gh auth refresh -h github.com -s repo,read:org` manually."
47842
47913
  ));
@@ -48007,13 +48078,13 @@ var GitHubCodespacesProvider = class {
48007
48078
  }
48008
48079
  async streamCommand(workspaceId, command2) {
48009
48080
  resetStdinForChild();
48010
- return new Promise((resolve14, reject) => {
48081
+ return new Promise((resolve13, reject) => {
48011
48082
  const proc = (0, import_child_process30.spawn)(
48012
48083
  "gh",
48013
48084
  ["codespace", "ssh", "-c", workspaceId, "--", "-tt", command2],
48014
48085
  { stdio: "inherit" }
48015
48086
  );
48016
- proc.on("exit", (code) => resolve14({ code: code ?? 0 }));
48087
+ proc.on("exit", (code) => resolve13({ code: code ?? 0 }));
48017
48088
  proc.on("error", reject);
48018
48089
  });
48019
48090
  }
@@ -48034,7 +48105,7 @@ var GitHubCodespacesProvider = class {
48034
48105
  "--",
48035
48106
  `mkdir -p ${shellQuote(remoteDir)} && tar -xzf - -C ${shellQuote(remoteDir)}`
48036
48107
  ];
48037
- await new Promise((resolve14, reject) => {
48108
+ await new Promise((resolve13, reject) => {
48038
48109
  const tar = (0, import_child_process30.spawn)("tar", tarArgs, {
48039
48110
  stdio: ["ignore", "pipe", "pipe"],
48040
48111
  env: tarEnv
@@ -48054,7 +48125,7 @@ var GitHubCodespacesProvider = class {
48054
48125
  ssh.on("error", reject);
48055
48126
  ssh.on("exit", (code) => {
48056
48127
  if (code === 0) {
48057
- resolve14();
48128
+ resolve13();
48058
48129
  } else {
48059
48130
  const reason = (sshErr || tarErr || `exit ${code}`).trim().slice(0, 500);
48060
48131
  reject(new Error(`Remote tar failed: ${reason}`));
@@ -48072,7 +48143,7 @@ var GitHubCodespacesProvider = class {
48072
48143
  parts.push(`chmod ${options.mode.toString(8)} ${shellQuote(remotePath)}`);
48073
48144
  }
48074
48145
  const cmd = parts.join(" && ");
48075
- await new Promise((resolve14, reject) => {
48146
+ await new Promise((resolve13, reject) => {
48076
48147
  const proc = (0, import_child_process30.spawn)(
48077
48148
  "gh",
48078
48149
  ["codespace", "ssh", "-c", workspaceId, "--", cmd],
@@ -48084,7 +48155,7 @@ var GitHubCodespacesProvider = class {
48084
48155
  });
48085
48156
  proc.on("error", reject);
48086
48157
  proc.on("exit", (code) => {
48087
- if (code === 0) resolve14();
48158
+ if (code === 0) resolve13();
48088
48159
  else reject(new Error(`Remote write failed: ${(stderr || `exit ${code}`).trim().slice(0, 500)}`));
48089
48160
  });
48090
48161
  proc.stdin?.write(contents);
@@ -48174,10 +48245,10 @@ var GitpodProvider = class {
48174
48245
  "Authenticating Gitpod"
48175
48246
  );
48176
48247
  resetStdinForChild2();
48177
- await new Promise((resolve14, reject) => {
48248
+ await new Promise((resolve13, reject) => {
48178
48249
  const proc = (0, import_child_process31.spawn)("gitpod", ["login"], { stdio: "inherit" });
48179
48250
  proc.on("exit", (code) => {
48180
- if (code === 0) resolve14();
48251
+ if (code === 0) resolve13();
48181
48252
  else reject(new Error("gitpod login failed."));
48182
48253
  });
48183
48254
  proc.on("error", reject);
@@ -48326,13 +48397,13 @@ var GitpodProvider = class {
48326
48397
  }
48327
48398
  async streamCommand(workspaceId, command2) {
48328
48399
  resetStdinForChild2();
48329
- return new Promise((resolve14, reject) => {
48400
+ return new Promise((resolve13, reject) => {
48330
48401
  const proc = (0, import_child_process31.spawn)(
48331
48402
  "gitpod",
48332
48403
  ["workspace", "ssh", workspaceId, "--", "-tt", command2],
48333
48404
  { stdio: "inherit" }
48334
48405
  );
48335
- proc.on("exit", (code) => resolve14({ code: code ?? 0 }));
48406
+ proc.on("exit", (code) => resolve13({ code: code ?? 0 }));
48336
48407
  proc.on("error", reject);
48337
48408
  });
48338
48409
  }
@@ -48346,7 +48417,7 @@ var GitpodProvider = class {
48346
48417
  tarArgs.push(".");
48347
48418
  const tarEnv = { ...process.env, COPYFILE_DISABLE: "1" };
48348
48419
  const remoteCmd = `mkdir -p ${shellQuote2(remoteDir)} && tar -xzf - -C ${shellQuote2(remoteDir)}`;
48349
- await new Promise((resolve14, reject) => {
48420
+ await new Promise((resolve13, reject) => {
48350
48421
  const tar = (0, import_child_process31.spawn)("tar", tarArgs, {
48351
48422
  stdio: ["ignore", "pipe", "pipe"],
48352
48423
  env: tarEnv
@@ -48367,7 +48438,7 @@ var GitpodProvider = class {
48367
48438
  tar.on("error", reject);
48368
48439
  ssh.on("error", reject);
48369
48440
  ssh.on("exit", (code) => {
48370
- if (code === 0) resolve14();
48441
+ if (code === 0) resolve13();
48371
48442
  else reject(new Error(`Remote tar failed: ${(sshErr || tarErr || `exit ${code}`).trim().slice(0, 500)}`));
48372
48443
  });
48373
48444
  });
@@ -48382,7 +48453,7 @@ var GitpodProvider = class {
48382
48453
  parts.push(`chmod ${options.mode.toString(8)} ${shellQuote2(remotePath)}`);
48383
48454
  }
48384
48455
  const cmd = parts.join(" && ");
48385
- await new Promise((resolve14, reject) => {
48456
+ await new Promise((resolve13, reject) => {
48386
48457
  const proc = (0, import_child_process31.spawn)(
48387
48458
  "gitpod",
48388
48459
  ["workspace", "ssh", workspaceId, "--", cmd],
@@ -48394,7 +48465,7 @@ var GitpodProvider = class {
48394
48465
  });
48395
48466
  proc.on("error", reject);
48396
48467
  proc.on("exit", (code) => {
48397
- if (code === 0) resolve14();
48468
+ if (code === 0) resolve13();
48398
48469
  else reject(new Error(`Remote write failed: ${(stderr || `exit ${code}`).trim().slice(0, 500)}`));
48399
48470
  });
48400
48471
  proc.stdin?.write(contents);
@@ -48451,14 +48522,14 @@ var GitLabWorkspacesProvider = class {
48451
48522
  "Authenticating GitLab"
48452
48523
  );
48453
48524
  resetStdinForChild3();
48454
- await new Promise((resolve14, reject) => {
48525
+ await new Promise((resolve13, reject) => {
48455
48526
  const proc = (0, import_child_process32.spawn)(
48456
48527
  "glab",
48457
48528
  ["auth", "login", "--scopes", "api,read_user,read_repository"],
48458
48529
  { stdio: "inherit" }
48459
48530
  );
48460
48531
  proc.on("exit", (code) => {
48461
- if (code === 0) resolve14();
48532
+ if (code === 0) resolve13();
48462
48533
  else reject(new Error("glab auth login failed."));
48463
48534
  });
48464
48535
  proc.on("error", reject);
@@ -48623,13 +48694,13 @@ Docs: https://docs.gitlab.com/ee/user/workspace/configuration.html`
48623
48694
  async streamCommand(workspaceId, command2) {
48624
48695
  const sshHost = process.env.CODEAM_GITLAB_SSH_HOST ?? "workspaces.gitlab.com";
48625
48696
  resetStdinForChild3();
48626
- return new Promise((resolve14, reject) => {
48697
+ return new Promise((resolve13, reject) => {
48627
48698
  const proc = (0, import_child_process32.spawn)(
48628
48699
  "ssh",
48629
48700
  ["-tt", "-o", "StrictHostKeyChecking=accept-new", `${workspaceId}@${sshHost}`, command2],
48630
48701
  { stdio: "inherit" }
48631
48702
  );
48632
- proc.on("exit", (code) => resolve14({ code: code ?? 0 }));
48703
+ proc.on("exit", (code) => resolve13({ code: code ?? 0 }));
48633
48704
  proc.on("error", reject);
48634
48705
  });
48635
48706
  }
@@ -48644,7 +48715,7 @@ Docs: https://docs.gitlab.com/ee/user/workspace/configuration.html`
48644
48715
  tarArgs.push(".");
48645
48716
  const tarEnv = { ...process.env, COPYFILE_DISABLE: "1" };
48646
48717
  const remoteCmd = `mkdir -p ${shellQuote3(remoteDir)} && tar -xzf - -C ${shellQuote3(remoteDir)}`;
48647
- await new Promise((resolve14, reject) => {
48718
+ await new Promise((resolve13, reject) => {
48648
48719
  const tar = (0, import_child_process32.spawn)("tar", tarArgs, { stdio: ["ignore", "pipe", "pipe"], env: tarEnv });
48649
48720
  const ssh = (0, import_child_process32.spawn)(
48650
48721
  "ssh",
@@ -48662,7 +48733,7 @@ Docs: https://docs.gitlab.com/ee/user/workspace/configuration.html`
48662
48733
  tar.on("error", reject);
48663
48734
  ssh.on("error", reject);
48664
48735
  ssh.on("exit", (code) => {
48665
- if (code === 0) resolve14();
48736
+ if (code === 0) resolve13();
48666
48737
  else reject(new Error(`Remote tar failed: ${(sshErr || tarErr || `exit ${code}`).trim().slice(0, 500)}`));
48667
48738
  });
48668
48739
  });
@@ -48675,7 +48746,7 @@ Docs: https://docs.gitlab.com/ee/user/workspace/configuration.html`
48675
48746
  parts.push(`chmod ${options.mode.toString(8)} ${shellQuote3(remotePath)}`);
48676
48747
  }
48677
48748
  const cmd = parts.join(" && ");
48678
- await new Promise((resolve14, reject) => {
48749
+ await new Promise((resolve13, reject) => {
48679
48750
  const proc = (0, import_child_process32.spawn)(
48680
48751
  "ssh",
48681
48752
  ["-o", "StrictHostKeyChecking=accept-new", `${workspaceId}@${sshHost}`, cmd],
@@ -48687,7 +48758,7 @@ Docs: https://docs.gitlab.com/ee/user/workspace/configuration.html`
48687
48758
  });
48688
48759
  proc.on("error", reject);
48689
48760
  proc.on("exit", (code) => {
48690
- if (code === 0) resolve14();
48761
+ if (code === 0) resolve13();
48691
48762
  else reject(new Error(`Remote write failed: ${(stderr || `exit ${code}`).trim().slice(0, 500)}`));
48692
48763
  });
48693
48764
  proc.stdin?.write(contents);
@@ -48778,10 +48849,10 @@ var RailwayProvider = class {
48778
48849
  "Authenticating Railway"
48779
48850
  );
48780
48851
  resetStdinForChild4();
48781
- await new Promise((resolve14, reject) => {
48852
+ await new Promise((resolve13, reject) => {
48782
48853
  const proc = (0, import_child_process33.spawn)("railway", ["login"], { stdio: "inherit" });
48783
48854
  proc.on("exit", (code) => {
48784
- if (code === 0) resolve14();
48855
+ if (code === 0) resolve13();
48785
48856
  else reject(new Error("railway login failed."));
48786
48857
  });
48787
48858
  proc.on("error", reject);
@@ -48921,13 +48992,13 @@ var RailwayProvider = class {
48921
48992
  throw new Error("Invalid Railway workspace id (expected projectId/serviceId).");
48922
48993
  }
48923
48994
  resetStdinForChild4();
48924
- return new Promise((resolve14, reject) => {
48995
+ return new Promise((resolve13, reject) => {
48925
48996
  const proc = (0, import_child_process33.spawn)(
48926
48997
  "railway",
48927
48998
  ["shell", "--project", projectId, "--service", serviceId, "--command", command2],
48928
48999
  { stdio: "inherit" }
48929
49000
  );
48930
- proc.on("exit", (code) => resolve14({ code: code ?? 0 }));
49001
+ proc.on("exit", (code) => resolve13({ code: code ?? 0 }));
48931
49002
  proc.on("error", reject);
48932
49003
  });
48933
49004
  }
@@ -48945,7 +49016,7 @@ var RailwayProvider = class {
48945
49016
  tarArgs.push(".");
48946
49017
  const tarEnv = { ...process.env, COPYFILE_DISABLE: "1" };
48947
49018
  const remoteCmd = `mkdir -p ${shellQuote4(remoteDir)} && tar -xzf - -C ${shellQuote4(remoteDir)}`;
48948
- await new Promise((resolve14, reject) => {
49019
+ await new Promise((resolve13, reject) => {
48949
49020
  const tar = (0, import_child_process33.spawn)("tar", tarArgs, { stdio: ["ignore", "pipe", "pipe"], env: tarEnv });
48950
49021
  const sh = (0, import_child_process33.spawn)(
48951
49022
  "railway",
@@ -48963,7 +49034,7 @@ var RailwayProvider = class {
48963
49034
  tar.on("error", reject);
48964
49035
  sh.on("error", reject);
48965
49036
  sh.on("exit", (code) => {
48966
- if (code === 0) resolve14();
49037
+ if (code === 0) resolve13();
48967
49038
  else reject(new Error(`Remote tar failed: ${(shErr || tarErr || `exit ${code}`).trim().slice(0, 500)}`));
48968
49039
  });
48969
49040
  });
@@ -48979,7 +49050,7 @@ var RailwayProvider = class {
48979
49050
  parts.push(`chmod ${options.mode.toString(8)} ${shellQuote4(remotePath)}`);
48980
49051
  }
48981
49052
  const cmd = parts.join(" && ");
48982
- await new Promise((resolve14, reject) => {
49053
+ await new Promise((resolve13, reject) => {
48983
49054
  const proc = (0, import_child_process33.spawn)(
48984
49055
  "railway",
48985
49056
  ["shell", "--project", projectId, "--service", serviceId, "--command", cmd],
@@ -48991,7 +49062,7 @@ var RailwayProvider = class {
48991
49062
  });
48992
49063
  proc.on("error", reject);
48993
49064
  proc.on("exit", (code) => {
48994
- if (code === 0) resolve14();
49065
+ if (code === 0) resolve13();
48995
49066
  else reject(new Error(`Remote write failed: ${(stderr || `exit ${code}`).trim().slice(0, 500)}`));
48996
49067
  });
48997
49068
  proc.stdin?.write(contents);
@@ -50190,7 +50261,7 @@ var defaultGitToolingRunner = {
50190
50261
  }
50191
50262
  },
50192
50263
  run(cmd, args2, opts = {}) {
50193
- return new Promise((resolve14) => {
50264
+ return new Promise((resolve13) => {
50194
50265
  const child = (0, import_node_child_process31.spawn)(cmd, args2, {
50195
50266
  stdio: [opts.input !== void 0 ? "pipe" : "ignore", "ignore", "pipe"]
50196
50267
  });
@@ -50199,7 +50270,7 @@ var defaultGitToolingRunner = {
50199
50270
  const done = (code) => {
50200
50271
  if (settled) return;
50201
50272
  settled = true;
50202
- resolve14({ code, stderr });
50273
+ resolve13({ code, stderr });
50203
50274
  };
50204
50275
  child.stderr?.on("data", (b) => {
50205
50276
  stderr += b.toString();
@@ -50280,14 +50351,14 @@ function compareSemver(a, b) {
50280
50351
  return 0;
50281
50352
  }
50282
50353
  function fetchLatest() {
50283
- return new Promise((resolve14) => {
50354
+ return new Promise((resolve13) => {
50284
50355
  const req = https8.get(
50285
50356
  REGISTRY_URL,
50286
50357
  { headers: { Accept: "application/json" }, timeout: REQUEST_TIMEOUT_MS },
50287
50358
  (res) => {
50288
50359
  if (res.statusCode !== 200) {
50289
50360
  res.resume();
50290
- resolve14(null);
50361
+ resolve13(null);
50291
50362
  return;
50292
50363
  }
50293
50364
  let buf = "";
@@ -50299,21 +50370,21 @@ function fetchLatest() {
50299
50370
  try {
50300
50371
  const json = JSON.parse(buf);
50301
50372
  if (typeof json.version === "string") {
50302
- resolve14(json.version);
50373
+ resolve13(json.version);
50303
50374
  } else {
50304
- resolve14(null);
50375
+ resolve13(null);
50305
50376
  }
50306
50377
  } catch {
50307
- resolve14(null);
50378
+ resolve13(null);
50308
50379
  }
50309
50380
  });
50310
50381
  }
50311
50382
  );
50312
50383
  req.on("timeout", () => {
50313
50384
  req.destroy();
50314
- resolve14(null);
50385
+ resolve13(null);
50315
50386
  });
50316
- req.on("error", () => resolve14(null));
50387
+ req.on("error", () => resolve13(null));
50317
50388
  });
50318
50389
  }
50319
50390
  function notifyIfStale(currentVersion, latest) {
@@ -50389,7 +50460,7 @@ async function autoUpgradeBeforeCriticalCommand() {
50389
50460
  if (process.env.NODE_ENV === "test") return;
50390
50461
  if (process.env.CODEAM_DISABLE_UPDATE_CHECK === "1") return;
50391
50462
  if (process.env.CI) return;
50392
- const current2 = true ? "2.76.14" : null;
50463
+ const current2 = true ? "2.76.16" : null;
50393
50464
  if (!current2) return;
50394
50465
  const cache = readCache();
50395
50466
  const fresh = cache && Date.now() - cache.fetchedAt < TTL_MS;
@@ -50406,7 +50477,7 @@ function checkForUpdates() {
50406
50477
  if (process.env.CODEAM_DISABLE_UPDATE_CHECK === "1") return;
50407
50478
  if (process.env.CI) return;
50408
50479
  if (!process.stdout.isTTY) return;
50409
- const current2 = true ? "2.76.14" : null;
50480
+ const current2 = true ? "2.76.16" : null;
50410
50481
  if (!current2) return;
50411
50482
  const cache = readCache();
50412
50483
  const fresh = cache && Date.now() - cache.fetchedAt < TTL_MS;
@@ -50514,18 +50585,29 @@ function pointerTarget(root, name) {
50514
50585
  }
50515
50586
  }
50516
50587
  function atomicPoint(root, name, targetDir) {
50517
- const tmp = path107.join(root, `.${name}.tmp-${process.pid}-${Date.now()}`);
50518
- fs94.symlinkSync(path107.relative(root, targetDir), tmp, "dir");
50588
+ const realRoot = fs94.realpathSync(root);
50589
+ const tmp = path107.join(realRoot, `.${name}.tmp-${process.pid}-${Date.now()}`);
50590
+ fs94.symlinkSync(path107.relative(realRoot, fs94.realpathSync(targetDir)), tmp, "dir");
50519
50591
  try {
50520
- fs94.renameSync(tmp, path107.join(root, name));
50592
+ fs94.renameSync(tmp, path107.join(realRoot, name));
50521
50593
  } catch (err) {
50522
50594
  fs94.rmSync(tmp, { force: true });
50523
50595
  throw err;
50524
50596
  }
50525
50597
  }
50598
+ function samePath(a, b) {
50599
+ const canon = (p2) => {
50600
+ try {
50601
+ return fs94.realpathSync(p2);
50602
+ } catch {
50603
+ return path107.resolve(p2);
50604
+ }
50605
+ };
50606
+ return canon(a) === canon(b);
50607
+ }
50526
50608
  function switchCurrent(root, versionDir) {
50527
50609
  const old = pointerTarget(root, "current");
50528
- if (old && path107.resolve(old) !== path107.resolve(versionDir)) atomicPoint(root, "previous", old);
50610
+ if (old && !samePath(old, versionDir)) atomicPoint(root, "previous", old);
50529
50611
  atomicPoint(root, "current", versionDir);
50530
50612
  }
50531
50613
  function validCurrent(root) {
@@ -50539,7 +50621,7 @@ function rollbackCurrent(root) {
50539
50621
  const prev = pointerTarget(root, "previous");
50540
50622
  if (!prev || isBad(prev) || !entryOf(prev)) return null;
50541
50623
  const cur = pointerTarget(root, "current");
50542
- if (cur && path107.resolve(cur) !== path107.resolve(prev)) atomicPoint(root, "previous", cur);
50624
+ if (cur && !samePath(cur, prev)) atomicPoint(root, "previous", cur);
50543
50625
  atomicPoint(root, "current", prev);
50544
50626
  return versionOf(prev);
50545
50627
  }
@@ -50677,7 +50759,7 @@ var SELF_UPDATE_VIEW_TIMEOUT_MS = 3e4;
50677
50759
  var SELF_UPDATE_INSTALL_TIMEOUT_MS = 18e4;
50678
50760
  var SELF_UPDATE_LS_TIMEOUT_MS = 15e3;
50679
50761
  function currentCliVersion() {
50680
- return true ? "2.76.14" : null;
50762
+ return true ? "2.76.16" : null;
50681
50763
  }
50682
50764
  async function installedVersion(deps) {
50683
50765
  const ls = await deps.run(
@@ -50693,10 +50775,10 @@ async function installedVersion(deps) {
50693
50775
  }
50694
50776
  }
50695
50777
  function runCmd(cmd, args2, timeoutMs) {
50696
- return new Promise((resolve14) => {
50778
+ return new Promise((resolve13) => {
50697
50779
  (0, import_node_child_process33.execFile)(cmd, args2, { timeout: timeoutMs }, (err, stdout, stderr) => {
50698
50780
  const code = err && typeof err.code === "number" ? err.code : err ? null : 0;
50699
- resolve14({ code, stdout: stdout ?? "", stderr: stderr ?? "" });
50781
+ resolve13({ code, stdout: stdout ?? "", stderr: stderr ?? "" });
50700
50782
  });
50701
50783
  });
50702
50784
  }
@@ -50720,14 +50802,22 @@ async function runSelfUpdateWith(deps) {
50720
50802
  }
50721
50803
  const root = deps.versionsRoot ?? cliVersionsRoot();
50722
50804
  const versioned = versionedModeSupported(deps.platform) ? validCurrent(root) : null;
50723
- if (versioned && compareSemver(versioned.version, current2) > 0) {
50805
+ const runningDir = versioned ? versionDirContaining(root, deps.runningEntry) : null;
50806
+ const runningIsCurrent = versioned !== null && runningDir !== null && samePath(runningDir, versioned.dir);
50807
+ if (runningIsCurrent && versioned && versioned.version !== current2) {
50808
+ log.warn(
50809
+ "host-agent",
50810
+ `self-update: running ${current2} from ${versioned.dir}, whose package.json says ${versioned.version} \u2014 not restarting onto it (it is this same code)`
50811
+ );
50812
+ }
50813
+ if (versioned && !runningIsCurrent && compareSemver(versioned.version, current2) > 0) {
50724
50814
  log.info(
50725
50815
  "host-agent",
50726
50816
  `self-update: ${versioned.version} already current in ${root} (running ${current2}) \u2014 restarting onto it`
50727
50817
  );
50728
50818
  return { status: "updated", version: versioned.version };
50729
50819
  }
50730
- const onDisk = await installedVersion(deps);
50820
+ const onDisk = runningIsCurrent ? null : await installedVersion(deps);
50731
50821
  if (onDisk && compareSemver(onDisk, current2) > 0) {
50732
50822
  log.info(
50733
50823
  "host-agent",
@@ -50741,15 +50831,19 @@ async function runSelfUpdateWith(deps) {
50741
50831
  SELF_UPDATE_VIEW_TIMEOUT_MS
50742
50832
  );
50743
50833
  if (view.code !== 0) {
50744
- log.trace("host-agent", `self-update: npm view exited ${String(view.code)} \u2014 skipping`);
50834
+ log.warn(
50835
+ "host-agent",
50836
+ `self-update: npm view ${SELF_UPDATE_PKG} exited ${String(view.code)} \u2014 cannot check, staying on ${current2}: ` + view.stderr.trim().slice(-300)
50837
+ );
50745
50838
  return { status: "skipped" };
50746
50839
  }
50747
50840
  const latest = view.stdout.trim();
50748
50841
  if (!latest) {
50749
- log.trace("host-agent", "self-update: empty npm view output \u2014 skipping");
50842
+ log.warn("host-agent", `self-update: npm view returned nothing \u2014 cannot check, staying on ${current2}`);
50750
50843
  return { status: "skipped" };
50751
50844
  }
50752
50845
  if (compareSemver(latest, current2) <= 0) {
50846
+ log.info("host-agent", `self-update: running ${current2}, npm latest ${latest} \u2014 up to date`);
50753
50847
  return { status: "current" };
50754
50848
  }
50755
50849
  if (!versionedModeSupported(deps.platform)) {
@@ -50786,11 +50880,15 @@ async function installVersioned(deps, root, latest, running2) {
50786
50880
  }
50787
50881
  try {
50788
50882
  const runningDir = versionDirContaining(root, deps.runningEntry);
50883
+ if (runningDir && samePath(runningDir, target)) {
50884
+ log.warn(
50885
+ "host-agent",
50886
+ `self-update: already running from ${target} (reports ${running2}) \u2014 leaving it alone`
50887
+ );
50888
+ return { status: "skipped" };
50889
+ }
50789
50890
  const reusable = entryOf(target) && versionOf(target) === latest;
50790
50891
  if (!reusable) {
50791
- if (runningDir && path108.resolve(runningDir) === path108.resolve(target)) {
50792
- return { status: "skipped" };
50793
- }
50794
50892
  fs95.rmSync(target, { recursive: true, force: true });
50795
50893
  const install = await deps.run(
50796
50894
  "npm",
@@ -50872,7 +50970,7 @@ function signalHostReady(send = process.send?.bind(process)) {
50872
50970
  }
50873
50971
  function defaultDeps() {
50874
50972
  return {
50875
- ownVersion: true ? "2.76.14" : null,
50973
+ ownVersion: true ? "2.76.16" : null,
50876
50974
  root: cliVersionsRoot(),
50877
50975
  args: process.argv.slice(3),
50878
50976
  execPath: process.execPath,
@@ -50921,9 +51019,9 @@ async function superviseCurrent(over = {}) {
50921
51019
  };
50922
51020
  if (deps.stdinIsTty) process.on("SIGINT", ignoreSigint);
50923
51021
  const { code, signal } = await new Promise(
50924
- (resolve14) => {
50925
- child.once("exit", (c2, s) => resolve14({ code: c2, signal: s }));
50926
- child.once("error", () => resolve14({ code: 1, signal: null }));
51022
+ (resolve13) => {
51023
+ child.once("exit", (c2, s) => resolve13({ code: c2, signal: s }));
51024
+ child.once("error", () => resolve13({ code: 1, signal: null }));
50927
51025
  }
50928
51026
  );
50929
51027
  for (const [sig, h] of handlers2) process.off(sig, h);
@@ -51190,6 +51288,12 @@ function fleetUserIdFromContainerName(containerName) {
51190
51288
  function isMissingContainerError(stderr) {
51191
51289
  return /no such container/i.test(stderr);
51192
51290
  }
51291
+ function fleetLaneKey(cmd) {
51292
+ if (!cmd.type.startsWith("fleet_")) return null;
51293
+ if (cmd.type === "fleet_prune_host") return "host";
51294
+ const payload = cmd.payload;
51295
+ return typeof payload?.containerName === "string" ? payload.containerName : cmd.type;
51296
+ }
51193
51297
  function isFleetPruneHostPayload(v) {
51194
51298
  if (typeof v !== "object" || v === null) return false;
51195
51299
  const p2 = v;
@@ -51265,7 +51369,7 @@ var DOCKER_RUN_WITH_PULL_TIMEOUT_MS = 6e5;
51265
51369
  var DOCKER_PRUNE_TIMEOUT_MS = 6e5;
51266
51370
  var defaultDockerRunner = {
51267
51371
  run(args2, opts = {}) {
51268
- return new Promise((resolve14) => {
51372
+ return new Promise((resolve13) => {
51269
51373
  const child = (0, import_node_child_process36.spawn)("docker", args2, {
51270
51374
  stdio: ["ignore", "pipe", "pipe"],
51271
51375
  env: { ...process.env, ...opts.env }
@@ -51284,7 +51388,7 @@ var defaultDockerRunner = {
51284
51388
  if (settled) return;
51285
51389
  settled = true;
51286
51390
  clearTimeout(timer);
51287
- resolve14({ code, stderr: stderrBuf, stdout: stdoutBuf });
51391
+ resolve13({ code, stderr: stderrBuf, stdout: stdoutBuf });
51288
51392
  };
51289
51393
  child.stdout?.on("data", (b) => {
51290
51394
  stdoutBuf += b.toString();
@@ -51462,7 +51566,7 @@ var HostAgentSupervisor = class {
51462
51566
  const make = this.deps.makeRelay ?? ((pluginId, onCommand, meta, pollSecret) => new CommandRelayService(pluginId, onCommand, meta, void 0, pollSecret));
51463
51567
  this.relay = make(
51464
51568
  this.identity.controlPluginId,
51465
- (cmd) => this.handleCommand(cmd),
51569
+ (cmd) => this.dispatchRelayCommand(cmd),
51466
51570
  CONTROL_AGENT_META,
51467
51571
  this.identity.controlPollSecret
51468
51572
  );
@@ -51624,19 +51728,20 @@ var HostAgentSupervisor = class {
51624
51728
  */
51625
51729
  maybeRestartForUpdate(version3) {
51626
51730
  const midTurn = [...this.children.values()].some((c2) => this.isChildMidTurn(c2.proc.pid));
51627
- if (midTurn) {
51731
+ const fleetBusy = this.fleetLanes.size > 0;
51732
+ if (midTurn || fleetBusy) {
51628
51733
  const since = this.pendingRestartSince ?? this.now();
51629
51734
  const waited = this.now() - since;
51630
51735
  if (waited < SELF_UPDATE_DEFER_MAX_MS) {
51631
51736
  log.info(
51632
51737
  "host-agent",
51633
- `self-update: ${version3} installed but a session is mid-turn \u2014 deferring restart`
51738
+ `self-update: ${version3} installed but ${fleetBusy ? `${this.fleetLanes.size} fleet op(s) are in flight` : "a session is mid-turn"} \u2014 deferring restart`
51634
51739
  );
51635
51740
  return false;
51636
51741
  }
51637
51742
  log.warn(
51638
51743
  "host-agent",
51639
- `self-update: ${version3} has been owed for ${Math.round(waited / 36e5)}h with a session still mid-turn \u2014 restarting anyway rather than staying on old code`
51744
+ `self-update: ${version3} has been owed for ${Math.round(waited / 36e5)}h with ${fleetBusy ? "fleet ops still in flight" : "a session still mid-turn"} \u2014 restarting anyway rather than staying on old code`
51640
51745
  );
51641
51746
  }
51642
51747
  this.onUpdated(version3);
@@ -51668,6 +51773,58 @@ var HostAgentSupervisor = class {
51668
51773
  * arbitrary command surface).
51669
51774
  */
51670
51775
  async handleCommand(cmd) {
51776
+ const lane = fleetLaneKey(cmd);
51777
+ if (lane !== null) return this.runInFleetLane(lane, () => this.handleFleetCommand(cmd));
51778
+ await this.handleNonFleetCommand(cmd);
51779
+ }
51780
+ /**
51781
+ * The relay's entry point. A fleet command is NOT awaited here.
51782
+ *
51783
+ * The relay acks a batch the moment it arrives, then awaits each command of
51784
+ * the batch in order. Awaiting a fleet op there let one slow op hold every
51785
+ * command queued behind it: on 2026-10-02 the hourly sweep's
51786
+ * `fleet_migrate_box_image` commands were each pulling the freshly released
51787
+ * 7.7 GB image (up to 10 min apiece), a new user's scratch `fleet_create_box`
51788
+ * sat behind three of them in the same batch (received 18:04:07, never
51789
+ * started), the 18:06 self-update restart dropped it, and since it was already
51790
+ * acked nothing ever redelivered it — the box failed at the 18:30
51791
+ * provisioning sweep. Per-container lanes keep each box's ops in order; ops on
51792
+ * different boxes no longer wait for each other.
51793
+ */
51794
+ dispatchRelayCommand(cmd) {
51795
+ const work = this.handleCommand(cmd);
51796
+ if (fleetLaneKey(cmd) === null) return work;
51797
+ void work;
51798
+ return Promise.resolve();
51799
+ }
51800
+ /** Fleet ops queued or running, keyed by container (or the host for a prune). */
51801
+ fleetLanes = /* @__PURE__ */ new Map();
51802
+ /** Number of fleet lanes with work queued or running — for tests + the restart gate. */
51803
+ fleetOpsInFlight() {
51804
+ return this.fleetLanes.size;
51805
+ }
51806
+ /**
51807
+ * Run `op` after every earlier op on the same lane. Never rejects: a failed op
51808
+ * is logged and the lane moves on. When the last lane drains and a self-update
51809
+ * restart is owed, take it now instead of waiting for the next hourly tick.
51810
+ */
51811
+ runInFleetLane(key, op) {
51812
+ const prev = this.fleetLanes.get(key) ?? Promise.resolve();
51813
+ const next = prev.then(op).catch((err) => {
51814
+ log.warn(
51815
+ "host-agent",
51816
+ `fleet op on ${key} failed: ${err instanceof Error ? err.message : String(err)}`
51817
+ );
51818
+ });
51819
+ this.fleetLanes.set(key, next);
51820
+ return next.then(() => {
51821
+ if (this.fleetLanes.get(key) === next) this.fleetLanes.delete(key);
51822
+ if (this.fleetLanes.size === 0 && this.pendingRestartVersion !== null) {
51823
+ this.maybeRestartForUpdate(this.pendingRestartVersion);
51824
+ }
51825
+ });
51826
+ }
51827
+ async handleFleetCommand(cmd) {
51671
51828
  if (cmd.type === "fleet_create_box") {
51672
51829
  if (!isFleetCreateBoxPayload(cmd.payload)) {
51673
51830
  log.warn("host-agent", `ignoring malformed fleet_create_box id=${cmd.id}`);
@@ -51716,6 +51873,8 @@ var HostAgentSupervisor = class {
51716
51873
  await this.fleetPruneHost(cmd.payload);
51717
51874
  return;
51718
51875
  }
51876
+ }
51877
+ async handleNonFleetCommand(cmd) {
51719
51878
  if (cmd.type === "self_hosted_deploy") {
51720
51879
  if (!isDeployPayload(cmd.payload)) {
51721
51880
  log.warn("host-agent", `ignoring malformed self_hosted_deploy id=${cmd.id}`);
@@ -52504,6 +52663,13 @@ var HostAgentSupervisor = class {
52504
52663
  );
52505
52664
  return null;
52506
52665
  }
52666
+ if (isWrapperCheckout(cwd)) {
52667
+ log.warn(
52668
+ "host-agent",
52669
+ `resume: skipping session ${session.id.slice(0, 8)} \u2014 it has no saved workspace and the fallback is the codespace wrapper checkout (${cwd}), not the user's repo`
52670
+ );
52671
+ return null;
52672
+ }
52507
52673
  const deployId = deployIdFromWorkspace(session.cwd) ?? session.id;
52508
52674
  return { deployId, cwd, session };
52509
52675
  }
@@ -52631,6 +52797,17 @@ var HostAgentSupervisor = class {
52631
52797
  const st3 = this.resumeStateFor(target);
52632
52798
  try {
52633
52799
  const cwd = fs97.existsSync(target.cwd) ? target.cwd : process.cwd();
52800
+ if (isWrapperCheckout(cwd)) {
52801
+ log.warn(
52802
+ "host-agent",
52803
+ `resume: skipping session ${session.id.slice(0, 8)} deploy=${deployId.slice(0, 8)} \u2014 resolved cwd ${cwd} is the codespace wrapper checkout, not the user's repo`
52804
+ );
52805
+ return;
52806
+ }
52807
+ log.info(
52808
+ "host-agent",
52809
+ `resume: session ${session.id.slice(0, 8)} deploy=${deployId.slice(0, 8)} cwd=${cwd}`
52810
+ );
52634
52811
  const proc = this.resumeSpawner(
52635
52812
  { ...readHouseProxyChildEnv(deployId), CODEAM_RESUME_SESSION_ID: session.id },
52636
52813
  cwd
@@ -53190,7 +53367,7 @@ function checkChokidar() {
53190
53367
  }
53191
53368
  async function doctor(args2 = []) {
53192
53369
  const json = args2.includes("--json");
53193
- const cliVersion = true ? "2.76.14" : "0.0.0-dev";
53370
+ const cliVersion = true ? "2.76.16" : "0.0.0-dev";
53194
53371
  const apiBase2 = resolveApiBaseUrl();
53195
53372
  const diagnosticId = (0, import_node_crypto17.randomUUID)();
53196
53373
  log.info("doctor", `run id=${diagnosticId} cli=${cliVersion}`);
@@ -53634,7 +53811,7 @@ var WARM_PACKAGE_TIMEOUT_MS = 12e4;
53634
53811
  var WARM_TOTAL_BUDGET_MS = 10 * 6e4;
53635
53812
  var WARM_CONCURRENCY = 4;
53636
53813
  function runCapturing(command2, args2, timeoutMs) {
53637
- return new Promise((resolve14) => {
53814
+ return new Promise((resolve13) => {
53638
53815
  const child = (0, import_node_child_process40.spawn)(command2, args2, {
53639
53816
  env: { ...process.env, ...LAUNCHER_ENV },
53640
53817
  stdio: ["ignore", "ignore", "pipe"],
@@ -53649,15 +53826,15 @@ function runCapturing(command2, args2, timeoutMs) {
53649
53826
  child.stderr?.on("data", (c2) => stderr += c2);
53650
53827
  const timer = setTimeout(() => {
53651
53828
  child.kill("SIGKILL");
53652
- resolve14({ status: null, stderr, error: new Error(`spawn ${command2} ETIMEDOUT`) });
53829
+ resolve13({ status: null, stderr, error: new Error(`spawn ${command2} ETIMEDOUT`) });
53653
53830
  }, timeoutMs);
53654
53831
  child.on("error", (error) => {
53655
53832
  clearTimeout(timer);
53656
- resolve14({ status: null, stderr, error });
53833
+ resolve13({ status: null, stderr, error });
53657
53834
  });
53658
53835
  child.on("close", (status2) => {
53659
53836
  clearTimeout(timer);
53660
- resolve14({ status: status2, stderr });
53837
+ resolve13({ status: status2, stderr });
53661
53838
  });
53662
53839
  });
53663
53840
  }
@@ -53714,7 +53891,7 @@ async function mcpWarm(argv = [], opts = {}) {
53714
53891
  // src/commands/version.ts
53715
53892
  var import_picocolors15 = __toESM(require("picocolors"));
53716
53893
  function version2() {
53717
- const v = true ? "2.76.14" : "unknown";
53894
+ const v = true ? "2.76.16" : "unknown";
53718
53895
  console.log(`${import_picocolors15.default.bold("codeam-cli")} ${import_picocolors15.default.cyan(v)}`);
53719
53896
  }
53720
53897