orkestrator 2.35.5-beta → 2.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -131,6 +131,8 @@ async function readStreamBounded(stream, maxBytes, onOverflow, signal) {
131
131
  signal?.removeEventListener("abort", onAbort);
132
132
  reader.releaseLock();
133
133
  }
134
+ if (chunks.length === 1)
135
+ return chunks[0];
134
136
  const output = new Uint8Array(total);
135
137
  let offset = 0;
136
138
  for (const chunk of chunks) {
@@ -4933,56 +4935,559 @@ var init_manifest = __esm(() => {
4933
4935
  ];
4934
4936
  });
4935
4937
 
4938
+ // ../toolchain/src/download.ts
4939
+ import { createHash as createHash4 } from "crypto";
4940
+ import { constants, createReadStream } from "fs";
4941
+ import { copyFile as copyFile2, lstat, mkdir as mkdir3, open as open3, readdir as readdir3, rename as rename2, rm as rm3 } from "fs/promises";
4942
+ import path17 from "path";
4943
+ function failure2(message, kind) {
4944
+ const error = new Error(message);
4945
+ if (kind === "untrusted")
4946
+ error.untrusted = true;
4947
+ if (kind === "restart")
4948
+ error.restart = true;
4949
+ return error;
4950
+ }
4951
+ function delay(milliseconds) {
4952
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
4953
+ }
4954
+ function partialDownloadDirectory(rootDir) {
4955
+ return path17.join(rootDir, PARTIAL_DOWNLOAD_DIRECTORY);
4956
+ }
4957
+ function partialDownloadPath(rootDir, archive) {
4958
+ return path17.join(partialDownloadDirectory(rootDir), `${archive.sha256}${PARTIAL_SUFFIX}`);
4959
+ }
4960
+ function assertDownloadLocation(label, archive, response, allowInsecureDownloadsForTests) {
4961
+ const requested = new URL(archive.url);
4962
+ const resolved = new URL(response.url || archive.url);
4963
+ if (!allowInsecureDownloadsForTests && (requested.protocol !== "https:" || resolved.protocol !== "https:")) {
4964
+ throw failure2(`${label} download did not use HTTPS`, "untrusted");
4965
+ }
4966
+ if (!archive.allowedHosts.includes(requested.hostname)) {
4967
+ throw failure2(`${label} download host is not allowlisted: ${requested.hostname}`, "untrusted");
4968
+ }
4969
+ if (!archive.allowedHosts.includes(resolved.hostname)) {
4970
+ throw failure2(`${label} redirected to an untrusted host: ${resolved.hostname}`, "untrusted");
4971
+ }
4972
+ }
4973
+ async function existingPartialSize(partialPath, archive) {
4974
+ const info = await lstat(partialPath).catch(() => null);
4975
+ if (!info)
4976
+ return 0;
4977
+ if (!info.isFile() || info.size > archive.size) {
4978
+ await rm3(partialPath, { force: true, recursive: true });
4979
+ return 0;
4980
+ }
4981
+ return info.size;
4982
+ }
4983
+ function parseContentRange(header) {
4984
+ const match = /^bytes (\d+)-(\d+)\/(\d+|\*)$/.exec(header?.trim() ?? "");
4985
+ if (!match)
4986
+ return null;
4987
+ return {
4988
+ start: Number(match[1]),
4989
+ end: Number(match[2]),
4990
+ total: match[3] === "*" ? null : Number(match[3])
4991
+ };
4992
+ }
4993
+ async function downloadAttempt(options2, partialPath) {
4994
+ const { label, archive, fetchImpl, onBytes, timings } = options2;
4995
+ let offset = await existingPartialSize(partialPath, archive);
4996
+ let hash = createHash4("sha256");
4997
+ if (offset > 0) {
4998
+ for await (const chunk of createReadStream(partialPath, { start: 0, end: offset - 1 })) {
4999
+ hash.update(chunk);
5000
+ }
5001
+ onBytes(offset);
5002
+ if (offset === archive.size) {
5003
+ if (hash.digest("hex") === archive.sha256)
5004
+ return;
5005
+ throw failure2(`${label} partial archive did not match the pinned manifest`, "restart");
5006
+ }
5007
+ }
5008
+ const controller = new AbortController;
5009
+ let idleTimer;
5010
+ const resetIdle = () => {
5011
+ clearTimeout(idleTimer);
5012
+ idleTimer = setTimeout(() => controller.abort(), timings.idleTimeoutMs);
5013
+ };
5014
+ let handle = null;
5015
+ let response = null;
5016
+ let reader = null;
5017
+ let finished = false;
5018
+ try {
5019
+ resetIdle();
5020
+ const headers = { "user-agent": "OrkestratorV2 toolchain installer" };
5021
+ if (offset > 0)
5022
+ headers.range = `bytes=${offset}-`;
5023
+ response = await fetchImpl(archive.url, {
5024
+ redirect: "follow",
5025
+ signal: controller.signal,
5026
+ headers
5027
+ });
5028
+ resetIdle();
5029
+ if (offset > 0 && response.status === 416) {
5030
+ throw failure2(`${label} server refused to resume the download`, "restart");
5031
+ }
5032
+ if (!response.ok || !response.body) {
5033
+ throw failure2(`${label} download failed with HTTP ${response.status}`, "transient");
5034
+ }
5035
+ assertDownloadLocation(label, archive, response, options2.allowInsecureDownloadsForTests);
5036
+ let flags = constants.O_WRONLY | constants.O_CREAT | constants.O_NOFOLLOW;
5037
+ if (response.status === 206) {
5038
+ const range = parseContentRange(response.headers.get("content-range"));
5039
+ if (offset === 0) {
5040
+ throw failure2(`${label} server sent a partial response that was not requested`, "untrusted");
5041
+ }
5042
+ if (!range || range.start !== offset || range.end !== archive.size - 1 || range.total !== null && range.total !== archive.size) {
5043
+ throw failure2(`${label} server resumed the download at the wrong range`, "restart");
5044
+ }
5045
+ flags |= constants.O_APPEND;
5046
+ } else {
5047
+ if (offset > 0) {
5048
+ offset = 0;
5049
+ hash = createHash4("sha256");
5050
+ onBytes(0);
5051
+ }
5052
+ flags |= constants.O_TRUNC;
5053
+ }
5054
+ const contentLength = response.headers.get("content-length");
5055
+ if (contentLength !== null && Number(contentLength) !== archive.size - offset) {
5056
+ throw failure2(`${label} archive size header did not match the pinned manifest`, "untrusted");
5057
+ }
5058
+ handle = await open3(partialPath, flags, 384);
5059
+ reader = response.body.getReader();
5060
+ let received = offset;
5061
+ while (true) {
5062
+ const { done, value } = await reader.read();
5063
+ if (done) {
5064
+ finished = true;
5065
+ break;
5066
+ }
5067
+ resetIdle();
5068
+ received += value.byteLength;
5069
+ if (received > archive.size) {
5070
+ throw failure2(`${label} archive exceeded its pinned size`, "untrusted");
5071
+ }
5072
+ hash.update(value);
5073
+ await handle.writeFile(value);
5074
+ onBytes(received);
5075
+ }
5076
+ await handle.close();
5077
+ handle = null;
5078
+ if (received !== archive.size) {
5079
+ throw failure2(`${label} archive was truncated`, "transient");
5080
+ }
5081
+ if (hash.digest("hex") !== archive.sha256) {
5082
+ throw failure2(`${label} archive checksum did not match the pinned manifest`, offset > 0 ? "restart" : "untrusted");
5083
+ }
5084
+ } catch (error) {
5085
+ if (controller.signal.aborted && !error.untrusted) {
5086
+ throw failure2(`${label} download stalled: nothing received for ${Math.round(timings.idleTimeoutMs / 1000)}s`, "transient");
5087
+ }
5088
+ throw error;
5089
+ } finally {
5090
+ clearTimeout(idleTimer);
5091
+ await handle?.close().catch(() => {
5092
+ return;
5093
+ });
5094
+ if (reader && !finished)
5095
+ await reader.cancel().catch(() => {
5096
+ return;
5097
+ });
5098
+ else if (!reader && response?.body)
5099
+ await response.body.cancel().catch(() => {
5100
+ return;
5101
+ });
5102
+ }
5103
+ }
5104
+ async function downloadArchive(options2) {
5105
+ const partialPath = partialDownloadPath(options2.rootDir, options2.archive);
5106
+ await mkdir3(path17.dirname(partialPath), { recursive: true, mode: 448 });
5107
+ const attempts = Math.max(1, options2.timings.attempts);
5108
+ for (let attempt = 1;; attempt += 1) {
5109
+ const startSize = await existingPartialSize(partialPath, options2.archive);
5110
+ try {
5111
+ await downloadAttempt(options2, partialPath);
5112
+ if (options2.retainComplete)
5113
+ await copyFile2(partialPath, options2.archivePath);
5114
+ else
5115
+ await rename2(partialPath, options2.archivePath);
5116
+ return;
5117
+ } catch (error) {
5118
+ const attemptFailure = error;
5119
+ if (attemptFailure.untrusted || attemptFailure.restart) {
5120
+ await rm3(partialPath, { force: true });
5121
+ }
5122
+ if (attemptFailure.untrusted || attempt >= attempts)
5123
+ throw error;
5124
+ if (!attemptFailure.restart) {
5125
+ const endSize = (await lstat(partialPath).catch(() => null))?.size ?? 0;
5126
+ if (endSize <= startSize)
5127
+ throw error;
5128
+ }
5129
+ await delay(options2.timings.retryDelayMs * attempt);
5130
+ }
5131
+ }
5132
+ }
5133
+ async function prunePartialDownloads(rootDir, archives, now = Date.now()) {
5134
+ const directory = partialDownloadDirectory(rootDir);
5135
+ const keep = new Set(archives.map((archive) => `${archive.sha256}${PARTIAL_SUFFIX}`));
5136
+ const entries = await readdir3(directory).catch(() => []);
5137
+ await Promise.all(entries.filter((name) => !keep.has(name)).map(async (name) => {
5138
+ const entryPath = path17.join(directory, name);
5139
+ const info = await lstat(entryPath).catch(() => null);
5140
+ if (!info)
5141
+ return;
5142
+ if (info.isFile() && now - info.mtimeMs < UNREFERENCED_PARTIAL_RETENTION_MS)
5143
+ return;
5144
+ await rm3(entryPath, { force: true, recursive: true }).catch(() => {
5145
+ return;
5146
+ });
5147
+ }));
5148
+ }
5149
+ var PARTIAL_DOWNLOAD_DIRECTORY = ".downloads", PARTIAL_SUFFIX = ".partial", UNREFERENCED_PARTIAL_RETENTION_MS, DEFAULT_DOWNLOAD_TIMINGS;
5150
+ var init_download = __esm(() => {
5151
+ UNREFERENCED_PARTIAL_RETENTION_MS = 24 * 60 * 60 * 1000;
5152
+ DEFAULT_DOWNLOAD_TIMINGS = {
5153
+ idleTimeoutMs: 60000,
5154
+ attempts: 5,
5155
+ retryDelayMs: 1000
5156
+ };
5157
+ });
5158
+
5159
+ // ../toolchain/src/executable-checks.ts
5160
+ async function probeExecutable(executablePath, artifact, timeoutMs, spawnProcess) {
5161
+ await new Promise((resolve, reject) => {
5162
+ const child = spawnProcess(executablePath, ["--version"], {
5163
+ env: process.env,
5164
+ stdio: ["ignore", "pipe", "pipe"]
5165
+ });
5166
+ const chunks = [];
5167
+ child.stdout.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
5168
+ child.stderr.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
5169
+ const timeout = setTimeout(() => {
5170
+ child.kill("SIGKILL");
5171
+ reject(new Error(`${artifact.name} version check timed out`));
5172
+ }, timeoutMs);
5173
+ child.once("error", (error) => {
5174
+ clearTimeout(timeout);
5175
+ reject(new Error(`${artifact.name} could not execute from the Orkestrator toolchain cache: ${error.message}`));
5176
+ });
5177
+ child.once("exit", (code, signal) => {
5178
+ clearTimeout(timeout);
5179
+ const output = Buffer.concat(chunks).toString("utf8");
5180
+ if (code !== 0) {
5181
+ reject(new Error(`${artifact.name} version check failed (code ${code ?? "unknown"}, signal ${signal ?? "none"})`));
5182
+ } else if (!output.includes(artifact.version)) {
5183
+ reject(new Error(`${artifact.name} reported an unexpected version: ${output.trim() || "no output"}`));
5184
+ } else {
5185
+ resolve();
5186
+ }
5187
+ });
5188
+ });
5189
+ }
5190
+ async function verifyMacCodeSignature(executablePath, label, timeoutMs, spawnProcess) {
5191
+ await new Promise((resolve, reject) => {
5192
+ const child = spawnProcess("/usr/bin/codesign", ["--verify", "--strict", "--verbose=2", executablePath], {
5193
+ stdio: ["ignore", "ignore", "pipe"]
5194
+ });
5195
+ const errors = [];
5196
+ child.stderr.on("data", (chunk) => errors.push(Buffer.from(chunk)));
5197
+ const timeout = setTimeout(() => {
5198
+ child.kill("SIGKILL");
5199
+ reject(new Error(`${label} code-signature check timed out`));
5200
+ }, timeoutMs);
5201
+ child.once("error", (error) => {
5202
+ clearTimeout(timeout);
5203
+ reject(error);
5204
+ });
5205
+ child.once("exit", (code, signal) => {
5206
+ clearTimeout(timeout);
5207
+ if (code === 0) {
5208
+ resolve();
5209
+ return;
5210
+ }
5211
+ const detail = Buffer.concat(errors).toString("utf8").trim();
5212
+ reject(new Error(`${label} has an invalid macOS code signature (code ${code ?? "unknown"}, signal ${signal ?? "none"})${detail ? `: ${detail}` : ""}`));
5213
+ });
5214
+ });
5215
+ }
5216
+ async function runCodesign(args, failureMessage, timeoutMs, spawnProcess) {
5217
+ await new Promise((resolve, reject) => {
5218
+ const child = spawnProcess("/usr/bin/codesign", args, { stdio: ["ignore", "ignore", "pipe"] });
5219
+ const errors = [];
5220
+ child.stderr.on("data", (chunk) => errors.push(Buffer.from(chunk)));
5221
+ const timeout = setTimeout(() => {
5222
+ child.kill("SIGKILL");
5223
+ reject(new Error(`${failureMessage} timed out`));
5224
+ }, timeoutMs);
5225
+ child.once("error", (error) => {
5226
+ clearTimeout(timeout);
5227
+ reject(error);
5228
+ });
5229
+ child.once("exit", (code, signal) => {
5230
+ clearTimeout(timeout);
5231
+ if (code === 0) {
5232
+ resolve();
5233
+ return;
5234
+ }
5235
+ const detail = Buffer.concat(errors).toString("utf8").trim();
5236
+ reject(new Error(`${failureMessage} (code ${code ?? "unknown"}, signal ${signal ?? "none"})${detail ? `: ${detail}` : ""}`));
5237
+ });
5238
+ });
5239
+ }
5240
+ async function repairInvalidMacSignature(executablePath, artifact, timeoutMs, spawnProcess) {
5241
+ await runCodesign(["--remove-signature", executablePath], `${artifact.name} invalid signature could not be removed`, timeoutMs, spawnProcess).catch((error) => {
5242
+ if (error instanceof Error && /code [1-9]/.test(error.message))
5243
+ return;
5244
+ throw error;
5245
+ });
5246
+ await runCodesign(["--sign", "-", "--force", executablePath], `${artifact.name} could not be ad-hoc signed after source verification`, timeoutMs, spawnProcess);
5247
+ }
5248
+
5249
+ // ../toolchain/src/file-stamps.ts
5250
+ import { createHash as createHash5, randomUUID as randomUUID5 } from "crypto";
5251
+ import { createReadStream as createReadStream2 } from "fs";
5252
+ import { lstat as lstat2, open as open4, readFile as readFile2, rename as rename3, rm as rm4 } from "fs/promises";
5253
+ import path18 from "path";
5254
+ async function sha256File(filePath) {
5255
+ const hash = createHash5("sha256");
5256
+ for await (const chunk of createReadStream2(filePath))
5257
+ hash.update(chunk);
5258
+ return hash.digest("hex");
5259
+ }
5260
+ function lstatBig(filePath) {
5261
+ return lstat2(filePath, { bigint: true });
5262
+ }
5263
+ function metadataMatches(stamp, info) {
5264
+ return info.isFile() && stamp.dev === String(info.dev) && stamp.ino === String(info.ino) && stamp.size === Number(info.size) && stamp.mtimeNs === String(info.mtimeNs) && stamp.ctimeNs === String(info.ctimeNs);
5265
+ }
5266
+ function sameMetadata(left, right) {
5267
+ return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
5268
+ }
5269
+ function isStampShape(value) {
5270
+ if (!value || typeof value !== "object")
5271
+ return false;
5272
+ const stamp = value;
5273
+ return typeof stamp.dev === "string" && typeof stamp.ino === "string" && typeof stamp.size === "number" && Number.isSafeInteger(stamp.size) && typeof stamp.mtimeNs === "string" && typeof stamp.ctimeNs === "string" && typeof stamp.stampedAtNs === "string" && /^\d+$/.test(stamp.mtimeNs) && /^\d+$/.test(stamp.ctimeNs) && /^\d+$/.test(stamp.stampedAtNs) && typeof stamp.sha256 === "string" && /^[a-f0-9]{64}$/.test(stamp.sha256);
5274
+ }
5275
+ async function readStampFile(filePath) {
5276
+ try {
5277
+ const info = await lstat2(filePath);
5278
+ if (!info.isFile() || info.size > MAX_STAMP_FILE_BYTES)
5279
+ return null;
5280
+ const parsed = JSON.parse(await readFile2(filePath, "utf8"));
5281
+ if (parsed.version !== STAMP_FORMAT_VERSION || typeof parsed.fullCheckAt !== "number" || !Number.isFinite(parsed.fullCheckAt) || !parsed.files || typeof parsed.files !== "object" || !parsed.derived || typeof parsed.derived !== "object") {
5282
+ return null;
5283
+ }
5284
+ const files = {};
5285
+ for (const [key, stamp] of Object.entries(parsed.files)) {
5286
+ if (isStampShape(stamp))
5287
+ files[key] = stamp;
5288
+ }
5289
+ const derived = {};
5290
+ for (const [key, source] of Object.entries(parsed.derived)) {
5291
+ if (typeof source === "string" && /^[a-f0-9]{64}$/.test(source))
5292
+ derived[key] = source;
5293
+ }
5294
+ return { version: STAMP_FORMAT_VERSION, fullCheckAt: parsed.fullCheckAt, files, derived };
5295
+ } catch {
5296
+ return null;
5297
+ }
5298
+ }
5299
+ function isUnder(filePath, directories) {
5300
+ return directories.some((directory) => filePath.startsWith(directory + path18.sep));
5301
+ }
5302
+ async function openFileStampStore(rootDir, options2 = {}) {
5303
+ const now = options2.now ?? Date.now;
5304
+ const hashFile = options2.hashFileForTests ?? sha256File;
5305
+ const fullCheckIntervalMs = options2.fullCheckIntervalMs ?? FULL_CHECK_INTERVAL_MS;
5306
+ const racyWindowNs = BigInt(Math.trunc(options2.racyWindowMs ?? RACY_STAMP_WINDOW_MS)) * 1000000n;
5307
+ const stampPath = path18.join(rootDir, STAMP_FILE);
5308
+ const persisted = await readStampFile(stampPath);
5309
+ const startedAt = now();
5310
+ const fullCheck = options2.forceFullCheck === true || persisted === null || startedAt - persisted.fullCheckAt >= fullCheckIntervalMs || persisted.fullCheckAt > startedAt;
5311
+ const previousFiles = fullCheck ? {} : persisted?.files ?? {};
5312
+ const previousDerived = fullCheck ? {} : persisted?.derived ?? {};
5313
+ const runFiles = new Map;
5314
+ const runDerived = new Map;
5315
+ const lookup = (filePath) => runFiles.get(filePath) ?? previousFiles[filePath];
5316
+ const isRacy = (stamp) => {
5317
+ const stampedAt = BigInt(stamp.stampedAtNs);
5318
+ const newest = BigInt(stamp.mtimeNs) > BigInt(stamp.ctimeNs) ? BigInt(stamp.mtimeNs) : BigInt(stamp.ctimeNs);
5319
+ return stampedAt - newest < racyWindowNs;
5320
+ };
5321
+ const hashAndStamp = async (filePath, before) => {
5322
+ const stampedAtNs = BigInt(now()) * 1000000n;
5323
+ const digest = await hashFile(filePath);
5324
+ const after = await lstatBig(filePath).catch(() => null);
5325
+ if (after && before.isFile() && after.isFile() && sameMetadata(before, after)) {
5326
+ runFiles.set(filePath, {
5327
+ dev: String(after.dev),
5328
+ ino: String(after.ino),
5329
+ size: Number(after.size),
5330
+ mtimeNs: String(after.mtimeNs),
5331
+ ctimeNs: String(after.ctimeNs),
5332
+ stampedAtNs: String(stampedAtNs),
5333
+ sha256: digest
5334
+ });
5335
+ } else {
5336
+ runFiles.delete(filePath);
5337
+ }
5338
+ return digest;
5339
+ };
5340
+ const sha256 = async (filePath) => {
5341
+ const info = await lstatBig(filePath);
5342
+ const stamp = lookup(filePath);
5343
+ if (stamp && metadataMatches(stamp, info) && !isRacy(stamp)) {
5344
+ runFiles.set(filePath, stamp);
5345
+ return stamp.sha256;
5346
+ }
5347
+ return hashAndStamp(filePath, info);
5348
+ };
5349
+ return {
5350
+ fullCheck,
5351
+ sha256,
5352
+ async isUnchanged(filePath) {
5353
+ const stamp = lookup(filePath);
5354
+ if (!stamp)
5355
+ return false;
5356
+ try {
5357
+ return await sha256(filePath) === stamp.sha256;
5358
+ } catch {
5359
+ return false;
5360
+ }
5361
+ },
5362
+ derivedFrom(filePath) {
5363
+ return runDerived.get(filePath) ?? previousDerived[filePath];
5364
+ },
5365
+ async recordDerived(filePath, sourceSha256) {
5366
+ const info = await lstatBig(filePath);
5367
+ await hashAndStamp(filePath, info);
5368
+ if (runFiles.has(filePath))
5369
+ runDerived.set(filePath, sourceSha256);
5370
+ else
5371
+ runDerived.delete(filePath);
5372
+ },
5373
+ retainDerived(filePath) {
5374
+ const source = previousDerived[filePath];
5375
+ if (source !== undefined && runFiles.has(filePath))
5376
+ runDerived.set(filePath, source);
5377
+ },
5378
+ async save(directories) {
5379
+ const files = {};
5380
+ let count = 0;
5381
+ for (const [filePath, stamp] of runFiles) {
5382
+ if (!isUnder(filePath, directories))
5383
+ continue;
5384
+ if (count >= MAX_STAMP_ENTRIES)
5385
+ break;
5386
+ files[filePath] = stamp;
5387
+ count += 1;
5388
+ }
5389
+ for (const [filePath, stamp] of Object.entries(previousFiles)) {
5390
+ if (count >= MAX_STAMP_ENTRIES)
5391
+ break;
5392
+ if (isUnder(filePath, directories) || !isUnder(filePath, [rootDir]))
5393
+ continue;
5394
+ const info = await lstatBig(filePath).catch(() => null);
5395
+ if (!info || !metadataMatches(stamp, info))
5396
+ continue;
5397
+ files[filePath] = stamp;
5398
+ count += 1;
5399
+ }
5400
+ const derived = {};
5401
+ for (const [filePath, source] of Object.entries(previousDerived)) {
5402
+ if (files[filePath] && !isUnder(filePath, directories))
5403
+ derived[filePath] = source;
5404
+ }
5405
+ for (const [filePath, source] of runDerived) {
5406
+ if (files[filePath])
5407
+ derived[filePath] = source;
5408
+ }
5409
+ const contents = {
5410
+ version: STAMP_FORMAT_VERSION,
5411
+ fullCheckAt: fullCheck ? startedAt : persisted.fullCheckAt,
5412
+ files,
5413
+ derived
5414
+ };
5415
+ const temporaryPath = path18.join(rootDir, `.${STAMP_FILE}-${randomUUID5()}.tmp`);
5416
+ try {
5417
+ const handle = await open4(temporaryPath, "wx", 384);
5418
+ try {
5419
+ await handle.writeFile(JSON.stringify(contents));
5420
+ await handle.sync();
5421
+ } finally {
5422
+ await handle.close();
5423
+ }
5424
+ await rename3(temporaryPath, stampPath);
5425
+ } catch {
5426
+ await rm4(temporaryPath, { force: true }).catch(() => {
5427
+ return;
5428
+ });
5429
+ }
5430
+ }
5431
+ };
5432
+ }
5433
+ var STAMP_FILE = ".verified-stamps.json", STAMP_FORMAT_VERSION = 1, MAX_STAMP_FILE_BYTES, MAX_STAMP_ENTRIES = 20000, FULL_CHECK_INTERVAL_MS, RACY_STAMP_WINDOW_MS = 2000, directFileDigests;
5434
+ var init_file_stamps = __esm(() => {
5435
+ MAX_STAMP_FILE_BYTES = 8 * 1024 * 1024;
5436
+ FULL_CHECK_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
5437
+ directFileDigests = { sha256: sha256File };
5438
+ });
5439
+
4936
5440
  // ../toolchain/src/manager.ts
4937
5441
  import { spawn } from "child_process";
4938
- import { createHash as createHash4, randomUUID as randomUUID5 } from "crypto";
4939
- import { createReadStream, createWriteStream } from "fs";
5442
+ import { createHash as createHash6, randomUUID as randomUUID6 } from "crypto";
5443
+ import { createReadStream as createReadStream3, createWriteStream } from "fs";
4940
5444
  import {
4941
5445
  chmod,
4942
- copyFile as copyFile2,
4943
- lstat,
4944
- mkdir as mkdir3,
5446
+ copyFile as copyFile3,
5447
+ lstat as lstat3,
5448
+ mkdir as mkdir4,
4945
5449
  mkdtemp as mkdtemp2,
4946
- open as open3,
4947
- readFile as readFile2,
4948
- readdir as readdir3,
5450
+ open as open5,
5451
+ readFile as readFile3,
5452
+ readdir as readdir4,
4949
5453
  readlink,
4950
- rename as rename2,
4951
- rm as rm3,
5454
+ rename as rename4,
5455
+ rm as rm5,
4952
5456
  stat as stat3,
4953
5457
  symlink as symlink2,
4954
5458
  utimes
4955
5459
  } from "fs/promises";
4956
- import path17 from "path";
5460
+ import path19 from "path";
4957
5461
  import { pipeline } from "stream/promises";
4958
5462
  import { createGunzip } from "zlib";
4959
- function delay(milliseconds) {
5463
+ function downloadTimings(timings) {
5464
+ return {
5465
+ idleTimeoutMs: timings.downloadIdleTimeoutMs,
5466
+ attempts: timings.downloadAttempts,
5467
+ retryDelayMs: timings.downloadRetryDelayMs
5468
+ };
5469
+ }
5470
+ function delay2(milliseconds) {
4960
5471
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
4961
5472
  }
4962
5473
  function artifactDirectory(rootDir, artifact) {
4963
- return path17.join(rootDir, artifact.name, artifact.version, `${artifact.platform}-${artifact.architecture}`);
5474
+ return path19.join(rootDir, artifact.name, artifact.version, `${artifact.platform}-${artifact.architecture}`);
4964
5475
  }
4965
5476
  function artifactExecutablePath(rootDir, artifact) {
4966
- return path17.join(artifactDirectory(rootDir, artifact), artifact.executable.fileName);
5477
+ return path19.join(artifactDirectory(rootDir, artifact), artifact.executable.fileName);
4967
5478
  }
4968
5479
  function upstreamExecutablePath(rootDir, artifact) {
4969
- return path17.join(artifactDirectory(rootDir, artifact), `.upstream-${artifact.executable.fileName}`);
5480
+ return path19.join(artifactDirectory(rootDir, artifact), `.upstream-${artifact.executable.fileName}`);
4970
5481
  }
4971
5482
  function artifactCompanions(artifact) {
4972
5483
  return artifact.companions ?? [];
4973
5484
  }
4974
5485
  function companionPath(rootDir, artifact, companion) {
4975
- return path17.join(artifactDirectory(rootDir, artifact), companion.fileName);
5486
+ return path19.join(artifactDirectory(rootDir, artifact), companion.fileName);
4976
5487
  }
4977
5488
  function artifactArchiveBytes(artifact) {
4978
5489
  return artifactCompanions(artifact).reduce((total, companion) => total + companion.archive.size, artifact.archive.size);
4979
5490
  }
4980
- async function sha256File(filePath) {
4981
- const hash = createHash4("sha256");
4982
- for await (const chunk of createReadStream(filePath))
4983
- hash.update(chunk);
4984
- return hash.digest("hex");
4985
- }
4986
5491
  function assertValidArtifactMetadata(artifact) {
4987
5492
  if (!["zip", "tar.gz", "raw"].includes(artifact.archive.format)) {
4988
5493
  throw new Error(`${artifact.name} manifest has unsupported archive format`);
@@ -4996,7 +5501,7 @@ function assertValidArtifactMetadata(artifact) {
4996
5501
  }
4997
5502
  const paths = new Set;
4998
5503
  for (const file of artifact.archive.bundleFiles) {
4999
- const normalized = path17.posix.normalize(file.path);
5504
+ const normalized = path19.posix.normalize(file.path);
5000
5505
  if (normalized !== file.path || normalized.startsWith("../") || normalized.startsWith("/") || normalized.includes("\\") || paths.has(normalized) || !Number.isSafeInteger(file.size) || file.size < 1 || !/^[a-f0-9]{64}$/.test(file.sha256)) {
5001
5506
  throw new Error(`${artifact.name} manifest has an unsafe bundle file`);
5002
5507
  }
@@ -5022,7 +5527,7 @@ function assertValidArtifactMetadata(artifact) {
5022
5527
  }
5023
5528
  const activationNames = new Set([artifact.name, artifact.executable.fileName]);
5024
5529
  for (const alias of artifact.activationAliases ?? []) {
5025
- if (!alias || alias.startsWith(".") || alias.includes("/") || alias.includes("\\") || alias !== path17.basename(alias) || activationNames.has(alias)) {
5530
+ if (!alias || alias.startsWith(".") || alias.includes("/") || alias.includes("\\") || alias !== path19.basename(alias) || activationNames.has(alias)) {
5026
5531
  throw new Error(`${artifact.name} manifest has an unsafe or duplicate activation alias`);
5027
5532
  }
5028
5533
  activationNames.add(alias);
@@ -5032,7 +5537,7 @@ function assertValidArtifactMetadata(artifact) {
5032
5537
  if (companion.archive.format !== "zip" && companion.archive.format !== "tar.gz") {
5033
5538
  throw new Error(`${artifact.name} companion has an unsupported archive format`);
5034
5539
  }
5035
- if (!companion.fileName || companion.fileName.startsWith(".") || companion.fileName.includes("/") || companion.fileName.includes("\\") || companion.fileName !== path17.basename(companion.fileName)) {
5540
+ if (!companion.fileName || companion.fileName.startsWith(".") || companion.fileName.includes("/") || companion.fileName.includes("\\") || companion.fileName !== path19.basename(companion.fileName)) {
5036
5541
  throw new Error(`${artifact.name} companion has an unsafe file name`);
5037
5542
  }
5038
5543
  if (companionNames.has(companion.fileName)) {
@@ -5079,47 +5584,44 @@ function pinnedInstalledState(artifact) {
5079
5584
  }
5080
5585
  return { size, sha256 };
5081
5586
  }
5082
- async function isValidFile(filePath, expected) {
5587
+ async function isValidFile(filePath, expected, digests) {
5083
5588
  try {
5084
- const file = await lstat(filePath);
5085
- return file.isFile() && !file.isSymbolicLink() && file.size === expected.size && await sha256File(filePath) === expected.sha256;
5589
+ const file = await lstat3(filePath);
5590
+ return file.isFile() && !file.isSymbolicLink() && file.size === expected.size && await digests.sha256(filePath) === expected.sha256;
5086
5591
  } catch {
5087
5592
  return false;
5088
5593
  }
5089
5594
  }
5090
- async function isValidUpstreamExecutable(rootDir, artifact) {
5091
- return isValidFile(upstreamExecutablePath(rootDir, artifact), {
5092
- size: artifact.executable.size,
5093
- sha256: artifact.executable.sha256
5094
- });
5595
+ async function isValidUpstreamExecutable(rootDir, artifact, digests) {
5596
+ return isValidFile(upstreamExecutablePath(rootDir, artifact), { size: artifact.executable.size, sha256: artifact.executable.sha256 }, digests);
5095
5597
  }
5096
- async function isValidExecutable(rootDir, artifact) {
5598
+ async function isValidExecutable(rootDir, artifact, digests) {
5097
5599
  if (artifact.executable.repairInvalidMacSignature) {
5098
- if (!await isValidUpstreamExecutable(rootDir, artifact))
5600
+ if (!await isValidUpstreamExecutable(rootDir, artifact, digests))
5099
5601
  return false;
5100
5602
  for (const bundled of artifact.archive.bundleFiles ?? []) {
5101
- if (!await isValidFile(path17.join(artifactDirectory(rootDir, artifact), ...bundled.path.split("/")), bundled)) {
5603
+ if (!await isValidFile(path19.join(artifactDirectory(rootDir, artifact), ...bundled.path.split("/")), bundled, digests)) {
5102
5604
  return false;
5103
5605
  }
5104
5606
  }
5105
- return !artifact.archive.bundleIntegrity || hasValidBundleIntegrity(artifactDirectory(rootDir, artifact), artifact);
5607
+ return !artifact.archive.bundleIntegrity || hasValidBundleIntegrity(artifactDirectory(rootDir, artifact), artifact, digests);
5106
5608
  }
5107
5609
  const executablePath = artifactExecutablePath(rootDir, artifact);
5108
5610
  try {
5109
5611
  const expected = pinnedInstalledState(artifact);
5110
- const file = await lstat(executablePath);
5612
+ const file = await lstat3(executablePath);
5111
5613
  if (!file.isFile() || file.isSymbolicLink() || file.size !== expected.size)
5112
5614
  return false;
5113
- if (await sha256File(executablePath) !== expected.sha256)
5615
+ if (await digests.sha256(executablePath) !== expected.sha256)
5114
5616
  return false;
5115
5617
  if ((file.mode & 511) !== 320)
5116
5618
  await chmod(executablePath, 320);
5117
5619
  for (const bundled of artifact.archive.bundleFiles ?? []) {
5118
- if (!await isValidFile(path17.join(artifactDirectory(rootDir, artifact), ...bundled.path.split("/")), bundled)) {
5620
+ if (!await isValidFile(path19.join(artifactDirectory(rootDir, artifact), ...bundled.path.split("/")), bundled, digests)) {
5119
5621
  return false;
5120
5622
  }
5121
5623
  }
5122
- if (artifact.archive.bundleIntegrity && !await hasValidBundleIntegrity(artifactDirectory(rootDir, artifact), artifact)) {
5624
+ if (artifact.archive.bundleIntegrity && !await hasValidBundleIntegrity(artifactDirectory(rootDir, artifact), artifact, digests)) {
5123
5625
  return false;
5124
5626
  }
5125
5627
  return true;
@@ -5127,27 +5629,27 @@ async function isValidExecutable(rootDir, artifact) {
5127
5629
  return false;
5128
5630
  }
5129
5631
  }
5130
- async function bundleTreeEntries(directory, artifact) {
5632
+ async function bundleTreeEntries(directory, artifact, digests) {
5131
5633
  const entries = [];
5132
5634
  const excludedExecutablePaths = new Set([artifact.executable.fileName]);
5133
5635
  if (artifact.executable.repairInvalidMacSignature) {
5134
5636
  excludedExecutablePaths.add(`.upstream-${artifact.executable.fileName}`);
5135
5637
  }
5136
5638
  const visit = async (currentDirectory, prefix = "") => {
5137
- for (const entry of await readdir3(currentDirectory, { withFileTypes: true })) {
5639
+ for (const entry of await readdir4(currentDirectory, { withFileTypes: true })) {
5138
5640
  const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;
5139
- const filePath = path17.join(currentDirectory, entry.name);
5641
+ const filePath = path19.join(currentDirectory, entry.name);
5140
5642
  if (entry.isDirectory()) {
5141
5643
  await visit(filePath, relativePath);
5142
5644
  } else if (entry.isFile() && !entry.isSymbolicLink()) {
5143
5645
  if (excludedExecutablePaths.has(relativePath))
5144
5646
  continue;
5145
- const info = await lstat(filePath);
5647
+ const info = await lstat3(filePath);
5146
5648
  entries.push({
5147
5649
  path: relativePath,
5148
5650
  size: info.size,
5149
5651
  executable: (info.mode & 73) !== 0,
5150
- sha256: await sha256File(filePath)
5652
+ sha256: await digests.sha256(filePath)
5151
5653
  });
5152
5654
  } else {
5153
5655
  throw new Error(`Bundle contains unsupported entry: ${relativePath}`);
@@ -5158,7 +5660,7 @@ async function bundleTreeEntries(directory, artifact) {
5158
5660
  return entries.sort((left, right) => left.path.localeCompare(right.path));
5159
5661
  }
5160
5662
  function bundleTreeDigest(entries) {
5161
- const hash = createHash4("sha256");
5663
+ const hash = createHash6("sha256");
5162
5664
  let totalSize = 0;
5163
5665
  for (const entry of entries) {
5164
5666
  totalSize += entry.size;
@@ -5174,20 +5676,20 @@ function bundleTreeDigest(entries) {
5174
5676
  }
5175
5677
  return { fileCount: entries.length, totalSize, sha256: hash.digest("hex") };
5176
5678
  }
5177
- async function hasValidBundleIntegrity(directory, artifact) {
5679
+ async function hasValidBundleIntegrity(directory, artifact, digests) {
5178
5680
  const expected = artifact.archive.bundleIntegrity;
5179
5681
  if (!expected)
5180
5682
  return true;
5181
- const actual = bundleTreeDigest(await bundleTreeEntries(directory, artifact));
5683
+ const actual = bundleTreeDigest(await bundleTreeEntries(directory, artifact, digests));
5182
5684
  return actual.fileCount === expected.fileCount && actual.totalSize === expected.totalSize && actual.sha256 === expected.sha256;
5183
5685
  }
5184
- async function isValidCompanion(rootDir, artifact, companion) {
5686
+ async function isValidCompanion(rootDir, artifact, companion, digests) {
5185
5687
  const filePath = companionPath(rootDir, artifact, companion);
5186
5688
  try {
5187
- const file = await lstat(filePath);
5689
+ const file = await lstat3(filePath);
5188
5690
  if (!file.isFile() || file.isSymbolicLink() || file.size !== companion.executable.size)
5189
5691
  return false;
5190
- if (await sha256File(filePath) !== companion.executable.sha256)
5692
+ if (await digests.sha256(filePath) !== companion.executable.sha256)
5191
5693
  return false;
5192
5694
  if ((file.mode & 511) !== 320)
5193
5695
  await chmod(filePath, 320);
@@ -5196,23 +5698,23 @@ async function isValidCompanion(rootDir, artifact, companion) {
5196
5698
  return false;
5197
5699
  }
5198
5700
  }
5199
- async function missingCompanions(rootDir, artifact) {
5701
+ async function missingCompanions(rootDir, artifact, digests) {
5200
5702
  const companions = artifactCompanions(artifact);
5201
- const validity = await Promise.all(companions.map((companion) => isValidCompanion(rootDir, artifact, companion)));
5703
+ const validity = await Promise.all(companions.map((companion) => isValidCompanion(rootDir, artifact, companion, digests)));
5202
5704
  return companions.filter((_, index) => !validity[index]);
5203
5705
  }
5204
- async function installationStatus(rootDir, artifact) {
5205
- if (!await isValidExecutable(rootDir, artifact))
5706
+ async function installationStatus(rootDir, artifact, digests) {
5707
+ if (!await isValidExecutable(rootDir, artifact, digests))
5206
5708
  return { state: "missing" };
5207
- const companions = await missingCompanions(rootDir, artifact);
5709
+ const companions = await missingCompanions(rootDir, artifact, digests);
5208
5710
  return companions.length === 0 ? { state: "valid" } : { state: "companions-missing", companions };
5209
5711
  }
5210
- async function isValidInstallation(rootDir, artifact) {
5211
- return (await installationStatus(rootDir, artifact)).state === "valid";
5712
+ async function isValidInstallation(rootDir, artifact, digests) {
5713
+ return (await installationStatus(rootDir, artifact, digests)).state === "valid";
5212
5714
  }
5213
5715
  async function readInstallLockOwner(lockPath) {
5214
5716
  try {
5215
- const parsed = JSON.parse(await readFile2(lockPath, "utf8"));
5717
+ const parsed = JSON.parse(await readFile3(lockPath, "utf8"));
5216
5718
  if (typeof parsed.token !== "string" || typeof parsed.pid !== "number" || typeof parsed.createdAt !== "string") {
5217
5719
  return null;
5218
5720
  }
@@ -5245,18 +5747,18 @@ async function initializeInstallLock(lockPath, owner, openLockFile) {
5245
5747
  return;
5246
5748
  });
5247
5749
  if (created && !initialized)
5248
- await rm3(lockPath, { force: true }).catch(() => {
5750
+ await rm5(lockPath, { force: true }).catch(() => {
5249
5751
  return;
5250
5752
  });
5251
5753
  }
5252
5754
  }
5253
5755
  async function acquireInstallLock(rootDir, onProgress, timings, openLockFile, ownerProcessExists) {
5254
- const lockPath = path17.join(rootDir, INSTALL_LOCK);
5756
+ const lockPath = path19.join(rootDir, INSTALL_LOCK);
5255
5757
  const startedAt = Date.now();
5256
5758
  let announcedWait = false;
5257
5759
  while (Date.now() - startedAt < timings.lockWaitTimeoutMs) {
5258
5760
  const owner = {
5259
- token: randomUUID5(),
5761
+ token: randomUUID6(),
5260
5762
  pid: process.pid,
5261
5763
  createdAt: new Date().toISOString()
5262
5764
  };
@@ -5287,7 +5789,7 @@ async function acquireInstallLock(rootDir, onProgress, timings, openLockFile, ow
5287
5789
  if (current.token !== owner.token) {
5288
5790
  throw new Error("Orkestrator toolchain installation lock ownership changed unexpectedly");
5289
5791
  }
5290
- await rm3(lockPath, { force: true });
5792
+ await rm5(lockPath, { force: true });
5291
5793
  }
5292
5794
  };
5293
5795
  } catch (error) {
@@ -5298,7 +5800,7 @@ async function acquireInstallLock(rootDir, onProgress, timings, openLockFile, ow
5298
5800
  if (observedOwner && !ownerProcessExists(observedOwner.pid)) {
5299
5801
  const currentOwner = await readInstallLockOwner(lockPath);
5300
5802
  if (currentOwner?.token === observedOwner.token) {
5301
- await rm3(lockPath, { force: true });
5803
+ await rm5(lockPath, { force: true });
5302
5804
  continue;
5303
5805
  }
5304
5806
  }
@@ -5306,7 +5808,7 @@ async function acquireInstallLock(rootDir, onProgress, timings, openLockFile, ow
5306
5808
  if (!observedOwner && lockStat && Date.now() - lockStat.mtimeMs > timings.lockStaleAfterMs) {
5307
5809
  const currentOwner = await readInstallLockOwner(lockPath);
5308
5810
  if (!currentOwner) {
5309
- await rm3(lockPath, { force: true });
5811
+ await rm5(lockPath, { force: true });
5310
5812
  continue;
5311
5813
  }
5312
5814
  }
@@ -5314,72 +5816,10 @@ async function acquireInstallLock(rootDir, onProgress, timings, openLockFile, ow
5314
5816
  announcedWait = true;
5315
5817
  onProgress("Waiting for another Orkestrator window to finish preparing tools\u2026");
5316
5818
  }
5317
- await delay(timings.lockPollMs);
5819
+ await delay2(timings.lockPollMs);
5318
5820
  }
5319
5821
  throw new Error("Timed out waiting for the Orkestrator toolchain installation lock");
5320
5822
  }
5321
- function assertDownloadLocation(label, archive, response, allowInsecureDownloadsForTests) {
5322
- const requested = new URL(archive.url);
5323
- const resolved = new URL(response.url || archive.url);
5324
- if (!allowInsecureDownloadsForTests && (requested.protocol !== "https:" || resolved.protocol !== "https:")) {
5325
- throw new Error(`${label} download did not use HTTPS`);
5326
- }
5327
- if (!archive.allowedHosts.includes(requested.hostname)) {
5328
- throw new Error(`${label} download host is not allowlisted: ${requested.hostname}`);
5329
- }
5330
- if (!archive.allowedHosts.includes(resolved.hostname)) {
5331
- throw new Error(`${label} redirected to an untrusted host: ${resolved.hostname}`);
5332
- }
5333
- }
5334
- async function downloadArchive(label, archive, archivePath, fetchImpl, onBytes, allowInsecureDownloadsForTests, timeoutMs) {
5335
- const controller = new AbortController;
5336
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
5337
- let handle = null;
5338
- try {
5339
- const response = await fetchImpl(archive.url, {
5340
- redirect: "follow",
5341
- signal: controller.signal,
5342
- headers: { "user-agent": "OrkestratorV2 toolchain installer" }
5343
- });
5344
- if (!response.ok || !response.body) {
5345
- throw new Error(`${label} download failed with HTTP ${response.status}`);
5346
- }
5347
- assertDownloadLocation(label, archive, response, allowInsecureDownloadsForTests);
5348
- const contentLength = response.headers.get("content-length");
5349
- if (contentLength !== null && Number(contentLength) !== archive.size) {
5350
- throw new Error(`${label} archive size header did not match the pinned manifest`);
5351
- }
5352
- handle = await open3(archivePath, "wx", 384);
5353
- const reader = response.body.getReader();
5354
- const hash = createHash4("sha256");
5355
- let received = 0;
5356
- while (true) {
5357
- const { done, value } = await reader.read();
5358
- if (done)
5359
- break;
5360
- received += value.byteLength;
5361
- if (received > archive.size) {
5362
- throw new Error(`${label} archive exceeded its pinned size`);
5363
- }
5364
- hash.update(value);
5365
- await handle.writeFile(value);
5366
- onBytes(received);
5367
- }
5368
- await handle.close();
5369
- handle = null;
5370
- if (received !== archive.size) {
5371
- throw new Error(`${label} archive was truncated`);
5372
- }
5373
- if (hash.digest("hex") !== archive.sha256) {
5374
- throw new Error(`${label} archive checksum did not match the pinned manifest`);
5375
- }
5376
- } finally {
5377
- clearTimeout(timeout);
5378
- await handle?.close().catch(() => {
5379
- return;
5380
- });
5381
- }
5382
- }
5383
5823
  async function extractTarGzipEntry(archivePath, destinationPath, label, archive, executableSize) {
5384
5824
  let found = false;
5385
5825
  const extract2 = exports_tar_stream.extract();
@@ -5403,7 +5843,7 @@ async function extractTarGzipEntry(archivePath, destinationPath, label, archive,
5403
5843
  }
5404
5844
  pipeline(stream, createWriteStream(destinationPath, { flags: "wx", mode: 320 })).then(() => next(), (error) => extract2.destroy(error instanceof Error ? error : new Error(String(error))));
5405
5845
  });
5406
- await pipeline(createReadStream(archivePath), createGunzip(), extract2);
5846
+ await pipeline(createReadStream3(archivePath), createGunzip(), extract2);
5407
5847
  if (!found)
5408
5848
  throw new Error(`${label} executable was not found in its archive`);
5409
5849
  }
@@ -5432,8 +5872,8 @@ async function extractTarGzipBundle(archivePath, destinationDirectory, label, ar
5432
5872
  stream.resume();
5433
5873
  return;
5434
5874
  }
5435
- const normalized = path17.posix.normalize(relative);
5436
- if (normalized.startsWith("../") || normalized.startsWith("/") || normalized.includes("\\") || path17.isAbsolute(normalized)) {
5875
+ const normalized = path19.posix.normalize(relative);
5876
+ if (normalized.startsWith("../") || normalized.startsWith("/") || normalized.includes("\\") || path19.isAbsolute(normalized)) {
5437
5877
  extract2.destroy(new Error(`Unsafe path in ${label} bundle`));
5438
5878
  stream.resume();
5439
5879
  return;
@@ -5445,7 +5885,7 @@ async function extractTarGzipBundle(archivePath, destinationDirectory, label, ar
5445
5885
  stream.resume();
5446
5886
  return;
5447
5887
  }
5448
- const destination = path17.join(destinationDirectory, ...normalized.split("/"));
5888
+ const destination = path19.join(destinationDirectory, ...normalized.split("/"));
5449
5889
  if (header.type === "directory") {
5450
5890
  stream.once("end", next);
5451
5891
  stream.resume();
@@ -5463,12 +5903,12 @@ async function extractTarGzipBundle(archivePath, destinationDirectory, label, ar
5463
5903
  }
5464
5904
  if (header.name === archive.entryPath)
5465
5905
  foundExecutable = true;
5466
- mkdir3(path17.dirname(destination), { recursive: true, mode: 448 }).then(() => pipeline(stream, createWriteStream(destination, {
5906
+ mkdir4(path19.dirname(destination), { recursive: true, mode: 448 }).then(() => pipeline(stream, createWriteStream(destination, {
5467
5907
  flags: "wx",
5468
5908
  mode: (header.mode ?? 0) & 73 ? 320 : 256
5469
5909
  }))).then(() => next(), (error) => extract2.destroy(error instanceof Error ? error : new Error(String(error))));
5470
5910
  });
5471
- await pipeline(createReadStream(archivePath), createGunzip(), extract2);
5911
+ await pipeline(createReadStream3(archivePath), createGunzip(), extract2);
5472
5912
  if (!foundExecutable)
5473
5913
  throw new Error(`${label} executable was not found in its bundle`);
5474
5914
  }
@@ -5536,98 +5976,10 @@ async function extractZipEntry(archivePath, destinationPath, label, archive, exe
5536
5976
  zipFile.readEntry();
5537
5977
  });
5538
5978
  }
5539
- async function probeExecutable(executablePath, artifact, timeoutMs, spawnProcess) {
5540
- await new Promise((resolve, reject) => {
5541
- const child = spawnProcess(executablePath, ["--version"], {
5542
- env: process.env,
5543
- stdio: ["ignore", "pipe", "pipe"]
5544
- });
5545
- const chunks = [];
5546
- child.stdout.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
5547
- child.stderr.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
5548
- const timeout = setTimeout(() => {
5549
- child.kill("SIGKILL");
5550
- reject(new Error(`${artifact.name} version check timed out`));
5551
- }, timeoutMs);
5552
- child.once("error", (error) => {
5553
- clearTimeout(timeout);
5554
- reject(new Error(`${artifact.name} could not execute from the Orkestrator toolchain cache: ${error.message}`));
5555
- });
5556
- child.once("exit", (code, signal) => {
5557
- clearTimeout(timeout);
5558
- const output = Buffer.concat(chunks).toString("utf8");
5559
- if (code !== 0) {
5560
- reject(new Error(`${artifact.name} version check failed (code ${code ?? "unknown"}, signal ${signal ?? "none"})`));
5561
- } else if (!output.includes(artifact.version)) {
5562
- reject(new Error(`${artifact.name} reported an unexpected version: ${output.trim() || "no output"}`));
5563
- } else {
5564
- resolve();
5565
- }
5566
- });
5567
- });
5568
- }
5569
- async function verifyMacCodeSignature(executablePath, label, timeoutMs, spawnProcess) {
5570
- await new Promise((resolve, reject) => {
5571
- const child = spawnProcess("/usr/bin/codesign", ["--verify", "--strict", "--verbose=2", executablePath], {
5572
- stdio: ["ignore", "ignore", "pipe"]
5573
- });
5574
- const errors = [];
5575
- child.stderr.on("data", (chunk) => errors.push(Buffer.from(chunk)));
5576
- const timeout = setTimeout(() => {
5577
- child.kill("SIGKILL");
5578
- reject(new Error(`${label} code-signature check timed out`));
5579
- }, timeoutMs);
5580
- child.once("error", (error) => {
5581
- clearTimeout(timeout);
5582
- reject(error);
5583
- });
5584
- child.once("exit", (code, signal) => {
5585
- clearTimeout(timeout);
5586
- if (code === 0) {
5587
- resolve();
5588
- return;
5589
- }
5590
- const detail = Buffer.concat(errors).toString("utf8").trim();
5591
- reject(new Error(`${label} has an invalid macOS code signature (code ${code ?? "unknown"}, signal ${signal ?? "none"})${detail ? `: ${detail}` : ""}`));
5592
- });
5593
- });
5594
- }
5595
- async function runCodesign(args, failureMessage, timeoutMs, spawnProcess) {
5596
- await new Promise((resolve, reject) => {
5597
- const child = spawnProcess("/usr/bin/codesign", args, { stdio: ["ignore", "ignore", "pipe"] });
5598
- const errors = [];
5599
- child.stderr.on("data", (chunk) => errors.push(Buffer.from(chunk)));
5600
- const timeout = setTimeout(() => {
5601
- child.kill("SIGKILL");
5602
- reject(new Error(`${failureMessage} timed out`));
5603
- }, timeoutMs);
5604
- child.once("error", (error) => {
5605
- clearTimeout(timeout);
5606
- reject(error);
5607
- });
5608
- child.once("exit", (code, signal) => {
5609
- clearTimeout(timeout);
5610
- if (code === 0) {
5611
- resolve();
5612
- return;
5613
- }
5614
- const detail = Buffer.concat(errors).toString("utf8").trim();
5615
- reject(new Error(`${failureMessage} (code ${code ?? "unknown"}, signal ${signal ?? "none"})${detail ? `: ${detail}` : ""}`));
5616
- });
5617
- });
5618
- }
5619
- async function repairInvalidMacSignature(executablePath, artifact, timeoutMs, spawnProcess) {
5620
- await runCodesign(["--remove-signature", executablePath], `${artifact.name} invalid signature could not be removed`, timeoutMs, spawnProcess).catch((error) => {
5621
- if (error instanceof Error && /code [1-9]/.test(error.message))
5622
- return;
5623
- throw error;
5624
- });
5625
- await runCodesign(["--sign", "-", "--force", executablePath], `${artifact.name} could not be ad-hoc signed after source verification`, timeoutMs, spawnProcess);
5626
- }
5627
5979
  async function prepareRepairableExecutable(sourcePath, executablePath, artifact, skipExecutableProbeForTests, processTimeoutMs, spawnProcess) {
5628
- const temporaryPath = path17.join(path17.dirname(executablePath), `.repair-${artifact.executable.fileName}-${randomUUID5()}.tmp`);
5980
+ const temporaryPath = path19.join(path19.dirname(executablePath), `.repair-${artifact.executable.fileName}-${randomUUID6()}.tmp`);
5629
5981
  try {
5630
- await copyFile2(sourcePath, temporaryPath);
5982
+ await copyFile3(sourcePath, temporaryPath);
5631
5983
  await chmod(temporaryPath, 448);
5632
5984
  if (!skipExecutableProbeForTests) {
5633
5985
  try {
@@ -5639,37 +5991,56 @@ async function prepareRepairableExecutable(sourcePath, executablePath, artifact,
5639
5991
  await probeExecutable(temporaryPath, artifact, processTimeoutMs, spawnProcess);
5640
5992
  }
5641
5993
  await chmod(temporaryPath, 320);
5642
- await rename2(temporaryPath, executablePath);
5994
+ await rename4(temporaryPath, executablePath);
5643
5995
  } catch (error) {
5644
- await rm3(temporaryPath, { force: true }).catch(() => {
5996
+ await rm5(temporaryPath, { force: true }).catch(() => {
5645
5997
  return;
5646
5998
  });
5647
5999
  throw error;
5648
6000
  }
5649
6001
  }
5650
- async function refreshRepairableArtifact(rootDir, artifact, skipExecutableProbeForTests, processTimeoutMs, spawnProcess) {
6002
+ async function refreshRepairableArtifact(rootDir, artifact, digests, skipExecutableProbeForTests, processTimeoutMs, spawnProcess) {
5651
6003
  const sourcePath = upstreamExecutablePath(rootDir, artifact);
5652
- if (!await isValidUpstreamExecutable(rootDir, artifact)) {
6004
+ if (!await isValidUpstreamExecutable(rootDir, artifact, digests)) {
5653
6005
  throw new Error(`${artifact.name} trusted upstream executable failed verification`);
5654
6006
  }
5655
- await prepareRepairableExecutable(sourcePath, artifactExecutablePath(rootDir, artifact), artifact, skipExecutableProbeForTests, processTimeoutMs, spawnProcess);
6007
+ const executablePath = artifactExecutablePath(rootDir, artifact);
6008
+ if (digests.derivedFrom(executablePath) === artifact.executable.sha256) {
6009
+ const current = await lstat3(executablePath).catch(() => null);
6010
+ if (current?.isFile() && !current.isSymbolicLink() && (current.mode & 511) === 320 && await digests.isUnchanged(executablePath)) {
6011
+ digests.retainDerived(executablePath);
6012
+ return;
6013
+ }
6014
+ }
6015
+ await prepareRepairableExecutable(sourcePath, executablePath, artifact, skipExecutableProbeForTests, processTimeoutMs, spawnProcess);
6016
+ await digests.recordDerived(executablePath, artifact.executable.sha256);
5656
6017
  }
5657
6018
  async function stageCompanions(stagingDirectory, artifact, companions, fetchImpl, onBytes, startBytes, allowInsecureDownloadsForTests, skipExecutableProbeForTests, timings, spawnProcess) {
5658
6019
  let downloadedBytes = startBytes;
5659
6020
  for (const companion of companions) {
5660
- const companionArchivePath = path17.join(stagingDirectory, `.archive-${companion.fileName}.${archiveExtension(companion.archive)}`);
5661
- const companionFilePath = path17.join(stagingDirectory, companion.fileName);
6021
+ const companionArchivePath = path19.join(stagingDirectory, `.archive-${companion.fileName}.${archiveExtension(companion.archive)}`);
6022
+ const companionFilePath = path19.join(stagingDirectory, companion.fileName);
5662
6023
  const precedingBytes = downloadedBytes;
5663
- await downloadArchive(companion.fileName, companion.archive, companionArchivePath, fetchImpl, (received) => onBytes(precedingBytes + received), allowInsecureDownloadsForTests, timings.downloadTimeoutMs);
6024
+ await downloadArchive({
6025
+ retainComplete: true,
6026
+ label: companion.fileName,
6027
+ archive: companion.archive,
6028
+ archivePath: companionArchivePath,
6029
+ rootDir: path19.dirname(stagingDirectory),
6030
+ fetchImpl,
6031
+ onBytes: (received) => onBytes(precedingBytes + received),
6032
+ allowInsecureDownloadsForTests,
6033
+ timings: downloadTimings(timings)
6034
+ });
5664
6035
  downloadedBytes += companion.archive.size;
5665
6036
  if (companion.archive.format === "zip") {
5666
6037
  await extractZipEntry(companionArchivePath, companionFilePath, companion.fileName, companion.archive, companion.executable.size);
5667
6038
  } else if (companion.archive.format === "tar.gz") {
5668
6039
  await extractTarGzipEntry(companionArchivePath, companionFilePath, companion.fileName, companion.archive, companion.executable.size);
5669
6040
  } else
5670
- await rename2(companionArchivePath, companionFilePath);
5671
- await rm3(companionArchivePath, { force: true });
5672
- const installedCompanion = await lstat(companionFilePath);
6041
+ await rename4(companionArchivePath, companionFilePath);
6042
+ await rm5(companionArchivePath, { force: true });
6043
+ const installedCompanion = await lstat3(companionFilePath);
5673
6044
  if (!installedCompanion.isFile() || installedCompanion.size !== companion.executable.size) {
5674
6045
  throw new Error(`${companion.fileName} extracted executable size did not match the pinned manifest`);
5675
6046
  }
@@ -5683,48 +6054,61 @@ async function stageCompanions(stagingDirectory, artifact, companions, fetchImpl
5683
6054
  }
5684
6055
  }
5685
6056
  async function repairArtifactCompanions(rootDir, artifact, companions, fetchImpl, onBytes, onVerify, allowInsecureDownloadsForTests, skipExecutableProbeForTests, timings, spawnProcess) {
5686
- const stagingDirectory = await mkdtemp2(path17.join(rootDir, `.staging-${artifact.name}-`));
6057
+ const stagingDirectory = await mkdtemp2(path19.join(rootDir, `.staging-${artifact.name}-`));
5687
6058
  try {
5688
6059
  await stageCompanions(stagingDirectory, artifact, companions, fetchImpl, onBytes, 0, allowInsecureDownloadsForTests, skipExecutableProbeForTests, timings, spawnProcess);
5689
6060
  onVerify();
5690
6061
  const destinationDirectory = artifactDirectory(rootDir, artifact);
5691
6062
  for (const companion of companions) {
5692
- await rename2(path17.join(stagingDirectory, companion.fileName), path17.join(destinationDirectory, companion.fileName));
6063
+ await rename4(path19.join(stagingDirectory, companion.fileName), path19.join(destinationDirectory, companion.fileName));
5693
6064
  }
6065
+ await Promise.all(artifactCompanions(artifact).map((companion) => rm5(partialDownloadPath(rootDir, companion.archive), { force: true }).catch(() => {
6066
+ return;
6067
+ })));
5694
6068
  } finally {
5695
- await rm3(stagingDirectory, { recursive: true, force: true });
6069
+ await rm5(stagingDirectory, { recursive: true, force: true });
5696
6070
  }
5697
6071
  }
5698
6072
  async function installArtifact(rootDir, artifact, fetchImpl, onBytes, onVerify, allowInsecureDownloadsForTests, skipExecutableProbeForTests, timings, spawnProcess) {
5699
- const stagingDirectory = await mkdtemp2(path17.join(rootDir, `.staging-${artifact.name}-`));
5700
- const archivePath = path17.join(stagingDirectory, `archive.${archiveExtension(artifact.archive)}`);
5701
- const executablePath = path17.join(stagingDirectory, artifact.executable.fileName);
5702
- const extractedPath = artifact.executable.repairInvalidMacSignature ? path17.join(stagingDirectory, `.upstream-${artifact.executable.fileName}`) : executablePath;
6073
+ const stagingDirectory = await mkdtemp2(path19.join(rootDir, `.staging-${artifact.name}-`));
6074
+ const archivePath = path19.join(stagingDirectory, `archive.${archiveExtension(artifact.archive)}`);
6075
+ const executablePath = path19.join(stagingDirectory, artifact.executable.fileName);
6076
+ const extractedPath = artifact.executable.repairInvalidMacSignature ? path19.join(stagingDirectory, `.upstream-${artifact.executable.fileName}`) : executablePath;
5703
6077
  try {
5704
- await downloadArchive(artifact.name, artifact.archive, archivePath, fetchImpl, onBytes, allowInsecureDownloadsForTests, timings.downloadTimeoutMs);
6078
+ await downloadArchive({
6079
+ retainComplete: artifactCompanions(artifact).length > 0,
6080
+ label: artifact.name,
6081
+ archive: artifact.archive,
6082
+ archivePath,
6083
+ rootDir,
6084
+ fetchImpl,
6085
+ onBytes,
6086
+ allowInsecureDownloadsForTests,
6087
+ timings: downloadTimings(timings)
6088
+ });
5705
6089
  if (artifact.archive.bundleRoot) {
5706
6090
  await extractTarGzipBundle(archivePath, stagingDirectory, artifact.name, artifact.archive);
5707
- const bundledExecutable = path17.join(stagingDirectory, ...artifact.archive.entryPath.slice(artifact.archive.bundleRoot.length).split("/"));
6091
+ const bundledExecutable = path19.join(stagingDirectory, ...artifact.archive.entryPath.slice(artifact.archive.bundleRoot.length).split("/"));
5708
6092
  if (bundledExecutable !== extractedPath) {
5709
- await rename2(bundledExecutable, extractedPath);
6093
+ await rename4(bundledExecutable, extractedPath);
5710
6094
  }
5711
6095
  } else if (artifact.archive.format === "zip") {
5712
6096
  await extractZipEntry(archivePath, extractedPath, artifact.name, artifact.archive, artifact.executable.size);
5713
6097
  } else if (artifact.archive.format === "tar.gz") {
5714
6098
  await extractTarGzipEntry(archivePath, extractedPath, artifact.name, artifact.archive, artifact.executable.size);
5715
6099
  } else if (artifact.archive.format === "raw") {
5716
- await rename2(archivePath, extractedPath);
6100
+ await rename4(archivePath, extractedPath);
5717
6101
  } else {
5718
6102
  const unreachable = artifact.archive.format;
5719
6103
  throw new Error(`Unsupported archive format: ${String(unreachable)}`);
5720
6104
  }
5721
6105
  if (artifact.archive.format !== "raw")
5722
- await rm3(archivePath, { force: true });
5723
- if (artifact.archive.bundleIntegrity && !await hasValidBundleIntegrity(stagingDirectory, artifact)) {
6106
+ await rm5(archivePath, { force: true });
6107
+ if (artifact.archive.bundleIntegrity && !await hasValidBundleIntegrity(stagingDirectory, artifact, directFileDigests)) {
5724
6108
  throw new Error(`${artifact.name} extracted bundle did not match the pinned manifest`);
5725
6109
  }
5726
6110
  await chmod(extractedPath, 448);
5727
- const extracted = await lstat(extractedPath);
6111
+ const extracted = await lstat3(extractedPath);
5728
6112
  if (!extracted.isFile() || extracted.size !== artifact.executable.size) {
5729
6113
  throw new Error(`${artifact.name} extracted executable size did not match the pinned manifest`);
5730
6114
  }
@@ -5738,7 +6122,7 @@ async function installArtifact(rootDir, artifact, fetchImpl, onBytes, onVerify,
5738
6122
  await verifyMacCodeSignature(executablePath, artifact.name, timings.processTimeoutMs, spawnProcess);
5739
6123
  }
5740
6124
  if (!artifact.executable.repairInvalidMacSignature) {
5741
- const installed = await lstat(executablePath);
6125
+ const installed = await lstat3(executablePath);
5742
6126
  const installedState = {
5743
6127
  size: installed.size,
5744
6128
  sha256: await sha256File(executablePath)
@@ -5755,43 +6139,46 @@ async function installArtifact(rootDir, artifact, fetchImpl, onBytes, onVerify,
5755
6139
  await stageCompanions(stagingDirectory, artifact, artifactCompanions(artifact), fetchImpl, onBytes, artifact.archive.size, allowInsecureDownloadsForTests, skipExecutableProbeForTests, timings, spawnProcess);
5756
6140
  onVerify();
5757
6141
  const destinationDirectory = artifactDirectory(rootDir, artifact);
5758
- await mkdir3(path17.dirname(destinationDirectory), { recursive: true, mode: 448 });
5759
- await rm3(destinationDirectory, { recursive: true, force: true });
5760
- await rename2(stagingDirectory, destinationDirectory);
6142
+ await mkdir4(path19.dirname(destinationDirectory), { recursive: true, mode: 448 });
6143
+ await rm5(destinationDirectory, { recursive: true, force: true });
6144
+ await rename4(stagingDirectory, destinationDirectory);
5761
6145
  await chmod(destinationDirectory, 448);
6146
+ await Promise.all([artifact.archive, ...artifactCompanions(artifact).map((companion) => companion.archive)].map((archive) => rm5(partialDownloadPath(rootDir, archive), { force: true }).catch(() => {
6147
+ return;
6148
+ })));
5762
6149
  return artifactExecutablePath(rootDir, artifact);
5763
6150
  } catch (error) {
5764
- await rm3(stagingDirectory, { recursive: true, force: true });
6151
+ await rm5(stagingDirectory, { recursive: true, force: true });
5765
6152
  throw error;
5766
6153
  }
5767
6154
  }
5768
6155
  async function cleanStagingDirectories(rootDir) {
5769
- const entries = await readdir3(rootDir, { withFileTypes: true });
5770
- await Promise.all(entries.filter((entry) => entry.isDirectory() && entry.name.startsWith(".staging-")).map((entry) => rm3(path17.join(rootDir, entry.name), { recursive: true, force: true })));
6156
+ const entries = await readdir4(rootDir, { withFileTypes: true });
6157
+ await Promise.all(entries.filter((entry) => entry.isDirectory() && entry.name.startsWith(".staging-")).map((entry) => rm5(path19.join(rootDir, entry.name), { recursive: true, force: true })));
5771
6158
  }
5772
6159
  async function touchArtifactDirectory(rootDir, artifact) {
5773
6160
  const now = new Date;
5774
- await utimes(path17.dirname(artifactDirectory(rootDir, artifact)), now, now).catch(() => {
6161
+ await utimes(path19.dirname(artifactDirectory(rootDir, artifact)), now, now).catch(() => {
5775
6162
  return;
5776
6163
  });
5777
6164
  }
5778
6165
  function versionLeaseDirectory(rootDir, name, version) {
5779
- return path17.join(rootDir, LEASE_DIRECTORY, name, version);
6166
+ return path19.join(rootDir, LEASE_DIRECTORY, name, version);
5780
6167
  }
5781
6168
  async function acquireVersionLease(rootDir, artifact, openLeaseFile) {
5782
6169
  const leaseKey = `${rootDir}\x00${artifact.name}\x00${artifact.version}`;
5783
6170
  const existingLeasePath = processVersionLeases.get(leaseKey);
5784
- if (existingLeasePath && await lstat(existingLeasePath).then((entry) => entry.isFile() && !entry.isSymbolicLink(), () => false))
6171
+ if (existingLeasePath && await lstat3(existingLeasePath).then((entry) => entry.isFile() && !entry.isSymbolicLink(), () => false))
5785
6172
  return;
5786
6173
  processVersionLeases.delete(leaseKey);
5787
6174
  const owner = {
5788
- token: randomUUID5(),
6175
+ token: randomUUID6(),
5789
6176
  pid: process.pid,
5790
6177
  createdAt: new Date().toISOString()
5791
6178
  };
5792
6179
  const directory = versionLeaseDirectory(rootDir, artifact.name, artifact.version);
5793
- await mkdir3(directory, { recursive: true, mode: 448 });
5794
- const leasePath = path17.join(directory, `${owner.pid}-${owner.token}.json`);
6180
+ await mkdir4(directory, { recursive: true, mode: 448 });
6181
+ const leasePath = path19.join(directory, `${owner.pid}-${owner.token}.json`);
5795
6182
  const handle = await openLeaseFile(leasePath, "wx", 384);
5796
6183
  try {
5797
6184
  await handle.writeFile(JSON.stringify(owner), "utf8");
@@ -5799,7 +6186,7 @@ async function acquireVersionLease(rootDir, artifact, openLeaseFile) {
5799
6186
  await handle.close().catch(() => {
5800
6187
  return;
5801
6188
  });
5802
- await rm3(leasePath, { force: true }).catch(() => {
6189
+ await rm5(leasePath, { force: true }).catch(() => {
5803
6190
  return;
5804
6191
  });
5805
6192
  throw error;
@@ -5809,18 +6196,18 @@ async function acquireVersionLease(rootDir, artifact, openLeaseFile) {
5809
6196
  }
5810
6197
  async function versionHasLiveLease(rootDir, name, version, ownerProcessExists) {
5811
6198
  const directory = versionLeaseDirectory(rootDir, name, version);
5812
- const entries = await readdir3(directory, { withFileTypes: true }).catch(() => []);
6199
+ const entries = await readdir4(directory, { withFileTypes: true }).catch(() => []);
5813
6200
  let live = false;
5814
6201
  await Promise.all(entries.filter((entry) => entry.isFile()).map(async (entry) => {
5815
- const leasePath = path17.join(directory, entry.name);
6202
+ const leasePath = path19.join(directory, entry.name);
5816
6203
  try {
5817
- const parsed = JSON.parse(await readFile2(leasePath, "utf8"));
6204
+ const parsed = JSON.parse(await readFile3(leasePath, "utf8"));
5818
6205
  if (typeof parsed.token === "string" && typeof parsed.pid === "number" && typeof parsed.createdAt === "string" && ownerProcessExists(parsed.pid)) {
5819
6206
  live = true;
5820
6207
  return;
5821
6208
  }
5822
6209
  } catch {}
5823
- await rm3(leasePath, { force: true }).catch(() => {
6210
+ await rm5(leasePath, { force: true }).catch(() => {
5824
6211
  return;
5825
6212
  });
5826
6213
  }));
@@ -5835,11 +6222,11 @@ async function pruneSupersededVersions(rootDir, artifacts, retainSupersededMs, o
5835
6222
  }
5836
6223
  const staleBefore = Date.now() - retainSupersededMs;
5837
6224
  await Promise.all(Array.from(keepByName, async ([name, keep]) => {
5838
- const toolDir = path17.join(rootDir, name);
6225
+ const toolDir = path19.join(rootDir, name);
5839
6226
  try {
5840
- const entries = await readdir3(toolDir, { withFileTypes: true });
6227
+ const entries = await readdir4(toolDir, { withFileTypes: true });
5841
6228
  await Promise.all(entries.filter((entry) => entry.isDirectory() && !keep.has(entry.name)).map(async (entry) => {
5842
- const versionDir = path17.join(toolDir, entry.name);
6229
+ const versionDir = path19.join(toolDir, entry.name);
5843
6230
  try {
5844
6231
  if ((await stat3(versionDir)).mtimeMs > staleBefore)
5845
6232
  return;
@@ -5877,42 +6264,42 @@ function activationSetId(artifacts) {
5877
6264
  const rightKey = `${right.name}\x00${right.platform}\x00${right.architecture}`;
5878
6265
  return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0;
5879
6266
  });
5880
- return createHash4("sha256").update(JSON.stringify(identity)).digest("hex");
6267
+ return createHash6("sha256").update(JSON.stringify(identity)).digest("hex");
5881
6268
  }
5882
6269
  async function activateExecutables(rootDir, artifacts) {
5883
- const binRoot = path17.join(rootDir, "bin");
5884
- const binDir = path17.join(binRoot, activationSetId(artifacts));
5885
- await mkdir3(binRoot, { recursive: true, mode: 448 });
5886
- const binRootEntry = await lstat(binRoot);
6270
+ const binRoot = path19.join(rootDir, "bin");
6271
+ const binDir = path19.join(binRoot, activationSetId(artifacts));
6272
+ await mkdir4(binRoot, { recursive: true, mode: 448 });
6273
+ const binRootEntry = await lstat3(binRoot);
5887
6274
  if (!binRootEntry.isDirectory() || binRootEntry.isSymbolicLink()) {
5888
6275
  throw new Error(`Refusing unsafe toolchain activation root: ${binRoot}`);
5889
6276
  }
5890
6277
  await chmod(binRoot, 448);
5891
- await mkdir3(binDir, { recursive: true, mode: 448 });
5892
- const binEntry = await lstat(binDir);
6278
+ await mkdir4(binDir, { recursive: true, mode: 448 });
6279
+ const binEntry = await lstat3(binDir);
5893
6280
  if (!binEntry.isDirectory() || binEntry.isSymbolicLink()) {
5894
6281
  throw new Error(`Refusing unsafe toolchain activation directory: ${binDir}`);
5895
6282
  }
5896
6283
  await chmod(binDir, 448);
5897
6284
  const executables = {};
5898
6285
  const activate = async (linkName, target) => {
5899
- const activePath = path17.join(binDir, linkName);
5900
- const temporaryLink = path17.join(binDir, `.${linkName}-${randomUUID5()}.tmp`);
6286
+ const activePath = path19.join(binDir, linkName);
6287
+ const temporaryLink = path19.join(binDir, `.${linkName}-${randomUUID6()}.tmp`);
5901
6288
  const existingTarget = await readlink(activePath).catch(() => null);
5902
6289
  if (existingTarget !== target) {
5903
6290
  await symlink2(target, temporaryLink, "file");
5904
6291
  try {
5905
- await rename2(temporaryLink, activePath);
6292
+ await rename4(temporaryLink, activePath);
5906
6293
  } catch {
5907
6294
  try {
5908
- const active = await lstat(activePath).catch(() => null);
6295
+ const active = await lstat3(activePath).catch(() => null);
5909
6296
  if (active?.isDirectory()) {
5910
6297
  throw new Error(`Refusing to replace toolchain activation directory: ${activePath}`);
5911
6298
  }
5912
- await rm3(activePath, { force: true });
5913
- await rename2(temporaryLink, activePath);
6299
+ await rm5(activePath, { force: true });
6300
+ await rename4(temporaryLink, activePath);
5914
6301
  } catch (error) {
5915
- await rm3(temporaryLink, { force: true }).catch(() => {
6302
+ await rm5(temporaryLink, { force: true }).catch(() => {
5916
6303
  return;
5917
6304
  });
5918
6305
  throw error;
@@ -5945,14 +6332,14 @@ async function ensurePinnedToolchains(options2) {
5945
6332
  const timings = { ...DEFAULT_TIMINGS, ...options2.timingsForTests };
5946
6333
  const spawnProcess = options2.spawnForTests ?? spawn;
5947
6334
  const ownerProcessExists = options2.processExistsForTests ?? ((pid) => processExists(pid, options2.processKillForTests));
5948
- const rootDir = path17.join(options2.dataDir, TOOLCHAIN_DIRECTORY);
6335
+ const rootDir = path19.join(options2.dataDir, TOOLCHAIN_DIRECTORY);
5949
6336
  const totalTools = artifacts.length;
5950
6337
  const toolFractions = new Map(artifacts.map((artifact) => [artifact.name, 0]));
5951
6338
  const progress = (value) => {
5952
6339
  const overallFraction = totalTools === 0 ? 1 : Array.from(toolFractions.values()).reduce((sum, fraction) => sum + fraction, 0) / totalTools;
5953
6340
  onProgress({ ...value, totalTools, overallFraction });
5954
6341
  };
5955
- await mkdir3(rootDir, { recursive: true, mode: 448 });
6342
+ await mkdir4(rootDir, { recursive: true, mode: 448 });
5956
6343
  await chmod(rootDir, 448);
5957
6344
  progress({
5958
6345
  phase: "checking",
@@ -5963,10 +6350,19 @@ async function ensurePinnedToolchains(options2) {
5963
6350
  phase: "waiting",
5964
6351
  completedTools: 0,
5965
6352
  message
5966
- }), timings, options2.openLockFileForTests ?? open3, ownerProcessExists);
6353
+ }), timings, options2.openLockFileForTests ?? open5, ownerProcessExists);
5967
6354
  try {
5968
6355
  await cleanStagingDirectories(rootDir);
5969
- const statuses = await Promise.all(artifacts.map((artifact) => installationStatus(rootDir, artifact)));
6356
+ await prunePartialDownloads(rootDir, [...pinnedToolchainArtifacts(options2.platform, options2.architecture), ...artifacts].flatMap((artifact) => [
6357
+ artifact.archive,
6358
+ ...artifactCompanions(artifact).map((companion) => companion.archive)
6359
+ ]));
6360
+ const digests = await openFileStampStore(rootDir, {
6361
+ forceFullCheck: options2.fullVerification === true,
6362
+ fullCheckIntervalMs: timings.fullCheckIntervalMs,
6363
+ racyWindowMs: timings.racyStampWindowMs
6364
+ });
6365
+ const statuses = await Promise.all(artifacts.map((artifact) => installationStatus(rootDir, artifact, digests)));
5970
6366
  artifacts.forEach((artifact, index) => toolFractions.set(artifact.name, statuses[index].state === "valid" ? 1 : 0));
5971
6367
  const pending = artifacts.map((artifact, index) => ({ artifact, status: statuses[index] })).filter((entry) => entry.status.state !== "valid");
5972
6368
  let completedTools = totalTools - pending.length;
@@ -6023,24 +6419,25 @@ async function ensurePinnedToolchains(options2) {
6023
6419
  const failedInstallation = installations.find((result) => result.status === "rejected");
6024
6420
  if (failedInstallation)
6025
6421
  throw failedInstallation.reason;
6026
- await Promise.all(artifacts.filter((artifact) => artifact.executable.repairInvalidMacSignature).map((artifact) => refreshRepairableArtifact(rootDir, artifact, options2.skipExecutableProbeForTests ?? false, timings.processTimeoutMs, spawnProcess)));
6422
+ await Promise.all(artifacts.filter((artifact) => artifact.executable.repairInvalidMacSignature).map((artifact) => refreshRepairableArtifact(rootDir, artifact, digests, options2.skipExecutableProbeForTests ?? false, timings.processTimeoutMs, spawnProcess)));
6027
6423
  await options2.beforeFinalVerificationForTests?.();
6028
6424
  const finalValidity = await Promise.all(artifacts.map(async (artifact) => {
6029
- if (!await isValidInstallation(rootDir, artifact))
6425
+ if (!await isValidInstallation(rootDir, artifact, digests))
6030
6426
  return false;
6031
- const executable = await lstat(artifactExecutablePath(rootDir, artifact)).catch(() => null);
6427
+ const executable = await lstat3(artifactExecutablePath(rootDir, artifact)).catch(() => null);
6032
6428
  return executable?.isFile() === true && !executable.isSymbolicLink();
6033
6429
  }));
6034
6430
  if (finalValidity.some((valid) => !valid)) {
6035
6431
  throw new Error("One or more pinned Orkestrator tools failed final verification");
6036
6432
  }
6433
+ await digests.save(artifacts.map((artifact) => artifactDirectory(rootDir, artifact)));
6037
6434
  const result = await activateExecutables(rootDir, artifacts);
6038
6435
  await Promise.all(artifacts.map((artifact) => touchArtifactDirectory(rootDir, artifact)));
6039
6436
  if (!options2.skipVersionLeaseForTests) {
6040
- await Promise.all(artifacts.map((artifact) => acquireVersionLease(rootDir, artifact, options2.openLeaseFileForTests ?? open3)));
6437
+ await Promise.all(artifacts.map((artifact) => acquireVersionLease(rootDir, artifact, options2.openLeaseFileForTests ?? open5)));
6041
6438
  }
6042
6439
  await options2.onActivated?.(result);
6043
- await pruneSupersededVersions(rootDir, artifacts, timings.retainSupersededMs, ownerProcessExists, options2.removeSupersededVersionForTests ?? rm3);
6440
+ await pruneSupersededVersions(rootDir, artifacts, timings.retainSupersededMs, ownerProcessExists, options2.removeSupersededVersionForTests ?? rm5);
6044
6441
  artifacts.forEach((artifact) => toolFractions.set(artifact.name, 1));
6045
6442
  progress({
6046
6443
  phase: "ready",
@@ -6052,30 +6449,35 @@ async function ensurePinnedToolchains(options2) {
6052
6449
  await installLock.release();
6053
6450
  }
6054
6451
  }
6055
- var INSTALL_LOCK = ".install.lock", LEASE_DIRECTORY = ".leases", LOCK_STALE_AFTER_MS, LOCK_WAIT_TIMEOUT_MS, LOCK_POLL_MS = 250, DOWNLOAD_TIMEOUT_MS, PROCESS_TIMEOUT_MS = 15000, RETAIN_SUPERSEDED_MS, DEFAULT_TIMINGS, processVersionLeases;
6452
+ var INSTALL_LOCK = ".install.lock", LEASE_DIRECTORY = ".leases", LOCK_STALE_AFTER_MS, LOCK_WAIT_TIMEOUT_MS, LOCK_POLL_MS = 250, PROCESS_TIMEOUT_MS = 15000, RETAIN_SUPERSEDED_MS, DEFAULT_TIMINGS, processVersionLeases;
6056
6453
  var init_manager = __esm(() => {
6057
6454
  init_tar_stream();
6058
6455
  init_yauzl();
6059
6456
  init_manifest();
6060
6457
  init_layout();
6458
+ init_download();
6459
+ init_file_stamps();
6061
6460
  LOCK_STALE_AFTER_MS = 10 * 60 * 1000;
6062
6461
  LOCK_WAIT_TIMEOUT_MS = 12 * 60 * 1000;
6063
- DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;
6064
6462
  RETAIN_SUPERSEDED_MS = 14 * 24 * 60 * 60 * 1000;
6065
6463
  DEFAULT_TIMINGS = {
6066
6464
  lockStaleAfterMs: LOCK_STALE_AFTER_MS,
6067
6465
  lockWaitTimeoutMs: LOCK_WAIT_TIMEOUT_MS,
6068
6466
  lockPollMs: LOCK_POLL_MS,
6069
- downloadTimeoutMs: DOWNLOAD_TIMEOUT_MS,
6467
+ downloadIdleTimeoutMs: DEFAULT_DOWNLOAD_TIMINGS.idleTimeoutMs,
6468
+ downloadAttempts: DEFAULT_DOWNLOAD_TIMINGS.attempts,
6469
+ downloadRetryDelayMs: DEFAULT_DOWNLOAD_TIMINGS.retryDelayMs,
6070
6470
  processTimeoutMs: PROCESS_TIMEOUT_MS,
6071
- retainSupersededMs: RETAIN_SUPERSEDED_MS
6471
+ retainSupersededMs: RETAIN_SUPERSEDED_MS,
6472
+ fullCheckIntervalMs: FULL_CHECK_INTERVAL_MS,
6473
+ racyStampWindowMs: RACY_STAMP_WINDOW_MS
6072
6474
  };
6073
6475
  processVersionLeases = new Map;
6074
6476
  });
6075
6477
 
6076
6478
  // ../toolchain/src/platform-selection.ts
6077
6479
  import { promises as fs7 } from "fs";
6078
- import path18 from "path";
6480
+ import path20 from "path";
6079
6481
  async function readJsonFile(filePath) {
6080
6482
  try {
6081
6483
  return JSON.parse(await fs7.readFile(filePath, "utf8"));
@@ -6084,7 +6486,7 @@ async function readJsonFile(filePath) {
6084
6486
  }
6085
6487
  }
6086
6488
  async function loadAgentPlatformSelection(dataDir) {
6087
- const config = await readJsonFile(path18.join(dataDir, AGENT_CONFIG_FILE));
6489
+ const config = await readJsonFile(path20.join(dataDir, AGENT_CONFIG_FILE));
6088
6490
  if (config && typeof config === "object" && !Array.isArray(config)) {
6089
6491
  const global2 = config.global;
6090
6492
  if (global2 && typeof global2 === "object" && !Array.isArray(global2)) {
@@ -6100,7 +6502,7 @@ async function loadAgentPlatformSelection(dataDir) {
6100
6502
  needsFirstRunChoice: false
6101
6503
  };
6102
6504
  }
6103
- const sidecar = await readJsonFile(path18.join(dataDir, AGENT_PLATFORM_SELECTION_FILE));
6505
+ const sidecar = await readJsonFile(path20.join(dataDir, AGENT_PLATFORM_SELECTION_FILE));
6104
6506
  if (sidecar && typeof sidecar === "object" && !Array.isArray(sidecar)) {
6105
6507
  const enabled = normalizeAgentPlatforms(sidecar.enabled, []);
6106
6508
  if (enabled.length > 0)
@@ -6114,9 +6516,9 @@ var init_platform_selection = __esm(() => {
6114
6516
  });
6115
6517
 
6116
6518
  // ../toolchain/src/install.ts
6117
- import { randomUUID as randomUUID6 } from "crypto";
6118
- import { lstat as lstat2, mkdir as mkdir4, readdir as readdir4, readlink as readlink2, rename as rename3, rm as rm4, symlink as symlink3 } from "fs/promises";
6119
- import path19 from "path";
6519
+ import { randomUUID as randomUUID7 } from "crypto";
6520
+ import { lstat as lstat4, mkdir as mkdir5, readdir as readdir5, readlink as readlink2, rename as rename5, rm as rm6, symlink as symlink3 } from "fs/promises";
6521
+ import path21 from "path";
6120
6522
  async function resolveToolchainSelection(options2) {
6121
6523
  const known = Object.keys(PINNED_TOOL_VERSIONS);
6122
6524
  const withSupportTools = (chosen) => known.filter((name) => chosen.has(name) || isSupportToolName(name));
@@ -6152,6 +6554,7 @@ async function installPinnedToolchains(options2) {
6152
6554
  ...options2.architecture ? { architecture: options2.architecture } : {},
6153
6555
  ...options2.fetchImpl ? { fetchImpl: options2.fetchImpl } : {},
6154
6556
  ...options2.onProgress ? { onProgress: options2.onProgress } : {},
6557
+ ...options2.fullVerification ? { fullVerification: true } : {},
6155
6558
  onActivated: async (result) => {
6156
6559
  const before = await toolsInCurrent(result.rootDir);
6157
6560
  currentBinDir = await pointCurrentAt(result.rootDir, result.binDir);
@@ -6175,29 +6578,29 @@ async function installPinnedToolchains(options2) {
6175
6578
  };
6176
6579
  }
6177
6580
  async function toolsInCurrent(rootDir) {
6178
- const entries = await readdir4(path19.join(rootDir, "bin", CURRENT_TOOLCHAIN_LINK)).catch(() => []);
6581
+ const entries = await readdir5(path21.join(rootDir, "bin", CURRENT_TOOLCHAIN_LINK)).catch(() => []);
6179
6582
  return Object.keys(PINNED_TOOL_VERSIONS).filter((tool) => entries.includes(tool));
6180
6583
  }
6181
6584
  async function pointCurrentAt(rootDir, binDir) {
6182
- const binRoot = path19.join(rootDir, "bin");
6183
- if (path19.dirname(binDir) !== binRoot) {
6585
+ const binRoot = path21.join(rootDir, "bin");
6586
+ if (path21.dirname(binDir) !== binRoot) {
6184
6587
  throw new Error(`Activation directory ${binDir} is not directly inside ${binRoot}`);
6185
6588
  }
6186
- const link = path19.join(binRoot, CURRENT_TOOLCHAIN_LINK);
6187
- const target = path19.basename(binDir);
6188
- await mkdir4(binRoot, { recursive: true, mode: 448 });
6189
- const existing = await lstat2(link).catch(() => null);
6589
+ const link = path21.join(binRoot, CURRENT_TOOLCHAIN_LINK);
6590
+ const target = path21.basename(binDir);
6591
+ await mkdir5(binRoot, { recursive: true, mode: 448 });
6592
+ const existing = await lstat4(link).catch(() => null);
6190
6593
  if (existing && !existing.isSymbolicLink()) {
6191
6594
  throw new Error(`Refusing to replace ${link}: it is not a symbolic link`);
6192
6595
  }
6193
6596
  if (existing && await readlink2(link) === target)
6194
6597
  return link;
6195
- const temporary = path19.join(binRoot, `.${CURRENT_TOOLCHAIN_LINK}-${randomUUID6()}.tmp`);
6598
+ const temporary = path21.join(binRoot, `.${CURRENT_TOOLCHAIN_LINK}-${randomUUID7()}.tmp`);
6196
6599
  await symlink3(target, temporary, "dir");
6197
6600
  try {
6198
- await rename3(temporary, link);
6601
+ await rename5(temporary, link);
6199
6602
  } catch (error) {
6200
- await rm4(temporary, { force: true }).catch(() => {
6603
+ await rm6(temporary, { force: true }).catch(() => {
6201
6604
  return;
6202
6605
  });
6203
6606
  throw error;
@@ -8211,6 +8614,7 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
8211
8614
  "session.created": "A session was created or recovered.",
8212
8615
  "session.delete-failed": "Deleting a session failed.",
8213
8616
  "session.fork-failed": "Forking a session failed.",
8617
+ "session.policy-widening-refused": "A config request tried to widen a live session's execution policy and was refused; widened names the axes.",
8214
8618
  "session.rename-failed": "Renaming a session failed.",
8215
8619
  "session.resolve-failed": "A session could not be found or loaded for a request; action names the request.",
8216
8620
  "session.rewind-failed": "Rewinding session files failed.",
@@ -8343,6 +8747,7 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
8343
8747
  "backend.keychain-link-remove-failed": "An agent-test profile kept a legacy link to the host keychain.",
8344
8748
  "backend.start-failed": "The Local backend did not start; continuing with remote machines.",
8345
8749
  "clipboard.write-failed": "Writing text to the system clipboard failed.",
8750
+ "dev-mode.ignored-packaged": "A packaged app was launched with ELECTRON_DEV=1 and ignored it; it loads its bundled renderer.",
8346
8751
  "instance.already-running": "Another instance holds this data directory; this one will quit.",
8347
8752
  "main-thread.stalled": "A timer fired late, so windows, IPC and the stdout reader waited.",
8348
8753
  "quit.stopping-backend": "The app is quitting and has asked the Local backend to stop.",
@@ -8415,7 +8820,8 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
8415
8820
  description: "Preparing the pinned agent toolchain at desktop startup.",
8416
8821
  events: {
8417
8822
  "bootstrap-progress.show-failed": "The toolchain progress window could not be shown.",
8418
- "prepare.failed": "Preparing the pinned agent tools failed."
8823
+ "prepare.failed": "Preparing the pinned agent tools failed.",
8824
+ "prepare.ready": "The pinned agent tools were verified and activated; durationMs is how long startup waited."
8419
8825
  }
8420
8826
  },
8421
8827
  "artifact-host": {
@@ -8603,6 +9009,7 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
8603
9009
  description: "Native agent sessions and what the backend reads from their bridges.",
8604
9010
  events: {
8605
9011
  "catalogue.outdated-bridge": "A bridge predates the command catalogue, so its commands stay unavailable.",
9012
+ "compact.instructions-ignored": "A bridge compacted without confirming the instructions sent with /compact: it predates them.",
8606
9013
  "handoff.summary-read-failed": "Change summaries could not be read for a handoff, so the carrier says they are unmeasured.",
8607
9014
  "handoff.consume-failed": "A delivered handoff could not be marked consumed.",
8608
9015
  "job.pr-refresh-rollback-failed": "Rolling back a pull request refresh for a job failed.",
@@ -8858,6 +9265,8 @@ var TMUX_LOG_AREAS = defineLogAreas({
8858
9265
  "interactive.snapshot-failed": "An interactive snapshot failed; expected while a pane is closing.",
8859
9266
  "signal.arm-failed": "The Claude state signal could not be armed.",
8860
9267
  "signal.degraded": "The Claude state signal missed a change or rang too often, so polling stays at one second until it is re-armed.",
9268
+ "hook-signal.arm-failed": "The tmux hook doorbell could not be armed.",
9269
+ "hook-signal.degraded": "The tmux hook doorbell missed a hook, so idle tabs poll every second until it is re-armed.",
8861
9270
  "pr-refresh.schedule-failed": "A pull request refresh after a turn could not be scheduled.",
8862
9271
  "pr-probe.failed": "Probing for a pull request an agent created failed.",
8863
9272
  "activity.persist-failed": "Tmux tab activity could not be saved.",
@@ -9039,6 +9448,7 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
9039
9448
  "work.move-failed": "Work could not move to the main coordinator.",
9040
9449
  "wake.observe-remote-workflow-failed": "A remote workflow could not be observed for status wakes.",
9041
9450
  "wake.observe-pull-request-failed": "A pull request could not be observed for status wakes.",
9451
+ "wake.observe-feature-plan-failed": "A feature plan could not be observed for status wakes.",
9042
9452
  "wake.observe-workflow-failed": "A workflow could not be observed for status wakes.",
9043
9453
  "wake.deliver-failed": "A workflow status wake could not be delivered; the next pass retries.",
9044
9454
  "wake.waiting-check-failed": "A waiting worker could not be checked; the next pass retries.",
@@ -9050,7 +9460,11 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
9050
9460
  "store.invalid-workspace": "An invalid coordinator workspace record was ignored.",
9051
9461
  "store.workflows-cleared": "The workflow store was full, so a batch of its oldest finished records was removed.",
9052
9462
  "store.workflows-in-use": "The workflow store was full and every record was still in use, so new work was refused.",
9053
- "remote-worker.settle-failed": "A remote worker could not be settled."
9463
+ "remote-worker.settle-failed": "A remote worker could not be settled.",
9464
+ "checkout.merge-followed": "After an environment's PR merged, the project checkout was fast-forwarded, or `outcome` says why not.",
9465
+ "checkout.merge-follow-failed": "Fast-forwarding the project checkout failed, after an environment's PR merged or before mail woke the main coordinator.",
9466
+ "checkout.mail-follow": "Before mail woke the main coordinator, the project checkout was fast-forwarded, or `outcome` says why not (`timed-out`, `failed`).",
9467
+ "checkout.mail-follow-failed": "Before mail woke the main coordinator, checking whether to fast-forward the project checkout failed; the mail was delivered anyway."
9054
9468
  }
9055
9469
  }
9056
9470
  });
@@ -9082,6 +9496,7 @@ var REVIEW_LOG_AREAS = defineLogAreas({
9082
9496
  "gh.pr-list-unparseable": "`gh pr list` returned nothing that parses. Sizes only, never the output.",
9083
9497
  "monitor.start-failed": "Monitoring could not start for a newly opened pull request.",
9084
9498
  "cleanup-scheduler.missing": "A merged pull request was seen, but this runtime has no merge cleanup scheduler.",
9499
+ "checkout.follow-merge-lookup-failed": "A merged pull request's project could not be read, so its checkout was not fast-forwarded.",
9085
9500
  "auto-merge.evaluation-failed": "Evaluating an environment for auto-merge failed.",
9086
9501
  "auto-merge.merge-failed": "Auto-merge could not merge a pull request; the attempt is held and retried.",
9087
9502
  "auto-merge.resolve-failed": "Auto-merge could not launch Resolve for a pull request; the attempt is held and retried.",
@@ -9125,6 +9540,8 @@ var AGENT_ACCOUNTS_LOG_AREAS = defineLogAreas({
9125
9540
  "container-sync.failed": "Handing a login or account to a container failed; `step` says which part.",
9126
9541
  "last-usage.save-failed": "The last plan usage reading could not be saved; the next save retries.",
9127
9542
  "login-cleanup.failed": "A temporary login could not be cleaned up.",
9543
+ "login-renewal.failed": "Renewing an idle account's sign-in to read its usage failed; it is retried after a backoff.",
9544
+ "login-renewal.not-extended": "Claude Code ran to renew an idle account's sign-in, but its token is still lapsed.",
9128
9545
  "login-refresh.deferred": "Containers were not told to refresh their login now; they reconcile from its durable generation."
9129
9546
  }
9130
9547
  }
@@ -9138,6 +9555,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
9138
9555
  "portable-inputs.relay-missing": "Docker is rootless and the image predates the staged-input relay, so the container cannot read them until rebuilt.",
9139
9556
  "project-seed.refused": "A project .env, .env.local or opencode.json was not copied into a new container: a link, not a regular file, outside the project, too large or unreadable.",
9140
9557
  "opencode.warm-incomplete": "OpenCode did not finish loading /workspace in a container.",
9558
+ "lifecycle-event.reconcile-failed": "Reconciling an environment after a container start or stop event failed; the next status read retries.",
9141
9559
  "login-keeper.pass-failed": "A Claude login keeper pass failed; the next interval retries.",
9142
9560
  "login-keeper.refresh-failed": "Refreshing the host Claude login failed. Fixed text: CLI output can hold credentials.",
9143
9561
  "login-keeper.refresh-not-extended": "Refreshing the host Claude login did not extend its expiry.",
@@ -9261,7 +9679,7 @@ var GRAPH_LOG_AREAS = defineLogAreas({
9261
9679
  // ../protocol/src/log-vocabulary/nodes.ts
9262
9680
  var NODES_LOG_AREAS = defineLogAreas({
9263
9681
  nodes: {
9264
- description: "Command nodes: links, handovers, leaf mail and project copies.",
9682
+ description: "Command nodes: links, handovers, leaf mail, ticket sync and project copies.",
9265
9683
  events: {
9266
9684
  "actions.resume-failed": "Approved actions could not be resumed; a later pass retries.",
9267
9685
  "project-copy.notify-failed": "The coordinator could not be told a project copy finished.",
@@ -9273,7 +9691,11 @@ var NODES_LOG_AREAS = defineLogAreas({
9273
9691
  "verification.record-failed": "A node verification could not be recorded.",
9274
9692
  "profile.record-failed": "A node profile could not be recorded.",
9275
9693
  "detach.unconfirmed": "A forgotten node has not confirmed the detach yet.",
9276
- "handover.recovery-pending": "Command handover recovery is still pending."
9694
+ "handover.recovery-pending": "Command handover recovery is still pending.",
9695
+ "ticket-sync.work-record-failed": "A remote build started but its ticket work location could not be saved.",
9696
+ "ticket-sync.failed": "A Kanban sync with a node failed; it is retried.",
9697
+ "ticket-sync.unknown-project": "A node sent ticket changes for a project that no longer exists here.",
9698
+ "ticket-sync.forget-failed": "A detached command node's ticket copies could not be released."
9277
9699
  }
9278
9700
  }
9279
9701
  });
@@ -10238,7 +10660,7 @@ import path5 from "path";
10238
10660
  // ../../apps/backend/package.json
10239
10661
  var package_default = {
10240
10662
  name: "@orkestrator/backend",
10241
- version: "2.35.5-beta",
10663
+ version: "2.36.0",
10242
10664
  private: true,
10243
10665
  type: "module",
10244
10666
  exports: {
@@ -13041,9 +13463,128 @@ async function readPatch(io, options2) {
13041
13463
  }
13042
13464
  return parsed;
13043
13465
  }
13044
-
13045
- // src/client/commands/workflows.ts
13046
- init_agent_platforms();
13466
+
13467
+ // src/client/commands/workflows.ts
13468
+ init_agent_platforms();
13469
+
13470
+ // ../protocol/src/public-api-resources.ts
13471
+ function isPublicTranscriptUnchanged(value) {
13472
+ return value.status === "unchanged";
13473
+ }
13474
+ var PUBLIC_CHANGE_SCOPES = Object.freeze(["environment"]);
13475
+ var AGENT_PLATFORM_KEYS = ["claude", "codex", "cursor", "grok", "opencode", "pi"];
13476
+ function agentSettingDescriptors(scope) {
13477
+ const application = "next-session";
13478
+ return [
13479
+ {
13480
+ key: "agent.defaultAgent",
13481
+ scope,
13482
+ type: "agent",
13483
+ inherits: true,
13484
+ application,
13485
+ description: "Agent platform used when a launch does not name one."
13486
+ },
13487
+ ...AGENT_PLATFORM_KEYS.flatMap((platform) => [
13488
+ {
13489
+ key: `agent.${platform}.mode`,
13490
+ scope,
13491
+ type: "agent-mode",
13492
+ inherits: true,
13493
+ application,
13494
+ description: `Launch mode (native or terminal) for ${platform}.`
13495
+ },
13496
+ {
13497
+ key: `agent.${platform}.model`,
13498
+ scope,
13499
+ type: "string",
13500
+ inherits: true,
13501
+ application,
13502
+ description: `Default model for new ${platform} sessions.`
13503
+ },
13504
+ {
13505
+ key: `agent.${platform}.reasoningEffort`,
13506
+ scope,
13507
+ type: "string",
13508
+ inherits: true,
13509
+ application,
13510
+ description: `Default reasoning level for new ${platform} sessions.`
13511
+ },
13512
+ {
13513
+ key: `agent.${platform}.fastMode`,
13514
+ scope,
13515
+ type: "boolean",
13516
+ inherits: true,
13517
+ application,
13518
+ description: `Default speed for new ${platform} sessions (true is Fast).`
13519
+ }
13520
+ ])
13521
+ ];
13522
+ }
13523
+ var PUBLIC_PROJECT_SETTINGS = Object.freeze([
13524
+ {
13525
+ key: "defaultBranch",
13526
+ scope: "project",
13527
+ type: "string",
13528
+ inherits: false,
13529
+ application: "next-environment",
13530
+ description: "Branch new environments are created from."
13531
+ },
13532
+ {
13533
+ key: "prBaseBranch",
13534
+ scope: "project",
13535
+ type: "string",
13536
+ inherits: false,
13537
+ application: "applied",
13538
+ description: "Base branch for pull requests and diff baselines."
13539
+ },
13540
+ {
13541
+ key: "defaultPortMappings",
13542
+ scope: "project",
13543
+ type: "port-mappings",
13544
+ inherits: false,
13545
+ environmentTypes: ["container"],
13546
+ application: "next-environment",
13547
+ description: "Port mappings copied into new container environments."
13548
+ },
13549
+ {
13550
+ key: "filesToCopy",
13551
+ scope: "project",
13552
+ type: "string-list",
13553
+ inherits: false,
13554
+ application: "next-environment",
13555
+ description: "Untracked files copied into new environments."
13556
+ },
13557
+ {
13558
+ key: "entryPort",
13559
+ scope: "project",
13560
+ type: "port",
13561
+ inherits: false,
13562
+ application: "next-environment",
13563
+ description: "Default preview entry port for new environments."
13564
+ },
13565
+ ...agentSettingDescriptors("project")
13566
+ ]);
13567
+ var PUBLIC_ENVIRONMENT_SETTINGS = Object.freeze([
13568
+ {
13569
+ key: "portMappings",
13570
+ scope: "environment",
13571
+ type: "port-mappings",
13572
+ inherits: false,
13573
+ environmentTypes: ["container"],
13574
+ application: "next-start",
13575
+ description: "Container port mappings; a running container adopts them on recreate."
13576
+ },
13577
+ {
13578
+ key: "allowedDomains",
13579
+ scope: "environment",
13580
+ type: "domain-list",
13581
+ inherits: true,
13582
+ environmentTypes: ["container"],
13583
+ application: "next-start",
13584
+ description: "Restricted-network allowlist; unset inherits the global list. A running container whose image supports it applies the change immediately (reported as applied)."
13585
+ },
13586
+ ...agentSettingDescriptors("environment")
13587
+ ]);
13047
13588
 
13048
13589
  // src/client/commands/session.ts
13049
13590
  import path8 from "path";
@@ -13841,7 +14382,7 @@ var sessionCommands = [
13841
14382
  path: ["session", "transcript"],
13842
14383
  action: "session.transcript",
13843
14384
  summary: "Read a bounded transcript page; --follow polls for new messages.",
13844
- description: "Pages are oldest-first and hold at most --limit messages (max 100). Pass the returned olderCursor as --before for earlier history. --follow --jsonl streams one record per new message by polling snapshots; it stops at --timeout or Ctrl+C and never affects the session.",
14385
+ description: "Pages are oldest-first and hold at most --limit messages (max 100). Pass the returned olderCursor as --before for earlier history. --follow --jsonl streams one record per new message by polling snapshots (a backend that supports it answers an unchanged transcript without resending it); it stops at --timeout or Ctrl+C and never affects the session.",
13845
14386
  positionals: [{ name: "session", required: true }],
13846
14387
  options: [
13847
14388
  {
@@ -13896,6 +14437,7 @@ var sessionCommands = [
13896
14437
  }
13897
14438
  const seen = new Set;
13898
14439
  let lastToken = null;
14440
+ let conditional = null;
13899
14441
  let emitted = 0;
13900
14442
  const emit = (record) => {
13901
14443
  if (context.global.output === "jsonl")
@@ -13909,10 +14451,15 @@ var sessionCommands = [
13909
14451
  };
13910
14452
  try {
13911
14453
  await observe(async () => {
13912
- const page = await session.read("session.transcript", {
14454
+ conditional ??= (await session.capabilities()).features.transcriptKnownToken === true;
14455
+ const answer = await session.read("session.transcript", {
13913
14456
  ...input,
13914
- limit: PUBLIC_API_LIMITS.transcriptMaxMessages
14457
+ limit: PUBLIC_API_LIMITS.transcriptMaxMessages,
14458
+ ...conditional && lastToken !== null ? { knownToken: lastToken } : {}
13915
14459
  });
14460
+ if (isPublicTranscriptUnchanged(answer))
14461
+ return { done: false };
14462
+ const page = answer;
13916
14463
  if (page.token !== null && page.token === lastToken)
13917
14464
  return { done: false };
13918
14465
  if (lastToken !== null && page.messages.length > 0 && !page.messages.some((m) => seen.has(m.id))) {
@@ -16978,122 +17525,6 @@ var graphCommands = [
16978
17525
  }
16979
17526
  ];
16980
17527
 
16981
- // ../protocol/src/public-api-resources.ts
16982
- var PUBLIC_CHANGE_SCOPES = Object.freeze(["environment"]);
16983
- var AGENT_PLATFORM_KEYS = ["claude", "codex", "cursor", "grok", "opencode", "pi"];
16984
- function agentSettingDescriptors(scope) {
16985
- const application = "next-session";
16986
- return [
16987
- {
16988
- key: "agent.defaultAgent",
16989
- scope,
16990
- type: "agent",
16991
- inherits: true,
16992
- application,
16993
- description: "Agent platform used when a launch does not name one."
16994
- },
16995
- ...AGENT_PLATFORM_KEYS.flatMap((platform) => [
16996
- {
16997
- key: `agent.${platform}.mode`,
16998
- scope,
16999
- type: "agent-mode",
17000
- inherits: true,
17001
- application,
17002
- description: `Launch mode (native or terminal) for ${platform}.`
17003
- },
17004
- {
17005
- key: `agent.${platform}.model`,
17006
- scope,
17007
- type: "string",
17008
- inherits: true,
17009
- application,
17010
- description: `Default model for new ${platform} sessions.`
17011
- },
17012
- {
17013
- key: `agent.${platform}.reasoningEffort`,
17014
- scope,
17015
- type: "string",
17016
- inherits: true,
17017
- application,
17018
- description: `Default reasoning level for new ${platform} sessions.`
17019
- },
17020
- {
17021
- key: `agent.${platform}.fastMode`,
17022
- scope,
17023
- type: "boolean",
17024
- inherits: true,
17025
- application,
17026
- description: `Default speed for new ${platform} sessions (true is Fast).`
17027
- }
17028
- ])
17029
- ];
17030
- }
17031
- var PUBLIC_PROJECT_SETTINGS = Object.freeze([
17032
- {
17033
- key: "defaultBranch",
17034
- scope: "project",
17035
- type: "string",
17036
- inherits: false,
17037
- application: "next-environment",
17038
- description: "Branch new environments are created from."
17039
- },
17040
- {
17041
- key: "prBaseBranch",
17042
- scope: "project",
17043
- type: "string",
17044
- inherits: false,
17045
- application: "applied",
17046
- description: "Base branch for pull requests and diff baselines."
17047
- },
17048
- {
17049
- key: "defaultPortMappings",
17050
- scope: "project",
17051
- type: "port-mappings",
17052
- inherits: false,
17053
- environmentTypes: ["container"],
17054
- application: "next-environment",
17055
- description: "Port mappings copied into new container environments."
17056
- },
17057
- {
17058
- key: "filesToCopy",
17059
- scope: "project",
17060
- type: "string-list",
17061
- inherits: false,
17062
- application: "next-environment",
17063
- description: "Untracked files copied into new environments."
17064
- },
17065
- {
17066
- key: "entryPort",
17067
- scope: "project",
17068
- type: "port",
17069
- inherits: false,
17070
- application: "next-environment",
17071
- description: "Default preview entry port for new environments."
17072
- },
17073
- ...agentSettingDescriptors("project")
17074
- ]);
17075
- var PUBLIC_ENVIRONMENT_SETTINGS = Object.freeze([
17076
- {
17077
- key: "portMappings",
17078
- scope: "environment",
17079
- type: "port-mappings",
17080
- inherits: false,
17081
- environmentTypes: ["container"],
17082
- application: "next-start",
17083
- description: "Container port mappings; a running container adopts them on recreate."
17084
- },
17085
- {
17086
- key: "allowedDomains",
17087
- scope: "environment",
17088
- type: "domain-list",
17089
- inherits: true,
17090
- environmentTypes: ["container"],
17091
- application: "next-start",
17092
- description: "Restricted-network allowlist; unset inherits the global list. A running container whose image supports it applies the change immediately (reported as applied)."
17093
- },
17094
- ...agentSettingDescriptors("environment")
17095
- ]);
17096
-
17097
17528
  // src/client/commands/changes.ts
17098
17529
  var SCOPE_LABELS = {
17099
17530
  "changes.scope.environment-net": "Environment changes",
@@ -17674,6 +18105,10 @@ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
17674
18105
  // src/client/transport.ts
17675
18106
  var DEFAULT_REQUEST_TIMEOUT_MS = 60000;
17676
18107
  var INVOKE_PATH = "/__orkestrator/invoke";
18108
+ var NO_BYTES = new Uint8Array;
18109
+ function refusedUnread(status) {
18110
+ return status >= 300 && status < 400 || status === 401 || status === 403;
18111
+ }
17677
18112
  function connectionRefused(error) {
17678
18113
  const code = error?.code;
17679
18114
  const cause = error?.cause?.code;
@@ -17707,9 +18142,6 @@ class GatewayTransport {
17707
18142
  let token = await this.target.readToken();
17708
18143
  let response = await sendWithBudget(token);
17709
18144
  if (response.status === 401 && !options2.mutation) {
17710
- await response.body?.cancel().catch(() => {
17711
- return;
17712
- });
17713
18145
  token = await this.target.readToken();
17714
18146
  response = await sendWithBudget(token);
17715
18147
  }
@@ -17740,7 +18172,13 @@ class GatewayTransport {
17740
18172
  signal: controller.signal
17741
18173
  });
17742
18174
  if (!response.body)
17743
- return response;
18175
+ return { status: response.status, bytes: NO_BYTES };
18176
+ if (refusedUnread(response.status)) {
18177
+ await response.body.cancel().catch(() => {
18178
+ return;
18179
+ });
18180
+ return { status: response.status, bytes: NO_BYTES };
18181
+ }
17744
18182
  const abort = new Promise((_, reject) => {
17745
18183
  if (controller.signal.aborted)
17746
18184
  reject(controller.signal.reason);
@@ -17753,10 +18191,7 @@ class GatewayTransport {
17753
18191
  readStreamBounded(response.body, PUBLIC_API_LIMITS.responseMaxBytes, () => new CliError("response-invalid", "The backend response exceeded the client limit"), controller.signal),
17754
18192
  abort
17755
18193
  ]);
17756
- return new Response(Buffer.from(bytes), {
17757
- status: response.status,
17758
- statusText: response.statusText
17759
- });
18194
+ return { status: response.status, bytes };
17760
18195
  } catch (error) {
17761
18196
  if (error instanceof CliError)
17762
18197
  throw error;
@@ -17769,30 +18204,16 @@ class GatewayTransport {
17769
18204
  options2.signal?.removeEventListener("abort", onAbort);
17770
18205
  }
17771
18206
  }
17772
- async decode(response, options2) {
18207
+ decode(response, options2) {
17773
18208
  if (response.status >= 300 && response.status < 400) {
17774
- await response.body?.cancel().catch(() => {
17775
- return;
17776
- });
17777
18209
  throw new CliError("connection-failed", "The backend answered with a redirect; redirects are never followed with credentials");
17778
18210
  }
17779
18211
  if (response.status === 401 || response.status === 403) {
17780
- await response.body?.cancel().catch(() => {
17781
- return;
17782
- });
17783
18212
  throw new CliError("auth-failed", response.status === 401 ? "The backend rejected the credential" : "The backend refused this client (origin or permission)");
17784
18213
  }
17785
- let bytes;
17786
- try {
17787
- bytes = response.body ? await readStreamBounded(response.body, PUBLIC_API_LIMITS.responseMaxBytes, () => new CliError("response-invalid", "The backend response exceeded the client limit")) : new Uint8Array;
17788
- } catch (error) {
17789
- if (error instanceof CliError)
17790
- throw error;
17791
- throw new CliError(options2.mutation ? "transport-uncertain" : "connection-failed", "The backend response was interrupted");
17792
- }
17793
18214
  let payload;
17794
18215
  try {
17795
- payload = JSON.parse(new TextDecoder().decode(bytes));
18216
+ payload = JSON.parse(new TextDecoder().decode(response.bytes));
17796
18217
  } catch {
17797
18218
  throw new CliError(options2.mutation ? "transport-uncertain" : "response-invalid", `The backend returned a non-JSON response (HTTP ${response.status})`);
17798
18219
  }
@@ -17800,7 +18221,7 @@ class GatewayTransport {
17800
18221
  throw new CliError("response-invalid", "The backend response is not a JSON object");
17801
18222
  }
17802
18223
  const record = payload;
17803
- if (response.ok)
18224
+ if (response.status >= 200 && response.status < 300)
17804
18225
  return record.result;
17805
18226
  const message = typeof record.error === "string" ? record.error : "";
17806
18227
  if (message.startsWith("Unknown backend command: ")) {
@@ -18032,7 +18453,7 @@ function quoteArgument(value) {
18032
18453
  }
18033
18454
 
18034
18455
  // src/client/targets.ts
18035
- import { promises as fs4 } from "fs";
18456
+ import { constants as fsConstants, promises as fs4 } from "fs";
18036
18457
  import path11 from "path";
18037
18458
  import { isIPv4 } from "net";
18038
18459
 
@@ -18169,35 +18590,75 @@ async function readTokenFile(file, requirePrivate) {
18169
18590
  }
18170
18591
  return token.trim();
18171
18592
  }
18172
- async function readDescriptor(file) {
18593
+ function descriptorTrustRefusal(stat, currentUid) {
18594
+ if (currentUid === undefined)
18595
+ return null;
18596
+ if (stat.uid !== currentUid) {
18597
+ return `it is owned by another user (uid ${stat.uid}, you are uid ${currentUid})`;
18598
+ }
18599
+ if ((stat.mode & 63) !== 0) {
18600
+ return `it is accessible to other users (mode ${(stat.mode & 511).toString(8).padStart(4, "0")}); if your own backend published it, restrict it with chmod 600`;
18601
+ }
18602
+ return null;
18603
+ }
18604
+ var DESCRIPTOR_OPEN_FLAGS = fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0);
18605
+ var UNTRUSTED_DESCRIPTOR = "untrusted";
18606
+ function refuseDescriptor(file, reason) {
18607
+ return new CliError("connection-failed", `Refusing to use the backend instance descriptor ${file}: ${reason}`, { details: { descriptor: UNTRUSTED_DESCRIPTOR } });
18608
+ }
18609
+ function isDescriptorRefusal(error) {
18610
+ return error instanceof CliError && error.details?.descriptor === UNTRUSTED_DESCRIPTOR;
18611
+ }
18612
+ async function readDescriptor(file, currentUid = process.getuid?.()) {
18613
+ let handle;
18614
+ try {
18615
+ handle = await fs4.open(file, DESCRIPTOR_OPEN_FLAGS);
18616
+ } catch (error) {
18617
+ const code = error.code;
18618
+ if (code === "ELOOP" || code === "EMLINK") {
18619
+ throw refuseDescriptor(file, "it is a symbolic link, not a regular file");
18620
+ }
18621
+ if (code !== "ENOENT") {
18622
+ throw refuseDescriptor(file, `it could not be opened (${code ?? "unknown error"})`);
18623
+ }
18624
+ throw new CliError("connection-failed", `No running backend published ${path11.basename(file)} at the selected location`, { details: { descriptor: "missing" } });
18625
+ }
18173
18626
  let text;
18174
18627
  try {
18175
- const stat = await fs4.lstat(file);
18628
+ const stat = await handle.stat();
18176
18629
  if (!stat.isFile())
18177
- throw new Error("not a file");
18178
- if (stat.size > BACKEND_INSTANCE_DESCRIPTOR_MAX_BYTES)
18179
- throw new Error("too large");
18180
- text = await fs4.readFile(file, "utf8");
18181
- } catch {
18182
- throw new CliError("connection-failed", `No running backend published ${path11.basename(file)} at the selected location`);
18630
+ throw refuseDescriptor(file, "it is not a regular file");
18631
+ const refusal = descriptorTrustRefusal(stat, currentUid);
18632
+ if (refusal)
18633
+ throw refuseDescriptor(file, refusal);
18634
+ if (stat.size > BACKEND_INSTANCE_DESCRIPTOR_MAX_BYTES) {
18635
+ throw refuseDescriptor(file, "it is too large");
18636
+ }
18637
+ text = await handle.readFile("utf8");
18638
+ } catch (error) {
18639
+ if (error instanceof CliError)
18640
+ throw error;
18641
+ throw refuseDescriptor(file, "its metadata or contents could not be read");
18642
+ } finally {
18643
+ await handle.close();
18183
18644
  }
18184
18645
  try {
18185
18646
  return parseBackendInstanceDescriptor(JSON.parse(text));
18186
- } catch (error) {
18187
- throw new CliError("connection-failed", `The backend instance descriptor is invalid: ${error instanceof Error ? error.message : "parse failed"}`);
18647
+ } catch {
18648
+ throw refuseDescriptor(file, "its contents are invalid");
18188
18649
  }
18189
18650
  }
18190
18651
  function processIsAlive(pid) {
18191
18652
  try {
18192
18653
  process.kill(pid, 0);
18193
18654
  return true;
18194
- } catch (error) {
18195
- return error.code === "EPERM";
18655
+ } catch {
18656
+ return false;
18196
18657
  }
18197
18658
  }
18198
18659
  function descriptorTarget(name, kind, descriptor, expectedInstallationId, refresh) {
18199
18660
  if (!processIsAlive(descriptor.pid)) {
18200
- throw new CliError("connection-failed", `The backend for ${kind} '${name}' is not running (its descriptor is stale)`);
18661
+ throw new CliError("connection-failed", `The backend for ${kind} '${name}' is not running as your user (its descriptor is stale)`);
18201
18662
  }
18202
18663
  if (expectedInstallationId && descriptor.installationId !== expectedInstallationId) {
18203
18664
  throw new CliError("identity-mismatch", `The backend at ${kind} '${name}' is a different installation than the one saved`, { details: { expected: expectedInstallationId, actual: descriptor.installationId } });
@@ -18277,7 +18738,11 @@ async function resolveProfile(profileName, env) {
18277
18738
  const refresh = () => resolveProfile(profileName, env);
18278
18739
  if (manifest.dataDir) {
18279
18740
  const descriptorFile = path11.join(manifest.dataDir, BACKEND_INSTANCE_DESCRIPTOR_FILE);
18280
- const descriptor = await readDescriptor(descriptorFile).catch(() => null);
18741
+ const descriptor = await readDescriptor(descriptorFile).catch((error) => {
18742
+ if (error instanceof CliError && error.details?.descriptor === "missing")
18743
+ return null;
18744
+ throw error;
18745
+ });
18281
18746
  if (descriptor) {
18282
18747
  if (descriptor.pid !== backendPid) {
18283
18748
  throw new CliError("profile-unavailable", `Profile '${located.id}' has a descriptor from a different backend process`);
@@ -20265,7 +20730,9 @@ import path13 from "path";
20265
20730
  async function currentDescriptorGeneration(dataDir) {
20266
20731
  try {
20267
20732
  return (await readDescriptor(path13.join(dataDir, BACKEND_INSTANCE_DESCRIPTOR_FILE))).generation;
20268
- } catch {
20733
+ } catch (error) {
20734
+ if (isDescriptorRefusal(error))
20735
+ throw error;
20269
20736
  return null;
20270
20737
  }
20271
20738
  }
@@ -20305,7 +20772,10 @@ async function awaitServiceConnection(dataDir, previousGeneration, options2) {
20305
20772
  const fresh = value.generation !== previousGeneration && path13.resolve(value.dataDir) === path13.resolve(dataDir) && (options2.expectedVersion === undefined || value.appVersion === options2.expectedVersion) && processIsAlive(value.pid);
20306
20773
  if (fresh)
20307
20774
  return { done: true, value };
20308
- } catch {}
20775
+ } catch (error) {
20776
+ if (isDescriptorRefusal(error))
20777
+ throw error;
20778
+ }
20309
20779
  await options2.assertStarting?.();
20310
20780
  return { done: false };
20311
20781
  }, options2);
@@ -22202,9 +22672,9 @@ var ticketCommands = [
22202
22672
  ];
22203
22673
 
22204
22674
  // src/client/commands/toolchain.ts
22205
- import path20 from "path";
22675
+ import path22 from "path";
22206
22676
  function dataDirectory2(context, parsed) {
22207
- return path20.resolve(stringOption(parsed.options, "data-dir") ?? context.io.env.ORKESTRATOR_DATA_DIR ?? defaultDataDir(process.platform, context.io.env));
22677
+ return path22.resolve(stringOption(parsed.options, "data-dir") ?? context.io.env.ORKESTRATOR_DATA_DIR ?? defaultDataDir(process.platform, context.io.env));
22208
22678
  }
22209
22679
  function requestedTools(parsed) {
22210
22680
  const raw = parsed.options.tool;
@@ -22307,7 +22777,7 @@ var toolchainCommands = [
22307
22777
  const rows = installed.tools.map((tool) => ({
22308
22778
  tool,
22309
22779
  version: installed.versions[tool] ?? "",
22310
- executable: path20.join(installed.currentBinDir, path20.basename(installed.executables[tool]))
22780
+ executable: path22.join(installed.currentBinDir, path22.basename(installed.executables[tool]))
22311
22781
  }));
22312
22782
  return {
22313
22783
  action: "toolchain.install",