orkestrator 2.35.4-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,171 +5903,83 @@ 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
- }))).then(() => next(), (error) => extract2.destroy(error instanceof Error ? error : new Error(String(error))));
5470
- });
5471
- await pipeline(createReadStream(archivePath), createGunzip(), extract2);
5472
- if (!foundExecutable)
5473
- throw new Error(`${label} executable was not found in its bundle`);
5474
- }
5475
- function openZip(archivePath) {
5476
- return new Promise((resolve, reject) => {
5477
- $open(archivePath, { autoClose: true, lazyEntries: true, validateEntrySizes: true }, (error, zipFile) => {
5478
- if (error)
5479
- reject(error);
5480
- else if (!zipFile)
5481
- reject(new Error("ZIP archive did not open"));
5482
- else
5483
- resolve(zipFile);
5484
- });
5485
- });
5486
- }
5487
- async function extractZipEntry(archivePath, destinationPath, label, archive, executableSize) {
5488
- const zipFile = await openZip(archivePath);
5489
- await new Promise((resolve, reject) => {
5490
- let found = false;
5491
- let settled = false;
5492
- const fail = (error) => {
5493
- if (settled)
5494
- return;
5495
- settled = true;
5496
- zipFile.close();
5497
- reject(error instanceof Error ? error : new Error(String(error)));
5498
- };
5499
- zipFile.on("error", fail);
5500
- zipFile.on("entry", (entry) => {
5501
- const invalidName = $validateFileName(entry.fileName);
5502
- if (invalidName) {
5503
- fail(new Error(`Unsafe ZIP entry in ${label} archive: ${invalidName}`));
5504
- return;
5505
- }
5506
- if (entry.fileName !== archive.entryPath) {
5507
- zipFile.readEntry();
5508
- return;
5509
- }
5510
- if (found) {
5511
- fail(new Error(`${label} archive contains a duplicate executable entry`));
5512
- return;
5513
- }
5514
- found = true;
5515
- if (entry.fileName.endsWith("/") || entry.uncompressedSize !== executableSize) {
5516
- fail(new Error(`${label} executable entry did not match the pinned manifest`));
5517
- return;
5518
- }
5519
- zipFile.openReadStream(entry, (error, stream) => {
5520
- if (error || !stream) {
5521
- fail(error ?? new Error(`${label} executable stream was unavailable`));
5522
- return;
5523
- }
5524
- pipeline(stream, createWriteStream(destinationPath, { flags: "wx", mode: 320 })).then(() => zipFile.readEntry(), fail);
5525
- });
5526
- });
5527
- zipFile.on("end", () => {
5528
- if (settled)
5529
- return;
5530
- settled = true;
5531
- if (found)
5532
- resolve();
5533
- else
5534
- reject(new Error(`${label} executable was not found in its archive`));
5535
- });
5536
- zipFile.readEntry();
5537
- });
5538
- }
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}` : ""}`));
5909
+ }))).then(() => next(), (error) => extract2.destroy(error instanceof Error ? error : new Error(String(error))));
5910
+ });
5911
+ await pipeline(createReadStream3(archivePath), createGunzip(), extract2);
5912
+ if (!foundExecutable)
5913
+ throw new Error(`${label} executable was not found in its bundle`);
5914
+ }
5915
+ function openZip(archivePath) {
5916
+ return new Promise((resolve, reject) => {
5917
+ $open(archivePath, { autoClose: true, lazyEntries: true, validateEntrySizes: true }, (error, zipFile) => {
5918
+ if (error)
5919
+ reject(error);
5920
+ else if (!zipFile)
5921
+ reject(new Error("ZIP archive did not open"));
5922
+ else
5923
+ resolve(zipFile);
5592
5924
  });
5593
5925
  });
5594
5926
  }
5595
- async function runCodesign(args, failureMessage, timeoutMs, spawnProcess) {
5927
+ async function extractZipEntry(archivePath, destinationPath, label, archive, executableSize) {
5928
+ const zipFile = await openZip(archivePath);
5596
5929
  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();
5930
+ let found = false;
5931
+ let settled = false;
5932
+ const fail = (error) => {
5933
+ if (settled)
5934
+ return;
5935
+ settled = true;
5936
+ zipFile.close();
5937
+ reject(error instanceof Error ? error : new Error(String(error)));
5938
+ };
5939
+ zipFile.on("error", fail);
5940
+ zipFile.on("entry", (entry) => {
5941
+ const invalidName = $validateFileName(entry.fileName);
5942
+ if (invalidName) {
5943
+ fail(new Error(`Unsafe ZIP entry in ${label} archive: ${invalidName}`));
5612
5944
  return;
5613
5945
  }
5614
- const detail = Buffer.concat(errors).toString("utf8").trim();
5615
- reject(new Error(`${failureMessage} (code ${code ?? "unknown"}, signal ${signal ?? "none"})${detail ? `: ${detail}` : ""}`));
5946
+ if (entry.fileName !== archive.entryPath) {
5947
+ zipFile.readEntry();
5948
+ return;
5949
+ }
5950
+ if (found) {
5951
+ fail(new Error(`${label} archive contains a duplicate executable entry`));
5952
+ return;
5953
+ }
5954
+ found = true;
5955
+ if (entry.fileName.endsWith("/") || entry.uncompressedSize !== executableSize) {
5956
+ fail(new Error(`${label} executable entry did not match the pinned manifest`));
5957
+ return;
5958
+ }
5959
+ zipFile.openReadStream(entry, (error, stream) => {
5960
+ if (error || !stream) {
5961
+ fail(error ?? new Error(`${label} executable stream was unavailable`));
5962
+ return;
5963
+ }
5964
+ pipeline(stream, createWriteStream(destinationPath, { flags: "wx", mode: 320 })).then(() => zipFile.readEntry(), fail);
5965
+ });
5616
5966
  });
5967
+ zipFile.on("end", () => {
5968
+ if (settled)
5969
+ return;
5970
+ settled = true;
5971
+ if (found)
5972
+ resolve();
5973
+ else
5974
+ reject(new Error(`${label} executable was not found in its archive`));
5975
+ });
5976
+ zipFile.readEntry();
5617
5977
  });
5618
5978
  }
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;
@@ -7906,6 +8309,7 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
7906
8309
  "update_schedule",
7907
8310
  "update_ticket"
7908
8311
  ]);
8312
+ var COORDINATOR_PROJECT_HOME_MESSAGE_WINDOW_MS = 3 * 60 * 60000;
7909
8313
 
7910
8314
  // ../protocol/src/bug-report.ts
7911
8315
  var BUG_REPORT_ISSUE_REPOSITORY = "orkestrator-ai/orkestrator-v2";
@@ -8062,7 +8466,16 @@ var AGENT_MAIL_LOG_AREAS = defineLogAreas({
8062
8466
  "agent-mail": {
8063
8467
  description: "Delivering agent mail into waiting agent sessions.",
8064
8468
  events: {
8065
- "delivery.waiting": "The drain passed over a pending message, for a reason it had not yet logged."
8469
+ "delivery.waiting": "The drain passed over a pending message, for a reason it had not yet logged.",
8470
+ "drain.new-mail-failed": "Draining newly received mail failed; the next sweep delivers it.",
8471
+ "presence.sync-failed": "Mailboxes could not be synchronized.",
8472
+ "inject.verified": "An injected message's delivery was checked. Ids and decisions only.",
8473
+ "inject.dispatched": "Messages were dispatched into a session. Ids and decisions only.",
8474
+ "stopped-worker.action-failed": "Nothing could act on mail for a stopped worker.",
8475
+ "coordinator.start-failed": "The main coordinator could not be started for a new message.",
8476
+ "message.placed": "A message was placed in a mailbox. Ids and decisions only, never subjects or bodies.",
8477
+ "budget.hold-notify-failed": "The coordinator could not be told about held worker mail.",
8478
+ "budget.reset-failed": "The mail budget could not be reset for a prompted tab."
8066
8479
  }
8067
8480
  }
8068
8481
  });
@@ -8084,6 +8497,30 @@ var BACKEND_LOG_AREAS = defineLogAreas({
8084
8497
  "job.failed": "One pass of the job named in `scope` failed; its next pass retries.",
8085
8498
  ...THROTTLE_LOG_EVENTS
8086
8499
  }
8500
+ },
8501
+ backend: {
8502
+ description: "The backend process: startup, background notices and shutdown.",
8503
+ events: {
8504
+ starting: "The backend process is starting.",
8505
+ "ssh-socket.resolved": "An SSH agent socket was found.",
8506
+ "ssh-socket.missing": "No usable SSH agent socket was found.",
8507
+ "standalone-updater.mismatch": "--standalone-updater does not match --data-dir, so self-update is off.",
8508
+ "instance.publish-failed": "The instance descriptor could not be published.",
8509
+ "instance.republish-failed": "The instance descriptor could not be republished; a later pass retries.",
8510
+ "parent.exited": "The parent process exited, so local servers are shutting down.",
8511
+ "startup.step-failed": "One part of startup failed and the backend carried on; `step` says which.",
8512
+ "startup.setup-fence-failed": "An environment's interrupted setup could not be fenced.",
8513
+ "startup.setup-adopt-failed": "An environment's pending setup could not be adopted.",
8514
+ "startup.deletion-pending": "An interrupted environment deletion stays pending. Its owning step logged the detail.",
8515
+ "startup.looped-review-pending": "Cleanup of the retired Looped Review stays pending.",
8516
+ "notice.failed": "A background notice after a turn or prompt failed; `step` says which.",
8517
+ "artifacts.live-unavailable": "Live interactive artifacts are unavailable.",
8518
+ "shutdown.step-failed": "One part of shutdown failed and the rest went on; `step` says which.",
8519
+ "shutdown.signal-received": "A signal started shutdown, which tells a clean quit from the backend being killed.",
8520
+ "shutdown.finished": "Shutdown finished, and the process exits with `code`.",
8521
+ "port-policy.second-backend": "Another backend serves the default data directory, so this one avoids its ports.",
8522
+ "port-policy.serve-on-free-port": "--tailscale-serve is on a free gateway port; pass --port with --strict-gateway-port to keep one."
8523
+ }
8087
8524
  }
8088
8525
  });
8089
8526
 
@@ -8091,11 +8528,12 @@ var BACKEND_LOG_AREAS = defineLogAreas({
8091
8528
  var MAX_BRIDGE_DIAGNOSTIC_BYTES = 8192;
8092
8529
  var BRIDGE_LOG_AREAS = defineLogAreas({
8093
8530
  "bridge.diagnostics": {
8094
- description: "Metadata snapshots of bridge turns and processes, written while Save Logs for Debugging is on. docs/architecture/bridge-diagnostics.md reads them.",
8531
+ description: "Metadata snapshots of bridge turns and processes: lifecycle, stalls and a keepalive at info, every minute at debug, and each change at trace. docs/architecture/bridge-diagnostics.md reads them.",
8095
8532
  tag: "bridge-diagnostics",
8096
8533
  maxStringChars: MAX_BRIDGE_DIAGNOSTIC_BYTES,
8097
8534
  events: {
8098
- heartbeat: "The once-a-minute snapshot of a turn or process that is still open.",
8535
+ heartbeat: "A periodic snapshot of an open turn or process: every minute at debug; at info only as stall evidence (a stall starting or clearing, a late timer, a change during a silent stall) or the ten-minute keepalive.",
8536
+ change: "At trace only: a snapshot written as soon as the phase, the pending tools or a counter past its threshold changes.",
8099
8537
  "send-started": "A turn or process diagnostic scope began.",
8100
8538
  "send-resolved": "The provider accepted a dispatch.",
8101
8539
  "cancel-requested": "Cancellation of a turn was requested.",
@@ -8176,6 +8614,7 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
8176
8614
  "session.created": "A session was created or recovered.",
8177
8615
  "session.delete-failed": "Deleting a session failed.",
8178
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.",
8179
8618
  "session.rename-failed": "Renaming a session failed.",
8180
8619
  "session.resolve-failed": "A session could not be found or loaded for a request; action names the request.",
8181
8620
  "session.rewind-failed": "Rewinding session files failed.",
@@ -8308,6 +8747,7 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
8308
8747
  "backend.keychain-link-remove-failed": "An agent-test profile kept a legacy link to the host keychain.",
8309
8748
  "backend.start-failed": "The Local backend did not start; continuing with remote machines.",
8310
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.",
8311
8751
  "instance.already-running": "Another instance holds this data directory; this one will quit.",
8312
8752
  "main-thread.stalled": "A timer fired late, so windows, IPC and the stdout reader waited.",
8313
8753
  "quit.stopping-backend": "The app is quitting and has asked the Local backend to stop.",
@@ -8380,7 +8820,8 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
8380
8820
  description: "Preparing the pinned agent toolchain at desktop startup.",
8381
8821
  events: {
8382
8822
  "bootstrap-progress.show-failed": "The toolchain progress window could not be shown.",
8383
- "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."
8384
8825
  }
8385
8826
  },
8386
8827
  "artifact-host": {
@@ -8394,7 +8835,7 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
8394
8835
  // ../protocol/src/log-vocabulary/environment.ts
8395
8836
  var ENVIRONMENT_LOG_AREAS = defineLogAreas({
8396
8837
  environment: {
8397
- description: "Environment naming, held setup and cleanup after deletion.",
8838
+ description: "Environment naming, setup, status, moves, deletion and cleanup afterwards.",
8398
8839
  events: {
8399
8840
  "cleanup.branch-kept": "A deleted environment's local branch was kept, as it may hold unmerged work.",
8400
8841
  "rename.failed": "Naming an environment from its pending prompt failed for the first time.",
@@ -8403,6 +8844,40 @@ var ENVIRONMENT_LOG_AREAS = defineLogAreas({
8403
8844
  "setup.attention-not-recorded": "Held setup could not be recorded as needing the user's attention.",
8404
8845
  "setup.coordinator-not-notified": "The worker's coordinator could not be told that its setup is held for approval.",
8405
8846
  "setup.unknown-environment": "The renderer was asked to act on the setup of an environment it does not hold.",
8847
+ "cleanup.rearmed": "A deleted environment's stopped cleanup is retried once under a new backend version.",
8848
+ "cleanup.exhausted": "A deleted environment's cleanup keeps failing after its attempts; written once per environment.",
8849
+ "cleanup.retry-not-admitted": "A cleanup retry was not admitted; the entry stays for the next start.",
8850
+ "cleanup.step-failed": "One step of a deleted environment's cleanup failed; a later reconcile retries it.",
8851
+ "cleanup.record-failed": "A finished cleanup step could not be recorded, so it may run again.",
8852
+ "cleanup.sweep-failed": "A cleanup sweep failed; written once per sweep.",
8853
+ "cleanup.reconcile-failed": "A cleanup reconcile pass failed; the next one retries.",
8854
+ "orphan-state.remove-failed": "An orphaned environment state directory could not be removed.",
8855
+ "orphan-state.removed": "Orphaned environment state directories were removed.",
8856
+ "orphan-state.sweep-failed": "Sweeping orphaned environment state failed.",
8857
+ "orphan-canvas.removed": "Orphaned design canvases were removed.",
8858
+ "orphan-canvas.sweep-failed": "Sweeping orphaned design canvases failed.",
8859
+ "orphan-branches.swept": "Orphaned environment branches were deleted, or kept as they may hold unmerged work.",
8860
+ "stray-workspace.remove-failed": "A stray workspace directory could not be removed.",
8861
+ "stray-workspace.removed": "Stray workspace directories were removed.",
8862
+ "stray-workspace.kept": "Unowned workspace directories that hold files were kept; remove them by hand if unneeded.",
8863
+ "temp-files.removed": "Abandoned temp files were removed.",
8864
+ "status.ownership-probe-failed": "A strict container ownership probe failed, so the stored status is kept.",
8865
+ "status.docker-error": "A transient Docker error stopped a status read, so the stored status is kept.",
8866
+ "setup.clear-launch-failed": "A pending agent launch could not be cleared after setup failed.",
8867
+ "setup.record-failure-failed": "A setup failure before its first attempt could not be recorded.",
8868
+ "lifecycle.failed": "Starting, rebuilding or recreating an environment failed; `operation` says which.",
8869
+ "tab-teardown.pending": "A tab's teardown failed and stays pending; the reconcile sweep retries.",
8870
+ "tab-reconcile.skipped": "Orphaned tab reconciliation was skipped because pane layouts are unreadable.",
8871
+ "orphan-session.reaped": "A native session no tab references was torn down.",
8872
+ "handoff-sweep.failed": "Sweeping transferred transcripts no tab references failed.",
8873
+ "delete.terminals-survived": "Terminal process trees outlived termination, so the deletion stops.",
8874
+ "delete.artifacts-left": "Graph run artifact directories were not removed.",
8875
+ "delete.worktrees-kept": "Graph runs kept branch worktrees.",
8876
+ "delete.step-failed": "One best-effort part of deleting an environment failed; `step` says which, and the rest goes on.",
8877
+ "merge-cleanup.resume-failed": "A merge cleanup interrupted by a restart could not be resumed.",
8878
+ "move.sessions-not-moved": "A provider's sessions could not follow a moved environment.",
8879
+ "move.recovery-failed": "Recovering an interrupted environment move failed.",
8880
+ "stop.settle-activity-failed": "Agent activity could not be settled after a runtime stopped.",
8406
8881
  ...THROTTLE_LOG_EVENTS
8407
8882
  }
8408
8883
  }
@@ -8411,10 +8886,50 @@ var ENVIRONMENT_LOG_AREAS = defineLogAreas({
8411
8886
  // ../protocol/src/log-vocabulary/gateway.ts
8412
8887
  var GATEWAY_LOG_AREAS = defineLogAreas({
8413
8888
  gateway: {
8414
- description: "The remote gateway other devices and browsers connect through.",
8889
+ description: "The gateway other devices, browsers and the desktop connect through.",
8415
8890
  events: {
8416
8891
  "remote.start-failed": "The desktop could not start the remote gateway.",
8417
- "remote.stop-failed": "The desktop could not stop the remote gateway cleanly."
8892
+ "remote.stop-failed": "The desktop could not stop the remote gateway cleanly.",
8893
+ disabled: "The gateway is disabled by its environment variable.",
8894
+ "tailscale.no-address": "No Tailscale address was found, so the gateway did not start.",
8895
+ "tailscale.no-address-fallback": "No Tailscale address was found, so the gateway binds its fallback address.",
8896
+ "control.listening": "The backend control listener is up.",
8897
+ "browser.listening": "The browser listener is up.",
8898
+ "browser.unavailable": "The browser listener could not start; control remains if started, or loopback is attempted.",
8899
+ "browser.unavailable-degraded": "No browser listener was started (`reason=no-tailscale-address`); control remains if started, or loopback is attempted.",
8900
+ "loopback.listening": "The loopback client listener is up.",
8901
+ "loopback.unavailable": "The loopback client listener could not start.",
8902
+ "auth-token.stored": "The gateway token's file was written. The path only, never the token.",
8903
+ "auth-token.persist-failed": "The gateway token could not be saved.",
8904
+ "port.fallback": "The preferred port was taken, so a nearby one is used.",
8905
+ "port.fallback-distant": "The preferred port and those nearby were taken, so another is used.",
8906
+ "request.failed": "A gateway request failed. Throttled: repeats are counted, not written.",
8907
+ "websocket.upgrade-failed": "A WebSocket upgrade failed.",
8908
+ "events.client-dropped": "An event-stream client buffered too much and was dropped; it reconnects and refetches.",
8909
+ "proxy.client-disconnected": "A proxy client went away, so its upstream request was aborted.",
8910
+ "throttle.suppressed": "Repeats of the throttled `site` were counted over a window, not written.",
8911
+ "throttle.recovered": "The throttled `site` succeeded again, so its fault has cleared.",
8912
+ "throttle.evicted": "The tracked-key limit dropped the `site`, so no recovered line follows unless it fails again."
8913
+ }
8914
+ },
8915
+ "gateway.terminal": {
8916
+ description: "The gateway's terminal WebSocket.",
8917
+ events: {
8918
+ "upgrade-rejected": "A terminal WebSocket upgrade was refused.",
8919
+ "socket-error": "A terminal WebSocket reported an error.",
8920
+ "subscription-failed": "A terminal subscription failed.",
8921
+ "operation-failed": "A terminal operation failed. Fixed text: the operation can hold terminal input."
8922
+ }
8923
+ },
8924
+ "gateway.tailscale": {
8925
+ description: "Tailscale Serve for desktop web access and a standalone backend.",
8926
+ events: {
8927
+ "web-access.disable-failed": "Desktop web access could not be turned off.",
8928
+ "web-access.enable-failed": "Desktop web access could not be turned on.",
8929
+ "web-access.cleanup-failed": "Cleaning up after a failed enable also failed.",
8930
+ "web-access.reset-failed": "Desktop web access could not be reset.",
8931
+ "startup.init-failed": "Desktop web access could not be initialized at startup.",
8932
+ available: "Tailscale Serve is publishing the gateway."
8418
8933
  }
8419
8934
  }
8420
8935
  });
@@ -8425,6 +8940,18 @@ var LOCAL_SERVER_LOG_AREAS = defineLogAreas({
8425
8940
  description: "Agent bridge processes the backend runs on the host.",
8426
8941
  events: {
8427
8942
  "bridge.not-answering": "A bridge with work in progress fails health checks, so it is not restarted yet.",
8943
+ "bridge-runtime.installing": "A bridge runtime is being installed.",
8944
+ "bridge-runtime.installed": "A bridge runtime finished installing.",
8945
+ "opencode.database-lost-retrying": "OpenCode lost its shared database at startup, so it is retried.",
8946
+ "server.stopping": "A local server is being stopped, for the fixed `reason` given.",
8947
+ "reaper.tmux-list-failed": "Orphaned claude-tmux sessions could not be listed.",
8948
+ "reaper.tmux-kill-failed": "An orphaned tmux session could not be killed.",
8949
+ "reaper.tmux-reaped": "Orphaned claude-tmux sessions of a deleted environment were killed.",
8950
+ "reaper.runtime-root-remove-failed": "A claude-tmux runtime root could not be removed; it stays for a retry.",
8951
+ "reaper.server-unidentified": "An orphan candidate could not be identified, so its record is kept.",
8952
+ "reaper.server-refused": "An orphan candidate leads no process group, so it was not reaped.",
8953
+ "reaper.server-reaping": "An orphaned server is being stopped.",
8954
+ "reaper.server-kill-failed": "An orphaned server did not exit.",
8428
8955
  ...THROTTLE_LOG_EVENTS
8429
8956
  }
8430
8957
  }
@@ -8466,7 +8993,12 @@ var MODEL_LOG_AREAS = defineLogAreas({
8466
8993
  models: {
8467
8994
  description: "Agent model catalogues and their persistent caches.",
8468
8995
  events: {
8469
- "cache.write-failed": "A successful catalogue refresh could not update the host cache."
8996
+ "cache.write-failed": "A successful catalogue refresh could not update the host cache.",
8997
+ "seed.pi-failed": "The host Pi model catalogue could not be seeded; the next launch retries.",
8998
+ "bridge.not-ready": "The first-use catalogue bridge did not become ready.",
8999
+ "bridge.start-failed": "The first-use catalogue bridge failed to start.",
9000
+ "probe.exit-unclean": "A catalogue probe or sign-in server did not exit cleanly.",
9001
+ "download.deferred": "A model catalogue could not be downloaded yet."
8470
9002
  }
8471
9003
  }
8472
9004
  });
@@ -8477,8 +9009,62 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
8477
9009
  description: "Native agent sessions and what the backend reads from their bridges.",
8478
9010
  events: {
8479
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.",
9013
+ "handoff.summary-read-failed": "Change summaries could not be read for a handoff, so the carrier says they are unmeasured.",
9014
+ "handoff.consume-failed": "A delivered handoff could not be marked consumed.",
9015
+ "job.pr-refresh-rollback-failed": "Rolling back a pull request refresh for a job failed.",
9016
+ "job.resend-queue-failed": "A resend could not be queued for a job.",
9017
+ "interaction.requests-dropped": "Interaction requests that could not be mapped were dropped.",
9018
+ "interaction.observe-failed": "Observing a session's interactions failed. Error class only.",
9019
+ "human-prompt.listener-failed": "A human prompt listener threw; the others still run.",
9020
+ "question.attention-record-failed": "Attention for an async question could not be recorded; the transcript stays readable.",
9021
+ "activity.reconcile-failed": "Reconciling an environment's activity failed. Error class only.",
9022
+ "activity.persist-failed": "An environment's activity could not be saved.",
9023
+ "pr-refresh.schedule-failed": "A pull request refresh after completion could not be scheduled.",
9024
+ "launch.startup-failed": "A startup launch failed; it retries unless `permanent`.",
9025
+ "queue.failing": "A native prompt queue keeps failing. The key and reason only, never the prompt.",
9026
+ "provider.retire-failed": "Retiring an obsolete provider failed.",
9027
+ "workflow-result.store-unavailable": "The workflow result store is unavailable, so the provider's result is used.",
9028
+ "catalogue.refresh-failed": "A provider's command catalogue could not be refreshed.",
9029
+ "dispatch.attach-failed": "Attaching an agent before dispatch failed; the prompt request answers authoritatively.",
9030
+ "coordinator-context.ack-failed": "Coordinator repository context could not be acknowledged.",
9031
+ "naming.prepare-failed": "First-prompt naming could not be prepared; the prompt still goes ahead.",
9032
+ "interrupt.persist-failed": "A turn interrupt could not be saved, so automatic publication stays fenced.",
9033
+ "resume.close-replaced-failed": "The session a resume replaced could not be closed.",
9034
+ "sign-in.check-failed": "A turn could not be checked for a login refusal.",
9035
+ "sign-in.resend-failed": "Sending refused prompts after sign-in failed.",
9036
+ "sign-in.prompt-resend-failed": "One refused prompt could not be sent again after sign-in. Error class only.",
9037
+ "shutdown.checkpoints-skipped": "Shutdown skipped display-tail checkpoints; provider history stays authoritative. Count only.",
9038
+ "turn-recovery.failed": "Recovering an incomplete turn failed.",
9039
+ "turn-recovery.exhausted": "A turn failed again after automatic recovery and is left for the user.",
9040
+ "turn-recovery.retrying": "An incomplete or provider-failed turn is being retried automatically.",
9041
+ "usage-limit.resend-failed": "Resending after a usage limit failed. An unknown send stays in the journal.",
9042
+ "title.strategy-failed": "A session title strategy failed, so the next is tried. Content-free: the error can quote the prompt.",
8480
9043
  ...THROTTLE_LOG_EVENTS
8481
9044
  }
9045
+ },
9046
+ "native-agent.goal": {
9047
+ description: "The /goal loop: advancing goals and their verifiers.",
9048
+ events: {
9049
+ "advance.failed": "A goal could not advance; the next sweep retries.",
9050
+ "attention.record-failed": "Attention for a goal could not be recorded.",
9051
+ "turn-end.settle-failed": "Turn-end work for a goal could not be settled.",
9052
+ "verifier.finish-failed": "A verifier failed to finish; the goal stays verifying, so the next sweep runs it again.",
9053
+ "verifier.stop-failed": "An earlier verifier could not be stopped.",
9054
+ "recover.failed": "Goals could not be recovered at startup."
9055
+ }
9056
+ },
9057
+ "native-agent.opencode": {
9058
+ description: "The OpenCode provider: its request monitor, retries and agent tools.",
9059
+ events: {
9060
+ "retry.abort-failed": "Aborting an automatic retry failed. Error class only.",
9061
+ "retry.abort-not-scheduled": "An automatic retry abort could not be scheduled. Error class only.",
9062
+ "agent-tools.unavailable": "OpenCode agent tools remain unavailable for a session.",
9063
+ "coordinator-servers.unavailable": "OpenCode coordinator research servers are unavailable.",
9064
+ "monitor.reconnecting": "The request monitor lost its stream and is reconnecting. Error class only.",
9065
+ "worker-limit.reached": "The bounded request workers are full, so the stream restarts and a snapshot reconciles.",
9066
+ "request.failed": "Handling a request event failed, so the stream restarts. Error class only."
9067
+ }
8482
9068
  }
8483
9069
  });
8484
9070
 
@@ -8501,6 +9087,17 @@ var PREVIEW_LOG_AREAS = defineLogAreas({
8501
9087
  "partitions.retry-forgotten-failed": "Retrying a forgotten preview cleanup failed.",
8502
9088
  "port-hints.persist-failed": "Preview port hints could not be saved.",
8503
9089
  "transport.close-failed": "A preview transport could not be closed.",
9090
+ "ca-bundle.read-failed": "The upstream CA bundle could not be read.",
9091
+ "publication.start-failed": "Private preview publication did not start.",
9092
+ "publication.reconfigure-failed": "Preview publication could not be reconfigured.",
9093
+ "publication.listening": "Private preview origins are listening.",
9094
+ "certificate.reloaded": "The preview certificate was reloaded.",
9095
+ "access.revoked-close-failed": "A revoked preview resource could not be closed. Error class only.",
9096
+ "registry.invalid-definition": "An invalid stored preview service definition was ignored.",
9097
+ "registry.environment-reconcile-failed": "An environment's preview services could not be reconciled.",
9098
+ "registry.resolver-failed": "A preview resolver failed. Error class only.",
9099
+ "registry.revocation-listener-failed": "A preview revocation listener threw. Error class only.",
9100
+ "registry.change-emit-failed": "A preview change event could not be emitted. Error class only.",
8504
9101
  ...THROTTLE_LOG_EVENTS
8505
9102
  }
8506
9103
  }
@@ -8519,9 +9116,33 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
8519
9116
  // ../protocol/src/log-vocabulary/terminal.ts
8520
9117
  var TERMINAL_LOG_AREAS = defineLogAreas({
8521
9118
  terminal: {
8522
- description: "The renderer's terminal. Its lines stay in the browser console, never the saved log.",
9119
+ description: "Terminals. The renderer's lines stay in the browser console; the backend's reach the saved log.",
8523
9120
  events: {
8524
9121
  "input.undelivered": "A keystroke did not reach a shell: `no-session` or `not-delivered`.",
9122
+ "orphan.reaped": "A terminal no tab references was closed.",
9123
+ "agent-completion.notify-failed": "A terminal agent's completion could not be reported.",
9124
+ "activity.record-failed": "Terminal environment activity could not be recorded.",
9125
+ "pty.exit-listener-failed": "A terminal exit listener threw; the others still run.",
9126
+ "pty.exit-notify-failed": "Notifying a terminal's exit failed.",
9127
+ "pty.late-exit-listener-failed": "A listener added after a terminal exited threw.",
9128
+ "setup.pty-reused": "A setup terminal reused its existing PTY.",
9129
+ "setup.pty-spawning": "A setup terminal is spawning its PTY. The argument count only, never the arguments.",
9130
+ "setup.pty-spawned": "A setup terminal's PTY started.",
9131
+ "setup.pty-exited": "A setup terminal's PTY exited.",
9132
+ "setup.preparing": "Workspace preparation started in the setup terminal.",
9133
+ "setup.session-creating": "A setup session is being created.",
9134
+ "setup.intro-emitted": "The setup intro was written to the terminal.",
9135
+ "setup.completed": "Setup finished.",
9136
+ "setup.failed": "Setup failed.",
9137
+ "setup.already-complete": "Setup was requested but had already finished.",
9138
+ "setup.renderer-ensured": "The renderer asked for setup to be running.",
9139
+ "setup.renderer-requested": "The renderer asked for the setup session.",
9140
+ "setup.renderer-requested-none": "The renderer asked for a setup session that does not exist.",
9141
+ "setup.no-commands": "An environment has no setup commands to run.",
9142
+ "setup.already-running": "Setup was requested while it was already running.",
9143
+ "setup.held-for-approval": "Setup is held until its commands are approved.",
9144
+ "setup.renderer-checked-session": "The renderer asked whether a setup terminal session exists.",
9145
+ "setup.renderer-requested-buffer": "The renderer asked for a setup terminal's output buffer. A size only, never its contents.",
8525
9146
  "input.resume-failed": "Asking the backend to resume refused terminal input failed.",
8526
9147
  "input.write-failed": "Writing input to a terminal session threw.",
8527
9148
  "listener.remove-failed": "Removing a terminal output listener threw.",
@@ -8621,13 +9242,41 @@ var TERMINAL_LOG_AREAS = defineLogAreas({
8621
9242
  // ../protocol/src/log-vocabulary/tmux.ts
8622
9243
  var TMUX_LOG_AREAS = defineLogAreas({
8623
9244
  tmux: {
8624
- description: "The poll loop behind a Claude tmux tab.",
9245
+ description: "Claude tmux tabs: launch, the poll loop, cleanup and the tmux prompt queue.",
8625
9246
  events: {
8626
9247
  "poll.discovery-failed": "Finding the session's transcript failed; a later tick retries.",
8627
9248
  "poll.snapshot-failed": "Reading the hook and transcript state failed; the next tick retries.",
8628
9249
  "poll.drain-pending-failed": "Delivering pending hook events failed; the next tick retries.",
8629
9250
  "poll.drain-timeouts-failed": "Delivering hook timeouts failed; the next tick retries.",
8630
9251
  "poll.tail-failed": "Reading new transcript lines failed; the next tick retries.",
9252
+ "cleanup.session-stop-failed": "A tmux session could not be stopped while cleaning up an environment.",
9253
+ "cleanup.skipped": "Environment tmux cleanup was skipped because tmux could not be reached and nothing required it.",
9254
+ "cleanup.environments-load-failed": "Environments could not be loaded during tmux cleanup, so it stays incomplete.",
9255
+ "cleanup.kill-failed": "An environment's tmux sessions could not be killed.",
9256
+ "hooks.uninstall-failed": "Workspace hooks could not be uninstalled.",
9257
+ "hooks.git-exclude-failed": "The git exclude for Claude's local settings could not be set.",
9258
+ "naming.prepare-failed": "First-prompt naming could not be prepared; the prompt still goes ahead.",
9259
+ "orphans.skipped": "Orphan reconciliation was skipped because pane layouts are unreadable.",
9260
+ "orphan.reaped": "A tmux session no tab references was killed.",
9261
+ "orphan.kill-skipped": "An orphan tmux kill was skipped because the tmux server could not be reached.",
9262
+ "cli.thinking-display-probe-failed": "Probing the CLI for --thinking-display failed, so it launches without it.",
9263
+ "cli.fast-mode-unsupported": "The claude CLI lacks --settings, so it launches without fast mode.",
9264
+ "cli.effort-unsupported": "The claude CLI lacks --effort, so it launches without it.",
9265
+ "interactive.snapshot-failed": "An interactive snapshot failed; expected while a pane is closing.",
9266
+ "signal.arm-failed": "The Claude state signal could not be armed.",
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.",
9270
+ "pr-refresh.schedule-failed": "A pull request refresh after a turn could not be scheduled.",
9271
+ "pr-probe.failed": "Probing for a pull request an agent created failed.",
9272
+ "activity.persist-failed": "Tmux tab activity could not be saved.",
9273
+ "fast-mode.persist-failed": "The launch fast mode could not be saved.",
9274
+ "fast-mode.repair-failed": "Fast mode metadata could not be repaired on a reattached session.",
9275
+ "pane.observe-failed": "A pane observation failed. Error class only: pane contents are sensitive.",
9276
+ "turn.failure-record-failed": "A failed turn could not be recorded.",
9277
+ "slash-command.settle-timeout": "Timed out waiting for a Claude slash command to settle.",
9278
+ "queue.failing": "A tmux prompt queue keeps failing to dispatch.",
9279
+ "queue.rename-failed": "An environment could not be named from its first prompt; the prompt still goes ahead.",
8631
9280
  ...THROTTLE_LOG_EVENTS
8632
9281
  }
8633
9282
  }
@@ -8654,7 +9303,8 @@ var UPDATER_LOG_AREAS = defineLogAreas({
8654
9303
  "remote.unavailable": "Updates requested by remote clients are unavailable in this session.",
8655
9304
  "restart-prompt.failed": "The restart prompt for a downloaded update failed.",
8656
9305
  unavailable: "Auto-update could not be set up in this session.",
8657
- "update.failed": "electron-updater reported an update error."
9306
+ "update.failed": "electron-updater reported an update error.",
9307
+ "standalone.restarting": "A standalone backend is restarting into a new version."
8658
9308
  }
8659
9309
  }
8660
9310
  });
@@ -8665,11 +9315,473 @@ var WEB_ANNOTATIONS_LOG_AREAS = defineLogAreas({
8665
9315
  description: "Web annotation requests and their background reconciler.",
8666
9316
  events: {
8667
9317
  "reconcile.failed": "A background reconcile pass failed; the next one retries.",
9318
+ "legacy.degraded": "Legacy annotation storage is damaged, so the previous committed copy is served read-only.",
9319
+ "legacy.draft-index-problem": "The legacy draft index could not be used; `status` says why.",
9320
+ "legacy.unreadable-records": "The legacy import found unreadable records; they stay unread.",
9321
+ "legacy.unavailable": "Legacy annotation storage could not be read.",
9322
+ "legacy.unreadable": "An environment's legacy annotation storage is unreadable.",
9323
+ "legacy.archive-failed": "Imported legacy annotation files could not be archived.",
9324
+ "legacy.files-archived": "Legacy files beside an imported environment were archived, not imported.",
9325
+ "migration.draft-failed": "Migrating one draft failed.",
9326
+ "draft-reconcile.deferred": "Draft reconciliation was deferred; a later pass retries.",
9327
+ "request.handoff-deferred": "A request's handoff was deferred; a later pass retries.",
9328
+ "evidence.materialize-failed": "Materializing a request's evidence failed; it backs off and retries.",
9329
+ "queue.publish-deferred": "Publishing a request to the queue was deferred; it retries under the same id.",
9330
+ "request.reconcile-failed": "Reconciling a request failed; the next pass retries.",
9331
+ "turn-end.reconcile-failed": "Reconciling a request at the end of a turn failed; the next pass retries.",
9332
+ "gc.failed": "Annotation garbage collection failed; the next pass retries.",
9333
+ "record.unavailable": "An annotation record is unavailable; written once per record.",
9334
+ "storage.unavailable": "An environment's annotation store is unreadable.",
9335
+ "change-hint.listener-failed": "A change hint listener threw.",
9336
+ "orphan.remove-failed": "An orphaned environment's annotation storage could not be removed.",
9337
+ "storage.load-failed": "An environment's annotation storage could not be loaded.",
8668
9338
  ...THROTTLE_LOG_EVENTS
8669
9339
  }
8670
9340
  }
8671
9341
  });
8672
9342
 
9343
+ // ../protocol/src/log-vocabulary/storage.ts
9344
+ var STORAGE_LOG_AREAS = defineLogAreas({
9345
+ storage: {
9346
+ description: "The SQLite-backed stores, their snapshots and imports from older formats.",
9347
+ events: {
9348
+ "usage.environment-label-failed": "Usage labels could not be retained for a removed environment; deletion continues.",
9349
+ "snapshot.integrity-failed": "An hourly database snapshot failed its integrity check and was discarded.",
9350
+ "snapshot.skipped-low-disk": "The hourly database snapshot was skipped because the disk lacks room; `retryAt` says when it tries again.",
9351
+ "snapshot.failed": "The hourly database snapshot failed; `retryAt` says when it tries again, if known.",
9352
+ "listener.attention-failed": "An environment attention listener threw; the committed mutation stands.",
9353
+ "listener.change-failed": "A resource change listener threw; the committed mutation stands.",
9354
+ "kanban.image-cleanup-failed": "An orphaned Kanban image could not be removed after its retries; it is safe to remove later.",
9355
+ "nodes.entries-dropped": "Unreadable node registry entries were ignored.",
9356
+ "preview-identity.reminted": "The data directory moved or was copied, so previews get a new backend identity.",
9357
+ "machine-profile.invalid": "The stored machine profile was invalid and the default was restored.",
9358
+ "permission-rules.cleanup-failed": "A deleted project's permission rules could not be removed.",
9359
+ "retired.turn-cleanup-pending": "Cleanup of a retired Looped Review turn did not finish and stays pending.",
9360
+ "handoffs.prune-failed": "Pruning agent handoffs that nothing references failed; a later prune retries.",
9361
+ "desktop-connections.malformed": "Stored desktop connection settings were malformed, so the local connection is used.",
9362
+ "legacy-json.moved": "JSON store files written after the SQLite migration were archived, not imported.",
9363
+ "legacy-json.archive-failed": "Imported JSON store files could not be archived."
9364
+ }
9365
+ }
9366
+ });
9367
+
9368
+ // ../protocol/src/log-vocabulary/build-pipeline.ts
9369
+ var BUILD_PIPELINE_LOG_AREAS = defineLogAreas({
9370
+ "build-pipeline": {
9371
+ description: "Build pipelines: their supervision, stages, transcripts and sidebar state.",
9372
+ events: {
9373
+ "sidebar.reconcile-failed": "Sidebar activity for pipelines could not be reconciled.",
9374
+ "sidebar.update-failed": "The sidebar could not be updated for one pipeline.",
9375
+ "result.consume-deferred": "Consuming a stage's workflow result failed; it stays staged and is retried.",
9376
+ "consolidation.consume-deferred": "Consuming a review consolidation result failed; it stays pending and is retried.",
9377
+ "dispatch.prepare-failed": "Attaching the agent before dispatch failed; the prompt request does the same work and answers authoritatively.",
9378
+ "interaction.resolved": "A human interaction on a pipeline stage resolved. Metadata only.",
9379
+ "transcripts.migrated": "A transcript migration pass moved stage transcripts; counts only.",
9380
+ "transcripts.maintenance-failed": "Migrating or sweeping stage transcripts failed; the next start retries.",
9381
+ "restore.skipped": "A pipeline could not be restored at startup and was skipped.",
9382
+ "criteria.record-failed": "Acceptance criteria results could not be recorded on the ticket.",
9383
+ "workspace.waiting": "A pipeline is waiting for its workspace; written once per reason.",
9384
+ "rewind.pending": "A pipeline's code rewind has not finished; written once per reason.",
9385
+ "kanban.status-failed": "A restarted pipeline's Kanban status could not be set; it retries shortly.",
9386
+ "usage.read-failed": "Reading a stage session's token usage failed.",
9387
+ "checkpoint.deferred": "A stage transcript checkpoint could not be written yet; the provider's history stands.",
9388
+ "checkpoint.not-committed": "A stage transcript checkpoint was reverted in the commit that should have kept it.",
9389
+ "legacy-transcript.deferred": "Moving a legacy inline transcript failed; the inline body stays readable."
9390
+ }
9391
+ }
9392
+ });
9393
+
9394
+ // ../protocol/src/log-vocabulary/agent-branch.ts
9395
+ var AGENT_BRANCH_LOG_AREAS = defineLogAreas({
9396
+ "agent-branch": {
9397
+ description: "Agent branches shared by review fan-outs, graph agents and goal verifiers; `owner` names which.",
9398
+ events: {
9399
+ "observation.checkpoint-failed": "Checkpointing reviewer observations failed; the next pass retries.",
9400
+ "transcript.mirror-failed": "Mirroring a reviewer transcript failed.",
9401
+ "usage.read-failed": "Reading a reviewer's token usage failed.",
9402
+ "result.nudge-failed": "An agent with an uncommitted result could not be nudged.",
9403
+ "dispatch.prepare-failed": "Attaching the agent before dispatch failed; the prompt request answers authoritatively.",
9404
+ "result.consume-deferred": "Consuming a branch's workflow result failed; it stays staged and is retried."
9405
+ }
9406
+ }
9407
+ });
9408
+
9409
+ // ../protocol/src/log-vocabulary/change-tracking.ts
9410
+ var CHANGE_TRACKING_LOG_AREAS = defineLogAreas({
9411
+ "change-tracking": {
9412
+ description: "Change tracking: turn capture, evidence pulls and measurements.",
9413
+ events: {
9414
+ "journal-import.failed": "Importing surviving OpenCode command journals as legacy summaries failed.",
9415
+ "projection.failed": "Projecting a change event onto its environment failed.",
9416
+ "startup.reconcile-failed": "Reconciling change tracking at startup failed.",
9417
+ "turn-start.capture-failed": "Capturing a turn's start failed, so the turn is untracked.",
9418
+ "dispatch.record-failed": "Recording a turn's dispatch outcome failed.",
9419
+ "turn.finalize-failed": "Finalizing a turn failed.",
9420
+ "turn.settle-failed": "Settling a late interrupted turn failed.",
9421
+ "evidence.pull-failed": "Pulling change evidence from a bridge failed; a later pull retries.",
9422
+ "measurement.failed": "Recomputing a tool's measurement failed."
9423
+ }
9424
+ },
9425
+ "diff-stats": {
9426
+ description: "Environment diff stats and the worktree signals that drive them.",
9427
+ events: {
9428
+ "baseline.update-failed": "An environment's diff baseline could not be updated.",
9429
+ "scan.watcher-failed": "An environment's diff watcher failed; its scans fall back to polling.",
9430
+ "scan.failed": "A diff scan failed; the last results stay, marked stale, and the scan is retried.",
9431
+ "scan.freshness-read-failed": "Reading whether an environment's remote is fresh failed.",
9432
+ "scan.listener-failed": "A change-tracking scan listener threw; the scan itself stands.",
9433
+ "emit.diff-stats-failed": "A diff stats change could not be emitted to its sink.",
9434
+ "emit.worktree-snapshot-failed": "A worktree snapshot could not be emitted to its sink.",
9435
+ "signal.demoted": "A worktree signal stopped being trusted, so scans fall back to timers until it is re-armed."
9436
+ }
9437
+ }
9438
+ });
9439
+
9440
+ // ../protocol/src/log-vocabulary/coordinator.ts
9441
+ var COORDINATOR_LOG_AREAS = defineLogAreas({
9442
+ coordinator: {
9443
+ description: "Coordinators: delegations, status wakes and their store.",
9444
+ events: {
9445
+ "delegation.open-failed": "A delegation could not be opened; `source` says for what.",
9446
+ "deliver-now.drain-failed": "The mail delivery pass after deliverNow failed; the next sweep delivers.",
9447
+ "mail.move-failed": "Mail could not move to the new main coordinator.",
9448
+ "work.move-failed": "Work could not move to the main coordinator.",
9449
+ "wake.observe-remote-workflow-failed": "A remote workflow could not be observed for status wakes.",
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.",
9452
+ "wake.observe-workflow-failed": "A workflow could not be observed for status wakes.",
9453
+ "wake.deliver-failed": "A workflow status wake could not be delivered; the next pass retries.",
9454
+ "wake.waiting-check-failed": "A waiting worker could not be checked; the next pass retries.",
9455
+ "wake.resolve-report-failed": "A finished Resolve tab could not be reported.",
9456
+ "wake.waiting-report-failed": "A waiting worker could not be reported.",
9457
+ "wake.worker-outcomes-failed": "Coordinator-owned workers' merges and deletions could not be checked; the next sweep retries.",
9458
+ "store.malformed": "The coordinator store was malformed and is treated as empty.",
9459
+ "store.unsupported-version": "The coordinator store has an unsupported version and is treated as empty.",
9460
+ "store.invalid-workspace": "An invalid coordinator workspace record was ignored.",
9461
+ "store.workflows-cleared": "The workflow store was full, so a batch of its oldest finished records was removed.",
9462
+ "store.workflows-in-use": "The workflow store was full and every record was still in use, so new work was refused.",
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."
9468
+ }
9469
+ }
9470
+ });
9471
+
9472
+ // ../protocol/src/log-vocabulary/review.ts
9473
+ var REVIEW_LOG_AREAS = defineLogAreas({
9474
+ review: {
9475
+ description: "Multi Review workflows: scheduling, graph runs and interactive fix sessions.",
9476
+ events: {
9477
+ "fix-tab.publish-failed": "A fix request was delivered but its tab could not be opened; the user is told.",
9478
+ "graph-run.not-started": "A workflow's graph run did not start.",
9479
+ "reconcile.scan-failed": "A reconciliation scan failed; the next scan retries.",
9480
+ "graph-engine.unavailable": "The graph engine is selected but unavailable, so the bespoke engine runs.",
9481
+ "graph-run.cancel-failed": "Cancelling a graph run failed; the next pass projects how it ended.",
9482
+ "delete.cleanup-failed": "A cleanup step after deleting a workflow failed; stale tabs reconcile away on hydration.",
9483
+ "fix-session.read-failed": "Reading an interactive fix session's state failed.",
9484
+ "fix-outcome.read-failed": "Reading an interactive fix's outcome failed; it stays pending.",
9485
+ "fix-usage.read-failed": "Reading a fix session's token usage failed.",
9486
+ "result.consume-deferred": "Consuming a workflow result failed; it stays staged and is retried.",
9487
+ "failure-triage.failed": "Classifying a review package's failing tests failed; the package is sealed without the triage and says so."
9488
+ }
9489
+ },
9490
+ "pull-request": {
9491
+ description: "Pull request monitoring, auto-merge and the `gh` reads behind them.",
9492
+ events: {
9493
+ "merged-state.persist-failed": "A merged pull request's state could not be saved; GitHub stays authoritative and cleanup goes on.",
9494
+ "refresh.failed": "A pull request could not be refreshed; the armed flag stands.",
9495
+ "arm.track-failed": "An armed environment could not be tracked; the monitor's next sync retries.",
9496
+ "gh.pr-list-unparseable": "`gh pr list` returned nothing that parses. Sizes only, never the output.",
9497
+ "monitor.start-failed": "Monitoring could not start for a newly opened pull request.",
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.",
9500
+ "auto-merge.evaluation-failed": "Evaluating an environment for auto-merge failed.",
9501
+ "auto-merge.merge-failed": "Auto-merge could not merge a pull request; the attempt is held and retried.",
9502
+ "auto-merge.resolve-failed": "Auto-merge could not launch Resolve for a pull request; the attempt is held and retried.",
9503
+ "monitor.detection-failed": "Checking an environment for its pull request failed.",
9504
+ "monitor.detection-admission-failed": "A pull request check could not be admitted to the work pool.",
9505
+ "monitor.terminal-repair-failed": "Repairing a merged or closed pull request's side effects failed.",
9506
+ "monitor.terminal-resume-failed": "Resuming a merged or closed pull request's side effects failed.",
9507
+ "monitor.stale-reading-ignored": "A non-merged reading (`state`) for a pull request already merged was ignored as stale.",
9508
+ "monitor.state-persist-failed": "A pull request's observed state could not be saved.",
9509
+ "monitor.state-clear-failed": "A pull request's saved state could not be cleared.",
9510
+ "monitor.task-reconcile-failed": "Updating the Kanban task of a merged or closed (`state`) pull request failed.",
9511
+ "monitor.task-store-failed": "A pull request could not be recorded on its Kanban task.",
9512
+ "monitor.emit-failed": "A pull request monitor event could not be emitted to its sink."
9513
+ }
9514
+ }
9515
+ });
9516
+
9517
+ // ../protocol/src/log-vocabulary/public-api.ts
9518
+ var PUBLIC_API_LOG_AREAS = defineLogAreas({
9519
+ "public-api": {
9520
+ description: "The public CLI's operations: their outcomes, reconciliation and exec workers.",
9521
+ events: {
9522
+ "outcome.record-failed": "A background operation's outcome could not be recorded; reconciliation settles it.",
9523
+ "goal-checks.stop-failed": "Goal checks could not be stopped.",
9524
+ "exec.list-failed": "Exec workers could not be listed.",
9525
+ "exec.cancel-failed": "An exec could not be cancelled.",
9526
+ "goal-workers.list-failed": "Goal check workers could not be listed.",
9527
+ "operation.reconcile-failed": "Reconciling one operation failed; the next pass retries.",
9528
+ "reconcile.pass-failed": "A reconciliation pass failed; the next one retries."
9529
+ }
9530
+ }
9531
+ });
9532
+
9533
+ // ../protocol/src/log-vocabulary/agent-accounts.ts
9534
+ var AGENT_ACCOUNTS_LOG_AREAS = defineLogAreas({
9535
+ "agent-accounts": {
9536
+ description: "Agent accounts: automatic switching, staged logins and plan usage.",
9537
+ events: {
9538
+ "switch-notice.failed": "A notice about an automatic account switch failed; the switch stands. `audience` says whose.",
9539
+ "auto-switch.check-failed": "An automatic account check failed; the next nudge retries.",
9540
+ "container-sync.failed": "Handing a login or account to a container failed; `step` says which part.",
9541
+ "last-usage.save-failed": "The last plan usage reading could not be saved; the next save retries.",
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.",
9545
+ "login-refresh.deferred": "Containers were not told to refresh their login now; they reconcile from its durable generation."
9546
+ }
9547
+ }
9548
+ });
9549
+
9550
+ // ../protocol/src/log-vocabulary/docker.ts
9551
+ var DOCKER_LOG_AREAS = defineLogAreas({
9552
+ docker: {
9553
+ description: "Docker containers: lifecycle, starts, staged inputs and the login files they hold.",
9554
+ events: {
9555
+ "portable-inputs.relay-missing": "Docker is rootless and the image predates the staged-input relay, so the container cannot read them until rebuilt.",
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.",
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.",
9559
+ "login-keeper.pass-failed": "A Claude login keeper pass failed; the next interval retries.",
9560
+ "login-keeper.refresh-failed": "Refreshing the host Claude login failed. Fixed text: CLI output can hold credentials.",
9561
+ "login-keeper.refresh-not-extended": "Refreshing the host Claude login did not extend its expiry.",
9562
+ "login-keeper.refresh-check-failed": "Checking the host Claude login after a refresh failed.",
9563
+ "login-watcher.pass-failed": "A container login file watcher pass failed; the next one retries.",
9564
+ "lifecycle.record-failure-failed": "A failed container operation could not be recorded.",
9565
+ "lifecycle.reconcile-failed": "Reconciling one environment's container operation failed; the next pass retries.",
9566
+ "replacement.clear-terminals-failed": "Terminal sessions could not be cleared after a container replacement.",
9567
+ "recovery.clear-terminals-failed": "Terminal sessions could not be cleared after a recovery restore.",
9568
+ "github-ranges.seed-not-copied": "The GitHub ranges seed could not be copied into a container, so its firewall fetches them.",
9569
+ "availability.probe-failed": "Docker is not available; written when the diagnostic changes. Fixed-shape metadata only: messages can hold daemon endpoints.",
9570
+ "start.port-collision-retrying": "An automatic host port collided on start, so it is retried once with fresh ports."
9571
+ }
9572
+ },
9573
+ "docker.reachability": {
9574
+ description: "Whether agents in containers can reach the backend's agent tools server.",
9575
+ events: {
9576
+ "check.crashed": "A reachability check crashed.",
9577
+ "check.started": "A reachability check started.",
9578
+ "check.finished": "A reachability check finished.",
9579
+ "check.probe": "One probe of a finished check.",
9580
+ "check.summary": "Content-free status and reason for a check that did not find the host reachable.",
9581
+ "check.remediation": "One command the user can run to unblock containers.",
9582
+ "shutdown.awaiting-network": "Shutdown is waiting for probe network preparation.",
9583
+ "shutdown.cleanup-deferred": "Probe network cleanup waits until its preparation settles.",
9584
+ "shutdown.removing-resources": "Shutdown is removing probe resources.",
9585
+ "shutdown.container-remove-failed": "A probe container could not be removed at shutdown.",
9586
+ "shutdown.network-remove-failed": "The probe network could not be removed at shutdown.",
9587
+ "probe.skipped": "A container probe was skipped because the agent tools server is not listening.",
9588
+ "preflight.refused": "A stage was refused because its container cannot reach the host.",
9589
+ "probe.prepare-failed": "A container could not be prepared for a probe.",
9590
+ "probe.result": "The outcome of probing one container.",
9591
+ "probe.contradicts-host": "A container probe disagrees with the host status, so the host is rechecked.",
9592
+ "topology.detected": "The Docker topology was read.",
9593
+ "firewall.detected": "The host firewall was read.",
9594
+ "probe-network.remove-failed": "The probe network could not be removed.",
9595
+ "probe-network.create-failed": "The probe network could not be created, so only the default bridge is checked.",
9596
+ "event.emit-failed": "A reachability event could not be emitted.",
9597
+ "host-addresses.list-failed": "Host addresses could not be listed.",
9598
+ "probe-image.present": "The probe image is already present.",
9599
+ "probe-image.pulling": "The probe image is being pulled.",
9600
+ "probe-image.pulled": "The probe image was pulled.",
9601
+ "probe-image.pull-failed": "The probe image could not be pulled.",
9602
+ "probe-image.fallback": "The environment image is used as the probe image.",
9603
+ "probe-image.missing": "No probe image is available.",
9604
+ "network.list-failed": "Docker networks could not be listed.",
9605
+ "network.inspect-failed": "A Docker network could not be inspected.",
9606
+ "stale-containers.removing": "Stale probe containers are being removed.",
9607
+ "stale-networks.removing": "Stale probe networks are being removed."
9608
+ }
9609
+ }
9610
+ });
9611
+
9612
+ // ../protocol/src/log-vocabulary/mcp.ts
9613
+ var MCP_LOG_AREAS = defineLogAreas({
9614
+ "control-mcp": {
9615
+ description: "The Control MCP server other agents and devices reach Orkestrator through.",
9616
+ events: {
9617
+ "listener.port-free": "The Control MCP's fixed port is free again, so it is listening.",
9618
+ "state-listener.failed": "A Control MCP state listener threw; the others still run.",
9619
+ "delegation.remote-open-failed": "A delegation could not be opened on another node.",
9620
+ "delegation.open-failed": "A coordinator delegation could not be opened."
9621
+ }
9622
+ },
9623
+ "mcp-management": {
9624
+ description: "Managed MCP configuration: its commands, overlays and apply loop.",
9625
+ events: {
9626
+ "command.failed": "An MCP management command failed; `ref` is the correlation id shown to the user.",
9627
+ "overlay.materialise-failed": "An MCP overlay could not be written.",
9628
+ "apply.tick-failed": "An MCP apply tick failed; the next one retries."
9629
+ }
9630
+ }
9631
+ });
9632
+
9633
+ // ../protocol/src/log-vocabulary/design.ts
9634
+ var DESIGN_LOG_AREAS = defineLogAreas({
9635
+ design: {
9636
+ description: "The design canvas: its library, renderer and session links.",
9637
+ events: {
9638
+ "change-signal.failed": "A design change signal failed.",
9639
+ "library.index-write-failed": "The design library index could not be written.",
9640
+ "library.refresh-failed": "The design library could not be refreshed.",
9641
+ "renderer.problem": "The renderer hit a limit or lost a browser; `problem` is a fixed name.",
9642
+ "task.failed": "A design background task failed.",
9643
+ "canvas.needs-recovery": "A design canvas is unreadable and marked for recovery.",
9644
+ "startup.step-failed": "One part of design startup failed; `step` says which.",
9645
+ "legacy.retire-failed": "A migrated legacy design could not be retired.",
9646
+ "profiles.swept": "Design startup removed stale browser profiles.",
9647
+ "session-link.record-failed": "A closing conversation could not be recorded on a design link."
9648
+ }
9649
+ }
9650
+ });
9651
+
9652
+ // ../protocol/src/log-vocabulary/graph.ts
9653
+ var GRAPH_LOG_AREAS = defineLogAreas({
9654
+ graph: {
9655
+ description: "Graph runs: launches, passes, rewinds, system actions and templates.",
9656
+ events: {
9657
+ "describe.pass-failed": "A graph describe pass failed. Content-free: never the description or draft.",
9658
+ "system.stop-failed": "A system action's work could not be stopped.",
9659
+ "system.action-failed": "A system action failed; `cause` is its fixed failure cause.",
9660
+ "attention.update-failed": "The sidebar could not be updated for a run.",
9661
+ "launch.ticket-link-failed": "A launched run's ticket could not be linked.",
9662
+ "launch.started": "A graph run was launched.",
9663
+ "launch.swept": "Runs that ended without an environment were removed.",
9664
+ "rewind.pending": "A run's code rewind has not finished.",
9665
+ "rewind.applied": "A run was restarted or rewound.",
9666
+ "rewind.waiting": "A run waits for its code rewind to finish.",
9667
+ "history.pruned": "Finished runs beyond an environment's history were removed.",
9668
+ "history.prune-failed": "Pruning an environment's run history failed.",
9669
+ "worktree.cleanup-failed": "A run's branch worktree cleanup failed.",
9670
+ "run.unreadable": "A run is unreadable, so it is not scheduled.",
9671
+ "run.pass-failed": "A pass over a run failed.",
9672
+ "transcript.capture-failed": "A run's transcript capture failed.",
9673
+ "ticket.link-failed": "A run's ticket could not be linked to its environment.",
9674
+ "template.skipped": "A built-in template was skipped as invalid or a duplicate."
9675
+ }
9676
+ }
9677
+ });
9678
+
9679
+ // ../protocol/src/log-vocabulary/nodes.ts
9680
+ var NODES_LOG_AREAS = defineLogAreas({
9681
+ nodes: {
9682
+ description: "Command nodes: links, handovers, leaf mail, ticket sync and project copies.",
9683
+ events: {
9684
+ "actions.resume-failed": "Approved actions could not be resumed; a later pass retries.",
9685
+ "project-copy.notify-failed": "The coordinator could not be told a project copy finished.",
9686
+ "mail.delivery-deferred": "Leaf mail could not reach a coordinator yet.",
9687
+ "command.post-step-failed": "A step after a routed command failed.",
9688
+ "seed-files.incomplete": "Seed files for a leaf environment were not all copied.",
9689
+ "contact.record-failed": "The latest controller contact could not be recorded.",
9690
+ "settings.send-failed": "Settings could not be sent to a node.",
9691
+ "verification.record-failed": "A node verification could not be recorded.",
9692
+ "profile.record-failed": "A node profile could not be recorded.",
9693
+ "detach.unconfirmed": "A forgotten node has not confirmed the detach yet.",
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."
9699
+ }
9700
+ }
9701
+ });
9702
+
9703
+ // ../protocol/src/log-vocabulary/linear.ts
9704
+ var LINEAR_LOG_AREAS = defineLogAreas({
9705
+ linear: {
9706
+ description: "Linear issues read for build actions.",
9707
+ events: {
9708
+ "comments.load-failed": "An issue's comments could not be loaded; the issue still renders without them."
9709
+ }
9710
+ }
9711
+ });
9712
+
9713
+ // ../protocol/src/log-vocabulary/usage-history.ts
9714
+ var USAGE_HISTORY_LOG_AREAS = defineLogAreas({
9715
+ "usage-history": {
9716
+ description: "Recorded agent token usage.",
9717
+ events: {
9718
+ "record.failed": "Agent usage could not be recorded; a later read counts it.",
9719
+ "prune.failed": "Pruning recorded usage failed; the next prune retries."
9720
+ }
9721
+ }
9722
+ });
9723
+
9724
+ // ../protocol/src/log-vocabulary/feature.ts
9725
+ var FEATURE_LOG_AREAS = defineLogAreas({
9726
+ feature: {
9727
+ description: "Pipeline environments started from a feature, and feature planning.",
9728
+ events: {
9729
+ "naming.fallback": "Automatic naming failed, so a local fallback name is used. Error kind only: the description stays out.",
9730
+ "planning.legacy-adopt-failed": "Legacy planning conversations could not be adopted.",
9731
+ "planning.tick-retrying": "A planning tick failed on a transient error; the next tick retries."
9732
+ }
9733
+ }
9734
+ });
9735
+
9736
+ // ../protocol/src/log-vocabulary/host.ts
9737
+ var HOST_LOG_AREAS = defineLogAreas({
9738
+ host: {
9739
+ description: "The host machine: its executables, load, suspends and maintenance.",
9740
+ events: {
9741
+ "path.discovered": "Executable discovery finished. Counts and booleans only: PATH entries can hold private directory names.",
9742
+ "tool.available": "A host tool's availability was read.",
9743
+ "tool.missing": "A host tool was not found.",
9744
+ "maintenance.listener-failed": "A host maintenance listener threw; the others still run.",
9745
+ "suspend.reconcile-failed": "Reconciling due work after a host suspension failed.",
9746
+ "load.sample-failed": "Sampling machine load failed; the next sample retries."
9747
+ }
9748
+ }
9749
+ });
9750
+
9751
+ // ../protocol/src/log-vocabulary/transcript-artifacts.ts
9752
+ var TRANSCRIPT_ARTIFACTS_LOG_AREAS = defineLogAreas({
9753
+ "transcript-artifacts": {
9754
+ description: "Transcript artifacts: previews, printing, grants and their ledger. Ids, kinds, sizes and reason codes only.",
9755
+ events: {
9756
+ "announce-failed": "An artifact change could not be announced.",
9757
+ "cleanup-failed": "An artifact cleanup failed.",
9758
+ "grant-revocation-failed": "A grant could not be revoked.",
9759
+ "ledger-listener-failed": "A ledger listener threw.",
9760
+ "ledger-read-failed": "The ledger could not be read.",
9761
+ "operation-executor-failed": "A preview operation's executor failed.",
9762
+ "operation-failed": "A preview operation failed.",
9763
+ "pdf-preview": "A PDF preview was served.",
9764
+ "pdf-preview-failed": "A PDF preview failed.",
9765
+ "pdf-print-failed": "Printing an artifact to PDF failed.",
9766
+ "pdf-printed": "An artifact was printed to PDF.",
9767
+ "runtime-unavailable": "The artifact runtime could not be created."
9768
+ }
9769
+ }
9770
+ });
9771
+
9772
+ // ../protocol/src/log-vocabulary/scheduler.ts
9773
+ var SCHEDULER_LOG_AREAS = defineLogAreas({
9774
+ scheduler: {
9775
+ description: "Scheduled jobs and the backend-owned timing that fires them.",
9776
+ events: {
9777
+ "tick.failed": "A scheduler tick failed; the next tick retries.",
9778
+ "job.claim-failed": "A due job could not be claimed.",
9779
+ "fire.heartbeat-failed": "A running fire's heartbeat could not be recorded.",
9780
+ "fire.outcome-record-failed": "A finished fire's outcome could not be recorded."
9781
+ }
9782
+ }
9783
+ });
9784
+
8673
9785
  // ../protocol/src/log-vocabulary/web-app.ts
8674
9786
  var WEB_APP_LOG_AREAS = defineLogAreas({
8675
9787
  "web.app": {
@@ -8837,7 +9949,7 @@ var WEB_ENVIRONMENT_LOG_AREAS = defineLogAreas({
8837
9949
  "models.pi-seed-failed": "The create dialog could not seed the Pi model catalogue.",
8838
9950
  "models.opencode-cache-load-failed": "The create dialog could not read cached OpenCode models.",
8839
9951
  "github-credential.check-failed": "The GitHub credential check before creating failed.",
8840
- "feature-build.start-failed": "Starting a feature build from the dialog failed.",
9952
+ "feature-build.start-failed": "Starting a pipeline environment from the dialog failed.",
8841
9953
  "settings.extensions-load-failed": "The settings dialog could not load extensions.",
8842
9954
  "settings.container-reset-failed": "The settings dialog could not reset the container.",
8843
9955
  "settings.save-failed": "The settings dialog could not save.",
@@ -9129,6 +10241,25 @@ var LOG_VOCABULARY = {
9129
10241
  ...TMUX_LOG_AREAS,
9130
10242
  ...UPDATER_LOG_AREAS,
9131
10243
  ...WEB_ANNOTATIONS_LOG_AREAS,
10244
+ ...STORAGE_LOG_AREAS,
10245
+ ...BUILD_PIPELINE_LOG_AREAS,
10246
+ ...AGENT_BRANCH_LOG_AREAS,
10247
+ ...CHANGE_TRACKING_LOG_AREAS,
10248
+ ...COORDINATOR_LOG_AREAS,
10249
+ ...REVIEW_LOG_AREAS,
10250
+ ...PUBLIC_API_LOG_AREAS,
10251
+ ...AGENT_ACCOUNTS_LOG_AREAS,
10252
+ ...DOCKER_LOG_AREAS,
10253
+ ...MCP_LOG_AREAS,
10254
+ ...DESIGN_LOG_AREAS,
10255
+ ...GRAPH_LOG_AREAS,
10256
+ ...NODES_LOG_AREAS,
10257
+ ...LINEAR_LOG_AREAS,
10258
+ ...USAGE_HISTORY_LOG_AREAS,
10259
+ ...FEATURE_LOG_AREAS,
10260
+ ...HOST_LOG_AREAS,
10261
+ ...TRANSCRIPT_ARTIFACTS_LOG_AREAS,
10262
+ ...SCHEDULER_LOG_AREAS,
9132
10263
  ...WEB_APP_LOG_AREAS,
9133
10264
  ...WEB_BUILD_PIPELINE_LOG_AREAS,
9134
10265
  ...WEB_CHAT_LOG_AREAS,
@@ -9529,7 +10660,7 @@ import path5 from "path";
9529
10660
  // ../../apps/backend/package.json
9530
10661
  var package_default = {
9531
10662
  name: "@orkestrator/backend",
9532
- version: "2.35.4-beta",
10663
+ version: "2.36.0",
9533
10664
  private: true,
9534
10665
  type: "module",
9535
10666
  exports: {
@@ -12332,9 +13463,128 @@ async function readPatch(io, options2) {
12332
13463
  }
12333
13464
  return parsed;
12334
13465
  }
12335
-
12336
- // src/client/commands/workflows.ts
12337
- 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
+ ]);
12338
13588
 
12339
13589
  // src/client/commands/session.ts
12340
13590
  import path8 from "path";
@@ -13132,7 +14382,7 @@ var sessionCommands = [
13132
14382
  path: ["session", "transcript"],
13133
14383
  action: "session.transcript",
13134
14384
  summary: "Read a bounded transcript page; --follow polls for new messages.",
13135
- 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.",
13136
14386
  positionals: [{ name: "session", required: true }],
13137
14387
  options: [
13138
14388
  {
@@ -13187,6 +14437,7 @@ var sessionCommands = [
13187
14437
  }
13188
14438
  const seen = new Set;
13189
14439
  let lastToken = null;
14440
+ let conditional = null;
13190
14441
  let emitted = 0;
13191
14442
  const emit = (record) => {
13192
14443
  if (context.global.output === "jsonl")
@@ -13200,10 +14451,15 @@ var sessionCommands = [
13200
14451
  };
13201
14452
  try {
13202
14453
  await observe(async () => {
13203
- const page = await session.read("session.transcript", {
14454
+ conditional ??= (await session.capabilities()).features.transcriptKnownToken === true;
14455
+ const answer = await session.read("session.transcript", {
13204
14456
  ...input,
13205
- limit: PUBLIC_API_LIMITS.transcriptMaxMessages
14457
+ limit: PUBLIC_API_LIMITS.transcriptMaxMessages,
14458
+ ...conditional && lastToken !== null ? { knownToken: lastToken } : {}
13206
14459
  });
14460
+ if (isPublicTranscriptUnchanged(answer))
14461
+ return { done: false };
14462
+ const page = answer;
13207
14463
  if (page.token !== null && page.token === lastToken)
13208
14464
  return { done: false };
13209
14465
  if (lastToken !== null && page.messages.length > 0 && !page.messages.some((m) => seen.has(m.id))) {
@@ -16269,122 +17525,6 @@ var graphCommands = [
16269
17525
  }
16270
17526
  ];
16271
17527
 
16272
- // ../protocol/src/public-api-resources.ts
16273
- var PUBLIC_CHANGE_SCOPES = Object.freeze(["environment"]);
16274
- var AGENT_PLATFORM_KEYS = ["claude", "codex", "cursor", "grok", "opencode", "pi"];
16275
- function agentSettingDescriptors(scope) {
16276
- const application = "next-session";
16277
- return [
16278
- {
16279
- key: "agent.defaultAgent",
16280
- scope,
16281
- type: "agent",
16282
- inherits: true,
16283
- application,
16284
- description: "Agent platform used when a launch does not name one."
16285
- },
16286
- ...AGENT_PLATFORM_KEYS.flatMap((platform) => [
16287
- {
16288
- key: `agent.${platform}.mode`,
16289
- scope,
16290
- type: "agent-mode",
16291
- inherits: true,
16292
- application,
16293
- description: `Launch mode (native or terminal) for ${platform}.`
16294
- },
16295
- {
16296
- key: `agent.${platform}.model`,
16297
- scope,
16298
- type: "string",
16299
- inherits: true,
16300
- application,
16301
- description: `Default model for new ${platform} sessions.`
16302
- },
16303
- {
16304
- key: `agent.${platform}.reasoningEffort`,
16305
- scope,
16306
- type: "string",
16307
- inherits: true,
16308
- application,
16309
- description: `Default reasoning level for new ${platform} sessions.`
16310
- },
16311
- {
16312
- key: `agent.${platform}.fastMode`,
16313
- scope,
16314
- type: "boolean",
16315
- inherits: true,
16316
- application,
16317
- description: `Default speed for new ${platform} sessions (true is Fast).`
16318
- }
16319
- ])
16320
- ];
16321
- }
16322
- var PUBLIC_PROJECT_SETTINGS = Object.freeze([
16323
- {
16324
- key: "defaultBranch",
16325
- scope: "project",
16326
- type: "string",
16327
- inherits: false,
16328
- application: "next-environment",
16329
- description: "Branch new environments are created from."
16330
- },
16331
- {
16332
- key: "prBaseBranch",
16333
- scope: "project",
16334
- type: "string",
16335
- inherits: false,
16336
- application: "applied",
16337
- description: "Base branch for pull requests and diff baselines."
16338
- },
16339
- {
16340
- key: "defaultPortMappings",
16341
- scope: "project",
16342
- type: "port-mappings",
16343
- inherits: false,
16344
- environmentTypes: ["container"],
16345
- application: "next-environment",
16346
- description: "Port mappings copied into new container environments."
16347
- },
16348
- {
16349
- key: "filesToCopy",
16350
- scope: "project",
16351
- type: "string-list",
16352
- inherits: false,
16353
- application: "next-environment",
16354
- description: "Untracked files copied into new environments."
16355
- },
16356
- {
16357
- key: "entryPort",
16358
- scope: "project",
16359
- type: "port",
16360
- inherits: false,
16361
- application: "next-environment",
16362
- description: "Default preview entry port for new environments."
16363
- },
16364
- ...agentSettingDescriptors("project")
16365
- ]);
16366
- var PUBLIC_ENVIRONMENT_SETTINGS = Object.freeze([
16367
- {
16368
- key: "portMappings",
16369
- scope: "environment",
16370
- type: "port-mappings",
16371
- inherits: false,
16372
- environmentTypes: ["container"],
16373
- application: "next-start",
16374
- description: "Container port mappings; a running container adopts them on recreate."
16375
- },
16376
- {
16377
- key: "allowedDomains",
16378
- scope: "environment",
16379
- type: "domain-list",
16380
- inherits: true,
16381
- environmentTypes: ["container"],
16382
- application: "next-start",
16383
- description: "Restricted-network allowlist; unset inherits the global list. A running container whose image supports it applies the change immediately (reported as applied)."
16384
- },
16385
- ...agentSettingDescriptors("environment")
16386
- ]);
16387
-
16388
17528
  // src/client/commands/changes.ts
16389
17529
  var SCOPE_LABELS = {
16390
17530
  "changes.scope.environment-net": "Environment changes",
@@ -16965,6 +18105,10 @@ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
16965
18105
  // src/client/transport.ts
16966
18106
  var DEFAULT_REQUEST_TIMEOUT_MS = 60000;
16967
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
+ }
16968
18112
  function connectionRefused(error) {
16969
18113
  const code = error?.code;
16970
18114
  const cause = error?.cause?.code;
@@ -16998,9 +18142,6 @@ class GatewayTransport {
16998
18142
  let token = await this.target.readToken();
16999
18143
  let response = await sendWithBudget(token);
17000
18144
  if (response.status === 401 && !options2.mutation) {
17001
- await response.body?.cancel().catch(() => {
17002
- return;
17003
- });
17004
18145
  token = await this.target.readToken();
17005
18146
  response = await sendWithBudget(token);
17006
18147
  }
@@ -17031,7 +18172,13 @@ class GatewayTransport {
17031
18172
  signal: controller.signal
17032
18173
  });
17033
18174
  if (!response.body)
17034
- 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
+ }
17035
18182
  const abort = new Promise((_, reject) => {
17036
18183
  if (controller.signal.aborted)
17037
18184
  reject(controller.signal.reason);
@@ -17044,10 +18191,7 @@ class GatewayTransport {
17044
18191
  readStreamBounded(response.body, PUBLIC_API_LIMITS.responseMaxBytes, () => new CliError("response-invalid", "The backend response exceeded the client limit"), controller.signal),
17045
18192
  abort
17046
18193
  ]);
17047
- return new Response(Buffer.from(bytes), {
17048
- status: response.status,
17049
- statusText: response.statusText
17050
- });
18194
+ return { status: response.status, bytes };
17051
18195
  } catch (error) {
17052
18196
  if (error instanceof CliError)
17053
18197
  throw error;
@@ -17060,30 +18204,16 @@ class GatewayTransport {
17060
18204
  options2.signal?.removeEventListener("abort", onAbort);
17061
18205
  }
17062
18206
  }
17063
- async decode(response, options2) {
18207
+ decode(response, options2) {
17064
18208
  if (response.status >= 300 && response.status < 400) {
17065
- await response.body?.cancel().catch(() => {
17066
- return;
17067
- });
17068
18209
  throw new CliError("connection-failed", "The backend answered with a redirect; redirects are never followed with credentials");
17069
18210
  }
17070
18211
  if (response.status === 401 || response.status === 403) {
17071
- await response.body?.cancel().catch(() => {
17072
- return;
17073
- });
17074
18212
  throw new CliError("auth-failed", response.status === 401 ? "The backend rejected the credential" : "The backend refused this client (origin or permission)");
17075
18213
  }
17076
- let bytes;
17077
- try {
17078
- bytes = response.body ? await readStreamBounded(response.body, PUBLIC_API_LIMITS.responseMaxBytes, () => new CliError("response-invalid", "The backend response exceeded the client limit")) : new Uint8Array;
17079
- } catch (error) {
17080
- if (error instanceof CliError)
17081
- throw error;
17082
- throw new CliError(options2.mutation ? "transport-uncertain" : "connection-failed", "The backend response was interrupted");
17083
- }
17084
18214
  let payload;
17085
18215
  try {
17086
- payload = JSON.parse(new TextDecoder().decode(bytes));
18216
+ payload = JSON.parse(new TextDecoder().decode(response.bytes));
17087
18217
  } catch {
17088
18218
  throw new CliError(options2.mutation ? "transport-uncertain" : "response-invalid", `The backend returned a non-JSON response (HTTP ${response.status})`);
17089
18219
  }
@@ -17091,7 +18221,7 @@ class GatewayTransport {
17091
18221
  throw new CliError("response-invalid", "The backend response is not a JSON object");
17092
18222
  }
17093
18223
  const record = payload;
17094
- if (response.ok)
18224
+ if (response.status >= 200 && response.status < 300)
17095
18225
  return record.result;
17096
18226
  const message = typeof record.error === "string" ? record.error : "";
17097
18227
  if (message.startsWith("Unknown backend command: ")) {
@@ -17323,7 +18453,7 @@ function quoteArgument(value) {
17323
18453
  }
17324
18454
 
17325
18455
  // src/client/targets.ts
17326
- import { promises as fs4 } from "fs";
18456
+ import { constants as fsConstants, promises as fs4 } from "fs";
17327
18457
  import path11 from "path";
17328
18458
  import { isIPv4 } from "net";
17329
18459
 
@@ -17460,35 +18590,75 @@ async function readTokenFile(file, requirePrivate) {
17460
18590
  }
17461
18591
  return token.trim();
17462
18592
  }
17463
- 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
+ }
17464
18626
  let text;
17465
18627
  try {
17466
- const stat = await fs4.lstat(file);
18628
+ const stat = await handle.stat();
17467
18629
  if (!stat.isFile())
17468
- throw new Error("not a file");
17469
- if (stat.size > BACKEND_INSTANCE_DESCRIPTOR_MAX_BYTES)
17470
- throw new Error("too large");
17471
- text = await fs4.readFile(file, "utf8");
17472
- } catch {
17473
- 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();
17474
18644
  }
17475
18645
  try {
17476
18646
  return parseBackendInstanceDescriptor(JSON.parse(text));
17477
- } catch (error) {
17478
- 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");
17479
18649
  }
17480
18650
  }
17481
18651
  function processIsAlive(pid) {
17482
18652
  try {
17483
18653
  process.kill(pid, 0);
17484
18654
  return true;
17485
- } catch (error) {
17486
- return error.code === "EPERM";
18655
+ } catch {
18656
+ return false;
17487
18657
  }
17488
18658
  }
17489
18659
  function descriptorTarget(name, kind, descriptor, expectedInstallationId, refresh) {
17490
18660
  if (!processIsAlive(descriptor.pid)) {
17491
- 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)`);
17492
18662
  }
17493
18663
  if (expectedInstallationId && descriptor.installationId !== expectedInstallationId) {
17494
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 } });
@@ -17568,7 +18738,11 @@ async function resolveProfile(profileName, env) {
17568
18738
  const refresh = () => resolveProfile(profileName, env);
17569
18739
  if (manifest.dataDir) {
17570
18740
  const descriptorFile = path11.join(manifest.dataDir, BACKEND_INSTANCE_DESCRIPTOR_FILE);
17571
- 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
+ });
17572
18746
  if (descriptor) {
17573
18747
  if (descriptor.pid !== backendPid) {
17574
18748
  throw new CliError("profile-unavailable", `Profile '${located.id}' has a descriptor from a different backend process`);
@@ -19556,7 +20730,9 @@ import path13 from "path";
19556
20730
  async function currentDescriptorGeneration(dataDir) {
19557
20731
  try {
19558
20732
  return (await readDescriptor(path13.join(dataDir, BACKEND_INSTANCE_DESCRIPTOR_FILE))).generation;
19559
- } catch {
20733
+ } catch (error) {
20734
+ if (isDescriptorRefusal(error))
20735
+ throw error;
19560
20736
  return null;
19561
20737
  }
19562
20738
  }
@@ -19596,7 +20772,10 @@ async function awaitServiceConnection(dataDir, previousGeneration, options2) {
19596
20772
  const fresh = value.generation !== previousGeneration && path13.resolve(value.dataDir) === path13.resolve(dataDir) && (options2.expectedVersion === undefined || value.appVersion === options2.expectedVersion) && processIsAlive(value.pid);
19597
20773
  if (fresh)
19598
20774
  return { done: true, value };
19599
- } catch {}
20775
+ } catch (error) {
20776
+ if (isDescriptorRefusal(error))
20777
+ throw error;
20778
+ }
19600
20779
  await options2.assertStarting?.();
19601
20780
  return { done: false };
19602
20781
  }, options2);
@@ -21493,9 +22672,9 @@ var ticketCommands = [
21493
22672
  ];
21494
22673
 
21495
22674
  // src/client/commands/toolchain.ts
21496
- import path20 from "path";
22675
+ import path22 from "path";
21497
22676
  function dataDirectory2(context, parsed) {
21498
- 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));
21499
22678
  }
21500
22679
  function requestedTools(parsed) {
21501
22680
  const raw = parsed.options.tool;
@@ -21598,7 +22777,7 @@ var toolchainCommands = [
21598
22777
  const rows = installed.tools.map((tool) => ({
21599
22778
  tool,
21600
22779
  version: installed.versions[tool] ?? "",
21601
- executable: path20.join(installed.currentBinDir, path20.basename(installed.executables[tool]))
22780
+ executable: path22.join(installed.currentBinDir, path22.basename(installed.executables[tool]))
21602
22781
  }));
21603
22782
  return {
21604
22783
  action: "toolchain.install",