@moxt-ai/cli 0.8.1 → 0.9.0-beta.1

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
@@ -3787,8 +3787,8 @@ var require_common = __commonJS({
3787
3787
  }
3788
3788
  return debug2;
3789
3789
  }
3790
- function extend(namespace, delimiter2) {
3791
- const newDebug = createDebug(this.namespace + (typeof delimiter2 === "undefined" ? ":" : delimiter2) + namespace);
3790
+ function extend(namespace, delimiter3) {
3791
+ const newDebug = createDebug(this.namespace + (typeof delimiter3 === "undefined" ? ":" : delimiter3) + namespace);
3792
3792
  newDebug.log = this.log;
3793
3793
  return newDebug;
3794
3794
  }
@@ -4495,10 +4495,6 @@ var init_v1 = __esm({
4495
4495
  });
4496
4496
 
4497
4497
  // ../machine-connector/dist/runtime/process-executor.js
4498
- async function executeCommand(rootPath, spec, callbacks) {
4499
- const workingDirectory = await resolveCanonicalWorkingDirectory(rootPath, spec.relativeWorkingDirectory);
4500
- return await executeProcess(spec.executable, spec.arguments, workingDirectory, spec.environment, spec.stdin, spec.timeoutSeconds, callbacks);
4501
- }
4502
4498
  async function executeProcess(executable, argumentsList, workingDirectory, environment, stdin, timeoutSeconds, callbacks) {
4503
4499
  if (callbacks.canSpawn && !callbacks.canSpawn()) {
4504
4500
  return {
@@ -4509,7 +4505,7 @@ async function executeProcess(executable, argumentsList, workingDirectory, envir
4509
4505
  const child = (0, import_node_child_process.spawn)(executable, argumentsList, {
4510
4506
  cwd: workingDirectory,
4511
4507
  detached: (0, import_node_os.platform)() !== "win32",
4512
- env: buildChildEnvironment(environment),
4508
+ env: { ...environment },
4513
4509
  shell: false,
4514
4510
  stdio: ["pipe", "pipe", "pipe"],
4515
4511
  windowsHide: true
@@ -4641,19 +4637,6 @@ async function executeProcess(executable, argumentsList, workingDirectory, envir
4641
4637
  status: processExit.exitCode === 0 ? MachineJobStatus.Succeeded : MachineJobStatus.Failed
4642
4638
  };
4643
4639
  }
4644
- function buildChildEnvironment(overrides) {
4645
- const environment = {};
4646
- for (const [name, value] of Object.entries(process.env)) {
4647
- if (name === "MOXT_MACHINE_ACCESS_TOKEN" || name === "MOXT_MACHINE_REFRESH_TOKEN" || name === "MOXT_MACHINE_DEVICE_PRIVATE_KEY" || name === "MOXT_API_TOKEN" || name === "MOXT_CLI_TOKEN") {
4648
- continue;
4649
- }
4650
- environment[name] = value;
4651
- }
4652
- return {
4653
- ...environment,
4654
- ...overrides
4655
- };
4656
- }
4657
4640
  async function resolveCanonicalWorkingDirectory(rootPath, relativeWorkingDirectory) {
4658
4641
  const canonicalRoot = await (0, import_promises3.realpath)(rootPath);
4659
4642
  const lexicalCandidate = resolveWorkingDirectory(canonicalRoot, relativeWorkingDirectory);
@@ -4767,9 +4750,9 @@ var init_process_executor = __esm({
4767
4750
  });
4768
4751
 
4769
4752
  // ../machine-connector/dist/runtime/claude-executor.js
4770
- async function executeClaudeStart(workingDirectory, spec, callbacks) {
4753
+ async function executeClaudeStart(workingDirectory, environment, spec, callbacks) {
4771
4754
  const sessionId = (0, import_node_crypto.randomUUID)();
4772
- return await executeClaude(workingDirectory, [
4755
+ return await executeClaude(workingDirectory, environment, [
4773
4756
  "--print",
4774
4757
  "--output-format",
4775
4758
  "stream-json",
@@ -4779,8 +4762,8 @@ async function executeClaudeStart(workingDirectory, spec, callbacks) {
4779
4762
  sessionId
4780
4763
  ], spec.prompt, sessionId, callbacks);
4781
4764
  }
4782
- async function executeClaudeReply(workingDirectory, spec, callbacks) {
4783
- return await executeClaude(workingDirectory, [
4765
+ async function executeClaudeReply(workingDirectory, environment, spec, callbacks) {
4766
+ return await executeClaude(workingDirectory, environment, [
4784
4767
  "--print",
4785
4768
  "--output-format",
4786
4769
  "stream-json",
@@ -4790,7 +4773,7 @@ async function executeClaudeReply(workingDirectory, spec, callbacks) {
4790
4773
  spec.threadId
4791
4774
  ], spec.prompt, spec.threadId, callbacks);
4792
4775
  }
4793
- async function executeClaude(workingDirectory, argumentsList, prompt, expectedSessionId, callbacks) {
4776
+ async function executeClaude(workingDirectory, environment, argumentsList, prompt, expectedSessionId, callbacks) {
4794
4777
  const metadata = {
4795
4778
  threadId: expectedSessionId
4796
4779
  };
@@ -4811,7 +4794,7 @@ async function executeClaude(workingDirectory, argumentsList, prompt, expectedSe
4811
4794
  },
4812
4795
  onSpawn: callbacks.onSpawn
4813
4796
  };
4814
- const result = await executeProcess(process.env.MOXT_CLAUDE_PATH ?? "claude", argumentsList, workingDirectory, {}, prompt, 43200, processCallbacks);
4797
+ const result = await executeProcess(process.env.MOXT_CLAUDE_PATH ?? "claude", argumentsList, workingDirectory, environment, prompt, 43200, processCallbacks);
4815
4798
  if (bufferedStdout.trim().length > 0) {
4816
4799
  await processClaudeLine(bufferedStdout, metadata, callbacks);
4817
4800
  }
@@ -4867,9 +4850,9 @@ var init_claude_executor = __esm({
4867
4850
  });
4868
4851
 
4869
4852
  // ../machine-connector/dist/runtime/codex-executor.js
4870
- async function executeCodexStart(workingDirectory, runtimeDirectory, spec, callbacks) {
4853
+ async function executeCodexStart(workingDirectory, runtimeDirectory, environment, spec, callbacks) {
4871
4854
  const outputPath = createOutputPath(runtimeDirectory);
4872
- return await executeCodex(workingDirectory, outputPath, [
4855
+ return await executeCodex(workingDirectory, outputPath, environment, [
4873
4856
  "exec",
4874
4857
  "--json",
4875
4858
  "--dangerously-bypass-approvals-and-sandbox",
@@ -4879,9 +4862,9 @@ async function executeCodexStart(workingDirectory, runtimeDirectory, spec, callb
4879
4862
  "-"
4880
4863
  ], spec.prompt, callbacks);
4881
4864
  }
4882
- async function executeCodexReply(workingDirectory, runtimeDirectory, spec, callbacks) {
4865
+ async function executeCodexReply(workingDirectory, runtimeDirectory, environment, spec, callbacks) {
4883
4866
  const outputPath = createOutputPath(runtimeDirectory);
4884
- return await executeCodex(workingDirectory, outputPath, [
4867
+ return await executeCodex(workingDirectory, outputPath, environment, [
4885
4868
  "exec",
4886
4869
  "resume",
4887
4870
  "--json",
@@ -4893,7 +4876,7 @@ async function executeCodexReply(workingDirectory, runtimeDirectory, spec, callb
4893
4876
  "-"
4894
4877
  ], spec.prompt, callbacks);
4895
4878
  }
4896
- async function executeCodex(workingDirectory, outputPath, argumentsList, prompt, callbacks) {
4879
+ async function executeCodex(workingDirectory, outputPath, environment, argumentsList, prompt, callbacks) {
4897
4880
  const executionMetadata = {};
4898
4881
  const turnCompletion = createCodexTurnCompletion();
4899
4882
  let bufferedStdout = "";
@@ -4926,7 +4909,7 @@ async function executeCodex(workingDirectory, outputPath, argumentsList, prompt,
4926
4909
  return result2;
4927
4910
  })
4928
4911
  };
4929
- const result = await executeProcess(process.env.MOXT_CODEX_PATH ?? "codex", argumentsList, workingDirectory, {}, prompt, 43200, processCallbacks);
4912
+ const result = await executeProcess(process.env.MOXT_CODEX_PATH ?? "codex", argumentsList, workingDirectory, environment, prompt, 43200, processCallbacks);
4930
4913
  if (bufferedStdout.trim().length > 0) {
4931
4914
  const event = parseCodexEvent(bufferedStdout).value;
4932
4915
  if (event !== void 0) {
@@ -5238,6 +5221,7 @@ var init_execution_cancellation = __esm({
5238
5221
  ExecutionCancellationReason2["Stopping"] = "stopping";
5239
5222
  })(ExecutionCancellationReason || (ExecutionCancellationReason = {}));
5240
5223
  ExecutionCancellation = class {
5224
+ abortController = new AbortController();
5241
5225
  handle;
5242
5226
  reason;
5243
5227
  requested;
@@ -5253,6 +5237,9 @@ var init_execution_cancellation = __esm({
5253
5237
  currentReason() {
5254
5238
  return this.reason;
5255
5239
  }
5240
+ signal() {
5241
+ return this.abortController.signal;
5242
+ }
5256
5243
  register(handle) {
5257
5244
  this.handle = handle;
5258
5245
  if (this.reason !== void 0) {
@@ -5269,6 +5256,7 @@ var init_execution_cancellation = __esm({
5269
5256
  async request(reason) {
5270
5257
  if (this.reason === void 0) {
5271
5258
  this.reason = reason;
5259
+ this.abortController.abort(reason);
5272
5260
  this.resolveRequested(reason);
5273
5261
  }
5274
5262
  if (this.handle) {
@@ -5555,6 +5543,12 @@ var init_image_viewer = __esm({
5555
5543
 
5556
5544
  // ../machine-connector/dist/runtime/local-ipc.js
5557
5545
  async function requestRuntimeStatus(store, timeoutMilliseconds = 1e3) {
5546
+ return await requestLocalIpc(store, "status", timeoutMilliseconds);
5547
+ }
5548
+ async function requestEnvironmentRefresh(store, timeoutMilliseconds = 1e4) {
5549
+ return await requestLocalIpc(store, "environment_refresh", timeoutMilliseconds);
5550
+ }
5551
+ async function requestLocalIpc(store, action, timeoutMilliseconds) {
5558
5552
  return await new Promise((resolvePromise, rejectPromise) => {
5559
5553
  const socket = (0, import_node_net.createConnection)(store.runtimeSocketPath());
5560
5554
  let responseText = "";
@@ -5574,7 +5568,7 @@ async function requestRuntimeStatus(store, timeoutMilliseconds = 1e3) {
5574
5568
  }
5575
5569
  });
5576
5570
  socket.once("connect", () => {
5577
- socket.write(`${JSON.stringify({ action: "status" })}
5571
+ socket.write(`${JSON.stringify({ action })}
5578
5572
  `);
5579
5573
  });
5580
5574
  });
@@ -5590,10 +5584,12 @@ var init_local_ipc = __esm({
5590
5584
  LocalIpcServer = class {
5591
5585
  store;
5592
5586
  getStatus;
5587
+ refreshEnvironment;
5593
5588
  server;
5594
- constructor(store, getStatus) {
5589
+ constructor(store, getStatus, refreshEnvironment) {
5595
5590
  this.store = store;
5596
5591
  this.getStatus = getStatus;
5592
+ this.refreshEnvironment = refreshEnvironment;
5597
5593
  }
5598
5594
  async start() {
5599
5595
  const socketPath = this.store.runtimeSocketPath();
@@ -5602,15 +5598,18 @@ var init_local_ipc = __esm({
5602
5598
  }
5603
5599
  this.server = (0, import_node_net.createServer)((socket) => {
5604
5600
  let requestText = "";
5601
+ let handled = false;
5605
5602
  socket.setEncoding("utf8");
5606
5603
  socket.on("data", (chunk) => {
5607
5604
  requestText += chunk;
5608
- if (!requestText.includes("\n")) {
5605
+ if (handled || !requestText.includes("\n")) {
5609
5606
  return;
5610
5607
  }
5611
- const response = this.handleRequest(requestText);
5612
- socket.end(`${JSON.stringify(response)}
5608
+ handled = true;
5609
+ void this.handleRequest(requestText).then((response) => {
5610
+ socket.end(`${JSON.stringify(response)}
5613
5611
  `);
5612
+ });
5614
5613
  });
5615
5614
  });
5616
5615
  await new Promise((resolvePromise, rejectPromise) => {
@@ -5632,12 +5631,20 @@ var init_local_ipc = __esm({
5632
5631
  await (0, import_promises6.rm)(this.store.runtimeSocketPath(), { force: true });
5633
5632
  }
5634
5633
  }
5635
- handleRequest(requestText) {
5634
+ async handleRequest(requestText) {
5636
5635
  try {
5637
5636
  const request2 = JSON.parse(requestText.trim());
5638
5637
  if (request2.action === "status") {
5639
5638
  return { status: this.getStatus() };
5640
5639
  }
5640
+ if (request2.action === "environment_refresh") {
5641
+ if (!this.refreshEnvironment) {
5642
+ return { error: "Environment refresh is unavailable" };
5643
+ }
5644
+ return {
5645
+ environmentRefresh: await this.refreshEnvironment()
5646
+ };
5647
+ }
5641
5648
  return { error: `Unsupported IPC action: ${request2.action}` };
5642
5649
  } catch (error) {
5643
5650
  return {
@@ -5650,6 +5657,175 @@ var init_local_ipc = __esm({
5650
5657
  });
5651
5658
 
5652
5659
  // ../machine-connector/dist/runtime/process-lock.js
5660
+ async function createCompleteLock(path4, record2) {
5661
+ await (0, import_promises7.mkdir)(path4, { mode: 448 });
5662
+ let metadata;
5663
+ try {
5664
+ metadata = await (0, import_promises7.stat)(path4);
5665
+ } catch (error) {
5666
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5667
+ throw nodeError("EEXIST", "Lock directory changed while publishing");
5668
+ }
5669
+ throw error;
5670
+ }
5671
+ const ownerPath = (0, import_node_path5.join)(path4, `${metadata.dev}.${metadata.ino}.${record2.pid}.${record2.token}.owner`);
5672
+ try {
5673
+ await (0, import_promises7.writeFile)(ownerPath, `${JSON.stringify(record2)}
5674
+ `, {
5675
+ encoding: "utf8",
5676
+ flag: "wx",
5677
+ mode: 384
5678
+ });
5679
+ let current2;
5680
+ try {
5681
+ current2 = await (0, import_promises7.stat)(path4);
5682
+ } catch (error) {
5683
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5684
+ throw nodeError("EEXIST", "Lock directory changed while publishing");
5685
+ }
5686
+ throw error;
5687
+ }
5688
+ if (!sameDirectoryIdentity(metadata, current2)) {
5689
+ throw nodeError("EEXIST", "Lock directory was replaced while publishing");
5690
+ }
5691
+ return ownerPath;
5692
+ } catch (error) {
5693
+ await removeFileIfPresent(ownerPath);
5694
+ await removeEmptyDirectory(path4);
5695
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5696
+ throw nodeError("EEXIST", "Lock directory changed while publishing");
5697
+ }
5698
+ throw error;
5699
+ }
5700
+ }
5701
+ async function readLockState(path4) {
5702
+ let metadata;
5703
+ try {
5704
+ metadata = await (0, import_promises7.stat)(path4);
5705
+ } catch (error) {
5706
+ if (isNodeErrorCode2(error, "ENOENT"))
5707
+ return void 0;
5708
+ throw error;
5709
+ }
5710
+ if (!metadata.isDirectory()) {
5711
+ return {
5712
+ metadata,
5713
+ record: await readRecord(path4)
5714
+ };
5715
+ }
5716
+ const ownerPrefix = `${metadata.dev}.${metadata.ino}.`;
5717
+ let names;
5718
+ try {
5719
+ names = await (0, import_promises7.readdir)(path4);
5720
+ } catch (error) {
5721
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5722
+ return void 0;
5723
+ }
5724
+ throw error;
5725
+ }
5726
+ const ownerName = names.find((name) => name.startsWith(ownerPrefix) && name.endsWith(".owner"));
5727
+ if (!ownerName)
5728
+ return { metadata };
5729
+ const ownerPath = (0, import_node_path5.join)(path4, ownerName);
5730
+ return {
5731
+ metadata,
5732
+ ownerPath,
5733
+ record: await readRecord(ownerPath)
5734
+ };
5735
+ }
5736
+ async function readRecord(path4) {
5737
+ try {
5738
+ const parsed = JSON.parse(await (0, import_promises7.readFile)(path4, "utf8"));
5739
+ 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) {
5740
+ return void 0;
5741
+ }
5742
+ return parsed;
5743
+ } catch (error) {
5744
+ if (isNodeErrorCode2(error, "ENOENT"))
5745
+ return void 0;
5746
+ if (error instanceof SyntaxError)
5747
+ return void 0;
5748
+ throw error;
5749
+ }
5750
+ }
5751
+ async function removeLockIfTokenMatches(path4, token) {
5752
+ const state = await readLockState(path4);
5753
+ if (state?.record?.token !== token)
5754
+ return;
5755
+ if (state.ownerPath) {
5756
+ await removeOwnedDirectoryLock(path4, state.ownerPath, token);
5757
+ return;
5758
+ }
5759
+ try {
5760
+ await (0, import_promises7.rm)(path4);
5761
+ } catch (error) {
5762
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "EISDIR") || isNodeErrorCode2(error, "ERR_FS_EISDIR") || isNodeErrorCode2(error, "EPERM")) {
5763
+ return;
5764
+ }
5765
+ throw error;
5766
+ }
5767
+ }
5768
+ async function removeOwnedDirectoryLock(path4, ownerPath, token) {
5769
+ if ((await readRecord(ownerPath))?.token !== token)
5770
+ return;
5771
+ await removeFileIfPresent(ownerPath);
5772
+ await removeEmptyDirectory(path4);
5773
+ }
5774
+ async function removeStaleIncompleteLock(path4, metadata) {
5775
+ if (Date.now() - Number(metadata.mtimeMs) < incompleteLockStaleMilliseconds) {
5776
+ return false;
5777
+ }
5778
+ const current2 = await readLockState(path4);
5779
+ if (!current2 || current2.record || !sameFileMetadata(metadata, current2.metadata)) {
5780
+ return false;
5781
+ }
5782
+ if (!metadata.isDirectory()) {
5783
+ try {
5784
+ await (0, import_promises7.rm)(path4);
5785
+ return true;
5786
+ } catch (error) {
5787
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "EISDIR") || isNodeErrorCode2(error, "ERR_FS_EISDIR") || isNodeErrorCode2(error, "EPERM")) {
5788
+ return false;
5789
+ }
5790
+ throw error;
5791
+ }
5792
+ }
5793
+ const ownerPrefix = `${metadata.dev}.${metadata.ino}.`;
5794
+ let names;
5795
+ try {
5796
+ names = await (0, import_promises7.readdir)(path4);
5797
+ } catch (error) {
5798
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5799
+ return false;
5800
+ }
5801
+ throw error;
5802
+ }
5803
+ const ownerNames = names.filter((name) => name.startsWith(ownerPrefix) && name.endsWith(".owner"));
5804
+ const deadOwnerNames = [];
5805
+ for (const name of ownerNames) {
5806
+ const ownerProcessId = directoryOwnerProcessId(ownerPrefix, name);
5807
+ if (ownerProcessId === void 0 || processIsAlive(ownerProcessId)) {
5808
+ return false;
5809
+ }
5810
+ deadOwnerNames.push(name);
5811
+ }
5812
+ for (const name of deadOwnerNames) {
5813
+ await removeFileIfPresent((0, import_node_path5.join)(path4, name));
5814
+ }
5815
+ return await removeEmptyDirectory(path4);
5816
+ }
5817
+ function directoryOwnerProcessId(ownerPrefix, ownerName) {
5818
+ const identity = ownerName.slice(ownerPrefix.length, -".owner".length);
5819
+ const separator = identity.indexOf(".");
5820
+ if (separator <= 0)
5821
+ return void 0;
5822
+ const processId = Number(identity.slice(0, separator));
5823
+ const token = identity.slice(separator + 1);
5824
+ if (!Number.isSafeInteger(processId) || processId <= 0 || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(token)) {
5825
+ return void 0;
5826
+ }
5827
+ return processId;
5828
+ }
5653
5829
  async function removeStalePendingLockCandidates(path4) {
5654
5830
  const directory = (0, import_node_path5.dirname)(path4);
5655
5831
  const lockName = (0, import_node_path5.basename)(path4);
@@ -5688,7 +5864,7 @@ async function removeOldUnchangedFile(path4) {
5688
5864
  } catch (error) {
5689
5865
  return isNodeErrorCode2(error, "ENOENT");
5690
5866
  }
5691
- if (Date.now() - metadata.mtimeMs < incompleteLockStaleMilliseconds) {
5867
+ if (Date.now() - Number(metadata.mtimeMs) < incompleteLockStaleMilliseconds) {
5692
5868
  return false;
5693
5869
  }
5694
5870
  let current2;
@@ -5702,62 +5878,29 @@ async function removeOldUnchangedFile(path4) {
5702
5878
  await (0, import_promises7.rm)(path4, { force: true });
5703
5879
  return true;
5704
5880
  }
5705
- async function createCompleteLock(path4, record2) {
5706
- const candidatePath = `${path4}.${record2.pid}.${record2.token}.pending`;
5881
+ async function removeEmptyDirectory(path4) {
5707
5882
  try {
5708
- await (0, import_promises7.writeFile)(candidatePath, `${JSON.stringify(record2)}
5709
- `, {
5710
- encoding: "utf8",
5711
- flag: "wx",
5712
- mode: 384
5713
- });
5714
- await (0, import_promises7.link)(candidatePath, path4);
5715
- } finally {
5716
- await (0, import_promises7.rm)(candidatePath, { force: true });
5717
- }
5718
- }
5719
- async function readLockRecord(path4) {
5720
- try {
5721
- const parsed = JSON.parse(await (0, import_promises7.readFile)(path4, "utf8"));
5722
- 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) {
5723
- return void 0;
5724
- }
5725
- return parsed;
5883
+ await (0, import_promises7.rmdir)(path4);
5884
+ return true;
5726
5885
  } catch (error) {
5727
- if (isNodeErrorCode2(error, "ENOENT"))
5728
- return void 0;
5729
- if (error instanceof SyntaxError)
5730
- return void 0;
5886
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTEMPTY") || isNodeErrorCode2(error, "EEXIST") || isNodeErrorCode2(error, "ENOTDIR")) {
5887
+ return false;
5888
+ }
5731
5889
  throw error;
5732
5890
  }
5733
5891
  }
5734
- async function removeLockIfTokenMatches(path4, token) {
5735
- const current2 = await readLockRecord(path4);
5736
- if (current2?.token === token)
5737
- await (0, import_promises7.rm)(path4, { force: true });
5738
- }
5739
- async function removeStaleIncompleteLock(path4) {
5740
- let metadata;
5892
+ async function removeFileIfPresent(path4) {
5741
5893
  try {
5742
- metadata = await (0, import_promises7.stat)(path4);
5743
- } catch (error) {
5744
- return isNodeErrorCode2(error, "ENOENT");
5745
- }
5746
- if (Date.now() - metadata.mtimeMs < incompleteLockStaleMilliseconds) {
5747
- return false;
5748
- }
5749
- if (await readLockRecord(path4))
5750
- return false;
5751
- let current2;
5752
- try {
5753
- current2 = await (0, import_promises7.stat)(path4);
5894
+ await (0, import_promises7.rm)(path4, { force: true });
5754
5895
  } catch (error) {
5755
- return isNodeErrorCode2(error, "ENOENT");
5896
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5897
+ return;
5898
+ }
5899
+ throw error;
5756
5900
  }
5757
- if (!sameFileMetadata(metadata, current2))
5758
- return false;
5759
- await (0, import_promises7.rm)(path4, { force: true });
5760
- return true;
5901
+ }
5902
+ function sameDirectoryIdentity(first, second) {
5903
+ return first.isDirectory() && second.isDirectory() && first.dev === second.dev && first.ino === second.ino;
5761
5904
  }
5762
5905
  function sameFileMetadata(first, second) {
5763
5906
  return first.dev === second.dev && first.ino === second.ino && first.mtimeMs === second.mtimeMs && first.size === second.size;
@@ -5773,6 +5916,9 @@ function processIsAlive(pid) {
5773
5916
  function isNodeErrorCode2(error, expectedCode) {
5774
5917
  return error instanceof Error && "code" in error && error.code === expectedCode;
5775
5918
  }
5919
+ function nodeError(code, message) {
5920
+ return Object.assign(new Error(message), { code });
5921
+ }
5776
5922
  function delay3(milliseconds) {
5777
5923
  return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
5778
5924
  }
@@ -5787,10 +5933,12 @@ var init_process_lock = __esm({
5787
5933
  incompleteLockStaleMilliseconds = 3e4;
5788
5934
  ProcessLock = class _ProcessLock {
5789
5935
  path;
5936
+ ownerPath;
5790
5937
  token;
5791
5938
  released = false;
5792
- constructor(path4, token) {
5939
+ constructor(path4, ownerPath, token) {
5793
5940
  this.path = path4;
5941
+ this.ownerPath = ownerPath;
5794
5942
  this.token = token;
5795
5943
  }
5796
5944
  static async acquire(path4, options) {
@@ -5799,22 +5947,22 @@ var init_process_lock = __esm({
5799
5947
  const token = (0, import_node_crypto4.randomUUID)();
5800
5948
  while (true) {
5801
5949
  try {
5802
- await createCompleteLock(path4, {
5950
+ const ownerPath = await createCompleteLock(path4, {
5803
5951
  createdAt: Date.now(),
5804
5952
  pid: process.pid,
5805
5953
  token
5806
5954
  });
5807
- return new _ProcessLock(path4, token);
5955
+ return new _ProcessLock(path4, ownerPath, token);
5808
5956
  } catch (error) {
5809
5957
  if (!isNodeErrorCode2(error, "EEXIST"))
5810
5958
  throw error;
5811
5959
  }
5812
- const existing = await readLockRecord(path4);
5813
- if (existing && !processIsAlive(existing.pid)) {
5814
- await removeLockIfTokenMatches(path4, existing.token);
5960
+ const existing = await readLockState(path4);
5961
+ if (existing?.record && !processIsAlive(existing.record.pid)) {
5962
+ await removeLockIfTokenMatches(path4, existing.record.token);
5815
5963
  continue;
5816
5964
  }
5817
- if (!existing && await removeStaleIncompleteLock(path4)) {
5965
+ if (existing && !existing.record && await removeStaleIncompleteLock(path4, existing.metadata)) {
5818
5966
  continue;
5819
5967
  }
5820
5968
  if (Date.now() >= deadline)
@@ -5826,7 +5974,484 @@ var init_process_lock = __esm({
5826
5974
  if (this.released)
5827
5975
  return;
5828
5976
  this.released = true;
5829
- await removeLockIfTokenMatches(this.path, this.token);
5977
+ await removeOwnedDirectoryLock(this.path, this.ownerPath, this.token);
5978
+ }
5979
+ };
5980
+ }
5981
+ });
5982
+
5983
+ // ../machine-connector/dist/runtime/shell-environment.js
5984
+ function sanitizeEnvironment(source) {
5985
+ const environment = createEnvironmentMap();
5986
+ for (const [name, value] of Object.entries(source)) {
5987
+ if (value === void 0 || isConnectorCredentialName(name)) {
5988
+ continue;
5989
+ }
5990
+ environment[name] = value;
5991
+ }
5992
+ return environment;
5993
+ }
5994
+ function parseNullSeparatedEnvironment(output) {
5995
+ if (output.length === 0 || output.at(-1) !== 0) {
5996
+ throw new Error("shell_environment_malformed");
5997
+ }
5998
+ const text3 = decodeUtf8(output, "shell_environment_malformed");
5999
+ const environment = createEnvironmentMap();
6000
+ const frames2 = text3.slice(0, -1).split("\0");
6001
+ for (const frame of frames2) {
6002
+ const separator = frame.indexOf("=");
6003
+ const name = frame.slice(0, separator);
6004
+ if (separator <= 0 || !environmentNamePattern.test(name) || Object.hasOwn(environment, name)) {
6005
+ throw new Error("shell_environment_malformed");
6006
+ }
6007
+ environment[name] = frame.slice(separator + 1);
6008
+ }
6009
+ return environment;
6010
+ }
6011
+ function parseDirenvJson(text3) {
6012
+ try {
6013
+ let index2 = skipWhitespace(text3, 0);
6014
+ if (text3[index2] !== "{")
6015
+ throw new Error("object expected");
6016
+ index2 = skipWhitespace(text3, index2 + 1);
6017
+ const exports2 = createEnvironmentMap();
6018
+ if (text3[index2] === "}") {
6019
+ index2 = skipWhitespace(text3, index2 + 1);
6020
+ if (index2 !== text3.length)
6021
+ throw new Error("trailing input");
6022
+ return exports2;
6023
+ }
6024
+ while (index2 < text3.length) {
6025
+ const key = readJsonString(text3, index2);
6026
+ if (!environmentNamePattern.test(key.value) || Object.hasOwn(exports2, key.value)) {
6027
+ throw new Error("invalid or duplicate key");
6028
+ }
6029
+ index2 = skipWhitespace(text3, key.next);
6030
+ if (text3[index2] !== ":")
6031
+ throw new Error("colon expected");
6032
+ index2 = skipWhitespace(text3, index2 + 1);
6033
+ if (text3.startsWith("null", index2)) {
6034
+ exports2[key.value] = null;
6035
+ index2 += 4;
6036
+ } else {
6037
+ const value = readJsonString(text3, index2);
6038
+ exports2[key.value] = value.value;
6039
+ index2 = value.next;
6040
+ }
6041
+ index2 = skipWhitespace(text3, index2);
6042
+ if (text3[index2] === "}") {
6043
+ index2 = skipWhitespace(text3, index2 + 1);
6044
+ if (index2 !== text3.length)
6045
+ throw new Error("trailing input");
6046
+ return exports2;
6047
+ }
6048
+ if (text3[index2] !== ",")
6049
+ throw new Error("comma expected");
6050
+ index2 = skipWhitespace(text3, index2 + 1);
6051
+ }
6052
+ throw new Error("unterminated object");
6053
+ } catch {
6054
+ throw new Error("direnv_malformed");
6055
+ }
6056
+ }
6057
+ function sanitizeDirenvExports(source) {
6058
+ const exports2 = createEnvironmentMap();
6059
+ for (const [name, value] of Object.entries(source)) {
6060
+ if (!isConnectorCredentialName(name)) {
6061
+ exports2[name] = value;
6062
+ }
6063
+ }
6064
+ return exports2;
6065
+ }
6066
+ function isConnectorCredentialName(name) {
6067
+ if (name === "MOXT_API_TOKEN" || name === "MOXT_CLI_TOKEN")
6068
+ return true;
6069
+ return name.startsWith("MOXT_MACHINE_") && /(?:^|_)(?:TOKEN|SECRET|CREDENTIALS?|PASSWORD|PRIVATE_KEY)(?:_|$)/.test(name.slice("MOXT_MACHINE_".length));
6070
+ }
6071
+ async function validateShell(shellPath) {
6072
+ if (!(0, import_node_path6.isAbsolute)(shellPath))
6073
+ throw new Error("default shell is not absolute");
6074
+ const canonicalPath = await validateExecutable(shellPath);
6075
+ const shellName = (0, import_node_path6.basename)(canonicalPath);
6076
+ if (shellName !== "bash" && shellName !== "zsh") {
6077
+ throw new Error("default shell is not Bash or Zsh");
6078
+ }
6079
+ return canonicalPath;
6080
+ }
6081
+ async function validateExecutable(path4) {
6082
+ const canonicalPath = await (0, import_promises8.realpath)(path4);
6083
+ const metadata = await (0, import_promises8.stat)(canonicalPath);
6084
+ if (!metadata.isFile())
6085
+ throw new Error("executable is not a regular file");
6086
+ await (0, import_promises8.access)(canonicalPath, import_promises8.constants.X_OK);
6087
+ return canonicalPath;
6088
+ }
6089
+ async function findExecutable(name, pathValue) {
6090
+ for (const directory of (pathValue ?? "").split(import_node_path6.delimiter)) {
6091
+ if (!(0, import_node_path6.isAbsolute)(directory))
6092
+ continue;
6093
+ try {
6094
+ const candidate = await validateExecutable((0, import_node_path6.join)(directory, name));
6095
+ if ((0, import_node_path6.basename)(candidate) === name)
6096
+ return candidate;
6097
+ } catch {
6098
+ }
6099
+ }
6100
+ return void 0;
6101
+ }
6102
+ async function findNearestEnvrc(canonicalRoot, canonicalWorkingDirectory) {
6103
+ let directory = canonicalWorkingDirectory;
6104
+ while (true) {
6105
+ const candidate = (0, import_node_path6.join)(directory, ".envrc");
6106
+ try {
6107
+ const metadata = await (0, import_promises8.stat)(candidate);
6108
+ if (!metadata.isFile()) {
6109
+ throw new JobEnvironmentError("direnv_malformed");
6110
+ }
6111
+ return candidate;
6112
+ } catch (error) {
6113
+ if (!isNodeError(error, "ENOENT"))
6114
+ throw error;
6115
+ }
6116
+ if (directory === canonicalRoot)
6117
+ return void 0;
6118
+ const parent = (0, import_node_path6.dirname)(directory);
6119
+ if (parent === directory)
6120
+ return void 0;
6121
+ directory = parent;
6122
+ }
6123
+ }
6124
+ async function executeBounded(options) {
6125
+ if (options.cancellationSignal?.aborted) {
6126
+ return {
6127
+ exitCode: -1,
6128
+ outcome: "cancelled",
6129
+ stderr: Buffer.alloc(0),
6130
+ stdout: Buffer.alloc(0)
6131
+ };
6132
+ }
6133
+ return await new Promise((resolvePromise) => {
6134
+ const child = (0, import_node_child_process2.spawn)(options.executable, options.argumentsList, {
6135
+ cwd: options.cwd,
6136
+ detached: (0, import_node_os3.platform)() !== "win32",
6137
+ env: options.environment,
6138
+ shell: false,
6139
+ stdio: ["ignore", "pipe", "pipe"],
6140
+ windowsHide: true
6141
+ });
6142
+ const stdout = [];
6143
+ const stderr = [];
6144
+ let bytes = 0;
6145
+ let outcome = "completed";
6146
+ let settled = false;
6147
+ let timeout;
6148
+ const finish = (exitCode) => {
6149
+ if (settled)
6150
+ return;
6151
+ settled = true;
6152
+ if (timeout)
6153
+ clearTimeout(timeout);
6154
+ options.cancellationSignal?.removeEventListener("abort", cancel);
6155
+ resolvePromise({
6156
+ exitCode,
6157
+ outcome,
6158
+ stderr: Buffer.concat(stderr),
6159
+ stdout: Buffer.concat(stdout)
6160
+ });
6161
+ };
6162
+ const terminateAndFinish = (terminalOutcome) => {
6163
+ if (settled || outcome !== "completed")
6164
+ return;
6165
+ outcome = terminalOutcome;
6166
+ terminateBoundedProcess(child.pid);
6167
+ child.stdout.destroy();
6168
+ child.stderr.destroy();
6169
+ finish(-1);
6170
+ };
6171
+ function cancel() {
6172
+ terminateAndFinish("cancelled");
6173
+ }
6174
+ const capture = (target) => (chunk) => {
6175
+ if (outcome !== "completed")
6176
+ return;
6177
+ bytes += chunk.length;
6178
+ if (bytes > options.outputLimitBytes) {
6179
+ terminateAndFinish("overflow");
6180
+ return;
6181
+ }
6182
+ target.push(Buffer.from(chunk));
6183
+ };
6184
+ child.stdout.on("data", capture(stdout));
6185
+ child.stderr.on("data", capture(stderr));
6186
+ child.once("error", () => {
6187
+ outcome = "spawn_failed";
6188
+ finish(-1);
6189
+ });
6190
+ child.once("close", (exitCode) => finish(exitCode ?? -1));
6191
+ timeout = setTimeout(() => terminateAndFinish("timeout"), options.timeoutMilliseconds);
6192
+ timeout.unref();
6193
+ options.cancellationSignal?.addEventListener("abort", cancel, {
6194
+ once: true
6195
+ });
6196
+ if (options.cancellationSignal?.aborted)
6197
+ cancel();
6198
+ });
6199
+ }
6200
+ function throwIfCancelled(signal) {
6201
+ if (signal?.aborted)
6202
+ throw new JobEnvironmentCancelledError();
6203
+ }
6204
+ function terminateBoundedProcess(pid) {
6205
+ if (pid === void 0)
6206
+ return;
6207
+ try {
6208
+ process.kill((0, import_node_os3.platform)() === "win32" ? pid : -pid, "SIGKILL");
6209
+ } catch (error) {
6210
+ if (isNodeError(error, "ESRCH"))
6211
+ return;
6212
+ try {
6213
+ process.kill(pid, "SIGKILL");
6214
+ } catch {
6215
+ }
6216
+ }
6217
+ }
6218
+ function readJsonString(text3, start) {
6219
+ if (text3[start] !== '"')
6220
+ throw new Error("string expected");
6221
+ let escaped = false;
6222
+ for (let index2 = start + 1; index2 < text3.length; index2 += 1) {
6223
+ const character = text3[index2];
6224
+ if (escaped) {
6225
+ escaped = false;
6226
+ continue;
6227
+ }
6228
+ if (character === "\\") {
6229
+ escaped = true;
6230
+ continue;
6231
+ }
6232
+ if (character === '"') {
6233
+ return {
6234
+ next: index2 + 1,
6235
+ value: JSON.parse(text3.slice(start, index2 + 1))
6236
+ };
6237
+ }
6238
+ }
6239
+ throw new Error("unterminated string");
6240
+ }
6241
+ function skipWhitespace(text3, start) {
6242
+ let index2 = start;
6243
+ while (/\s/.test(text3[index2] ?? ""))
6244
+ index2 += 1;
6245
+ return index2;
6246
+ }
6247
+ function decodeUtf8(value, category) {
6248
+ try {
6249
+ return new TextDecoder("utf-8", { fatal: true }).decode(value);
6250
+ } catch {
6251
+ throw new Error(category);
6252
+ }
6253
+ }
6254
+ function freezeEnvironment(environment) {
6255
+ return Object.freeze({ ...environment });
6256
+ }
6257
+ function createEnvironmentMap() {
6258
+ return /* @__PURE__ */ Object.create(null);
6259
+ }
6260
+ function degradedCapture(category) {
6261
+ return { status: { category, state: "degraded" } };
6262
+ }
6263
+ function isNodeError(error, code) {
6264
+ return error instanceof Error && "code" in error && error.code === code;
6265
+ }
6266
+ var import_node_child_process2, import_promises8, import_node_os3, import_node_path6, defaultCaptureTimeoutMilliseconds, defaultCaptureOutputLimitBytes, defaultDirenvTimeoutMilliseconds, defaultDirenvOutputLimitBytes, shellCaptureScript, environmentNamePattern, JobEnvironmentError, JobEnvironmentCancelledError, ShellEnvironmentManager;
6267
+ var init_shell_environment = __esm({
6268
+ "../machine-connector/dist/runtime/shell-environment.js"() {
6269
+ "use strict";
6270
+ init_cjs_shims();
6271
+ import_node_child_process2 = require("child_process");
6272
+ import_promises8 = require("fs/promises");
6273
+ import_node_os3 = require("os");
6274
+ import_node_path6 = require("path");
6275
+ defaultCaptureTimeoutMilliseconds = 5e3;
6276
+ defaultCaptureOutputLimitBytes = 1048576;
6277
+ defaultDirenvTimeoutMilliseconds = 5e3;
6278
+ defaultDirenvOutputLimitBytes = 1048576;
6279
+ shellCaptureScript = `exec "$1" -e 'for (const [name, value] of Object.entries(process.env)) process.stdout.write(name + "=" + value + "\\0")'`;
6280
+ environmentNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
6281
+ JobEnvironmentError = class extends Error {
6282
+ category;
6283
+ constructor(category) {
6284
+ super(`Local Machine Job environment resolution failed (${category})`);
6285
+ this.category = category;
6286
+ this.name = "JobEnvironmentError";
6287
+ }
6288
+ };
6289
+ JobEnvironmentCancelledError = class extends Error {
6290
+ constructor() {
6291
+ super("Local Machine Job environment resolution was cancelled");
6292
+ this.name = "JobEnvironmentCancelledError";
6293
+ }
6294
+ };
6295
+ ShellEnvironmentManager = class {
6296
+ captureOutputLimitBytes;
6297
+ captureTimeoutMilliseconds;
6298
+ daemonEnvironment;
6299
+ defaultShell;
6300
+ direnvOutputLimitBytes;
6301
+ direnvTimeoutMilliseconds;
6302
+ currentEnvironment;
6303
+ currentStatus = { state: "degraded" };
6304
+ refreshPromise;
6305
+ constructor(options = {}) {
6306
+ this.captureOutputLimitBytes = options.captureOutputLimitBytes ?? defaultCaptureOutputLimitBytes;
6307
+ this.captureTimeoutMilliseconds = options.captureTimeoutMilliseconds ?? defaultCaptureTimeoutMilliseconds;
6308
+ this.daemonEnvironment = freezeEnvironment(sanitizeEnvironment(options.daemonEnvironment ?? process.env));
6309
+ this.defaultShell = options.defaultShell ?? (0, import_node_os3.userInfo)().shell ?? "";
6310
+ this.direnvOutputLimitBytes = options.direnvOutputLimitBytes ?? defaultDirenvOutputLimitBytes;
6311
+ this.direnvTimeoutMilliseconds = options.direnvTimeoutMilliseconds ?? defaultDirenvTimeoutMilliseconds;
6312
+ this.currentEnvironment = this.daemonEnvironment;
6313
+ }
6314
+ async initialize() {
6315
+ const capture = await this.capture();
6316
+ this.currentEnvironment = capture.environment ?? this.daemonEnvironment;
6317
+ this.currentStatus = capture.status;
6318
+ return { ...this.currentStatus };
6319
+ }
6320
+ async refresh() {
6321
+ if (!this.refreshPromise) {
6322
+ this.refreshPromise = this.refreshOnce().finally(() => {
6323
+ this.refreshPromise = void 0;
6324
+ });
6325
+ }
6326
+ return await this.refreshPromise;
6327
+ }
6328
+ snapshot() {
6329
+ return this.currentEnvironment;
6330
+ }
6331
+ status() {
6332
+ return { ...this.currentStatus };
6333
+ }
6334
+ async resolveForJob(canonicalRoot, canonicalWorkingDirectory, explicitEnvironment, cancellationSignal) {
6335
+ throwIfCancelled(cancellationSignal);
6336
+ const relativeWorkingDirectory = (0, import_node_path6.relative)(canonicalRoot, canonicalWorkingDirectory);
6337
+ if (relativeWorkingDirectory === ".." || relativeWorkingDirectory.startsWith(`..${import_node_path6.sep}`) || (0, import_node_path6.isAbsolute)(relativeWorkingDirectory)) {
6338
+ throw new JobEnvironmentError("direnv_malformed");
6339
+ }
6340
+ const baseSnapshot = this.currentEnvironment;
6341
+ const envrcPath = await findNearestEnvrc(canonicalRoot, canonicalWorkingDirectory);
6342
+ throwIfCancelled(cancellationSignal);
6343
+ if (!envrcPath) {
6344
+ return freezeEnvironment({
6345
+ ...baseSnapshot,
6346
+ ...explicitEnvironment
6347
+ });
6348
+ }
6349
+ const direnvExecutable = await findExecutable("direnv", baseSnapshot.PATH);
6350
+ if (!direnvExecutable) {
6351
+ throw new JobEnvironmentError("direnv_missing");
6352
+ }
6353
+ const result = await executeBounded({
6354
+ argumentsList: ["export", "json"],
6355
+ cwd: canonicalWorkingDirectory,
6356
+ environment: baseSnapshot,
6357
+ executable: direnvExecutable,
6358
+ outputLimitBytes: this.direnvOutputLimitBytes,
6359
+ timeoutMilliseconds: this.direnvTimeoutMilliseconds,
6360
+ cancellationSignal
6361
+ });
6362
+ if (result.outcome === "cancelled") {
6363
+ throw new JobEnvironmentCancelledError();
6364
+ }
6365
+ if (result.outcome === "timeout") {
6366
+ throw new JobEnvironmentError("direnv_timeout");
6367
+ }
6368
+ if (result.outcome === "overflow") {
6369
+ throw new JobEnvironmentError("direnv_overflow");
6370
+ }
6371
+ if (result.outcome === "spawn_failed") {
6372
+ throw new JobEnvironmentError("direnv_spawn_failed");
6373
+ }
6374
+ if (result.exitCode !== 0) {
6375
+ const stderr = decodeUtf8(result.stderr, "direnv_malformed");
6376
+ throw new JobEnvironmentError(/blocked|not allowed|denied/i.test(stderr) ? "direnv_blocked" : "direnv_nonzero");
6377
+ }
6378
+ let parsedExports;
6379
+ try {
6380
+ parsedExports = parseDirenvJson(decodeUtf8(result.stdout, "direnv_malformed"));
6381
+ } catch {
6382
+ throw new JobEnvironmentError("direnv_malformed");
6383
+ }
6384
+ const exports2 = sanitizeDirenvExports(parsedExports);
6385
+ const environment = { ...baseSnapshot };
6386
+ for (const [name, value] of Object.entries(exports2)) {
6387
+ if (value === null) {
6388
+ delete environment[name];
6389
+ } else {
6390
+ environment[name] = value;
6391
+ }
6392
+ }
6393
+ return freezeEnvironment({
6394
+ ...environment,
6395
+ ...explicitEnvironment
6396
+ });
6397
+ }
6398
+ async capture() {
6399
+ let shell;
6400
+ try {
6401
+ shell = await validateShell(this.defaultShell);
6402
+ } catch {
6403
+ return degradedCapture("shell_environment_invalid_shell");
6404
+ }
6405
+ const result = await executeBounded({
6406
+ argumentsList: [
6407
+ "-l",
6408
+ "-i",
6409
+ "-c",
6410
+ shellCaptureScript,
6411
+ "moxt-shell-environment",
6412
+ process.execPath
6413
+ ],
6414
+ cwd: this.daemonEnvironment.HOME,
6415
+ environment: this.daemonEnvironment,
6416
+ executable: shell,
6417
+ outputLimitBytes: this.captureOutputLimitBytes,
6418
+ timeoutMilliseconds: this.captureTimeoutMilliseconds
6419
+ });
6420
+ if (result.outcome === "timeout") {
6421
+ return degradedCapture("shell_environment_timeout");
6422
+ }
6423
+ if (result.outcome === "overflow") {
6424
+ return degradedCapture("shell_environment_overflow");
6425
+ }
6426
+ if (result.outcome === "spawn_failed") {
6427
+ return degradedCapture("shell_environment_spawn_failed");
6428
+ }
6429
+ if (result.exitCode !== 0) {
6430
+ return degradedCapture("shell_environment_nonzero");
6431
+ }
6432
+ try {
6433
+ const snapshot = parseNullSeparatedEnvironment(result.stdout);
6434
+ return {
6435
+ environment: freezeEnvironment({
6436
+ ...this.daemonEnvironment,
6437
+ ...sanitizeEnvironment(snapshot)
6438
+ }),
6439
+ status: {
6440
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
6441
+ state: "captured"
6442
+ }
6443
+ };
6444
+ } catch {
6445
+ return degradedCapture("shell_environment_malformed");
6446
+ }
6447
+ }
6448
+ async refreshOnce() {
6449
+ const capture = await this.capture();
6450
+ if (capture.environment) {
6451
+ this.currentEnvironment = capture.environment;
6452
+ this.currentStatus = capture.status;
6453
+ }
6454
+ return { ...capture.status };
5830
6455
  }
5831
6456
  };
5832
6457
  }
@@ -6019,12 +6644,12 @@ var init_relay_client = __esm({
6019
6644
  });
6020
6645
 
6021
6646
  // ../machine-connector/dist/runtime/runtime-logger.js
6022
- var import_promises8, RuntimeLogger;
6647
+ var import_promises9, RuntimeLogger;
6023
6648
  var init_runtime_logger = __esm({
6024
6649
  "../machine-connector/dist/runtime/runtime-logger.js"() {
6025
6650
  "use strict";
6026
6651
  init_cjs_shims();
6027
- import_promises8 = require("fs/promises");
6652
+ import_promises9 = require("fs/promises");
6028
6653
  RuntimeLogger = class {
6029
6654
  store;
6030
6655
  constructor(store) {
@@ -6038,7 +6663,7 @@ var init_runtime_logger = __esm({
6038
6663
  await this.write("error", message, metadata, this.store.runtimeErrorLogPath());
6039
6664
  }
6040
6665
  async write(level, message, metadata, path4) {
6041
- await (0, import_promises8.appendFile)(path4, `${JSON.stringify({
6666
+ await (0, import_promises9.appendFile)(path4, `${JSON.stringify({
6042
6667
  level,
6043
6668
  message,
6044
6669
  metadata,
@@ -6059,12 +6684,12 @@ function defaultRuntimeDirectory() {
6059
6684
  if (override) {
6060
6685
  return override;
6061
6686
  }
6062
- const homeDirectory = process.env.HOME ?? (0, import_node_os3.homedir)();
6063
- if ((0, import_node_os3.platform)() === "darwin") {
6064
- return (0, import_node_path6.join)(homeDirectory, "Library", "Application Support", "Moxt", "Machine Connector");
6687
+ const homeDirectory = process.env.HOME ?? (0, import_node_os4.homedir)();
6688
+ if ((0, import_node_os4.platform)() === "darwin") {
6689
+ return (0, import_node_path7.join)(homeDirectory, "Library", "Application Support", "Moxt", "Machine Connector");
6065
6690
  }
6066
- const stateHome = process.env.XDG_STATE_HOME ?? (0, import_node_path6.join)(homeDirectory, ".local", "state");
6067
- return (0, import_node_path6.join)(stateHome, "moxt", "machine-connector");
6691
+ const stateHome = process.env.XDG_STATE_HOME ?? (0, import_node_path7.join)(homeDirectory, ".local", "state");
6692
+ return (0, import_node_path7.join)(stateHome, "moxt", "machine-connector");
6068
6693
  }
6069
6694
  function isNodeErrorCode3(error, expectedCode) {
6070
6695
  if (!(error instanceof Error) || !("code" in error)) {
@@ -6072,14 +6697,14 @@ function isNodeErrorCode3(error, expectedCode) {
6072
6697
  }
6073
6698
  return error.code === expectedCode;
6074
6699
  }
6075
- var import_promises9, import_node_os3, import_node_path6, privateFileMode, privateDirectoryMode, MachineRuntimeStore;
6700
+ var import_promises10, import_node_os4, import_node_path7, privateFileMode, privateDirectoryMode, MachineRuntimeStore;
6076
6701
  var init_store = __esm({
6077
6702
  "../machine-connector/dist/runtime/store.js"() {
6078
6703
  "use strict";
6079
6704
  init_cjs_shims();
6080
- import_promises9 = require("fs/promises");
6081
- import_node_os3 = require("os");
6082
- import_node_path6 = require("path");
6705
+ import_promises10 = require("fs/promises");
6706
+ import_node_os4 = require("os");
6707
+ import_node_path7 = require("path");
6083
6708
  privateFileMode = 384;
6084
6709
  privateDirectoryMode = 448;
6085
6710
  MachineRuntimeStore = class {
@@ -6088,20 +6713,20 @@ var init_store = __esm({
6088
6713
  this.baseDirectory = baseDirectory;
6089
6714
  }
6090
6715
  async initialize() {
6091
- await (0, import_promises9.mkdir)(this.jobsDirectory(), {
6716
+ await (0, import_promises10.mkdir)(this.jobsDirectory(), {
6092
6717
  mode: privateDirectoryMode,
6093
6718
  recursive: true
6094
6719
  });
6095
- await (0, import_promises9.mkdir)(this.detachedProcessesDirectory(), {
6720
+ await (0, import_promises10.mkdir)(this.detachedProcessesDirectory(), {
6096
6721
  mode: privateDirectoryMode,
6097
6722
  recursive: true
6098
6723
  });
6099
- await (0, import_promises9.chmod)(this.baseDirectory, privateDirectoryMode);
6100
- await (0, import_promises9.chmod)(this.jobsDirectory(), privateDirectoryMode);
6101
- await (0, import_promises9.chmod)(this.detachedProcessesDirectory(), privateDirectoryMode);
6724
+ await (0, import_promises10.chmod)(this.baseDirectory, privateDirectoryMode);
6725
+ await (0, import_promises10.chmod)(this.jobsDirectory(), privateDirectoryMode);
6726
+ await (0, import_promises10.chmod)(this.detachedProcessesDirectory(), privateDirectoryMode);
6102
6727
  }
6103
6728
  async getCanonicalRoot(rootPath) {
6104
- return await (0, import_promises9.realpath)(rootPath);
6729
+ return await (0, import_promises10.realpath)(rootPath);
6105
6730
  }
6106
6731
  async readIdentity() {
6107
6732
  return await this.readOptionalJson(this.identityPath());
@@ -6144,7 +6769,7 @@ var init_store = __esm({
6144
6769
  await this.writePrivateJson(this.serviceManagerPath(), serviceManager);
6145
6770
  }
6146
6771
  async removeServiceManager() {
6147
- await (0, import_promises9.rm)(this.serviceManagerPath(), { force: true });
6772
+ await (0, import_promises10.rm)(this.serviceManagerPath(), { force: true });
6148
6773
  }
6149
6774
  async readJob(jobId) {
6150
6775
  return await this.readOptionalJson(this.jobPath(jobId));
@@ -6155,7 +6780,7 @@ var init_store = __esm({
6155
6780
  async listJobs() {
6156
6781
  let names = [];
6157
6782
  try {
6158
- names = await (0, import_promises9.readdir)(this.jobsDirectory());
6783
+ names = await (0, import_promises10.readdir)(this.jobsDirectory());
6159
6784
  } catch (error) {
6160
6785
  if (isNodeErrorCode3(error, "ENOENT")) {
6161
6786
  return [];
@@ -6164,7 +6789,7 @@ var init_store = __esm({
6164
6789
  }
6165
6790
  const jobs = [];
6166
6791
  for (const name of names.filter((entry) => entry.endsWith(".json"))) {
6167
- const job = await this.readOptionalJson((0, import_node_path6.join)(this.jobsDirectory(), name));
6792
+ const job = await this.readOptionalJson((0, import_node_path7.join)(this.jobsDirectory(), name));
6168
6793
  if (job.value) {
6169
6794
  jobs.push(job.value);
6170
6795
  }
@@ -6172,7 +6797,7 @@ var init_store = __esm({
6172
6797
  return jobs;
6173
6798
  }
6174
6799
  async deleteJob(jobId) {
6175
- await (0, import_promises9.rm)(this.jobPath(jobId), { force: true });
6800
+ await (0, import_promises10.rm)(this.jobPath(jobId), { force: true });
6176
6801
  }
6177
6802
  async writeDetachedProcess(resource) {
6178
6803
  await this.writePrivateJson(this.detachedProcessPath(resource.jobId), resource);
@@ -6180,7 +6805,7 @@ var init_store = __esm({
6180
6805
  async listDetachedProcesses() {
6181
6806
  let names = [];
6182
6807
  try {
6183
- names = await (0, import_promises9.readdir)(this.detachedProcessesDirectory());
6808
+ names = await (0, import_promises10.readdir)(this.detachedProcessesDirectory());
6184
6809
  } catch (error) {
6185
6810
  if (isNodeErrorCode3(error, "ENOENT")) {
6186
6811
  return [];
@@ -6189,7 +6814,7 @@ var init_store = __esm({
6189
6814
  }
6190
6815
  const resources = [];
6191
6816
  for (const name of names.filter((entry) => entry.endsWith(".json"))) {
6192
- const resource = await this.readOptionalJson((0, import_node_path6.join)(this.detachedProcessesDirectory(), name));
6817
+ const resource = await this.readOptionalJson((0, import_node_path7.join)(this.detachedProcessesDirectory(), name));
6193
6818
  if (resource.value) {
6194
6819
  resources.push(resource.value);
6195
6820
  }
@@ -6197,52 +6822,52 @@ var init_store = __esm({
6197
6822
  return resources;
6198
6823
  }
6199
6824
  async deleteDetachedProcess(jobId) {
6200
- await (0, import_promises9.rm)(this.detachedProcessPath(jobId), { force: true });
6825
+ await (0, import_promises10.rm)(this.detachedProcessPath(jobId), { force: true });
6201
6826
  }
6202
6827
  runtimeLogPath() {
6203
- return (0, import_node_path6.join)(this.baseDirectory, "machine-connector.log");
6828
+ return (0, import_node_path7.join)(this.baseDirectory, "machine-connector.log");
6204
6829
  }
6205
6830
  runtimeErrorLogPath() {
6206
- return (0, import_node_path6.join)(this.baseDirectory, "machine-connector.error.log");
6831
+ return (0, import_node_path7.join)(this.baseDirectory, "machine-connector.error.log");
6207
6832
  }
6208
6833
  runtimeStatusPath() {
6209
- return (0, import_node_path6.join)(this.baseDirectory, "runtime-status.json");
6834
+ return (0, import_node_path7.join)(this.baseDirectory, "runtime-status.json");
6210
6835
  }
6211
6836
  runtimeSocketPath() {
6212
- if ((0, import_node_os3.platform)() === "win32") {
6837
+ if ((0, import_node_os4.platform)() === "win32") {
6213
6838
  return String.raw`\\.\pipe\moxt-machine-connector`;
6214
6839
  }
6215
- return (0, import_node_path6.join)(this.baseDirectory, "machine-connector.sock");
6840
+ return (0, import_node_path7.join)(this.baseDirectory, "machine-connector.sock");
6216
6841
  }
6217
6842
  daemonLockPath() {
6218
- return (0, import_node_path6.join)(this.baseDirectory, "daemon.lock");
6843
+ return (0, import_node_path7.join)(this.baseDirectory, "daemon.lock");
6219
6844
  }
6220
6845
  reconcileLockPath() {
6221
- return (0, import_node_path6.join)(this.baseDirectory, "daemon-reconcile.lock");
6846
+ return (0, import_node_path7.join)(this.baseDirectory, "daemon-reconcile.lock");
6222
6847
  }
6223
6848
  connectionsPath() {
6224
- return (0, import_node_path6.join)(this.baseDirectory, "connections.json");
6849
+ return (0, import_node_path7.join)(this.baseDirectory, "connections.json");
6225
6850
  }
6226
6851
  detachedProcessesDirectory() {
6227
- return (0, import_node_path6.join)(this.baseDirectory, "detached-processes");
6852
+ return (0, import_node_path7.join)(this.baseDirectory, "detached-processes");
6228
6853
  }
6229
6854
  detachedProcessPath(jobId) {
6230
- return (0, import_node_path6.join)(this.detachedProcessesDirectory(), `${jobId}.json`);
6855
+ return (0, import_node_path7.join)(this.detachedProcessesDirectory(), `${jobId}.json`);
6231
6856
  }
6232
6857
  identityPath() {
6233
- return (0, import_node_path6.join)(this.baseDirectory, "identity.json");
6858
+ return (0, import_node_path7.join)(this.baseDirectory, "identity.json");
6234
6859
  }
6235
6860
  serviceManagerPath() {
6236
- return (0, import_node_path6.join)(this.baseDirectory, "service-manager.json");
6861
+ return (0, import_node_path7.join)(this.baseDirectory, "service-manager.json");
6237
6862
  }
6238
6863
  privateKeyPath() {
6239
- return (0, import_node_path6.join)(this.baseDirectory, "device-private-key.pem");
6864
+ return (0, import_node_path7.join)(this.baseDirectory, "device-private-key.pem");
6240
6865
  }
6241
6866
  jobsDirectory() {
6242
- return (0, import_node_path6.join)(this.baseDirectory, "jobs");
6867
+ return (0, import_node_path7.join)(this.baseDirectory, "jobs");
6243
6868
  }
6244
6869
  jobPath(jobId) {
6245
- return (0, import_node_path6.join)(this.jobsDirectory(), `${jobId}.json`);
6870
+ return (0, import_node_path7.join)(this.jobsDirectory(), `${jobId}.json`);
6246
6871
  }
6247
6872
  async readOptionalJson(path4) {
6248
6873
  const content3 = await this.readOptionalText(path4);
@@ -6253,7 +6878,7 @@ var init_store = __esm({
6253
6878
  }
6254
6879
  async readOptionalText(path4) {
6255
6880
  try {
6256
- return { value: await (0, import_promises9.readFile)(path4, "utf8") };
6881
+ return { value: await (0, import_promises10.readFile)(path4, "utf8") };
6257
6882
  } catch (error) {
6258
6883
  if (isNodeErrorCode3(error, "ENOENT")) {
6259
6884
  return {};
@@ -6266,17 +6891,17 @@ var init_store = __esm({
6266
6891
  `);
6267
6892
  }
6268
6893
  async writePrivateText(path4, value) {
6269
- await (0, import_promises9.mkdir)((0, import_node_path6.dirname)(path4), {
6894
+ await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), {
6270
6895
  mode: privateDirectoryMode,
6271
6896
  recursive: true
6272
6897
  });
6273
6898
  const temporaryPath = `${path4}.${process.pid}.tmp`;
6274
- await (0, import_promises9.writeFile)(temporaryPath, value, {
6899
+ await (0, import_promises10.writeFile)(temporaryPath, value, {
6275
6900
  encoding: "utf8",
6276
6901
  mode: privateFileMode
6277
6902
  });
6278
- await (0, import_promises9.chmod)(temporaryPath, privateFileMode);
6279
- await (0, import_promises9.rename)(temporaryPath, path4);
6903
+ await (0, import_promises10.chmod)(temporaryPath, privateFileMode);
6904
+ await (0, import_promises10.rename)(temporaryPath, path4);
6280
6905
  }
6281
6906
  };
6282
6907
  }
@@ -6306,12 +6931,12 @@ function delay4(milliseconds) {
6306
6931
  setTimeout(resolvePromise, milliseconds);
6307
6932
  });
6308
6933
  }
6309
- var import_node_os4, import_node_crypto5, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
6934
+ var import_node_os5, import_node_crypto5, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
6310
6935
  var init_daemon = __esm({
6311
6936
  "../machine-connector/dist/runtime/daemon.js"() {
6312
6937
  "use strict";
6313
6938
  init_cjs_shims();
6314
- import_node_os4 = require("os");
6939
+ import_node_os5 = require("os");
6315
6940
  import_node_crypto5 = require("crypto");
6316
6941
  init_enums();
6317
6942
  init_contracts();
@@ -6323,6 +6948,7 @@ var init_daemon = __esm({
6323
6948
  init_local_ipc();
6324
6949
  init_process_lock();
6325
6950
  init_process_executor();
6951
+ init_shell_environment();
6326
6952
  init_relay_client();
6327
6953
  init_runtime_logger();
6328
6954
  init_runtime_types();
@@ -6358,6 +6984,10 @@ var init_daemon = __esm({
6358
6984
  connections = [];
6359
6985
  daemonLock;
6360
6986
  ipcServer;
6987
+ lifetimeSettled;
6988
+ settleLifetime;
6989
+ startupSettled;
6990
+ settleStartup;
6361
6991
  stopping = false;
6362
6992
  leaseSafetyMarginMilliseconds;
6363
6993
  leaseSeconds;
@@ -6365,10 +6995,18 @@ var init_daemon = __esm({
6365
6995
  random;
6366
6996
  terminalForegroundBudgetMilliseconds;
6367
6997
  cliVersion;
6998
+ shellEnvironmentManager;
6368
6999
  constructor(store = new MachineRuntimeStore(), options = {}) {
6369
7000
  this.store = store;
7001
+ this.lifetimeSettled = new Promise((resolvePromise) => {
7002
+ this.settleLifetime = resolvePromise;
7003
+ });
7004
+ this.startupSettled = new Promise((resolvePromise) => {
7005
+ this.settleStartup = resolvePromise;
7006
+ });
6370
7007
  this.logger = new RuntimeLogger(store);
6371
7008
  this.cliVersion = options.cliVersion;
7009
+ this.shellEnvironmentManager = options.shellEnvironmentManager ?? new ShellEnvironmentManager();
6372
7010
  this.leaseSafetyMarginMilliseconds = options.leaseSafetyMarginMilliseconds ?? defaultLeaseSafetyMarginMilliseconds;
6373
7011
  this.leaseSeconds = options.leaseSeconds ?? defaultLeaseSeconds;
6374
7012
  this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds;
@@ -6376,36 +7014,64 @@ var init_daemon = __esm({
6376
7014
  this.terminalForegroundBudgetMilliseconds = options.terminalForegroundBudgetMilliseconds ?? defaultTerminalForegroundBudgetMilliseconds;
6377
7015
  }
6378
7016
  async start() {
6379
- if (process.getuid?.() === 0) {
6380
- throw new Error("Moxt Machine Connector must run as an unprivileged user");
6381
- }
6382
- await this.store.initialize();
6383
- this.daemonLock = await ProcessLock.acquire(this.store.daemonLockPath(), { timeoutMilliseconds: 1e3 });
6384
- if (!this.daemonLock) {
6385
- throw new Error("Another Moxt Machine Connector daemon is already running or starting");
6386
- }
6387
7017
  try {
7018
+ if (process.getuid?.() === 0) {
7019
+ throw new Error("Moxt Machine Connector must run as an unprivileged user");
7020
+ }
7021
+ await this.store.initialize();
7022
+ this.throwIfStopping();
7023
+ this.daemonLock = await ProcessLock.acquire(this.store.daemonLockPath(), { timeoutMilliseconds: 1e3 });
7024
+ if (!this.daemonLock) {
7025
+ throw new Error("Another Moxt Machine Connector daemon is already running or starting");
7026
+ }
7027
+ this.throwIfStopping();
7028
+ const shellEnvironmentStatus = await this.shellEnvironmentManager.initialize();
7029
+ await this.logger.info("Local Machine shell environment initialized", {
7030
+ category: shellEnvironmentStatus.category,
7031
+ state: shellEnvironmentStatus.state
7032
+ });
7033
+ this.throwIfStopping();
6388
7034
  await this.recoverInterruptedJobs();
6389
- this.ipcServer = new LocalIpcServer(this.store, () => this.getStatus());
7035
+ this.throwIfStopping();
7036
+ this.ipcServer = new LocalIpcServer(this.store, () => this.getStatus(), async () => {
7037
+ const status = await this.shellEnvironmentManager.refresh();
7038
+ await this.logger.info("Local Machine shell environment refreshed", {
7039
+ category: status.category,
7040
+ state: status.state
7041
+ });
7042
+ return status;
7043
+ });
6390
7044
  await this.ipcServer.start();
7045
+ this.throwIfStopping();
6391
7046
  await this.logger.info("Moxt Machine Connector started", {
6392
7047
  connectorInstanceId: this.connectorInstanceId,
6393
- hostname: (0, import_node_os4.hostname)(),
7048
+ hostname: (0, import_node_os5.hostname)(),
6394
7049
  version: connectorVersion
6395
7050
  });
6396
7051
  this.connections = await this.store.listConnections();
7052
+ this.throwIfStopping();
6397
7053
  if (this.connections.length === 0) {
6398
7054
  await this.logger.info("No Local Machine connections are configured");
6399
7055
  }
7056
+ this.settleStartup();
6400
7057
  await Promise.all(this.connections.map(async (connection) => {
6401
7058
  await this.runConnection(connection);
6402
7059
  }));
6403
7060
  await this.waitForExecutionTasks();
6404
7061
  } catch (error) {
6405
- await this.ipcServer?.close();
6406
- this.ipcServer = void 0;
6407
- await this.releaseDaemonLock();
7062
+ try {
7063
+ await this.ipcServer?.close();
7064
+ } finally {
7065
+ this.ipcServer = void 0;
7066
+ try {
7067
+ await this.releaseDaemonLock();
7068
+ } finally {
7069
+ this.settleStartup();
7070
+ }
7071
+ }
6408
7072
  throw error;
7073
+ } finally {
7074
+ this.settleLifetime();
6409
7075
  }
6410
7076
  }
6411
7077
  async stop() {
@@ -6413,10 +7079,15 @@ var init_daemon = __esm({
6413
7079
  await Promise.all([...this.activeJobs.values()].map(async (activeJob) => {
6414
7080
  await activeJob.cancellation.request(ExecutionCancellationReason.Stopping);
6415
7081
  }));
7082
+ await this.startupSettled;
6416
7083
  await this.ipcServer?.close();
6417
7084
  this.ipcServer = void 0;
6418
- await this.releaseDaemonLock();
6419
- await this.logger.info("Moxt Machine Connector stopped");
7085
+ await this.lifetimeSettled;
7086
+ try {
7087
+ await this.logger.info("Moxt Machine Connector stopped");
7088
+ } finally {
7089
+ await this.releaseDaemonLock();
7090
+ }
6420
7091
  }
6421
7092
  getStatus() {
6422
7093
  return {
@@ -6440,6 +7111,7 @@ var init_daemon = __esm({
6440
7111
  connectorInstanceId: this.connectorInstanceId,
6441
7112
  pid: process.pid,
6442
7113
  startedAt: this.startedAt,
7114
+ shellEnvironment: this.shellEnvironmentManager.status(),
6443
7115
  version: connectorVersion
6444
7116
  };
6445
7117
  }
@@ -6653,12 +7325,27 @@ var init_daemon = __esm({
6653
7325
  const { claim } = activeJob;
6654
7326
  const registerProcess = activeJob.cancellation.register.bind(activeJob.cancellation);
6655
7327
  const canSpawn = activeJob.cancellation.canSpawn.bind(activeJob.cancellation);
7328
+ const resolveEnvironment = async (workingDirectory2, explicitEnvironment) => {
7329
+ try {
7330
+ return await this.shellEnvironmentManager.resolveForJob(activeJob.connection.rootPath, workingDirectory2, explicitEnvironment, activeJob.cancellation.signal());
7331
+ } catch (error) {
7332
+ if (error instanceof JobEnvironmentCancelledError) {
7333
+ return void 0;
7334
+ }
7335
+ throw error;
7336
+ }
7337
+ };
7338
+ if (!canSpawn()) {
7339
+ return this.cancellationResult(activeJob);
7340
+ }
6656
7341
  if (claim.kind === MachineJobKind.Command) {
6657
7342
  const request2 = claim.requestPayload;
6658
- const result = await executeCommand(activeJob.connection.rootPath, {
6659
- ...request2,
6660
- relativeWorkingDirectory: claim.relativeWorkingDirectory
6661
- }, {
7343
+ const workingDirectory2 = await resolveCanonicalWorkingDirectory(activeJob.connection.rootPath, claim.relativeWorkingDirectory);
7344
+ const environment2 = await resolveEnvironment(workingDirectory2, request2.environment);
7345
+ if (!environment2 || !canSpawn()) {
7346
+ return this.cancellationResult(activeJob);
7347
+ }
7348
+ const result = await executeProcess(request2.executable, request2.arguments, workingDirectory2, environment2, request2.stdin, request2.timeoutSeconds, {
6662
7349
  canSpawn,
6663
7350
  onOutput: async (output) => {
6664
7351
  if (activeJob.cancellation.currentReason() !== void 0) {
@@ -6685,6 +7372,10 @@ var init_daemon = __esm({
6685
7372
  if (!canSpawn()) {
6686
7373
  return this.cancellationResult(activeJob);
6687
7374
  }
7375
+ const environment = await resolveEnvironment(workingDirectory, {});
7376
+ if (!environment || !canSpawn()) {
7377
+ return this.cancellationResult(activeJob);
7378
+ }
6688
7379
  const callbacks = {
6689
7380
  canSpawn,
6690
7381
  onEvent: async (event) => {
@@ -6706,7 +7397,7 @@ var init_daemon = __esm({
6706
7397
  };
6707
7398
  if (claim.kind === MachineJobKind.CodexStart) {
6708
7399
  const request2 = claim.requestPayload;
6709
- const result = await executeCodexStart(workingDirectory, this.store.baseDirectory, {
7400
+ const result = await executeCodexStart(workingDirectory, this.store.baseDirectory, environment, {
6710
7401
  ...request2,
6711
7402
  relativeWorkingDirectory: claim.relativeWorkingDirectory
6712
7403
  }, callbacks);
@@ -6720,7 +7411,7 @@ var init_daemon = __esm({
6720
7411
  }
6721
7412
  if (claim.kind === MachineJobKind.CodexReply) {
6722
7413
  const request2 = claim.requestPayload;
6723
- const result = await executeCodexReply(workingDirectory, this.store.baseDirectory, {
7414
+ const result = await executeCodexReply(workingDirectory, this.store.baseDirectory, environment, {
6724
7415
  ...request2,
6725
7416
  relativeWorkingDirectory: claim.relativeWorkingDirectory
6726
7417
  }, callbacks);
@@ -6735,7 +7426,7 @@ var init_daemon = __esm({
6735
7426
  }
6736
7427
  if (claim.kind === MachineJobKind.ClaudeStart) {
6737
7428
  const request2 = claim.requestPayload;
6738
- const result = await executeClaudeStart(workingDirectory, {
7429
+ const result = await executeClaudeStart(workingDirectory, environment, {
6739
7430
  ...request2,
6740
7431
  relativeWorkingDirectory: claim.relativeWorkingDirectory
6741
7432
  }, callbacks);
@@ -6749,7 +7440,7 @@ var init_daemon = __esm({
6749
7440
  }
6750
7441
  if (claim.kind === MachineJobKind.ClaudeReply) {
6751
7442
  const request2 = claim.requestPayload;
6752
- const result = await executeClaudeReply(workingDirectory, {
7443
+ const result = await executeClaudeReply(workingDirectory, environment, {
6753
7444
  ...request2,
6754
7445
  relativeWorkingDirectory: claim.relativeWorkingDirectory
6755
7446
  }, callbacks);
@@ -7012,6 +7703,11 @@ var init_daemon = __esm({
7012
7703
  await this.daemonLock?.release();
7013
7704
  this.daemonLock = void 0;
7014
7705
  }
7706
+ throwIfStopping() {
7707
+ if (this.stopping) {
7708
+ throw new Error("Moxt Machine Connector stopped during startup");
7709
+ }
7710
+ }
7015
7711
  async recoverInterruptedJobs() {
7016
7712
  const jobs = await this.store.listJobs();
7017
7713
  for (const job of jobs) {
@@ -7217,12 +7913,12 @@ async function installUserService(store, request2, runtime = defaultServiceManag
7217
7913
  }
7218
7914
  function createServiceEnvironment(options) {
7219
7915
  const inheritedPath = options.environment.PATH ?? process.env.PATH ?? "";
7220
- const nodeDirectory = (0, import_node_path7.dirname)(options.nodePath);
7221
- const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path7.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
7916
+ const nodeDirectory = (0, import_node_path8.dirname)(options.nodePath);
7917
+ const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path8.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
7222
7918
  return {
7223
7919
  ...options.environment,
7224
- HOME: options.environment.HOME ?? process.env.HOME ?? (0, import_node_os5.homedir)(),
7225
- PATH: pathEntries.join(import_node_path7.delimiter)
7920
+ HOME: options.environment.HOME ?? process.env.HOME ?? (0, import_node_os6.homedir)(),
7921
+ PATH: pathEntries.join(import_node_path8.delimiter)
7226
7922
  };
7227
7923
  }
7228
7924
  async function restartUserService(store, runtime = defaultServiceManagerRuntime) {
@@ -7265,39 +7961,35 @@ async function refreshManagedUserService(store, options, runtime = defaultServic
7265
7961
  return { manager, rollback };
7266
7962
  }
7267
7963
  async function managedServiceOwnsProcess(manager, processId, store, runtime = defaultServiceManagerRuntime) {
7268
- try {
7269
- if (manager === UserServiceManager.Launchd) {
7270
- const result = await runtime.run("launchctl", [
7271
- "print",
7272
- `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7273
- ]);
7274
- const match = /(?:^|\s)pid\s*=\s*(\d+)(?:\s|$)/m.exec(result.stdout);
7275
- return match ? Number(match[1]) === processId : false;
7276
- }
7277
- if (manager === UserServiceManager.Systemd) {
7278
- const result = await runtime.run("systemctl", [
7279
- "--user",
7280
- "show",
7281
- "--property",
7282
- "MainPID",
7283
- "--value",
7284
- "moxt-machine-connector.service"
7285
- ]);
7286
- return parseProcessId(result.stdout) === processId;
7287
- }
7288
- if (manager === UserServiceManager.Supervisor) {
7289
- const result = await runtime.run("supervisorctl", [
7290
- "-c",
7291
- supervisorConfigPath(store),
7292
- "pid",
7293
- supervisorProgramName
7294
- ]);
7295
- return parseProcessId(result.stdout) === processId;
7296
- }
7297
- return false;
7298
- } catch {
7299
- return false;
7964
+ if (manager === UserServiceManager.Launchd) {
7965
+ const result = await runServiceProbe(runtime, "launchctl", [
7966
+ "print",
7967
+ `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7968
+ ]);
7969
+ const match = /(?:^|\s)pid\s*=\s*(\d+)(?:\s|$)/m.exec(result.stdout);
7970
+ return match ? Number(match[1]) === processId : false;
7300
7971
  }
7972
+ if (manager === UserServiceManager.Systemd) {
7973
+ const result = await runServiceProbe(runtime, "systemctl", [
7974
+ "--user",
7975
+ "show",
7976
+ "--property",
7977
+ "MainPID",
7978
+ "--value",
7979
+ "moxt-machine-connector.service"
7980
+ ]);
7981
+ return parseProcessId(result.stdout) === processId;
7982
+ }
7983
+ if (manager === UserServiceManager.Supervisor) {
7984
+ const result = await runServiceProbe(runtime, "supervisorctl", [
7985
+ "-c",
7986
+ supervisorConfigPath(store),
7987
+ "pid",
7988
+ supervisorProgramName
7989
+ ]);
7990
+ return parseProcessId(result.stdout) === processId;
7991
+ }
7992
+ return false;
7301
7993
  }
7302
7994
  async function recordedServiceManager(store) {
7303
7995
  return await readStoredServiceManager(store);
@@ -7409,7 +8101,7 @@ async function uninstallManager(manager, store, runtime) {
7409
8101
  "bootout",
7410
8102
  `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7411
8103
  ]);
7412
- await (0, import_promises10.rm)(launchAgentPath(), { force: true });
8104
+ await (0, import_promises11.rm)(launchAgentPath(), { force: true });
7413
8105
  return;
7414
8106
  }
7415
8107
  if (manager === UserServiceManager.Systemd) {
@@ -7419,7 +8111,7 @@ async function uninstallManager(manager, store, runtime) {
7419
8111
  "--now",
7420
8112
  "moxt-machine-connector.service"
7421
8113
  ]);
7422
- await (0, import_promises10.rm)(systemdUnitPath(), { force: true });
8114
+ await (0, import_promises11.rm)(systemdUnitPath(), { force: true });
7423
8115
  await runCommandIgnoringFailure(runtime, "systemctl", [
7424
8116
  "--user",
7425
8117
  "daemon-reload"
@@ -7433,7 +8125,7 @@ async function uninstallManager(manager, store, runtime) {
7433
8125
  supervisorProgramName
7434
8126
  ]);
7435
8127
  await runCommandIgnoringFailure(runtime, "supervisorctl", ["-c", supervisorConfigPath(store), "shutdown"]);
7436
- await (0, import_promises10.rm)(supervisorDirectory(store), {
8128
+ await (0, import_promises11.rm)(supervisorDirectory(store), {
7437
8129
  force: true,
7438
8130
  recursive: true
7439
8131
  });
@@ -7459,7 +8151,7 @@ async function readStoredServiceManager(store) {
7459
8151
  }
7460
8152
  async function readManagedServiceDefinition(manager, store) {
7461
8153
  try {
7462
- return await (0, import_promises10.readFile)(managedServiceDefinitionPath(manager, store), "utf8");
8154
+ return await (0, import_promises11.readFile)(managedServiceDefinitionPath(manager, store), "utf8");
7463
8155
  } catch (error) {
7464
8156
  if (isNodeErrorCode4(error, "ENOENT"))
7465
8157
  return void 0;
@@ -7468,8 +8160,8 @@ async function readManagedServiceDefinition(manager, store) {
7468
8160
  }
7469
8161
  async function restoreManagedServiceDefinition(manager, store, definition2, runtime) {
7470
8162
  const path4 = managedServiceDefinitionPath(manager, store);
7471
- await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
7472
- await (0, import_promises10.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
8163
+ await (0, import_promises11.mkdir)((0, import_node_path8.dirname)(path4), { recursive: true });
8164
+ await (0, import_promises11.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
7473
8165
  if (manager === UserServiceManager.Launchd) {
7474
8166
  const domain = `gui/${process.getuid?.() ?? 0}`;
7475
8167
  await runCommandIgnoringFailure(runtime, "launchctl", [
@@ -7481,8 +8173,7 @@ async function restoreManagedServiceDefinition(manager, store, definition2, runt
7481
8173
  } else if (manager === UserServiceManager.Systemd) {
7482
8174
  await runtime.run("systemctl", ["--user", "daemon-reload"]);
7483
8175
  } else if (manager === UserServiceManager.Supervisor) {
7484
- await runtime.run("supervisorctl", ["-c", path4, "reread"]);
7485
- await runtime.run("supervisorctl", ["-c", path4, "update"]);
8176
+ await reloadSupervisorConfiguration(store, runtime);
7486
8177
  return;
7487
8178
  }
7488
8179
  await restartManager(manager, store, runtime);
@@ -7545,10 +8236,10 @@ function automaticSelectionDetail(manager) {
7545
8236
  }
7546
8237
  async function installLaunchAgent(store, options, runtime) {
7547
8238
  const path4 = launchAgentPath();
7548
- await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
8239
+ await (0, import_promises11.mkdir)((0, import_node_path8.dirname)(path4), { recursive: true });
7549
8240
  const programArguments = [
7550
8241
  options.nodePath,
7551
- (0, import_node_path7.resolve)(options.entrypointPath),
8242
+ (0, import_node_path8.resolve)(options.entrypointPath),
7552
8243
  ...options.commandArguments
7553
8244
  ];
7554
8245
  const plist = `<?xml version="1.0" encoding="UTF-8"?>
@@ -7579,7 +8270,7 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
7579
8270
  </dict>
7580
8271
  </plist>
7581
8272
  `;
7582
- await (0, import_promises10.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
8273
+ await (0, import_promises11.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
7583
8274
  const domain = `gui/${process.getuid?.() ?? 0}`;
7584
8275
  await runCommandIgnoringFailure(runtime, "launchctl", [
7585
8276
  "bootout",
@@ -7595,10 +8286,10 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
7595
8286
  }
7596
8287
  async function installSystemdUserService(store, options, runtime) {
7597
8288
  const path4 = systemdUnitPath();
7598
- await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
8289
+ await (0, import_promises11.mkdir)((0, import_node_path8.dirname)(path4), { recursive: true });
7599
8290
  const command = [
7600
8291
  options.nodePath,
7601
- (0, import_node_path7.resolve)(options.entrypointPath),
8292
+ (0, import_node_path8.resolve)(options.entrypointPath),
7602
8293
  ...options.commandArguments
7603
8294
  ].map(escapeSystemdArgument).join(" ");
7604
8295
  const unit = `[Unit]
@@ -7617,7 +8308,7 @@ ${Object.entries(options.environment).map(([name, value]) => `Environment=${esca
7617
8308
  [Install]
7618
8309
  WantedBy=default.target
7619
8310
  `;
7620
- await (0, import_promises10.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
8311
+ await (0, import_promises11.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
7621
8312
  await runtime.run("systemctl", ["--user", "daemon-reload"]);
7622
8313
  await runtime.run("systemctl", [
7623
8314
  "--user",
@@ -7627,32 +8318,31 @@ WantedBy=default.target
7627
8318
  ]);
7628
8319
  await runCommandIgnoringFailure(runtime, "loginctl", [
7629
8320
  "enable-linger",
7630
- (0, import_node_os5.userInfo)().username
8321
+ (0, import_node_os6.userInfo)().username
7631
8322
  ]);
7632
8323
  }
7633
8324
  async function installSupervisorUserService(store, options, runtime) {
7634
8325
  const directory = supervisorDirectory(store);
7635
8326
  const configPath = supervisorConfigPath(store);
7636
- await (0, import_promises10.mkdir)(directory, { recursive: true, mode: 448 });
7637
- await (0, import_promises10.writeFile)(configPath, createSupervisorConfiguration(store, options), {
8327
+ await (0, import_promises11.mkdir)(directory, { recursive: true, mode: 448 });
8328
+ await (0, import_promises11.writeFile)(configPath, createSupervisorConfiguration(store, options), {
7638
8329
  encoding: "utf8",
7639
8330
  mode: 384
7640
8331
  });
7641
8332
  const supervisorWasRunning = await supervisorIsRunning(store, runtime);
7642
8333
  if (!supervisorWasRunning) {
7643
- await (0, import_promises10.rm)(supervisorSocketPath(store), { force: true });
7644
- await (0, import_promises10.rm)(supervisorPidPath(store), { force: true });
8334
+ await (0, import_promises11.rm)(supervisorSocketPath(store), { force: true });
8335
+ await (0, import_promises11.rm)(supervisorPidPath(store), { force: true });
7645
8336
  await runtime.run("supervisord", ["-c", configPath]);
7646
8337
  await waitForSupervisorControl(store, runtime);
7647
8338
  return;
7648
8339
  }
7649
- await runtime.run("supervisorctl", ["-c", configPath, "reread"]);
7650
- await runtime.run("supervisorctl", ["-c", configPath, "update"]);
8340
+ await reloadSupervisorConfiguration(store, runtime);
7651
8341
  }
7652
8342
  function createSupervisorConfiguration(store, options) {
7653
8343
  const command = [
7654
8344
  options.nodePath,
7655
- (0, import_node_path7.resolve)(options.entrypointPath),
8345
+ (0, import_node_path8.resolve)(options.entrypointPath),
7656
8346
  ...options.commandArguments
7657
8347
  ].map(escapeSupervisorArgument).join(" ");
7658
8348
  const environment = Object.entries(options.environment).map(([name, value]) => `${name}="${escapeSupervisorEnvironment(value)}"`).join(",");
@@ -7676,7 +8366,7 @@ serverurl=unix://${supervisorSocketPath(store)}
7676
8366
 
7677
8367
  [program:${supervisorProgramName}]
7678
8368
  command=${command}
7679
- directory=${escapeSupervisorPath((0, import_node_path7.dirname)((0, import_node_path7.resolve)(options.entrypointPath)))}
8369
+ directory=${escapeSupervisorPath((0, import_node_path8.dirname)((0, import_node_path8.resolve)(options.entrypointPath)))}
7680
8370
  environment=${environment}
7681
8371
  autostart=true
7682
8372
  autorestart=true
@@ -7697,8 +8387,8 @@ stderr_logfile_backups=3
7697
8387
  async function restartSupervisorUserService(store, runtime) {
7698
8388
  const configPath = supervisorConfigPath(store);
7699
8389
  if (!await supervisorIsRunning(store, runtime)) {
7700
- await (0, import_promises10.rm)(supervisorSocketPath(store), { force: true });
7701
- await (0, import_promises10.rm)(supervisorPidPath(store), { force: true });
8390
+ await (0, import_promises11.rm)(supervisorSocketPath(store), { force: true });
8391
+ await (0, import_promises11.rm)(supervisorPidPath(store), { force: true });
7702
8392
  await runtime.run("supervisord", ["-c", configPath]);
7703
8393
  await waitForSupervisorControl(store, runtime);
7704
8394
  return;
@@ -7719,6 +8409,43 @@ async function restartSupervisorUserService(store, runtime) {
7719
8409
  ]);
7720
8410
  }
7721
8411
  }
8412
+ async function reloadSupervisorConfiguration(store, runtime) {
8413
+ const configPath = supervisorConfigPath(store);
8414
+ const processIdBeforeStop = await runServiceProbe(runtime, "supervisorctl", [
8415
+ "-c",
8416
+ configPath,
8417
+ "pid",
8418
+ supervisorProgramName
8419
+ ]);
8420
+ if ((parseProcessId(processIdBeforeStop.stdout) ?? 0) > 0) {
8421
+ await runtime.run("supervisorctl", [
8422
+ "-c",
8423
+ configPath,
8424
+ "stop",
8425
+ supervisorProgramName
8426
+ ]);
8427
+ const processIdAfterStop = await runServiceProbe(runtime, "supervisorctl", ["-c", configPath, "pid", supervisorProgramName]);
8428
+ if ((parseProcessId(processIdAfterStop.stdout) ?? 0) > 0) {
8429
+ throw new Error("Supervisor did not stop the existing Moxt Machine Connector process");
8430
+ }
8431
+ }
8432
+ await runtime.run("supervisorctl", ["-c", configPath, "reread"]);
8433
+ await runtime.run("supervisorctl", ["-c", configPath, "update"]);
8434
+ const processId = await runServiceProbe(runtime, "supervisorctl", [
8435
+ "-c",
8436
+ configPath,
8437
+ "pid",
8438
+ supervisorProgramName
8439
+ ]);
8440
+ if ((parseProcessId(processId.stdout) ?? 0) > 0)
8441
+ return;
8442
+ await runtime.run("supervisorctl", [
8443
+ "-c",
8444
+ configPath,
8445
+ "start",
8446
+ supervisorProgramName
8447
+ ]);
8448
+ }
7722
8449
  async function supervisorIsRunning(store, runtime) {
7723
8450
  return await commandSucceeds(runtime, "supervisorctl", [
7724
8451
  "-c",
@@ -7737,35 +8464,40 @@ async function waitForSupervisorControl(store, runtime) {
7737
8464
  throw new Error("Supervisor did not become ready within 5 seconds");
7738
8465
  }
7739
8466
  function launchAgentPath() {
7740
- return (0, import_node_path7.join)(process.env.HOME ?? (0, import_node_os5.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
8467
+ return (0, import_node_path8.join)(process.env.HOME ?? (0, import_node_os6.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
7741
8468
  }
7742
8469
  function systemdUnitPath() {
7743
- const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path7.join)(process.env.HOME ?? (0, import_node_os5.homedir)(), ".config");
7744
- return (0, import_node_path7.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
8470
+ const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path8.join)(process.env.HOME ?? (0, import_node_os6.homedir)(), ".config");
8471
+ return (0, import_node_path8.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
7745
8472
  }
7746
8473
  function supervisorDirectory(store) {
7747
- return (0, import_node_path7.join)(store.baseDirectory, "supervisor");
8474
+ return (0, import_node_path8.join)(store.baseDirectory, "supervisor");
7748
8475
  }
7749
8476
  function supervisorConfigPath(store) {
7750
- return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.conf");
8477
+ return (0, import_node_path8.join)(supervisorDirectory(store), "supervisord.conf");
7751
8478
  }
7752
8479
  function supervisorSocketPath(store) {
7753
- return (0, import_node_path7.join)(supervisorDirectory(store), "supervisor.sock");
8480
+ return (0, import_node_path8.join)(supervisorDirectory(store), "supervisor.sock");
7754
8481
  }
7755
8482
  function supervisorPidPath(store) {
7756
- return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.pid");
8483
+ return (0, import_node_path8.join)(supervisorDirectory(store), "supervisord.pid");
7757
8484
  }
7758
8485
  function supervisorLogPath(store) {
7759
- return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.log");
8486
+ return (0, import_node_path8.join)(supervisorDirectory(store), "supervisord.log");
7760
8487
  }
7761
8488
  async function commandSucceeds(runtime, command, argumentsList) {
7762
8489
  try {
7763
- await runtime.run(command, argumentsList);
8490
+ await runServiceProbe(runtime, command, argumentsList);
7764
8491
  return true;
7765
8492
  } catch {
7766
8493
  return false;
7767
8494
  }
7768
8495
  }
8496
+ async function runServiceProbe(runtime, command, argumentsList) {
8497
+ return await runtime.run(command, argumentsList, {
8498
+ timeoutMilliseconds: serviceManagerProbeTimeoutMilliseconds
8499
+ });
8500
+ }
7769
8501
  async function runCommandIgnoringFailure(runtime, command, argumentsList) {
7770
8502
  try {
7771
8503
  await runtime.run(command, argumentsList);
@@ -7812,19 +8544,20 @@ function delay5(milliseconds) {
7812
8544
  setTimeout(resolvePromise, milliseconds);
7813
8545
  });
7814
8546
  }
7815
- var import_node_child_process2, import_promises10, import_node_os5, import_node_path7, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerCommandTimeoutMilliseconds, supervisorProgramName, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
8547
+ var import_node_child_process3, import_promises11, import_node_os6, import_node_path8, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerProbeTimeoutMilliseconds, serviceManagerMutationTimeoutMilliseconds, supervisorProgramName, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
7816
8548
  var init_service_manager = __esm({
7817
8549
  "../machine-connector/dist/runtime/service-manager.js"() {
7818
8550
  "use strict";
7819
8551
  init_cjs_shims();
7820
- import_node_child_process2 = require("child_process");
7821
- import_promises10 = require("fs/promises");
7822
- import_node_os5 = require("os");
7823
- import_node_path7 = require("path");
8552
+ import_node_child_process3 = require("child_process");
8553
+ import_promises11 = require("fs/promises");
8554
+ import_node_os6 = require("os");
8555
+ import_node_path8 = require("path");
7824
8556
  import_node_util2 = require("util");
7825
- execFileAsync = (0, import_node_util2.promisify)(import_node_child_process2.execFile);
8557
+ execFileAsync = (0, import_node_util2.promisify)(import_node_child_process3.execFile);
7826
8558
  launchAgentLabel = "ai.moxt.machine-connector";
7827
- serviceManagerCommandTimeoutMilliseconds = 5e3;
8559
+ serviceManagerProbeTimeoutMilliseconds = 5e3;
8560
+ serviceManagerMutationTimeoutMilliseconds = 3e4;
7828
8561
  supervisorProgramName = "moxt-machine-connector";
7829
8562
  (function(ServiceManagerPreference2) {
7830
8563
  ServiceManagerPreference2["Auto"] = "auto";
@@ -7839,12 +8572,12 @@ var init_service_manager = __esm({
7839
8572
  UserServiceManager2["Systemd"] = "systemd";
7840
8573
  })(UserServiceManager || (UserServiceManager = {}));
7841
8574
  defaultServiceManagerRuntime = {
7842
- operatingSystem: (0, import_node_os5.platform)(),
7843
- async run(command, argumentsList) {
8575
+ operatingSystem: (0, import_node_os6.platform)(),
8576
+ async run(command, argumentsList, options) {
7844
8577
  const result = await execFileAsync(command, argumentsList, {
7845
8578
  encoding: "utf8",
7846
8579
  killSignal: "SIGKILL",
7847
- timeout: serviceManagerCommandTimeoutMilliseconds
8580
+ timeout: options?.timeoutMilliseconds ?? serviceManagerMutationTimeoutMilliseconds
7848
8581
  });
7849
8582
  return {
7850
8583
  stderr: String(result.stderr),
@@ -7874,7 +8607,13 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
7874
8607
  if (initial.cliVersion === options.cliVersion) {
7875
8608
  return { manager, outcome: DaemonReconcileOutcome.Skipped };
7876
8609
  }
7877
- if (!await managedServiceOwnsProcess(manager, initial.pid, store)) {
8610
+ let managerOwnsProcess;
8611
+ try {
8612
+ managerOwnsProcess = await managedServiceOwnsProcess(manager, initial.pid, store);
8613
+ } catch (error) {
8614
+ throw new DaemonRefreshError("ownership", `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage2(error)}`, { cause: error });
8615
+ }
8616
+ if (!managerOwnsProcess) {
7878
8617
  return { outcome: DaemonReconcileOutcome.Skipped };
7879
8618
  }
7880
8619
  try {
@@ -7891,9 +8630,9 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
7891
8630
  try {
7892
8631
  refresh = await refreshManagedUserService(store, {
7893
8632
  commandArguments: [...options.commandArguments],
7894
- entrypointPath: (0, import_node_path8.resolve)(options.entrypointPath),
8633
+ entrypointPath: (0, import_node_path9.resolve)(options.entrypointPath),
7895
8634
  environment: { ...options.environment },
7896
- nodePath: (0, import_node_path8.resolve)(options.nodePath)
8635
+ nodePath: (0, import_node_path9.resolve)(options.nodePath)
7897
8636
  });
7898
8637
  if (!refresh) {
7899
8638
  throw new Error("The Connector service is no longer managed by Moxt");
@@ -7924,10 +8663,10 @@ async function validateCliEntrypoint(options, store) {
7924
8663
  if (options.commandArguments.length !== 2 || options.commandArguments[0] !== "machine" || options.commandArguments[1] !== "daemon") {
7925
8664
  throw new Error("The managed daemon command must be `machine daemon`");
7926
8665
  }
7927
- const nodePath = await (0, import_promises11.realpath)((0, import_node_path8.resolve)(options.nodePath));
7928
- const entrypointPath = await (0, import_promises11.realpath)((0, import_node_path8.resolve)(options.entrypointPath));
7929
- await (0, import_promises11.access)(nodePath, import_promises11.constants.X_OK);
7930
- await (0, import_promises11.access)(entrypointPath, import_promises11.constants.R_OK);
8666
+ const nodePath = await (0, import_promises12.realpath)((0, import_node_path9.resolve)(options.nodePath));
8667
+ const entrypointPath = await (0, import_promises12.realpath)((0, import_node_path9.resolve)(options.entrypointPath));
8668
+ await (0, import_promises12.access)(nodePath, import_promises12.constants.X_OK);
8669
+ await (0, import_promises12.access)(entrypointPath, import_promises12.constants.R_OK);
7931
8670
  const probe = await execFileAsync2(nodePath, [entrypointPath, "--version"], {
7932
8671
  encoding: "utf8",
7933
8672
  env: {
@@ -7960,21 +8699,21 @@ function delay6(milliseconds) {
7960
8699
  function errorMessage2(error) {
7961
8700
  return error instanceof Error ? error.message : String(error);
7962
8701
  }
7963
- var import_node_child_process3, import_promises11, import_node_path8, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshError;
8702
+ var import_node_child_process4, import_promises12, import_node_path9, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshError;
7964
8703
  var init_daemon_reconcile = __esm({
7965
8704
  "../machine-connector/dist/runtime/daemon-reconcile.js"() {
7966
8705
  "use strict";
7967
8706
  init_cjs_shims();
7968
- import_node_child_process3 = require("child_process");
7969
- import_promises11 = require("fs/promises");
7970
- import_node_path8 = require("path");
8707
+ import_node_child_process4 = require("child_process");
8708
+ import_promises12 = require("fs/promises");
8709
+ import_node_path9 = require("path");
7971
8710
  import_node_util3 = require("util");
7972
8711
  init_local_ipc();
7973
8712
  init_process_lock();
7974
8713
  init_service_manager();
7975
8714
  init_store();
7976
8715
  reconcileTimeoutMilliseconds = 12e3;
7977
- execFileAsync2 = (0, import_node_util3.promisify)(import_node_child_process3.execFile);
8716
+ execFileAsync2 = (0, import_node_util3.promisify)(import_node_child_process4.execFile);
7978
8717
  (function(DaemonReconcileOutcome2) {
7979
8718
  DaemonReconcileOutcome2["Restarted"] = "restarted";
7980
8719
  DaemonReconcileOutcome2["Skipped"] = "skipped";
@@ -8006,6 +8745,14 @@ async function runMachineDoctor(store) {
8006
8745
  name: "daemon",
8007
8746
  status: response.error ? DoctorCheckStatus.Failed : DoctorCheckStatus.Passed
8008
8747
  });
8748
+ if (response.status) {
8749
+ const shellEnvironment = response.status.shellEnvironment;
8750
+ checks.push({
8751
+ detail: shellEnvironment.state === "captured" ? "User shell environment captured" : `Using sanitized daemon environment (${shellEnvironment.category ?? "unavailable"})`,
8752
+ name: "shell-environment",
8753
+ status: shellEnvironment.state === "captured" ? DoctorCheckStatus.Passed : DoctorCheckStatus.Warning
8754
+ });
8755
+ }
8009
8756
  } catch (error) {
8010
8757
  checks.push({
8011
8758
  detail: errorMessage3(error),
@@ -8015,7 +8762,7 @@ async function runMachineDoctor(store) {
8015
8762
  }
8016
8763
  for (const connection of connections) {
8017
8764
  try {
8018
- await (0, import_promises12.access)(connection.rootPath, import_node_fs.constants.R_OK | import_node_fs.constants.X_OK);
8765
+ await (0, import_promises13.access)(connection.rootPath, import_node_fs.constants.R_OK | import_node_fs.constants.X_OK);
8019
8766
  checks.push({
8020
8767
  detail: connection.rootPath,
8021
8768
  name: `root:${connection.connectionId}`,
@@ -8030,7 +8777,7 @@ async function runMachineDoctor(store) {
8030
8777
  }
8031
8778
  const relayUrl = new URL(connection.relayOrigin);
8032
8779
  try {
8033
- const address = await (0, import_promises13.lookup)(relayUrl.hostname);
8780
+ const address = await (0, import_promises14.lookup)(relayUrl.hostname);
8034
8781
  checks.push({
8035
8782
  detail: `${relayUrl.hostname} resolves to ${address.address}`,
8036
8783
  name: `dns:${connection.connectionId}`,
@@ -8112,18 +8859,18 @@ async function runMachineDoctor(store) {
8112
8859
  function errorMessage3(error) {
8113
8860
  return error instanceof Error ? error.message : String(error);
8114
8861
  }
8115
- var import_node_child_process4, import_promises12, import_node_fs, import_promises13, import_node_util4, execFileAsync3, DoctorCheckStatus;
8862
+ var import_node_child_process5, import_promises13, import_node_fs, import_promises14, import_node_util4, execFileAsync3, DoctorCheckStatus;
8116
8863
  var init_doctor = __esm({
8117
8864
  "../machine-connector/dist/runtime/doctor.js"() {
8118
8865
  "use strict";
8119
8866
  init_cjs_shims();
8120
- import_node_child_process4 = require("child_process");
8121
- import_promises12 = require("fs/promises");
8867
+ import_node_child_process5 = require("child_process");
8868
+ import_promises13 = require("fs/promises");
8122
8869
  import_node_fs = require("fs");
8123
- import_promises13 = require("dns/promises");
8870
+ import_promises14 = require("dns/promises");
8124
8871
  import_node_util4 = require("util");
8125
8872
  init_local_ipc();
8126
- execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process4.execFile);
8873
+ execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process5.execFile);
8127
8874
  (function(DoctorCheckStatus2) {
8128
8875
  DoctorCheckStatus2["Failed"] = "failed";
8129
8876
  DoctorCheckStatus2["Passed"] = "passed";
@@ -8389,7 +9136,7 @@ async function readRecentLogLines(store) {
8389
9136
  }
8390
9137
  async function readOptionalFile(path4) {
8391
9138
  try {
8392
- return await (0, import_promises14.readFile)(path4, "utf8");
9139
+ return await (0, import_promises15.readFile)(path4, "utf8");
8393
9140
  } catch (error) {
8394
9141
  if (isMissingFile(error)) {
8395
9142
  return "";
@@ -8448,13 +9195,13 @@ function isMissingFile(error) {
8448
9195
  function errorMessage4(error) {
8449
9196
  return error instanceof Error ? error.message : String(error);
8450
9197
  }
8451
- var import_promises14, import_promises15, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
9198
+ var import_promises15, import_promises16, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
8452
9199
  var init_machine_manager = __esm({
8453
9200
  "../machine-connector/dist/runtime/machine-manager.js"() {
8454
9201
  "use strict";
8455
9202
  init_cjs_shims();
8456
- import_promises14 = require("fs/promises");
8457
- import_promises15 = require("readline/promises");
9203
+ import_promises15 = require("fs/promises");
9204
+ import_promises16 = require("readline/promises");
8458
9205
  import_node_readline = require("readline");
8459
9206
  init_doctor();
8460
9207
  init_local_ipc();
@@ -8688,7 +9435,7 @@ var init_machine_manager = __esm({
8688
9435
  }
8689
9436
  async runCommandAction(action) {
8690
9437
  this.suspendTerminal();
8691
- const reader = (0, import_promises15.createInterface)({
9438
+ const reader = (0, import_promises16.createInterface)({
8692
9439
  input: process.stdin,
8693
9440
  output: process.stdout
8694
9441
  });
@@ -8867,7 +9614,7 @@ async function pairMachine(store, options) {
8867
9614
  await store.initialize();
8868
9615
  const canonicalRoot = await store.getCanonicalRoot(options.rootPath);
8869
9616
  const identity = await ensureMachineIdentity(store);
8870
- const machineName = options.machineName ?? (0, import_node_os6.hostname)();
9617
+ const machineName = options.machineName ?? (0, import_node_os7.hostname)();
8871
9618
  const operatingSystem = getOperatingSystem();
8872
9619
  const rootHandle = (0, import_node_crypto7.createHash)("sha256").update(identity.identity.deviceKeyFingerprint, "utf8").update("\0").update(canonicalRoot, "utf8").digest("base64url");
8873
9620
  const client = new PairingRelayClient(options.relayOrigin);
@@ -8878,7 +9625,7 @@ async function pairMachine(store, options) {
8878
9625
  machineName,
8879
9626
  operatingSystem,
8880
9627
  protocolVersion: machineProtocolVersion,
8881
- rootDisplayName: (0, import_node_path9.basename)(canonicalRoot),
9628
+ rootDisplayName: (0, import_node_path10.basename)(canonicalRoot),
8882
9629
  rootHandle
8883
9630
  });
8884
9631
  options.onConfirmation?.(proposal.confirmationUrl);
@@ -8906,7 +9653,7 @@ async function pairMachine(store, options) {
8906
9653
  operatingSystem,
8907
9654
  refreshToken: credentials.refreshToken,
8908
9655
  relayOrigin: options.relayOrigin.replace(/\/+$/, ""),
8909
- rootDisplayName: (0, import_node_path9.basename)(canonicalRoot),
9656
+ rootDisplayName: (0, import_node_path10.basename)(canonicalRoot),
8910
9657
  rootHandle,
8911
9658
  rootPath: canonicalRoot,
8912
9659
  targetId: credentials.targetId,
@@ -8927,17 +9674,17 @@ async function pairMachine(store, options) {
8927
9674
  throw new Error("Local Machine pairing expired");
8928
9675
  }
8929
9676
  function getOperatingSystem() {
8930
- if ((0, import_node_os6.platform)() === "darwin") {
9677
+ if ((0, import_node_os7.platform)() === "darwin") {
8931
9678
  return MachineOperatingSystem.MacOS;
8932
9679
  }
8933
- if ((0, import_node_os6.platform)() === "linux") {
9680
+ if ((0, import_node_os7.platform)() === "linux") {
8934
9681
  return MachineOperatingSystem.Linux;
8935
9682
  }
8936
9683
  return MachineOperatingSystem.Windows;
8937
9684
  }
8938
9685
  function openBrowser(url) {
8939
- const command = (0, import_node_os6.platform)() === "darwin" ? "open" : "xdg-open";
8940
- const child = (0, import_node_child_process5.execFile)(command, [url], () => void 0);
9686
+ const command = (0, import_node_os7.platform)() === "darwin" ? "open" : "xdg-open";
9687
+ const child = (0, import_node_child_process6.execFile)(command, [url], () => void 0);
8941
9688
  child.unref();
8942
9689
  }
8943
9690
  function delay7(milliseconds) {
@@ -8945,15 +9692,15 @@ function delay7(milliseconds) {
8945
9692
  setTimeout(resolvePromise, milliseconds);
8946
9693
  });
8947
9694
  }
8948
- var import_node_child_process5, import_node_crypto7, import_node_os6, import_node_path9, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
9695
+ var import_node_child_process6, import_node_crypto7, import_node_os7, import_node_path10, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
8949
9696
  var init_pairing = __esm({
8950
9697
  "../machine-connector/dist/runtime/pairing.js"() {
8951
9698
  "use strict";
8952
9699
  init_cjs_shims();
8953
- import_node_child_process5 = require("child_process");
9700
+ import_node_child_process6 = require("child_process");
8954
9701
  import_node_crypto7 = require("crypto");
8955
- import_node_os6 = require("os");
8956
- import_node_path9 = require("path");
9702
+ import_node_os7 = require("os");
9703
+ import_node_path10 = require("path");
8957
9704
  init_contracts();
8958
9705
  init_version();
8959
9706
  init_enums();
@@ -8988,6 +9735,10 @@ async function runMachineCli(argumentsList, entrypoint) {
8988
9735
  await doctorCommand(store, commandArguments);
8989
9736
  return;
8990
9737
  }
9738
+ if (command === "environment") {
9739
+ await environmentCommand(store, commandArguments);
9740
+ return;
9741
+ }
8991
9742
  if (command === "disconnect") {
8992
9743
  await disconnectCommand(store, commandArguments);
8993
9744
  return;
@@ -9017,7 +9768,7 @@ async function runMachineCli(argumentsList, entrypoint) {
9017
9768
  async function connectCommand(store, argumentsList, entrypoint) {
9018
9769
  const options = parseOptions(argumentsList);
9019
9770
  const connectionCode = requiredOption(options, "code");
9020
- const rootPath = (0, import_node_path10.resolve)(options.root ?? process.cwd());
9771
+ const rootPath = (0, import_node_path11.resolve)(options.root ?? process.cwd());
9021
9772
  const serviceManagerPreference = requestedServiceManagerPreference(options);
9022
9773
  await validateExplicitServiceManagerPreference(serviceManagerPreference);
9023
9774
  writeLine("Internal Full Host Access: enabled");
@@ -9125,6 +9876,24 @@ async function doctorCommand(store, argumentsList) {
9125
9876
  process.exitCode = 1;
9126
9877
  }
9127
9878
  }
9879
+ async function environmentCommand(store, argumentsList) {
9880
+ const action = argumentsList[0] ?? "status";
9881
+ const response = action === "refresh" ? await requestEnvironmentRefresh(store) : action === "status" ? await requestRuntimeStatus(store) : void 0;
9882
+ if (!response) {
9883
+ throw new Error(`Unsupported environment action: ${action}`);
9884
+ }
9885
+ if (response.error) {
9886
+ throw new Error(response.error);
9887
+ }
9888
+ const status = action === "refresh" ? response.environmentRefresh : response.status?.shellEnvironment;
9889
+ if (!status) {
9890
+ throw new Error("Connector did not return shell environment status");
9891
+ }
9892
+ writeLine(`Shell environment: ${status.state}${status.category ? ` (${status.category})` : ""}`);
9893
+ if (action === "refresh" && status.state === "degraded") {
9894
+ process.exitCode = 1;
9895
+ }
9896
+ }
9128
9897
  async function disconnectCommand(store, argumentsList) {
9129
9898
  const options = parseOptions(argumentsList);
9130
9899
  const connectionId = requiredOption(options, "connection");
@@ -9284,7 +10053,7 @@ async function waitForDaemonOnline(store) {
9284
10053
  }
9285
10054
  async function readOptionalFile2(path4) {
9286
10055
  try {
9287
- return await (0, import_promises16.readFile)(path4, "utf8");
10056
+ return await (0, import_promises17.readFile)(path4, "utf8");
9288
10057
  } catch {
9289
10058
  return "";
9290
10059
  }
@@ -9297,6 +10066,7 @@ Usage:
9297
10066
  moxt machine status [--json]
9298
10067
  moxt machine logs [--lines 100]
9299
10068
  moxt machine doctor [--json]
10069
+ moxt machine environment <status|refresh>
9300
10070
  moxt machine disconnect --connection <id> [--local-only]
9301
10071
  moxt machine manager
9302
10072
  moxt machine service install [--service-manager <auto|systemd|supervisor|none>]
@@ -9312,13 +10082,13 @@ function delay8(milliseconds) {
9312
10082
  setTimeout(resolvePromise, milliseconds);
9313
10083
  });
9314
10084
  }
9315
- var import_promises16, import_node_path10, defaultRelayOrigin;
10085
+ var import_promises17, import_node_path11, defaultRelayOrigin;
9316
10086
  var init_cli = __esm({
9317
10087
  "../machine-connector/dist/cli.js"() {
9318
10088
  "use strict";
9319
10089
  init_cjs_shims();
9320
- import_promises16 = require("fs/promises");
9321
- import_node_path10 = require("path");
10090
+ import_promises17 = require("fs/promises");
10091
+ import_node_path11 = require("path");
9322
10092
  init_daemon();
9323
10093
  init_daemon_reconcile();
9324
10094
  init_doctor();
@@ -9392,6 +10162,7 @@ __export(dist_exports, {
9392
10162
  recordedServiceManager: () => recordedServiceManager,
9393
10163
  refreshManagedUserService: () => refreshManagedUserService,
9394
10164
  renderMachineManager: () => renderMachineManager,
10165
+ requestEnvironmentRefresh: () => requestEnvironmentRefresh,
9395
10166
  requestRuntimeStatus: () => requestRuntimeStatus,
9396
10167
  resolveWorkingDirectory: () => resolveWorkingDirectory,
9397
10168
  restartUserService: () => restartUserService,
@@ -9599,7 +10370,7 @@ function getApiKeyOrUndefined() {
9599
10370
 
9600
10371
  // src/utils/http.ts
9601
10372
  function getUserAgent() {
9602
- return `moxt-cli/${"0.8.1"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
10373
+ return `moxt-cli/${"0.9.0-beta.1"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
9603
10374
  }
9604
10375
  async function sendRequest(method, path4, init) {
9605
10376
  const response = await fetch(`${getApiBaseUrl()}${path4}`, {
@@ -9775,8 +10546,8 @@ function readCommentContentFile(path4) {
9775
10546
  if (!fs.existsSync(path4)) {
9776
10547
  throw new FileCommentOptionsError(`Error: comment content file not found: ${path4}`);
9777
10548
  }
9778
- const stat3 = fs.statSync(path4);
9779
- if (!stat3.isFile()) {
10549
+ const stat4 = fs.statSync(path4);
10550
+ if (!stat4.isFile()) {
9780
10551
  throw new FileCommentOptionsError(`Error: comment content path is not a file: ${path4}`);
9781
10552
  }
9782
10553
  const buffer2 = fs.readFileSync(path4);
@@ -10450,8 +11221,8 @@ var FileTokenizer = class _FileTokenizer extends AbstractTokenizer {
10450
11221
  */
10451
11222
  static async fromFile(sourceFilePath) {
10452
11223
  const fileHandle = await (0, import_promises.open)(sourceFilePath, "r");
10453
- const stat3 = await fileHandle.stat();
10454
- return new _FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat3.size } });
11224
+ const stat4 = await fileHandle.stat();
11225
+ return new _FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat4.size } });
10455
11226
  }
10456
11227
  constructor(fileHandle, options) {
10457
11228
  super(options);
@@ -19713,7 +20484,7 @@ function compiler(options) {
19713
20484
  transforms: [],
19714
20485
  canContainEols: ["emphasis", "fragment", "heading", "paragraph", "strong"],
19715
20486
  enter: {
19716
- autolink: opener(link2),
20487
+ autolink: opener(link),
19717
20488
  autolinkProtocol: onenterdata,
19718
20489
  autolinkEmail: onenterdata,
19719
20490
  atxHeading: opener(heading),
@@ -19741,7 +20512,7 @@ function compiler(options) {
19741
20512
  htmlTextData: onenterdata,
19742
20513
  image: opener(image),
19743
20514
  label: buffer2,
19744
- link: opener(link2),
20515
+ link: opener(link),
19745
20516
  listItem: opener(listItem),
19746
20517
  listItemValue: onenterlistitemvalue,
19747
20518
  listOrdered: opener(list2, onenterlistordered),
@@ -20293,7 +21064,7 @@ function compiler(options) {
20293
21064
  alt: null
20294
21065
  };
20295
21066
  }
20296
- function link2() {
21067
+ function link() {
20297
21068
  return {
20298
21069
  type: "link",
20299
21070
  title: null,
@@ -21586,7 +22357,7 @@ init_cjs_shims();
21586
22357
 
21587
22358
  // src/update/install.ts
21588
22359
  init_cjs_shims();
21589
- var import_node_child_process6 = require("child_process");
22360
+ var import_node_child_process7 = require("child_process");
21590
22361
  var import_node_fs2 = require("fs");
21591
22362
  var path3 = __toESM(require("path"), 1);
21592
22363
 
@@ -21702,7 +22473,7 @@ function runUpgrade(channel, targetVersion) {
21702
22473
  }
21703
22474
  process.stderr.write(`Updating via \`${display}\`...
21704
22475
  `);
21705
- const installation = (0, import_node_child_process6.spawnSync)(plan.command, plan.args, {
22476
+ const installation = (0, import_node_child_process7.spawnSync)(plan.command, plan.args, {
21706
22477
  encoding: "utf8",
21707
22478
  env: process.env,
21708
22479
  maxBuffer: 10 * 1024 * 1024,
@@ -21717,7 +22488,7 @@ function runUpgrade(channel, targetVersion) {
21717
22488
  success: false
21718
22489
  };
21719
22490
  }
21720
- const verification = (0, import_node_child_process6.spawnSync)("moxt", ["--version"], {
22491
+ const verification = (0, import_node_child_process7.spawnSync)("moxt", ["--version"], {
21721
22492
  encoding: "utf8",
21722
22493
  env: process.env,
21723
22494
  maxBuffer: 1024 * 1024,
@@ -21731,7 +22502,7 @@ function runUpgrade(channel, targetVersion) {
21731
22502
  success: false
21732
22503
  };
21733
22504
  }
21734
- const daemonRefresh = (0, import_node_child_process6.spawnSync)(
22505
+ const daemonRefresh = (0, import_node_child_process7.spawnSync)(
21735
22506
  "moxt",
21736
22507
  ["machine", "daemon-reconcile", "--report"],
21737
22508
  {
@@ -22130,8 +22901,8 @@ function readDescFile(path4) {
22130
22901
  if (!fs5.existsSync(path4)) {
22131
22902
  throw new WorkflowOptionsError(`Error: desc file not found: ${path4}`);
22132
22903
  }
22133
- const stat3 = fs5.statSync(path4);
22134
- if (!stat3.isFile()) {
22904
+ const stat4 = fs5.statSync(path4);
22905
+ if (!stat4.isFile()) {
22135
22906
  throw new WorkflowOptionsError(`Error: desc file is not a file: ${path4}`);
22136
22907
  }
22137
22908
  const buffer2 = fs5.readFileSync(path4);
@@ -22148,11 +22919,11 @@ function readCommentContentFile2(path4) {
22148
22919
  if (!fs5.existsSync(path4)) {
22149
22920
  throw new WorkflowOptionsError(`Error: comment content file not found: ${path4}`);
22150
22921
  }
22151
- const stat3 = fs5.statSync(path4);
22152
- if (!stat3.isFile()) {
22922
+ const stat4 = fs5.statSync(path4);
22923
+ if (!stat4.isFile()) {
22153
22924
  throw new WorkflowOptionsError(`Error: comment content path is not a file: ${path4}`);
22154
22925
  }
22155
- if (stat3.size > MAX_COMMENT_CONTENT_BYTES) {
22926
+ if (stat4.size > MAX_COMMENT_CONTENT_BYTES) {
22156
22927
  throw new WorkflowOptionsError(
22157
22928
  `Error: comment content file must be at most ${MAX_COMMENT_CONTENT_LENGTH} characters.`
22158
22929
  );
@@ -22203,6 +22974,7 @@ function parseAssigneeBody(options, allowClear) {
22203
22974
  }
22204
22975
  function parseTaskListFilterQuery(options) {
22205
22976
  const filterOwnerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
22977
+ const filterPriority = parsePriority(options.priority);
22206
22978
  const filterAssigneeHumanId = parseOptionalPositiveInteger(options.assigneeHumanId, "--assignee-human-id");
22207
22979
  const filterAssigneeAssistantId = parseOptionalPositiveInteger(
22208
22980
  options.assigneeAssistantId,
@@ -22218,6 +22990,7 @@ function parseTaskListFilterQuery(options) {
22218
22990
  }
22219
22991
  return {
22220
22992
  filterOwnerHumanId,
22993
+ filterPriority,
22221
22994
  filterAssigneeHumanId,
22222
22995
  filterAssigneeAssistantId,
22223
22996
  filterAssigneeTeammateId
@@ -22696,7 +23469,7 @@ function registerTransitionCommands(workflow) {
22696
23469
  function registerTaskCommands(workflow) {
22697
23470
  const task = workflow.command("task").description("Workflow task operations");
22698
23471
  addWorkspaceOption(
22699
- task.command("list").description("List workflow tasks").option("--workflow-file-id <workflowFileId>", "Filter by workflow file ID").option("--scope <scope>", "Task scope", "all").option("-l, --limit <limit>", "Maximum number of tasks to return", "50").option("--cursor <cursor>", "Pagination cursor").option("--owner-human-id <humanId>", "Filter by task owner human ID").option("--assignee-human-id <humanId>", "Filter by human assignee ID").option("--assignee-assistant-id <assistantId>", "Filter by AI assistant assignee ID").option("--assignee-teammate-id <teammateId>", "Filter by AI teammate assignee ID")
23472
+ task.command("list").description("List workflow tasks").option("--workflow-file-id <workflowFileId>", "Filter by workflow file ID").option("--scope <scope>", "Task scope", "all").option("-l, --limit <limit>", "Maximum number of tasks to return", "50").option("--cursor <cursor>", "Pagination cursor").option("--priority <priority>", "Filter by priority: urgent, high, medium, or low").option("--owner-human-id <humanId>", "Filter by task owner human ID").option("--assignee-human-id <humanId>", "Filter by human assignee ID").option("--assignee-assistant-id <assistantId>", "Filter by AI assistant assignee ID").option("--assignee-teammate-id <teammateId>", "Filter by AI teammate assignee ID")
22700
23473
  ).action(
22701
23474
  async (options) => {
22702
23475
  const query = runOrExit4(
@@ -23084,16 +23857,16 @@ function createProgram(version) {
23084
23857
 
23085
23858
  // src/telemetry/client.ts
23086
23859
  init_cjs_shims();
23087
- var import_node_os7 = require("os");
23860
+ var import_node_os8 = require("os");
23088
23861
  var buffer = [];
23089
23862
  var FLUSH_TIMEOUT_MS = 3e3;
23090
23863
  var MAX_BATCH_SIZE = 100;
23091
23864
  function commonLabels() {
23092
23865
  return {
23093
- cli_version: "0.8.1",
23866
+ cli_version: "0.9.0-beta.1",
23094
23867
  node_version: process.versions.node,
23095
- os: (0, import_node_os7.platform)(),
23096
- arch: (0, import_node_os7.arch)(),
23868
+ os: (0, import_node_os8.platform)(),
23869
+ arch: (0, import_node_os8.arch)(),
23097
23870
  is_ci: isCiEnvironment() ? "true" : "false"
23098
23871
  };
23099
23872
  }
@@ -23136,7 +23909,7 @@ async function flush() {
23136
23909
  }
23137
23910
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
23138
23911
  const payload = {
23139
- release_id: "0.8.1",
23912
+ release_id: "0.9.0-beta.1",
23140
23913
  client_type: "cli",
23141
23914
  metric_data_list: batch.map((m) => ({
23142
23915
  profile: "cli",
@@ -23337,7 +24110,7 @@ function registryWorker() {
23337
24110
 
23338
24111
  // src/update/prompt.ts
23339
24112
  init_cjs_shims();
23340
- var import_promises17 = require("readline/promises");
24113
+ var import_promises18 = require("readline/promises");
23341
24114
  async function promptForUpdate(input, output, currentVersion, latestVersion, timeoutMs) {
23342
24115
  output.write(`
23343
24116
  A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion}
@@ -23350,7 +24123,7 @@ A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion
23350
24123
  const controller = new AbortController();
23351
24124
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
23352
24125
  timeout.unref();
23353
- const readline = (0, import_promises17.createInterface)({ input, output, terminal: true });
24126
+ const readline = (0, import_promises18.createInterface)({ input, output, terminal: true });
23354
24127
  try {
23355
24128
  const answer = await readline.question("", { signal: controller.signal });
23356
24129
  if (answer.trim() === "1") return "update";
@@ -23453,7 +24226,7 @@ function commandPath2(command) {
23453
24226
 
23454
24227
  // src/update/daemon-reconcile-hook.ts
23455
24228
  init_cjs_shims();
23456
- var import_node_path11 = require("path");
24229
+ var import_node_path12 = require("path");
23457
24230
  function installDaemonReconcileHook(program3, cliVersion) {
23458
24231
  program3.hook("preAction", async (_thisCommand, actionCommand) => {
23459
24232
  if (!isEligible2(actionCommand)) return;
@@ -23467,9 +24240,9 @@ function installDaemonReconcileHook(program3, cliVersion) {
23467
24240
  await reconcileManagedDaemon2({
23468
24241
  cliVersion,
23469
24242
  commandArguments: ["machine", "daemon"],
23470
- entrypointPath: (0, import_node_path11.resolve)(entrypointPath),
24243
+ entrypointPath: (0, import_node_path12.resolve)(entrypointPath),
23471
24244
  environment: {},
23472
- nodePath: (0, import_node_path11.resolve)(process.execPath),
24245
+ nodePath: (0, import_node_path12.resolve)(process.execPath),
23473
24246
  onActiveJobs: (count) => {
23474
24247
  process.stderr.write(
23475
24248
  `Warning: restarting the managed Connector will interrupt ${count} active ${count === 1 ? "Job" : "Jobs"}.
@@ -23511,9 +24284,9 @@ function commandPath3(command) {
23511
24284
  }
23512
24285
 
23513
24286
  // src/index.ts
23514
- var program2 = createProgram("0.8.1");
23515
- installDaemonReconcileHook(program2, "0.8.1");
23516
- installUpdateHook(program2, "0.8.1");
24287
+ var program2 = createProgram("0.9.0-beta.1");
24288
+ installDaemonReconcileHook(program2, "0.9.0-beta.1");
24289
+ installUpdateHook(program2, "0.9.0-beta.1");
23517
24290
  instrumentProgram(program2);
23518
24291
  installExitHandler();
23519
24292
  program2.parseAsync(process.argv).then(async () => {