@moxt-ai/cli 0.10.0-beta.5 → 0.10.0-beta.6

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/index.cjs CHANGED
@@ -1174,18 +1174,18 @@ var require_suggestSimilar = __commonJS({
1174
1174
  }
1175
1175
  return d[a.length][b.length];
1176
1176
  }
1177
- function suggestSimilar(word, candidates) {
1178
- if (!candidates || candidates.length === 0) return "";
1179
- candidates = Array.from(new Set(candidates));
1177
+ function suggestSimilar(word, candidates2) {
1178
+ if (!candidates2 || candidates2.length === 0) return "";
1179
+ candidates2 = Array.from(new Set(candidates2));
1180
1180
  const searchingOptions = word.startsWith("--");
1181
1181
  if (searchingOptions) {
1182
1182
  word = word.slice(2);
1183
- candidates = candidates.map((candidate) => candidate.slice(2));
1183
+ candidates2 = candidates2.map((candidate) => candidate.slice(2));
1184
1184
  }
1185
1185
  let similar = [];
1186
1186
  let bestDistance = maxDistance;
1187
1187
  const minSimilarity = 0.4;
1188
- candidates.forEach((candidate) => {
1188
+ candidates2.forEach((candidate) => {
1189
1189
  if (candidate.length <= 1) return;
1190
1190
  const distance = editDistance(word, candidate);
1191
1191
  const length = Math.max(word.length, candidate.length);
@@ -4356,7 +4356,7 @@ function assertClientRequestId(clientRequestId) {
4356
4356
  }
4357
4357
  }
4358
4358
  function assertRelativeWorkingDirectory(relativeWorkingDirectory) {
4359
- if (relativeWorkingDirectory.length === 0 || relativeWorkingDirectory.includes("\0") || (0, import_node_path.isAbsolute)(relativeWorkingDirectory) || import_node_path.win32.isAbsolute(relativeWorkingDirectory) || windowsDrivePattern.test(relativeWorkingDirectory)) {
4359
+ if (relativeWorkingDirectory.length === 0 || relativeWorkingDirectory.includes("\0") || (0, import_node_path2.isAbsolute)(relativeWorkingDirectory) || import_node_path2.win32.isAbsolute(relativeWorkingDirectory) || windowsDrivePattern.test(relativeWorkingDirectory)) {
4360
4360
  throwRootViolation(relativeWorkingDirectory);
4361
4361
  }
4362
4362
  const pathSegments = relativeWorkingDirectory.split(/[\\/]/);
@@ -4365,14 +4365,14 @@ function assertRelativeWorkingDirectory(relativeWorkingDirectory) {
4365
4365
  }
4366
4366
  }
4367
4367
  function resolveWorkingDirectory(rootPath, relativeWorkingDirectory) {
4368
- if (!(0, import_node_path.isAbsolute)(rootPath)) {
4368
+ if (!(0, import_node_path2.isAbsolute)(rootPath)) {
4369
4369
  throw new MachineProtocolInvariantError(MachineProtocolErrorCode.RootViolation, "The paired working root must be an absolute path");
4370
4370
  }
4371
4371
  assertRelativeWorkingDirectory(relativeWorkingDirectory);
4372
- const resolvedRoot = (0, import_node_path.resolve)(rootPath);
4373
- const resolvedWorkingDirectory = (0, import_node_path.resolve)(resolvedRoot, relativeWorkingDirectory);
4374
- const pathFromRoot = (0, import_node_path.relative)(resolvedRoot, resolvedWorkingDirectory);
4375
- if (pathFromRoot === ".." || pathFromRoot.startsWith(`..${import_node_path.sep}`) || (0, import_node_path.isAbsolute)(pathFromRoot)) {
4372
+ const resolvedRoot = (0, import_node_path2.resolve)(rootPath);
4373
+ const resolvedWorkingDirectory = (0, import_node_path2.resolve)(resolvedRoot, relativeWorkingDirectory);
4374
+ const pathFromRoot = (0, import_node_path2.relative)(resolvedRoot, resolvedWorkingDirectory);
4375
+ if (pathFromRoot === ".." || pathFromRoot.startsWith(`..${import_node_path2.sep}`) || (0, import_node_path2.isAbsolute)(pathFromRoot)) {
4376
4376
  throwRootViolation(relativeWorkingDirectory);
4377
4377
  }
4378
4378
  return resolvedWorkingDirectory;
@@ -4420,12 +4420,12 @@ function throwRootViolation(relativeWorkingDirectory) {
4420
4420
  function throwEventSequenceConflict(message) {
4421
4421
  throw new MachineProtocolInvariantError(MachineProtocolErrorCode.EventSequenceConflict, message);
4422
4422
  }
4423
- var import_node_path, minimumClientRequestIdLength, maximumClientRequestIdLength, minimumWaitTimeoutSeconds, maximumWaitTimeoutSeconds, clientRequestIdPattern, windowsDrivePattern, terminalJobStatuses, validJobTransitions, MachineProtocolInvariantError;
4423
+ var import_node_path2, minimumClientRequestIdLength, maximumClientRequestIdLength, minimumWaitTimeoutSeconds, maximumWaitTimeoutSeconds, clientRequestIdPattern, windowsDrivePattern, terminalJobStatuses, validJobTransitions, MachineProtocolInvariantError;
4424
4424
  var init_invariants = __esm({
4425
4425
  "../machine-connector/dist/protocol/v1/invariants.js"() {
4426
4426
  "use strict";
4427
4427
  init_cjs_shims();
4428
- import_node_path = require("path");
4428
+ import_node_path2 = require("path");
4429
4429
  init_contracts();
4430
4430
  init_enums();
4431
4431
  minimumClientRequestIdLength = 8;
@@ -4508,7 +4508,7 @@ async function executeProcess(executable, argumentsList, workingDirectory, envir
4508
4508
  }
4509
4509
  const child = (0, import_node_child_process.spawn)(executable, argumentsList, {
4510
4510
  cwd: workingDirectory,
4511
- detached: (0, import_node_os.platform)() !== "win32",
4511
+ detached: (0, import_node_os2.platform)() !== "win32",
4512
4512
  env: { ...environment },
4513
4513
  shell: false,
4514
4514
  stdio: ["pipe", "pipe", "pipe"],
@@ -4642,17 +4642,17 @@ async function executeProcess(executable, argumentsList, workingDirectory, envir
4642
4642
  };
4643
4643
  }
4644
4644
  async function resolveCanonicalWorkingDirectory(rootPath, relativeWorkingDirectory) {
4645
- const canonicalRoot = await (0, import_promises3.realpath)(rootPath);
4645
+ const canonicalRoot = await (0, import_promises4.realpath)(rootPath);
4646
4646
  const lexicalCandidate = resolveWorkingDirectory(canonicalRoot, relativeWorkingDirectory);
4647
- const canonicalCandidate = await (0, import_promises3.realpath)(lexicalCandidate);
4648
- const relativePath = (0, import_node_path2.relative)(canonicalRoot, canonicalCandidate);
4649
- if (relativePath === ".." || relativePath.startsWith(`..${import_node_path2.sep}`) || (0, import_node_path2.isAbsolute)(relativePath)) {
4647
+ const canonicalCandidate = await (0, import_promises4.realpath)(lexicalCandidate);
4648
+ const relativePath = (0, import_node_path3.relative)(canonicalRoot, canonicalCandidate);
4649
+ if (relativePath === ".." || relativePath.startsWith(`..${import_node_path3.sep}`) || (0, import_node_path3.isAbsolute)(relativePath)) {
4650
4650
  throw new Error(`Working directory escapes paired root: ${relativeWorkingDirectory}`);
4651
4651
  }
4652
4652
  return canonicalCandidate;
4653
4653
  }
4654
4654
  async function terminateProcessTree(pid) {
4655
- if ((0, import_node_os.platform)() === "win32") {
4655
+ if ((0, import_node_os2.platform)() === "win32") {
4656
4656
  const process2 = (0, import_node_child_process.spawn)("taskkill", ["/pid", String(pid), "/t", "/f"], {
4657
4657
  stdio: "ignore",
4658
4658
  windowsHide: true
@@ -4702,15 +4702,15 @@ function delay(milliseconds) {
4702
4702
  setTimeout(resolvePromise, milliseconds);
4703
4703
  });
4704
4704
  }
4705
- var import_node_child_process, import_promises3, import_node_os, import_node_path2, cancellationDeadlineMilliseconds, RunningProcessHandle;
4705
+ var import_node_child_process, import_promises4, import_node_os2, import_node_path3, cancellationDeadlineMilliseconds, RunningProcessHandle;
4706
4706
  var init_process_executor = __esm({
4707
4707
  "../machine-connector/dist/runtime/process-executor.js"() {
4708
4708
  "use strict";
4709
4709
  init_cjs_shims();
4710
4710
  import_node_child_process = require("child_process");
4711
- import_promises3 = require("fs/promises");
4712
- import_node_os = require("os");
4713
- import_node_path2 = require("path");
4711
+ import_promises4 = require("fs/promises");
4712
+ import_node_os2 = require("os");
4713
+ import_node_path3 = require("path");
4714
4714
  init_enums();
4715
4715
  init_invariants();
4716
4716
  cancellationDeadlineMilliseconds = 4e3;
@@ -5038,7 +5038,7 @@ async function executeCodex(workingDirectory, outputPath, environment, arguments
5038
5038
  }
5039
5039
  }
5040
5040
  const finalMessage = (await readOptionalOutput(outputPath)).value;
5041
- await (0, import_promises4.rm)(outputPath, { force: true });
5041
+ await (0, import_promises5.rm)(outputPath, { force: true });
5042
5042
  return {
5043
5043
  ...result,
5044
5044
  finalMessage,
@@ -5104,7 +5104,7 @@ function extractCodexFailureMessage(event2) {
5104
5104
  return {};
5105
5105
  }
5106
5106
  function createOutputPath(runtimeDirectory) {
5107
- return (0, import_node_path3.join)(runtimeDirectory, `codex-last-message-${(0, import_node_crypto2.randomUUID)()}.txt`);
5107
+ return (0, import_node_path4.join)(runtimeDirectory, `codex-last-message-${(0, import_node_crypto2.randomUUID)()}.txt`);
5108
5108
  }
5109
5109
  function parseCodexEvent(line) {
5110
5110
  const trimmed = line.trim();
@@ -5138,9 +5138,9 @@ function extractThreadId(event2) {
5138
5138
  }
5139
5139
  async function readOptionalOutput(path4) {
5140
5140
  try {
5141
- return { value: (await (0, import_promises4.readFile)(path4, "utf8")).trim() };
5141
+ return { value: (await (0, import_promises5.readFile)(path4, "utf8")).trim() };
5142
5142
  } catch (error) {
5143
- if (isNodeErrorCode(error, "ENOENT")) {
5143
+ if (isNodeErrorCode2(error, "ENOENT")) {
5144
5144
  return {};
5145
5145
  }
5146
5146
  throw error;
@@ -5149,7 +5149,7 @@ async function readOptionalOutput(path4) {
5149
5149
  function isRecord2(value) {
5150
5150
  return typeof value === "object" && value !== null && !Array.isArray(value);
5151
5151
  }
5152
- function isNodeErrorCode(error, expectedCode) {
5152
+ function isNodeErrorCode2(error, expectedCode) {
5153
5153
  if (!(error instanceof Error) || !("code" in error)) {
5154
5154
  return false;
5155
5155
  }
@@ -5160,13 +5160,13 @@ function delay2(milliseconds) {
5160
5160
  setTimeout(resolvePromise, milliseconds);
5161
5161
  });
5162
5162
  }
5163
- var import_promises4, import_node_path3, import_node_crypto2, codexProcessExitGraceMilliseconds;
5163
+ var import_promises5, import_node_path4, import_node_crypto2, codexProcessExitGraceMilliseconds;
5164
5164
  var init_codex_executor = __esm({
5165
5165
  "../machine-connector/dist/runtime/codex-executor.js"() {
5166
5166
  "use strict";
5167
5167
  init_cjs_shims();
5168
- import_promises4 = require("fs/promises");
5169
- import_node_path3 = require("path");
5168
+ import_promises5 = require("fs/promises");
5169
+ import_node_path4 = require("path");
5170
5170
  import_node_crypto2 = require("crypto");
5171
5171
  init_enums();
5172
5172
  init_process_executor();
@@ -5422,14 +5422,14 @@ async function requestLocalIpc(store, action, timeoutMilliseconds) {
5422
5422
  });
5423
5423
  });
5424
5424
  }
5425
- var import_promises5, import_node_net, import_node_os2, LocalIpcServer;
5425
+ var import_promises6, import_node_net, import_node_os3, LocalIpcServer;
5426
5426
  var init_local_ipc = __esm({
5427
5427
  "../machine-connector/dist/runtime/local-ipc.js"() {
5428
5428
  "use strict";
5429
5429
  init_cjs_shims();
5430
- import_promises5 = require("fs/promises");
5430
+ import_promises6 = require("fs/promises");
5431
5431
  import_node_net = require("net");
5432
- import_node_os2 = require("os");
5432
+ import_node_os3 = require("os");
5433
5433
  LocalIpcServer = class {
5434
5434
  store;
5435
5435
  getStatus;
@@ -5442,8 +5442,8 @@ var init_local_ipc = __esm({
5442
5442
  }
5443
5443
  async start() {
5444
5444
  const socketPath = this.store.runtimeSocketPath();
5445
- if ((0, import_node_os2.platform)() !== "win32") {
5446
- await (0, import_promises5.rm)(socketPath, { force: true });
5445
+ if ((0, import_node_os3.platform)() !== "win32") {
5446
+ await (0, import_promises6.rm)(socketPath, { force: true });
5447
5447
  }
5448
5448
  this.server = (0, import_node_net.createServer)((socket) => {
5449
5449
  let requestText = "";
@@ -5465,8 +5465,8 @@ var init_local_ipc = __esm({
5465
5465
  this.server?.once("error", rejectPromise);
5466
5466
  this.server?.listen(socketPath, resolvePromise);
5467
5467
  });
5468
- if ((0, import_node_os2.platform)() !== "win32") {
5469
- await (0, import_promises5.chmod)(socketPath, 384);
5468
+ if ((0, import_node_os3.platform)() !== "win32") {
5469
+ await (0, import_promises6.chmod)(socketPath, 384);
5470
5470
  }
5471
5471
  }
5472
5472
  async close() {
@@ -5476,8 +5476,8 @@ var init_local_ipc = __esm({
5476
5476
  await new Promise((resolvePromise) => {
5477
5477
  this.server?.close(() => resolvePromise());
5478
5478
  });
5479
- if ((0, import_node_os2.platform)() !== "win32") {
5480
- await (0, import_promises5.rm)(this.store.runtimeSocketPath(), { force: true });
5479
+ if ((0, import_node_os3.platform)() !== "win32") {
5480
+ await (0, import_promises6.rm)(this.store.runtimeSocketPath(), { force: true });
5481
5481
  }
5482
5482
  }
5483
5483
  async handleRequest(requestText) {
@@ -5513,7 +5513,7 @@ function createLocalMachineJobExecutionContext(connectorInstanceId, runtimeDirec
5513
5513
  return {
5514
5514
  connectorInstanceId,
5515
5515
  kind: "local_machine_job",
5516
- runtimeDirectory: (0, import_node_path4.resolve)(runtimeDirectory)
5516
+ runtimeDirectory: (0, import_node_path5.resolve)(runtimeDirectory)
5517
5517
  };
5518
5518
  }
5519
5519
  function serializeLocalMachineJobExecutionContext(context) {
@@ -5524,7 +5524,7 @@ function parseLocalMachineJobExecutionContext(value) {
5524
5524
  return void 0;
5525
5525
  try {
5526
5526
  const decoded = JSON.parse(Buffer.from(value.slice(localMachineJobPrefix.length), "base64url").toString("utf8"));
5527
- if (decoded.kind !== "local_machine_job" || typeof decoded.connectorInstanceId !== "string" || decoded.connectorInstanceId.length === 0 || typeof decoded.runtimeDirectory !== "string" || decoded.runtimeDirectory.length === 0 || (0, import_node_path4.resolve)(decoded.runtimeDirectory) !== decoded.runtimeDirectory) {
5527
+ if (decoded.kind !== "local_machine_job" || typeof decoded.connectorInstanceId !== "string" || decoded.connectorInstanceId.length === 0 || typeof decoded.runtimeDirectory !== "string" || decoded.runtimeDirectory.length === 0 || (0, import_node_path5.resolve)(decoded.runtimeDirectory) !== decoded.runtimeDirectory) {
5528
5528
  return void 0;
5529
5529
  }
5530
5530
  return decoded;
@@ -5536,8 +5536,8 @@ async function localMachineJobTargetRelationship(store, value = process.env[mach
5536
5536
  const context = parseLocalMachineJobExecutionContext(value);
5537
5537
  if (!context)
5538
5538
  return void 0;
5539
- const targetRuntimeDirectory = (0, import_node_path4.resolve)(store.baseDirectory);
5540
- const carryingRuntimeDirectory = (0, import_node_path4.resolve)(context.runtimeDirectory);
5539
+ const targetRuntimeDirectory = (0, import_node_path5.resolve)(store.baseDirectory);
5540
+ const carryingRuntimeDirectory = (0, import_node_path5.resolve)(context.runtimeDirectory);
5541
5541
  if (targetRuntimeDirectory !== carryingRuntimeDirectory) {
5542
5542
  try {
5543
5543
  const [canonicalTarget, canonicalCarrying] = await Promise.all([
@@ -5562,24 +5562,24 @@ async function localMachineJobTargetRelationship(store, value = process.env[mach
5562
5562
  }
5563
5563
  async function canonicalizePotentialRuntimeDirectory(path4) {
5564
5564
  try {
5565
- return await (0, import_promises6.realpath)(path4);
5565
+ return await (0, import_promises7.realpath)(path4);
5566
5566
  } catch (error) {
5567
5567
  if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") {
5568
5568
  throw error;
5569
5569
  }
5570
- const parent = (0, import_node_path4.dirname)(path4);
5570
+ const parent = (0, import_node_path5.dirname)(path4);
5571
5571
  if (parent === path4)
5572
5572
  return path4;
5573
- return (0, import_node_path4.join)(await canonicalizePotentialRuntimeDirectory(parent), (0, import_node_path4.basename)(path4));
5573
+ return (0, import_node_path5.join)(await canonicalizePotentialRuntimeDirectory(parent), (0, import_node_path5.basename)(path4));
5574
5574
  }
5575
5575
  }
5576
- var import_promises6, import_node_path4, machineExecutionContextEnvironmentName, localMachineJobPrefix;
5576
+ var import_promises7, import_node_path5, machineExecutionContextEnvironmentName, localMachineJobPrefix;
5577
5577
  var init_execution_context = __esm({
5578
5578
  "../machine-connector/dist/runtime/execution-context.js"() {
5579
5579
  "use strict";
5580
5580
  init_cjs_shims();
5581
- import_promises6 = require("fs/promises");
5582
- import_node_path4 = require("path");
5581
+ import_promises7 = require("fs/promises");
5582
+ import_node_path5 = require("path");
5583
5583
  init_local_ipc();
5584
5584
  machineExecutionContextEnvironmentName = "MOXT_MACHINE_EXECUTION_CONTEXT";
5585
5585
  localMachineJobPrefix = "local_machine_job:v1:";
@@ -5612,41 +5612,41 @@ async function viewLocalMachineImage(rootPath, relativeImagePath) {
5612
5612
  }
5613
5613
  async function resolvePairedRoot(rootPath) {
5614
5614
  try {
5615
- return await (0, import_promises7.realpath)(rootPath);
5615
+ return await (0, import_promises8.realpath)(rootPath);
5616
5616
  } catch {
5617
5617
  throw new Error("Paired Local Machine root is unavailable");
5618
5618
  }
5619
5619
  }
5620
5620
  async function resolveImagePath(canonicalRoot, relativeImagePath) {
5621
5621
  try {
5622
- return await (0, import_promises7.realpath)((0, import_node_path5.resolve)(canonicalRoot, relativeImagePath));
5622
+ return await (0, import_promises8.realpath)((0, import_node_path6.resolve)(canonicalRoot, relativeImagePath));
5623
5623
  } catch {
5624
5624
  throw new Error(`Image could not be read: ${relativeImagePath}`);
5625
5625
  }
5626
5626
  }
5627
5627
  async function statImage(canonicalImage, relativeImagePath) {
5628
5628
  try {
5629
- return await (0, import_promises7.stat)(canonicalImage);
5629
+ return await (0, import_promises8.stat)(canonicalImage);
5630
5630
  } catch {
5631
5631
  throw new Error(`Image could not be read: ${relativeImagePath}`);
5632
5632
  }
5633
5633
  }
5634
5634
  async function readImageBytes(canonicalImage, relativeImagePath) {
5635
5635
  try {
5636
- return await (0, import_promises7.readFile)(canonicalImage);
5636
+ return await (0, import_promises8.readFile)(canonicalImage);
5637
5637
  } catch {
5638
5638
  throw new Error(`Image could not be read: ${relativeImagePath}`);
5639
5639
  }
5640
5640
  }
5641
5641
  function validateRelativeImagePath(path4) {
5642
5642
  const segments = path4.split(/[\\/]/);
5643
- if (path4.length === 0 || path4.length > 4096 || path4.includes("\0") || (0, import_node_path5.isAbsolute)(path4) || import_node_path5.win32.isAbsolute(path4) || segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
5643
+ if (path4.length === 0 || path4.length > 4096 || path4.includes("\0") || (0, import_node_path6.isAbsolute)(path4) || import_node_path6.win32.isAbsolute(path4) || segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
5644
5644
  throw new Error(`Invalid relative image path: ${path4}`);
5645
5645
  }
5646
5646
  }
5647
5647
  function requireInsideRoot(canonicalRoot, canonicalImage) {
5648
- const relativePath = (0, import_node_path5.relative)(canonicalRoot, canonicalImage);
5649
- if (relativePath === ".." || relativePath.startsWith(`..${import_node_path5.sep}`) || (0, import_node_path5.isAbsolute)(relativePath)) {
5648
+ const relativePath = (0, import_node_path6.relative)(canonicalRoot, canonicalImage);
5649
+ if (relativePath === ".." || relativePath.startsWith(`..${import_node_path6.sep}`) || (0, import_node_path6.isAbsolute)(relativePath)) {
5650
5650
  throw new Error("Image path escapes paired root");
5651
5651
  }
5652
5652
  }
@@ -5846,32 +5846,32 @@ function startsWithAscii(bytes, offset, text3) {
5846
5846
  }
5847
5847
  return true;
5848
5848
  }
5849
- var import_promises7, import_node_path5, maximumLocalMachineImageBytes;
5849
+ var import_promises8, import_node_path6, maximumLocalMachineImageBytes;
5850
5850
  var init_image_viewer = __esm({
5851
5851
  "../machine-connector/dist/runtime/image-viewer.js"() {
5852
5852
  "use strict";
5853
5853
  init_cjs_shims();
5854
- import_promises7 = require("fs/promises");
5855
- import_node_path5 = require("path");
5854
+ import_promises8 = require("fs/promises");
5855
+ import_node_path6 = require("path");
5856
5856
  maximumLocalMachineImageBytes = 1e7;
5857
5857
  }
5858
5858
  });
5859
5859
 
5860
5860
  // ../machine-connector/dist/runtime/process-lock.js
5861
5861
  async function createCompleteLock(path4, record2) {
5862
- await (0, import_promises8.mkdir)(path4, { mode: 448 });
5862
+ await (0, import_promises9.mkdir)(path4, { mode: 448 });
5863
5863
  let metadata;
5864
5864
  try {
5865
- metadata = await (0, import_promises8.stat)(path4);
5865
+ metadata = await (0, import_promises9.stat)(path4);
5866
5866
  } catch (error) {
5867
- if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5867
+ if (isNodeErrorCode3(error, "ENOENT") || isNodeErrorCode3(error, "ENOTDIR")) {
5868
5868
  throw nodeError("EEXIST", "Lock directory changed while publishing");
5869
5869
  }
5870
5870
  throw error;
5871
5871
  }
5872
- const ownerPath = (0, import_node_path6.join)(path4, `${metadata.dev}.${metadata.ino}.${record2.pid}.${record2.token}.owner`);
5872
+ const ownerPath = (0, import_node_path7.join)(path4, `${metadata.dev}.${metadata.ino}.${record2.pid}.${record2.token}.owner`);
5873
5873
  try {
5874
- await (0, import_promises8.writeFile)(ownerPath, `${JSON.stringify(record2)}
5874
+ await (0, import_promises9.writeFile)(ownerPath, `${JSON.stringify(record2)}
5875
5875
  `, {
5876
5876
  encoding: "utf8",
5877
5877
  flag: "wx",
@@ -5879,9 +5879,9 @@ async function createCompleteLock(path4, record2) {
5879
5879
  });
5880
5880
  let current2;
5881
5881
  try {
5882
- current2 = await (0, import_promises8.stat)(path4);
5882
+ current2 = await (0, import_promises9.stat)(path4);
5883
5883
  } catch (error) {
5884
- if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5884
+ if (isNodeErrorCode3(error, "ENOENT") || isNodeErrorCode3(error, "ENOTDIR")) {
5885
5885
  throw nodeError("EEXIST", "Lock directory changed while publishing");
5886
5886
  }
5887
5887
  throw error;
@@ -5893,7 +5893,7 @@ async function createCompleteLock(path4, record2) {
5893
5893
  } catch (error) {
5894
5894
  await removeFileIfPresent(ownerPath);
5895
5895
  await removeEmptyDirectory(path4);
5896
- if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5896
+ if (isNodeErrorCode3(error, "ENOENT") || isNodeErrorCode3(error, "ENOTDIR")) {
5897
5897
  throw nodeError("EEXIST", "Lock directory changed while publishing");
5898
5898
  }
5899
5899
  throw error;
@@ -5902,9 +5902,9 @@ async function createCompleteLock(path4, record2) {
5902
5902
  async function readLockState(path4) {
5903
5903
  let metadata;
5904
5904
  try {
5905
- metadata = await (0, import_promises8.stat)(path4);
5905
+ metadata = await (0, import_promises9.stat)(path4);
5906
5906
  } catch (error) {
5907
- if (isNodeErrorCode2(error, "ENOENT"))
5907
+ if (isNodeErrorCode3(error, "ENOENT"))
5908
5908
  return void 0;
5909
5909
  throw error;
5910
5910
  }
@@ -5917,9 +5917,9 @@ async function readLockState(path4) {
5917
5917
  const ownerPrefix = `${metadata.dev}.${metadata.ino}.`;
5918
5918
  let names;
5919
5919
  try {
5920
- names = await (0, import_promises8.readdir)(path4);
5920
+ names = await (0, import_promises9.readdir)(path4);
5921
5921
  } catch (error) {
5922
- if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5922
+ if (isNodeErrorCode3(error, "ENOENT") || isNodeErrorCode3(error, "ENOTDIR")) {
5923
5923
  return void 0;
5924
5924
  }
5925
5925
  throw error;
@@ -5927,7 +5927,7 @@ async function readLockState(path4) {
5927
5927
  const ownerName = names.find((name) => name.startsWith(ownerPrefix) && name.endsWith(".owner"));
5928
5928
  if (!ownerName)
5929
5929
  return { metadata };
5930
- const ownerPath = (0, import_node_path6.join)(path4, ownerName);
5930
+ const ownerPath = (0, import_node_path7.join)(path4, ownerName);
5931
5931
  return {
5932
5932
  metadata,
5933
5933
  ownerPath,
@@ -5936,13 +5936,13 @@ async function readLockState(path4) {
5936
5936
  }
5937
5937
  async function readRecord(path4) {
5938
5938
  try {
5939
- const parsed = JSON.parse(await (0, import_promises8.readFile)(path4, "utf8"));
5939
+ const parsed = JSON.parse(await (0, import_promises9.readFile)(path4, "utf8"));
5940
5940
  if (typeof parsed.createdAt !== "number" || !Number.isFinite(parsed.createdAt) || typeof parsed.pid !== "number" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0 || typeof parsed.token !== "string" || parsed.token.length === 0) {
5941
5941
  return void 0;
5942
5942
  }
5943
5943
  return parsed;
5944
5944
  } catch (error) {
5945
- if (isNodeErrorCode2(error, "ENOENT"))
5945
+ if (isNodeErrorCode3(error, "ENOENT"))
5946
5946
  return void 0;
5947
5947
  if (error instanceof SyntaxError)
5948
5948
  return void 0;
@@ -5958,9 +5958,9 @@ async function removeLockIfTokenMatches(path4, token) {
5958
5958
  return;
5959
5959
  }
5960
5960
  try {
5961
- await (0, import_promises8.rm)(path4);
5961
+ await (0, import_promises9.rm)(path4);
5962
5962
  } catch (error) {
5963
- if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "EISDIR") || isNodeErrorCode2(error, "ERR_FS_EISDIR") || isNodeErrorCode2(error, "EPERM")) {
5963
+ if (isNodeErrorCode3(error, "ENOENT") || isNodeErrorCode3(error, "EISDIR") || isNodeErrorCode3(error, "ERR_FS_EISDIR") || isNodeErrorCode3(error, "EPERM")) {
5964
5964
  return;
5965
5965
  }
5966
5966
  throw error;
@@ -5982,10 +5982,10 @@ async function removeStaleIncompleteLock(path4, metadata) {
5982
5982
  }
5983
5983
  if (!metadata.isDirectory()) {
5984
5984
  try {
5985
- await (0, import_promises8.rm)(path4);
5985
+ await (0, import_promises9.rm)(path4);
5986
5986
  return true;
5987
5987
  } catch (error) {
5988
- if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "EISDIR") || isNodeErrorCode2(error, "ERR_FS_EISDIR") || isNodeErrorCode2(error, "EPERM")) {
5988
+ if (isNodeErrorCode3(error, "ENOENT") || isNodeErrorCode3(error, "EISDIR") || isNodeErrorCode3(error, "ERR_FS_EISDIR") || isNodeErrorCode3(error, "EPERM")) {
5989
5989
  return false;
5990
5990
  }
5991
5991
  throw error;
@@ -5994,9 +5994,9 @@ async function removeStaleIncompleteLock(path4, metadata) {
5994
5994
  const ownerPrefix = `${metadata.dev}.${metadata.ino}.`;
5995
5995
  let names;
5996
5996
  try {
5997
- names = await (0, import_promises8.readdir)(path4);
5997
+ names = await (0, import_promises9.readdir)(path4);
5998
5998
  } catch (error) {
5999
- if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5999
+ if (isNodeErrorCode3(error, "ENOENT") || isNodeErrorCode3(error, "ENOTDIR")) {
6000
6000
  return false;
6001
6001
  }
6002
6002
  throw error;
@@ -6011,7 +6011,7 @@ async function removeStaleIncompleteLock(path4, metadata) {
6011
6011
  deadOwnerNames.push(name);
6012
6012
  }
6013
6013
  for (const name of deadOwnerNames) {
6014
- await removeFileIfPresent((0, import_node_path6.join)(path4, name));
6014
+ await removeFileIfPresent((0, import_node_path7.join)(path4, name));
6015
6015
  }
6016
6016
  return await removeEmptyDirectory(path4);
6017
6017
  }
@@ -6028,20 +6028,20 @@ function directoryOwnerProcessId(ownerPrefix, ownerName) {
6028
6028
  return processId;
6029
6029
  }
6030
6030
  async function removeStalePendingLockCandidates(path4) {
6031
- const directory = (0, import_node_path6.dirname)(path4);
6032
- const lockName = (0, import_node_path6.basename)(path4);
6031
+ const directory = (0, import_node_path7.dirname)(path4);
6032
+ const lockName = (0, import_node_path7.basename)(path4);
6033
6033
  let names;
6034
6034
  try {
6035
- names = await (0, import_promises8.readdir)(directory);
6035
+ names = await (0, import_promises9.readdir)(directory);
6036
6036
  } catch (error) {
6037
- if (isNodeErrorCode2(error, "ENOENT"))
6037
+ if (isNodeErrorCode3(error, "ENOENT"))
6038
6038
  return;
6039
6039
  throw error;
6040
6040
  }
6041
6041
  for (const name of names) {
6042
6042
  if (!isPendingLockCandidateName(lockName, name))
6043
6043
  continue;
6044
- await removeOldUnchangedFile((0, import_node_path6.join)(directory, name));
6044
+ await removeOldUnchangedFile((0, import_node_path7.join)(directory, name));
6045
6045
  }
6046
6046
  }
6047
6047
  function isPendingLockCandidateName(lockName, name) {
@@ -6061,30 +6061,30 @@ function isPendingLockCandidateName(lockName, name) {
6061
6061
  async function removeOldUnchangedFile(path4) {
6062
6062
  let metadata;
6063
6063
  try {
6064
- metadata = await (0, import_promises8.stat)(path4);
6064
+ metadata = await (0, import_promises9.stat)(path4);
6065
6065
  } catch (error) {
6066
- return isNodeErrorCode2(error, "ENOENT");
6066
+ return isNodeErrorCode3(error, "ENOENT");
6067
6067
  }
6068
6068
  if (Date.now() - Number(metadata.mtimeMs) < incompleteLockStaleMilliseconds) {
6069
6069
  return false;
6070
6070
  }
6071
6071
  let current2;
6072
6072
  try {
6073
- current2 = await (0, import_promises8.stat)(path4);
6073
+ current2 = await (0, import_promises9.stat)(path4);
6074
6074
  } catch (error) {
6075
- return isNodeErrorCode2(error, "ENOENT");
6075
+ return isNodeErrorCode3(error, "ENOENT");
6076
6076
  }
6077
6077
  if (!sameFileMetadata(metadata, current2))
6078
6078
  return false;
6079
- await (0, import_promises8.rm)(path4, { force: true });
6079
+ await (0, import_promises9.rm)(path4, { force: true });
6080
6080
  return true;
6081
6081
  }
6082
6082
  async function removeEmptyDirectory(path4) {
6083
6083
  try {
6084
- await (0, import_promises8.rmdir)(path4);
6084
+ await (0, import_promises9.rmdir)(path4);
6085
6085
  return true;
6086
6086
  } catch (error) {
6087
- if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTEMPTY") || isNodeErrorCode2(error, "EEXIST") || isNodeErrorCode2(error, "ENOTDIR")) {
6087
+ if (isNodeErrorCode3(error, "ENOENT") || isNodeErrorCode3(error, "ENOTEMPTY") || isNodeErrorCode3(error, "EEXIST") || isNodeErrorCode3(error, "ENOTDIR")) {
6088
6088
  return false;
6089
6089
  }
6090
6090
  throw error;
@@ -6092,9 +6092,9 @@ async function removeEmptyDirectory(path4) {
6092
6092
  }
6093
6093
  async function removeFileIfPresent(path4) {
6094
6094
  try {
6095
- await (0, import_promises8.rm)(path4, { force: true });
6095
+ await (0, import_promises9.rm)(path4, { force: true });
6096
6096
  } catch (error) {
6097
- if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
6097
+ if (isNodeErrorCode3(error, "ENOENT") || isNodeErrorCode3(error, "ENOTDIR")) {
6098
6098
  return;
6099
6099
  }
6100
6100
  throw error;
@@ -6111,10 +6111,10 @@ function processIsAlive(pid) {
6111
6111
  process.kill(pid, 0);
6112
6112
  return true;
6113
6113
  } catch (error) {
6114
- return !isNodeErrorCode2(error, "ESRCH");
6114
+ return !isNodeErrorCode3(error, "ESRCH");
6115
6115
  }
6116
6116
  }
6117
- function isNodeErrorCode2(error, expectedCode) {
6117
+ function isNodeErrorCode3(error, expectedCode) {
6118
6118
  return error instanceof Error && "code" in error && error.code === expectedCode;
6119
6119
  }
6120
6120
  function nodeError(code, message) {
@@ -6123,14 +6123,14 @@ function nodeError(code, message) {
6123
6123
  function delay3(milliseconds) {
6124
6124
  return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
6125
6125
  }
6126
- var import_node_crypto4, import_promises8, import_node_path6, incompleteLockStaleMilliseconds, ProcessLock;
6126
+ var import_node_crypto4, import_promises9, import_node_path7, incompleteLockStaleMilliseconds, ProcessLock;
6127
6127
  var init_process_lock = __esm({
6128
6128
  "../machine-connector/dist/runtime/process-lock.js"() {
6129
6129
  "use strict";
6130
6130
  init_cjs_shims();
6131
6131
  import_node_crypto4 = require("crypto");
6132
- import_promises8 = require("fs/promises");
6133
- import_node_path6 = require("path");
6132
+ import_promises9 = require("fs/promises");
6133
+ import_node_path7 = require("path");
6134
6134
  incompleteLockStaleMilliseconds = 3e4;
6135
6135
  ProcessLock = class _ProcessLock {
6136
6136
  path;
@@ -6155,7 +6155,7 @@ var init_process_lock = __esm({
6155
6155
  });
6156
6156
  return new _ProcessLock(path4, ownerPath, token);
6157
6157
  } catch (error) {
6158
- if (!isNodeErrorCode2(error, "EEXIST"))
6158
+ if (!isNodeErrorCode3(error, "EEXIST"))
6159
6159
  throw error;
6160
6160
  }
6161
6161
  const existing = await readLockState(path4);
@@ -6270,30 +6270,30 @@ function isConnectorCredentialName(name) {
6270
6270
  return name.startsWith("MOXT_MACHINE_") && /(?:^|_)(?:TOKEN|SECRET|CREDENTIALS?|PASSWORD|PRIVATE_KEY)(?:_|$)/.test(name.slice("MOXT_MACHINE_".length));
6271
6271
  }
6272
6272
  async function validateShell(shellPath) {
6273
- if (!(0, import_node_path7.isAbsolute)(shellPath))
6273
+ if (!(0, import_node_path8.isAbsolute)(shellPath))
6274
6274
  throw new Error("default shell is not absolute");
6275
6275
  const canonicalPath = await validateExecutable(shellPath);
6276
- const shellName = (0, import_node_path7.basename)(canonicalPath);
6276
+ const shellName = (0, import_node_path8.basename)(canonicalPath);
6277
6277
  if (shellName !== "bash" && shellName !== "zsh") {
6278
6278
  throw new Error("default shell is not Bash or Zsh");
6279
6279
  }
6280
6280
  return canonicalPath;
6281
6281
  }
6282
6282
  async function validateExecutable(path4) {
6283
- const canonicalPath = await (0, import_promises9.realpath)(path4);
6284
- const metadata = await (0, import_promises9.stat)(canonicalPath);
6283
+ const canonicalPath = await (0, import_promises10.realpath)(path4);
6284
+ const metadata = await (0, import_promises10.stat)(canonicalPath);
6285
6285
  if (!metadata.isFile())
6286
6286
  throw new Error("executable is not a regular file");
6287
- await (0, import_promises9.access)(canonicalPath, import_promises9.constants.X_OK);
6287
+ await (0, import_promises10.access)(canonicalPath, import_promises10.constants.X_OK);
6288
6288
  return canonicalPath;
6289
6289
  }
6290
6290
  async function findExecutable(name, pathValue) {
6291
- for (const directory of (pathValue ?? "").split(import_node_path7.delimiter)) {
6292
- if (!(0, import_node_path7.isAbsolute)(directory))
6291
+ for (const directory of (pathValue ?? "").split(import_node_path8.delimiter)) {
6292
+ if (!(0, import_node_path8.isAbsolute)(directory))
6293
6293
  continue;
6294
6294
  try {
6295
- const candidate = await validateExecutable((0, import_node_path7.join)(directory, name));
6296
- if ((0, import_node_path7.basename)(candidate) === name)
6295
+ const candidate = await validateExecutable((0, import_node_path8.join)(directory, name));
6296
+ if ((0, import_node_path8.basename)(candidate) === name)
6297
6297
  return candidate;
6298
6298
  } catch {
6299
6299
  }
@@ -6303,9 +6303,9 @@ async function findExecutable(name, pathValue) {
6303
6303
  async function findNearestEnvrc(canonicalRoot, canonicalWorkingDirectory) {
6304
6304
  let directory = canonicalWorkingDirectory;
6305
6305
  while (true) {
6306
- const candidate = (0, import_node_path7.join)(directory, ".envrc");
6306
+ const candidate = (0, import_node_path8.join)(directory, ".envrc");
6307
6307
  try {
6308
- const metadata = await (0, import_promises9.stat)(candidate);
6308
+ const metadata = await (0, import_promises10.stat)(candidate);
6309
6309
  if (!metadata.isFile()) {
6310
6310
  throw new JobEnvironmentError("direnv_malformed");
6311
6311
  }
@@ -6316,7 +6316,7 @@ async function findNearestEnvrc(canonicalRoot, canonicalWorkingDirectory) {
6316
6316
  }
6317
6317
  if (directory === canonicalRoot)
6318
6318
  return void 0;
6319
- const parent = (0, import_node_path7.dirname)(directory);
6319
+ const parent = (0, import_node_path8.dirname)(directory);
6320
6320
  if (parent === directory)
6321
6321
  return void 0;
6322
6322
  directory = parent;
@@ -6334,7 +6334,7 @@ async function executeBounded(options) {
6334
6334
  return await new Promise((resolvePromise) => {
6335
6335
  const child = (0, import_node_child_process2.spawn)(options.executable, options.argumentsList, {
6336
6336
  cwd: options.cwd,
6337
- detached: (0, import_node_os3.platform)() !== "win32",
6337
+ detached: (0, import_node_os4.platform)() !== "win32",
6338
6338
  env: options.environment,
6339
6339
  shell: false,
6340
6340
  stdio: ["ignore", "pipe", "pipe"],
@@ -6406,7 +6406,7 @@ function terminateBoundedProcess(pid) {
6406
6406
  if (pid === void 0)
6407
6407
  return;
6408
6408
  try {
6409
- process.kill((0, import_node_os3.platform)() === "win32" ? pid : -pid, "SIGKILL");
6409
+ process.kill((0, import_node_os4.platform)() === "win32" ? pid : -pid, "SIGKILL");
6410
6410
  } catch (error) {
6411
6411
  if (isNodeError(error, "ESRCH"))
6412
6412
  return;
@@ -6464,15 +6464,15 @@ function degradedCapture(category) {
6464
6464
  function isNodeError(error, code) {
6465
6465
  return error instanceof Error && "code" in error && error.code === code;
6466
6466
  }
6467
- var import_node_child_process2, import_promises9, import_node_os3, import_node_path7, defaultCaptureTimeoutMilliseconds, defaultCaptureOutputLimitBytes, defaultDirenvTimeoutMilliseconds, defaultDirenvOutputLimitBytes, shellCaptureScript, environmentNamePattern, direnvSessionStateNames, JobEnvironmentError, JobEnvironmentCancelledError, ShellEnvironmentManager;
6467
+ var import_node_child_process2, import_promises10, import_node_os4, import_node_path8, defaultCaptureTimeoutMilliseconds, defaultCaptureOutputLimitBytes, defaultDirenvTimeoutMilliseconds, defaultDirenvOutputLimitBytes, shellCaptureScript, environmentNamePattern, direnvSessionStateNames, JobEnvironmentError, JobEnvironmentCancelledError, ShellEnvironmentManager;
6468
6468
  var init_shell_environment = __esm({
6469
6469
  "../machine-connector/dist/runtime/shell-environment.js"() {
6470
6470
  "use strict";
6471
6471
  init_cjs_shims();
6472
6472
  import_node_child_process2 = require("child_process");
6473
- import_promises9 = require("fs/promises");
6474
- import_node_os3 = require("os");
6475
- import_node_path7 = require("path");
6473
+ import_promises10 = require("fs/promises");
6474
+ import_node_os4 = require("os");
6475
+ import_node_path8 = require("path");
6476
6476
  init_execution_context();
6477
6477
  defaultCaptureTimeoutMilliseconds = 5e3;
6478
6478
  defaultCaptureOutputLimitBytes = 1048576;
@@ -6514,7 +6514,7 @@ var init_shell_environment = __esm({
6514
6514
  this.captureOutputLimitBytes = options.captureOutputLimitBytes ?? defaultCaptureOutputLimitBytes;
6515
6515
  this.captureTimeoutMilliseconds = options.captureTimeoutMilliseconds ?? defaultCaptureTimeoutMilliseconds;
6516
6516
  this.daemonEnvironment = freezeEnvironment(sanitizeEnvironment(options.daemonEnvironment ?? process.env));
6517
- this.defaultShell = options.defaultShell ?? (0, import_node_os3.userInfo)().shell ?? "";
6517
+ this.defaultShell = options.defaultShell ?? (0, import_node_os4.userInfo)().shell ?? "";
6518
6518
  this.direnvOutputLimitBytes = options.direnvOutputLimitBytes ?? defaultDirenvOutputLimitBytes;
6519
6519
  this.direnvTimeoutMilliseconds = options.direnvTimeoutMilliseconds ?? defaultDirenvTimeoutMilliseconds;
6520
6520
  this.currentEnvironment = this.daemonEnvironment;
@@ -6545,8 +6545,8 @@ var init_shell_environment = __esm({
6545
6545
  throw new JobEnvironmentError("reserved_environment");
6546
6546
  }
6547
6547
  const executionContextValue = serializeLocalMachineJobExecutionContext(options.executionContext);
6548
- const relativeWorkingDirectory = (0, import_node_path7.relative)(canonicalRoot, canonicalWorkingDirectory);
6549
- if (relativeWorkingDirectory === ".." || relativeWorkingDirectory.startsWith(`..${import_node_path7.sep}`) || (0, import_node_path7.isAbsolute)(relativeWorkingDirectory)) {
6548
+ const relativeWorkingDirectory = (0, import_node_path8.relative)(canonicalRoot, canonicalWorkingDirectory);
6549
+ if (relativeWorkingDirectory === ".." || relativeWorkingDirectory.startsWith(`..${import_node_path8.sep}`) || (0, import_node_path8.isAbsolute)(relativeWorkingDirectory)) {
6550
6550
  throw new JobEnvironmentError("direnv_malformed");
6551
6551
  }
6552
6552
  const baseSnapshot = this.currentEnvironment;
@@ -6686,7 +6686,7 @@ var init_version = __esm({
6686
6686
  });
6687
6687
 
6688
6688
  // ../machine-connector/dist/runtime/local-codex-runtime/contracts.js
6689
- var localCodexRuntimeProtocolVersion, localCodexRuntimeEventSchemaVersion, localCodexRuntimeEventRedactionVersion, LocalCodexComponentStatusWire, LocalCodexTurnStatusWire, LocalCodexControlKindWire, LocalCodexControlOutcomeWire, LocalCodexDiscoveryKindWire, LocalCodexDiscoveryStatusWire, LocalCodexAttemptPhase, LocalCodexControlApplyPhase;
6689
+ var localCodexRuntimeProtocolVersion, localCodexRuntimeEventSchemaVersion, localCodexRuntimeEventRedactionVersion, LocalCodexComponentStatusWire, LocalCodexUnavailableReasonWire, LocalCodexTurnStatusWire, LocalCodexControlKindWire, LocalCodexControlOutcomeWire, LocalCodexDiscoveryKindWire, LocalCodexDiscoveryStatusWire, LocalCodexAttemptPhase, LocalCodexControlApplyPhase;
6690
6690
  var init_contracts2 = __esm({
6691
6691
  "../machine-connector/dist/runtime/local-codex-runtime/contracts.js"() {
6692
6692
  "use strict";
@@ -6702,6 +6702,10 @@ var init_contracts2 = __esm({
6702
6702
  LocalCodexComponentStatusWire2["Ready"] = "ready";
6703
6703
  LocalCodexComponentStatusWire2["Unknown"] = "unknown";
6704
6704
  })(LocalCodexComponentStatusWire || (LocalCodexComponentStatusWire = {}));
6705
+ (function(LocalCodexUnavailableReasonWire2) {
6706
+ LocalCodexUnavailableReasonWire2["AppServerStartupFailed"] = "app_server_startup_failed";
6707
+ LocalCodexUnavailableReasonWire2["CodexVersionUnsupported"] = "codex_version_unsupported";
6708
+ })(LocalCodexUnavailableReasonWire || (LocalCodexUnavailableReasonWire = {}));
6705
6709
  (function(LocalCodexTurnStatusWire2) {
6706
6710
  LocalCodexTurnStatusWire2["Cancelled"] = "cancelled";
6707
6711
  LocalCodexTurnStatusWire2["Failed"] = "failed";
@@ -7006,12 +7010,12 @@ var init_relay_client = __esm({
7006
7010
  });
7007
7011
 
7008
7012
  // ../machine-connector/dist/runtime/runtime-logger.js
7009
- var import_promises10, RuntimeLogger;
7013
+ var import_promises11, RuntimeLogger;
7010
7014
  var init_runtime_logger = __esm({
7011
7015
  "../machine-connector/dist/runtime/runtime-logger.js"() {
7012
7016
  "use strict";
7013
7017
  init_cjs_shims();
7014
- import_promises10 = require("fs/promises");
7018
+ import_promises11 = require("fs/promises");
7015
7019
  RuntimeLogger = class {
7016
7020
  store;
7017
7021
  constructor(store) {
@@ -7025,7 +7029,7 @@ var init_runtime_logger = __esm({
7025
7029
  await this.write("error", message, { ...context, ...errorMetadata }, this.store.runtimeErrorLogPath());
7026
7030
  }
7027
7031
  async write(level, message, metadata, path4) {
7028
- await (0, import_promises10.appendFile)(path4, `${JSON.stringify({
7032
+ await (0, import_promises11.appendFile)(path4, `${JSON.stringify({
7029
7033
  level,
7030
7034
  message,
7031
7035
  metadata,
@@ -7046,28 +7050,28 @@ function defaultRuntimeDirectory() {
7046
7050
  if (override) {
7047
7051
  return override;
7048
7052
  }
7049
- const homeDirectory = process.env.HOME ?? (0, import_node_os4.homedir)();
7050
- if ((0, import_node_os4.platform)() === "darwin") {
7051
- return (0, import_node_path8.join)(homeDirectory, "Library", "Application Support", "Moxt", "Machine Connector");
7053
+ const homeDirectory = process.env.HOME ?? (0, import_node_os5.homedir)();
7054
+ if ((0, import_node_os5.platform)() === "darwin") {
7055
+ return (0, import_node_path9.join)(homeDirectory, "Library", "Application Support", "Moxt", "Machine Connector");
7052
7056
  }
7053
- const stateHome = process.env.XDG_STATE_HOME ?? (0, import_node_path8.join)(homeDirectory, ".local", "state");
7054
- return (0, import_node_path8.join)(stateHome, "moxt", "machine-connector");
7057
+ const stateHome = process.env.XDG_STATE_HOME ?? (0, import_node_path9.join)(homeDirectory, ".local", "state");
7058
+ return (0, import_node_path9.join)(stateHome, "moxt", "machine-connector");
7055
7059
  }
7056
- function isNodeErrorCode3(error, expectedCode) {
7060
+ function isNodeErrorCode4(error, expectedCode) {
7057
7061
  if (!(error instanceof Error) || !("code" in error)) {
7058
7062
  return false;
7059
7063
  }
7060
7064
  return error.code === expectedCode;
7061
7065
  }
7062
- var import_promises11, import_node_crypto5, import_node_os4, import_node_path8, privateFileMode, privateDirectoryMode, maximumProcessGeneration, MachineRuntimeStore;
7066
+ var import_promises12, import_node_crypto5, import_node_os5, import_node_path9, privateFileMode, privateDirectoryMode, maximumProcessGeneration, MachineRuntimeStore;
7063
7067
  var init_store = __esm({
7064
7068
  "../machine-connector/dist/runtime/store.js"() {
7065
7069
  "use strict";
7066
7070
  init_cjs_shims();
7067
- import_promises11 = require("fs/promises");
7071
+ import_promises12 = require("fs/promises");
7068
7072
  import_node_crypto5 = require("crypto");
7069
- import_node_os4 = require("os");
7070
- import_node_path8 = require("path");
7073
+ import_node_os5 = require("os");
7074
+ import_node_path9 = require("path");
7071
7075
  privateFileMode = 384;
7072
7076
  privateDirectoryMode = 448;
7073
7077
  maximumProcessGeneration = 2147483647;
@@ -7078,30 +7082,30 @@ var init_store = __esm({
7078
7082
  this.baseDirectory = baseDirectory;
7079
7083
  }
7080
7084
  async initialize() {
7081
- await (0, import_promises11.mkdir)(this.jobsDirectory(), {
7085
+ await (0, import_promises12.mkdir)(this.jobsDirectory(), {
7082
7086
  mode: privateDirectoryMode,
7083
7087
  recursive: true
7084
7088
  });
7085
- await (0, import_promises11.mkdir)(this.detachedProcessesDirectory(), {
7089
+ await (0, import_promises12.mkdir)(this.detachedProcessesDirectory(), {
7086
7090
  mode: privateDirectoryMode,
7087
7091
  recursive: true
7088
7092
  });
7089
- await (0, import_promises11.mkdir)(this.localCodexAttemptsDirectory(), {
7093
+ await (0, import_promises12.mkdir)(this.localCodexAttemptsDirectory(), {
7090
7094
  mode: privateDirectoryMode,
7091
7095
  recursive: true
7092
7096
  });
7093
- await (0, import_promises11.mkdir)(this.localCodexProcessGenerationsDirectory(), {
7097
+ await (0, import_promises12.mkdir)(this.localCodexProcessGenerationsDirectory(), {
7094
7098
  mode: privateDirectoryMode,
7095
7099
  recursive: true
7096
7100
  });
7097
- await (0, import_promises11.chmod)(this.baseDirectory, privateDirectoryMode);
7098
- await (0, import_promises11.chmod)(this.jobsDirectory(), privateDirectoryMode);
7099
- await (0, import_promises11.chmod)(this.detachedProcessesDirectory(), privateDirectoryMode);
7100
- await (0, import_promises11.chmod)(this.localCodexAttemptsDirectory(), privateDirectoryMode);
7101
- await (0, import_promises11.chmod)(this.localCodexProcessGenerationsDirectory(), privateDirectoryMode);
7101
+ await (0, import_promises12.chmod)(this.baseDirectory, privateDirectoryMode);
7102
+ await (0, import_promises12.chmod)(this.jobsDirectory(), privateDirectoryMode);
7103
+ await (0, import_promises12.chmod)(this.detachedProcessesDirectory(), privateDirectoryMode);
7104
+ await (0, import_promises12.chmod)(this.localCodexAttemptsDirectory(), privateDirectoryMode);
7105
+ await (0, import_promises12.chmod)(this.localCodexProcessGenerationsDirectory(), privateDirectoryMode);
7102
7106
  }
7103
7107
  async getCanonicalRoot(rootPath) {
7104
- return await (0, import_promises11.realpath)(rootPath);
7108
+ return await (0, import_promises12.realpath)(rootPath);
7105
7109
  }
7106
7110
  async readIdentity() {
7107
7111
  return await this.readOptionalJson(this.identityPath());
@@ -7144,7 +7148,7 @@ var init_store = __esm({
7144
7148
  await this.writePrivateJson(this.serviceManagerPath(), serviceManager);
7145
7149
  }
7146
7150
  async removeServiceManager() {
7147
- await (0, import_promises11.rm)(this.serviceManagerPath(), { force: true });
7151
+ await (0, import_promises12.rm)(this.serviceManagerPath(), { force: true });
7148
7152
  }
7149
7153
  async readJob(jobId) {
7150
7154
  return await this.readOptionalJson(this.jobPath(jobId));
@@ -7155,16 +7159,16 @@ var init_store = __esm({
7155
7159
  async listJobs() {
7156
7160
  let names = [];
7157
7161
  try {
7158
- names = await (0, import_promises11.readdir)(this.jobsDirectory());
7162
+ names = await (0, import_promises12.readdir)(this.jobsDirectory());
7159
7163
  } catch (error) {
7160
- if (isNodeErrorCode3(error, "ENOENT")) {
7164
+ if (isNodeErrorCode4(error, "ENOENT")) {
7161
7165
  return [];
7162
7166
  }
7163
7167
  throw error;
7164
7168
  }
7165
7169
  const jobs = [];
7166
7170
  for (const name of names.filter((entry) => entry.endsWith(".json"))) {
7167
- const job = await this.readOptionalJson((0, import_node_path8.join)(this.jobsDirectory(), name));
7171
+ const job = await this.readOptionalJson((0, import_node_path9.join)(this.jobsDirectory(), name));
7168
7172
  if (job.value) {
7169
7173
  jobs.push(job.value);
7170
7174
  }
@@ -7172,7 +7176,7 @@ var init_store = __esm({
7172
7176
  return jobs;
7173
7177
  }
7174
7178
  async deleteJob(jobId) {
7175
- await (0, import_promises11.rm)(this.jobPath(jobId), { force: true });
7179
+ await (0, import_promises12.rm)(this.jobPath(jobId), { force: true });
7176
7180
  }
7177
7181
  async writeDetachedProcess(resource) {
7178
7182
  await this.writePrivateJson(this.detachedProcessPath(resource.jobId), resource);
@@ -7180,16 +7184,16 @@ var init_store = __esm({
7180
7184
  async listDetachedProcesses() {
7181
7185
  let names = [];
7182
7186
  try {
7183
- names = await (0, import_promises11.readdir)(this.detachedProcessesDirectory());
7187
+ names = await (0, import_promises12.readdir)(this.detachedProcessesDirectory());
7184
7188
  } catch (error) {
7185
- if (isNodeErrorCode3(error, "ENOENT")) {
7189
+ if (isNodeErrorCode4(error, "ENOENT")) {
7186
7190
  return [];
7187
7191
  }
7188
7192
  throw error;
7189
7193
  }
7190
7194
  const resources = [];
7191
7195
  for (const name of names.filter((entry) => entry.endsWith(".json"))) {
7192
- const resource = await this.readOptionalJson((0, import_node_path8.join)(this.detachedProcessesDirectory(), name));
7196
+ const resource = await this.readOptionalJson((0, import_node_path9.join)(this.detachedProcessesDirectory(), name));
7193
7197
  if (resource.value) {
7194
7198
  resources.push(resource.value);
7195
7199
  }
@@ -7197,7 +7201,7 @@ var init_store = __esm({
7197
7201
  return resources;
7198
7202
  }
7199
7203
  async deleteDetachedProcess(jobId) {
7200
- await (0, import_promises11.rm)(this.detachedProcessPath(jobId), { force: true });
7204
+ await (0, import_promises12.rm)(this.detachedProcessPath(jobId), { force: true });
7201
7205
  }
7202
7206
  async readLocalCodexAttempt(attemptId) {
7203
7207
  return await this.readOptionalJson(this.localCodexAttemptPath(attemptId));
@@ -7208,16 +7212,16 @@ var init_store = __esm({
7208
7212
  async listLocalCodexAttempts() {
7209
7213
  let names = [];
7210
7214
  try {
7211
- names = await (0, import_promises11.readdir)(this.localCodexAttemptsDirectory());
7215
+ names = await (0, import_promises12.readdir)(this.localCodexAttemptsDirectory());
7212
7216
  } catch (error) {
7213
- if (isNodeErrorCode3(error, "ENOENT")) {
7217
+ if (isNodeErrorCode4(error, "ENOENT")) {
7214
7218
  return [];
7215
7219
  }
7216
7220
  throw error;
7217
7221
  }
7218
7222
  const attempts = [];
7219
7223
  for (const name of names.filter((entry) => entry.endsWith(".json"))) {
7220
- const attempt = await this.readOptionalJson((0, import_node_path8.join)(this.localCodexAttemptsDirectory(), name));
7224
+ const attempt = await this.readOptionalJson((0, import_node_path9.join)(this.localCodexAttemptsDirectory(), name));
7221
7225
  if (attempt.value !== void 0) {
7222
7226
  attempts.push(attempt.value);
7223
7227
  }
@@ -7225,7 +7229,7 @@ var init_store = __esm({
7225
7229
  return attempts;
7226
7230
  }
7227
7231
  async deleteLocalCodexAttempt(attemptId) {
7228
- await (0, import_promises11.rm)(this.localCodexAttemptPath(attemptId), { force: true });
7232
+ await (0, import_promises12.rm)(this.localCodexAttemptPath(attemptId), { force: true });
7229
7233
  }
7230
7234
  async allocateLocalCodexProcessGeneration(poolKey) {
7231
7235
  if (!/^[a-f0-9]{64}$/.test(poolKey)) {
@@ -7254,62 +7258,62 @@ var init_store = __esm({
7254
7258
  return allocated;
7255
7259
  }
7256
7260
  runtimeLogPath() {
7257
- return (0, import_node_path8.join)(this.baseDirectory, "machine-connector.log");
7261
+ return (0, import_node_path9.join)(this.baseDirectory, "machine-connector.log");
7258
7262
  }
7259
7263
  runtimeErrorLogPath() {
7260
- return (0, import_node_path8.join)(this.baseDirectory, "machine-connector.error.log");
7264
+ return (0, import_node_path9.join)(this.baseDirectory, "machine-connector.error.log");
7261
7265
  }
7262
7266
  runtimeStatusPath() {
7263
- return (0, import_node_path8.join)(this.baseDirectory, "runtime-status.json");
7267
+ return (0, import_node_path9.join)(this.baseDirectory, "runtime-status.json");
7264
7268
  }
7265
7269
  runtimeSocketPath() {
7266
- if ((0, import_node_os4.platform)() === "win32") {
7270
+ if ((0, import_node_os5.platform)() === "win32") {
7267
7271
  return String.raw`\\.\pipe\moxt-machine-connector`;
7268
7272
  }
7269
- return (0, import_node_path8.join)(this.baseDirectory, "machine-connector.sock");
7273
+ return (0, import_node_path9.join)(this.baseDirectory, "machine-connector.sock");
7270
7274
  }
7271
7275
  daemonLockPath() {
7272
- return (0, import_node_path8.join)(this.baseDirectory, "daemon.lock");
7276
+ return (0, import_node_path9.join)(this.baseDirectory, "daemon.lock");
7273
7277
  }
7274
7278
  reconcileLockPath() {
7275
- return (0, import_node_path8.join)(this.baseDirectory, "daemon-reconcile.lock");
7279
+ return (0, import_node_path9.join)(this.baseDirectory, "daemon-reconcile.lock");
7276
7280
  }
7277
7281
  connectionsPath() {
7278
- return (0, import_node_path8.join)(this.baseDirectory, "connections.json");
7282
+ return (0, import_node_path9.join)(this.baseDirectory, "connections.json");
7279
7283
  }
7280
7284
  detachedProcessesDirectory() {
7281
- return (0, import_node_path8.join)(this.baseDirectory, "detached-processes");
7285
+ return (0, import_node_path9.join)(this.baseDirectory, "detached-processes");
7282
7286
  }
7283
7287
  detachedProcessPath(jobId) {
7284
- return (0, import_node_path8.join)(this.detachedProcessesDirectory(), `${jobId}.json`);
7288
+ return (0, import_node_path9.join)(this.detachedProcessesDirectory(), `${jobId}.json`);
7285
7289
  }
7286
7290
  identityPath() {
7287
- return (0, import_node_path8.join)(this.baseDirectory, "identity.json");
7291
+ return (0, import_node_path9.join)(this.baseDirectory, "identity.json");
7288
7292
  }
7289
7293
  serviceManagerPath() {
7290
- return (0, import_node_path8.join)(this.baseDirectory, "service-manager.json");
7294
+ return (0, import_node_path9.join)(this.baseDirectory, "service-manager.json");
7291
7295
  }
7292
7296
  privateKeyPath() {
7293
- return (0, import_node_path8.join)(this.baseDirectory, "device-private-key.pem");
7297
+ return (0, import_node_path9.join)(this.baseDirectory, "device-private-key.pem");
7294
7298
  }
7295
7299
  jobsDirectory() {
7296
- return (0, import_node_path8.join)(this.baseDirectory, "jobs");
7300
+ return (0, import_node_path9.join)(this.baseDirectory, "jobs");
7297
7301
  }
7298
7302
  localCodexAttemptsDirectory() {
7299
- return (0, import_node_path8.join)(this.baseDirectory, "local-codex-runtime-attempts");
7303
+ return (0, import_node_path9.join)(this.baseDirectory, "local-codex-runtime-attempts");
7300
7304
  }
7301
7305
  localCodexAttemptPath(attemptId) {
7302
- return (0, import_node_path8.join)(this.localCodexAttemptsDirectory(), `${attemptId}.json`);
7306
+ return (0, import_node_path9.join)(this.localCodexAttemptsDirectory(), `${attemptId}.json`);
7303
7307
  }
7304
7308
  localCodexProcessGenerationsDirectory() {
7305
- return (0, import_node_path8.join)(this.baseDirectory, "local-codex-runtime-process-generations");
7309
+ return (0, import_node_path9.join)(this.baseDirectory, "local-codex-runtime-process-generations");
7306
7310
  }
7307
7311
  localCodexProcessGenerationPath(poolKey) {
7308
7312
  const key = (0, import_node_crypto5.createHash)("sha256").update(poolKey).digest("hex");
7309
- return (0, import_node_path8.join)(this.localCodexProcessGenerationsDirectory(), `${key}.json`);
7313
+ return (0, import_node_path9.join)(this.localCodexProcessGenerationsDirectory(), `${key}.json`);
7310
7314
  }
7311
7315
  jobPath(jobId) {
7312
- return (0, import_node_path8.join)(this.jobsDirectory(), `${jobId}.json`);
7316
+ return (0, import_node_path9.join)(this.jobsDirectory(), `${jobId}.json`);
7313
7317
  }
7314
7318
  async readOptionalJson(path4) {
7315
7319
  const content3 = await this.readOptionalText(path4);
@@ -7320,9 +7324,9 @@ var init_store = __esm({
7320
7324
  }
7321
7325
  async readOptionalText(path4) {
7322
7326
  try {
7323
- return { value: await (0, import_promises11.readFile)(path4, "utf8") };
7327
+ return { value: await (0, import_promises12.readFile)(path4, "utf8") };
7324
7328
  } catch (error) {
7325
- if (isNodeErrorCode3(error, "ENOENT")) {
7329
+ if (isNodeErrorCode4(error, "ENOENT")) {
7326
7330
  return {};
7327
7331
  }
7328
7332
  throw error;
@@ -7333,17 +7337,17 @@ var init_store = __esm({
7333
7337
  `);
7334
7338
  }
7335
7339
  async writePrivateText(path4, value) {
7336
- await (0, import_promises11.mkdir)((0, import_node_path8.dirname)(path4), {
7340
+ await (0, import_promises12.mkdir)((0, import_node_path9.dirname)(path4), {
7337
7341
  mode: privateDirectoryMode,
7338
7342
  recursive: true
7339
7343
  });
7340
7344
  const temporaryPath = `${path4}.${process.pid}.tmp`;
7341
- await (0, import_promises11.writeFile)(temporaryPath, value, {
7345
+ await (0, import_promises12.writeFile)(temporaryPath, value, {
7342
7346
  encoding: "utf8",
7343
7347
  mode: privateFileMode
7344
7348
  });
7345
- await (0, import_promises11.chmod)(temporaryPath, privateFileMode);
7346
- await (0, import_promises11.rename)(temporaryPath, path4);
7349
+ await (0, import_promises12.chmod)(temporaryPath, privateFileMode);
7350
+ await (0, import_promises12.rename)(temporaryPath, path4);
7347
7351
  }
7348
7352
  };
7349
7353
  }
@@ -7383,56 +7387,327 @@ function extractCodexVersion(userAgent) {
7383
7387
  const matched = /(?:codex_cli_rs|codex-cli|codex(?: desktop)?)\/([0-9][^\s/]*)/i.exec(userAgent);
7384
7388
  return matched?.[1] ?? userAgent.slice(0, 64);
7385
7389
  }
7390
+ function assertSupportedCodexVersion(codexVersion) {
7391
+ const parsed = /^(\d+)\.(\d+)\.(\d+)/.exec(codexVersion);
7392
+ const minimum = /^(\d+)\.(\d+)\.(\d+)/.exec(minimumCodexVersion);
7393
+ if (parsed === null || minimum === null) {
7394
+ throw new AppServerUnsupportedVersionError(codexVersion);
7395
+ }
7396
+ const actualParts = parsed.slice(1, 4).map(Number);
7397
+ const minimumParts = minimum.slice(1, 4).map(Number);
7398
+ for (let index2 = 0; index2 < minimumParts.length; index2 += 1) {
7399
+ const actualPart = actualParts[index2];
7400
+ const minimumPart = minimumParts[index2];
7401
+ if (actualPart > minimumPart) {
7402
+ return;
7403
+ }
7404
+ if (actualPart < minimumPart) {
7405
+ throw new AppServerUnsupportedVersionError(codexVersion);
7406
+ }
7407
+ }
7408
+ }
7409
+ function errorMessage2(error) {
7410
+ return error instanceof Error ? error.message : String(error);
7411
+ }
7412
+ function stderrIndicatesUnsupportedAppServerArguments(stderr) {
7413
+ const normalized = stderr.toLowerCase();
7414
+ const mentionsRequiredArgument = normalized.includes("--disable") || normalized.includes("unified_exec");
7415
+ if (!mentionsRequiredArgument) {
7416
+ return false;
7417
+ }
7418
+ return [
7419
+ "unexpected argument",
7420
+ "unknown argument",
7421
+ "unknown feature",
7422
+ "unrecognized option",
7423
+ "unknown option"
7424
+ ].some((pattern) => normalized.includes(pattern));
7425
+ }
7386
7426
  async function completionWithinExit(child, milliseconds) {
7387
7427
  if (child.exitCode !== null || child.signalCode !== null) {
7388
7428
  return;
7389
7429
  }
7390
- await new Promise((resolve9) => {
7391
- const timeout = setTimeout(resolve9, milliseconds);
7430
+ await new Promise((resolve10) => {
7431
+ const timeout = setTimeout(resolve10, milliseconds);
7392
7432
  timeout.unref();
7393
7433
  child.once("close", () => {
7394
7434
  clearTimeout(timeout);
7395
- resolve9();
7435
+ resolve10();
7396
7436
  });
7397
7437
  });
7398
7438
  }
7399
- function terminateAppServerProcess(child) {
7400
- if ((0, import_node_os5.platform)() === "win32" || child.pid === void 0) {
7439
+ async function completionWithinProcessTreeExit(child, stopTarget, milliseconds) {
7440
+ const deadline = Date.now() + milliseconds;
7441
+ while (Date.now() < deadline) {
7442
+ if (!await appServerProcessTreeIsRunning(child, stopTarget)) {
7443
+ return;
7444
+ }
7445
+ await new Promise((resolve10) => {
7446
+ setTimeout(resolve10, processTreePollMilliseconds);
7447
+ });
7448
+ }
7449
+ }
7450
+ async function appServerProcessTreeIsRunning(child, stopTarget) {
7451
+ if ((0, import_node_os6.platform)() === "win32" || child.pid === void 0) {
7452
+ return child.exitCode === null && child.signalCode === null;
7453
+ }
7454
+ if (child.exitCode === null && child.signalCode === null) {
7455
+ return true;
7456
+ }
7457
+ if (!stopTarget.verificationAvailable) {
7458
+ return true;
7459
+ }
7460
+ if (stopTarget.descendantProcesses.size === 0) {
7461
+ return false;
7462
+ }
7463
+ const processTable = await appServerProcessTableWithRetry();
7464
+ if (!processTable.available) {
7465
+ return true;
7466
+ }
7467
+ for (const processIdentity of stopTarget.descendantProcesses.values()) {
7468
+ if (processIdentityIsCurrent(processIdentity, processTable)) {
7469
+ return true;
7470
+ }
7471
+ }
7472
+ return false;
7473
+ }
7474
+ async function terminateAppServerProcess(child, stopTarget) {
7475
+ if ((0, import_node_os6.platform)() === "win32" || child.pid === void 0) {
7401
7476
  child.kill("SIGTERM");
7402
7477
  return;
7403
7478
  }
7479
+ const processTable = stopTarget.descendantProcesses.size === 0 ? unavailableAppServerProcessTable() : await appServerProcessTableWithRetry();
7480
+ for (const processIdentity of Array.from(stopTarget.descendantProcesses.values()).reverse()) {
7481
+ if (!processIdentityIsCurrent(processIdentity, processTable)) {
7482
+ continue;
7483
+ }
7484
+ try {
7485
+ process.kill(processIdentity.processId, "SIGTERM");
7486
+ } catch {
7487
+ }
7488
+ }
7489
+ if (child.exitCode !== null || child.signalCode !== null) {
7490
+ return;
7491
+ }
7404
7492
  try {
7405
7493
  process.kill(-child.pid, "SIGTERM");
7406
7494
  } catch {
7407
7495
  child.kill("SIGTERM");
7408
7496
  }
7409
7497
  }
7410
- function killAppServerProcess(child) {
7411
- if ((0, import_node_os5.platform)() === "win32" || child.pid === void 0) {
7498
+ async function killAppServerProcess(child, stopTarget) {
7499
+ if ((0, import_node_os6.platform)() === "win32" || child.pid === void 0) {
7412
7500
  child.kill("SIGKILL");
7413
7501
  return;
7414
7502
  }
7503
+ const processTable = stopTarget.descendantProcesses.size === 0 ? unavailableAppServerProcessTable() : await appServerProcessTableWithRetry();
7504
+ for (const processIdentity of Array.from(stopTarget.descendantProcesses.values()).reverse()) {
7505
+ if (!processIdentityIsCurrent(processIdentity, processTable)) {
7506
+ continue;
7507
+ }
7508
+ try {
7509
+ process.kill(processIdentity.processId, "SIGKILL");
7510
+ } catch {
7511
+ }
7512
+ }
7513
+ if (child.exitCode !== null || child.signalCode !== null) {
7514
+ return;
7515
+ }
7415
7516
  try {
7416
7517
  process.kill(-child.pid, "SIGKILL");
7417
7518
  } catch {
7418
7519
  child.kill("SIGKILL");
7419
7520
  }
7420
7521
  }
7421
- var import_node_child_process3, import_node_crypto6, import_node_os5, maximumFrameBytes, requestTimeoutMilliseconds2, AppServerProcessLostError, AppServerProtocolError, AppServerRequestTimeoutError, AppServerResponseError, AppServerClient, LocalCodexAppServerSupervisor;
7522
+ async function captureAppServerProcessTree(child) {
7523
+ if ((0, import_node_os6.platform)() === "win32" || child.pid === void 0) {
7524
+ return {
7525
+ descendantProcesses: [],
7526
+ status: AppServerProcessTreeCaptureStatus.Complete
7527
+ };
7528
+ }
7529
+ if (child.exitCode !== null || child.signalCode !== null) {
7530
+ return {
7531
+ descendantProcesses: [],
7532
+ status: AppServerProcessTreeCaptureStatus.ProcessExited
7533
+ };
7534
+ }
7535
+ const processTable = await appServerProcessTableWithRetry();
7536
+ if (!processTable.available) {
7537
+ return {
7538
+ descendantProcesses: [],
7539
+ status: AppServerProcessTreeCaptureStatus.ProcessTableUnavailable
7540
+ };
7541
+ }
7542
+ if (!processTable.processes.has(child.pid)) {
7543
+ return {
7544
+ descendantProcesses: [],
7545
+ status: AppServerProcessTreeCaptureStatus.ProcessExited
7546
+ };
7547
+ }
7548
+ const childrenByParent = /* @__PURE__ */ new Map();
7549
+ for (const processRecord of processTable.processes.values()) {
7550
+ const children = childrenByParent.get(processRecord.parentProcessId) ?? [];
7551
+ children.push(processRecord);
7552
+ childrenByParent.set(processRecord.parentProcessId, children);
7553
+ }
7554
+ const descendants = [];
7555
+ const pending = [child.pid];
7556
+ const seen = new Set(pending);
7557
+ while (pending.length > 0) {
7558
+ const parentProcessId = pending.shift();
7559
+ if (parentProcessId === void 0) {
7560
+ continue;
7561
+ }
7562
+ for (const processRecord of childrenByParent.get(parentProcessId) ?? []) {
7563
+ if (seen.has(processRecord.processId)) {
7564
+ continue;
7565
+ }
7566
+ seen.add(processRecord.processId);
7567
+ descendants.push({
7568
+ processId: processRecord.processId,
7569
+ startedAt: processRecord.startedAt
7570
+ });
7571
+ pending.push(processRecord.processId);
7572
+ }
7573
+ }
7574
+ return {
7575
+ descendantProcesses: descendants,
7576
+ status: AppServerProcessTreeCaptureStatus.Complete
7577
+ };
7578
+ }
7579
+ async function appServerProcessTable() {
7580
+ const listed = await new Promise((resolve10) => {
7581
+ (0, import_node_child_process3.execFile)(processTableExecutable(), ["-axo", "pid=,ppid=,lstart="], {
7582
+ encoding: "utf8",
7583
+ maxBuffer: maximumProcessTableBytes,
7584
+ timeout: processTableTimeoutMilliseconds,
7585
+ windowsHide: true
7586
+ }, (error, stdout) => {
7587
+ if (error !== null || typeof stdout !== "string") {
7588
+ resolve10({});
7589
+ return;
7590
+ }
7591
+ resolve10({ output: stdout });
7592
+ });
7593
+ });
7594
+ if (listed.output === void 0) {
7595
+ return unavailableAppServerProcessTable();
7596
+ }
7597
+ const processes = /* @__PURE__ */ new Map();
7598
+ for (const line of listed.output.split("\n")) {
7599
+ if (line.trim() === "") {
7600
+ continue;
7601
+ }
7602
+ const matched = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line);
7603
+ if (matched === null) {
7604
+ return unavailableAppServerProcessTable();
7605
+ }
7606
+ const processId = Number(matched[1]);
7607
+ const parentProcessId = Number(matched[2]);
7608
+ processes.set(processId, {
7609
+ parentProcessId,
7610
+ processId,
7611
+ startedAt: matched[3].trim()
7612
+ });
7613
+ }
7614
+ return { available: processes.size > 0, processes };
7615
+ }
7616
+ function processTableExecutable() {
7617
+ const configured = process.env.MOXT_LOCAL_CODEX_PS_PATH;
7618
+ if (configured !== void 0 && configured !== "") {
7619
+ return configured;
7620
+ }
7621
+ return defaultProcessTableExecutable;
7622
+ }
7623
+ function resolveDefaultProcessTableExecutable() {
7624
+ const candidates2 = (0, import_node_os6.platform)() === "linux" ? ["/usr/bin/ps", "/bin/ps"] : ["/bin/ps", "/usr/bin/ps"];
7625
+ for (const candidate of candidates2) {
7626
+ try {
7627
+ (0, import_node_fs2.accessSync)(candidate, import_node_fs2.constants.X_OK);
7628
+ return candidate;
7629
+ } catch {
7630
+ continue;
7631
+ }
7632
+ }
7633
+ return "ps";
7634
+ }
7635
+ async function appServerProcessTableWithRetry() {
7636
+ for (let attempt = 1; attempt <= maximumProcessTableAttempts; attempt += 1) {
7637
+ const processTable = await appServerProcessTable();
7638
+ if (processTable.available) {
7639
+ return processTable;
7640
+ }
7641
+ if (attempt < maximumProcessTableAttempts) {
7642
+ await new Promise((resolve10) => {
7643
+ setTimeout(resolve10, processTableRetryMilliseconds);
7644
+ });
7645
+ }
7646
+ }
7647
+ return unavailableAppServerProcessTable();
7648
+ }
7649
+ function unavailableAppServerProcessTable() {
7650
+ return { available: false, processes: /* @__PURE__ */ new Map() };
7651
+ }
7652
+ function processIdentityIsCurrent(processIdentity, processTable) {
7653
+ return processTable.available && processTable.processes.get(processIdentity.processId)?.startedAt === processIdentity.startedAt;
7654
+ }
7655
+ function stopWindowsProcessTree(child) {
7656
+ if (child.pid === void 0 || child.exitCode !== null || child.signalCode !== null) {
7657
+ return {};
7658
+ }
7659
+ const stopped = (0, import_node_child_process3.spawnSync)("taskkill", ["/pid", String(child.pid), "/t", "/f"], {
7660
+ encoding: "utf8",
7661
+ windowsHide: true
7662
+ });
7663
+ if (stopped.error === void 0 && stopped.status === 0) {
7664
+ return {};
7665
+ }
7666
+ return {
7667
+ failureMessage: stopped.error?.message ?? `taskkill exited with status ${String(stopped.status)}`
7668
+ };
7669
+ }
7670
+ var import_node_child_process3, import_node_crypto6, import_node_fs2, import_node_os6, maximumFrameBytes, requestTimeoutMilliseconds2, processExitGraceMilliseconds, processTreePollMilliseconds, processTableTimeoutMilliseconds, processTableRetryMilliseconds, maximumProcessTableAttempts, maximumProcessTableBytes, maximumStderrTailCharacters, minimumCodexVersion, defaultProcessTableExecutable, appServerArguments, AppServerProcessTreeCaptureStatus, AppServerProcessLostError, AppServerProtocolError, AppServerUnsupportedVersionError, AppServerRequestTimeoutError, AppServerResponseError, AppServerClient, LocalCodexAppServerSupervisor;
7422
7671
  var init_app_server_client = __esm({
7423
7672
  "../machine-connector/dist/runtime/local-codex-runtime/app-server-client.js"() {
7424
7673
  "use strict";
7425
7674
  init_cjs_shims();
7426
7675
  import_node_child_process3 = require("child_process");
7427
7676
  import_node_crypto6 = require("crypto");
7428
- import_node_os5 = require("os");
7677
+ import_node_fs2 = require("fs");
7678
+ import_node_os6 = require("os");
7429
7679
  init_version();
7430
7680
  init_contracts2();
7431
7681
  maximumFrameBytes = 8e6;
7432
7682
  requestTimeoutMilliseconds2 = 3e4;
7683
+ processExitGraceMilliseconds = 2e3;
7684
+ processTreePollMilliseconds = 250;
7685
+ processTableTimeoutMilliseconds = 1e3;
7686
+ processTableRetryMilliseconds = 100;
7687
+ maximumProcessTableAttempts = 3;
7688
+ maximumProcessTableBytes = 8e6;
7689
+ maximumStderrTailCharacters = 4e3;
7690
+ minimumCodexVersion = "0.146.0";
7691
+ defaultProcessTableExecutable = resolveDefaultProcessTableExecutable();
7692
+ appServerArguments = [
7693
+ "app-server",
7694
+ "--listen",
7695
+ "stdio://",
7696
+ "--disable",
7697
+ "unified_exec"
7698
+ ];
7699
+ (function(AppServerProcessTreeCaptureStatus2) {
7700
+ AppServerProcessTreeCaptureStatus2["Complete"] = "complete";
7701
+ AppServerProcessTreeCaptureStatus2["ProcessExited"] = "process_exited";
7702
+ AppServerProcessTreeCaptureStatus2["ProcessTableUnavailable"] = "process_table_unavailable";
7703
+ })(AppServerProcessTreeCaptureStatus || (AppServerProcessTreeCaptureStatus = {}));
7433
7704
  AppServerProcessLostError = class extends Error {
7434
- constructor(message) {
7705
+ code;
7706
+ unavailableReason;
7707
+ constructor(message, code, unavailableReason) {
7435
7708
  super(message);
7709
+ this.code = code;
7710
+ this.unavailableReason = unavailableReason;
7436
7711
  this.name = "AppServerProcessLostError";
7437
7712
  }
7438
7713
  };
@@ -7442,6 +7717,14 @@ var init_app_server_client = __esm({
7442
7717
  this.name = "AppServerProtocolError";
7443
7718
  }
7444
7719
  };
7720
+ AppServerUnsupportedVersionError = class extends AppServerProtocolError {
7721
+ codexVersion;
7722
+ constructor(codexVersion) {
7723
+ super(`Moxt Local Codex Runtime requires Codex ${minimumCodexVersion} or newer; detected ${codexVersion}`);
7724
+ this.codexVersion = codexVersion;
7725
+ this.name = "AppServerUnsupportedVersionError";
7726
+ }
7727
+ };
7445
7728
  AppServerRequestTimeoutError = class extends AppServerProtocolError {
7446
7729
  method;
7447
7730
  constructor(method) {
@@ -7467,8 +7750,10 @@ var init_app_server_client = __esm({
7467
7750
  closed = false;
7468
7751
  handlerQueue = Promise.resolve();
7469
7752
  intentionalStop = false;
7753
+ initializationCompleted = false;
7470
7754
  nextRequestId = 1;
7471
7755
  pending = /* @__PURE__ */ new Map();
7756
+ stderrTail = "";
7472
7757
  writeQueue = Promise.resolve();
7473
7758
  constructor(child, handlers, processGeneration) {
7474
7759
  this.child = child;
@@ -7477,21 +7762,32 @@ var init_app_server_client = __esm({
7477
7762
  child.stdout.on("data", (chunk) => this.receive(chunk));
7478
7763
  child.stderr.setEncoding("utf8");
7479
7764
  child.stderr.on("data", (text3) => {
7765
+ this.stderrTail = `${this.stderrTail}${text3}`.slice(-maximumStderrTailCharacters);
7480
7766
  this.enqueueHandler(async () => await handlers.onStderr(text3), "stderr");
7481
7767
  });
7482
7768
  child.once("error", (error) => {
7483
- this.closeWithError(new AppServerProcessLostError(`Codex App Server process failed: ${error.message}`));
7769
+ const code = "code" in error && typeof error.code === "string" ? error.code : void 0;
7770
+ const unavailableReason = this.initializationCompleted ? void 0 : LocalCodexUnavailableReasonWire.AppServerStartupFailed;
7771
+ this.closeWithError(new AppServerProcessLostError(`Codex App Server process failed: ${error.message}`, code, unavailableReason));
7484
7772
  });
7485
7773
  child.once("close", (code, signal) => {
7486
- this.closeWithError(new AppServerProcessLostError(`Codex App Server process exited with code ${String(code)} and signal ${String(signal)}`));
7774
+ const stderr = this.stderrTail.trim();
7775
+ const unsupportedArguments = !this.initializationCompleted && stderrIndicatesUnsupportedAppServerArguments(stderr);
7776
+ const startupRequirement = unsupportedArguments ? `; Moxt Local Codex Runtime requires Codex ${minimumCodexVersion} or newer` : "";
7777
+ const startupStderr = !this.initializationCompleted && stderr !== "" ? `; stderr: ${stderr}` : "";
7778
+ const unavailableReason = {};
7779
+ if (!this.initializationCompleted) {
7780
+ unavailableReason.value = unsupportedArguments ? LocalCodexUnavailableReasonWire.CodexVersionUnsupported : LocalCodexUnavailableReasonWire.AppServerStartupFailed;
7781
+ }
7782
+ this.closeWithError(new AppServerProcessLostError(`Codex App Server process exited with code ${String(code)} and signal ${String(signal)}${startupStderr}${startupRequirement}`, void 0, unavailableReason.value));
7487
7783
  });
7488
7784
  }
7489
7785
  static async start(options) {
7490
7786
  const environment = createAppServerEnvironment(options.environment);
7491
7787
  const executable = process.env.MOXT_CODEX_PATH ?? "codex";
7492
- const child = (0, import_node_child_process3.spawn)(executable, ["app-server", "--listen", "stdio://"], {
7788
+ const child = (0, import_node_child_process3.spawn)(executable, appServerArguments, {
7493
7789
  cwd: options.processBaseDirectory,
7494
- detached: (0, import_node_os5.platform)() !== "win32",
7790
+ detached: (0, import_node_os6.platform)() !== "win32",
7495
7791
  env: environment,
7496
7792
  shell: false,
7497
7793
  stdio: ["pipe", "pipe", "pipe"],
@@ -7510,6 +7806,9 @@ var init_app_server_client = __esm({
7510
7806
  version: connectorVersion
7511
7807
  }
7512
7808
  });
7809
+ const codexVersion = extractCodexVersion(initialized.userAgent);
7810
+ assertSupportedCodexVersion(codexVersion);
7811
+ client.initializationCompleted = true;
7513
7812
  await client.notify("initialized");
7514
7813
  const account = await client.request("account/read", { refreshToken: false });
7515
7814
  await client.request("thread/loaded/list", {
@@ -7522,14 +7821,21 @@ var init_app_server_client = __esm({
7522
7821
  appServerStatus: LocalCodexComponentStatusWire.Ready,
7523
7822
  codexAuthStatus: authenticated ? LocalCodexComponentStatusWire.Ready : LocalCodexComponentStatusWire.AuthenticationRequired,
7524
7823
  codexBinaryStatus: LocalCodexComponentStatusWire.Ready,
7525
- codexVersion: extractCodexVersion(initialized.userAgent),
7824
+ codexVersion,
7526
7825
  nativeStoreIdentity: digestOpaque(`${options.nativeStoreIdentitySeed}\0${initialized.codexHome}`),
7527
7826
  processGeneration: options.processGeneration
7528
7827
  },
7529
7828
  client
7530
7829
  };
7531
7830
  } catch (error) {
7532
- await client.stop();
7831
+ try {
7832
+ await client.stop();
7833
+ } catch (cleanupError) {
7834
+ try {
7835
+ await options.handlers.onStderr(`Failed to clean up Codex App Server after startup failed: ${errorMessage2(cleanupError)}`);
7836
+ } catch {
7837
+ }
7838
+ }
7533
7839
  throw error;
7534
7840
  }
7535
7841
  }
@@ -7537,19 +7843,22 @@ var init_app_server_client = __esm({
7537
7843
  return this.closed;
7538
7844
  }
7539
7845
  async request(method, params) {
7846
+ return await this.requestWithin(method, params, requestTimeoutMilliseconds2);
7847
+ }
7848
+ async requestWithin(method, params, timeoutMilliseconds) {
7540
7849
  if (this.closed) {
7541
7850
  throw new AppServerProcessLostError("Codex App Server process is closed");
7542
7851
  }
7543
7852
  const id = this.nextRequestId;
7544
7853
  this.nextRequestId += 1;
7545
7854
  const key = String(id);
7546
- const response = new Promise((resolve9, reject) => {
7855
+ const response = new Promise((resolve10, reject) => {
7547
7856
  const timeout = setTimeout(() => {
7548
7857
  this.pending.delete(key);
7549
7858
  reject(new AppServerRequestTimeoutError(method));
7550
- }, requestTimeoutMilliseconds2);
7859
+ }, timeoutMilliseconds);
7551
7860
  timeout.unref();
7552
- this.pending.set(key, { reject, resolve: resolve9, timeout });
7861
+ this.pending.set(key, { reject, resolve: resolve10, timeout });
7553
7862
  });
7554
7863
  await this.write({ id, method, params });
7555
7864
  return await response;
@@ -7566,20 +7875,56 @@ var init_app_server_client = __esm({
7566
7875
  async respondWithError(id, code, message) {
7567
7876
  await this.write({ error: { code, message }, id });
7568
7877
  }
7569
- async stop() {
7570
- if (this.closed) {
7878
+ async captureProcessTree() {
7879
+ return await captureAppServerProcessTree(this.child);
7880
+ }
7881
+ async stop(capture) {
7882
+ const stopAlreadyRequested = this.intentionalStop;
7883
+ this.intentionalStop = true;
7884
+ const currentCapture = await captureAppServerProcessTree(this.child);
7885
+ const stopTarget = {
7886
+ descendantProcesses: /* @__PURE__ */ new Map(),
7887
+ verificationAvailable: currentCapture.status !== AppServerProcessTreeCaptureStatus.ProcessTableUnavailable && capture?.status !== AppServerProcessTreeCaptureStatus.ProcessTableUnavailable
7888
+ };
7889
+ for (const processIdentity of capture?.descendantProcesses ?? []) {
7890
+ stopTarget.descendantProcesses.set(processIdentity.processId, processIdentity);
7891
+ }
7892
+ for (const processIdentity of currentCapture.descendantProcesses) {
7893
+ stopTarget.descendantProcesses.set(processIdentity.processId, processIdentity);
7894
+ }
7895
+ if (stopAlreadyRequested && !await appServerProcessTreeIsRunning(this.child, stopTarget)) {
7571
7896
  return;
7572
7897
  }
7573
- this.intentionalStop = true;
7574
- this.child.stdin.end();
7575
- await completionWithinExit(this.child, 2e3);
7576
7898
  if (!this.closed) {
7577
- terminateAppServerProcess(this.child);
7578
- await completionWithinExit(this.child, 2e3);
7899
+ this.child.stdin.end();
7900
+ await completionWithinExit(this.child, processExitGraceMilliseconds);
7579
7901
  }
7580
- if (!this.closed) {
7581
- killAppServerProcess(this.child);
7582
- await completionWithinExit(this.child, 2e3);
7902
+ if ((0, import_node_os6.platform)() === "win32" && await appServerProcessTreeIsRunning(this.child, stopTarget)) {
7903
+ const stopped = stopWindowsProcessTree(this.child);
7904
+ await completionWithinExit(this.child, processExitGraceMilliseconds);
7905
+ if (!await appServerProcessTreeIsRunning(this.child, stopTarget)) {
7906
+ return;
7907
+ }
7908
+ this.child.kill("SIGKILL");
7909
+ await completionWithinExit(this.child, processExitGraceMilliseconds);
7910
+ if (stopped.failureMessage !== void 0) {
7911
+ throw new AppServerProcessLostError(`Failed to stop Codex App Server process tree: ${stopped.failureMessage}`);
7912
+ }
7913
+ if (await appServerProcessTreeIsRunning(this.child, stopTarget)) {
7914
+ throw new AppServerProcessLostError("Codex App Server process tree did not stop");
7915
+ }
7916
+ return;
7917
+ }
7918
+ if (await appServerProcessTreeIsRunning(this.child, stopTarget)) {
7919
+ await terminateAppServerProcess(this.child, stopTarget);
7920
+ await completionWithinProcessTreeExit(this.child, stopTarget, processExitGraceMilliseconds);
7921
+ }
7922
+ if (await appServerProcessTreeIsRunning(this.child, stopTarget)) {
7923
+ await killAppServerProcess(this.child, stopTarget);
7924
+ await completionWithinProcessTreeExit(this.child, stopTarget, processExitGraceMilliseconds);
7925
+ }
7926
+ if (await appServerProcessTreeIsRunning(this.child, stopTarget)) {
7927
+ throw new AppServerProcessLostError(stopTarget.verificationAvailable ? "Codex App Server process tree did not stop" : "Codex App Server process tree could not be enumerated and verified as stopped");
7583
7928
  }
7584
7929
  }
7585
7930
  receive(chunk) {
@@ -7650,12 +7995,12 @@ var init_app_server_client = __esm({
7650
7995
  if (Buffer.byteLength(frame, "utf8") > maximumFrameBytes) {
7651
7996
  throw new AppServerProtocolError("Codex App Server request exceeds the size limit");
7652
7997
  }
7653
- const operation = this.writeQueue.then(async () => await new Promise((resolve9, reject) => {
7998
+ const operation = this.writeQueue.then(async () => await new Promise((resolve10, reject) => {
7654
7999
  this.child.stdin.write(frame, (error) => {
7655
8000
  if (error) {
7656
8001
  reject(error);
7657
8002
  } else {
7658
- resolve9();
8003
+ resolve10();
7659
8004
  }
7660
8005
  });
7661
8006
  }));
@@ -7687,6 +8032,7 @@ var init_app_server_client = __esm({
7687
8032
  client = {};
7688
8033
  quarantinePromise;
7689
8034
  startPromise;
8035
+ unavailableReason;
7690
8036
  constructor(processBaseDirectory, environment, nativeStoreIdentitySeed, handlers, allocateProcessGeneration) {
7691
8037
  this.processBaseDirectory = processBaseDirectory;
7692
8038
  this.environment = environment;
@@ -7707,6 +8053,9 @@ var init_app_server_client = __esm({
7707
8053
  currentClient() {
7708
8054
  return this.client;
7709
8055
  }
8056
+ currentUnavailableReason() {
8057
+ return this.unavailableReason === void 0 ? {} : { value: this.unavailableReason };
8058
+ }
7710
8059
  async ensureStarted() {
7711
8060
  await this.quarantinePromise;
7712
8061
  if (this.client.value !== void 0 && !this.client.value.isClosed()) {
@@ -7720,7 +8069,7 @@ var init_app_server_client = __esm({
7720
8069
  return await this.startPromise;
7721
8070
  }
7722
8071
  markProcessLost(processGeneration) {
7723
- if (this.capability.processGeneration !== processGeneration) {
8072
+ if (this.client.value?.processGeneration !== processGeneration) {
7724
8073
  return false;
7725
8074
  }
7726
8075
  this.client = {};
@@ -7734,7 +8083,7 @@ var init_app_server_client = __esm({
7734
8083
  await this.client.value?.stop();
7735
8084
  this.client = {};
7736
8085
  }
7737
- async quarantineCurrentProcess() {
8086
+ async quarantineCurrentProcess(capture) {
7738
8087
  if (this.quarantinePromise !== void 0) {
7739
8088
  await this.quarantinePromise;
7740
8089
  return;
@@ -7746,7 +8095,7 @@ var init_app_server_client = __esm({
7746
8095
  appServerStatus: LocalCodexComponentStatusWire.Error
7747
8096
  };
7748
8097
  const operation = (async () => {
7749
- await client?.stop();
8098
+ await client?.stop(capture);
7750
8099
  })();
7751
8100
  this.quarantinePromise = operation;
7752
8101
  try {
@@ -7769,13 +8118,25 @@ var init_app_server_client = __esm({
7769
8118
  });
7770
8119
  this.capability = started.capability;
7771
8120
  this.client = { value: started.client };
8121
+ this.unavailableReason = void 0;
7772
8122
  return started.client;
7773
8123
  } catch (error) {
7774
8124
  const missing = error instanceof Error && "code" in error && error.code === "ENOENT";
8125
+ const unsupportedVersion = error instanceof AppServerUnsupportedVersionError;
8126
+ const unsupportedStartupArguments = error instanceof AppServerProcessLostError && error.unavailableReason === LocalCodexUnavailableReasonWire.CodexVersionUnsupported;
8127
+ const incompatible = unsupportedVersion || unsupportedStartupArguments;
8128
+ this.unavailableReason = void 0;
8129
+ if (incompatible) {
8130
+ this.unavailableReason = LocalCodexUnavailableReasonWire.CodexVersionUnsupported;
8131
+ } else if (error instanceof AppServerProcessLostError && error.unavailableReason !== void 0 && !missing) {
8132
+ this.unavailableReason = error.unavailableReason;
8133
+ }
8134
+ const failureStatus = incompatible ? LocalCodexComponentStatusWire.Incompatible : LocalCodexComponentStatusWire.Error;
7775
8135
  this.capability = {
7776
8136
  ...this.capability,
7777
- appServerStatus: missing ? LocalCodexComponentStatusWire.Missing : LocalCodexComponentStatusWire.Error,
7778
- codexBinaryStatus: missing ? LocalCodexComponentStatusWire.Missing : LocalCodexComponentStatusWire.Error,
8137
+ appServerStatus: missing ? LocalCodexComponentStatusWire.Missing : failureStatus,
8138
+ codexBinaryStatus: missing ? LocalCodexComponentStatusWire.Missing : failureStatus,
8139
+ ...error instanceof AppServerUnsupportedVersionError ? { codexVersion: error.codexVersion } : {},
7779
8140
  processGeneration
7780
8141
  };
7781
8142
  throw error;
@@ -8240,10 +8601,10 @@ function redactPath(value, canonicalRoot) {
8240
8601
  if (value === canonicalRoot) {
8241
8602
  return ".";
8242
8603
  }
8243
- if (value.startsWith(`${canonicalRoot}${import_node_path9.sep}`)) {
8244
- return (0, import_node_path9.relative)(canonicalRoot, value);
8604
+ if (value.startsWith(`${canonicalRoot}${import_node_path10.sep}`)) {
8605
+ return (0, import_node_path10.relative)(canonicalRoot, value);
8245
8606
  }
8246
- if ((0, import_node_path9.isAbsolute)(value) || /^[A-Za-z]:[\\/]/.test(value)) {
8607
+ if ((0, import_node_path10.isAbsolute)(value) || /^[A-Za-z]:[\\/]/.test(value)) {
8247
8608
  return "[redacted-absolute-path]";
8248
8609
  }
8249
8610
  return value;
@@ -8292,12 +8653,12 @@ function recordValue(value) {
8292
8653
  function isRecord3(value) {
8293
8654
  return typeof value === "object" && value !== null && !Array.isArray(value);
8294
8655
  }
8295
- var import_node_path9;
8656
+ var import_node_path10;
8296
8657
  var init_event_normalizer = __esm({
8297
8658
  "../machine-connector/dist/runtime/local-codex-runtime/event-normalizer.js"() {
8298
8659
  "use strict";
8299
8660
  init_cjs_shims();
8300
- import_node_path9 = require("path");
8661
+ import_node_path10 = require("path");
8301
8662
  init_contracts2();
8302
8663
  }
8303
8664
  });
@@ -8311,12 +8672,12 @@ function isThreadNameMetadataPendingResponse(message) {
8311
8672
  }
8312
8673
  function createActiveAttempt(claim, durable, workingDirectory) {
8313
8674
  let resolveTerminal = (_value) => void 0;
8314
- const terminal = new Promise((resolve9) => {
8315
- resolveTerminal = resolve9;
8675
+ const terminal = new Promise((resolve10) => {
8676
+ resolveTerminal = resolve10;
8316
8677
  });
8317
8678
  let resolveFatal = (_error) => void 0;
8318
- const fatal = new Promise((resolve9) => {
8319
- resolveFatal = resolve9;
8679
+ const fatal = new Promise((resolve10) => {
8680
+ resolveFatal = resolve10;
8320
8681
  });
8321
8682
  return {
8322
8683
  acceptedByAppServer: false,
@@ -8329,24 +8690,111 @@ function createActiveAttempt(claim, durable, workingDirectory) {
8329
8690
  eventUploadQueue: Promise.resolve(),
8330
8691
  fatal,
8331
8692
  finished: new AbortController(),
8693
+ interruptedCleanupStarted: false,
8332
8694
  leaseDeadlineMilliseconds: parseLeaseDeadline(claim.leaseExpiresAt),
8333
8695
  nativeThreadId: durable.snapshot().nativeThreadId ?? claim.nativeThreadId,
8334
8696
  spoolQueue: Promise.resolve(),
8697
+ subagentThreadIds: /* @__PURE__ */ new Set(),
8335
8698
  terminal,
8336
8699
  resolveFatal,
8337
8700
  resolveTerminal,
8338
8701
  workingDirectory
8339
8702
  };
8340
8703
  }
8341
- function createInitialThreadNameState() {
8704
+ function createThreadTitleGenerationState(threadId) {
8342
8705
  let resolveCompletion = () => void 0;
8343
- const completion = new Promise((resolve9) => {
8344
- resolveCompletion = resolve9;
8706
+ const completion = new Promise((resolve10) => {
8707
+ resolveCompletion = resolve10;
8345
8708
  });
8346
- return {
8709
+ const state = {
8710
+ completed: false,
8347
8711
  completion,
8348
- resolve: resolveCompletion
8712
+ responseText: "",
8713
+ resolve: () => void 0,
8714
+ threadId
8349
8715
  };
8716
+ state.resolve = () => {
8717
+ if (state.completed) {
8718
+ return;
8719
+ }
8720
+ state.completed = true;
8721
+ resolveCompletion();
8722
+ };
8723
+ return state;
8724
+ }
8725
+ function captureThreadTitleGenerationNotification(active, message) {
8726
+ const generation = active.initialThreadName?.generation;
8727
+ if (generation === void 0 || appServerMessageThreadId(message).value !== generation.threadId) {
8728
+ return false;
8729
+ }
8730
+ const method = message.method;
8731
+ const params = safeRecord(message.params);
8732
+ if (method === "item/agentMessage/delta") {
8733
+ const delta = optionalString2(params.delta).value;
8734
+ if (delta !== void 0) {
8735
+ generation.responseText += delta;
8736
+ }
8737
+ } else if (method === "item/completed") {
8738
+ const item = safeRecord(params.item);
8739
+ const text3 = optionalString2(item.text).value;
8740
+ if (item.type === "agentMessage" && text3 !== void 0) {
8741
+ generation.responseText = text3;
8742
+ }
8743
+ } else if (method === "turn/started") {
8744
+ const turnId = optionalString2(safeRecord(params.turn).id).value;
8745
+ if (turnId !== void 0) {
8746
+ generation.turnId = turnId;
8747
+ }
8748
+ } else if (method === "turn/completed") {
8749
+ const turn = safeRecord(params.turn);
8750
+ generation.status = optionalString2(turn.status).value;
8751
+ const turnId = optionalString2(turn.id).value;
8752
+ if (turnId !== void 0) {
8753
+ generation.turnId = turnId;
8754
+ }
8755
+ generation.resolve();
8756
+ }
8757
+ return true;
8758
+ }
8759
+ function captureSubagentThreadIds(active, message) {
8760
+ if (message.method !== "item/started" && message.method !== "item/completed") {
8761
+ return;
8762
+ }
8763
+ const item = safeRecord(safeRecord(message.params).item);
8764
+ const agentThreadId = optionalString2(item.agentThreadId).value;
8765
+ if (agentThreadId !== void 0) {
8766
+ active.subagentThreadIds.add(agentThreadId);
8767
+ }
8768
+ if (!Array.isArray(item.receiverThreadIds)) {
8769
+ return;
8770
+ }
8771
+ for (const threadId of item.receiverThreadIds) {
8772
+ if (typeof threadId === "string") {
8773
+ active.subagentThreadIds.add(threadId);
8774
+ }
8775
+ }
8776
+ }
8777
+ function appServerMessageThreadId(message) {
8778
+ const params = safeRecord(message.params);
8779
+ const direct = optionalString2(params.threadId).value;
8780
+ if (direct !== void 0) {
8781
+ return { value: direct };
8782
+ }
8783
+ return optionalString2(safeRecord(params.thread).id);
8784
+ }
8785
+ function normalizeThreadTitle(value) {
8786
+ const title = Array.from(value.trim().replace(/\s+/g, " ")).slice(0, maximumThreadTitleCharacters).join("");
8787
+ return title === "" ? {} : { value: title };
8788
+ }
8789
+ function parseGeneratedThreadTitle(value) {
8790
+ let parsed;
8791
+ try {
8792
+ parsed = JSON.parse(value);
8793
+ } catch {
8794
+ return {};
8795
+ }
8796
+ const title = optionalString2(safeRecord(parsed).title).value;
8797
+ return title === void 0 ? {} : normalizeThreadTitle(title);
8350
8798
  }
8351
8799
  function fenceFor(claim, connectorInstanceId) {
8352
8800
  return {
@@ -8577,7 +9025,7 @@ function rpcIdentifier2(value) {
8577
9025
  }
8578
9026
  return {};
8579
9027
  }
8580
- function errorMessage2(error) {
9028
+ function errorMessage3(error) {
8581
9029
  return error instanceof Error ? error.message : String(error);
8582
9030
  }
8583
9031
  async function probeExecutable(executable, environment) {
@@ -8590,7 +9038,7 @@ async function probeExecutable(executable, environment) {
8590
9038
  const output = [];
8591
9039
  child.stdout?.on("data", (chunk) => output.push(chunk));
8592
9040
  try {
8593
- const code = await new Promise((resolve9, reject) => {
9041
+ const code = await new Promise((resolve10, reject) => {
8594
9042
  const timeout = setTimeout(() => {
8595
9043
  child.kill("SIGTERM");
8596
9044
  reject(new Error("Executable probe timed out"));
@@ -8602,7 +9050,7 @@ async function probeExecutable(executable, environment) {
8602
9050
  });
8603
9051
  child.once("close", (exitCode) => {
8604
9052
  clearTimeout(timeout);
8605
- resolve9(exitCode ?? 1);
9053
+ resolve10(exitCode ?? 1);
8606
9054
  });
8607
9055
  });
8608
9056
  if (code !== 0) {
@@ -8623,11 +9071,11 @@ async function waitForAbort(signal, milliseconds) {
8623
9071
  if (signal.aborted) {
8624
9072
  return;
8625
9073
  }
8626
- await new Promise((resolve9) => {
9074
+ await new Promise((resolve10) => {
8627
9075
  const complete = () => {
8628
9076
  clearTimeout(timeout);
8629
9077
  signal.removeEventListener("abort", complete);
8630
- resolve9();
9078
+ resolve10();
8631
9079
  };
8632
9080
  const timeout = setTimeout(complete, milliseconds);
8633
9081
  timeout.unref();
@@ -8641,14 +9089,15 @@ function parseLeaseDeadline(value) {
8641
9089
  }
8642
9090
  return parsed;
8643
9091
  }
8644
- var import_node_child_process4, import_promises12, import_node_path10, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, discoveryWaitSeconds, discoveryRetryMilliseconds, maximumDiscoveryDirectories, maximumDiscoveryModels, maximumModelListPages, eventUploadCoalesceMilliseconds, eventUploadRetryMilliseconds, maximumEventUploadCount, preferredEventUploadRequestBytes, leaseRenewIntervalMilliseconds, leaseRenewRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryRetryMilliseconds, initialThreadNameRetryMilliseconds, maximumThreadNameRetryMilliseconds, maximumInitialThreadNameAttempts, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, LocalCodexRuntimeConnectionWorker;
9092
+ var import_node_child_process4, import_promises13, import_node_os7, import_node_path11, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, discoveryWaitSeconds, discoveryRetryMilliseconds, maximumDiscoveryDirectories, maximumDiscoveryModels, maximumModelListPages, eventUploadCoalesceMilliseconds, eventUploadRetryMilliseconds, maximumEventUploadCount, preferredEventUploadRequestBytes, leaseRenewIntervalMilliseconds, leaseRenewRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryRetryMilliseconds, initialThreadNameRetryMilliseconds, maximumThreadNameRetryMilliseconds, maximumInitialThreadNameAttempts, maximumThreadTitleCharacters, maximumThreadTitleSourceCharacters, threadTitleGenerationTimeoutMilliseconds, interruptedExecutionCleanupTimeoutMilliseconds, threadTitleGenerationInstructions, threadTitleGenerationOutputSchema, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, LocalCodexRuntimeConnectionWorker;
8645
9093
  var init_runtime_worker = __esm({
8646
9094
  "../machine-connector/dist/runtime/local-codex-runtime/runtime-worker.js"() {
8647
9095
  "use strict";
8648
9096
  init_cjs_shims();
8649
9097
  import_node_child_process4 = require("child_process");
8650
- import_promises12 = require("fs/promises");
8651
- import_node_path10 = require("path");
9098
+ import_promises13 = require("fs/promises");
9099
+ import_node_os7 = require("os");
9100
+ import_node_path11 = require("path");
8652
9101
  init_process_executor();
8653
9102
  init_relay_client();
8654
9103
  init_app_server_client();
@@ -8675,6 +9124,23 @@ var init_runtime_worker = __esm({
8675
9124
  initialThreadNameRetryMilliseconds = 250;
8676
9125
  maximumThreadNameRetryMilliseconds = 2e3;
8677
9126
  maximumInitialThreadNameAttempts = 8;
9127
+ maximumThreadTitleCharacters = 40;
9128
+ maximumThreadTitleSourceCharacters = 4e3;
9129
+ threadTitleGenerationTimeoutMilliseconds = 2e4;
9130
+ interruptedExecutionCleanupTimeoutMilliseconds = 3e3;
9131
+ threadTitleGenerationInstructions = "Generate a concise semantic UI title for a coding conversation from its opening request. Use the request language. Prefer a specific noun phrase over a sentence, omit filler and incidental identifiers, and do not copy the full request unless it is already concise. Return only the structured result.";
9132
+ threadTitleGenerationOutputSchema = {
9133
+ additionalProperties: false,
9134
+ properties: {
9135
+ title: {
9136
+ maxLength: maximumThreadTitleCharacters,
9137
+ minLength: 1,
9138
+ type: "string"
9139
+ }
9140
+ },
9141
+ required: ["title"],
9142
+ type: "object"
9143
+ };
8678
9144
  ThreadUnavailableError = class extends Error {
8679
9145
  constructor(message) {
8680
9146
  super(message);
@@ -8710,6 +9176,7 @@ var init_runtime_worker = __esm({
8710
9176
  active = {};
8711
9177
  configured = false;
8712
9178
  enabled = false;
9179
+ lastCapabilityStartError;
8713
9180
  lifetimeAbort = new AbortController();
8714
9181
  registered = true;
8715
9182
  unrecoverableAttemptIds = /* @__PURE__ */ new Set();
@@ -8747,6 +9214,9 @@ var init_runtime_worker = __esm({
8747
9214
  if (active === void 0 || active.finished.signal.aborted) {
8748
9215
  return;
8749
9216
  }
9217
+ if (captureThreadTitleGenerationNotification(active, message)) {
9218
+ return;
9219
+ }
8750
9220
  const normalized = normalizeAppServerNotification(message, active.workingDirectory).value;
8751
9221
  if (normalized === void 0) {
8752
9222
  return;
@@ -8755,8 +9225,13 @@ var init_runtime_worker = __esm({
8755
9225
  if (normalized.correlation.nativeThreadId !== void 0 && active.nativeThreadId !== void 0 && normalized.correlation.nativeThreadId !== active.nativeThreadId) {
8756
9226
  return;
8757
9227
  }
8758
- if (normalized.kind === "thread_title_updated" && normalized.payload.title === initialThreadName?.projectedTitle) {
8759
- return;
9228
+ if (normalized.kind === "thread_title_updated") {
9229
+ if (initialThreadName?.terminalObserved === true) {
9230
+ return;
9231
+ }
9232
+ if (normalized.payload.title === initialThreadName?.projectedTitle) {
9233
+ return;
9234
+ }
8760
9235
  }
8761
9236
  const notificationTurnId = normalized.correlation.nativeTurnId;
8762
9237
  if (notificationTurnId !== void 0) {
@@ -8772,12 +9247,20 @@ var init_runtime_worker = __esm({
8772
9247
  return;
8773
9248
  }
8774
9249
  }
9250
+ captureSubagentThreadIds(active, message);
8775
9251
  if (normalized.terminalStatus !== void 0 && initialThreadName !== void 0) {
8776
- await initialThreadName.completion;
8777
- if (active.finished.signal.aborted) {
8778
- return;
8779
- }
9252
+ initialThreadName.terminalObserved = true;
8780
9253
  }
9254
+ if (normalized.terminalStatus === LocalCodexTurnStatusWire.Interrupted) {
9255
+ await this.stopInterruptedExecution(active, normalized);
9256
+ return;
9257
+ }
9258
+ if (normalized.terminalStatus !== void 0 && initialThreadName !== void 0 && !initialThreadName.completed) {
9259
+ this.completeInitialThreadName(active);
9260
+ }
9261
+ this.persistNormalizedNotification(active, normalized);
9262
+ }
9263
+ persistNormalizedNotification(active, normalized) {
8781
9264
  void this.enqueueSpool(active, async () => {
8782
9265
  const persisted = await active.durable.appendEvent(normalized.kind, normalized.payload, normalized.correlation);
8783
9266
  if (normalized.correlation.nativeThreadId !== void 0 && active.nativeThreadId === void 0) {
@@ -8795,6 +9278,45 @@ var init_runtime_worker = __esm({
8795
9278
  }).catch(() => void 0);
8796
9279
  void this.enqueueEventFlush(active).catch(() => void 0);
8797
9280
  }
9281
+ async stopInterruptedExecution(active, normalized) {
9282
+ active.interruptedCleanupStarted = true;
9283
+ active.initialThreadName?.generation?.resolve();
9284
+ const client = this.processPool.currentClient().value;
9285
+ if (client !== void 0 && active.nativeThreadId !== void 0) {
9286
+ await Promise.all([active.nativeThreadId, ...active.subagentThreadIds].map(async (threadId) => {
9287
+ try {
9288
+ await client.requestWithin("thread/backgroundTerminals/clean", { threadId }, interruptedExecutionCleanupTimeoutMilliseconds);
9289
+ } catch (error) {
9290
+ await this.logger.error(`Failed to clean background terminals for interrupted Local Codex thread ${threadId}; stopping its App Server process tree`, error);
9291
+ }
9292
+ }));
9293
+ }
9294
+ try {
9295
+ await this.processPool.quarantineCurrentProcess(active.processTreeCapture);
9296
+ } catch (error) {
9297
+ const failure = error instanceof Error ? error : new AppServerProcessLostError(String(error));
9298
+ await this.enqueueSpool(active, async () => {
9299
+ const terminal = await active.durable.appendEvent("turn_failed", {
9300
+ message: failure.message,
9301
+ status: "runtime_lost"
9302
+ }, {
9303
+ nativeThreadId: active.nativeThreadId,
9304
+ nativeTurnId: active.nativeTurnId
9305
+ });
9306
+ const result = {
9307
+ errorCode: "runtime_lost",
9308
+ errorMessage: failure.message,
9309
+ finalSequence: terminal.sequence,
9310
+ status: LocalCodexTurnStatusWire.RuntimeLost
9311
+ };
9312
+ await active.durable.markTerminal(result);
9313
+ this.settleTerminal(active, result);
9314
+ });
9315
+ return;
9316
+ }
9317
+ this.completeInitialThreadName(active);
9318
+ this.persistNormalizedNotification(active, normalized);
9319
+ }
8798
9320
  async onServerRequest(message) {
8799
9321
  const active = this.active.value;
8800
9322
  const client = this.processPool.currentClient().value;
@@ -8805,6 +9327,11 @@ var init_runtime_worker = __esm({
8805
9327
  }
8806
9328
  return;
8807
9329
  }
9330
+ const titleGeneration = active.initialThreadName?.generation;
9331
+ if (titleGeneration !== void 0 && appServerMessageThreadId(message).value === titleGeneration.threadId) {
9332
+ await client.respondWithError(message.id, -32601, "Thread title generation does not support interactive tools");
9333
+ return;
9334
+ }
8808
9335
  const interactionKind = interactionKindFor(message.method, message.params).value;
8809
9336
  if (interactionKind === void 0) {
8810
9337
  await client.respondWithError(message.id, -32601, `Unsupported Local Codex interaction ${message.method}`);
@@ -8837,6 +9364,7 @@ var init_runtime_worker = __esm({
8837
9364
  if (active === void 0 || !active.acceptedByAppServer) {
8838
9365
  return;
8839
9366
  }
9367
+ active.initialThreadName?.generation?.resolve();
8840
9368
  await this.enqueueSpool(active, async () => {
8841
9369
  await active.durable.appendEvent("runtime_error", { message: error.message }, {
8842
9370
  nativeThreadId: active.nativeThreadId,
@@ -8871,6 +9399,10 @@ var init_runtime_worker = __esm({
8871
9399
  }
8872
9400
  async runHeartbeatLoop() {
8873
9401
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9402
+ if (this.active.value?.interruptedCleanupStarted) {
9403
+ await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
9404
+ continue;
9405
+ }
8874
9406
  try {
8875
9407
  await this.ensureCapability();
8876
9408
  const response = await this.sendHeartbeat();
@@ -9000,7 +9532,7 @@ var init_runtime_worker = __esm({
9000
9532
  async discoverDirectories(relativeDirectory) {
9001
9533
  const canonicalRoot = await resolveCanonicalWorkingDirectory(this.connection.rootPath, ".");
9002
9534
  const canonicalDirectory = await resolveCanonicalWorkingDirectory(canonicalRoot, relativeDirectory);
9003
- const entries = (await (0, import_promises12.readdir)(canonicalDirectory, {
9535
+ const entries = (await (0, import_promises13.readdir)(canonicalDirectory, {
9004
9536
  withFileTypes: true
9005
9537
  })).filter((entry) => entry.isDirectory()).filter((entry) => !entry.name.includes("\\")).sort((left, right) => left.name.localeCompare(right.name, void 0, {
9006
9538
  numeric: true,
@@ -9008,11 +9540,11 @@ var init_runtime_worker = __esm({
9008
9540
  }));
9009
9541
  const eligibleDirectories = entries.map((entry) => ({
9010
9542
  name: entry.name,
9011
- relativePath: portableRelativeDirectory((0, import_node_path10.relative)(canonicalRoot, (0, import_node_path10.join)(canonicalDirectory, entry.name)))
9543
+ relativePath: portableRelativeDirectory((0, import_node_path11.relative)(canonicalRoot, (0, import_node_path11.join)(canonicalDirectory, entry.name)))
9012
9544
  })).filter((entry) => entry.name.length <= 255 && entry.relativePath.length <= 1024);
9013
9545
  const directories = eligibleDirectories.slice(0, maximumDiscoveryDirectories);
9014
9546
  return {
9015
- currentRelativeDirectory: portableRelativeDirectory((0, import_node_path10.relative)(canonicalRoot, canonicalDirectory)),
9547
+ currentRelativeDirectory: portableRelativeDirectory((0, import_node_path11.relative)(canonicalRoot, canonicalDirectory)),
9016
9548
  directories,
9017
9549
  truncated: eligibleDirectories.length > maximumDiscoveryDirectories
9018
9550
  };
@@ -9042,7 +9574,10 @@ var init_runtime_worker = __esm({
9042
9574
  await durable.markThreadPrepared(nativeThreadId);
9043
9575
  await active.spoolQueue;
9044
9576
  if (isNewThread) {
9045
- active.initialThreadName = createInitialThreadNameState();
9577
+ active.initialThreadName = {
9578
+ completed: false,
9579
+ terminalObserved: false
9580
+ };
9046
9581
  }
9047
9582
  if (isNewThread && !active.durable.snapshot().events.some((event2) => event2.kind === "thread_started")) {
9048
9583
  await active.durable.appendEvent("thread_started", {}, { nativeThreadId });
@@ -9072,18 +9607,24 @@ var init_runtime_worker = __esm({
9072
9607
  active.nativeTurnId = nativeTurnId;
9073
9608
  active.acceptedByAppServer = true;
9074
9609
  await durable.markRunning(nativeThreadId, nativeTurnId);
9610
+ if (isNewThread) {
9611
+ const initialThreadName = active.initialThreadName;
9612
+ if (initialThreadName === void 0) {
9613
+ throw new AppServerProtocolError("Initial thread name state is unavailable");
9614
+ }
9615
+ initialThreadName.task = this.setInitialThreadName(client, active, nativeThreadId).catch(async (error) => {
9616
+ if (!initialThreadName.completed) {
9617
+ await this.logger.error(`Failed to initialize the Local Codex thread name for ${nativeThreadId}`, error);
9618
+ }
9619
+ }).finally(() => {
9620
+ this.completeInitialThreadName(active);
9621
+ });
9622
+ }
9075
9623
  await this.retryStateUpdate(active, {
9076
9624
  nativeTurnId,
9077
9625
  status: LocalCodexTurnStatusWire.Running
9078
9626
  });
9079
9627
  await this.interruptActiveTurnIfRequested(active, client);
9080
- if (isNewThread) {
9081
- try {
9082
- await this.setInitialThreadName(client, active, nativeThreadId);
9083
- } finally {
9084
- active.initialThreadName?.resolve();
9085
- }
9086
- }
9087
9628
  const terminal = await Promise.race([
9088
9629
  active.terminal,
9089
9630
  active.fatal.then((error) => {
@@ -9102,11 +9643,19 @@ var init_runtime_worker = __esm({
9102
9643
  });
9103
9644
  await durable.markUploaded();
9104
9645
  await this.store.deleteLocalCodexAttempt(claim.attemptId);
9646
+ if (active.interruptedCleanupStarted) {
9647
+ active.finished.abort();
9648
+ await this.restoreAppServerAfterInterruption(active);
9649
+ }
9105
9650
  } catch (error) {
9106
9651
  if (error instanceof LeaseLostError) {
9107
9652
  await this.logger.error(`Local Codex attempt ${claim.attemptId} stopped after losing its execution lease`, error);
9108
9653
  } else if (error instanceof SpoolPersistenceError) {
9109
- await this.processPool.quarantineCurrentProcess();
9654
+ try {
9655
+ await this.processPool.quarantineCurrentProcess();
9656
+ } catch (cleanupError) {
9657
+ await this.logger.error(`Failed to quarantine the Codex App Server after Local Codex attempt ${claim.attemptId} lost its durable spool`, cleanupError);
9658
+ }
9110
9659
  await this.logger.error(`Local Codex attempt ${claim.attemptId} stopped after its durable spool failed`, error);
9111
9660
  } else if (!active.acceptedByAppServer && error instanceof AppServerProcessLostError) {
9112
9661
  await this.logger.error(`Local Codex attempt ${claim.attemptId} failed before App Server accepted the turn; it remains reclaimable`, error);
@@ -9114,11 +9663,16 @@ var init_runtime_worker = __esm({
9114
9663
  await this.failAttempt(active, error);
9115
9664
  }
9116
9665
  } finally {
9117
- active.initialThreadName?.resolve();
9666
+ this.completeInitialThreadName(active);
9667
+ active.finished.abort();
9668
+ await active.initialThreadName?.task;
9669
+ const titleGenerationTurnId = active.initialThreadName?.generation?.turnId;
9670
+ if (titleGenerationTurnId !== void 0) {
9671
+ this.processPool.retireTurn(titleGenerationTurnId);
9672
+ }
9118
9673
  if (active.acceptedByAppServer && active.nativeTurnId !== void 0) {
9119
9674
  this.processPool.retireTurn(active.nativeTurnId);
9120
9675
  }
9121
- active.finished.abort();
9122
9676
  await Promise.all([leaseLoop, controlLoop]);
9123
9677
  }
9124
9678
  }
@@ -9126,7 +9680,10 @@ var init_runtime_worker = __esm({
9126
9680
  const claim = active.claim;
9127
9681
  const parameters = {
9128
9682
  approvalPolicy: claim.approvalPolicy,
9129
- config: { model_reasoning_effort: claim.reasoningEffort },
9683
+ config: {
9684
+ model_reasoning_effort: claim.reasoningEffort,
9685
+ ...claim.developerInstructions === void 0 || claim.developerInstructions.length === 0 ? {} : { developer_instructions: claim.developerInstructions }
9686
+ },
9130
9687
  cwd: active.workingDirectory,
9131
9688
  ephemeral: false,
9132
9689
  ...claim.model === void 0 ? {} : { model: claim.model },
@@ -9157,7 +9714,7 @@ var init_runtime_worker = __esm({
9157
9714
  throw error;
9158
9715
  }
9159
9716
  if (error instanceof AppServerResponseError && isMissingThreadResponse(error.responseMessage, preparedThreadId)) {
9160
- throw new ThreadUnavailableError(errorMessage2(error));
9717
+ throw new ThreadUnavailableError(errorMessage3(error));
9161
9718
  }
9162
9719
  throw error;
9163
9720
  }
@@ -9174,13 +9731,13 @@ var init_runtime_worker = __esm({
9174
9731
  try {
9175
9732
  const createdResult = {};
9176
9733
  await this.enqueueSpool(active, async () => {
9177
- const terminal = await active.durable.appendEvent("turn_failed", { message: errorMessage2(error), status: errorCode2 }, {
9734
+ const terminal = await active.durable.appendEvent("turn_failed", { message: errorMessage3(error), status: errorCode2 }, {
9178
9735
  nativeThreadId: active.nativeThreadId,
9179
9736
  nativeTurnId: active.nativeTurnId
9180
9737
  });
9181
9738
  const result2 = {
9182
9739
  errorCode: errorCode2,
9183
- errorMessage: errorMessage2(error),
9740
+ errorMessage: errorMessage3(error),
9184
9741
  finalSequence: terminal.sequence,
9185
9742
  status
9186
9743
  };
@@ -9303,7 +9860,7 @@ var init_runtime_worker = __esm({
9303
9860
  }
9304
9861
  await this.logger.error(`Failed to renew Local Codex attempt ${active.claim.attemptId}`, error);
9305
9862
  if (error instanceof LeaseLostError || error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
9306
- await this.loseLease(active, errorMessage2(error));
9863
+ await this.loseLease(active, errorMessage3(error));
9307
9864
  return;
9308
9865
  }
9309
9866
  const retryRemaining = active.leaseDeadlineMilliseconds - Date.now();
@@ -9356,7 +9913,7 @@ var init_runtime_worker = __esm({
9356
9913
  } catch (error) {
9357
9914
  if (!active.finished.signal.aborted) {
9358
9915
  if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
9359
- await this.loseLease(active, errorMessage2(error));
9916
+ await this.loseLease(active, errorMessage3(error));
9360
9917
  return;
9361
9918
  }
9362
9919
  await this.logger.error(`Failed to poll Local Codex controls for ${active.claim.attemptId}`, error);
@@ -9429,6 +9986,7 @@ var init_runtime_worker = __esm({
9429
9986
  if (!active.abortRequested || active.abortSent || active.nativeThreadId === void 0 || active.nativeTurnId === void 0) {
9430
9987
  return;
9431
9988
  }
9989
+ active.processTreeCapture = (await this.processPool.captureCurrentProcessTree()).value;
9432
9990
  await client.request("turn/interrupt", {
9433
9991
  threadId: active.nativeThreadId,
9434
9992
  turnId: active.nativeTurnId
@@ -9548,7 +10106,7 @@ var init_runtime_worker = __esm({
9548
10106
  await action();
9549
10107
  });
9550
10108
  active.spoolQueue = operation.catch((error) => {
9551
- const failure = new SpoolPersistenceError(`Durable Local Codex spool failed: ${errorMessage2(error)}`, {
10109
+ const failure = new SpoolPersistenceError(`Durable Local Codex spool failed: ${errorMessage3(error)}`, {
9552
10110
  cause: error
9553
10111
  });
9554
10112
  this.signalFatal(active, failure);
@@ -9565,19 +10123,41 @@ var init_runtime_worker = __esm({
9565
10123
  async ensureCapability() {
9566
10124
  try {
9567
10125
  await this.processPool.ensureStarted();
9568
- } catch {
10126
+ this.lastCapabilityStartError = void 0;
10127
+ } catch (error) {
10128
+ const unavailableReason = this.processPool.currentUnavailableReason().value;
10129
+ const errorSignature = unavailableReason ?? errorMessage3(error);
10130
+ if (this.lastCapabilityStartError === errorSignature) {
10131
+ return;
10132
+ }
10133
+ await this.logger.error(`Failed to start the shared Codex App Server for Local Codex connection ${this.connection.connectionId}`, error);
10134
+ this.lastCapabilityStartError = errorSignature;
10135
+ }
10136
+ }
10137
+ async restoreAppServerAfterInterruption(active) {
10138
+ if (this.lifetimeAbort.signal.aborted || this.relay.isRevoked()) {
9569
10139
  return;
9570
10140
  }
10141
+ try {
10142
+ await this.processPool.ensureStarted();
10143
+ this.applyHeartbeatResponse(await this.sendHeartbeat());
10144
+ } catch (error) {
10145
+ this.configured = false;
10146
+ this.enabled = false;
10147
+ await this.logger.error(`Failed to restore the shared Codex App Server after interrupting thread ${active.nativeThreadId ?? "unknown"}`, error);
10148
+ }
9571
10149
  }
9572
10150
  async sendHeartbeat() {
9573
10151
  const capability = this.processPool.status();
10152
+ const unavailableReason = this.processPool.currentUnavailableReason().value;
9574
10153
  const moxt = await probeExecutable(process.env.MOXT_CLI_PATH ?? "moxt", this.environment);
9575
10154
  return await this.relay.heartbeatCodexRuntime({
9576
10155
  ...capability,
9577
10156
  connectorInstanceId: this.connectorInstanceId,
9578
10157
  moxtCliStatus: moxt.status,
9579
10158
  moxtCliVersion: moxt.version,
9580
- protocolVersion: localCodexRuntimeProtocolVersion
10159
+ protocolVersion: localCodexRuntimeProtocolVersion,
10160
+ ...unavailableReason === void 0 ? {} : { unavailableReason }
9581
10161
  });
9582
10162
  }
9583
10163
  applyHeartbeatResponse(response) {
@@ -9590,21 +10170,138 @@ var init_runtime_worker = __esm({
9590
10170
  }
9591
10171
  async setInitialThreadName(client, active, threadId) {
9592
10172
  const claim = active.claim;
9593
- if (claim.executionContext.workflowTaskId !== void 0 || claim.executionContext.workflowWatcherId !== void 0) {
10173
+ const initialThreadName = active.initialThreadName;
10174
+ if (initialThreadName === void 0 || initialThreadName.completed || active.interruptedCleanupStarted || claim.executionContext.workflowTaskId !== void 0 || claim.executionContext.workflowWatcherId !== void 0) {
9594
10175
  return;
9595
10176
  }
9596
10177
  const text3 = firstTextInput(claim).value;
9597
10178
  if (text3 === void 0) {
9598
10179
  return;
9599
10180
  }
9600
- const name = Array.from(text3.trim().replace(/\s+/g, " ")).slice(0, 40).join("");
9601
- if (name === "") {
10181
+ const fallbackName = normalizeThreadTitle(text3).value;
10182
+ if (fallbackName === void 0) {
10183
+ return;
10184
+ }
10185
+ let name = fallbackName;
10186
+ try {
10187
+ const generatedName = await this.generateInitialThreadName(client, active, threadId, text3);
10188
+ if (initialThreadName.completed) {
10189
+ return;
10190
+ }
10191
+ if (generatedName.value === void 0) {
10192
+ throw new AppServerProtocolError("Codex returned no valid semantic thread title");
10193
+ }
10194
+ name = generatedName.value;
10195
+ } catch (error) {
10196
+ if (initialThreadName.completed || active.interruptedCleanupStarted) {
10197
+ return;
10198
+ }
10199
+ await this.logger.error(`Failed to generate a semantic title for Local Codex thread ${threadId}; using the opening request`, error);
10200
+ }
10201
+ if (initialThreadName.completed || active.interruptedCleanupStarted) {
10202
+ return;
10203
+ }
10204
+ await this.applyInitialThreadName(client, active, threadId, name);
10205
+ }
10206
+ async generateInitialThreadName(client, active, targetThreadId, openingRequest) {
10207
+ const initialThreadName = active.initialThreadName;
10208
+ if (initialThreadName === void 0) {
10209
+ throw new AppServerProtocolError("Initial thread name state is unavailable");
10210
+ }
10211
+ if (initialThreadName.completed) {
10212
+ return {};
10213
+ }
10214
+ const titleDirectory = (0, import_node_os7.tmpdir)();
10215
+ const titleThreadId = requireThreadId(await client.request("thread/start", {
10216
+ approvalPolicy: "never",
10217
+ baseInstructions: threadTitleGenerationInstructions,
10218
+ config: { model_reasoning_effort: "low" },
10219
+ cwd: titleDirectory,
10220
+ dynamicTools: [],
10221
+ ephemeral: true,
10222
+ ...active.claim.model === void 0 ? {} : { model: active.claim.model },
10223
+ sandbox: "read-only",
10224
+ serviceName: "moxt-title-generation",
10225
+ threadSource: "title_generation"
10226
+ }));
10227
+ if (initialThreadName.completed) {
10228
+ return {};
10229
+ }
10230
+ if (titleThreadId === targetThreadId) {
10231
+ throw new AppServerProtocolError("Codex reused the visible thread for title generation");
10232
+ }
10233
+ const generation = createThreadTitleGenerationState(titleThreadId);
10234
+ initialThreadName.generation = generation;
10235
+ const titleInput = Array.from(openingRequest.trim()).slice(0, maximumThreadTitleSourceCharacters).join("");
10236
+ const response = await client.request("turn/start", {
10237
+ approvalPolicy: "never",
10238
+ cwd: titleDirectory,
10239
+ effort: "low",
10240
+ input: [
10241
+ {
10242
+ text: `Generate the title for this opening request:
10243
+
10244
+ ${titleInput}`,
10245
+ type: "text"
10246
+ }
10247
+ ],
10248
+ outputSchema: threadTitleGenerationOutputSchema,
10249
+ sandboxPolicy: { networkAccess: false, type: "readOnly" },
10250
+ threadId: titleThreadId
10251
+ });
10252
+ const titleTurnId = requireTurnId(response);
10253
+ if (generation.turnId !== void 0 && generation.turnId !== titleTurnId) {
10254
+ throw new AppServerProtocolError("Codex title generation crossed its turn boundary");
10255
+ }
10256
+ generation.turnId = titleTurnId;
10257
+ if (initialThreadName.completed) {
10258
+ if (generation.status !== "completed") {
10259
+ this.interruptInitialThreadNameGeneration(client, targetThreadId, generation);
10260
+ }
10261
+ return {};
10262
+ }
10263
+ await Promise.race([
10264
+ generation.completion,
10265
+ waitForAbort(active.finished.signal, threadTitleGenerationTimeoutMilliseconds),
10266
+ active.fatal.then(() => void 0)
10267
+ ]);
10268
+ if (initialThreadName.completed) {
10269
+ if (generation.status !== "completed") {
10270
+ this.interruptInitialThreadNameGeneration(client, targetThreadId, generation);
10271
+ }
10272
+ return {};
10273
+ }
10274
+ if (!generation.completed) {
10275
+ this.interruptInitialThreadNameGeneration(client, targetThreadId, generation);
10276
+ throw new AppServerProtocolError("Codex semantic thread title generation timed out");
10277
+ }
10278
+ this.processPool.retireTurn(titleTurnId);
10279
+ if (generation.status !== "completed") {
10280
+ throw new AppServerProtocolError(`Codex semantic thread title generation ended with status ${generation.status ?? "unknown"}`);
10281
+ }
10282
+ return parseGeneratedThreadTitle(generation.responseText);
10283
+ }
10284
+ interruptInitialThreadNameGeneration(client, targetThreadId, generation) {
10285
+ if (generation.turnId === void 0) {
9602
10286
  return;
9603
10287
  }
10288
+ this.processPool.retireTurn(generation.turnId);
10289
+ void client.request("turn/interrupt", {
10290
+ threadId: generation.threadId,
10291
+ turnId: generation.turnId
10292
+ }).catch(async (error) => {
10293
+ await this.logger.error(`Failed to interrupt title generation for Local Codex thread ${targetThreadId}`, error);
10294
+ });
10295
+ }
10296
+ async applyInitialThreadName(client, active, threadId, name) {
9604
10297
  const signal = active.finished.signal;
10298
+ const initialThreadName = active.initialThreadName;
10299
+ if (initialThreadName === void 0) {
10300
+ throw new AppServerProtocolError("Initial thread name state is unavailable");
10301
+ }
9605
10302
  let retryMilliseconds = initialThreadNameRetryMilliseconds;
9606
10303
  for (let attempt = 1; attempt <= maximumInitialThreadNameAttempts; attempt += 1) {
9607
- if (signal.aborted) {
10304
+ if (signal.aborted || initialThreadName.completed) {
9608
10305
  return;
9609
10306
  }
9610
10307
  try {
@@ -9613,6 +10310,9 @@ var init_runtime_worker = __esm({
9613
10310
  threadId
9614
10311
  });
9615
10312
  } catch (error) {
10313
+ if (initialThreadName.completed) {
10314
+ return;
10315
+ }
9616
10316
  const metadataPending = error instanceof AppServerResponseError && isThreadNameMetadataPendingResponse(error.responseMessage);
9617
10317
  if (!metadataPending || attempt === maximumInitialThreadNameAttempts) {
9618
10318
  await this.logger.error(`Failed to name Local Codex thread ${threadId}`, error);
@@ -9622,9 +10322,8 @@ var init_runtime_worker = __esm({
9622
10322
  retryMilliseconds = Math.min(retryMilliseconds * 2, maximumThreadNameRetryMilliseconds);
9623
10323
  continue;
9624
10324
  }
9625
- const initialThreadName = active.initialThreadName;
9626
- if (initialThreadName === void 0) {
9627
- throw new AppServerProtocolError("Initial thread name state is unavailable");
10325
+ if (initialThreadName.completed) {
10326
+ return;
9628
10327
  }
9629
10328
  initialThreadName.projectedTitle = name;
9630
10329
  await this.enqueueSpool(active, async () => {
@@ -9639,6 +10338,14 @@ var init_runtime_worker = __esm({
9639
10338
  return;
9640
10339
  }
9641
10340
  }
10341
+ completeInitialThreadName(active) {
10342
+ const initialThreadName = active.initialThreadName;
10343
+ if (initialThreadName === void 0 || initialThreadName.completed) {
10344
+ return;
10345
+ }
10346
+ initialThreadName.completed = true;
10347
+ initialThreadName.generation?.resolve();
10348
+ }
9642
10349
  unregisterRoute() {
9643
10350
  if (!this.registered) {
9644
10351
  return;
@@ -9783,12 +10490,19 @@ var init_process_pool = __esm({
9783
10490
  currentClient() {
9784
10491
  return this.supervisor.currentClient();
9785
10492
  }
10493
+ currentUnavailableReason() {
10494
+ return this.supervisor.currentUnavailableReason();
10495
+ }
9786
10496
  async ensureStarted() {
9787
10497
  return await this.supervisor.ensureStarted();
9788
10498
  }
9789
- async quarantineCurrentProcess() {
10499
+ async captureCurrentProcessTree() {
10500
+ const client = this.supervisor.currentClient().value;
10501
+ return client === void 0 ? {} : { value: await client.captureProcessTree() };
10502
+ }
10503
+ async quarantineCurrentProcess(capture) {
9790
10504
  this.loadedThreadIds.clear();
9791
- await this.supervisor.quarantineCurrentProcess();
10505
+ await this.supervisor.quarantineCurrentProcess(capture);
9792
10506
  }
9793
10507
  async stop() {
9794
10508
  this.loadedThreadIds.clear();
@@ -9830,12 +10544,12 @@ function delay4(milliseconds) {
9830
10544
  setTimeout(resolvePromise, milliseconds);
9831
10545
  });
9832
10546
  }
9833
- var import_node_os6, import_node_crypto9, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, commandOutputBatchMaxBytes, commandOutputFlushIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
10547
+ var import_node_os8, import_node_crypto9, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, commandOutputBatchMaxBytes, commandOutputFlushIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
9834
10548
  var init_daemon = __esm({
9835
10549
  "../machine-connector/dist/runtime/daemon.js"() {
9836
10550
  "use strict";
9837
10551
  init_cjs_shims();
9838
- import_node_os6 = require("os");
10552
+ import_node_os8 = require("os");
9839
10553
  import_node_crypto9 = require("crypto");
9840
10554
  init_enums();
9841
10555
  init_contracts();
@@ -9952,7 +10666,7 @@ var init_daemon = __esm({
9952
10666
  this.throwIfStopping();
9953
10667
  await this.logger.info("Moxt Machine Connector started", {
9954
10668
  connectorInstanceId: this.connectorInstanceId,
9955
- hostname: (0, import_node_os6.hostname)(),
10669
+ hostname: (0, import_node_os8.hostname)(),
9956
10670
  version: connectorVersion
9957
10671
  });
9958
10672
  this.connections = await this.store.listConnections();
@@ -9983,21 +10697,35 @@ var init_daemon = __esm({
9983
10697
  }
9984
10698
  async stop() {
9985
10699
  this.stopping = true;
9986
- await Promise.all([...this.activeJobs.values()].map(async (activeJob) => {
9987
- await activeJob.cancellation.request(ExecutionCancellationReason.Stopping);
9988
- }));
9989
- await Promise.all([...this.localCodexWorkers.values()].map(async (worker) => await worker.stop()));
9990
- await Promise.all([...this.localCodexProcessPools.values()].map(async (pool) => await pool.stop()));
9991
- await this.startupSettled;
9992
- await this.ipcServer?.close();
9993
- this.ipcServer = void 0;
9994
- await this.lifetimeSettled;
9995
10700
  try {
10701
+ await Promise.all([...this.activeJobs.values()].map(async (activeJob) => {
10702
+ await this.stopRuntimeComponent(`Failed to cancel Local Machine Job ${activeJob.claim.jobId} while stopping`, async () => await activeJob.cancellation.request(ExecutionCancellationReason.Stopping));
10703
+ }));
10704
+ await Promise.all([...this.localCodexWorkers.entries()].map(async ([connectionId, worker]) => {
10705
+ await this.stopRuntimeComponent(`Failed to stop Local Codex worker ${connectionId}`, async () => await worker.stop());
10706
+ }));
10707
+ await Promise.all([...this.localCodexProcessPools.values()].map(async (pool) => {
10708
+ await this.stopRuntimeComponent(`Failed to stop Local Codex App Server pool ${pool.poolKey}`, async () => await pool.stop());
10709
+ }));
10710
+ await this.stopRuntimeComponent("Failed while waiting for Moxt Machine Connector startup to settle", async () => await this.startupSettled);
10711
+ await this.stopRuntimeComponent("Failed to close Moxt Machine Connector IPC server", async () => {
10712
+ await this.ipcServer?.close();
10713
+ });
10714
+ this.ipcServer = void 0;
10715
+ await this.stopRuntimeComponent("Failed while waiting for Moxt Machine Connector lifetime to settle", async () => await this.lifetimeSettled);
9996
10716
  await this.logger.info("Moxt Machine Connector stopped");
9997
10717
  } finally {
10718
+ this.ipcServer = void 0;
9998
10719
  await this.releaseDaemonLock();
9999
10720
  }
10000
10721
  }
10722
+ async stopRuntimeComponent(message, action) {
10723
+ try {
10724
+ await action();
10725
+ } catch (error) {
10726
+ await this.logger.error(message, error);
10727
+ }
10728
+ }
10001
10729
  getStatus() {
10002
10730
  return {
10003
10731
  activeJobs: [...this.activeJobs.values()].map((activeJob) => {
@@ -10863,10 +11591,10 @@ async function installUserService(store, request2, runtime = defaultServiceManag
10863
11591
  manager: selection.manager
10864
11592
  };
10865
11593
  }
10866
- const candidates = await automaticManagerCandidates(store, capabilities);
11594
+ const candidates2 = await automaticManagerCandidates(store, capabilities);
10867
11595
  const failures = [];
10868
11596
  let cleanupFailed = false;
10869
- for (const manager of candidates) {
11597
+ for (const manager of candidates2) {
10870
11598
  try {
10871
11599
  await replaceConfiguredManager(store, manager, options, runtime);
10872
11600
  return {
@@ -10896,12 +11624,12 @@ async function installUserService(store, request2, runtime = defaultServiceManag
10896
11624
  }
10897
11625
  function createServiceEnvironment(options) {
10898
11626
  const inheritedPath = options.environment.PATH ?? process.env.PATH ?? "";
10899
- const nodeDirectory = (0, import_node_path11.dirname)(options.nodePath);
10900
- const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path11.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
11627
+ const nodeDirectory = (0, import_node_path12.dirname)(options.nodePath);
11628
+ const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path12.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
10901
11629
  return {
10902
11630
  ...options.environment,
10903
- HOME: options.environment.HOME ?? process.env.HOME ?? (0, import_node_os7.homedir)(),
10904
- PATH: pathEntries.join(import_node_path11.delimiter)
11631
+ HOME: options.environment.HOME ?? process.env.HOME ?? (0, import_node_os9.homedir)(),
11632
+ PATH: pathEntries.join(import_node_path12.delimiter)
10905
11633
  };
10906
11634
  }
10907
11635
  async function restartUserService(store, runtime = defaultServiceManagerRuntime) {
@@ -10938,7 +11666,7 @@ async function refreshManagedUserService(store, options, runtime = defaultServic
10938
11666
  try {
10939
11667
  await rollback();
10940
11668
  } catch (rollbackError) {
10941
- throw new Error(`${errorMessage3(error)}; restoring the previous ${manager} definition also failed: ${errorMessage3(rollbackError)}`, { cause: error });
11669
+ throw new Error(`${errorMessage4(error)}; restoring the previous ${manager} definition also failed: ${errorMessage4(rollbackError)}`, { cause: error });
10942
11670
  }
10943
11671
  throw error;
10944
11672
  }
@@ -11005,21 +11733,21 @@ async function uninstallUserService(store, runtime = defaultServiceManagerRuntim
11005
11733
  return manager;
11006
11734
  }
11007
11735
  async function automaticManagerCandidates(store, capabilities) {
11008
- const candidates = [];
11736
+ const candidates2 = [];
11009
11737
  const storedManager = await readStoredServiceManager(store);
11010
11738
  if (storedManager !== UserServiceManager.None && managerIsAvailable(storedManager, capabilities)) {
11011
- candidates.push(storedManager);
11739
+ candidates2.push(storedManager);
11012
11740
  }
11013
- if (capabilities.operatingSystem === "darwin" && !candidates.includes(UserServiceManager.Launchd)) {
11014
- candidates.push(UserServiceManager.Launchd);
11741
+ if (capabilities.operatingSystem === "darwin" && !candidates2.includes(UserServiceManager.Launchd)) {
11742
+ candidates2.push(UserServiceManager.Launchd);
11015
11743
  }
11016
- if (capabilities.systemdUserAvailable && !candidates.includes(UserServiceManager.Systemd)) {
11017
- candidates.push(UserServiceManager.Systemd);
11744
+ if (capabilities.systemdUserAvailable && !candidates2.includes(UserServiceManager.Systemd)) {
11745
+ candidates2.push(UserServiceManager.Systemd);
11018
11746
  }
11019
- if (capabilities.supervisorAvailable && !candidates.includes(UserServiceManager.Supervisor)) {
11020
- candidates.push(UserServiceManager.Supervisor);
11747
+ if (capabilities.supervisorAvailable && !candidates2.includes(UserServiceManager.Supervisor)) {
11748
+ candidates2.push(UserServiceManager.Supervisor);
11021
11749
  }
11022
- return candidates;
11750
+ return candidates2;
11023
11751
  }
11024
11752
  async function replaceConfiguredManager(store, manager, options, runtime) {
11025
11753
  const configuredManager = await readStoredServiceManager(store);
@@ -11095,7 +11823,7 @@ async function uninstallManager(manager, store, runtime) {
11095
11823
  "bootout",
11096
11824
  `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
11097
11825
  ]);
11098
- await (0, import_promises13.rm)(launchAgentPath(), { force: true });
11826
+ await (0, import_promises14.rm)(launchAgentPath(), { force: true });
11099
11827
  return;
11100
11828
  }
11101
11829
  if (manager === UserServiceManager.Systemd) {
@@ -11105,7 +11833,7 @@ async function uninstallManager(manager, store, runtime) {
11105
11833
  "--now",
11106
11834
  "moxt-machine-connector.service"
11107
11835
  ]);
11108
- await (0, import_promises13.rm)(systemdUnitPath(), { force: true });
11836
+ await (0, import_promises14.rm)(systemdUnitPath(), { force: true });
11109
11837
  await runCommandIgnoringFailure(runtime, "systemctl", [
11110
11838
  "--user",
11111
11839
  "daemon-reload"
@@ -11122,7 +11850,7 @@ async function uninstallManager(manager, store, runtime) {
11122
11850
  ]);
11123
11851
  await waitForSupervisorExit(store, runtime, supervisorProcessId);
11124
11852
  }
11125
- await (0, import_promises13.rm)(supervisorDirectory(store), {
11853
+ await (0, import_promises14.rm)(supervisorDirectory(store), {
11126
11854
  force: true,
11127
11855
  recursive: true
11128
11856
  });
@@ -11148,17 +11876,17 @@ async function readStoredServiceManager(store) {
11148
11876
  }
11149
11877
  async function readManagedServiceDefinition(manager, store) {
11150
11878
  try {
11151
- return await (0, import_promises13.readFile)(managedServiceDefinitionPath(manager, store), "utf8");
11879
+ return await (0, import_promises14.readFile)(managedServiceDefinitionPath(manager, store), "utf8");
11152
11880
  } catch (error) {
11153
- if (isNodeErrorCode4(error, "ENOENT"))
11881
+ if (isNodeErrorCode5(error, "ENOENT"))
11154
11882
  return void 0;
11155
11883
  throw error;
11156
11884
  }
11157
11885
  }
11158
11886
  async function restoreManagedServiceDefinition(manager, store, definition2, runtime) {
11159
11887
  const path4 = managedServiceDefinitionPath(manager, store);
11160
- await (0, import_promises13.mkdir)((0, import_node_path11.dirname)(path4), { recursive: true });
11161
- await (0, import_promises13.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
11888
+ await (0, import_promises14.mkdir)((0, import_node_path12.dirname)(path4), { recursive: true });
11889
+ await (0, import_promises14.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
11162
11890
  if (manager === UserServiceManager.Launchd) {
11163
11891
  const domain = `gui/${process.getuid?.() ?? 0}`;
11164
11892
  await runCommandIgnoringFailure(runtime, "launchctl", [
@@ -11207,7 +11935,7 @@ function parseProcessId(value) {
11207
11935
  async function persistServiceManager(store, manager, managedEntrypointPath, desiredState = ManagedServiceDesiredState.Running) {
11208
11936
  await store.writeServiceManager({
11209
11937
  desiredState,
11210
- ...managedEntrypointPath ? { managedEntrypointPath: (0, import_node_path11.resolve)(managedEntrypointPath) } : {},
11938
+ ...managedEntrypointPath ? { managedEntrypointPath: (0, import_node_path12.resolve)(managedEntrypointPath) } : {},
11211
11939
  manager,
11212
11940
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
11213
11941
  });
@@ -11220,9 +11948,9 @@ async function assertManagedServiceProvenance(store, candidateEntrypointPath) {
11220
11948
  const stored = (await store.readServiceManager()).value;
11221
11949
  if (!stored || stored.manager === UserServiceManager.None)
11222
11950
  return;
11223
- const candidate = (0, import_node_path11.resolve)(candidateEntrypointPath);
11951
+ const candidate = (0, import_node_path12.resolve)(candidateEntrypointPath);
11224
11952
  if (stored.managedEntrypointPath) {
11225
- if ((0, import_node_path11.resolve)(stored.managedEntrypointPath) !== candidate) {
11953
+ if ((0, import_node_path12.resolve)(stored.managedEntrypointPath) !== candidate) {
11226
11954
  throw new Error("The managed Connector belongs to a different CLI installation. Run service install from the owning CLI to transfer management.");
11227
11955
  }
11228
11956
  return;
@@ -11232,16 +11960,16 @@ async function assertManagedServiceProvenance(store, candidateEntrypointPath) {
11232
11960
  }
11233
11961
  }
11234
11962
  async function isInsideSourceCheckout(path4) {
11235
- let directory = (0, import_node_path11.dirname)(path4);
11963
+ let directory = (0, import_node_path12.dirname)(path4);
11236
11964
  while (true) {
11237
11965
  try {
11238
- await (0, import_promises13.stat)((0, import_node_path11.join)(directory, ".git"));
11966
+ await (0, import_promises14.stat)((0, import_node_path12.join)(directory, ".git"));
11239
11967
  return true;
11240
11968
  } catch (error) {
11241
- if (!isNodeErrorCode4(error, "ENOENT"))
11969
+ if (!isNodeErrorCode5(error, "ENOENT"))
11242
11970
  throw error;
11243
11971
  }
11244
- const parent = (0, import_node_path11.dirname)(directory);
11972
+ const parent = (0, import_node_path12.dirname)(directory);
11245
11973
  if (parent === directory)
11246
11974
  return false;
11247
11975
  directory = parent;
@@ -11270,10 +11998,10 @@ function automaticSelectionDetail(manager) {
11270
11998
  }
11271
11999
  async function installLaunchAgent(store, options, runtime) {
11272
12000
  const path4 = launchAgentPath();
11273
- await (0, import_promises13.mkdir)((0, import_node_path11.dirname)(path4), { recursive: true });
12001
+ await (0, import_promises14.mkdir)((0, import_node_path12.dirname)(path4), { recursive: true });
11274
12002
  const programArguments = [
11275
12003
  options.nodePath,
11276
- (0, import_node_path11.resolve)(options.entrypointPath),
12004
+ (0, import_node_path12.resolve)(options.entrypointPath),
11277
12005
  ...options.commandArguments
11278
12006
  ];
11279
12007
  const plist = `<?xml version="1.0" encoding="UTF-8"?>
@@ -11304,7 +12032,7 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
11304
12032
  </dict>
11305
12033
  </plist>
11306
12034
  `;
11307
- await (0, import_promises13.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
12035
+ await (0, import_promises14.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
11308
12036
  const domain = `gui/${process.getuid?.() ?? 0}`;
11309
12037
  await runCommandIgnoringFailure(runtime, "launchctl", [
11310
12038
  "bootout",
@@ -11320,10 +12048,10 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
11320
12048
  }
11321
12049
  async function installSystemdUserService(store, options, runtime) {
11322
12050
  const path4 = systemdUnitPath();
11323
- await (0, import_promises13.mkdir)((0, import_node_path11.dirname)(path4), { recursive: true });
12051
+ await (0, import_promises14.mkdir)((0, import_node_path12.dirname)(path4), { recursive: true });
11324
12052
  const command = [
11325
12053
  options.nodePath,
11326
- (0, import_node_path11.resolve)(options.entrypointPath),
12054
+ (0, import_node_path12.resolve)(options.entrypointPath),
11327
12055
  ...options.commandArguments
11328
12056
  ].map(escapeSystemdArgument).join(" ");
11329
12057
  const unit = `[Unit]
@@ -11342,7 +12070,7 @@ ${Object.entries(options.environment).map(([name, value]) => `Environment=${esca
11342
12070
  [Install]
11343
12071
  WantedBy=default.target
11344
12072
  `;
11345
- await (0, import_promises13.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
12073
+ await (0, import_promises14.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
11346
12074
  await runtime.run("systemctl", ["--user", "daemon-reload"]);
11347
12075
  await runtime.run("systemctl", [
11348
12076
  "--user",
@@ -11357,14 +12085,14 @@ WantedBy=default.target
11357
12085
  ]);
11358
12086
  await runCommandIgnoringFailure(runtime, "loginctl", [
11359
12087
  "enable-linger",
11360
- (0, import_node_os7.userInfo)().username
12088
+ (0, import_node_os9.userInfo)().username
11361
12089
  ]);
11362
12090
  }
11363
12091
  async function installSupervisorUserService(store, options, runtime) {
11364
12092
  const directory = supervisorDirectory(store);
11365
12093
  const configPath = supervisorConfigPath(store);
11366
- await (0, import_promises13.mkdir)(directory, { recursive: true, mode: 448 });
11367
- await (0, import_promises13.writeFile)(configPath, createSupervisorConfiguration(store, options), {
12094
+ await (0, import_promises14.mkdir)(directory, { recursive: true, mode: 448 });
12095
+ await (0, import_promises14.writeFile)(configPath, createSupervisorConfiguration(store, options), {
11368
12096
  encoding: "utf8",
11369
12097
  mode: 384
11370
12098
  });
@@ -11378,7 +12106,7 @@ async function installSupervisorUserService(store, options, runtime) {
11378
12106
  function createSupervisorConfiguration(store, options) {
11379
12107
  const command = [
11380
12108
  options.nodePath,
11381
- (0, import_node_path11.resolve)(options.entrypointPath),
12109
+ (0, import_node_path12.resolve)(options.entrypointPath),
11382
12110
  ...options.commandArguments
11383
12111
  ].map(escapeSupervisorArgument).join(" ");
11384
12112
  const environment = Object.entries(options.environment).map(([name, value]) => `${name}="${escapeSupervisorEnvironment(value)}"`).join(",");
@@ -11402,7 +12130,7 @@ serverurl=unix://${supervisorSocketPath(store)}
11402
12130
 
11403
12131
  [program:${supervisorProgramName}]
11404
12132
  command=${command}
11405
- directory=${escapeSupervisorPath((0, import_node_path11.dirname)((0, import_node_path11.resolve)(options.entrypointPath)))}
12133
+ directory=${escapeSupervisorPath((0, import_node_path12.dirname)((0, import_node_path12.resolve)(options.entrypointPath)))}
11406
12134
  environment=${environment}
11407
12135
  autostart=true
11408
12136
  autorestart=true
@@ -11435,8 +12163,8 @@ async function restartSupervisorUserService(store, runtime) {
11435
12163
  await startSupervisorUserService(store, runtime, supervisorProcessId, stoppedConnector.processId);
11436
12164
  }
11437
12165
  async function startSupervisorUserService(store, runtime, previousSupervisorProcessId, previousConnectorProcessId) {
11438
- await (0, import_promises13.rm)(supervisorSocketPath(store), { force: true });
11439
- await (0, import_promises13.rm)(supervisorPidPath(store), { force: true });
12166
+ await (0, import_promises14.rm)(supervisorSocketPath(store), { force: true });
12167
+ await (0, import_promises14.rm)(supervisorPidPath(store), { force: true });
11440
12168
  await runtime.run("supervisord", ["-c", supervisorConfigPath(store)], {
11441
12169
  environment: sanitizeEnvironment(process.env),
11442
12170
  timeoutMilliseconds: serviceManagerMutationTimeoutMilliseconds
@@ -11517,7 +12245,7 @@ function localProcessIsRunning(processId) {
11517
12245
  process.kill(processId, 0);
11518
12246
  return true;
11519
12247
  } catch (error) {
11520
- if (isNodeErrorCode4(error, "ESRCH"))
12248
+ if (isNodeErrorCode5(error, "ESRCH"))
11521
12249
  return false;
11522
12250
  throw error;
11523
12251
  }
@@ -11545,10 +12273,10 @@ async function currentSupervisorProcessId(store, runtime) {
11545
12273
  } catch {
11546
12274
  }
11547
12275
  try {
11548
- const processId = parseProcessId(await (0, import_promises13.readFile)(supervisorPidPath(store), "utf8"));
12276
+ const processId = parseProcessId(await (0, import_promises14.readFile)(supervisorPidPath(store), "utf8"));
11549
12277
  return processId !== void 0 && serviceProcessIsRunning(runtime, processId) ? processId : void 0;
11550
12278
  } catch (error) {
11551
- if (isNodeErrorCode4(error, "ENOENT"))
12279
+ if (isNodeErrorCode5(error, "ENOENT"))
11552
12280
  return void 0;
11553
12281
  throw error;
11554
12282
  }
@@ -11567,26 +12295,26 @@ async function currentSupervisorProgramProcessId(store, runtime) {
11567
12295
  }
11568
12296
  }
11569
12297
  function launchAgentPath() {
11570
- return (0, import_node_path11.join)(process.env.HOME ?? (0, import_node_os7.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
12298
+ return (0, import_node_path12.join)(process.env.HOME ?? (0, import_node_os9.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
11571
12299
  }
11572
12300
  function systemdUnitPath() {
11573
- const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path11.join)(process.env.HOME ?? (0, import_node_os7.homedir)(), ".config");
11574
- return (0, import_node_path11.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
12301
+ const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path12.join)(process.env.HOME ?? (0, import_node_os9.homedir)(), ".config");
12302
+ return (0, import_node_path12.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
11575
12303
  }
11576
12304
  function supervisorDirectory(store) {
11577
- return (0, import_node_path11.join)(store.baseDirectory, "supervisor");
12305
+ return (0, import_node_path12.join)(store.baseDirectory, "supervisor");
11578
12306
  }
11579
12307
  function supervisorConfigPath(store) {
11580
- return (0, import_node_path11.join)(supervisorDirectory(store), "supervisord.conf");
12308
+ return (0, import_node_path12.join)(supervisorDirectory(store), "supervisord.conf");
11581
12309
  }
11582
12310
  function supervisorSocketPath(store) {
11583
- return (0, import_node_path11.join)(supervisorDirectory(store), "supervisor.sock");
12311
+ return (0, import_node_path12.join)(supervisorDirectory(store), "supervisor.sock");
11584
12312
  }
11585
12313
  function supervisorPidPath(store) {
11586
- return (0, import_node_path11.join)(supervisorDirectory(store), "supervisord.pid");
12314
+ return (0, import_node_path12.join)(supervisorDirectory(store), "supervisord.pid");
11587
12315
  }
11588
12316
  function supervisorLogPath(store) {
11589
- return (0, import_node_path11.join)(supervisorDirectory(store), "supervisord.log");
12317
+ return (0, import_node_path12.join)(supervisorDirectory(store), "supervisord.log");
11590
12318
  }
11591
12319
  async function commandSucceeds(runtime, command, argumentsList) {
11592
12320
  try {
@@ -11629,10 +12357,10 @@ function escapeSupervisorPath(value) {
11629
12357
  function escapeSupervisorValue(value) {
11630
12358
  return value.replaceAll("%", "%%").replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n");
11631
12359
  }
11632
- function errorMessage3(error) {
12360
+ function errorMessage4(error) {
11633
12361
  return error instanceof Error ? error.message : String(error);
11634
12362
  }
11635
- function isNodeErrorCode4(error, expectedCode) {
12363
+ function isNodeErrorCode5(error, expectedCode) {
11636
12364
  return error instanceof Error && "code" in error && error.code === expectedCode;
11637
12365
  }
11638
12366
  function delay5(milliseconds) {
@@ -11646,15 +12374,15 @@ function serviceManagerCurrentTime(runtime) {
11646
12374
  async function serviceManagerDelay(runtime, milliseconds) {
11647
12375
  await (runtime.delay?.(milliseconds) ?? delay5(milliseconds));
11648
12376
  }
11649
- var import_node_child_process5, import_promises13, import_node_os7, import_node_path11, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerProbeTimeoutMilliseconds, serviceManagerMutationTimeoutMilliseconds, supervisorProgramName, supervisorControlTimeoutMilliseconds, supervisorProgramStartSeconds, supervisorProgramStartRetries, supervisorProgramStopWaitSeconds, supervisorLifecycleBufferMilliseconds, supervisorExitTimeoutMilliseconds, supervisorProgramStartTimeoutMilliseconds, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
12377
+ var import_node_child_process5, import_promises14, import_node_os9, import_node_path12, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerProbeTimeoutMilliseconds, serviceManagerMutationTimeoutMilliseconds, supervisorProgramName, supervisorControlTimeoutMilliseconds, supervisorProgramStartSeconds, supervisorProgramStartRetries, supervisorProgramStopWaitSeconds, supervisorLifecycleBufferMilliseconds, supervisorExitTimeoutMilliseconds, supervisorProgramStartTimeoutMilliseconds, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
11650
12378
  var init_service_manager = __esm({
11651
12379
  "../machine-connector/dist/runtime/service-manager.js"() {
11652
12380
  "use strict";
11653
12381
  init_cjs_shims();
11654
12382
  import_node_child_process5 = require("child_process");
11655
- import_promises13 = require("fs/promises");
11656
- import_node_os7 = require("os");
11657
- import_node_path11 = require("path");
12383
+ import_promises14 = require("fs/promises");
12384
+ import_node_os9 = require("os");
12385
+ import_node_path12 = require("path");
11658
12386
  import_node_util2 = require("util");
11659
12387
  init_runtime_types();
11660
12388
  init_shell_environment();
@@ -11683,7 +12411,7 @@ var init_service_manager = __esm({
11683
12411
  UserServiceManager2["Systemd"] = "systemd";
11684
12412
  })(UserServiceManager || (UserServiceManager = {}));
11685
12413
  defaultServiceManagerRuntime = {
11686
- operatingSystem: (0, import_node_os7.platform)(),
12414
+ operatingSystem: (0, import_node_os9.platform)(),
11687
12415
  processIsRunning(processId) {
11688
12416
  return localProcessIsRunning(processId);
11689
12417
  },
@@ -11729,7 +12457,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
11729
12457
  try {
11730
12458
  managerOwnsProcess = await managedServiceOwnsProcess(manager, initial.pid, store);
11731
12459
  } catch (error) {
11732
- throw new DaemonRefreshError(DaemonRefreshStage.Ownership, `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage4(error)}`, { cause: error });
12460
+ throw new DaemonRefreshError(DaemonRefreshStage.Ownership, `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage5(error)}`, { cause: error });
11733
12461
  }
11734
12462
  if (!managerOwnsProcess) {
11735
12463
  throw new DaemonRefreshError(DaemonRefreshStage.Ownership, `${manager} does not own reachable daemon PID ${initial.pid}; stop that foreground or orphaned daemon before restarting the managed Connector`);
@@ -11738,7 +12466,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
11738
12466
  try {
11739
12467
  await validateCliEntrypoint(options, store);
11740
12468
  } catch (error) {
11741
- throw new DaemonRefreshError(DaemonRefreshStage.Validation, errorMessage4(error), {
12469
+ throw new DaemonRefreshError(DaemonRefreshStage.Validation, errorMessage5(error), {
11742
12470
  cause: error
11743
12471
  });
11744
12472
  }
@@ -11749,9 +12477,9 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
11749
12477
  try {
11750
12478
  refresh = await refreshManagedUserService(store, {
11751
12479
  commandArguments: [...options.commandArguments],
11752
- entrypointPath: (0, import_node_path12.resolve)(options.entrypointPath),
12480
+ entrypointPath: (0, import_node_path13.resolve)(options.entrypointPath),
11753
12481
  environment: { ...options.environment },
11754
- nodePath: (0, import_node_path12.resolve)(options.nodePath)
12482
+ nodePath: (0, import_node_path13.resolve)(options.nodePath)
11755
12483
  });
11756
12484
  if (!refresh) {
11757
12485
  throw new Error("The Connector service is no longer managed by Moxt");
@@ -11771,7 +12499,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
11771
12499
  try {
11772
12500
  await refresh.rollback();
11773
12501
  } catch (error) {
11774
- throw new DaemonRefreshError(DaemonRefreshStage.Verification, `${verificationMessage}; restoring the previous service definition also failed: ${errorMessage4(error)}`, { cause: error });
12502
+ throw new DaemonRefreshError(DaemonRefreshStage.Verification, `${verificationMessage}; restoring the previous service definition also failed: ${errorMessage5(error)}`, { cause: error });
11775
12503
  }
11776
12504
  throw new DaemonRefreshError(DaemonRefreshStage.Verification, verificationMessage);
11777
12505
  } finally {
@@ -11787,10 +12515,10 @@ async function validateCliEntrypoint(options, store) {
11787
12515
  if (options.commandArguments.length !== 2 || options.commandArguments[0] !== "machine" || options.commandArguments[1] !== "daemon") {
11788
12516
  throw new Error("The managed daemon command must be `machine daemon`");
11789
12517
  }
11790
- const nodePath = await (0, import_promises14.realpath)((0, import_node_path12.resolve)(options.nodePath));
11791
- const entrypointPath = await (0, import_promises14.realpath)((0, import_node_path12.resolve)(options.entrypointPath));
11792
- await (0, import_promises14.access)(nodePath, import_promises14.constants.X_OK);
11793
- await (0, import_promises14.access)(entrypointPath, import_promises14.constants.R_OK);
12518
+ const nodePath = await (0, import_promises15.realpath)((0, import_node_path13.resolve)(options.nodePath));
12519
+ const entrypointPath = await (0, import_promises15.realpath)((0, import_node_path13.resolve)(options.entrypointPath));
12520
+ await (0, import_promises15.access)(nodePath, import_promises15.constants.X_OK);
12521
+ await (0, import_promises15.access)(entrypointPath, import_promises15.constants.R_OK);
11794
12522
  const probe = await execFileAsync2(nodePath, [entrypointPath, "--version"], {
11795
12523
  encoding: "utf8",
11796
12524
  env: {
@@ -11820,17 +12548,17 @@ async function reachableRuntimeStatus(store) {
11820
12548
  function delay6(milliseconds) {
11821
12549
  return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
11822
12550
  }
11823
- function errorMessage4(error) {
12551
+ function errorMessage5(error) {
11824
12552
  return error instanceof Error ? error.message : String(error);
11825
12553
  }
11826
- var import_node_child_process6, import_promises14, import_node_path12, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshStage, DaemonRefreshError;
12554
+ var import_node_child_process6, import_promises15, import_node_path13, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshStage, DaemonRefreshError;
11827
12555
  var init_daemon_reconcile = __esm({
11828
12556
  "../machine-connector/dist/runtime/daemon-reconcile.js"() {
11829
12557
  "use strict";
11830
12558
  init_cjs_shims();
11831
12559
  import_node_child_process6 = require("child_process");
11832
- import_promises14 = require("fs/promises");
11833
- import_node_path12 = require("path");
12560
+ import_promises15 = require("fs/promises");
12561
+ import_node_path13 = require("path");
11834
12562
  import_node_util3 = require("util");
11835
12563
  init_local_ipc();
11836
12564
  init_process_lock();
@@ -11886,14 +12614,14 @@ async function runMachineDoctor(store) {
11886
12614
  }
11887
12615
  } catch (error) {
11888
12616
  checks.push({
11889
- detail: errorMessage5(error),
12617
+ detail: errorMessage6(error),
11890
12618
  name: "daemon",
11891
12619
  status: DoctorCheckStatus.Failed
11892
12620
  });
11893
12621
  }
11894
12622
  for (const connection of connections) {
11895
12623
  try {
11896
- await (0, import_promises15.access)(connection.rootPath, import_node_fs.constants.R_OK | import_node_fs.constants.X_OK);
12624
+ await (0, import_promises16.access)(connection.rootPath, import_node_fs3.constants.R_OK | import_node_fs3.constants.X_OK);
11897
12625
  checks.push({
11898
12626
  detail: connection.rootPath,
11899
12627
  name: `root:${connection.connectionId}`,
@@ -11901,14 +12629,14 @@ async function runMachineDoctor(store) {
11901
12629
  });
11902
12630
  } catch (error) {
11903
12631
  checks.push({
11904
- detail: errorMessage5(error),
12632
+ detail: errorMessage6(error),
11905
12633
  name: `root:${connection.connectionId}`,
11906
12634
  status: DoctorCheckStatus.Failed
11907
12635
  });
11908
12636
  }
11909
12637
  const relayUrl = new URL(connection.relayOrigin);
11910
12638
  try {
11911
- const address = await (0, import_promises16.lookup)(relayUrl.hostname);
12639
+ const address = await (0, import_promises17.lookup)(relayUrl.hostname);
11912
12640
  checks.push({
11913
12641
  detail: `${relayUrl.hostname} resolves to ${address.address}`,
11914
12642
  name: `dns:${connection.connectionId}`,
@@ -11916,7 +12644,7 @@ async function runMachineDoctor(store) {
11916
12644
  });
11917
12645
  } catch (error) {
11918
12646
  checks.push({
11919
- detail: errorMessage5(error),
12647
+ detail: errorMessage6(error),
11920
12648
  name: `dns:${connection.connectionId}`,
11921
12649
  status: DoctorCheckStatus.Failed
11922
12650
  });
@@ -11940,7 +12668,7 @@ async function runMachineDoctor(store) {
11940
12668
  });
11941
12669
  } catch (error) {
11942
12670
  checks.push({
11943
- detail: errorMessage5(error),
12671
+ detail: errorMessage6(error),
11944
12672
  name: `tls:${connection.connectionId}`,
11945
12673
  status: DoctorCheckStatus.Failed
11946
12674
  });
@@ -11966,7 +12694,7 @@ async function runMachineDoctor(store) {
11966
12694
  });
11967
12695
  } catch (error) {
11968
12696
  checks.push({
11969
- detail: errorMessage5(error),
12697
+ detail: errorMessage6(error),
11970
12698
  name: "codex",
11971
12699
  status: DoctorCheckStatus.Warning
11972
12700
  });
@@ -11980,25 +12708,25 @@ async function runMachineDoctor(store) {
11980
12708
  });
11981
12709
  } catch (error) {
11982
12710
  checks.push({
11983
- detail: errorMessage5(error),
12711
+ detail: errorMessage6(error),
11984
12712
  name: "claude",
11985
12713
  status: DoctorCheckStatus.Warning
11986
12714
  });
11987
12715
  }
11988
12716
  return checks;
11989
12717
  }
11990
- function errorMessage5(error) {
12718
+ function errorMessage6(error) {
11991
12719
  return error instanceof Error ? error.message : String(error);
11992
12720
  }
11993
- var import_node_child_process7, import_promises15, import_node_fs, import_promises16, import_node_util4, execFileAsync3, DoctorCheckStatus;
12721
+ var import_node_child_process7, import_promises16, import_node_fs3, import_promises17, import_node_util4, execFileAsync3, DoctorCheckStatus;
11994
12722
  var init_doctor = __esm({
11995
12723
  "../machine-connector/dist/runtime/doctor.js"() {
11996
12724
  "use strict";
11997
12725
  init_cjs_shims();
11998
12726
  import_node_child_process7 = require("child_process");
11999
- import_promises15 = require("fs/promises");
12000
- import_node_fs = require("fs");
12001
- import_promises16 = require("dns/promises");
12727
+ import_promises16 = require("fs/promises");
12728
+ import_node_fs3 = require("fs");
12729
+ import_promises17 = require("dns/promises");
12002
12730
  import_node_util4 = require("util");
12003
12731
  init_local_ipc();
12004
12732
  execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process7.execFile);
@@ -12268,7 +12996,7 @@ async function readRecentLogLines(store) {
12268
12996
  }
12269
12997
  async function readOptionalFile(path4) {
12270
12998
  try {
12271
- return await (0, import_promises17.readFile)(path4, "utf8");
12999
+ return await (0, import_promises18.readFile)(path4, "utf8");
12272
13000
  } catch (error) {
12273
13001
  if (isMissingFile(error)) {
12274
13002
  return "";
@@ -12324,16 +13052,16 @@ function isRecord4(value) {
12324
13052
  function isMissingFile(error) {
12325
13053
  return error instanceof Error && "code" in error && error.code === "ENOENT";
12326
13054
  }
12327
- function errorMessage6(error) {
13055
+ function errorMessage7(error) {
12328
13056
  return error instanceof Error ? error.message : String(error);
12329
13057
  }
12330
- var import_promises17, import_promises18, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
13058
+ var import_promises18, import_promises19, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
12331
13059
  var init_machine_manager = __esm({
12332
13060
  "../machine-connector/dist/runtime/machine-manager.js"() {
12333
13061
  "use strict";
12334
13062
  init_cjs_shims();
12335
- import_promises17 = require("fs/promises");
12336
- import_promises18 = require("readline/promises");
13063
+ import_promises18 = require("fs/promises");
13064
+ import_promises19 = require("readline/promises");
12337
13065
  import_node_readline = require("readline");
12338
13066
  init_doctor();
12339
13067
  init_local_ipc();
@@ -12530,7 +13258,7 @@ var init_machine_manager = __esm({
12530
13258
  };
12531
13259
  this.state.message = void 0;
12532
13260
  } catch (error) {
12533
- this.state.message = errorMessage6(error);
13261
+ this.state.message = errorMessage7(error);
12534
13262
  } finally {
12535
13263
  this.refreshing = false;
12536
13264
  this.render();
@@ -12567,7 +13295,7 @@ var init_machine_manager = __esm({
12567
13295
  }
12568
13296
  async runCommandAction(action) {
12569
13297
  this.suspendTerminal();
12570
- const reader = (0, import_promises18.createInterface)({
13298
+ const reader = (0, import_promises19.createInterface)({
12571
13299
  input: process.stdin,
12572
13300
  output: process.stdout
12573
13301
  });
@@ -12578,7 +13306,7 @@ var init_machine_manager = __esm({
12578
13306
  }
12579
13307
  } catch (error) {
12580
13308
  process.stdout.write(`
12581
- Error: ${errorMessage6(error)}
13309
+ Error: ${errorMessage7(error)}
12582
13310
  `);
12583
13311
  }
12584
13312
  await reader.question("\nPress Enter to return to the manager...");
@@ -12747,7 +13475,7 @@ async function pairMachine(store, options) {
12747
13475
  const canonicalRoot = await store.getCanonicalRoot(options.rootPath);
12748
13476
  const rootDisplayName = displayNameForRoot(canonicalRoot);
12749
13477
  const identity = await ensureMachineIdentity(store);
12750
- const machineName = options.machineName ?? (0, import_node_os8.hostname)();
13478
+ const machineName = options.machineName ?? (0, import_node_os10.hostname)();
12751
13479
  const operatingSystem = getOperatingSystem();
12752
13480
  const rootHandle = (0, import_node_crypto11.createHash)("sha256").update(identity.identity.deviceKeyFingerprint, "utf8").update("\0").update(canonicalRoot, "utf8").digest("base64url");
12753
13481
  const client = new PairingRelayClient(options.relayOrigin);
@@ -12808,20 +13536,20 @@ async function pairMachine(store, options) {
12808
13536
  throw new Error("Local Machine pairing expired");
12809
13537
  }
12810
13538
  function displayNameForRoot(canonicalRoot) {
12811
- const name = (0, import_node_path13.basename)(canonicalRoot);
13539
+ const name = (0, import_node_path14.basename)(canonicalRoot);
12812
13540
  return name.length > 0 ? name : canonicalRoot;
12813
13541
  }
12814
13542
  function getOperatingSystem() {
12815
- if ((0, import_node_os8.platform)() === "darwin") {
13543
+ if ((0, import_node_os10.platform)() === "darwin") {
12816
13544
  return MachineOperatingSystem.MacOS;
12817
13545
  }
12818
- if ((0, import_node_os8.platform)() === "linux") {
13546
+ if ((0, import_node_os10.platform)() === "linux") {
12819
13547
  return MachineOperatingSystem.Linux;
12820
13548
  }
12821
13549
  return MachineOperatingSystem.Windows;
12822
13550
  }
12823
13551
  function openBrowser(url) {
12824
- const command = (0, import_node_os8.platform)() === "darwin" ? "open" : "xdg-open";
13552
+ const command = (0, import_node_os10.platform)() === "darwin" ? "open" : "xdg-open";
12825
13553
  const child = (0, import_node_child_process8.execFile)(command, [url], () => void 0);
12826
13554
  child.unref();
12827
13555
  }
@@ -12830,15 +13558,15 @@ function delay7(milliseconds) {
12830
13558
  setTimeout(resolvePromise, milliseconds);
12831
13559
  });
12832
13560
  }
12833
- var import_node_child_process8, import_node_crypto11, import_node_os8, import_node_path13, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
13561
+ var import_node_child_process8, import_node_crypto11, import_node_os10, import_node_path14, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
12834
13562
  var init_pairing = __esm({
12835
13563
  "../machine-connector/dist/runtime/pairing.js"() {
12836
13564
  "use strict";
12837
13565
  init_cjs_shims();
12838
13566
  import_node_child_process8 = require("child_process");
12839
13567
  import_node_crypto11 = require("crypto");
12840
- import_node_os8 = require("os");
12841
- import_node_path13 = require("path");
13568
+ import_node_os10 = require("os");
13569
+ import_node_path14 = require("path");
12842
13570
  init_contracts();
12843
13571
  init_version();
12844
13572
  init_enums();
@@ -12926,7 +13654,7 @@ function isMachineLifecycleMutation(command, commandArguments) {
12926
13654
  async function connectCommand(store, argumentsList, entrypoint) {
12927
13655
  const options = parseOptions(argumentsList);
12928
13656
  const connectionCode = requiredOption(options, "code");
12929
- const rootPath = (0, import_node_path14.resolve)(options.root ?? process.cwd());
13657
+ const rootPath = (0, import_node_path15.resolve)(options.root ?? process.cwd());
12930
13658
  const serviceManagerPreference = requestedServiceManagerPreference(options);
12931
13659
  await validateExplicitServiceManagerPreference(serviceManagerPreference);
12932
13660
  await assertConnectionRuntimeCanConverge(store, serviceManagerPreference);
@@ -13278,7 +14006,7 @@ async function reachableRuntimeStatus2(store) {
13278
14006
  }
13279
14007
  async function readOptionalFile2(path4) {
13280
14008
  try {
13281
- return await (0, import_promises19.readFile)(path4, "utf8");
14009
+ return await (0, import_promises20.readFile)(path4, "utf8");
13282
14010
  } catch {
13283
14011
  return "";
13284
14012
  }
@@ -13307,13 +14035,13 @@ function delay8(milliseconds) {
13307
14035
  setTimeout(resolvePromise, milliseconds);
13308
14036
  });
13309
14037
  }
13310
- var import_promises19, import_node_path14, defaultRelayOrigin;
14038
+ var import_promises20, import_node_path15, defaultRelayOrigin;
13311
14039
  var init_cli = __esm({
13312
14040
  "../machine-connector/dist/cli.js"() {
13313
14041
  "use strict";
13314
14042
  init_cjs_shims();
13315
- import_promises19 = require("fs/promises");
13316
- import_node_path14 = require("path");
14043
+ import_promises20 = require("fs/promises");
14044
+ import_node_path15 = require("path");
13317
14045
  init_daemon();
13318
14046
  init_daemon_reconcile();
13319
14047
  init_doctor();
@@ -13608,7 +14336,7 @@ function getApiKeyOrUndefined() {
13608
14336
 
13609
14337
  // src/utils/http.ts
13610
14338
  function getUserAgent() {
13611
- return `moxt-cli/${"0.10.0-beta.5"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
14339
+ return `moxt-cli/${"0.10.0-beta.6"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
13612
14340
  }
13613
14341
  async function sendRequest(method, path4, init) {
13614
14342
  return await fetch(`${getApiBaseUrl()}${path4}`, {
@@ -13795,8 +14523,8 @@ function readCommentContentFile(path4) {
13795
14523
  if (!fs.existsSync(path4)) {
13796
14524
  throw new FileCommentOptionsError(`Error: comment content file not found: ${path4}`);
13797
14525
  }
13798
- const stat5 = fs.statSync(path4);
13799
- if (!stat5.isFile()) {
14526
+ const stat6 = fs.statSync(path4);
14527
+ if (!stat6.isFile()) {
13800
14528
  throw new FileCommentOptionsError(`Error: comment content path is not a file: ${path4}`);
13801
14529
  }
13802
14530
  const buffer2 = fs.readFileSync(path4);
@@ -14470,8 +15198,8 @@ var FileTokenizer = class _FileTokenizer extends AbstractTokenizer {
14470
15198
  */
14471
15199
  static async fromFile(sourceFilePath) {
14472
15200
  const fileHandle = await (0, import_promises.open)(sourceFilePath, "r");
14473
- const stat5 = await fileHandle.stat();
14474
- return new _FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat5.size } });
15201
+ const stat6 = await fileHandle.stat();
15202
+ return new _FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat6.size } });
14475
15203
  }
14476
15204
  constructor(fileHandle, options) {
14477
15205
  super(options);
@@ -15026,7 +15754,9 @@ var fdt = new u8(32);
15026
15754
  for (i = 0; i < 32; ++i)
15027
15755
  fdt[i] = 5;
15028
15756
  var i;
15757
+ var flm = /* @__PURE__ */ hMap(flt, 9, 0);
15029
15758
  var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
15759
+ var fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
15030
15760
  var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
15031
15761
  var max = function(a) {
15032
15762
  var m = a[0];
@@ -15222,7 +15952,357 @@ var inflt = function(dat, st, buf, dict) {
15222
15952
  } while (!final);
15223
15953
  return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
15224
15954
  };
15955
+ var wbits = function(d, p, v) {
15956
+ v <<= p & 7;
15957
+ var o = p / 8 | 0;
15958
+ d[o] |= v;
15959
+ d[o + 1] |= v >> 8;
15960
+ };
15961
+ var wbits16 = function(d, p, v) {
15962
+ v <<= p & 7;
15963
+ var o = p / 8 | 0;
15964
+ d[o] |= v;
15965
+ d[o + 1] |= v >> 8;
15966
+ d[o + 2] |= v >> 16;
15967
+ };
15968
+ var hTree = function(d, mb) {
15969
+ var t = [];
15970
+ for (var i2 = 0; i2 < d.length; ++i2) {
15971
+ if (d[i2])
15972
+ t.push({ s: i2, f: d[i2] });
15973
+ }
15974
+ var s = t.length;
15975
+ var t2 = t.slice();
15976
+ if (!s)
15977
+ return { t: et, l: 0 };
15978
+ if (s == 1) {
15979
+ var v = new u8(t[0].s + 1);
15980
+ v[t[0].s] = 1;
15981
+ return { t: v, l: 1 };
15982
+ }
15983
+ t.sort(function(a, b) {
15984
+ return a.f - b.f;
15985
+ });
15986
+ t.push({ s: -1, f: 25001 });
15987
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i22 = 2;
15988
+ t[0] = { s: -1, f: l.f + r.f, l, r };
15989
+ while (i1 != s - 1) {
15990
+ l = t[t[i0].f < t[i22].f ? i0++ : i22++];
15991
+ r = t[i0 != i1 && t[i0].f < t[i22].f ? i0++ : i22++];
15992
+ t[i1++] = { s: -1, f: l.f + r.f, l, r };
15993
+ }
15994
+ var maxSym = t2[0].s;
15995
+ for (var i2 = 1; i2 < s; ++i2) {
15996
+ if (t2[i2].s > maxSym)
15997
+ maxSym = t2[i2].s;
15998
+ }
15999
+ var tr = new u16(maxSym + 1);
16000
+ var mbt = ln(t[i1 - 1], tr, 0);
16001
+ if (mbt > mb) {
16002
+ var i2 = 0, dt = 0;
16003
+ var lft = mbt - mb, cst = 1 << lft;
16004
+ t2.sort(function(a, b) {
16005
+ return tr[b.s] - tr[a.s] || a.f - b.f;
16006
+ });
16007
+ for (; i2 < s; ++i2) {
16008
+ var i2_1 = t2[i2].s;
16009
+ if (tr[i2_1] > mb) {
16010
+ dt += cst - (1 << mbt - tr[i2_1]);
16011
+ tr[i2_1] = mb;
16012
+ } else
16013
+ break;
16014
+ }
16015
+ dt >>= lft;
16016
+ while (dt > 0) {
16017
+ var i2_2 = t2[i2].s;
16018
+ if (tr[i2_2] < mb)
16019
+ dt -= 1 << mb - tr[i2_2]++ - 1;
16020
+ else
16021
+ ++i2;
16022
+ }
16023
+ for (; i2 >= 0 && dt; --i2) {
16024
+ var i2_3 = t2[i2].s;
16025
+ if (tr[i2_3] == mb) {
16026
+ --tr[i2_3];
16027
+ ++dt;
16028
+ }
16029
+ }
16030
+ mbt = mb;
16031
+ }
16032
+ return { t: new u8(tr), l: mbt };
16033
+ };
16034
+ var ln = function(n, l, d) {
16035
+ return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : l[n.s] = d;
16036
+ };
16037
+ var lc = function(c) {
16038
+ var s = c.length;
16039
+ while (s && !c[--s])
16040
+ ;
16041
+ var cl = new u16(++s);
16042
+ var cli = 0, cln = c[0], cls = 1;
16043
+ var w = function(v) {
16044
+ cl[cli++] = v;
16045
+ };
16046
+ for (var i2 = 1; i2 <= s; ++i2) {
16047
+ if (c[i2] == cln && i2 != s)
16048
+ ++cls;
16049
+ else {
16050
+ if (!cln && cls > 2) {
16051
+ for (; cls > 138; cls -= 138)
16052
+ w(32754);
16053
+ if (cls > 2) {
16054
+ w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
16055
+ cls = 0;
16056
+ }
16057
+ } else if (cls > 3) {
16058
+ w(cln), --cls;
16059
+ for (; cls > 6; cls -= 6)
16060
+ w(8304);
16061
+ if (cls > 2)
16062
+ w(cls - 3 << 5 | 8208), cls = 0;
16063
+ }
16064
+ while (cls--)
16065
+ w(cln);
16066
+ cls = 1;
16067
+ cln = c[i2];
16068
+ }
16069
+ }
16070
+ return { c: cl.subarray(0, cli), n: s };
16071
+ };
16072
+ var clen = function(cf, cl) {
16073
+ var l = 0;
16074
+ for (var i2 = 0; i2 < cl.length; ++i2)
16075
+ l += cf[i2] * cl[i2];
16076
+ return l;
16077
+ };
16078
+ var wfblk = function(out, pos, dat) {
16079
+ var s = dat.length;
16080
+ var o = shft(pos + 2);
16081
+ out[o] = s & 255;
16082
+ out[o + 1] = s >> 8;
16083
+ out[o + 2] = out[o] ^ 255;
16084
+ out[o + 3] = out[o + 1] ^ 255;
16085
+ for (var i2 = 0; i2 < s; ++i2)
16086
+ out[o + i2 + 4] = dat[i2];
16087
+ return (o + 4 + s) * 8;
16088
+ };
16089
+ var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
16090
+ wbits(out, p++, final);
16091
+ ++lf[256];
16092
+ var _a2 = hTree(lf, 15), dlt = _a2.t, mlb = _a2.l;
16093
+ var _b2 = hTree(df, 15), ddt = _b2.t, mdb = _b2.l;
16094
+ var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
16095
+ var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
16096
+ var lcfreq = new u16(19);
16097
+ for (var i2 = 0; i2 < lclt.length; ++i2)
16098
+ ++lcfreq[lclt[i2] & 31];
16099
+ for (var i2 = 0; i2 < lcdt.length; ++i2)
16100
+ ++lcfreq[lcdt[i2] & 31];
16101
+ var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
16102
+ var nlcc = 19;
16103
+ for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
16104
+ ;
16105
+ var flen = bl + 5 << 3;
16106
+ var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
16107
+ var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
16108
+ if (bs >= 0 && flen <= ftlen && flen <= dtlen)
16109
+ return wfblk(out, p, dat.subarray(bs, bs + bl));
16110
+ var lm, ll, dm, dl;
16111
+ wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
16112
+ if (dtlen < ftlen) {
16113
+ lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
16114
+ var llm = hMap(lct, mlcb, 0);
16115
+ wbits(out, p, nlc - 257);
16116
+ wbits(out, p + 5, ndc - 1);
16117
+ wbits(out, p + 10, nlcc - 4);
16118
+ p += 14;
16119
+ for (var i2 = 0; i2 < nlcc; ++i2)
16120
+ wbits(out, p + 3 * i2, lct[clim[i2]]);
16121
+ p += 3 * nlcc;
16122
+ var lcts = [lclt, lcdt];
16123
+ for (var it = 0; it < 2; ++it) {
16124
+ var clct = lcts[it];
16125
+ for (var i2 = 0; i2 < clct.length; ++i2) {
16126
+ var len = clct[i2] & 31;
16127
+ wbits(out, p, llm[len]), p += lct[len];
16128
+ if (len > 15)
16129
+ wbits(out, p, clct[i2] >> 5 & 127), p += clct[i2] >> 12;
16130
+ }
16131
+ }
16132
+ } else {
16133
+ lm = flm, ll = flt, dm = fdm, dl = fdt;
16134
+ }
16135
+ for (var i2 = 0; i2 < li; ++i2) {
16136
+ var sym = syms[i2];
16137
+ if (sym > 255) {
16138
+ var len = sym >> 18 & 31;
16139
+ wbits16(out, p, lm[len + 257]), p += ll[len + 257];
16140
+ if (len > 7)
16141
+ wbits(out, p, sym >> 23 & 31), p += fleb[len];
16142
+ var dst = sym & 31;
16143
+ wbits16(out, p, dm[dst]), p += dl[dst];
16144
+ if (dst > 3)
16145
+ wbits16(out, p, sym >> 5 & 8191), p += fdeb[dst];
16146
+ } else {
16147
+ wbits16(out, p, lm[sym]), p += ll[sym];
16148
+ }
16149
+ }
16150
+ wbits16(out, p, lm[256]);
16151
+ return p + ll[256];
16152
+ };
16153
+ var deo = /* @__PURE__ */ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
15225
16154
  var et = /* @__PURE__ */ new u8(0);
16155
+ var dflt = function(dat, lvl, plvl, pre, post, st) {
16156
+ var s = st.z || dat.length;
16157
+ var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7e3)) + post);
16158
+ var w = o.subarray(pre, o.length - post);
16159
+ var lst = st.l;
16160
+ var pos = (st.r || 0) & 7;
16161
+ if (lvl) {
16162
+ if (pos)
16163
+ w[0] = st.r >> 3;
16164
+ var opt = deo[lvl - 1];
16165
+ var n = opt >> 13, c = opt & 8191;
16166
+ var msk_1 = (1 << plvl) - 1;
16167
+ var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
16168
+ var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
16169
+ var hsh = function(i3) {
16170
+ return (dat[i3] ^ dat[i3 + 1] << bs1_1 ^ dat[i3 + 2] << bs2_1) & msk_1;
16171
+ };
16172
+ var syms = new i32(25e3);
16173
+ var lf = new u16(288), df = new u16(32);
16174
+ var lc_1 = 0, eb = 0, i2 = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
16175
+ for (; i2 + 2 < s; ++i2) {
16176
+ var hv = hsh(i2);
16177
+ var imod = i2 & 32767, pimod = head[hv];
16178
+ prev[imod] = pimod;
16179
+ head[hv] = imod;
16180
+ if (wi <= i2) {
16181
+ var rem = s - i2;
16182
+ if ((lc_1 > 7e3 || li > 24576) && (rem > 423 || !lst)) {
16183
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i2 - bs, pos);
16184
+ li = lc_1 = eb = 0, bs = i2;
16185
+ for (var j = 0; j < 286; ++j)
16186
+ lf[j] = 0;
16187
+ for (var j = 0; j < 30; ++j)
16188
+ df[j] = 0;
16189
+ }
16190
+ var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
16191
+ if (rem > 2 && hv == hsh(i2 - dif)) {
16192
+ var maxn = Math.min(n, rem) - 1;
16193
+ var maxd = Math.min(32767, i2);
16194
+ var ml = Math.min(258, rem);
16195
+ while (dif <= maxd && --ch_1 && imod != pimod) {
16196
+ if (dat[i2 + l] == dat[i2 + l - dif]) {
16197
+ var nl = 0;
16198
+ for (; nl < ml && dat[i2 + nl] == dat[i2 + nl - dif]; ++nl)
16199
+ ;
16200
+ if (nl > l) {
16201
+ l = nl, d = dif;
16202
+ if (nl > maxn)
16203
+ break;
16204
+ var mmd = Math.min(dif, nl - 2);
16205
+ var md = 0;
16206
+ for (var j = 0; j < mmd; ++j) {
16207
+ var ti = i2 - dif + j & 32767;
16208
+ var pti = prev[ti];
16209
+ var cd = ti - pti & 32767;
16210
+ if (cd > md)
16211
+ md = cd, pimod = ti;
16212
+ }
16213
+ }
16214
+ }
16215
+ imod = pimod, pimod = prev[imod];
16216
+ dif += imod - pimod & 32767;
16217
+ }
16218
+ }
16219
+ if (d) {
16220
+ syms[li++] = 268435456 | revfl[l] << 18 | revfd[d];
16221
+ var lin = revfl[l] & 31, din = revfd[d] & 31;
16222
+ eb += fleb[lin] + fdeb[din];
16223
+ ++lf[257 + lin];
16224
+ ++df[din];
16225
+ wi = i2 + l;
16226
+ ++lc_1;
16227
+ } else {
16228
+ syms[li++] = dat[i2];
16229
+ ++lf[dat[i2]];
16230
+ }
16231
+ }
16232
+ }
16233
+ for (i2 = Math.max(i2, wi); i2 < s; ++i2) {
16234
+ syms[li++] = dat[i2];
16235
+ ++lf[dat[i2]];
16236
+ }
16237
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i2 - bs, pos);
16238
+ if (!lst) {
16239
+ st.r = pos & 7 | w[pos / 8 | 0] << 3;
16240
+ pos -= 7;
16241
+ st.h = head, st.p = prev, st.i = i2, st.w = wi;
16242
+ }
16243
+ } else {
16244
+ for (var i2 = st.w || 0; i2 < s + lst; i2 += 65535) {
16245
+ var e = i2 + 65535;
16246
+ if (e >= s) {
16247
+ w[pos / 8 | 0] = lst;
16248
+ e = s;
16249
+ }
16250
+ pos = wfblk(w, pos + 1, dat.subarray(i2, e));
16251
+ }
16252
+ st.i = s;
16253
+ }
16254
+ return slc(o, 0, pre + shft(pos) + post);
16255
+ };
16256
+ var crct = /* @__PURE__ */ (function() {
16257
+ var t = new Int32Array(256);
16258
+ for (var i2 = 0; i2 < 256; ++i2) {
16259
+ var c = i2, k = 9;
16260
+ while (--k)
16261
+ c = (c & 1 && -306674912) ^ c >>> 1;
16262
+ t[i2] = c;
16263
+ }
16264
+ return t;
16265
+ })();
16266
+ var crc = function() {
16267
+ var c = -1;
16268
+ return {
16269
+ p: function(d) {
16270
+ var cr = c;
16271
+ for (var i2 = 0; i2 < d.length; ++i2)
16272
+ cr = crct[cr & 255 ^ d[i2]] ^ cr >>> 8;
16273
+ c = cr;
16274
+ },
16275
+ d: function() {
16276
+ return ~c;
16277
+ }
16278
+ };
16279
+ };
16280
+ var dopt = function(dat, opt, pre, post, st) {
16281
+ if (!st) {
16282
+ st = { l: 1 };
16283
+ if (opt.dictionary) {
16284
+ var dict = opt.dictionary.subarray(-32768);
16285
+ var newDat = new u8(dict.length + dat.length);
16286
+ newDat.set(dict);
16287
+ newDat.set(dat, dict.length);
16288
+ dat = newDat;
16289
+ st.w = dict.length;
16290
+ }
16291
+ }
16292
+ return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
16293
+ };
16294
+ var mrg = function(a, b) {
16295
+ var o = {};
16296
+ for (var k in a)
16297
+ o[k] = a[k];
16298
+ for (var k in b)
16299
+ o[k] = b[k];
16300
+ return o;
16301
+ };
16302
+ var wbytes = function(d, b, v) {
16303
+ for (; v; ++b)
16304
+ d[b] = v, v >>>= 8;
16305
+ };
15226
16306
  var gzs = function(d) {
15227
16307
  if (d[0] != 31 || d[1] != 139 || d[2] != 8)
15228
16308
  err(6, "invalid gzip data");
@@ -15245,6 +16325,9 @@ var zls = function(d, dict) {
15245
16325
  err(6, "invalid zlib data: " + (d[1] & 32 ? "need" : "unexpected") + " dictionary");
15246
16326
  return (d[1] >> 3 & 4) + 2;
15247
16327
  };
16328
+ function deflateSync(data, opts) {
16329
+ return dopt(data, opts || {}, 0, 0);
16330
+ }
15248
16331
  function inflateSync(data, opts) {
15249
16332
  return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
15250
16333
  }
@@ -15260,6 +16343,20 @@ function unzlibSync(data, opts) {
15260
16343
  function decompressSync(data, opts) {
15261
16344
  return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzipSync(data, opts) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflateSync(data, opts) : unzlibSync(data, opts);
15262
16345
  }
16346
+ var fltn = function(d, p, t, o) {
16347
+ for (var k in d) {
16348
+ var val = d[k], n = p + k, op = o;
16349
+ if (Array.isArray(val))
16350
+ op = mrg(o, val[1]), val = val[0];
16351
+ if (ArrayBuffer.isView(val))
16352
+ t[n] = [val, op];
16353
+ else {
16354
+ t[n += "/"] = [new u8(0), op];
16355
+ fltn(val, n, t, o);
16356
+ }
16357
+ }
16358
+ };
16359
+ var te = typeof TextEncoder != "undefined" && /* @__PURE__ */ new TextEncoder();
15263
16360
  var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
15264
16361
  var tds = 0;
15265
16362
  try {
@@ -15267,6 +16364,140 @@ try {
15267
16364
  tds = 1;
15268
16365
  } catch (e) {
15269
16366
  }
16367
+ function strToU8(str, latin1) {
16368
+ if (latin1) {
16369
+ var ar_1 = new u8(str.length);
16370
+ for (var i2 = 0; i2 < str.length; ++i2)
16371
+ ar_1[i2] = str.charCodeAt(i2);
16372
+ return ar_1;
16373
+ }
16374
+ if (te)
16375
+ return te.encode(str);
16376
+ var l = str.length;
16377
+ var ar = new u8(str.length + (str.length >> 1));
16378
+ var ai = 0;
16379
+ var w = function(v) {
16380
+ ar[ai++] = v;
16381
+ };
16382
+ for (var i2 = 0; i2 < l; ++i2) {
16383
+ if (ai + 5 > ar.length) {
16384
+ var n = new u8(ai + 8 + (l - i2 << 1));
16385
+ n.set(ar);
16386
+ ar = n;
16387
+ }
16388
+ var c = str.charCodeAt(i2);
16389
+ if (c < 128 || latin1)
16390
+ w(c);
16391
+ else if (c < 2048)
16392
+ w(192 | c >> 6), w(128 | c & 63);
16393
+ else if (c > 55295 && c < 57344)
16394
+ c = 65536 + (c & 1023 << 10) | str.charCodeAt(++i2) & 1023, w(240 | c >> 18), w(128 | c >> 12 & 63), w(128 | c >> 6 & 63), w(128 | c & 63);
16395
+ else
16396
+ w(224 | c >> 12), w(128 | c >> 6 & 63), w(128 | c & 63);
16397
+ }
16398
+ return slc(ar, 0, ai);
16399
+ }
16400
+ var exfl = function(ex) {
16401
+ var le = 0;
16402
+ if (ex) {
16403
+ for (var k in ex) {
16404
+ var l = ex[k].length;
16405
+ if (l > 65535)
16406
+ err(9);
16407
+ le += l + 4;
16408
+ }
16409
+ }
16410
+ return le;
16411
+ };
16412
+ var wzh = function(d, b, f, fn, u, c, ce, co) {
16413
+ var fl2 = fn.length, ex = f.extra, col = co && co.length;
16414
+ var exl = exfl(ex);
16415
+ wbytes(d, b, ce != null ? 33639248 : 67324752), b += 4;
16416
+ if (ce != null)
16417
+ d[b++] = 20, d[b++] = f.os;
16418
+ d[b] = 20, b += 2;
16419
+ d[b++] = f.flag << 1 | (c < 0 && 8), d[b++] = u && 8;
16420
+ d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
16421
+ var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
16422
+ if (y < 0 || y > 119)
16423
+ err(10);
16424
+ wbytes(d, b, y << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >> 1), b += 4;
16425
+ if (c != -1) {
16426
+ wbytes(d, b, f.crc);
16427
+ wbytes(d, b + 4, c < 0 ? -c - 2 : c);
16428
+ wbytes(d, b + 8, f.size);
16429
+ }
16430
+ wbytes(d, b + 12, fl2);
16431
+ wbytes(d, b + 14, exl), b += 16;
16432
+ if (ce != null) {
16433
+ wbytes(d, b, col);
16434
+ wbytes(d, b + 6, f.attrs);
16435
+ wbytes(d, b + 10, ce), b += 14;
16436
+ }
16437
+ d.set(fn, b);
16438
+ b += fl2;
16439
+ if (exl) {
16440
+ for (var k in ex) {
16441
+ var exf = ex[k], l = exf.length;
16442
+ wbytes(d, b, +k);
16443
+ wbytes(d, b + 2, l);
16444
+ d.set(exf, b + 4), b += 4 + l;
16445
+ }
16446
+ }
16447
+ if (col)
16448
+ d.set(co, b), b += col;
16449
+ return b;
16450
+ };
16451
+ var wzf = function(o, b, c, d, e) {
16452
+ wbytes(o, b, 101010256);
16453
+ wbytes(o, b + 8, c);
16454
+ wbytes(o, b + 10, c);
16455
+ wbytes(o, b + 12, d);
16456
+ wbytes(o, b + 16, e);
16457
+ };
16458
+ function zipSync(data, opts) {
16459
+ if (!opts)
16460
+ opts = {};
16461
+ var r = {};
16462
+ var files = [];
16463
+ fltn(data, "", r, opts);
16464
+ var o = 0;
16465
+ var tot = 0;
16466
+ for (var fn in r) {
16467
+ var _a2 = r[fn], file = _a2[0], p = _a2[1];
16468
+ var compression = p.level == 0 ? 0 : 8;
16469
+ var f = strToU8(fn), s = f.length;
16470
+ var com = p.comment, m = com && strToU8(com), ms = m && m.length;
16471
+ var exl = exfl(p.extra);
16472
+ if (s > 65535)
16473
+ err(11);
16474
+ var d = compression ? deflateSync(file, p) : file, l = d.length;
16475
+ var c = crc();
16476
+ c.p(file);
16477
+ files.push(mrg(p, {
16478
+ size: file.length,
16479
+ crc: c.d(),
16480
+ c: d,
16481
+ f,
16482
+ m,
16483
+ u: s != fn.length || m && com.length != ms,
16484
+ o,
16485
+ compression
16486
+ }));
16487
+ o += 30 + s + exl + l;
16488
+ tot += 76 + 2 * (s + exl) + (ms || 0) + l;
16489
+ }
16490
+ var out = new u8(tot + 22), oe = o, cdl = tot - o;
16491
+ for (var i2 = 0; i2 < files.length; ++i2) {
16492
+ var f = files[i2];
16493
+ wzh(out, f.o, f, f.f, f.u, f.c.length);
16494
+ var badd = 30 + f.f.length + exfl(f.extra);
16495
+ out.set(f.c, f.o + badd);
16496
+ wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
16497
+ }
16498
+ wzf(out, o, files.length, cdl, oe);
16499
+ return out;
16500
+ }
15270
16501
 
15271
16502
  // node_modules/.pnpm/@tokenizer+inflate@0.2.7/node_modules/@tokenizer/inflate/lib/index.js
15272
16503
  var import_debug = __toESM(require_src(), 1);
@@ -20017,10 +21248,10 @@ function resolveAll(constructs2, events, context) {
20017
21248
  const called = [];
20018
21249
  let index2 = -1;
20019
21250
  while (++index2 < constructs2.length) {
20020
- const resolve9 = constructs2[index2].resolveAll;
20021
- if (resolve9 && !called.includes(resolve9)) {
20022
- events = resolve9(events, context);
20023
- called.push(resolve9);
21251
+ const resolve10 = constructs2[index2].resolveAll;
21252
+ if (resolve10 && !called.includes(resolve10)) {
21253
+ events = resolve10(events, context);
21254
+ called.push(resolve10);
20024
21255
  }
20025
21256
  }
20026
21257
  return events;
@@ -20034,7 +21265,7 @@ var attention = {
20034
21265
  };
20035
21266
  function resolveAllAttention(events, context) {
20036
21267
  let index2 = -1;
20037
- let open;
21268
+ let open2;
20038
21269
  let group;
20039
21270
  let text3;
20040
21271
  let openingSequence;
@@ -20044,16 +21275,16 @@ function resolveAllAttention(events, context) {
20044
21275
  let offset;
20045
21276
  while (++index2 < events.length) {
20046
21277
  if (events[index2][0] === "enter" && events[index2][1].type === "attentionSequence" && events[index2][1]._close) {
20047
- open = index2;
20048
- while (open--) {
20049
- if (events[open][0] === "exit" && events[open][1].type === "attentionSequence" && events[open][1]._open && // If the markers are the same:
20050
- context.sliceSerialize(events[open][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
20051
- if ((events[open][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open][1].end.offset - events[open][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
21278
+ open2 = index2;
21279
+ while (open2--) {
21280
+ if (events[open2][0] === "exit" && events[open2][1].type === "attentionSequence" && events[open2][1]._open && // If the markers are the same:
21281
+ context.sliceSerialize(events[open2][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
21282
+ if ((events[open2][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open2][1].end.offset - events[open2][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
20052
21283
  continue;
20053
21284
  }
20054
- use = events[open][1].end.offset - events[open][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
21285
+ use = events[open2][1].end.offset - events[open2][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
20055
21286
  const start = {
20056
- ...events[open][1].end
21287
+ ...events[open2][1].end
20057
21288
  };
20058
21289
  const end = {
20059
21290
  ...events[index2][1].start
@@ -20064,7 +21295,7 @@ function resolveAllAttention(events, context) {
20064
21295
  type: use > 1 ? "strongSequence" : "emphasisSequence",
20065
21296
  start,
20066
21297
  end: {
20067
- ...events[open][1].end
21298
+ ...events[open2][1].end
20068
21299
  }
20069
21300
  };
20070
21301
  closingSequence = {
@@ -20077,7 +21308,7 @@ function resolveAllAttention(events, context) {
20077
21308
  text3 = {
20078
21309
  type: use > 1 ? "strongText" : "emphasisText",
20079
21310
  start: {
20080
- ...events[open][1].end
21311
+ ...events[open2][1].end
20081
21312
  },
20082
21313
  end: {
20083
21314
  ...events[index2][1].start
@@ -20092,18 +21323,18 @@ function resolveAllAttention(events, context) {
20092
21323
  ...closingSequence.end
20093
21324
  }
20094
21325
  };
20095
- events[open][1].end = {
21326
+ events[open2][1].end = {
20096
21327
  ...openingSequence.start
20097
21328
  };
20098
21329
  events[index2][1].start = {
20099
21330
  ...closingSequence.end
20100
21331
  };
20101
21332
  nextEvents = [];
20102
- if (events[open][1].end.offset - events[open][1].start.offset) {
20103
- nextEvents = push(nextEvents, [["enter", events[open][1], context], ["exit", events[open][1], context]]);
21333
+ if (events[open2][1].end.offset - events[open2][1].start.offset) {
21334
+ nextEvents = push(nextEvents, [["enter", events[open2][1], context], ["exit", events[open2][1], context]]);
20104
21335
  }
20105
21336
  nextEvents = push(nextEvents, [["enter", group, context], ["enter", openingSequence, context], ["exit", openingSequence, context], ["enter", text3, context]]);
20106
- nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + 1, index2), context));
21337
+ nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open2 + 1, index2), context));
20107
21338
  nextEvents = push(nextEvents, [["exit", text3, context], ["enter", closingSequence, context], ["exit", closingSequence, context], ["exit", group, context]]);
20108
21339
  if (events[index2][1].end.offset - events[index2][1].start.offset) {
20109
21340
  offset = 2;
@@ -20111,8 +21342,8 @@ function resolveAllAttention(events, context) {
20111
21342
  } else {
20112
21343
  offset = 0;
20113
21344
  }
20114
- splice(events, open - 1, index2 - open + 3, nextEvents);
20115
- index2 = open + nextEvents.length - offset - 2;
21345
+ splice(events, open2 - 1, index2 - open2 + 3, nextEvents);
21346
+ index2 = open2 + nextEvents.length - offset - 2;
20116
21347
  break;
20117
21348
  }
20118
21349
  }
@@ -20144,10 +21375,10 @@ function tokenizeAttention(effects, ok2) {
20144
21375
  }
20145
21376
  const token = effects.exit("attentionSequence");
20146
21377
  const after = classifyCharacter(code);
20147
- const open = !after || after === 2 && before || attentionMarkers2.includes(code);
21378
+ const open2 = !after || after === 2 && before || attentionMarkers2.includes(code);
20148
21379
  const close = !before || before === 2 && after || attentionMarkers2.includes(previous2);
20149
- token._open = Boolean(marker === 42 ? open : open && (before || !close));
20150
- token._close = Boolean(marker === 42 ? close : close && (after || !open));
21380
+ token._open = Boolean(marker === 42 ? open2 : open2 && (before || !close));
21381
+ token._close = Boolean(marker === 42 ? close : close && (after || !open2));
20151
21382
  return ok2(code);
20152
21383
  }
20153
21384
  }
@@ -20172,9 +21403,9 @@ function tokenizeAutolink(effects, ok2, nok) {
20172
21403
  effects.consume(code);
20173
21404
  effects.exit("autolinkMarker");
20174
21405
  effects.enter("autolinkProtocol");
20175
- return open;
21406
+ return open2;
20176
21407
  }
20177
- function open(code) {
21408
+ function open2(code) {
20178
21409
  if (asciiAlpha(code)) {
20179
21410
  effects.consume(code);
20180
21411
  return schemeOrEmailAtext;
@@ -20378,9 +21609,9 @@ function tokenizeCharacterReference(effects, ok2, nok) {
20378
21609
  effects.enter("characterReferenceMarker");
20379
21610
  effects.consume(code);
20380
21611
  effects.exit("characterReferenceMarker");
20381
- return open;
21612
+ return open2;
20382
21613
  }
20383
- function open(code) {
21614
+ function open2(code) {
20384
21615
  if (code === 35) {
20385
21616
  effects.enter("characterReferenceMarkerNumeric");
20386
21617
  effects.consume(code);
@@ -21772,9 +23003,9 @@ function tokenizeHtmlFlow(effects, ok2, nok) {
21772
23003
  effects.enter("htmlFlow");
21773
23004
  effects.enter("htmlFlowData");
21774
23005
  effects.consume(code);
21775
- return open;
23006
+ return open2;
21776
23007
  }
21777
- function open(code) {
23008
+ function open2(code) {
21778
23009
  if (code === 33) {
21779
23010
  effects.consume(code);
21780
23011
  return declarationOpen;
@@ -22123,9 +23354,9 @@ function tokenizeHtmlText(effects, ok2, nok) {
22123
23354
  effects.enter("htmlText");
22124
23355
  effects.enter("htmlTextData");
22125
23356
  effects.consume(code);
22126
- return open;
23357
+ return open2;
22127
23358
  }
22128
- function open(code) {
23359
+ function open2(code) {
22129
23360
  if (code === 33) {
22130
23361
  effects.consume(code);
22131
23362
  return declarationOpen;
@@ -22452,12 +23683,12 @@ function resolveToLabelEnd(events, context) {
22452
23683
  let index2 = events.length;
22453
23684
  let offset = 0;
22454
23685
  let token;
22455
- let open;
23686
+ let open2;
22456
23687
  let close;
22457
23688
  let media;
22458
23689
  while (index2--) {
22459
23690
  token = events[index2][1];
22460
- if (open) {
23691
+ if (open2) {
22461
23692
  if (token.type === "link" || token.type === "labelLink" && token._inactive) {
22462
23693
  break;
22463
23694
  }
@@ -22466,7 +23697,7 @@ function resolveToLabelEnd(events, context) {
22466
23697
  }
22467
23698
  } else if (close) {
22468
23699
  if (events[index2][0] === "enter" && (token.type === "labelImage" || token.type === "labelLink") && !token._balanced) {
22469
- open = index2;
23700
+ open2 = index2;
22470
23701
  if (token.type !== "labelLink") {
22471
23702
  offset = 2;
22472
23703
  break;
@@ -22477,9 +23708,9 @@ function resolveToLabelEnd(events, context) {
22477
23708
  }
22478
23709
  }
22479
23710
  const group = {
22480
- type: events[open][1].type === "labelLink" ? "link" : "image",
23711
+ type: events[open2][1].type === "labelLink" ? "link" : "image",
22481
23712
  start: {
22482
- ...events[open][1].start
23713
+ ...events[open2][1].start
22483
23714
  },
22484
23715
  end: {
22485
23716
  ...events[events.length - 1][1].end
@@ -22488,7 +23719,7 @@ function resolveToLabelEnd(events, context) {
22488
23719
  const label = {
22489
23720
  type: "label",
22490
23721
  start: {
22491
- ...events[open][1].start
23722
+ ...events[open2][1].start
22492
23723
  },
22493
23724
  end: {
22494
23725
  ...events[close][1].end
@@ -22497,20 +23728,20 @@ function resolveToLabelEnd(events, context) {
22497
23728
  const text3 = {
22498
23729
  type: "labelText",
22499
23730
  start: {
22500
- ...events[open + offset + 2][1].end
23731
+ ...events[open2 + offset + 2][1].end
22501
23732
  },
22502
23733
  end: {
22503
23734
  ...events[close - 2][1].start
22504
23735
  }
22505
23736
  };
22506
23737
  media = [["enter", group, context], ["enter", label, context]];
22507
- media = push(media, events.slice(open + 1, open + offset + 3));
23738
+ media = push(media, events.slice(open2 + 1, open2 + offset + 3));
22508
23739
  media = push(media, [["enter", text3, context]]);
22509
- media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + offset + 4, close - 3), context));
23740
+ media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open2 + offset + 4, close - 3), context));
22510
23741
  media = push(media, [["exit", text3, context], events[close - 2], events[close - 1], ["exit", label, context]]);
22511
23742
  media = push(media, events.slice(close + 1));
22512
23743
  media = push(media, [["exit", group, context]]);
22513
- splice(events, open, events.length, media);
23744
+ splice(events, open2, events.length, media);
22514
23745
  return events;
22515
23746
  }
22516
23747
  function tokenizeLabelEnd(effects, ok2, nok) {
@@ -22656,9 +23887,9 @@ function tokenizeLabelStartImage(effects, ok2, nok) {
22656
23887
  effects.enter("labelImageMarker");
22657
23888
  effects.consume(code);
22658
23889
  effects.exit("labelImageMarker");
22659
- return open;
23890
+ return open2;
22660
23891
  }
22661
- function open(code) {
23892
+ function open2(code) {
22662
23893
  if (code === 91) {
22663
23894
  effects.enter("labelMarker");
22664
23895
  effects.consume(code);
@@ -23979,8 +25210,8 @@ function compiler(options) {
23979
25210
  return length;
23980
25211
  }
23981
25212
  function opener(create, and) {
23982
- return open;
23983
- function open(token) {
25213
+ return open2;
25214
+ function open2(token) {
23984
25215
  enter.call(this, create(token), token);
23985
25216
  if (and) and.call(this, token);
23986
25217
  }
@@ -24012,18 +25243,18 @@ function compiler(options) {
24012
25243
  }
24013
25244
  function exit2(token, onExitError) {
24014
25245
  const node2 = this.stack.pop();
24015
- const open = this.tokenStack.pop();
24016
- if (!open) {
25246
+ const open2 = this.tokenStack.pop();
25247
+ if (!open2) {
24017
25248
  throw new Error("Cannot close `" + token.type + "` (" + stringifyPosition({
24018
25249
  start: token.start,
24019
25250
  end: token.end
24020
25251
  }) + "): it\u2019s not open");
24021
- } else if (open[0].type !== token.type) {
25252
+ } else if (open2[0].type !== token.type) {
24022
25253
  if (onExitError) {
24023
- onExitError.call(this, token, open[0]);
25254
+ onExitError.call(this, token, open2[0]);
24024
25255
  } else {
24025
- const handler = open[1] || defaultOnError;
24026
- handler.call(this, token, open[0]);
25256
+ const handler = open2[1] || defaultOnError;
25257
+ handler.call(this, token, open2[0]);
24027
25258
  }
24028
25259
  }
24029
25260
  node2.position.end = point2(token.end);
@@ -24706,7 +25937,7 @@ function collectImageCandidates(content3) {
24706
25937
  const tree = fromMarkdown(content3);
24707
25938
  const syntaxByRange = collectImageSyntax(content3);
24708
25939
  const definitions = /* @__PURE__ */ new Map();
24709
- const candidates = [];
25940
+ const candidates2 = [];
24710
25941
  visit(tree, "definition", (node2) => {
24711
25942
  definitions.set(node2.identifier, node2);
24712
25943
  });
@@ -24717,7 +25948,7 @@ function collectImageCandidates(content3) {
24717
25948
  }
24718
25949
  const destinationRange = syntaxByRange.get(rangeKey(range))?.destinationRange;
24719
25950
  if (destinationRange) {
24720
- candidates.push({
25951
+ candidates2.push({
24721
25952
  kind: "inline",
24722
25953
  destination: node2.url,
24723
25954
  destinationRange
@@ -24734,7 +25965,7 @@ function collectImageCandidates(content3) {
24734
25965
  if (!syntax) {
24735
25966
  return;
24736
25967
  }
24737
- candidates.push({
25968
+ candidates2.push({
24738
25969
  kind: "reference",
24739
25970
  destination: definition2.url,
24740
25971
  range,
@@ -24742,7 +25973,7 @@ function collectImageCandidates(content3) {
24742
25973
  title: definition2.title ?? null
24743
25974
  });
24744
25975
  });
24745
- return candidates;
25976
+ return candidates2;
24746
25977
  }
24747
25978
  function isRemoteDestination(destination) {
24748
25979
  if (WINDOWS_DRIVE_RE.test(destination)) {
@@ -25076,13 +26307,13 @@ function registerFileCommand(program3) {
25076
26307
  const outputMode = options.json ? "json" : "text";
25077
26308
  const mode = runFileReadResolverOrExit(() => resolveReadMode(options), outputMode);
25078
26309
  let response;
25079
- let displayPath;
26310
+ let displayPath2;
25080
26311
  let requestPath;
25081
26312
  if (mode.kind === "by-url") {
25082
- displayPath = mode.url;
26313
+ displayPath2 = mode.url;
25083
26314
  requestPath = `/files/read-by-url?url=${encodeURIComponent(mode.url)}`;
25084
26315
  } else {
25085
- displayPath = mode.path;
26316
+ displayPath2 = mode.path;
25086
26317
  const spaceParams = runFileReadResolverOrExit(
25087
26318
  () => resolveSpaceSelector(options),
25088
26319
  outputMode
@@ -25124,7 +26355,7 @@ function registerFileCommand(program3) {
25124
26355
  if (response.status === 404) {
25125
26356
  exitFileReadJson({
25126
26357
  code: "not_found",
25127
- message: `${displayPath} does not exist`,
26358
+ message: `${displayPath2} does not exist`,
25128
26359
  status: response.status,
25129
26360
  details: response.data
25130
26361
  });
@@ -25137,7 +26368,7 @@ function registerFileCommand(program3) {
25137
26368
  });
25138
26369
  }
25139
26370
  if (response.status === 404) {
25140
- print(`${colors.red}\u2620 ${displayPath} does not exist${colors.reset}`);
26371
+ print(`${colors.red}\u2620 ${displayPath2} does not exist${colors.reset}`);
25141
26372
  } else {
25142
26373
  printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
25143
26374
  }
@@ -25148,12 +26379,12 @@ function registerFileCommand(program3) {
25148
26379
  if (options.json) {
25149
26380
  exitFileReadJson({
25150
26381
  code: "not_a_file",
25151
- message: `${displayPath} is a directory`,
26382
+ message: `${displayPath2} is a directory`,
25152
26383
  status: null,
25153
26384
  details: null
25154
26385
  });
25155
26386
  }
25156
- print(`${colors.red}\u2620 ${displayPath} is a directory${colors.reset}`);
26387
+ print(`${colors.red}\u2620 ${displayPath2} is a directory${colors.reset}`);
25157
26388
  process.exit(1);
25158
26389
  }
25159
26390
  if (options.json) {
@@ -25198,15 +26429,15 @@ function registerFileCommand(program3) {
25198
26429
  }
25199
26430
  startSpinner("Uploading...");
25200
26431
  let response;
25201
- let displayPath;
26432
+ let displayPath2;
25202
26433
  if (mode.kind === "by-url") {
25203
- displayPath = mode.url;
26434
+ displayPath2 = mode.url;
25204
26435
  response = await httpPut("/files/write-by-url", {
25205
26436
  url: mode.url,
25206
26437
  content: content3
25207
26438
  });
25208
26439
  } else {
25209
- displayPath = mode.path;
26440
+ displayPath2 = mode.path;
25210
26441
  const spaceParams = runOrExit2(() => resolveSpaceSelector(options));
25211
26442
  response = await httpPut(
25212
26443
  `/workspaces/${mode.workspace}/files/write`,
@@ -25222,7 +26453,7 @@ function registerFileCommand(program3) {
25222
26453
  stopSpinner(false, "Failed");
25223
26454
  if (response.status === 404) {
25224
26455
  if (mode.kind === "by-url") {
25225
- print(`${colors.red}\u2620 ${displayPath} does not exist${colors.reset}`);
26456
+ print(`${colors.red}\u2620 ${displayPath2} does not exist${colors.reset}`);
25226
26457
  } else {
25227
26458
  print(`${colors.red}\u2620 Parent directory does not exist${colors.reset}`);
25228
26459
  }
@@ -25335,6 +26566,284 @@ function registerMemoryCommand(program3) {
25335
26566
 
25336
26567
  // src/commands/machine.ts
25337
26568
  init_cjs_shims();
26569
+
26570
+ // src/commands/machine-dump.ts
26571
+ init_cjs_shims();
26572
+ var import_node_fs = require("fs");
26573
+ var import_promises3 = require("fs/promises");
26574
+ var import_node_os = require("os");
26575
+ var import_node_path = require("path");
26576
+ var redactedValue = "[REDACTED]";
26577
+ var candidates = [
26578
+ ...connectorLogCandidates("machine-connector.log"),
26579
+ ...connectorLogCandidates("machine-connector.error.log"),
26580
+ ...connectorLogCandidates("supervisor/supervisord.log"),
26581
+ {
26582
+ archivePath: "state/runtime-status.json",
26583
+ sourceName: "runtime-status.json"
26584
+ },
26585
+ {
26586
+ archivePath: "state/service-manager.json",
26587
+ sourceName: "service-manager.json"
26588
+ }
26589
+ ];
26590
+ async function createMachineDump(options) {
26591
+ const outputPath = (0, import_node_path.resolve)(
26592
+ options.outputPath ?? defaultDumpFilename(/* @__PURE__ */ new Date())
26593
+ );
26594
+ const entries = {};
26595
+ const included = [];
26596
+ const skipped = [];
26597
+ const runtimeRoot = await canonicalRuntimeRoot(options.runtimeDirectory);
26598
+ for (const candidate of candidates) {
26599
+ const content3 = await readAllowlistedFile(
26600
+ runtimeRoot,
26601
+ candidate.sourceName
26602
+ );
26603
+ if (content3.status !== "available") {
26604
+ skipped.push({
26605
+ reason: content3.status,
26606
+ sourceName: candidate.sourceName
26607
+ });
26608
+ continue;
26609
+ }
26610
+ entries[candidate.archivePath] = strToU8(redactSecrets(content3.value));
26611
+ included.push(candidate.archivePath);
26612
+ }
26613
+ const daemonSocketPresent = await pathExistsInsideRuntime(
26614
+ runtimeRoot,
26615
+ "machine-connector.sock"
26616
+ );
26617
+ entries["diagnostics.json"] = strToU8(
26618
+ `${JSON.stringify(
26619
+ {
26620
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
26621
+ cliVersion: options.cliVersion,
26622
+ nodeVersion: process.version,
26623
+ platform: process.platform,
26624
+ architecture: process.arch,
26625
+ runtimeDirectory: displayPath(options.runtimeDirectory),
26626
+ daemonSocketPresent,
26627
+ daemonLockPresent: await pathExistsInsideRuntime(
26628
+ runtimeRoot,
26629
+ "daemon.lock"
26630
+ ),
26631
+ reconcileLockPresent: await pathExistsInsideRuntime(
26632
+ runtimeRoot,
26633
+ "daemon-reconcile.lock"
26634
+ ),
26635
+ supervisorPidPresent: await pathExistsInsideRuntime(
26636
+ runtimeRoot,
26637
+ "supervisor/supervisord.pid"
26638
+ ),
26639
+ included,
26640
+ skipped,
26641
+ security: {
26642
+ redactionApplied: true,
26643
+ excluded: [
26644
+ "connections and pairing credentials",
26645
+ "device private key and identity",
26646
+ "Job payloads, output, and process state",
26647
+ "Local Codex Runtime attempt state",
26648
+ "service definitions and environment variables",
26649
+ "sockets, lock contents, browser data, and .env files",
26650
+ "all unrecognized files"
26651
+ ]
26652
+ }
26653
+ },
26654
+ void 0,
26655
+ 2
26656
+ )}
26657
+ `
26658
+ );
26659
+ included.unshift("diagnostics.json");
26660
+ await (0, import_promises3.mkdir)((0, import_node_path.dirname)(outputPath), { recursive: true });
26661
+ await (0, import_promises3.writeFile)(outputPath, zipSync(entries, { level: 6 }), {
26662
+ flag: "wx",
26663
+ mode: 384
26664
+ });
26665
+ return { included, outputPath, skipped };
26666
+ }
26667
+ function connectorLogCandidates(sourceName) {
26668
+ return ["", ".1", ".2", ".3"].map((suffix) => ({
26669
+ archivePath: `logs/${sourceName}${suffix}`,
26670
+ sourceName: `${sourceName}${suffix}`
26671
+ }));
26672
+ }
26673
+ async function readAllowlistedFile(runtimeRoot, sourceName) {
26674
+ if (runtimeRoot === void 0) return { status: "missing" };
26675
+ const path4 = (0, import_node_path.resolve)(runtimeRoot, sourceName);
26676
+ try {
26677
+ const metadata = await (0, import_promises3.lstat)(path4);
26678
+ if (!metadata.isFile()) return { status: "not a regular file" };
26679
+ const canonicalPath = await (0, import_promises3.realpath)(path4);
26680
+ if (!pathIsInside(runtimeRoot, canonicalPath)) {
26681
+ return { status: "outside runtime directory" };
26682
+ }
26683
+ const handle = await (0, import_promises3.open)(
26684
+ path4,
26685
+ import_node_fs.constants.O_RDONLY | (import_node_fs.constants.O_NOFOLLOW ?? 0)
26686
+ );
26687
+ try {
26688
+ const openedMetadata = await handle.stat();
26689
+ if (!openedMetadata.isFile()) {
26690
+ return { status: "not a regular file" };
26691
+ }
26692
+ const openedPathStatus = await validateOpenedPath(
26693
+ runtimeRoot,
26694
+ path4,
26695
+ openedMetadata
26696
+ );
26697
+ if (openedPathStatus !== "available") {
26698
+ return { status: openedPathStatus };
26699
+ }
26700
+ return { status: "available", value: await handle.readFile("utf8") };
26701
+ } finally {
26702
+ await handle.close();
26703
+ }
26704
+ } catch (error) {
26705
+ if (isNodeErrorCode(error, "ENOENT")) return { status: "missing" };
26706
+ if (isNodeErrorCode(error, "ENOTDIR")) {
26707
+ return { status: "not a regular file" };
26708
+ }
26709
+ if (isNodeErrorCode(error, "ELOOP")) {
26710
+ return { status: "not a regular file" };
26711
+ }
26712
+ throw error;
26713
+ }
26714
+ }
26715
+ async function validateOpenedPath(runtimeRoot, path4, openedMetadata) {
26716
+ try {
26717
+ const canonicalPath = await (0, import_promises3.realpath)(path4);
26718
+ if (!pathIsInside(runtimeRoot, canonicalPath)) {
26719
+ return "outside runtime directory";
26720
+ }
26721
+ const currentMetadata = await (0, import_promises3.stat)(path4);
26722
+ if (currentMetadata.dev !== openedMetadata.dev || currentMetadata.ino !== openedMetadata.ino) {
26723
+ return "path changed while reading";
26724
+ }
26725
+ return "available";
26726
+ } catch (error) {
26727
+ if (isNodeErrorCode(error, "ENOENT")) {
26728
+ return "path changed while reading";
26729
+ }
26730
+ throw error;
26731
+ }
26732
+ }
26733
+ async function canonicalRuntimeRoot(path4) {
26734
+ try {
26735
+ const canonicalPath = await (0, import_promises3.realpath)(path4);
26736
+ const metadata = await (0, import_promises3.stat)(canonicalPath);
26737
+ return metadata.isDirectory() ? canonicalPath : void 0;
26738
+ } catch (error) {
26739
+ if (isNodeErrorCode(error, "ENOENT") || isNodeErrorCode(error, "ENOTDIR") || isNodeErrorCode(error, "ELOOP")) {
26740
+ return void 0;
26741
+ }
26742
+ throw error;
26743
+ }
26744
+ }
26745
+ function pathIsInside(runtimeRoot, path4) {
26746
+ const relativePath = (0, import_node_path.relative)(runtimeRoot, path4);
26747
+ return relativePath === "" || relativePath !== ".." && !relativePath.startsWith(`..${import_node_path.sep}`) && !(0, import_node_path.isAbsolute)(relativePath);
26748
+ }
26749
+ function redactSecrets(value) {
26750
+ const structured = redactStructuredText(value);
26751
+ return structured.replace(
26752
+ /-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/giu,
26753
+ redactedValue
26754
+ ).replace(
26755
+ /(\b(?:authorization|proxy-authorization)\s*[:=]\s*(?:bearer|basic)\s+)[^\s,"']+/giu,
26756
+ `$1${redactedValue}`
26757
+ ).replace(
26758
+ /(\b(?:cookie|set-cookie)\s*[:=]\s*)[^\r\n]+/giu,
26759
+ `$1${redactedValue}`
26760
+ ).replace(
26761
+ /(["'][A-Za-z0-9_-]*(?:token|secret|password|passphrase|api[_-]?key|authorization|private[_-]?key|credential|connection[_-]?string|cookie|pairing[_-]?code)[A-Za-z0-9_-]*["']\s*:\s*["'])[^"']*(["'])/giu,
26762
+ `$1${redactedValue}$2`
26763
+ ).replace(
26764
+ /(\b[A-Za-z0-9_-]*(?:token|secret|password|passphrase|api[_-]?key|authorization|private[_-]?key|credential|connection[_-]?string|cookie|pairing[_-]?code)[A-Za-z0-9_-]*\s*=\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu,
26765
+ `$1${redactedValue}`
26766
+ ).replace(
26767
+ /(--(?:access-token|refresh-token|token|secret|password|api-key|credential|connection-string|pairing-code)\s+)(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu,
26768
+ `$1${redactedValue}`
26769
+ ).replace(
26770
+ /([?&](?:access_token|refresh_token|token|secret|password|api_key|key|code)=)[^&#\s]+/giu,
26771
+ `$1${redactedValue}`
26772
+ ).replace(
26773
+ /([a-z][a-z0-9+.-]*:\/\/[^:\s/@]+:)[^@\s/]+(@)/giu,
26774
+ `$1${redactedValue}$2`
26775
+ ).replace(
26776
+ /\b(?:github_pat_|gh[pousr]_|sk-|moxt_)[A-Za-z0-9_-]{8,}\b/gu,
26777
+ redactedValue
26778
+ ).replace(
26779
+ /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/gu,
26780
+ redactedValue
26781
+ );
26782
+ }
26783
+ function redactStructuredText(value) {
26784
+ const parsed = parseJson(value);
26785
+ if (parsed !== void 0) {
26786
+ return `${JSON.stringify(redactJsonValue(parsed), void 0, 2)}
26787
+ `;
26788
+ }
26789
+ return value.split("\n").map((line) => {
26790
+ const parsedLine = parseJson(line);
26791
+ return parsedLine === void 0 ? line : JSON.stringify(redactJsonValue(parsedLine));
26792
+ }).join("\n");
26793
+ }
26794
+ function redactJsonValue(value) {
26795
+ if (Array.isArray(value)) return value.map(redactJsonValue);
26796
+ if (value === null || typeof value !== "object") return value;
26797
+ return Object.fromEntries(
26798
+ Object.entries(value).map(([key, nestedValue]) => [
26799
+ key,
26800
+ sensitiveKey(key) ? redactedValue : redactJsonValue(nestedValue)
26801
+ ])
26802
+ );
26803
+ }
26804
+ function sensitiveKey(key) {
26805
+ return /token|secret|password|passphrase|api.?key|authorization|private.?key|credential|connection.?string|cookie|pairing.?code/iu.test(
26806
+ key
26807
+ );
26808
+ }
26809
+ function parseJson(value) {
26810
+ if (value.trim() === "") return void 0;
26811
+ try {
26812
+ return JSON.parse(value);
26813
+ } catch {
26814
+ return void 0;
26815
+ }
26816
+ }
26817
+ async function pathExistsInsideRuntime(runtimeRoot, sourceName) {
26818
+ if (runtimeRoot === void 0) return false;
26819
+ const path4 = (0, import_node_path.resolve)(runtimeRoot, sourceName);
26820
+ try {
26821
+ const canonicalPath = await (0, import_promises3.realpath)(path4);
26822
+ return pathIsInside(runtimeRoot, canonicalPath);
26823
+ } catch (error) {
26824
+ if (isNodeErrorCode(error, "ENOENT") || isNodeErrorCode(error, "ENOTDIR") || isNodeErrorCode(error, "ELOOP")) {
26825
+ return false;
26826
+ }
26827
+ throw error;
26828
+ }
26829
+ }
26830
+ function displayPath(path4) {
26831
+ const home = process.env.HOME ?? (0, import_node_os.homedir)();
26832
+ const relativeToHome = (0, import_node_path.relative)(home, path4);
26833
+ if (relativeToHome === "" || !relativeToHome.startsWith(`..${import_node_path.sep}`) && relativeToHome !== "..") {
26834
+ return relativeToHome === "" ? "~" : (0, import_node_path.join)("~", relativeToHome);
26835
+ }
26836
+ return path4;
26837
+ }
26838
+ function defaultDumpFilename(date) {
26839
+ const timestamp = date.toISOString().replace(/[-:]/gu, "").replace(/\.\d{3}Z$/u, "Z");
26840
+ return `moxt-machine-dump-${timestamp}.zip`;
26841
+ }
26842
+ function isNodeErrorCode(error, code) {
26843
+ return error instanceof Error && "code" in error && error.code === code;
26844
+ }
26845
+
26846
+ // src/commands/machine.ts
25338
26847
  var serviceManagerOption = new Option(
25339
26848
  "--service-manager <manager>",
25340
26849
  "Background service manager: auto, systemd, supervisor, or none"
@@ -25378,6 +26887,24 @@ function registerMachineCommand(program3, cliVersion) {
25378
26887
  ...options.json ? ["--json"] : []
25379
26888
  ]);
25380
26889
  });
26890
+ machine.command("dump").description("Create a redacted Connector support archive").option("--output <path>", "Zip archive output path").action(async (options) => {
26891
+ const { defaultRuntimeDirectory: defaultRuntimeDirectory2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
26892
+ const result = await createMachineDump({
26893
+ cliVersion,
26894
+ outputPath: options.output,
26895
+ runtimeDirectory: defaultRuntimeDirectory2()
26896
+ });
26897
+ for (const path4 of result.included) {
26898
+ console.log(`Included: ${path4}`);
26899
+ }
26900
+ for (const skipped of result.skipped) {
26901
+ const reason = skipped.reason === "missing" ? "not found" : skipped.reason;
26902
+ console.log(
26903
+ `Skipped (${reason}): ${skipped.sourceName}`
26904
+ );
26905
+ }
26906
+ console.log(`Archive: ${result.outputPath}`);
26907
+ });
25381
26908
  machine.command("disconnect").description("Remove a local connection").requiredOption("--connection <id>", "Local Machine connection ID").option(
25382
26909
  "--local-only",
25383
26910
  "Remove local state without contacting the Relay"
@@ -25686,7 +27213,7 @@ init_cjs_shims();
25686
27213
  // src/update/install.ts
25687
27214
  init_cjs_shims();
25688
27215
  var import_node_child_process9 = require("child_process");
25689
- var import_node_fs2 = require("fs");
27216
+ var import_node_fs4 = require("fs");
25690
27217
  var path3 = __toESM(require("path"), 1);
25691
27218
 
25692
27219
  // src/update/version.ts
@@ -25879,7 +27406,7 @@ function packageManagerFromUserAgent(userAgent) {
25879
27406
  function normalizePath(value) {
25880
27407
  let resolved = value;
25881
27408
  try {
25882
- resolved = import_node_fs2.realpathSync.native(value);
27409
+ resolved = import_node_fs4.realpathSync.native(value);
25883
27410
  } catch {
25884
27411
  }
25885
27412
  return path3.normalize(resolved).replaceAll(path3.sep, "/");
@@ -26134,6 +27661,7 @@ function registerWorkspaceCommand(program3) {
26134
27661
  // src/commands/workflow.ts
26135
27662
  init_cjs_shims();
26136
27663
  var fs5 = __toESM(require("fs"), 1);
27664
+ var import_node_path16 = require("path");
26137
27665
  var import_node_util6 = require("util");
26138
27666
  var MAX_DESC_LENGTH = 5e3;
26139
27667
  var MAX_COMMENT_CONTENT_LENGTH = 5e3;
@@ -26216,21 +27744,22 @@ function parseTaskScope(raw) {
26216
27744
  'Error: --scope must be "all", "assigned_to_me", "subscribed_by_me", or "owner_is_me".'
26217
27745
  );
26218
27746
  }
26219
- function parseFileIds(raw, label = "--file-ids") {
26220
- if (raw == null || raw === "") return void 0;
26221
- const ids = raw.split(",").map((item) => item.trim()).filter(Boolean);
26222
- if (ids.length === 0) {
26223
- throw new WorkflowOptionsError(`Error: ${label} must include at least one file ID.`);
27747
+ function parseHttpUrl(raw, label = "--url") {
27748
+ const url = raw.trim();
27749
+ try {
27750
+ const parsed = new URL(url);
27751
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") return url;
27752
+ } catch {
26224
27753
  }
26225
- return ids;
27754
+ throw new WorkflowOptionsError(`Error: ${label} must be an HTTP or HTTPS URL.`);
26226
27755
  }
26227
27756
  function readDescFile(path4) {
26228
27757
  if (path4 == null || path4 === "") return void 0;
26229
27758
  if (!fs5.existsSync(path4)) {
26230
27759
  throw new WorkflowOptionsError(`Error: desc file not found: ${path4}`);
26231
27760
  }
26232
- const stat5 = fs5.statSync(path4);
26233
- if (!stat5.isFile()) {
27761
+ const stat6 = fs5.statSync(path4);
27762
+ if (!stat6.isFile()) {
26234
27763
  throw new WorkflowOptionsError(`Error: desc file is not a file: ${path4}`);
26235
27764
  }
26236
27765
  const buffer2 = fs5.readFileSync(path4);
@@ -26247,11 +27776,11 @@ function readCommentContentFile2(path4) {
26247
27776
  if (!fs5.existsSync(path4)) {
26248
27777
  throw new WorkflowOptionsError(`Error: comment content file not found: ${path4}`);
26249
27778
  }
26250
- const stat5 = fs5.statSync(path4);
26251
- if (!stat5.isFile()) {
27779
+ const stat6 = fs5.statSync(path4);
27780
+ if (!stat6.isFile()) {
26252
27781
  throw new WorkflowOptionsError(`Error: comment content path is not a file: ${path4}`);
26253
27782
  }
26254
- if (stat5.size > MAX_COMMENT_CONTENT_BYTES) {
27783
+ if (stat6.size > MAX_COMMENT_CONTENT_BYTES) {
26255
27784
  throw new WorkflowOptionsError(
26256
27785
  `Error: comment content file must be at most ${MAX_COMMENT_CONTENT_LENGTH} characters.`
26257
27786
  );
@@ -26505,7 +28034,7 @@ function printTaskSummary(item) {
26505
28034
  `${colors.bold}#${item.scopedId}${colors.reset} ${item.title} status=${item.statusScopedId} priority=${priorityLabel(item.priority)} assignee=${formatAssignee(item.assignee)} runs=${runIds}`
26506
28035
  );
26507
28036
  }
26508
- function printTaskDetail(item) {
28037
+ function printTaskDetail(item, linkedLinkTitles) {
26509
28038
  print(`${colors.bold}Task${colors.reset}`);
26510
28039
  printDetailField2("scopedId", item.scopedId);
26511
28040
  printDetailField2("workflowFileId", item.workflowFileId);
@@ -26515,11 +28044,14 @@ function printTaskDetail(item) {
26515
28044
  printDetailField2("statusScopedId", item.statusScopedId);
26516
28045
  printDetailField2("priority", `${item.priority} (${priorityLabel(item.priority)})`);
26517
28046
  printAssigneeDetail("assignee", item.assignee);
26518
- if (item.linkedFileIds.length === 0) {
26519
- print("linkedFileIds: []");
28047
+ if (item.linkedLinks.length === 0) {
28048
+ print("linkedLinks: []");
26520
28049
  } else {
26521
- print("linkedFileIds:");
26522
- for (const fileId of item.linkedFileIds) print(` - ${fileId}`);
28050
+ print("linkedLinks:");
28051
+ for (const [index2, link] of item.linkedLinks.entries()) {
28052
+ print(` - title: ${formatDetailScalar2(linkedLinkTitles[index2] ?? link.url)}`);
28053
+ printDetailField2("url", link.url, 4);
28054
+ }
26523
28055
  }
26524
28056
  printDetailField2("subscribed", item.subscribed);
26525
28057
  if (item.runningAgentRuns.length === 0) {
@@ -26534,6 +28066,36 @@ function printTaskDetail(item) {
26534
28066
  printDetailField2("createdAt", item.createdAt);
26535
28067
  printDetailField2("latestActAt", item.latestActAt);
26536
28068
  }
28069
+ async function printResolvedTaskDetail(item, workspaceId) {
28070
+ printTaskDetail(item, await resolveLinkedLinkTitles(item, workspaceId));
28071
+ }
28072
+ async function resolveLinkedLinkTitles(item, workspaceId) {
28073
+ return Promise.all(
28074
+ item.linkedLinks.map(async (link) => {
28075
+ if (link.title.trim().length > 0) return link.title;
28076
+ if (!isWorkspaceFileLink(link.url, workspaceId)) return link.url;
28077
+ try {
28078
+ const response = await httpGet(
28079
+ `/files/read-by-url?url=${encodeURIComponent(link.url)}`
28080
+ );
28081
+ if (!response.ok || response.data.type !== "file") return link.url;
28082
+ return import_node_path16.posix.basename(response.data.path) || link.url;
28083
+ } catch {
28084
+ return link.url;
28085
+ }
28086
+ })
28087
+ );
28088
+ }
28089
+ function isWorkspaceFileLink(url, workspaceId) {
28090
+ try {
28091
+ const segments = new URL(url).pathname.split("/").filter(Boolean);
28092
+ return segments.length === 3 && segments[0] === "w" && segments[1] === workspaceId && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
28093
+ segments[2]
28094
+ );
28095
+ } catch {
28096
+ return false;
28097
+ }
28098
+ }
26537
28099
  function printCommentDetail(item) {
26538
28100
  print(`${colors.bold}Comment${colors.reset}`);
26539
28101
  printDetailField2("id", item.id);
@@ -26835,7 +28397,7 @@ function registerTaskCommands(workflow) {
26835
28397
  failResponse(response);
26836
28398
  }
26837
28399
  stopSpinner(true, "Task fetched");
26838
- printTaskDetail(response.data);
28400
+ await printResolvedTaskDetail(response.data, options.workspace);
26839
28401
  });
26840
28402
  addAssigneeOptions(
26841
28403
  addWorkspaceOption(
@@ -26875,7 +28437,7 @@ function registerTaskCommands(workflow) {
26875
28437
  failResponse(response);
26876
28438
  }
26877
28439
  stopSpinner(true, "Task created");
26878
- printTaskDetail(response.data);
28440
+ await printResolvedTaskDetail(response.data, options.workspace);
26879
28441
  }
26880
28442
  );
26881
28443
  addWorkspaceOption(
@@ -26914,21 +28476,26 @@ function registerTaskCommands(workflow) {
26914
28476
  failResponse(response);
26915
28477
  }
26916
28478
  stopSpinner(true, "Task updated");
26917
- printTaskDetail(response.data);
28479
+ await printResolvedTaskDetail(response.data, options.workspace);
26918
28480
  }
26919
28481
  );
26920
- for (const action of ["add-linked-files", "remove-linked-files"]) {
26921
- addWorkspaceOption(
26922
- task.command(action).description(`${action === "add-linked-files" ? "Add" : "Remove"} linked files on a workflow task`).argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--file-ids <ids>", "Comma-separated file IDs")
26923
- ).action(
28482
+ for (const action of ["add-linked-links", "remove-linked-links"]) {
28483
+ const command = task.command(action).description(`${action === "add-linked-links" ? "Add" : "Remove"} a URL link on a workflow task`).argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--url <url>", "HTTP or HTTPS URL");
28484
+ if (action === "add-linked-links") {
28485
+ command.option("--title <title>", "Optional link title");
28486
+ }
28487
+ addWorkspaceOption(command).action(
26924
28488
  async (workflowFileId, taskScopedId, options) => {
26925
- const { id, fileIds } = runOrExit4(() => ({
28489
+ const { id, link } = runOrExit4(() => ({
26926
28490
  id: parsePositiveInteger(taskScopedId, "taskScopedId"),
26927
- fileIds: parseFileIds(options.fileIds, "--file-ids")
28491
+ link: {
28492
+ title: action === "add-linked-links" ? options.title?.trim() ?? "" : "",
28493
+ url: parseHttpUrl(options.url)
28494
+ }
26928
28495
  }));
26929
- startSpinner(action === "add-linked-files" ? "Adding linked files..." : "Removing linked files...");
26930
- const path4 = `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/linked-files`;
26931
- const updateResponse = action === "add-linked-files" ? await httpPost(path4, { fileIds }) : await httpDelete(path4, { fileIds });
28496
+ startSpinner(action === "add-linked-links" ? "Adding linked URL..." : "Removing linked URL...");
28497
+ const path4 = `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/linked-links`;
28498
+ const updateResponse = action === "add-linked-links" ? await httpPost(path4, { links: [link] }) : await httpDelete(path4, { links: [link] });
26932
28499
  if (!updateResponse.ok) {
26933
28500
  stopSpinner(false, "Failed");
26934
28501
  failResponse(updateResponse);
@@ -26938,8 +28505,8 @@ function registerTaskCommands(workflow) {
26938
28505
  stopSpinner(false, "Failed");
26939
28506
  failResponse(response);
26940
28507
  }
26941
- stopSpinner(true, action === "add-linked-files" ? "Linked files added" : "Linked files removed");
26942
- printTaskDetail(response.data);
28508
+ stopSpinner(true, action === "add-linked-links" ? "Linked URL added" : "Linked URL removed");
28509
+ await printResolvedTaskDetail(response.data, options.workspace);
26943
28510
  }
26944
28511
  );
26945
28512
  }
@@ -26966,7 +28533,7 @@ function registerTaskCommands(workflow) {
26966
28533
  failResponse(response);
26967
28534
  }
26968
28535
  stopSpinner(true, "Task moved");
26969
- printTaskDetail(response.data);
28536
+ await printResolvedTaskDetail(response.data, options.workspace);
26970
28537
  }
26971
28538
  );
26972
28539
  addWorkspaceOption(
@@ -27001,7 +28568,7 @@ function registerTaskCommands(workflow) {
27001
28568
  failResponse(response);
27002
28569
  }
27003
28570
  stopSpinner(true, "Task moved");
27004
- printTaskDetail(response.data);
28571
+ await printResolvedTaskDetail(response.data, options.workspace);
27005
28572
  }
27006
28573
  );
27007
28574
  addAssigneeOptions(
@@ -27031,7 +28598,7 @@ function registerTaskCommands(workflow) {
27031
28598
  failResponse(response);
27032
28599
  }
27033
28600
  stopSpinner(true, "Task assignee updated");
27034
- printTaskDetail(response.data);
28601
+ await printResolvedTaskDetail(response.data, options.workspace);
27035
28602
  }
27036
28603
  );
27037
28604
  addWorkspaceOption(
@@ -27051,7 +28618,7 @@ function registerTaskCommands(workflow) {
27051
28618
  }
27052
28619
  function getWorkflowTask(workspaceId, workflowFileId, taskScopedId) {
27053
28620
  return httpGet(
27054
- `/workspaces/${workspaceId}/workflows/${workflowFileId}/tasks-v2/${taskScopedId}`
28621
+ `/workspaces/${workspaceId}/workflows/${workflowFileId}/tasks-v3/${taskScopedId}`
27055
28622
  );
27056
28623
  }
27057
28624
  function registerCommentCommands(workflow) {
@@ -27185,16 +28752,16 @@ function createProgram(version) {
27185
28752
 
27186
28753
  // src/telemetry/client.ts
27187
28754
  init_cjs_shims();
27188
- var import_node_os9 = require("os");
28755
+ var import_node_os11 = require("os");
27189
28756
  var buffer = [];
27190
28757
  var FLUSH_TIMEOUT_MS = 3e3;
27191
28758
  var MAX_BATCH_SIZE = 100;
27192
28759
  function commonLabels() {
27193
28760
  return {
27194
- cli_version: "0.10.0-beta.5",
28761
+ cli_version: "0.10.0-beta.6",
27195
28762
  node_version: process.versions.node,
27196
- os: (0, import_node_os9.platform)(),
27197
- arch: (0, import_node_os9.arch)(),
28763
+ os: (0, import_node_os11.platform)(),
28764
+ arch: (0, import_node_os11.arch)(),
27198
28765
  is_ci: isCiEnvironment() ? "true" : "false"
27199
28766
  };
27200
28767
  }
@@ -27237,7 +28804,7 @@ async function flush() {
27237
28804
  }
27238
28805
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
27239
28806
  const payload = {
27240
- release_id: "0.10.0-beta.5",
28807
+ release_id: "0.10.0-beta.6",
27241
28808
  client_type: "cli",
27242
28809
  metric_data_list: batch.map((m) => ({
27243
28810
  profile: "cli",
@@ -27438,7 +29005,7 @@ function registryWorker() {
27438
29005
 
27439
29006
  // src/update/prompt.ts
27440
29007
  init_cjs_shims();
27441
- var import_promises20 = require("readline/promises");
29008
+ var import_promises21 = require("readline/promises");
27442
29009
  async function promptForUpdate(input, output, currentVersion, latestVersion, timeoutMs) {
27443
29010
  output.write(`
27444
29011
  A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion}
@@ -27451,7 +29018,7 @@ A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion
27451
29018
  const controller = new AbortController();
27452
29019
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
27453
29020
  timeout.unref();
27454
- const readline = (0, import_promises20.createInterface)({ input, output, terminal: true });
29021
+ const readline = (0, import_promises21.createInterface)({ input, output, terminal: true });
27455
29022
  try {
27456
29023
  const answer = await readline.question("", { signal: controller.signal });
27457
29024
  if (answer.trim() === "1") return "update";
@@ -27554,7 +29121,7 @@ function commandPath2(command) {
27554
29121
 
27555
29122
  // src/update/daemon-reconcile-hook.ts
27556
29123
  init_cjs_shims();
27557
- var import_node_path15 = require("path");
29124
+ var import_node_path17 = require("path");
27558
29125
  function installDaemonReconcileHook(program3, cliVersion) {
27559
29126
  program3.hook("preAction", async (_thisCommand, actionCommand) => {
27560
29127
  if (!isEligible2(actionCommand)) return;
@@ -27576,9 +29143,9 @@ function installDaemonReconcileHook(program3, cliVersion) {
27576
29143
  await reconcileManagedDaemon2({
27577
29144
  cliVersion,
27578
29145
  commandArguments: ["machine", "daemon"],
27579
- entrypointPath: (0, import_node_path15.resolve)(entrypointPath),
29146
+ entrypointPath: (0, import_node_path17.resolve)(entrypointPath),
27580
29147
  environment: {},
27581
- nodePath: (0, import_node_path15.resolve)(process.execPath),
29148
+ nodePath: (0, import_node_path17.resolve)(process.execPath),
27582
29149
  onActiveJobs: (count) => {
27583
29150
  process.stderr.write(
27584
29151
  `Warning: restarting the managed Connector will interrupt ${count} active ${count === 1 ? "Job" : "Jobs"}.
@@ -27620,9 +29187,9 @@ function commandPath3(command) {
27620
29187
  }
27621
29188
 
27622
29189
  // src/index.ts
27623
- var program2 = createProgram("0.10.0-beta.5");
27624
- installDaemonReconcileHook(program2, "0.10.0-beta.5");
27625
- installUpdateHook(program2, "0.10.0-beta.5");
29190
+ var program2 = createProgram("0.10.0-beta.6");
29191
+ installDaemonReconcileHook(program2, "0.10.0-beta.6");
29192
+ installUpdateHook(program2, "0.10.0-beta.6");
27626
29193
  instrumentProgram(program2);
27627
29194
  installExitHandler();
27628
29195
  program2.parseAsync(process.argv).then(async () => {