@moxt-ai/cli 0.8.0 → 0.8.2

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
@@ -4575,8 +4575,32 @@ async function executeProcess(executable, argumentsList, workingDirectory, envir
4575
4575
  const cancellation = handle.waitForCancellation().then(() => ({
4576
4576
  kind: "cancellation_deadline"
4577
4577
  }));
4578
- const outcome = await Promise.race([completion, cancellation]);
4578
+ const semanticCompletion = callbacks.completion?.then((result) => ({
4579
+ kind: "semantic_completion",
4580
+ result
4581
+ }));
4582
+ const outcome = await Promise.race([
4583
+ completion,
4584
+ cancellation,
4585
+ ...semanticCompletion ? [semanticCompletion] : []
4586
+ ]);
4579
4587
  clearTimeout(timeout);
4588
+ if (outcome.kind === "semantic_completion") {
4589
+ await outputWrites;
4590
+ if (outcome.result.status !== MachineJobStatus.Succeeded) {
4591
+ await handle.cancel();
4592
+ return outcome.result;
4593
+ }
4594
+ child.stdout.removeAllListeners("data");
4595
+ child.stderr.removeAllListeners("data");
4596
+ child.stdout.resume();
4597
+ child.stderr.resume();
4598
+ child.unref();
4599
+ return {
4600
+ ...outcome.result,
4601
+ detachedProcessHandle: handle
4602
+ };
4603
+ }
4580
4604
  if (outcome.kind === "cancellation_deadline") {
4581
4605
  void outputWrites.catch(() => void 0);
4582
4606
  return timedOut ? {
@@ -4718,6 +4742,9 @@ var init_process_executor = __esm({
4718
4742
  wasCancelled() {
4719
4743
  return this.cancelled;
4720
4744
  }
4745
+ processGroupId() {
4746
+ return this.pid;
4747
+ }
4721
4748
  async cancel() {
4722
4749
  if (this.cancellation) {
4723
4750
  await this.cancellation;
@@ -4868,6 +4895,7 @@ async function executeCodexReply(workingDirectory, runtimeDirectory, spec, callb
4868
4895
  }
4869
4896
  async function executeCodex(workingDirectory, outputPath, argumentsList, prompt, callbacks) {
4870
4897
  const executionMetadata = {};
4898
+ const turnCompletion = createCodexTurnCompletion();
4871
4899
  let bufferedStdout = "";
4872
4900
  const processCallbacks = {
4873
4901
  canSpawn: callbacks.canSpawn,
@@ -4888,10 +4916,15 @@ async function executeCodex(workingDirectory, outputPath, argumentsList, prompt,
4888
4916
  if (eventThreadId) {
4889
4917
  executionMetadata.value = eventThreadId;
4890
4918
  }
4919
+ turnCompletion.observe(event);
4891
4920
  await callbacks.onEvent(event);
4892
4921
  }
4893
4922
  },
4894
- onSpawn: callbacks.onSpawn
4923
+ onSpawn: callbacks.onSpawn,
4924
+ completion: turnCompletion.result.then(async (result2) => {
4925
+ await delay2(codexProcessExitGraceMilliseconds);
4926
+ return result2;
4927
+ })
4895
4928
  };
4896
4929
  const result = await executeProcess(process.env.MOXT_CODEX_PATH ?? "codex", argumentsList, workingDirectory, {}, prompt, 43200, processCallbacks);
4897
4930
  if (bufferedStdout.trim().length > 0) {
@@ -4901,6 +4934,7 @@ async function executeCodex(workingDirectory, outputPath, argumentsList, prompt,
4901
4934
  if (eventThreadId) {
4902
4935
  executionMetadata.value = eventThreadId;
4903
4936
  }
4937
+ turnCompletion.observe(event);
4904
4938
  await callbacks.onEvent(event);
4905
4939
  }
4906
4940
  }
@@ -4912,6 +4946,64 @@ async function executeCodex(workingDirectory, outputPath, argumentsList, prompt,
4912
4946
  threadId: executionMetadata.value
4913
4947
  };
4914
4948
  }
4949
+ function createCodexTurnCompletion() {
4950
+ const activeCommandIds = /* @__PURE__ */ new Set();
4951
+ const completedCommandIds = /* @__PURE__ */ new Set();
4952
+ let terminal;
4953
+ let settled = false;
4954
+ let resolveResult;
4955
+ const result = new Promise((resolvePromise) => {
4956
+ resolveResult = resolvePromise;
4957
+ });
4958
+ const settleIfReady = () => {
4959
+ if (settled || terminal === void 0 || activeCommandIds.size > 0) {
4960
+ return;
4961
+ }
4962
+ settled = true;
4963
+ resolveResult({
4964
+ exitCode: terminal.status === MachineJobStatus.Succeeded ? 0 : -1,
4965
+ failureCode: terminal.status === MachineJobStatus.Failed ? "codex_turn_failed" : void 0,
4966
+ failureMessage: terminal.failureMessage,
4967
+ status: terminal.status
4968
+ });
4969
+ };
4970
+ return {
4971
+ observe: (event) => {
4972
+ if (!isRecord2(event)) {
4973
+ return;
4974
+ }
4975
+ const item = event.item;
4976
+ if (isRecord2(item) && item.type === "command_execution" && typeof item.id === "string") {
4977
+ if (event.type === "item.completed") {
4978
+ completedCommandIds.add(item.id);
4979
+ activeCommandIds.delete(item.id);
4980
+ } else if (event.type === "item.started" && !completedCommandIds.has(item.id)) {
4981
+ activeCommandIds.add(item.id);
4982
+ }
4983
+ }
4984
+ if (terminal === void 0 && event.type === "turn.completed") {
4985
+ terminal = { status: MachineJobStatus.Succeeded };
4986
+ }
4987
+ if (terminal === void 0 && event.type === "turn.failed") {
4988
+ terminal = {
4989
+ failureMessage: extractCodexFailureMessage(event).value,
4990
+ status: MachineJobStatus.Failed
4991
+ };
4992
+ }
4993
+ settleIfReady();
4994
+ },
4995
+ result
4996
+ };
4997
+ }
4998
+ function extractCodexFailureMessage(event) {
4999
+ if (typeof event.message === "string") {
5000
+ return { value: event.message };
5001
+ }
5002
+ if (isRecord2(event.error) && typeof event.error.message === "string") {
5003
+ return { value: event.error.message };
5004
+ }
5005
+ return {};
5006
+ }
4915
5007
  function createOutputPath(runtimeDirectory) {
4916
5008
  return (0, import_node_path3.join)(runtimeDirectory, `codex-last-message-${(0, import_node_crypto2.randomUUID)()}.txt`);
4917
5009
  }
@@ -4964,7 +5056,12 @@ function isNodeErrorCode(error, expectedCode) {
4964
5056
  }
4965
5057
  return error.code === expectedCode;
4966
5058
  }
4967
- var import_promises4, import_node_path3, import_node_crypto2;
5059
+ function delay2(milliseconds) {
5060
+ return new Promise((resolvePromise) => {
5061
+ setTimeout(resolvePromise, milliseconds);
5062
+ });
5063
+ }
5064
+ var import_promises4, import_node_path3, import_node_crypto2, codexProcessExitGraceMilliseconds;
4968
5065
  var init_codex_executor = __esm({
4969
5066
  "../machine-connector/dist/runtime/codex-executor.js"() {
4970
5067
  "use strict";
@@ -4974,6 +5071,7 @@ var init_codex_executor = __esm({
4974
5071
  import_node_crypto2 = require("crypto");
4975
5072
  init_enums();
4976
5073
  init_process_executor();
5074
+ codexProcessExitGraceMilliseconds = 250;
4977
5075
  }
4978
5076
  });
4979
5077
 
@@ -5161,6 +5259,13 @@ var init_execution_cancellation = __esm({
5161
5259
  void handle.cancel();
5162
5260
  }
5163
5261
  }
5262
+ release(handle) {
5263
+ if (this.reason !== void 0 || this.handle !== handle) {
5264
+ return false;
5265
+ }
5266
+ this.handle = void 0;
5267
+ return true;
5268
+ }
5164
5269
  async request(reason) {
5165
5270
  if (this.reason === void 0) {
5166
5271
  this.reason = reason;
@@ -5449,12 +5554,15 @@ var init_image_viewer = __esm({
5449
5554
  });
5450
5555
 
5451
5556
  // ../machine-connector/dist/runtime/local-ipc.js
5452
- async function requestRuntimeStatus(store) {
5557
+ async function requestRuntimeStatus(store, timeoutMilliseconds = 1e3) {
5453
5558
  return await new Promise((resolvePromise, rejectPromise) => {
5454
5559
  const socket = (0, import_node_net.createConnection)(store.runtimeSocketPath());
5455
5560
  let responseText = "";
5456
5561
  socket.setEncoding("utf8");
5457
5562
  socket.once("error", rejectPromise);
5563
+ socket.setTimeout(timeoutMilliseconds, () => {
5564
+ socket.destroy(new Error(`Runtime status timed out after ${timeoutMilliseconds}ms`));
5565
+ });
5458
5566
  socket.on("data", (chunk) => {
5459
5567
  responseText += chunk;
5460
5568
  });
@@ -5541,6 +5649,330 @@ var init_local_ipc = __esm({
5541
5649
  }
5542
5650
  });
5543
5651
 
5652
+ // ../machine-connector/dist/runtime/process-lock.js
5653
+ async function createCompleteLock(path4, record2) {
5654
+ await (0, import_promises7.mkdir)(path4, { mode: 448 });
5655
+ let metadata;
5656
+ try {
5657
+ metadata = await (0, import_promises7.stat)(path4);
5658
+ } catch (error) {
5659
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5660
+ throw nodeError("EEXIST", "Lock directory changed while publishing");
5661
+ }
5662
+ throw error;
5663
+ }
5664
+ const ownerPath = (0, import_node_path5.join)(path4, `${metadata.dev}.${metadata.ino}.${record2.pid}.${record2.token}.owner`);
5665
+ try {
5666
+ await (0, import_promises7.writeFile)(ownerPath, `${JSON.stringify(record2)}
5667
+ `, {
5668
+ encoding: "utf8",
5669
+ flag: "wx",
5670
+ mode: 384
5671
+ });
5672
+ let current2;
5673
+ try {
5674
+ current2 = await (0, import_promises7.stat)(path4);
5675
+ } catch (error) {
5676
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5677
+ throw nodeError("EEXIST", "Lock directory changed while publishing");
5678
+ }
5679
+ throw error;
5680
+ }
5681
+ if (!sameDirectoryIdentity(metadata, current2)) {
5682
+ throw nodeError("EEXIST", "Lock directory was replaced while publishing");
5683
+ }
5684
+ return ownerPath;
5685
+ } catch (error) {
5686
+ await removeFileIfPresent(ownerPath);
5687
+ await removeEmptyDirectory(path4);
5688
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5689
+ throw nodeError("EEXIST", "Lock directory changed while publishing");
5690
+ }
5691
+ throw error;
5692
+ }
5693
+ }
5694
+ async function readLockState(path4) {
5695
+ let metadata;
5696
+ try {
5697
+ metadata = await (0, import_promises7.stat)(path4);
5698
+ } catch (error) {
5699
+ if (isNodeErrorCode2(error, "ENOENT"))
5700
+ return void 0;
5701
+ throw error;
5702
+ }
5703
+ if (!metadata.isDirectory()) {
5704
+ return {
5705
+ metadata,
5706
+ record: await readRecord(path4)
5707
+ };
5708
+ }
5709
+ const ownerPrefix = `${metadata.dev}.${metadata.ino}.`;
5710
+ let names;
5711
+ try {
5712
+ names = await (0, import_promises7.readdir)(path4);
5713
+ } catch (error) {
5714
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5715
+ return void 0;
5716
+ }
5717
+ throw error;
5718
+ }
5719
+ const ownerName = names.find((name) => name.startsWith(ownerPrefix) && name.endsWith(".owner"));
5720
+ if (!ownerName)
5721
+ return { metadata };
5722
+ const ownerPath = (0, import_node_path5.join)(path4, ownerName);
5723
+ return {
5724
+ metadata,
5725
+ ownerPath,
5726
+ record: await readRecord(ownerPath)
5727
+ };
5728
+ }
5729
+ async function readRecord(path4) {
5730
+ try {
5731
+ const parsed = JSON.parse(await (0, import_promises7.readFile)(path4, "utf8"));
5732
+ 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) {
5733
+ return void 0;
5734
+ }
5735
+ return parsed;
5736
+ } catch (error) {
5737
+ if (isNodeErrorCode2(error, "ENOENT"))
5738
+ return void 0;
5739
+ if (error instanceof SyntaxError)
5740
+ return void 0;
5741
+ throw error;
5742
+ }
5743
+ }
5744
+ async function removeLockIfTokenMatches(path4, token) {
5745
+ const state = await readLockState(path4);
5746
+ if (state?.record?.token !== token)
5747
+ return;
5748
+ if (state.ownerPath) {
5749
+ await removeOwnedDirectoryLock(path4, state.ownerPath, token);
5750
+ return;
5751
+ }
5752
+ try {
5753
+ await (0, import_promises7.rm)(path4);
5754
+ } catch (error) {
5755
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "EISDIR") || isNodeErrorCode2(error, "ERR_FS_EISDIR") || isNodeErrorCode2(error, "EPERM")) {
5756
+ return;
5757
+ }
5758
+ throw error;
5759
+ }
5760
+ }
5761
+ async function removeOwnedDirectoryLock(path4, ownerPath, token) {
5762
+ if ((await readRecord(ownerPath))?.token !== token)
5763
+ return;
5764
+ await removeFileIfPresent(ownerPath);
5765
+ await removeEmptyDirectory(path4);
5766
+ }
5767
+ async function removeStaleIncompleteLock(path4, metadata) {
5768
+ if (Date.now() - Number(metadata.mtimeMs) < incompleteLockStaleMilliseconds) {
5769
+ return false;
5770
+ }
5771
+ const current2 = await readLockState(path4);
5772
+ if (!current2 || current2.record || !sameFileMetadata(metadata, current2.metadata)) {
5773
+ return false;
5774
+ }
5775
+ if (!metadata.isDirectory()) {
5776
+ try {
5777
+ await (0, import_promises7.rm)(path4);
5778
+ return true;
5779
+ } catch (error) {
5780
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "EISDIR") || isNodeErrorCode2(error, "ERR_FS_EISDIR") || isNodeErrorCode2(error, "EPERM")) {
5781
+ return false;
5782
+ }
5783
+ throw error;
5784
+ }
5785
+ }
5786
+ const ownerPrefix = `${metadata.dev}.${metadata.ino}.`;
5787
+ let names;
5788
+ try {
5789
+ names = await (0, import_promises7.readdir)(path4);
5790
+ } catch (error) {
5791
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5792
+ return false;
5793
+ }
5794
+ throw error;
5795
+ }
5796
+ const ownerNames = names.filter((name) => name.startsWith(ownerPrefix) && name.endsWith(".owner"));
5797
+ const deadOwnerNames = [];
5798
+ for (const name of ownerNames) {
5799
+ const ownerProcessId = directoryOwnerProcessId(ownerPrefix, name);
5800
+ if (ownerProcessId === void 0 || processIsAlive(ownerProcessId)) {
5801
+ return false;
5802
+ }
5803
+ deadOwnerNames.push(name);
5804
+ }
5805
+ for (const name of deadOwnerNames) {
5806
+ await removeFileIfPresent((0, import_node_path5.join)(path4, name));
5807
+ }
5808
+ return await removeEmptyDirectory(path4);
5809
+ }
5810
+ function directoryOwnerProcessId(ownerPrefix, ownerName) {
5811
+ const identity = ownerName.slice(ownerPrefix.length, -".owner".length);
5812
+ const separator = identity.indexOf(".");
5813
+ if (separator <= 0)
5814
+ return void 0;
5815
+ const processId = Number(identity.slice(0, separator));
5816
+ const token = identity.slice(separator + 1);
5817
+ 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)) {
5818
+ return void 0;
5819
+ }
5820
+ return processId;
5821
+ }
5822
+ async function removeStalePendingLockCandidates(path4) {
5823
+ const directory = (0, import_node_path5.dirname)(path4);
5824
+ const lockName = (0, import_node_path5.basename)(path4);
5825
+ let names;
5826
+ try {
5827
+ names = await (0, import_promises7.readdir)(directory);
5828
+ } catch (error) {
5829
+ if (isNodeErrorCode2(error, "ENOENT"))
5830
+ return;
5831
+ throw error;
5832
+ }
5833
+ for (const name of names) {
5834
+ if (!isPendingLockCandidateName(lockName, name))
5835
+ continue;
5836
+ await removeOldUnchangedFile((0, import_node_path5.join)(directory, name));
5837
+ }
5838
+ }
5839
+ function isPendingLockCandidateName(lockName, name) {
5840
+ const prefix = `${lockName}.`;
5841
+ const suffix = ".pending";
5842
+ if (!name.startsWith(prefix) || !name.endsWith(suffix))
5843
+ return false;
5844
+ const identity = name.slice(prefix.length, -suffix.length);
5845
+ const separator = identity.indexOf(".");
5846
+ if (separator <= 0 || identity.indexOf(".", separator + 1) >= 0) {
5847
+ return false;
5848
+ }
5849
+ const processId = Number(identity.slice(0, separator));
5850
+ const token = identity.slice(separator + 1);
5851
+ return 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);
5852
+ }
5853
+ async function removeOldUnchangedFile(path4) {
5854
+ let metadata;
5855
+ try {
5856
+ metadata = await (0, import_promises7.stat)(path4);
5857
+ } catch (error) {
5858
+ return isNodeErrorCode2(error, "ENOENT");
5859
+ }
5860
+ if (Date.now() - Number(metadata.mtimeMs) < incompleteLockStaleMilliseconds) {
5861
+ return false;
5862
+ }
5863
+ let current2;
5864
+ try {
5865
+ current2 = await (0, import_promises7.stat)(path4);
5866
+ } catch (error) {
5867
+ return isNodeErrorCode2(error, "ENOENT");
5868
+ }
5869
+ if (!sameFileMetadata(metadata, current2))
5870
+ return false;
5871
+ await (0, import_promises7.rm)(path4, { force: true });
5872
+ return true;
5873
+ }
5874
+ async function removeEmptyDirectory(path4) {
5875
+ try {
5876
+ await (0, import_promises7.rmdir)(path4);
5877
+ return true;
5878
+ } catch (error) {
5879
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTEMPTY") || isNodeErrorCode2(error, "EEXIST") || isNodeErrorCode2(error, "ENOTDIR")) {
5880
+ return false;
5881
+ }
5882
+ throw error;
5883
+ }
5884
+ }
5885
+ async function removeFileIfPresent(path4) {
5886
+ try {
5887
+ await (0, import_promises7.rm)(path4, { force: true });
5888
+ } catch (error) {
5889
+ if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5890
+ return;
5891
+ }
5892
+ throw error;
5893
+ }
5894
+ }
5895
+ function sameDirectoryIdentity(first, second) {
5896
+ return first.isDirectory() && second.isDirectory() && first.dev === second.dev && first.ino === second.ino;
5897
+ }
5898
+ function sameFileMetadata(first, second) {
5899
+ return first.dev === second.dev && first.ino === second.ino && first.mtimeMs === second.mtimeMs && first.size === second.size;
5900
+ }
5901
+ function processIsAlive(pid) {
5902
+ try {
5903
+ process.kill(pid, 0);
5904
+ return true;
5905
+ } catch (error) {
5906
+ return !isNodeErrorCode2(error, "ESRCH");
5907
+ }
5908
+ }
5909
+ function isNodeErrorCode2(error, expectedCode) {
5910
+ return error instanceof Error && "code" in error && error.code === expectedCode;
5911
+ }
5912
+ function nodeError(code, message) {
5913
+ return Object.assign(new Error(message), { code });
5914
+ }
5915
+ function delay3(milliseconds) {
5916
+ return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
5917
+ }
5918
+ var import_node_crypto4, import_promises7, import_node_path5, incompleteLockStaleMilliseconds, ProcessLock;
5919
+ var init_process_lock = __esm({
5920
+ "../machine-connector/dist/runtime/process-lock.js"() {
5921
+ "use strict";
5922
+ init_cjs_shims();
5923
+ import_node_crypto4 = require("crypto");
5924
+ import_promises7 = require("fs/promises");
5925
+ import_node_path5 = require("path");
5926
+ incompleteLockStaleMilliseconds = 3e4;
5927
+ ProcessLock = class _ProcessLock {
5928
+ path;
5929
+ ownerPath;
5930
+ token;
5931
+ released = false;
5932
+ constructor(path4, ownerPath, token) {
5933
+ this.path = path4;
5934
+ this.ownerPath = ownerPath;
5935
+ this.token = token;
5936
+ }
5937
+ static async acquire(path4, options) {
5938
+ await removeStalePendingLockCandidates(path4);
5939
+ const deadline = Date.now() + options.timeoutMilliseconds;
5940
+ const token = (0, import_node_crypto4.randomUUID)();
5941
+ while (true) {
5942
+ try {
5943
+ const ownerPath = await createCompleteLock(path4, {
5944
+ createdAt: Date.now(),
5945
+ pid: process.pid,
5946
+ token
5947
+ });
5948
+ return new _ProcessLock(path4, ownerPath, token);
5949
+ } catch (error) {
5950
+ if (!isNodeErrorCode2(error, "EEXIST"))
5951
+ throw error;
5952
+ }
5953
+ const existing = await readLockState(path4);
5954
+ if (existing?.record && !processIsAlive(existing.record.pid)) {
5955
+ await removeLockIfTokenMatches(path4, existing.record.token);
5956
+ continue;
5957
+ }
5958
+ if (existing && !existing.record && await removeStaleIncompleteLock(path4, existing.metadata)) {
5959
+ continue;
5960
+ }
5961
+ if (Date.now() >= deadline)
5962
+ return void 0;
5963
+ await delay3(Math.min(50, Math.max(1, deadline - Date.now())));
5964
+ }
5965
+ }
5966
+ async release() {
5967
+ if (this.released)
5968
+ return;
5969
+ this.released = true;
5970
+ await removeOwnedDirectoryLock(this.path, this.ownerPath, this.token);
5971
+ }
5972
+ };
5973
+ }
5974
+ });
5975
+
5544
5976
  // ../machine-connector/dist/runtime/version.js
5545
5977
  var connectorVersion;
5546
5978
  var init_version = __esm({
@@ -5728,12 +6160,12 @@ var init_relay_client = __esm({
5728
6160
  });
5729
6161
 
5730
6162
  // ../machine-connector/dist/runtime/runtime-logger.js
5731
- var import_promises7, RuntimeLogger;
6163
+ var import_promises8, RuntimeLogger;
5732
6164
  var init_runtime_logger = __esm({
5733
6165
  "../machine-connector/dist/runtime/runtime-logger.js"() {
5734
6166
  "use strict";
5735
6167
  init_cjs_shims();
5736
- import_promises7 = require("fs/promises");
6168
+ import_promises8 = require("fs/promises");
5737
6169
  RuntimeLogger = class {
5738
6170
  store;
5739
6171
  constructor(store) {
@@ -5747,7 +6179,7 @@ var init_runtime_logger = __esm({
5747
6179
  await this.write("error", message, metadata, this.store.runtimeErrorLogPath());
5748
6180
  }
5749
6181
  async write(level, message, metadata, path4) {
5750
- await (0, import_promises7.appendFile)(path4, `${JSON.stringify({
6182
+ await (0, import_promises8.appendFile)(path4, `${JSON.stringify({
5751
6183
  level,
5752
6184
  message,
5753
6185
  metadata,
@@ -5768,26 +6200,27 @@ function defaultRuntimeDirectory() {
5768
6200
  if (override) {
5769
6201
  return override;
5770
6202
  }
6203
+ const homeDirectory = process.env.HOME ?? (0, import_node_os3.homedir)();
5771
6204
  if ((0, import_node_os3.platform)() === "darwin") {
5772
- return (0, import_node_path5.join)((0, import_node_os3.homedir)(), "Library", "Application Support", "Moxt", "Machine Connector");
6205
+ return (0, import_node_path6.join)(homeDirectory, "Library", "Application Support", "Moxt", "Machine Connector");
5773
6206
  }
5774
- const stateHome = process.env.XDG_STATE_HOME ?? (0, import_node_path5.join)((0, import_node_os3.homedir)(), ".local", "state");
5775
- return (0, import_node_path5.join)(stateHome, "moxt", "machine-connector");
6207
+ const stateHome = process.env.XDG_STATE_HOME ?? (0, import_node_path6.join)(homeDirectory, ".local", "state");
6208
+ return (0, import_node_path6.join)(stateHome, "moxt", "machine-connector");
5776
6209
  }
5777
- function isNodeErrorCode2(error, expectedCode) {
6210
+ function isNodeErrorCode3(error, expectedCode) {
5778
6211
  if (!(error instanceof Error) || !("code" in error)) {
5779
6212
  return false;
5780
6213
  }
5781
6214
  return error.code === expectedCode;
5782
6215
  }
5783
- var import_promises8, import_node_os3, import_node_path5, privateFileMode, privateDirectoryMode, MachineRuntimeStore;
6216
+ var import_promises9, import_node_os3, import_node_path6, privateFileMode, privateDirectoryMode, MachineRuntimeStore;
5784
6217
  var init_store = __esm({
5785
6218
  "../machine-connector/dist/runtime/store.js"() {
5786
6219
  "use strict";
5787
6220
  init_cjs_shims();
5788
- import_promises8 = require("fs/promises");
6221
+ import_promises9 = require("fs/promises");
5789
6222
  import_node_os3 = require("os");
5790
- import_node_path5 = require("path");
6223
+ import_node_path6 = require("path");
5791
6224
  privateFileMode = 384;
5792
6225
  privateDirectoryMode = 448;
5793
6226
  MachineRuntimeStore = class {
@@ -5796,15 +6229,20 @@ var init_store = __esm({
5796
6229
  this.baseDirectory = baseDirectory;
5797
6230
  }
5798
6231
  async initialize() {
5799
- await (0, import_promises8.mkdir)(this.jobsDirectory(), {
6232
+ await (0, import_promises9.mkdir)(this.jobsDirectory(), {
5800
6233
  mode: privateDirectoryMode,
5801
6234
  recursive: true
5802
6235
  });
5803
- await (0, import_promises8.chmod)(this.baseDirectory, privateDirectoryMode);
5804
- await (0, import_promises8.chmod)(this.jobsDirectory(), privateDirectoryMode);
6236
+ await (0, import_promises9.mkdir)(this.detachedProcessesDirectory(), {
6237
+ mode: privateDirectoryMode,
6238
+ recursive: true
6239
+ });
6240
+ await (0, import_promises9.chmod)(this.baseDirectory, privateDirectoryMode);
6241
+ await (0, import_promises9.chmod)(this.jobsDirectory(), privateDirectoryMode);
6242
+ await (0, import_promises9.chmod)(this.detachedProcessesDirectory(), privateDirectoryMode);
5805
6243
  }
5806
6244
  async getCanonicalRoot(rootPath) {
5807
- return await (0, import_promises8.realpath)(rootPath);
6245
+ return await (0, import_promises9.realpath)(rootPath);
5808
6246
  }
5809
6247
  async readIdentity() {
5810
6248
  return await this.readOptionalJson(this.identityPath());
@@ -5847,7 +6285,7 @@ var init_store = __esm({
5847
6285
  await this.writePrivateJson(this.serviceManagerPath(), serviceManager);
5848
6286
  }
5849
6287
  async removeServiceManager() {
5850
- await (0, import_promises8.rm)(this.serviceManagerPath(), { force: true });
6288
+ await (0, import_promises9.rm)(this.serviceManagerPath(), { force: true });
5851
6289
  }
5852
6290
  async readJob(jobId) {
5853
6291
  return await this.readOptionalJson(this.jobPath(jobId));
@@ -5858,16 +6296,16 @@ var init_store = __esm({
5858
6296
  async listJobs() {
5859
6297
  let names = [];
5860
6298
  try {
5861
- names = await (0, import_promises8.readdir)(this.jobsDirectory());
6299
+ names = await (0, import_promises9.readdir)(this.jobsDirectory());
5862
6300
  } catch (error) {
5863
- if (isNodeErrorCode2(error, "ENOENT")) {
6301
+ if (isNodeErrorCode3(error, "ENOENT")) {
5864
6302
  return [];
5865
6303
  }
5866
6304
  throw error;
5867
6305
  }
5868
6306
  const jobs = [];
5869
6307
  for (const name of names.filter((entry) => entry.endsWith(".json"))) {
5870
- const job = await this.readOptionalJson((0, import_node_path5.join)(this.jobsDirectory(), name));
6308
+ const job = await this.readOptionalJson((0, import_node_path6.join)(this.jobsDirectory(), name));
5871
6309
  if (job.value) {
5872
6310
  jobs.push(job.value);
5873
6311
  }
@@ -5875,40 +6313,77 @@ var init_store = __esm({
5875
6313
  return jobs;
5876
6314
  }
5877
6315
  async deleteJob(jobId) {
5878
- await (0, import_promises8.rm)(this.jobPath(jobId), { force: true });
6316
+ await (0, import_promises9.rm)(this.jobPath(jobId), { force: true });
6317
+ }
6318
+ async writeDetachedProcess(resource) {
6319
+ await this.writePrivateJson(this.detachedProcessPath(resource.jobId), resource);
6320
+ }
6321
+ async listDetachedProcesses() {
6322
+ let names = [];
6323
+ try {
6324
+ names = await (0, import_promises9.readdir)(this.detachedProcessesDirectory());
6325
+ } catch (error) {
6326
+ if (isNodeErrorCode3(error, "ENOENT")) {
6327
+ return [];
6328
+ }
6329
+ throw error;
6330
+ }
6331
+ const resources = [];
6332
+ for (const name of names.filter((entry) => entry.endsWith(".json"))) {
6333
+ const resource = await this.readOptionalJson((0, import_node_path6.join)(this.detachedProcessesDirectory(), name));
6334
+ if (resource.value) {
6335
+ resources.push(resource.value);
6336
+ }
6337
+ }
6338
+ return resources;
6339
+ }
6340
+ async deleteDetachedProcess(jobId) {
6341
+ await (0, import_promises9.rm)(this.detachedProcessPath(jobId), { force: true });
5879
6342
  }
5880
6343
  runtimeLogPath() {
5881
- return (0, import_node_path5.join)(this.baseDirectory, "machine-connector.log");
6344
+ return (0, import_node_path6.join)(this.baseDirectory, "machine-connector.log");
5882
6345
  }
5883
6346
  runtimeErrorLogPath() {
5884
- return (0, import_node_path5.join)(this.baseDirectory, "machine-connector.error.log");
6347
+ return (0, import_node_path6.join)(this.baseDirectory, "machine-connector.error.log");
5885
6348
  }
5886
6349
  runtimeStatusPath() {
5887
- return (0, import_node_path5.join)(this.baseDirectory, "runtime-status.json");
6350
+ return (0, import_node_path6.join)(this.baseDirectory, "runtime-status.json");
5888
6351
  }
5889
6352
  runtimeSocketPath() {
5890
6353
  if ((0, import_node_os3.platform)() === "win32") {
5891
6354
  return String.raw`\\.\pipe\moxt-machine-connector`;
5892
6355
  }
5893
- return (0, import_node_path5.join)(this.baseDirectory, "machine-connector.sock");
6356
+ return (0, import_node_path6.join)(this.baseDirectory, "machine-connector.sock");
6357
+ }
6358
+ daemonLockPath() {
6359
+ return (0, import_node_path6.join)(this.baseDirectory, "daemon.lock");
6360
+ }
6361
+ reconcileLockPath() {
6362
+ return (0, import_node_path6.join)(this.baseDirectory, "daemon-reconcile.lock");
5894
6363
  }
5895
6364
  connectionsPath() {
5896
- return (0, import_node_path5.join)(this.baseDirectory, "connections.json");
6365
+ return (0, import_node_path6.join)(this.baseDirectory, "connections.json");
6366
+ }
6367
+ detachedProcessesDirectory() {
6368
+ return (0, import_node_path6.join)(this.baseDirectory, "detached-processes");
6369
+ }
6370
+ detachedProcessPath(jobId) {
6371
+ return (0, import_node_path6.join)(this.detachedProcessesDirectory(), `${jobId}.json`);
5897
6372
  }
5898
6373
  identityPath() {
5899
- return (0, import_node_path5.join)(this.baseDirectory, "identity.json");
6374
+ return (0, import_node_path6.join)(this.baseDirectory, "identity.json");
5900
6375
  }
5901
6376
  serviceManagerPath() {
5902
- return (0, import_node_path5.join)(this.baseDirectory, "service-manager.json");
6377
+ return (0, import_node_path6.join)(this.baseDirectory, "service-manager.json");
5903
6378
  }
5904
6379
  privateKeyPath() {
5905
- return (0, import_node_path5.join)(this.baseDirectory, "device-private-key.pem");
6380
+ return (0, import_node_path6.join)(this.baseDirectory, "device-private-key.pem");
5906
6381
  }
5907
6382
  jobsDirectory() {
5908
- return (0, import_node_path5.join)(this.baseDirectory, "jobs");
6383
+ return (0, import_node_path6.join)(this.baseDirectory, "jobs");
5909
6384
  }
5910
6385
  jobPath(jobId) {
5911
- return (0, import_node_path5.join)(this.jobsDirectory(), `${jobId}.json`);
6386
+ return (0, import_node_path6.join)(this.jobsDirectory(), `${jobId}.json`);
5912
6387
  }
5913
6388
  async readOptionalJson(path4) {
5914
6389
  const content3 = await this.readOptionalText(path4);
@@ -5919,9 +6394,9 @@ var init_store = __esm({
5919
6394
  }
5920
6395
  async readOptionalText(path4) {
5921
6396
  try {
5922
- return { value: await (0, import_promises8.readFile)(path4, "utf8") };
6397
+ return { value: await (0, import_promises9.readFile)(path4, "utf8") };
5923
6398
  } catch (error) {
5924
- if (isNodeErrorCode2(error, "ENOENT")) {
6399
+ if (isNodeErrorCode3(error, "ENOENT")) {
5925
6400
  return {};
5926
6401
  }
5927
6402
  throw error;
@@ -5932,17 +6407,17 @@ var init_store = __esm({
5932
6407
  `);
5933
6408
  }
5934
6409
  async writePrivateText(path4, value) {
5935
- await (0, import_promises8.mkdir)((0, import_node_path5.dirname)(path4), {
6410
+ await (0, import_promises9.mkdir)((0, import_node_path6.dirname)(path4), {
5936
6411
  mode: privateDirectoryMode,
5937
6412
  recursive: true
5938
6413
  });
5939
6414
  const temporaryPath = `${path4}.${process.pid}.tmp`;
5940
- await (0, import_promises8.writeFile)(temporaryPath, value, {
6415
+ await (0, import_promises9.writeFile)(temporaryPath, value, {
5941
6416
  encoding: "utf8",
5942
6417
  mode: privateFileMode
5943
6418
  });
5944
- await (0, import_promises8.chmod)(temporaryPath, privateFileMode);
5945
- await (0, import_promises8.rename)(temporaryPath, path4);
6419
+ await (0, import_promises9.chmod)(temporaryPath, privateFileMode);
6420
+ await (0, import_promises9.rename)(temporaryPath, path4);
5946
6421
  }
5947
6422
  };
5948
6423
  }
@@ -5962,23 +6437,23 @@ async function withDeadline(operation, deadline) {
5962
6437
  }
5963
6438
  return await Promise.race([
5964
6439
  operation,
5965
- delay2(remaining).then(() => {
6440
+ delay4(remaining).then(() => {
5966
6441
  throw new Error("Operation exceeded its foreground deadline");
5967
6442
  })
5968
6443
  ]);
5969
6444
  }
5970
- function delay2(milliseconds) {
6445
+ function delay4(milliseconds) {
5971
6446
  return new Promise((resolvePromise) => {
5972
6447
  setTimeout(resolvePromise, milliseconds);
5973
6448
  });
5974
6449
  }
5975
- var import_node_os4, import_node_crypto4, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
6450
+ var import_node_os4, import_node_crypto5, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
5976
6451
  var init_daemon = __esm({
5977
6452
  "../machine-connector/dist/runtime/daemon.js"() {
5978
6453
  "use strict";
5979
6454
  init_cjs_shims();
5980
6455
  import_node_os4 = require("os");
5981
- import_node_crypto4 = require("crypto");
6456
+ import_node_crypto5 = require("crypto");
5982
6457
  init_enums();
5983
6458
  init_contracts();
5984
6459
  init_claude_executor();
@@ -5987,6 +6462,7 @@ var init_daemon = __esm({
5987
6462
  init_execution_cancellation();
5988
6463
  init_image_viewer();
5989
6464
  init_local_ipc();
6465
+ init_process_lock();
5990
6466
  init_process_executor();
5991
6467
  init_relay_client();
5992
6468
  init_runtime_logger();
@@ -6015,22 +6491,35 @@ var init_daemon = __esm({
6015
6491
  MachineConnectorDaemon = class {
6016
6492
  store;
6017
6493
  activeJobs = /* @__PURE__ */ new Map();
6018
- connectorInstanceId = (0, import_node_crypto4.randomUUID)();
6494
+ connectorInstanceId = (0, import_node_crypto5.randomUUID)();
6019
6495
  executionTasks = /* @__PURE__ */ new Set();
6020
6496
  logger;
6021
6497
  relayClients = /* @__PURE__ */ new Map();
6022
6498
  startedAt = (/* @__PURE__ */ new Date()).toISOString();
6023
6499
  connections = [];
6500
+ daemonLock;
6024
6501
  ipcServer;
6502
+ lifetimeSettled;
6503
+ settleLifetime;
6504
+ startupSettled;
6505
+ settleStartup;
6025
6506
  stopping = false;
6026
6507
  leaseSafetyMarginMilliseconds;
6027
6508
  leaseSeconds;
6028
6509
  networkRetryMilliseconds;
6029
6510
  random;
6030
6511
  terminalForegroundBudgetMilliseconds;
6512
+ cliVersion;
6031
6513
  constructor(store = new MachineRuntimeStore(), options = {}) {
6032
6514
  this.store = store;
6515
+ this.lifetimeSettled = new Promise((resolvePromise) => {
6516
+ this.settleLifetime = resolvePromise;
6517
+ });
6518
+ this.startupSettled = new Promise((resolvePromise) => {
6519
+ this.settleStartup = resolvePromise;
6520
+ });
6033
6521
  this.logger = new RuntimeLogger(store);
6522
+ this.cliVersion = options.cliVersion;
6034
6523
  this.leaseSafetyMarginMilliseconds = options.leaseSafetyMarginMilliseconds ?? defaultLeaseSafetyMarginMilliseconds;
6035
6524
  this.leaseSeconds = options.leaseSeconds ?? defaultLeaseSeconds;
6036
6525
  this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds;
@@ -6038,34 +6527,67 @@ var init_daemon = __esm({
6038
6527
  this.terminalForegroundBudgetMilliseconds = options.terminalForegroundBudgetMilliseconds ?? defaultTerminalForegroundBudgetMilliseconds;
6039
6528
  }
6040
6529
  async start() {
6041
- if (process.getuid?.() === 0) {
6042
- throw new Error("Moxt Machine Connector must run as an unprivileged user");
6043
- }
6044
- await this.store.initialize();
6045
- await this.recoverInterruptedJobs();
6046
- this.ipcServer = new LocalIpcServer(this.store, () => this.getStatus());
6047
- await this.ipcServer.start();
6048
- await this.logger.info("Moxt Machine Connector started", {
6049
- connectorInstanceId: this.connectorInstanceId,
6050
- hostname: (0, import_node_os4.hostname)(),
6051
- version: connectorVersion
6052
- });
6053
- this.connections = await this.store.listConnections();
6054
- if (this.connections.length === 0) {
6055
- await this.logger.info("No Local Machine connections are configured");
6530
+ try {
6531
+ if (process.getuid?.() === 0) {
6532
+ throw new Error("Moxt Machine Connector must run as an unprivileged user");
6533
+ }
6534
+ await this.store.initialize();
6535
+ this.throwIfStopping();
6536
+ this.daemonLock = await ProcessLock.acquire(this.store.daemonLockPath(), { timeoutMilliseconds: 1e3 });
6537
+ if (!this.daemonLock) {
6538
+ throw new Error("Another Moxt Machine Connector daemon is already running or starting");
6539
+ }
6540
+ this.throwIfStopping();
6541
+ await this.recoverInterruptedJobs();
6542
+ this.throwIfStopping();
6543
+ this.ipcServer = new LocalIpcServer(this.store, () => this.getStatus());
6544
+ await this.ipcServer.start();
6545
+ this.throwIfStopping();
6546
+ await this.logger.info("Moxt Machine Connector started", {
6547
+ connectorInstanceId: this.connectorInstanceId,
6548
+ hostname: (0, import_node_os4.hostname)(),
6549
+ version: connectorVersion
6550
+ });
6551
+ this.connections = await this.store.listConnections();
6552
+ this.throwIfStopping();
6553
+ if (this.connections.length === 0) {
6554
+ await this.logger.info("No Local Machine connections are configured");
6555
+ }
6556
+ this.settleStartup();
6557
+ await Promise.all(this.connections.map(async (connection) => {
6558
+ await this.runConnection(connection);
6559
+ }));
6560
+ await this.waitForExecutionTasks();
6561
+ } catch (error) {
6562
+ try {
6563
+ await this.ipcServer?.close();
6564
+ } finally {
6565
+ this.ipcServer = void 0;
6566
+ try {
6567
+ await this.releaseDaemonLock();
6568
+ } finally {
6569
+ this.settleStartup();
6570
+ }
6571
+ }
6572
+ throw error;
6573
+ } finally {
6574
+ this.settleLifetime();
6056
6575
  }
6057
- await Promise.all(this.connections.map(async (connection) => {
6058
- await this.runConnection(connection);
6059
- }));
6060
- await this.waitForExecutionTasks();
6061
6576
  }
6062
6577
  async stop() {
6063
6578
  this.stopping = true;
6064
6579
  await Promise.all([...this.activeJobs.values()].map(async (activeJob) => {
6065
6580
  await activeJob.cancellation.request(ExecutionCancellationReason.Stopping);
6066
6581
  }));
6582
+ await this.startupSettled;
6067
6583
  await this.ipcServer?.close();
6068
- await this.logger.info("Moxt Machine Connector stopped");
6584
+ this.ipcServer = void 0;
6585
+ await this.lifetimeSettled;
6586
+ try {
6587
+ await this.logger.info("Moxt Machine Connector stopped");
6588
+ } finally {
6589
+ await this.releaseDaemonLock();
6590
+ }
6069
6591
  }
6070
6592
  getStatus() {
6071
6593
  return {
@@ -6078,6 +6600,7 @@ var init_daemon = __esm({
6078
6600
  relativeWorkingDirectory: activeJob.claim.relativeWorkingDirectory
6079
6601
  };
6080
6602
  }),
6603
+ ...this.cliVersion ? { cliVersion: this.cliVersion } : {},
6081
6604
  connections: this.connections.map((connection) => ({
6082
6605
  connectionId: connection.connectionId,
6083
6606
  machineName: connection.machineName,
@@ -6245,6 +6768,36 @@ var init_daemon = __esm({
6245
6768
  activeJob.cancellation.wait().then(() => this.cancellationResult(activeJob))
6246
6769
  ]);
6247
6770
  void execution.catch(() => void 0);
6771
+ const detachedProcessHandle = "detachedProcessHandle" in executionResult ? executionResult.detachedProcessHandle : void 0;
6772
+ if (detachedProcessHandle) {
6773
+ let resourceRecorded = false;
6774
+ try {
6775
+ await this.store.writeDetachedProcess({
6776
+ connectionId: activeJob.connection.connectionId,
6777
+ jobId: claim.jobId,
6778
+ processGroupId: detachedProcessHandle.processGroupId(),
6779
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString(),
6780
+ relativeWorkingDirectory: claim.relativeWorkingDirectory
6781
+ });
6782
+ resourceRecorded = true;
6783
+ } catch (error) {
6784
+ await this.logger.error(`Failed to record detached process for Job ${claim.jobId}`, error);
6785
+ }
6786
+ if (!activeJob.cancellation.release(detachedProcessHandle)) {
6787
+ if (resourceRecorded) {
6788
+ try {
6789
+ await this.store.deleteDetachedProcess(claim.jobId);
6790
+ } catch (error) {
6791
+ await this.logger.error(`Failed to remove detached process record for cancelled Job ${claim.jobId}`, error);
6792
+ }
6793
+ }
6794
+ await detachedProcessHandle.cancel();
6795
+ await durableJob.markTerminal(this.cancellationResult(activeJob));
6796
+ await this.finishTerminalUpload(activeJob);
6797
+ await Promise.all([uploadLoop, leaseLoop]);
6798
+ return;
6799
+ }
6800
+ }
6248
6801
  await durableJob.markTerminal(executionResult);
6249
6802
  await this.finishTerminalUpload(activeJob);
6250
6803
  await Promise.all([uploadLoop, leaseLoop]);
@@ -6602,7 +7155,7 @@ var init_daemon = __esm({
6602
7155
  async waitUntilStop(milliseconds) {
6603
7156
  const deadline = Date.now() + milliseconds;
6604
7157
  while (!this.stopping && Date.now() < deadline) {
6605
- await delay2(Math.min(250, deadline - Date.now()));
7158
+ await delay4(Math.min(250, deadline - Date.now()));
6606
7159
  }
6607
7160
  }
6608
7161
  cancellationResult(activeJob) {
@@ -6626,6 +7179,15 @@ var init_daemon = __esm({
6626
7179
  }
6627
7180
  return activeJob.durableJob;
6628
7181
  }
7182
+ async releaseDaemonLock() {
7183
+ await this.daemonLock?.release();
7184
+ this.daemonLock = void 0;
7185
+ }
7186
+ throwIfStopping() {
7187
+ if (this.stopping) {
7188
+ throw new Error("Moxt Machine Connector stopped during startup");
7189
+ }
7190
+ }
6629
7191
  async recoverInterruptedJobs() {
6630
7192
  const jobs = await this.store.listJobs();
6631
7193
  for (const job of jobs) {
@@ -6665,1659 +7227,1961 @@ var init_daemon = __esm({
6665
7227
  }
6666
7228
  });
6667
7229
 
6668
- // ../machine-connector/dist/runtime/doctor.js
6669
- async function runMachineDoctor(store) {
6670
- const checks = [];
6671
- const connections = await store.listConnections();
6672
- checks.push({
6673
- detail: `${connections.length} configured connection(s)`,
6674
- name: "configuration",
6675
- status: connections.length > 0 ? DoctorCheckStatus.Passed : DoctorCheckStatus.Warning
6676
- });
6677
- try {
6678
- const response = await requestRuntimeStatus(store);
6679
- checks.push({
6680
- detail: response.error ?? `PID ${response.status?.pid ?? "unknown"}`,
6681
- name: "daemon",
6682
- status: response.error ? DoctorCheckStatus.Failed : DoctorCheckStatus.Passed
6683
- });
6684
- } catch (error) {
6685
- checks.push({
6686
- detail: errorMessage(error),
6687
- name: "daemon",
6688
- status: DoctorCheckStatus.Failed
6689
- });
7230
+ // ../machine-connector/dist/runtime/service-manager.js
7231
+ function parseServiceManagerPreference(value) {
7232
+ if (value === ServiceManagerPreference.Auto) {
7233
+ return ServiceManagerPreference.Auto;
6690
7234
  }
6691
- for (const connection of connections) {
6692
- try {
6693
- await (0, import_promises9.access)(connection.rootPath, import_node_fs.constants.R_OK | import_node_fs.constants.X_OK);
6694
- checks.push({
6695
- detail: connection.rootPath,
6696
- name: `root:${connection.connectionId}`,
6697
- status: DoctorCheckStatus.Passed
6698
- });
6699
- } catch (error) {
6700
- checks.push({
6701
- detail: errorMessage(error),
6702
- name: `root:${connection.connectionId}`,
6703
- status: DoctorCheckStatus.Failed
6704
- });
6705
- }
6706
- const relayUrl = new URL(connection.relayOrigin);
6707
- try {
6708
- const address = await (0, import_promises10.lookup)(relayUrl.hostname);
6709
- checks.push({
6710
- detail: `${relayUrl.hostname} resolves to ${address.address}`,
6711
- name: `dns:${connection.connectionId}`,
6712
- status: DoctorCheckStatus.Passed
6713
- });
6714
- } catch (error) {
6715
- checks.push({
6716
- detail: errorMessage(error),
6717
- name: `dns:${connection.connectionId}`,
6718
- status: DoctorCheckStatus.Failed
6719
- });
6720
- }
6721
- try {
6722
- const response = await fetch(connection.relayOrigin, {
6723
- method: "HEAD",
6724
- signal: AbortSignal.timeout(1e4)
6725
- });
6726
- checks.push({
6727
- detail: `TLS and HTTPS succeeded with status ${response.status}`,
6728
- name: `tls:${connection.connectionId}`,
6729
- status: DoctorCheckStatus.Passed
6730
- });
6731
- const serverDate = response.headers.get("date");
6732
- const clockDifference = serverDate ? Math.abs(Date.parse(serverDate) - Date.now()) : 0;
6733
- checks.push({
6734
- detail: serverDate ? `${Math.round(clockDifference / 1e3)} second clock difference` : "Relay did not return a Date header",
6735
- name: `clock:${connection.connectionId}`,
6736
- status: serverDate && clockDifference > 3e5 ? DoctorCheckStatus.Warning : DoctorCheckStatus.Passed
6737
- });
6738
- } catch (error) {
6739
- checks.push({
6740
- detail: errorMessage(error),
6741
- name: `tls:${connection.connectionId}`,
6742
- status: DoctorCheckStatus.Failed
6743
- });
6744
- }
7235
+ if (value === ServiceManagerPreference.Systemd) {
7236
+ return ServiceManagerPreference.Systemd;
6745
7237
  }
6746
- const proxy = process.env.HTTPS_PROXY ?? process.env.https_proxy ?? process.env.ALL_PROXY ?? process.env.all_proxy;
6747
- checks.push({
6748
- detail: proxy ? "A process-level proxy is configured" : "Direct outbound HTTPS",
6749
- name: "proxy",
6750
- status: proxy ? DoctorCheckStatus.Warning : DoctorCheckStatus.Passed
6751
- });
6752
- checks.push({
6753
- detail: "HTTPS long-poll is authoritative; optional WSS wakeup is not required",
6754
- name: "transport",
6755
- status: DoctorCheckStatus.Passed
6756
- });
6757
- try {
6758
- const result = await execFileAsync(process.env.MOXT_CODEX_PATH ?? "codex", ["--version"]);
6759
- checks.push({
6760
- detail: result.stdout.trim(),
6761
- name: "codex",
6762
- status: DoctorCheckStatus.Passed
6763
- });
6764
- } catch (error) {
6765
- checks.push({
6766
- detail: errorMessage(error),
6767
- name: "codex",
6768
- status: DoctorCheckStatus.Warning
6769
- });
7238
+ if (value === ServiceManagerPreference.Supervisor) {
7239
+ return ServiceManagerPreference.Supervisor;
6770
7240
  }
6771
- try {
6772
- const result = await execFileAsync(process.env.MOXT_CLAUDE_PATH ?? "claude", ["--version"]);
6773
- checks.push({
6774
- detail: result.stdout.trim(),
6775
- name: "claude",
6776
- status: DoctorCheckStatus.Passed
6777
- });
6778
- } catch (error) {
6779
- checks.push({
6780
- detail: errorMessage(error),
6781
- name: "claude",
6782
- status: DoctorCheckStatus.Warning
6783
- });
7241
+ if (value === ServiceManagerPreference.None) {
7242
+ return ServiceManagerPreference.None;
6784
7243
  }
6785
- return checks;
6786
- }
6787
- function errorMessage(error) {
6788
- return error instanceof Error ? error.message : String(error);
7244
+ throw new Error(`Unsupported service manager: ${value}`);
6789
7245
  }
6790
- var import_node_child_process2, import_promises9, import_node_fs, import_promises10, import_node_util2, execFileAsync, DoctorCheckStatus;
6791
- var init_doctor = __esm({
6792
- "../machine-connector/dist/runtime/doctor.js"() {
6793
- "use strict";
6794
- init_cjs_shims();
6795
- import_node_child_process2 = require("child_process");
6796
- import_promises9 = require("fs/promises");
6797
- import_node_fs = require("fs");
6798
- import_promises10 = require("dns/promises");
6799
- import_node_util2 = require("util");
6800
- init_local_ipc();
6801
- execFileAsync = (0, import_node_util2.promisify)(import_node_child_process2.execFile);
6802
- (function(DoctorCheckStatus2) {
6803
- DoctorCheckStatus2["Failed"] = "failed";
6804
- DoctorCheckStatus2["Passed"] = "passed";
6805
- DoctorCheckStatus2["Warning"] = "warning";
6806
- })(DoctorCheckStatus || (DoctorCheckStatus = {}));
7246
+ function selectUserServiceManager(preference, capabilities) {
7247
+ if (preference === ServiceManagerPreference.None) {
7248
+ return {
7249
+ detail: "Background service installation was explicitly disabled.",
7250
+ manager: UserServiceManager.None
7251
+ };
6807
7252
  }
6808
- });
6809
-
6810
- // ../machine-connector/dist/runtime/machine-manager.js
6811
- function machineManagerActions() {
6812
- return [
6813
- {
6814
- action: MachineManagerAction.Refresh,
6815
- label: "Refresh now"
6816
- },
6817
- {
6818
- action: MachineManagerAction.Connect,
6819
- label: "Pair a new machine connection"
6820
- },
6821
- {
6822
- action: MachineManagerAction.Disconnect,
6823
- label: "Disconnect the selected connection"
6824
- },
6825
- {
6826
- action: MachineManagerAction.Doctor,
6827
- label: "Run diagnostics"
6828
- },
6829
- {
6830
- action: MachineManagerAction.Logs,
6831
- label: "Open recent logs"
6832
- },
6833
- {
6834
- action: MachineManagerAction.ServiceInstall,
6835
- label: "Install the Connector service"
6836
- },
6837
- {
6838
- action: MachineManagerAction.ServiceRestart,
6839
- label: "Restart the Connector service"
6840
- },
6841
- {
6842
- action: MachineManagerAction.ServiceStop,
6843
- label: "Stop the Connector service"
6844
- },
6845
- {
6846
- action: MachineManagerAction.ServiceUninstall,
6847
- label: "Uninstall the Connector service"
6848
- },
6849
- {
6850
- action: MachineManagerAction.Quit,
6851
- label: "Quit"
7253
+ if (capabilities.operatingSystem === "darwin") {
7254
+ if (preference !== ServiceManagerPreference.Auto) {
7255
+ throw new Error(`${preference} service management is supported only on Linux`);
6852
7256
  }
6853
- ];
6854
- }
6855
- function ensureInteractiveTerminal(inputIsTty, outputIsTty) {
6856
- if (!inputIsTty || !outputIsTty) {
6857
- throw new Error("moxt machine manager requires an interactive TTY. Use `moxt machine status`, `logs`, or `doctor` in non-interactive scripts.");
7257
+ return {
7258
+ detail: "Using the macOS LaunchAgent service manager.",
7259
+ manager: UserServiceManager.Launchd
7260
+ };
6858
7261
  }
6859
- }
6860
- async function collectMachineManagerSnapshot(store, depth) {
6861
- const connections = await store.listConnections();
6862
- const jobs = await store.listJobs();
6863
- const serviceManager = (await store.readServiceManager()).value;
6864
- const runtime = {};
6865
- try {
6866
- runtime.value = (await requestRuntimeStatus(store)).status;
6867
- } catch {
6868
- runtime.value = void 0;
7262
+ if (capabilities.operatingSystem !== "linux") {
7263
+ if (preference === ServiceManagerPreference.Auto) {
7264
+ return {
7265
+ detail: "No supported background service manager is available on this platform.",
7266
+ manager: UserServiceManager.None
7267
+ };
7268
+ }
7269
+ throw new Error(`${preference} service management is supported only on Linux`);
7270
+ }
7271
+ if (preference === ServiceManagerPreference.Systemd) {
7272
+ if (!capabilities.systemdUserAvailable) {
7273
+ throw new Error("The systemd user service manager is not available in this environment");
7274
+ }
7275
+ return {
7276
+ detail: "Using the systemd user service manager.",
7277
+ manager: UserServiceManager.Systemd
7278
+ };
7279
+ }
7280
+ if (preference === ServiceManagerPreference.Supervisor) {
7281
+ if (!capabilities.supervisorAvailable) {
7282
+ throw new Error("Supervisor is not available; install supervisord and supervisorctl or choose another service manager");
7283
+ }
7284
+ return {
7285
+ detail: "Using the Supervisor service manager.",
7286
+ manager: UserServiceManager.Supervisor
7287
+ };
7288
+ }
7289
+ if (capabilities.systemdUserAvailable) {
7290
+ return {
7291
+ detail: "Automatically selected the systemd user service manager.",
7292
+ manager: UserServiceManager.Systemd
7293
+ };
7294
+ }
7295
+ if (capabilities.supervisorAvailable) {
7296
+ return {
7297
+ detail: "Automatically selected the Supervisor service manager.",
7298
+ manager: UserServiceManager.Supervisor
7299
+ };
6869
7300
  }
6870
- const checks = depth === MachineManagerSnapshotDepth.WithDoctor ? await runMachineDoctor(store) : [];
6871
7301
  return {
6872
- checks,
6873
- connections: connections.map(toManagerConnection),
6874
- jobs: jobs.map(toManagerJob).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
6875
- logLines: await readRecentLogLines(store),
6876
- refreshedAt: (/* @__PURE__ */ new Date()).toISOString(),
6877
- runtime: runtime.value,
6878
- serviceManager: serviceManager?.manager
7302
+ detail: "No supported background service manager is available. Pairing is complete, but the Connector must be started manually.",
7303
+ manager: UserServiceManager.None
6879
7304
  };
6880
7305
  }
6881
- function renderMachineManager(snapshot, state, requestedWidth, requestedHeight) {
6882
- const width = Math.max(24, requestedWidth);
6883
- const height = Math.max(8, requestedHeight);
6884
- const lines = [];
6885
- const online = snapshot.runtime !== void 0;
6886
- lines.push(styledLine(` MOXT MACHINE MANAGER ${online ? "ONLINE" : "OFFLINE"} ${snapshot.serviceManager ?? "no service"}`, width, styleHeader));
6887
- lines.push(fitLine(renderTabs(state.view), width));
6888
- lines.push(repeatCharacter("\u2500", width));
6889
- const contentHeight = Math.max(1, height - 5);
6890
- const content3 = state.actionMenuOpen ? renderActions(state) : renderView(snapshot, state);
6891
- for (const line of content3.slice(0, contentHeight)) {
6892
- lines.push(fitLine(line, width));
6893
- }
6894
- while (lines.length < height - 2) {
6895
- lines.push(" ".repeat(width));
7306
+ async function detectServiceManagerCapabilities(runtime = defaultServiceManagerRuntime) {
7307
+ if (runtime.operatingSystem !== "linux") {
7308
+ return {
7309
+ operatingSystem: runtime.operatingSystem,
7310
+ supervisorAvailable: false,
7311
+ systemdUserAvailable: false
7312
+ };
6896
7313
  }
6897
- lines.push(repeatCharacter("\u2500", width));
6898
- lines.push(fitLine(state.message ?? "[A] Actions [Tab/1-5] View [Up/Down] Select [R] Refresh [Q] Quit", width));
6899
- return lines.slice(0, height).join("\n");
6900
- }
6901
- async function runMachineManager(store, commandRunner) {
6902
- ensureInteractiveTerminal(Boolean(process.stdin.isTTY), Boolean(process.stdout.isTTY));
6903
- const manager = new InteractiveMachineManager(store, commandRunner);
6904
- await manager.run();
7314
+ const systemdUserAvailable = await commandSucceeds(runtime, "systemctl", ["--user", "show-environment"]);
7315
+ const supervisordAvailable = await commandSucceeds(runtime, "supervisord", ["--version"]);
7316
+ const supervisorctlAvailable = await commandSucceeds(runtime, "supervisorctl", ["-h"]);
7317
+ return {
7318
+ operatingSystem: runtime.operatingSystem,
7319
+ supervisorAvailable: supervisordAvailable && supervisorctlAvailable,
7320
+ systemdUserAvailable
7321
+ };
6905
7322
  }
6906
- function renderTabs(selected) {
6907
- const labels = [
6908
- "1 Overview",
6909
- "2 Connections",
6910
- "3 Jobs",
6911
- "4 Logs",
6912
- "5 Doctor"
6913
- ];
6914
- return labels.map((label, index2) => index2 === selected ? `[${label}]` : ` ${label} `).join(" ");
7323
+ async function validateServiceManagerPreference(preference, runtime = defaultServiceManagerRuntime) {
7324
+ if (preference === ServiceManagerPreference.None) {
7325
+ return selectUserServiceManager(preference, {
7326
+ operatingSystem: runtime.operatingSystem,
7327
+ supervisorAvailable: false,
7328
+ systemdUserAvailable: false
7329
+ });
7330
+ }
7331
+ const capabilities = await detectServiceManagerCapabilities(runtime);
7332
+ return selectUserServiceManager(preference, capabilities);
6915
7333
  }
6916
- function renderView(snapshot, state) {
6917
- if (state.view === MachineManagerView.Overview) {
6918
- return renderOverview(snapshot);
7334
+ async function installUserService(store, request2, runtime = defaultServiceManagerRuntime) {
7335
+ if (request2.preference === ServiceManagerPreference.None) {
7336
+ const configuredManager = await readStoredServiceManager(store);
7337
+ if (configuredManager !== UserServiceManager.None) {
7338
+ await uninstallManager(configuredManager, store, runtime);
7339
+ }
7340
+ await persistServiceManager(store, UserServiceManager.None);
7341
+ return {
7342
+ detail: "Background service installation was explicitly disabled.",
7343
+ installed: false,
7344
+ manager: UserServiceManager.None
7345
+ };
6919
7346
  }
6920
- if (state.view === MachineManagerView.Connections) {
6921
- return renderConnections(snapshot, state.selectedRowIndex);
7347
+ const options = {
7348
+ ...request2.options,
7349
+ environment: {
7350
+ ...createServiceEnvironment(request2.options),
7351
+ MOXT_MACHINE_HOME: store.baseDirectory
7352
+ }
7353
+ };
7354
+ const capabilities = await detectServiceManagerCapabilities(runtime);
7355
+ const selection = selectUserServiceManager(request2.preference, capabilities);
7356
+ if (selection.manager === UserServiceManager.None) {
7357
+ await persistServiceManager(store, UserServiceManager.None);
7358
+ return {
7359
+ detail: selection.detail,
7360
+ installed: false,
7361
+ manager: UserServiceManager.None
7362
+ };
6922
7363
  }
6923
- if (state.view === MachineManagerView.Jobs) {
6924
- return renderJobs(snapshot, state.selectedRowIndex);
7364
+ if (request2.preference !== ServiceManagerPreference.Auto) {
7365
+ await replaceConfiguredManager(store, selection.manager, options, runtime);
7366
+ return {
7367
+ detail: selection.detail,
7368
+ installed: true,
7369
+ manager: selection.manager
7370
+ };
6925
7371
  }
6926
- if (state.view === MachineManagerView.Logs) {
6927
- return renderLogs(snapshot);
7372
+ const candidates = await automaticManagerCandidates(store, capabilities);
7373
+ const failures = [];
7374
+ for (const manager of candidates) {
7375
+ try {
7376
+ await replaceConfiguredManager(store, manager, options, runtime);
7377
+ return {
7378
+ detail: automaticSelectionDetail(manager),
7379
+ installed: true,
7380
+ manager
7381
+ };
7382
+ } catch (error) {
7383
+ failures.push(`${manager}: ${error instanceof Error ? error.message : String(error)}`);
7384
+ await uninstallManagerIgnoringFailure(manager, store, runtime);
7385
+ }
6928
7386
  }
6929
- return renderDoctor(snapshot);
7387
+ await persistServiceManager(store, UserServiceManager.None);
7388
+ return {
7389
+ detail: failures.length === 0 ? selection.detail : `Automatic background service setup failed (${failures.join("; ")}). Pairing is complete, but the Connector must be started manually.`,
7390
+ installed: false,
7391
+ manager: UserServiceManager.None
7392
+ };
6930
7393
  }
6931
- function renderOverview(snapshot) {
6932
- const runtime = snapshot.runtime;
6933
- const lines = [
6934
- "",
6935
- ` Daemon ${runtime ? `ONLINE PID ${runtime.pid} v${runtime.version}` : "OFFLINE"}`,
6936
- ` Service ${snapshot.serviceManager ?? "not installed"}`,
6937
- ` Connections ${snapshot.connections.length}`,
6938
- ` Active Jobs ${runtime?.activeJobs.length ?? 0}`,
6939
- ` Stored Jobs ${snapshot.jobs.length}`,
6940
- ` Refreshed ${formatTimestamp(snapshot.refreshedAt)}`,
6941
- ""
6942
- ];
6943
- if (snapshot.connections.length === 0) {
6944
- lines.push(' No connections. Press A and choose "Pair a new machine connection".');
6945
- return lines;
7394
+ function createServiceEnvironment(options) {
7395
+ const inheritedPath = options.environment.PATH ?? process.env.PATH ?? "";
7396
+ const nodeDirectory = (0, import_node_path7.dirname)(options.nodePath);
7397
+ const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path7.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
7398
+ return {
7399
+ ...options.environment,
7400
+ HOME: options.environment.HOME ?? process.env.HOME ?? (0, import_node_os5.homedir)(),
7401
+ PATH: pathEntries.join(import_node_path7.delimiter)
7402
+ };
7403
+ }
7404
+ async function restartUserService(store, runtime = defaultServiceManagerRuntime) {
7405
+ const manager = await configuredServiceManager(store, runtime);
7406
+ await restartManager(manager, store, runtime);
7407
+ return manager;
7408
+ }
7409
+ async function refreshManagedUserService(store, options, runtime = defaultServiceManagerRuntime) {
7410
+ const manager = await readStoredServiceManager(store);
7411
+ if (manager === UserServiceManager.None)
7412
+ return void 0;
7413
+ const snapshot = await readManagedServiceDefinition(manager, store);
7414
+ if (snapshot === void 0) {
7415
+ throw new Error(`The recorded ${manager} service definition does not exist`);
6946
7416
  }
6947
- lines.push(" Connected roots");
6948
- for (const connection of snapshot.connections) {
6949
- lines.push(` ${connection.machineName} ${connection.rootPath}`);
7417
+ const refreshedOptions = {
7418
+ ...options,
7419
+ environment: {
7420
+ ...createServiceEnvironment(options),
7421
+ MOXT_MACHINE_HOME: store.baseDirectory
7422
+ }
7423
+ };
7424
+ const rollback = async () => {
7425
+ await restoreManagedServiceDefinition(manager, store, snapshot, runtime);
7426
+ };
7427
+ try {
7428
+ await installManager(manager, store, refreshedOptions, runtime);
7429
+ if (manager === UserServiceManager.Systemd) {
7430
+ await restartManager(manager, store, runtime);
7431
+ }
7432
+ await persistServiceManager(store, manager);
7433
+ } catch (error) {
7434
+ try {
7435
+ await rollback();
7436
+ } catch (rollbackError) {
7437
+ throw new Error(`${errorMessage(error)}; restoring the previous ${manager} definition also failed: ${errorMessage(rollbackError)}`, { cause: error });
7438
+ }
7439
+ throw error;
6950
7440
  }
6951
- return lines;
7441
+ return { manager, rollback };
6952
7442
  }
6953
- function renderConnections(snapshot, selectedRowIndex) {
6954
- if (snapshot.connections.length === 0) {
6955
- return ["", " No connections", " Press A to pair a machine."];
7443
+ async function managedServiceOwnsProcess(manager, processId, store, runtime = defaultServiceManagerRuntime) {
7444
+ if (manager === UserServiceManager.Launchd) {
7445
+ const result = await runServiceProbe(runtime, "launchctl", [
7446
+ "print",
7447
+ `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7448
+ ]);
7449
+ const match = /(?:^|\s)pid\s*=\s*(\d+)(?:\s|$)/m.exec(result.stdout);
7450
+ return match ? Number(match[1]) === processId : false;
6956
7451
  }
6957
- const lines = [
6958
- " MACHINE ROOT WORKSPACE / TARGET"
6959
- ];
6960
- snapshot.connections.forEach((connection, index2) => {
6961
- const marker = index2 === selectedRowIndex ? ">" : " ";
6962
- lines.push(`${marker} ${connection.machineName} ${connection.rootPath} ${connection.workspaceId} / ${connection.targetId}`);
6963
- lines.push(` ${connection.connectionId} ${connection.relayOrigin}`);
6964
- });
6965
- return lines;
6966
- }
6967
- function renderJobs(snapshot, selectedRowIndex) {
6968
- if (snapshot.jobs.length === 0) {
6969
- return ["", " No Jobs have been stored on this machine."];
7452
+ if (manager === UserServiceManager.Systemd) {
7453
+ const result = await runServiceProbe(runtime, "systemctl", [
7454
+ "--user",
7455
+ "show",
7456
+ "--property",
7457
+ "MainPID",
7458
+ "--value",
7459
+ "moxt-machine-connector.service"
7460
+ ]);
7461
+ return parseProcessId(result.stdout) === processId;
6970
7462
  }
6971
- const lines = [" STATUS KIND JOB / COMMAND"];
6972
- snapshot.jobs.forEach((job, index2) => {
6973
- const marker = index2 === selectedRowIndex ? ">" : " ";
6974
- lines.push(`${marker} ${job.status ?? job.phase} ${job.kind} ${job.command ?? job.jobId}`);
6975
- lines.push(` ${job.jobId} ${job.relativeWorkingDirectory} ${formatTimestamp(job.updatedAt)}`);
6976
- });
6977
- return lines;
6978
- }
6979
- function renderLogs(snapshot) {
6980
- if (snapshot.logLines.length === 0) {
6981
- return ["", " No Connector logs are available."];
7463
+ if (manager === UserServiceManager.Supervisor) {
7464
+ const result = await runServiceProbe(runtime, "supervisorctl", [
7465
+ "-c",
7466
+ supervisorConfigPath(store),
7467
+ "pid",
7468
+ supervisorProgramName
7469
+ ]);
7470
+ return parseProcessId(result.stdout) === processId;
6982
7471
  }
6983
- return snapshot.logLines.map((line) => ` ${line}`);
7472
+ return false;
6984
7473
  }
6985
- function renderDoctor(snapshot) {
6986
- if (snapshot.checks.length === 0) {
6987
- return [
6988
- "",
6989
- " Diagnostics have not run yet.",
6990
- ' Press A and choose "Run diagnostics".'
6991
- ];
6992
- }
6993
- return snapshot.checks.map((check) => ` ${check.status.padEnd(7)} ${check.name}: ${check.detail}`);
7474
+ async function recordedServiceManager(store) {
7475
+ return await readStoredServiceManager(store);
6994
7476
  }
6995
- function renderActions(state) {
6996
- const lines = [
6997
- " Actions",
6998
- " Use Up/Down and Enter. Esc closes this menu.",
6999
- ""
7000
- ];
7001
- machineManagerActions().forEach((definition2, index2) => {
7002
- const selected = index2 === state.selectedActionIndex;
7003
- const line = `${selected ? ">" : " "} ${definition2.label}`;
7004
- lines.push(selected ? `${styleSelected}${line}${styleReset}` : line);
7005
- });
7006
- return lines;
7477
+ async function stopUserService(store, runtime = defaultServiceManagerRuntime) {
7478
+ const manager = await configuredServiceManager(store, runtime);
7479
+ await stopManager(manager, store, runtime);
7480
+ return manager;
7007
7481
  }
7008
- function rowCountForView(snapshot, view) {
7009
- if (view === MachineManagerView.Connections) {
7010
- return snapshot.connections.length;
7482
+ async function uninstallUserService(store, runtime = defaultServiceManagerRuntime) {
7483
+ const manager = await configuredServiceManager(store, runtime);
7484
+ await uninstallManager(manager, store, runtime);
7485
+ await store.removeServiceManager();
7486
+ return manager;
7487
+ }
7488
+ async function automaticManagerCandidates(store, capabilities) {
7489
+ const candidates = [];
7490
+ const storedManager = await readStoredServiceManager(store);
7491
+ if (storedManager !== UserServiceManager.None && managerIsAvailable(storedManager, capabilities)) {
7492
+ candidates.push(storedManager);
7011
7493
  }
7012
- if (view === MachineManagerView.Jobs) {
7013
- return snapshot.jobs.length;
7494
+ if (capabilities.operatingSystem === "darwin" && !candidates.includes(UserServiceManager.Launchd)) {
7495
+ candidates.push(UserServiceManager.Launchd);
7014
7496
  }
7015
- return 0;
7497
+ if (capabilities.systemdUserAvailable && !candidates.includes(UserServiceManager.Systemd)) {
7498
+ candidates.push(UserServiceManager.Systemd);
7499
+ }
7500
+ if (capabilities.supervisorAvailable && !candidates.includes(UserServiceManager.Supervisor)) {
7501
+ candidates.push(UserServiceManager.Supervisor);
7502
+ }
7503
+ return candidates;
7016
7504
  }
7017
- function toManagerConnection(connection) {
7018
- return {
7019
- connectionId: connection.connectionId,
7020
- machineName: connection.machineName,
7021
- relayOrigin: connection.relayOrigin,
7022
- rootDisplayName: connection.rootDisplayName,
7023
- rootPath: connection.rootPath,
7024
- targetId: connection.targetId,
7025
- targetKind: connection.targetKind,
7026
- workspaceId: connection.workspaceId
7027
- };
7505
+ async function replaceConfiguredManager(store, manager, options, runtime) {
7506
+ const configuredManager = await readStoredServiceManager(store);
7507
+ if (configuredManager !== UserServiceManager.None && configuredManager !== manager) {
7508
+ await uninstallManagerIgnoringFailure(configuredManager, store, runtime);
7509
+ }
7510
+ await installManager(manager, store, options, runtime);
7511
+ await persistServiceManager(store, manager);
7028
7512
  }
7029
- function toManagerJob(job) {
7030
- return {
7031
- command: formatPersistedCommand(job).value,
7032
- connectionId: job.connectionId,
7033
- jobId: job.claim.jobId,
7034
- kind: job.claim.kind,
7035
- phase: job.phase,
7036
- relativeWorkingDirectory: job.claim.relativeWorkingDirectory,
7037
- status: job.finalStatus,
7038
- updatedAt: job.updatedAt
7039
- };
7513
+ async function installManager(manager, store, options, runtime) {
7514
+ if (manager === UserServiceManager.Launchd) {
7515
+ await installLaunchAgent(store, options, runtime);
7516
+ return;
7517
+ }
7518
+ if (manager === UserServiceManager.Systemd) {
7519
+ await installSystemdUserService(store, options, runtime);
7520
+ return;
7521
+ }
7522
+ if (manager === UserServiceManager.Supervisor) {
7523
+ await installSupervisorUserService(store, options, runtime);
7524
+ return;
7525
+ }
7040
7526
  }
7041
- function formatPersistedCommand(job) {
7042
- if (job.claim.kind !== "command") {
7043
- return {};
7527
+ async function restartManager(manager, store, runtime) {
7528
+ if (manager === UserServiceManager.None) {
7529
+ return;
7044
7530
  }
7045
- if (!isRecord3(job.claim.requestPayload)) {
7046
- return {};
7531
+ if (manager === UserServiceManager.Launchd) {
7532
+ await runtime.run("launchctl", [
7533
+ "kickstart",
7534
+ "-k",
7535
+ `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7536
+ ]);
7537
+ return;
7047
7538
  }
7048
- const executable = job.claim.requestPayload.executable;
7049
- const argumentsValue = job.claim.requestPayload.arguments;
7050
- if (typeof executable !== "string" || !Array.isArray(argumentsValue) || !argumentsValue.every((argument) => typeof argument === "string")) {
7051
- return {};
7539
+ if (manager === UserServiceManager.Systemd) {
7540
+ await runtime.run("systemctl", [
7541
+ "--user",
7542
+ "restart",
7543
+ "moxt-machine-connector.service"
7544
+ ]);
7545
+ return;
7052
7546
  }
7053
- return {
7054
- value: [executable, ...argumentsValue].map(formatCommandArgument).join(" ")
7055
- };
7547
+ await restartSupervisorUserService(store, runtime);
7056
7548
  }
7057
- function formatCommandArgument(value) {
7058
- return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : JSON.stringify(value);
7549
+ async function stopManager(manager, store, runtime) {
7550
+ if (manager === UserServiceManager.None) {
7551
+ return;
7552
+ }
7553
+ if (manager === UserServiceManager.Launchd) {
7554
+ await runtime.run("launchctl", [
7555
+ "bootout",
7556
+ `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7557
+ ]);
7558
+ return;
7559
+ }
7560
+ if (manager === UserServiceManager.Systemd) {
7561
+ await runtime.run("systemctl", [
7562
+ "--user",
7563
+ "stop",
7564
+ "moxt-machine-connector.service"
7565
+ ]);
7566
+ return;
7567
+ }
7568
+ await runCommandIgnoringFailure(runtime, "supervisorctl", [
7569
+ "-c",
7570
+ supervisorConfigPath(store),
7571
+ "stop",
7572
+ supervisorProgramName
7573
+ ]);
7059
7574
  }
7060
- async function readRecentLogLines(store) {
7061
- const normal = await readOptionalFile(store.runtimeLogPath());
7062
- const errors = await readOptionalFile(store.runtimeErrorLogPath());
7063
- return [...normal.split("\n"), ...errors.split("\n")].filter((line) => line.length > 0).slice(-maximumLogLines);
7575
+ async function uninstallManager(manager, store, runtime) {
7576
+ if (manager === UserServiceManager.None) {
7577
+ return;
7578
+ }
7579
+ if (manager === UserServiceManager.Launchd) {
7580
+ await runCommandIgnoringFailure(runtime, "launchctl", [
7581
+ "bootout",
7582
+ `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7583
+ ]);
7584
+ await (0, import_promises10.rm)(launchAgentPath(), { force: true });
7585
+ return;
7586
+ }
7587
+ if (manager === UserServiceManager.Systemd) {
7588
+ await runCommandIgnoringFailure(runtime, "systemctl", [
7589
+ "--user",
7590
+ "disable",
7591
+ "--now",
7592
+ "moxt-machine-connector.service"
7593
+ ]);
7594
+ await (0, import_promises10.rm)(systemdUnitPath(), { force: true });
7595
+ await runCommandIgnoringFailure(runtime, "systemctl", [
7596
+ "--user",
7597
+ "daemon-reload"
7598
+ ]);
7599
+ return;
7600
+ }
7601
+ await runCommandIgnoringFailure(runtime, "supervisorctl", [
7602
+ "-c",
7603
+ supervisorConfigPath(store),
7604
+ "stop",
7605
+ supervisorProgramName
7606
+ ]);
7607
+ await runCommandIgnoringFailure(runtime, "supervisorctl", ["-c", supervisorConfigPath(store), "shutdown"]);
7608
+ await (0, import_promises10.rm)(supervisorDirectory(store), {
7609
+ force: true,
7610
+ recursive: true
7611
+ });
7064
7612
  }
7065
- async function readOptionalFile(path4) {
7613
+ async function configuredServiceManager(store, runtime) {
7614
+ const storedManager = await readStoredServiceManager(store);
7615
+ if (storedManager !== UserServiceManager.None) {
7616
+ return storedManager;
7617
+ }
7618
+ const stored = await store.readServiceManager();
7619
+ if (stored.value) {
7620
+ return UserServiceManager.None;
7621
+ }
7622
+ const capabilities = await detectServiceManagerCapabilities(runtime);
7623
+ return selectUserServiceManager(ServiceManagerPreference.Auto, capabilities).manager;
7624
+ }
7625
+ async function readStoredServiceManager(store) {
7626
+ const stored = await store.readServiceManager();
7627
+ if (!stored.value) {
7628
+ return UserServiceManager.None;
7629
+ }
7630
+ return parseStoredServiceManager(stored.value.manager);
7631
+ }
7632
+ async function readManagedServiceDefinition(manager, store) {
7066
7633
  try {
7067
- return await (0, import_promises11.readFile)(path4, "utf8");
7634
+ return await (0, import_promises10.readFile)(managedServiceDefinitionPath(manager, store), "utf8");
7068
7635
  } catch (error) {
7069
- if (isMissingFile(error)) {
7070
- return "";
7071
- }
7636
+ if (isNodeErrorCode4(error, "ENOENT"))
7637
+ return void 0;
7072
7638
  throw error;
7073
7639
  }
7074
7640
  }
7075
- async function questionWithDefault(reader, label, defaultValue) {
7076
- const suffix = defaultValue.length > 0 ? ` [${defaultValue}]` : "";
7077
- const answer = (await reader.question(`${label}${suffix}: `)).trim();
7078
- return answer.length > 0 ? answer : defaultValue;
7079
- }
7080
- function appendOption(argumentsList, name, value) {
7081
- if (value.length > 0) {
7082
- argumentsList.push(name, value);
7641
+ async function restoreManagedServiceDefinition(manager, store, definition2, runtime) {
7642
+ const path4 = managedServiceDefinitionPath(manager, store);
7643
+ await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
7644
+ await (0, import_promises10.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
7645
+ if (manager === UserServiceManager.Launchd) {
7646
+ const domain = `gui/${process.getuid?.() ?? 0}`;
7647
+ await runCommandIgnoringFailure(runtime, "launchctl", [
7648
+ "bootout",
7649
+ domain,
7650
+ path4
7651
+ ]);
7652
+ await runtime.run("launchctl", ["bootstrap", domain, path4]);
7653
+ } else if (manager === UserServiceManager.Systemd) {
7654
+ await runtime.run("systemctl", ["--user", "daemon-reload"]);
7655
+ } else if (manager === UserServiceManager.Supervisor) {
7656
+ await reloadSupervisorConfiguration(store, runtime);
7657
+ return;
7083
7658
  }
7659
+ await restartManager(manager, store, runtime);
7084
7660
  }
7085
- function styledLine(value, width, style) {
7086
- return `${style}${fitLine(value, width)}${styleReset}`;
7661
+ function managedServiceDefinitionPath(manager, store) {
7662
+ if (manager === UserServiceManager.Launchd)
7663
+ return launchAgentPath();
7664
+ if (manager === UserServiceManager.Systemd)
7665
+ return systemdUnitPath();
7666
+ if (manager === UserServiceManager.Supervisor) {
7667
+ return supervisorConfigPath(store);
7668
+ }
7669
+ throw new Error("An unmanaged daemon has no service definition");
7087
7670
  }
7088
- function fitLine(value, width) {
7089
- const plainValue = stripAnsi(value);
7090
- if (plainValue.length > width) {
7091
- if (width <= 1) {
7092
- return plainValue.slice(0, width);
7093
- }
7094
- return `${plainValue.slice(0, width - 1)}\u2026`;
7671
+ function parseStoredServiceManager(value) {
7672
+ if (value === UserServiceManager.Launchd) {
7673
+ return UserServiceManager.Launchd;
7095
7674
  }
7096
- if (value.includes("\x1B[")) {
7097
- return value;
7675
+ if (value === UserServiceManager.Systemd) {
7676
+ return UserServiceManager.Systemd;
7098
7677
  }
7099
- return value.padEnd(width);
7100
- }
7101
- function stripAnsi(value) {
7102
- return value.replaceAll(styleHeader, "").replaceAll(styleSelected, "").replaceAll(styleReset, "");
7678
+ if (value === UserServiceManager.Supervisor) {
7679
+ return UserServiceManager.Supervisor;
7680
+ }
7681
+ if (value === UserServiceManager.None) {
7682
+ return UserServiceManager.None;
7683
+ }
7684
+ throw new Error(`Unsupported stored service manager: ${value}`);
7103
7685
  }
7104
- function repeatCharacter(value, count) {
7105
- return value.repeat(count);
7686
+ function parseProcessId(value) {
7687
+ const processId = Number.parseInt(value.trim(), 10);
7688
+ return Number.isSafeInteger(processId) && processId > 0 ? processId : void 0;
7106
7689
  }
7107
- function wrapIndex(value, count) {
7108
- return (value % count + count) % count;
7690
+ async function persistServiceManager(store, manager) {
7691
+ await store.writeServiceManager({
7692
+ manager,
7693
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
7694
+ });
7109
7695
  }
7110
- function formatTimestamp(value) {
7111
- const timestamp = Date.parse(value);
7112
- if (Number.isNaN(timestamp)) {
7113
- return value;
7696
+ function managerIsAvailable(manager, capabilities) {
7697
+ if (manager === UserServiceManager.Launchd) {
7698
+ return capabilities.operatingSystem === "darwin";
7114
7699
  }
7115
- return new Date(timestamp).toLocaleString();
7116
- }
7117
- function isRecord3(value) {
7118
- return typeof value === "object" && value !== null && !Array.isArray(value);
7119
- }
7120
- function isMissingFile(error) {
7121
- return error instanceof Error && "code" in error && error.code === "ENOENT";
7700
+ if (manager === UserServiceManager.Systemd) {
7701
+ return capabilities.systemdUserAvailable;
7702
+ }
7703
+ if (manager === UserServiceManager.Supervisor) {
7704
+ return capabilities.supervisorAvailable;
7705
+ }
7706
+ return false;
7122
7707
  }
7123
- function errorMessage2(error) {
7124
- return error instanceof Error ? error.message : String(error);
7708
+ function automaticSelectionDetail(manager) {
7709
+ if (manager === UserServiceManager.Launchd) {
7710
+ return "Automatically selected the macOS LaunchAgent service manager.";
7711
+ }
7712
+ if (manager === UserServiceManager.Systemd) {
7713
+ return "Automatically selected the systemd user service manager.";
7714
+ }
7715
+ return "Automatically selected the Supervisor service manager.";
7125
7716
  }
7126
- var import_promises11, import_promises12, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
7127
- var init_machine_manager = __esm({
7128
- "../machine-connector/dist/runtime/machine-manager.js"() {
7129
- "use strict";
7130
- init_cjs_shims();
7131
- import_promises11 = require("fs/promises");
7132
- import_promises12 = require("readline/promises");
7133
- import_node_readline = require("readline");
7134
- init_doctor();
7135
- init_local_ipc();
7136
- alternateScreenEnter = "\x1B[?1049h";
7137
- alternateScreenExit = "\x1B[?1049l";
7138
- clearScreen = "\x1B[2J\x1B[H";
7139
- cursorHide = "\x1B[?25l";
7140
- cursorShow = "\x1B[?25h";
7141
- styleReset = "\x1B[0m";
7142
- styleHeader = "\x1B[1;30;46m";
7143
- styleSelected = "\x1B[30;47m";
7144
- refreshIntervalMilliseconds = 1e3;
7145
- maximumLogLines = 200;
7146
- (function(MachineManagerView2) {
7147
- MachineManagerView2[MachineManagerView2["Overview"] = 0] = "Overview";
7148
- MachineManagerView2[MachineManagerView2["Connections"] = 1] = "Connections";
7149
- MachineManagerView2[MachineManagerView2["Jobs"] = 2] = "Jobs";
7150
- MachineManagerView2[MachineManagerView2["Logs"] = 3] = "Logs";
7151
- MachineManagerView2[MachineManagerView2["Doctor"] = 4] = "Doctor";
7152
- })(MachineManagerView || (MachineManagerView = {}));
7153
- (function(MachineManagerAction2) {
7154
- MachineManagerAction2["Refresh"] = "refresh";
7155
- MachineManagerAction2["Connect"] = "connect";
7156
- MachineManagerAction2["Disconnect"] = "disconnect";
7157
- MachineManagerAction2["Doctor"] = "doctor";
7158
- MachineManagerAction2["Logs"] = "logs";
7159
- MachineManagerAction2["ServiceInstall"] = "service_install";
7160
- MachineManagerAction2["ServiceRestart"] = "service_restart";
7161
- MachineManagerAction2["ServiceStop"] = "service_stop";
7162
- MachineManagerAction2["ServiceUninstall"] = "service_uninstall";
7163
- MachineManagerAction2["Quit"] = "quit";
7164
- })(MachineManagerAction || (MachineManagerAction = {}));
7165
- (function(MachineManagerSnapshotDepth2) {
7166
- MachineManagerSnapshotDepth2["Basic"] = "basic";
7167
- MachineManagerSnapshotDepth2["WithDoctor"] = "with_doctor";
7168
- })(MachineManagerSnapshotDepth || (MachineManagerSnapshotDepth = {}));
7169
- InteractiveMachineManager = class {
7170
- store;
7171
- commandRunner;
7172
- checks = [];
7173
- refreshTimer;
7174
- refreshing = false;
7175
- resolveRun;
7176
- snapshot = {
7177
- checks: [],
7178
- connections: [],
7179
- jobs: [],
7180
- logLines: [],
7181
- refreshedAt: (/* @__PURE__ */ new Date()).toISOString()
7182
- };
7183
- state = {
7184
- actionMenuOpen: false,
7185
- selectedActionIndex: 0,
7186
- selectedRowIndex: 0,
7187
- view: MachineManagerView.Overview
7188
- };
7189
- stopped = false;
7190
- terminalSuspended = true;
7191
- constructor(store, commandRunner) {
7192
- this.store = store;
7193
- this.commandRunner = commandRunner;
7194
- }
7195
- async run() {
7196
- await this.refresh(MachineManagerSnapshotDepth.Basic);
7197
- this.enterTerminal();
7198
- try {
7199
- await new Promise((resolvePromise) => {
7200
- this.resolveRun = resolvePromise;
7201
- });
7202
- } finally {
7203
- this.leaveTerminal();
7204
- }
7205
- }
7206
- enterTerminal() {
7207
- (0, import_node_readline.emitKeypressEvents)(process.stdin);
7208
- process.stdin.setRawMode(true);
7209
- process.stdin.resume();
7210
- process.stdin.on("keypress", this.onKeypress);
7211
- process.stdout.on("resize", this.onResize);
7212
- process.on("SIGINT", this.onTerminationSignal);
7213
- process.on("SIGTERM", this.onTerminationSignal);
7214
- process.stdout.write(`${alternateScreenEnter}${cursorHide}${clearScreen}`);
7215
- this.terminalSuspended = false;
7216
- this.refreshTimer = setInterval(() => {
7217
- void this.refresh(MachineManagerSnapshotDepth.Basic);
7218
- }, refreshIntervalMilliseconds);
7219
- this.render();
7220
- }
7221
- leaveTerminal() {
7222
- if (this.refreshTimer) {
7223
- clearInterval(this.refreshTimer);
7224
- this.refreshTimer = void 0;
7225
- }
7226
- process.stdin.off("keypress", this.onKeypress);
7227
- process.stdout.off("resize", this.onResize);
7228
- process.off("SIGINT", this.onTerminationSignal);
7229
- process.off("SIGTERM", this.onTerminationSignal);
7230
- if (process.stdin.isTTY) {
7231
- process.stdin.setRawMode(false);
7232
- }
7233
- process.stdin.pause();
7234
- process.stdout.write(`${cursorShow}${styleReset}${alternateScreenExit}`);
7235
- }
7236
- onResize = () => {
7237
- this.render();
7238
- };
7239
- onTerminationSignal = () => {
7240
- this.stop();
7241
- };
7242
- onKeypress = (text3, key) => {
7243
- if (key.ctrl && key.name === "c") {
7244
- this.stop();
7245
- return;
7246
- }
7247
- if (key.name === "q" || text3 === "q") {
7248
- this.stop();
7249
- return;
7250
- }
7251
- if (key.name === "a" || text3 === "a" || text3 === "?") {
7252
- this.state.actionMenuOpen = !this.state.actionMenuOpen;
7253
- this.state.message = void 0;
7254
- this.render();
7255
- return;
7256
- }
7257
- if (key.name === "escape") {
7258
- this.state.actionMenuOpen = false;
7259
- this.render();
7260
- return;
7261
- }
7262
- if (key.name === "up") {
7263
- this.moveSelection(-1);
7264
- return;
7265
- }
7266
- if (key.name === "down") {
7267
- this.moveSelection(1);
7268
- return;
7269
- }
7270
- if (key.name === "return" && this.state.actionMenuOpen) {
7271
- void this.executeSelectedAction();
7272
- return;
7273
- }
7274
- if (key.name === "tab" || key.name === "right") {
7275
- this.changeView(1);
7276
- return;
7277
- }
7278
- if (key.name === "left") {
7279
- this.changeView(-1);
7280
- return;
7281
- }
7282
- if (text3 === "r") {
7283
- void this.refresh(MachineManagerSnapshotDepth.Basic);
7284
- return;
7285
- }
7286
- const viewNumber = Number(text3);
7287
- if (Number.isInteger(viewNumber) && viewNumber >= 1 && viewNumber <= 5) {
7288
- this.state.view = viewNumber - 1;
7289
- this.state.selectedRowIndex = 0;
7290
- this.state.actionMenuOpen = false;
7291
- this.render();
7292
- }
7293
- };
7294
- moveSelection(delta) {
7295
- const rowCount = this.state.actionMenuOpen ? machineManagerActions().length : rowCountForView(this.snapshot, this.state.view);
7296
- if (rowCount === 0) {
7297
- return;
7298
- }
7299
- if (this.state.actionMenuOpen) {
7300
- this.state.selectedActionIndex = wrapIndex(this.state.selectedActionIndex + delta, rowCount);
7301
- } else {
7302
- this.state.selectedRowIndex = wrapIndex(this.state.selectedRowIndex + delta, rowCount);
7303
- }
7304
- this.render();
7305
- }
7306
- changeView(delta) {
7307
- this.state.view = wrapIndex(this.state.view + delta, 5);
7308
- this.state.selectedRowIndex = 0;
7309
- this.state.actionMenuOpen = false;
7310
- this.state.message = void 0;
7311
- this.render();
7312
- }
7313
- async refresh(depth) {
7314
- if (this.refreshing || this.stopped) {
7315
- return;
7316
- }
7317
- this.refreshing = true;
7318
- try {
7319
- const snapshot = await collectMachineManagerSnapshot(this.store, depth);
7320
- if (snapshot.checks.length > 0) {
7321
- this.checks = snapshot.checks;
7322
- }
7323
- this.snapshot = {
7324
- ...snapshot,
7325
- checks: this.checks
7326
- };
7327
- this.state.message = void 0;
7328
- } catch (error) {
7329
- this.state.message = errorMessage2(error);
7330
- } finally {
7331
- this.refreshing = false;
7332
- this.render();
7333
- }
7334
- }
7335
- render() {
7336
- if (this.stopped || this.terminalSuspended || !process.stdout.isTTY) {
7337
- return;
7338
- }
7339
- process.stdout.write(`${clearScreen}${renderMachineManager(this.snapshot, this.state, process.stdout.columns ?? 80, process.stdout.rows ?? 24)}`);
7340
- }
7341
- async executeSelectedAction() {
7342
- const definition2 = machineManagerActions()[this.state.selectedActionIndex];
7343
- this.state.actionMenuOpen = false;
7344
- if (definition2.action === MachineManagerAction.Quit) {
7345
- this.stop();
7346
- return;
7347
- }
7348
- if (definition2.action === MachineManagerAction.Refresh) {
7349
- await this.refresh(MachineManagerSnapshotDepth.Basic);
7350
- return;
7351
- }
7352
- if (definition2.action === MachineManagerAction.Doctor) {
7353
- this.state.view = MachineManagerView.Doctor;
7354
- await this.refresh(MachineManagerSnapshotDepth.WithDoctor);
7355
- return;
7356
- }
7357
- if (definition2.action === MachineManagerAction.Logs) {
7358
- this.state.view = MachineManagerView.Logs;
7359
- await this.refresh(MachineManagerSnapshotDepth.Basic);
7360
- return;
7361
- }
7362
- await this.runCommandAction(definition2.action);
7363
- }
7364
- async runCommandAction(action) {
7365
- this.suspendTerminal();
7366
- const reader = (0, import_promises12.createInterface)({
7367
- input: process.stdin,
7368
- output: process.stdout
7369
- });
7370
- try {
7371
- const argumentsList = await this.buildCommandArguments(reader, action);
7372
- if (argumentsList.length > 0) {
7373
- await this.commandRunner.run(argumentsList);
7374
- }
7375
- } catch (error) {
7376
- process.stdout.write(`
7377
- Error: ${errorMessage2(error)}
7378
- `);
7379
- }
7380
- await reader.question("\nPress Enter to return to the manager...");
7381
- reader.close();
7382
- this.resumeTerminal();
7383
- await this.refresh(MachineManagerSnapshotDepth.Basic);
7384
- }
7385
- suspendTerminal() {
7386
- this.terminalSuspended = true;
7387
- process.stdin.off("keypress", this.onKeypress);
7388
- process.stdout.off("resize", this.onResize);
7389
- process.stdin.setRawMode(false);
7390
- process.stdout.write(`${cursorShow}${styleReset}${alternateScreenExit}`);
7391
- }
7392
- resumeTerminal() {
7393
- (0, import_node_readline.emitKeypressEvents)(process.stdin);
7394
- process.stdin.setRawMode(true);
7395
- process.stdin.resume();
7396
- process.stdin.on("keypress", this.onKeypress);
7397
- process.stdout.on("resize", this.onResize);
7398
- process.stdout.write(`${alternateScreenEnter}${cursorHide}${clearScreen}`);
7399
- this.terminalSuspended = false;
7400
- }
7401
- async buildCommandArguments(reader, action) {
7402
- if (action === MachineManagerAction.Connect) {
7403
- return await this.buildConnectArguments(reader);
7404
- }
7405
- if (action === MachineManagerAction.Disconnect) {
7406
- return await this.buildDisconnectArguments(reader);
7407
- }
7408
- if (action === MachineManagerAction.ServiceInstall) {
7409
- const manager = await questionWithDefault(reader, "Service manager (auto/systemd/supervisor/none)", "auto");
7410
- return ["service", "install", "--service-manager", manager];
7411
- }
7412
- if (action === MachineManagerAction.ServiceRestart) {
7413
- return ["service", "restart"];
7414
- }
7415
- if (action === MachineManagerAction.ServiceStop) {
7416
- return ["service", "stop"];
7417
- }
7418
- if (action === MachineManagerAction.ServiceUninstall) {
7419
- return ["service", "uninstall"];
7420
- }
7421
- return [];
7422
- }
7423
- async buildConnectArguments(reader) {
7424
- const code = (await reader.question("Pairing code: ")).trim();
7425
- if (code.length === 0) {
7426
- throw new Error("Pairing code is required");
7427
- }
7428
- const root = await questionWithDefault(reader, "Working root", process.cwd());
7429
- const relay = (await reader.question("Relay origin (leave blank for the default): ")).trim();
7430
- const name = (await reader.question("Machine name (leave blank for the hostname): ")).trim();
7431
- const serviceManager = await questionWithDefault(reader, "Service manager (auto/systemd/supervisor/none)", "auto");
7432
- const noOpen = (await reader.question("Skip opening the confirmation page? [y/N]: ")).trim().toLowerCase();
7433
- const argumentsList = [
7434
- "connect",
7435
- "--code",
7436
- code,
7437
- "--root",
7438
- root,
7439
- "--service-manager",
7440
- serviceManager
7441
- ];
7442
- appendOption(argumentsList, "--relay", relay);
7443
- appendOption(argumentsList, "--name", name);
7444
- if (noOpen === "y" || noOpen === "yes") {
7445
- argumentsList.push("--no-open");
7446
- }
7447
- return argumentsList;
7448
- }
7449
- async buildDisconnectArguments(reader) {
7450
- const selected = this.snapshot.connections[this.state.selectedRowIndex];
7451
- const connectionId = await questionWithDefault(reader, "Connection ID", selected?.connectionId ?? "");
7452
- if (connectionId.length === 0) {
7453
- throw new Error("Connection ID is required");
7454
- }
7455
- const confirmed = (await reader.question(`Disconnect ${connectionId}? [y/N]: `)).trim().toLowerCase();
7456
- if (confirmed !== "y" && confirmed !== "yes") {
7457
- return [];
7458
- }
7459
- const localOnly = (await reader.question("Remove local state without contacting Moxt? [y/N]: ")).trim().toLowerCase();
7460
- const argumentsList = ["disconnect", "--connection", connectionId];
7461
- if (localOnly === "y" || localOnly === "yes") {
7462
- argumentsList.push("--local-only");
7463
- }
7464
- return argumentsList;
7465
- }
7466
- stop() {
7467
- if (this.stopped) {
7468
- return;
7469
- }
7470
- this.stopped = true;
7471
- this.resolveRun?.();
7472
- }
7473
- };
7717
+ async function installLaunchAgent(store, options, runtime) {
7718
+ const path4 = launchAgentPath();
7719
+ await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
7720
+ const programArguments = [
7721
+ options.nodePath,
7722
+ (0, import_node_path7.resolve)(options.entrypointPath),
7723
+ ...options.commandArguments
7724
+ ];
7725
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
7726
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
7727
+ <plist version="1.0">
7728
+ <dict>
7729
+ <key>Label</key>
7730
+ <string>${launchAgentLabel}</string>
7731
+ <key>ProgramArguments</key>
7732
+ <array>
7733
+ ${programArguments.map((argument) => ` <string>${escapeXml(argument)}</string>`).join("\n")}
7734
+ </array>
7735
+ <key>RunAtLoad</key>
7736
+ <true/>
7737
+ <key>KeepAlive</key>
7738
+ <true/>
7739
+ <key>EnvironmentVariables</key>
7740
+ <dict>
7741
+ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeXml(name)}</key>
7742
+ <string>${escapeXml(value)}</string>`).join("\n")}
7743
+ </dict>
7744
+ <key>ProcessType</key>
7745
+ <string>Background</string>
7746
+ <key>StandardOutPath</key>
7747
+ <string>${escapeXml(store.runtimeLogPath())}</string>
7748
+ <key>StandardErrorPath</key>
7749
+ <string>${escapeXml(store.runtimeErrorLogPath())}</string>
7750
+ </dict>
7751
+ </plist>
7752
+ `;
7753
+ await (0, import_promises10.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
7754
+ const domain = `gui/${process.getuid?.() ?? 0}`;
7755
+ await runCommandIgnoringFailure(runtime, "launchctl", [
7756
+ "bootout",
7757
+ domain,
7758
+ path4
7759
+ ]);
7760
+ await runtime.run("launchctl", ["bootstrap", domain, path4]);
7761
+ await runtime.run("launchctl", [
7762
+ "kickstart",
7763
+ "-k",
7764
+ `${domain}/${launchAgentLabel}`
7765
+ ]);
7766
+ }
7767
+ async function installSystemdUserService(store, options, runtime) {
7768
+ const path4 = systemdUnitPath();
7769
+ await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
7770
+ const command = [
7771
+ options.nodePath,
7772
+ (0, import_node_path7.resolve)(options.entrypointPath),
7773
+ ...options.commandArguments
7774
+ ].map(escapeSystemdArgument).join(" ");
7775
+ const unit = `[Unit]
7776
+ Description=Moxt Machine Connector
7777
+ After=network-online.target
7778
+ Wants=network-online.target
7779
+
7780
+ [Service]
7781
+ Type=simple
7782
+ ExecStart=${command}
7783
+ Restart=always
7784
+ RestartSec=3
7785
+ NoNewPrivileges=true
7786
+ ${Object.entries(options.environment).map(([name, value]) => `Environment=${escapeSystemdEnvironment(name)}=${escapeSystemdEnvironment(value)}`).join("\n")}
7787
+
7788
+ [Install]
7789
+ WantedBy=default.target
7790
+ `;
7791
+ await (0, import_promises10.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
7792
+ await runtime.run("systemctl", ["--user", "daemon-reload"]);
7793
+ await runtime.run("systemctl", [
7794
+ "--user",
7795
+ "enable",
7796
+ "--now",
7797
+ "moxt-machine-connector.service"
7798
+ ]);
7799
+ await runCommandIgnoringFailure(runtime, "loginctl", [
7800
+ "enable-linger",
7801
+ (0, import_node_os5.userInfo)().username
7802
+ ]);
7803
+ }
7804
+ async function installSupervisorUserService(store, options, runtime) {
7805
+ const directory = supervisorDirectory(store);
7806
+ const configPath = supervisorConfigPath(store);
7807
+ await (0, import_promises10.mkdir)(directory, { recursive: true, mode: 448 });
7808
+ await (0, import_promises10.writeFile)(configPath, createSupervisorConfiguration(store, options), {
7809
+ encoding: "utf8",
7810
+ mode: 384
7811
+ });
7812
+ const supervisorWasRunning = await supervisorIsRunning(store, runtime);
7813
+ if (!supervisorWasRunning) {
7814
+ await (0, import_promises10.rm)(supervisorSocketPath(store), { force: true });
7815
+ await (0, import_promises10.rm)(supervisorPidPath(store), { force: true });
7816
+ await runtime.run("supervisord", ["-c", configPath]);
7817
+ await waitForSupervisorControl(store, runtime);
7818
+ return;
7474
7819
  }
7475
- });
7820
+ await reloadSupervisorConfiguration(store, runtime);
7821
+ }
7822
+ function createSupervisorConfiguration(store, options) {
7823
+ const command = [
7824
+ options.nodePath,
7825
+ (0, import_node_path7.resolve)(options.entrypointPath),
7826
+ ...options.commandArguments
7827
+ ].map(escapeSupervisorArgument).join(" ");
7828
+ const environment = Object.entries(options.environment).map(([name, value]) => `${name}="${escapeSupervisorEnvironment(value)}"`).join(",");
7829
+ return `[unix_http_server]
7830
+ file=${supervisorSocketPath(store)}
7831
+ chmod=0600
7476
7832
 
7477
- // ../machine-connector/dist/runtime/device-identity.js
7478
- async function ensureMachineIdentity(store) {
7479
- const existingIdentity = (await store.readIdentity()).value;
7480
- const existingPrivateKey = (await store.readPrivateKey()).value;
7481
- if (existingIdentity && existingPrivateKey) {
7482
- return {
7483
- identity: existingIdentity,
7484
- privateKeyPem: existingPrivateKey
7485
- };
7833
+ [supervisord]
7834
+ logfile=${supervisorLogPath(store)}
7835
+ pidfile=${supervisorPidPath(store)}
7836
+ childlogdir=${supervisorDirectory(store)}
7837
+ nodaemon=false
7838
+ minfds=1024
7839
+ minprocs=200
7840
+
7841
+ [rpcinterface:supervisor]
7842
+ supervisor.rpcinterface_factory=supervisor.rpcinterface:make_main_rpcinterface
7843
+
7844
+ [supervisorctl]
7845
+ serverurl=unix://${supervisorSocketPath(store)}
7846
+
7847
+ [program:${supervisorProgramName}]
7848
+ command=${command}
7849
+ directory=${escapeSupervisorPath((0, import_node_path7.dirname)((0, import_node_path7.resolve)(options.entrypointPath)))}
7850
+ environment=${environment}
7851
+ autostart=true
7852
+ autorestart=true
7853
+ startsecs=3
7854
+ startretries=10
7855
+ stopsignal=TERM
7856
+ stopasgroup=true
7857
+ killasgroup=true
7858
+ stopwaitsecs=20
7859
+ stdout_logfile=${escapeSupervisorPath(store.runtimeLogPath())}
7860
+ stderr_logfile=${escapeSupervisorPath(store.runtimeErrorLogPath())}
7861
+ stdout_logfile_maxbytes=20MB
7862
+ stderr_logfile_maxbytes=20MB
7863
+ stdout_logfile_backups=3
7864
+ stderr_logfile_backups=3
7865
+ `;
7866
+ }
7867
+ async function restartSupervisorUserService(store, runtime) {
7868
+ const configPath = supervisorConfigPath(store);
7869
+ if (!await supervisorIsRunning(store, runtime)) {
7870
+ await (0, import_promises10.rm)(supervisorSocketPath(store), { force: true });
7871
+ await (0, import_promises10.rm)(supervisorPidPath(store), { force: true });
7872
+ await runtime.run("supervisord", ["-c", configPath]);
7873
+ await waitForSupervisorControl(store, runtime);
7874
+ return;
7875
+ }
7876
+ try {
7877
+ await runtime.run("supervisorctl", [
7878
+ "-c",
7879
+ configPath,
7880
+ "restart",
7881
+ supervisorProgramName
7882
+ ]);
7883
+ } catch {
7884
+ await runtime.run("supervisorctl", [
7885
+ "-c",
7886
+ configPath,
7887
+ "start",
7888
+ supervisorProgramName
7889
+ ]);
7486
7890
  }
7487
- const keyPair = await generateKeyPairAsync("rsa", {
7488
- modulusLength: 4096,
7489
- privateKeyEncoding: {
7490
- format: "pem",
7491
- type: "pkcs8"
7492
- },
7493
- publicKeyEncoding: {
7494
- format: "pem",
7495
- type: "spki"
7496
- }
7497
- });
7498
- const identity = {
7499
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
7500
- deviceKeyFingerprint: (0, import_node_crypto5.createHash)("sha256").update(keyPair.publicKey, "utf8").digest("hex"),
7501
- publicKeyPem: keyPair.publicKey
7502
- };
7503
- await store.writePrivateKey(keyPair.privateKey);
7504
- await store.writeIdentity(identity);
7505
- return {
7506
- identity,
7507
- privateKeyPem: keyPair.privateKey
7508
- };
7509
7891
  }
7510
- function decryptPairingCredentials(privateKeyPem, encryptedCredentials) {
7511
- const serializedEnvelope = Buffer.from(encryptedCredentials, "base64url").toString("utf8");
7512
- const envelope = JSON.parse(serializedEnvelope);
7513
- if (envelope.version !== 1 || envelope.algorithm !== "RSA-OAEP-256+A256GCM") {
7514
- throw new Error("Unsupported Local Machine credentials envelope");
7892
+ async function reloadSupervisorConfiguration(store, runtime) {
7893
+ const configPath = supervisorConfigPath(store);
7894
+ const processIdBeforeStop = await runServiceProbe(runtime, "supervisorctl", [
7895
+ "-c",
7896
+ configPath,
7897
+ "pid",
7898
+ supervisorProgramName
7899
+ ]);
7900
+ if ((parseProcessId(processIdBeforeStop.stdout) ?? 0) > 0) {
7901
+ await runtime.run("supervisorctl", [
7902
+ "-c",
7903
+ configPath,
7904
+ "stop",
7905
+ supervisorProgramName
7906
+ ]);
7907
+ const processIdAfterStop = await runServiceProbe(runtime, "supervisorctl", ["-c", configPath, "pid", supervisorProgramName]);
7908
+ if ((parseProcessId(processIdAfterStop.stdout) ?? 0) > 0) {
7909
+ throw new Error("Supervisor did not stop the existing Moxt Machine Connector process");
7910
+ }
7515
7911
  }
7516
- const encryptionKey = (0, import_node_crypto5.privateDecrypt)({
7517
- key: privateKeyPem,
7518
- oaepHash: "sha256",
7519
- padding: import_node_crypto5.constants.RSA_PKCS1_OAEP_PADDING
7520
- }, Buffer.from(envelope.encryptedKey, "base64url"));
7521
- const decipher = (0, import_node_crypto5.createDecipheriv)("aes-256-gcm", encryptionKey, Buffer.from(envelope.initializationVector, "base64url"));
7522
- decipher.setAuthTag(Buffer.from(envelope.authenticationTag, "base64url"));
7523
- const decrypted = Buffer.concat([
7524
- decipher.update(Buffer.from(envelope.ciphertext, "base64url")),
7525
- decipher.final()
7912
+ await runtime.run("supervisorctl", ["-c", configPath, "reread"]);
7913
+ await runtime.run("supervisorctl", ["-c", configPath, "update"]);
7914
+ const processId = await runServiceProbe(runtime, "supervisorctl", [
7915
+ "-c",
7916
+ configPath,
7917
+ "pid",
7918
+ supervisorProgramName
7919
+ ]);
7920
+ if ((parseProcessId(processId.stdout) ?? 0) > 0)
7921
+ return;
7922
+ await runtime.run("supervisorctl", [
7923
+ "-c",
7924
+ configPath,
7925
+ "start",
7926
+ supervisorProgramName
7526
7927
  ]);
7527
- return JSON.parse(decrypted.toString("utf8"));
7528
7928
  }
7529
- var import_node_crypto5, import_node_util3, generateKeyPairAsync;
7530
- var init_device_identity = __esm({
7531
- "../machine-connector/dist/runtime/device-identity.js"() {
7532
- "use strict";
7533
- init_cjs_shims();
7534
- import_node_crypto5 = require("crypto");
7535
- import_node_util3 = require("util");
7536
- generateKeyPairAsync = (0, import_node_util3.promisify)(import_node_crypto5.generateKeyPair);
7537
- }
7538
- });
7539
-
7540
- // ../machine-connector/dist/runtime/pairing.js
7541
- async function pairMachine(store, options) {
7542
- await store.initialize();
7543
- const canonicalRoot = await store.getCanonicalRoot(options.rootPath);
7544
- const identity = await ensureMachineIdentity(store);
7545
- const machineName = options.machineName ?? (0, import_node_os5.hostname)();
7546
- const operatingSystem = getOperatingSystem();
7547
- const rootHandle = (0, import_node_crypto6.createHash)("sha256").update(identity.identity.deviceKeyFingerprint, "utf8").update("\0").update(canonicalRoot, "utf8").digest("base64url");
7548
- const client = new PairingRelayClient(options.relayOrigin);
7549
- const proposal = await client.propose({
7550
- connectionCode: options.connectionCode,
7551
- connectorVersion,
7552
- devicePublicKey: identity.identity.publicKeyPem,
7553
- machineName,
7554
- operatingSystem,
7555
- protocolVersion: machineProtocolVersion,
7556
- rootDisplayName: (0, import_node_path6.basename)(canonicalRoot),
7557
- rootHandle
7558
- });
7559
- options.onConfirmation?.(proposal.confirmationUrl);
7560
- if (!options.noOpen) {
7561
- openBrowser(proposal.confirmationUrl);
7562
- }
7563
- while (Date.parse(proposal.expiresAt) > Date.now()) {
7564
- const status = await client.pollStatus({
7565
- pairingIntentId: proposal.pairingIntentId,
7566
- pollingToken: proposal.pollingToken
7567
- });
7568
- if (status.status === connectedPairingStatus) {
7569
- if (!status.encryptedCredentials) {
7570
- throw new Error("Pairing completed without encrypted Connector credentials");
7571
- }
7572
- const credentials = decryptPairingCredentials(identity.privateKeyPem, status.encryptedCredentials);
7573
- const connection = {
7574
- accessToken: credentials.accessToken,
7575
- accessTokenExpiresAt: credentials.accessTokenExpiresAt,
7576
- connectionId: credentials.connectionId,
7577
- connectorVersion,
7578
- heartbeatIntervalSeconds: credentials.heartbeatIntervalSeconds,
7579
- machineId: credentials.machineId,
7580
- machineName,
7581
- operatingSystem,
7582
- refreshToken: credentials.refreshToken,
7583
- relayOrigin: options.relayOrigin.replace(/\/+$/, ""),
7584
- rootDisplayName: (0, import_node_path6.basename)(canonicalRoot),
7585
- rootHandle,
7586
- rootPath: canonicalRoot,
7587
- targetId: credentials.targetId,
7588
- targetKind: credentials.targetKind,
7589
- workspaceId: credentials.workspaceId
7590
- };
7591
- await store.saveConnection(connection);
7592
- return {
7593
- confirmationUrl: proposal.confirmationUrl,
7594
- connection
7595
- };
7596
- }
7597
- if (status.status === rejectedPairingStatus || status.status === expiredPairingStatus) {
7598
- throw new Error(status.status === rejectedPairingStatus ? "Local Machine pairing was rejected" : "Local Machine pairing expired");
7929
+ async function supervisorIsRunning(store, runtime) {
7930
+ return await commandSucceeds(runtime, "supervisorctl", [
7931
+ "-c",
7932
+ supervisorConfigPath(store),
7933
+ "pid"
7934
+ ]);
7935
+ }
7936
+ async function waitForSupervisorControl(store, runtime) {
7937
+ const deadline = Date.now() + 5e3;
7938
+ while (Date.now() < deadline) {
7939
+ if (await supervisorIsRunning(store, runtime)) {
7940
+ return;
7599
7941
  }
7600
- await delay3(pairingPollMilliseconds);
7942
+ await delay5(100);
7601
7943
  }
7602
- throw new Error("Local Machine pairing expired");
7944
+ throw new Error("Supervisor did not become ready within 5 seconds");
7603
7945
  }
7604
- function getOperatingSystem() {
7605
- if ((0, import_node_os5.platform)() === "darwin") {
7606
- return MachineOperatingSystem.MacOS;
7946
+ function launchAgentPath() {
7947
+ return (0, import_node_path7.join)(process.env.HOME ?? (0, import_node_os5.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
7948
+ }
7949
+ function systemdUnitPath() {
7950
+ const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path7.join)(process.env.HOME ?? (0, import_node_os5.homedir)(), ".config");
7951
+ return (0, import_node_path7.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
7952
+ }
7953
+ function supervisorDirectory(store) {
7954
+ return (0, import_node_path7.join)(store.baseDirectory, "supervisor");
7955
+ }
7956
+ function supervisorConfigPath(store) {
7957
+ return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.conf");
7958
+ }
7959
+ function supervisorSocketPath(store) {
7960
+ return (0, import_node_path7.join)(supervisorDirectory(store), "supervisor.sock");
7961
+ }
7962
+ function supervisorPidPath(store) {
7963
+ return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.pid");
7964
+ }
7965
+ function supervisorLogPath(store) {
7966
+ return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.log");
7967
+ }
7968
+ async function commandSucceeds(runtime, command, argumentsList) {
7969
+ try {
7970
+ await runServiceProbe(runtime, command, argumentsList);
7971
+ return true;
7972
+ } catch {
7973
+ return false;
7607
7974
  }
7608
- if ((0, import_node_os5.platform)() === "linux") {
7609
- return MachineOperatingSystem.Linux;
7975
+ }
7976
+ async function runServiceProbe(runtime, command, argumentsList) {
7977
+ return await runtime.run(command, argumentsList, {
7978
+ timeoutMilliseconds: serviceManagerProbeTimeoutMilliseconds
7979
+ });
7980
+ }
7981
+ async function runCommandIgnoringFailure(runtime, command, argumentsList) {
7982
+ try {
7983
+ await runtime.run(command, argumentsList);
7984
+ } catch {
7985
+ return;
7610
7986
  }
7611
- return MachineOperatingSystem.Windows;
7612
7987
  }
7613
- function openBrowser(url) {
7614
- const command = (0, import_node_os5.platform)() === "darwin" ? "open" : "xdg-open";
7615
- const child = (0, import_node_child_process3.execFile)(command, [url], () => void 0);
7616
- child.unref();
7988
+ async function uninstallManagerIgnoringFailure(manager, store, runtime) {
7989
+ try {
7990
+ await uninstallManager(manager, store, runtime);
7991
+ } catch {
7992
+ return;
7993
+ }
7617
7994
  }
7618
- function delay3(milliseconds) {
7995
+ function escapeXml(value) {
7996
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
7997
+ }
7998
+ function escapeSystemdArgument(value) {
7999
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
8000
+ }
8001
+ function escapeSystemdEnvironment(value) {
8002
+ return value.replaceAll("%", "%%").replaceAll(" ", "\\x20");
8003
+ }
8004
+ function escapeSupervisorArgument(value) {
8005
+ return `"${escapeSupervisorValue(value)}"`;
8006
+ }
8007
+ function escapeSupervisorEnvironment(value) {
8008
+ return escapeSupervisorValue(value);
8009
+ }
8010
+ function escapeSupervisorPath(value) {
8011
+ return value.replaceAll("%", "%%");
8012
+ }
8013
+ function escapeSupervisorValue(value) {
8014
+ return value.replaceAll("%", "%%").replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n");
8015
+ }
8016
+ function errorMessage(error) {
8017
+ return error instanceof Error ? error.message : String(error);
8018
+ }
8019
+ function isNodeErrorCode4(error, expectedCode) {
8020
+ return error instanceof Error && "code" in error && error.code === expectedCode;
8021
+ }
8022
+ function delay5(milliseconds) {
7619
8023
  return new Promise((resolvePromise) => {
7620
8024
  setTimeout(resolvePromise, milliseconds);
7621
8025
  });
7622
8026
  }
7623
- var import_node_child_process3, import_node_crypto6, import_node_os5, import_node_path6, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
7624
- var init_pairing = __esm({
7625
- "../machine-connector/dist/runtime/pairing.js"() {
8027
+ var import_node_child_process2, import_promises10, import_node_os5, import_node_path7, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerProbeTimeoutMilliseconds, serviceManagerMutationTimeoutMilliseconds, supervisorProgramName, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
8028
+ var init_service_manager = __esm({
8029
+ "../machine-connector/dist/runtime/service-manager.js"() {
7626
8030
  "use strict";
7627
8031
  init_cjs_shims();
7628
- import_node_child_process3 = require("child_process");
7629
- import_node_crypto6 = require("crypto");
8032
+ import_node_child_process2 = require("child_process");
8033
+ import_promises10 = require("fs/promises");
7630
8034
  import_node_os5 = require("os");
7631
- import_node_path6 = require("path");
7632
- init_contracts();
7633
- init_version();
7634
- init_enums();
7635
- init_device_identity();
7636
- init_relay_client();
7637
- connectedPairingStatus = 3;
7638
- rejectedPairingStatus = 4;
7639
- expiredPairingStatus = 5;
7640
- pairingPollMilliseconds = 2e3;
8035
+ import_node_path7 = require("path");
8036
+ import_node_util2 = require("util");
8037
+ execFileAsync = (0, import_node_util2.promisify)(import_node_child_process2.execFile);
8038
+ launchAgentLabel = "ai.moxt.machine-connector";
8039
+ serviceManagerProbeTimeoutMilliseconds = 5e3;
8040
+ serviceManagerMutationTimeoutMilliseconds = 3e4;
8041
+ supervisorProgramName = "moxt-machine-connector";
8042
+ (function(ServiceManagerPreference2) {
8043
+ ServiceManagerPreference2["Auto"] = "auto";
8044
+ ServiceManagerPreference2["None"] = "none";
8045
+ ServiceManagerPreference2["Supervisor"] = "supervisor";
8046
+ ServiceManagerPreference2["Systemd"] = "systemd";
8047
+ })(ServiceManagerPreference || (ServiceManagerPreference = {}));
8048
+ (function(UserServiceManager2) {
8049
+ UserServiceManager2["Launchd"] = "launchd";
8050
+ UserServiceManager2["None"] = "none";
8051
+ UserServiceManager2["Supervisor"] = "supervisor";
8052
+ UserServiceManager2["Systemd"] = "systemd";
8053
+ })(UserServiceManager || (UserServiceManager = {}));
8054
+ defaultServiceManagerRuntime = {
8055
+ operatingSystem: (0, import_node_os5.platform)(),
8056
+ async run(command, argumentsList, options) {
8057
+ const result = await execFileAsync(command, argumentsList, {
8058
+ encoding: "utf8",
8059
+ killSignal: "SIGKILL",
8060
+ timeout: options?.timeoutMilliseconds ?? serviceManagerMutationTimeoutMilliseconds
8061
+ });
8062
+ return {
8063
+ stderr: String(result.stderr),
8064
+ stdout: String(result.stdout)
8065
+ };
8066
+ }
8067
+ };
7641
8068
  }
7642
8069
  });
7643
8070
 
7644
- // ../machine-connector/dist/runtime/service-manager.js
7645
- function parseServiceManagerPreference(value) {
7646
- if (value === ServiceManagerPreference.Auto) {
7647
- return ServiceManagerPreference.Auto;
8071
+ // ../machine-connector/dist/runtime/daemon-reconcile.js
8072
+ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()) {
8073
+ await store.initialize();
8074
+ const lock = await ProcessLock.acquire(store.reconcileLockPath(), {
8075
+ timeoutMilliseconds: reconcileTimeoutMilliseconds
8076
+ });
8077
+ if (!lock)
8078
+ return { outcome: DaemonReconcileOutcome.Skipped };
8079
+ try {
8080
+ const initial = await reachableRuntimeStatus(store);
8081
+ if (!initial)
8082
+ return { outcome: DaemonReconcileOutcome.Skipped };
8083
+ const manager = await recordedServiceManager(store);
8084
+ if (manager === UserServiceManager.None) {
8085
+ return { outcome: DaemonReconcileOutcome.Skipped };
8086
+ }
8087
+ if (initial.cliVersion === options.cliVersion) {
8088
+ return { manager, outcome: DaemonReconcileOutcome.Skipped };
8089
+ }
8090
+ let managerOwnsProcess;
8091
+ try {
8092
+ managerOwnsProcess = await managedServiceOwnsProcess(manager, initial.pid, store);
8093
+ } catch (error) {
8094
+ throw new DaemonRefreshError("ownership", `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage2(error)}`, { cause: error });
8095
+ }
8096
+ if (!managerOwnsProcess) {
8097
+ return { outcome: DaemonReconcileOutcome.Skipped };
8098
+ }
8099
+ try {
8100
+ await validateCliEntrypoint(options, store);
8101
+ } catch (error) {
8102
+ throw new DaemonRefreshError("validation", errorMessage2(error), {
8103
+ cause: error
8104
+ });
8105
+ }
8106
+ if (initial.activeJobs.length > 0) {
8107
+ options.onActiveJobs?.(initial.activeJobs.length);
8108
+ }
8109
+ let refresh;
8110
+ try {
8111
+ refresh = await refreshManagedUserService(store, {
8112
+ commandArguments: [...options.commandArguments],
8113
+ entrypointPath: (0, import_node_path8.resolve)(options.entrypointPath),
8114
+ environment: { ...options.environment },
8115
+ nodePath: (0, import_node_path8.resolve)(options.nodePath)
8116
+ });
8117
+ if (!refresh) {
8118
+ throw new Error("The Connector service is no longer managed by Moxt");
8119
+ }
8120
+ } catch (error) {
8121
+ throw new DaemonRefreshError("restart", error instanceof Error ? error.message : String(error), { cause: error });
8122
+ }
8123
+ const deadline = Date.now() + reconcileTimeoutMilliseconds;
8124
+ while (Date.now() < deadline) {
8125
+ const current2 = await reachableRuntimeStatus(store);
8126
+ if (current2?.cliVersion === options.cliVersion && current2.connectorInstanceId !== initial.connectorInstanceId) {
8127
+ return { manager, outcome: DaemonReconcileOutcome.Restarted };
8128
+ }
8129
+ await delay6(100);
8130
+ }
8131
+ const verificationMessage = `managed daemon did not report CLI ${options.cliVersion} with a new instance ID`;
8132
+ try {
8133
+ await refresh.rollback();
8134
+ } catch (error) {
8135
+ throw new DaemonRefreshError("verification", `${verificationMessage}; restoring the previous service definition also failed: ${errorMessage2(error)}`, { cause: error });
8136
+ }
8137
+ throw new DaemonRefreshError("verification", verificationMessage);
8138
+ } finally {
8139
+ await lock.release();
7648
8140
  }
7649
- if (value === ServiceManagerPreference.Systemd) {
7650
- return ServiceManagerPreference.Systemd;
8141
+ }
8142
+ async function validateCliEntrypoint(options, store) {
8143
+ if (options.commandArguments.length !== 2 || options.commandArguments[0] !== "machine" || options.commandArguments[1] !== "daemon") {
8144
+ throw new Error("The managed daemon command must be `machine daemon`");
7651
8145
  }
7652
- if (value === ServiceManagerPreference.Supervisor) {
7653
- return ServiceManagerPreference.Supervisor;
8146
+ const nodePath = await (0, import_promises11.realpath)((0, import_node_path8.resolve)(options.nodePath));
8147
+ const entrypointPath = await (0, import_promises11.realpath)((0, import_node_path8.resolve)(options.entrypointPath));
8148
+ await (0, import_promises11.access)(nodePath, import_promises11.constants.X_OK);
8149
+ await (0, import_promises11.access)(entrypointPath, import_promises11.constants.R_OK);
8150
+ const probe = await execFileAsync2(nodePath, [entrypointPath, "--version"], {
8151
+ encoding: "utf8",
8152
+ env: {
8153
+ ...process.env,
8154
+ ...options.environment,
8155
+ MOXT_MACHINE_HOME: store.baseDirectory,
8156
+ MOXT_TELEMETRY_DISABLED: "1",
8157
+ NO_UPDATE_NOTIFIER: "1"
8158
+ },
8159
+ maxBuffer: 1024 * 1024,
8160
+ killSignal: "SIGKILL",
8161
+ timeout: 5e3
8162
+ });
8163
+ const reportedVersion = probe.stdout.trim().replace(/^v/, "");
8164
+ if (reportedVersion !== options.cliVersion) {
8165
+ throw new Error(`candidate CLI reported ${reportedVersion || "no version"} instead of ${options.cliVersion}`);
7654
8166
  }
7655
- if (value === ServiceManagerPreference.None) {
7656
- return ServiceManagerPreference.None;
8167
+ }
8168
+ async function reachableRuntimeStatus(store) {
8169
+ try {
8170
+ const response = await requestRuntimeStatus(store);
8171
+ return response.status;
8172
+ } catch {
8173
+ return void 0;
7657
8174
  }
7658
- throw new Error(`Unsupported service manager: ${value}`);
7659
8175
  }
7660
- function selectUserServiceManager(preference, capabilities) {
7661
- if (preference === ServiceManagerPreference.None) {
7662
- return {
7663
- detail: "Background service installation was explicitly disabled.",
7664
- manager: UserServiceManager.None
8176
+ function delay6(milliseconds) {
8177
+ return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
8178
+ }
8179
+ function errorMessage2(error) {
8180
+ return error instanceof Error ? error.message : String(error);
8181
+ }
8182
+ var import_node_child_process3, import_promises11, import_node_path8, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshError;
8183
+ var init_daemon_reconcile = __esm({
8184
+ "../machine-connector/dist/runtime/daemon-reconcile.js"() {
8185
+ "use strict";
8186
+ init_cjs_shims();
8187
+ import_node_child_process3 = require("child_process");
8188
+ import_promises11 = require("fs/promises");
8189
+ import_node_path8 = require("path");
8190
+ import_node_util3 = require("util");
8191
+ init_local_ipc();
8192
+ init_process_lock();
8193
+ init_service_manager();
8194
+ init_store();
8195
+ reconcileTimeoutMilliseconds = 12e3;
8196
+ execFileAsync2 = (0, import_node_util3.promisify)(import_node_child_process3.execFile);
8197
+ (function(DaemonReconcileOutcome2) {
8198
+ DaemonReconcileOutcome2["Restarted"] = "restarted";
8199
+ DaemonReconcileOutcome2["Skipped"] = "skipped";
8200
+ })(DaemonReconcileOutcome || (DaemonReconcileOutcome = {}));
8201
+ DaemonRefreshError = class extends Error {
8202
+ stage;
8203
+ constructor(stage, message, options) {
8204
+ super(message, options);
8205
+ this.stage = stage;
8206
+ this.name = "DaemonRefreshError";
8207
+ }
7665
8208
  };
7666
8209
  }
7667
- if (capabilities.operatingSystem === "darwin") {
7668
- if (preference !== ServiceManagerPreference.Auto) {
7669
- throw new Error(`${preference} service management is supported only on Linux`);
7670
- }
7671
- return {
7672
- detail: "Using the macOS LaunchAgent service manager.",
7673
- manager: UserServiceManager.Launchd
7674
- };
8210
+ });
8211
+
8212
+ // ../machine-connector/dist/runtime/doctor.js
8213
+ async function runMachineDoctor(store) {
8214
+ const checks = [];
8215
+ const connections = await store.listConnections();
8216
+ checks.push({
8217
+ detail: `${connections.length} configured connection(s)`,
8218
+ name: "configuration",
8219
+ status: connections.length > 0 ? DoctorCheckStatus.Passed : DoctorCheckStatus.Warning
8220
+ });
8221
+ try {
8222
+ const response = await requestRuntimeStatus(store);
8223
+ checks.push({
8224
+ detail: response.error ?? `PID ${response.status?.pid ?? "unknown"}`,
8225
+ name: "daemon",
8226
+ status: response.error ? DoctorCheckStatus.Failed : DoctorCheckStatus.Passed
8227
+ });
8228
+ } catch (error) {
8229
+ checks.push({
8230
+ detail: errorMessage3(error),
8231
+ name: "daemon",
8232
+ status: DoctorCheckStatus.Failed
8233
+ });
7675
8234
  }
7676
- if (capabilities.operatingSystem !== "linux") {
7677
- if (preference === ServiceManagerPreference.Auto) {
7678
- return {
7679
- detail: "No supported background service manager is available on this platform.",
7680
- manager: UserServiceManager.None
7681
- };
8235
+ for (const connection of connections) {
8236
+ try {
8237
+ await (0, import_promises12.access)(connection.rootPath, import_node_fs.constants.R_OK | import_node_fs.constants.X_OK);
8238
+ checks.push({
8239
+ detail: connection.rootPath,
8240
+ name: `root:${connection.connectionId}`,
8241
+ status: DoctorCheckStatus.Passed
8242
+ });
8243
+ } catch (error) {
8244
+ checks.push({
8245
+ detail: errorMessage3(error),
8246
+ name: `root:${connection.connectionId}`,
8247
+ status: DoctorCheckStatus.Failed
8248
+ });
7682
8249
  }
7683
- throw new Error(`${preference} service management is supported only on Linux`);
7684
- }
7685
- if (preference === ServiceManagerPreference.Systemd) {
7686
- if (!capabilities.systemdUserAvailable) {
7687
- throw new Error("The systemd user service manager is not available in this environment");
8250
+ const relayUrl = new URL(connection.relayOrigin);
8251
+ try {
8252
+ const address = await (0, import_promises13.lookup)(relayUrl.hostname);
8253
+ checks.push({
8254
+ detail: `${relayUrl.hostname} resolves to ${address.address}`,
8255
+ name: `dns:${connection.connectionId}`,
8256
+ status: DoctorCheckStatus.Passed
8257
+ });
8258
+ } catch (error) {
8259
+ checks.push({
8260
+ detail: errorMessage3(error),
8261
+ name: `dns:${connection.connectionId}`,
8262
+ status: DoctorCheckStatus.Failed
8263
+ });
7688
8264
  }
7689
- return {
7690
- detail: "Using the systemd user service manager.",
7691
- manager: UserServiceManager.Systemd
7692
- };
7693
- }
7694
- if (preference === ServiceManagerPreference.Supervisor) {
7695
- if (!capabilities.supervisorAvailable) {
7696
- throw new Error("Supervisor is not available; install supervisord and supervisorctl or choose another service manager");
8265
+ try {
8266
+ const response = await fetch(connection.relayOrigin, {
8267
+ method: "HEAD",
8268
+ signal: AbortSignal.timeout(1e4)
8269
+ });
8270
+ checks.push({
8271
+ detail: `TLS and HTTPS succeeded with status ${response.status}`,
8272
+ name: `tls:${connection.connectionId}`,
8273
+ status: DoctorCheckStatus.Passed
8274
+ });
8275
+ const serverDate = response.headers.get("date");
8276
+ const clockDifference = serverDate ? Math.abs(Date.parse(serverDate) - Date.now()) : 0;
8277
+ checks.push({
8278
+ detail: serverDate ? `${Math.round(clockDifference / 1e3)} second clock difference` : "Relay did not return a Date header",
8279
+ name: `clock:${connection.connectionId}`,
8280
+ status: serverDate && clockDifference > 3e5 ? DoctorCheckStatus.Warning : DoctorCheckStatus.Passed
8281
+ });
8282
+ } catch (error) {
8283
+ checks.push({
8284
+ detail: errorMessage3(error),
8285
+ name: `tls:${connection.connectionId}`,
8286
+ status: DoctorCheckStatus.Failed
8287
+ });
7697
8288
  }
7698
- return {
7699
- detail: "Using the Supervisor service manager.",
7700
- manager: UserServiceManager.Supervisor
7701
- };
7702
- }
7703
- if (capabilities.systemdUserAvailable) {
7704
- return {
7705
- detail: "Automatically selected the systemd user service manager.",
7706
- manager: UserServiceManager.Systemd
7707
- };
7708
- }
7709
- if (capabilities.supervisorAvailable) {
7710
- return {
7711
- detail: "Automatically selected the Supervisor service manager.",
7712
- manager: UserServiceManager.Supervisor
7713
- };
7714
8289
  }
7715
- return {
7716
- detail: "No supported background service manager is available. Pairing is complete, but the Connector must be started manually.",
7717
- manager: UserServiceManager.None
7718
- };
7719
- }
7720
- async function detectServiceManagerCapabilities(runtime = defaultServiceManagerRuntime) {
7721
- if (runtime.operatingSystem !== "linux") {
7722
- return {
7723
- operatingSystem: runtime.operatingSystem,
7724
- supervisorAvailable: false,
7725
- systemdUserAvailable: false
7726
- };
8290
+ const proxy = process.env.HTTPS_PROXY ?? process.env.https_proxy ?? process.env.ALL_PROXY ?? process.env.all_proxy;
8291
+ checks.push({
8292
+ detail: proxy ? "A process-level proxy is configured" : "Direct outbound HTTPS",
8293
+ name: "proxy",
8294
+ status: proxy ? DoctorCheckStatus.Warning : DoctorCheckStatus.Passed
8295
+ });
8296
+ checks.push({
8297
+ detail: "HTTPS long-poll is authoritative; optional WSS wakeup is not required",
8298
+ name: "transport",
8299
+ status: DoctorCheckStatus.Passed
8300
+ });
8301
+ try {
8302
+ const result = await execFileAsync3(process.env.MOXT_CODEX_PATH ?? "codex", ["--version"]);
8303
+ checks.push({
8304
+ detail: result.stdout.trim(),
8305
+ name: "codex",
8306
+ status: DoctorCheckStatus.Passed
8307
+ });
8308
+ } catch (error) {
8309
+ checks.push({
8310
+ detail: errorMessage3(error),
8311
+ name: "codex",
8312
+ status: DoctorCheckStatus.Warning
8313
+ });
7727
8314
  }
7728
- const systemdUserAvailable = await commandSucceeds(runtime, "systemctl", ["--user", "show-environment"]);
7729
- const supervisordAvailable = await commandSucceeds(runtime, "supervisord", ["--version"]);
7730
- const supervisorctlAvailable = await commandSucceeds(runtime, "supervisorctl", ["-h"]);
7731
- return {
7732
- operatingSystem: runtime.operatingSystem,
7733
- supervisorAvailable: supervisordAvailable && supervisorctlAvailable,
7734
- systemdUserAvailable
7735
- };
7736
- }
7737
- async function validateServiceManagerPreference(preference, runtime = defaultServiceManagerRuntime) {
7738
- if (preference === ServiceManagerPreference.None) {
7739
- return selectUserServiceManager(preference, {
7740
- operatingSystem: runtime.operatingSystem,
7741
- supervisorAvailable: false,
7742
- systemdUserAvailable: false
8315
+ try {
8316
+ const result = await execFileAsync3(process.env.MOXT_CLAUDE_PATH ?? "claude", ["--version"]);
8317
+ checks.push({
8318
+ detail: result.stdout.trim(),
8319
+ name: "claude",
8320
+ status: DoctorCheckStatus.Passed
8321
+ });
8322
+ } catch (error) {
8323
+ checks.push({
8324
+ detail: errorMessage3(error),
8325
+ name: "claude",
8326
+ status: DoctorCheckStatus.Warning
7743
8327
  });
7744
8328
  }
7745
- const capabilities = await detectServiceManagerCapabilities(runtime);
7746
- return selectUserServiceManager(preference, capabilities);
8329
+ return checks;
7747
8330
  }
7748
- async function installUserService(store, request2, runtime = defaultServiceManagerRuntime) {
7749
- if (request2.preference === ServiceManagerPreference.None) {
7750
- const configuredManager = await readStoredServiceManager(store);
7751
- if (configuredManager !== UserServiceManager.None) {
7752
- await uninstallManager(configuredManager, store, runtime);
7753
- }
7754
- await persistServiceManager(store, UserServiceManager.None);
7755
- return {
7756
- detail: "Background service installation was explicitly disabled.",
7757
- installed: false,
7758
- manager: UserServiceManager.None
7759
- };
7760
- }
7761
- const options = {
7762
- ...request2.options,
7763
- environment: {
7764
- ...createServiceEnvironment(request2.options),
7765
- MOXT_MACHINE_HOME: store.baseDirectory
7766
- }
7767
- };
7768
- const capabilities = await detectServiceManagerCapabilities(runtime);
7769
- const selection = selectUserServiceManager(request2.preference, capabilities);
7770
- if (selection.manager === UserServiceManager.None) {
7771
- await persistServiceManager(store, UserServiceManager.None);
7772
- return {
7773
- detail: selection.detail,
7774
- installed: false,
7775
- manager: UserServiceManager.None
7776
- };
7777
- }
7778
- if (request2.preference !== ServiceManagerPreference.Auto) {
7779
- await replaceConfiguredManager(store, selection.manager, options, runtime);
7780
- return {
7781
- detail: selection.detail,
7782
- installed: true,
7783
- manager: selection.manager
7784
- };
8331
+ function errorMessage3(error) {
8332
+ return error instanceof Error ? error.message : String(error);
8333
+ }
8334
+ var import_node_child_process4, import_promises12, import_node_fs, import_promises13, import_node_util4, execFileAsync3, DoctorCheckStatus;
8335
+ var init_doctor = __esm({
8336
+ "../machine-connector/dist/runtime/doctor.js"() {
8337
+ "use strict";
8338
+ init_cjs_shims();
8339
+ import_node_child_process4 = require("child_process");
8340
+ import_promises12 = require("fs/promises");
8341
+ import_node_fs = require("fs");
8342
+ import_promises13 = require("dns/promises");
8343
+ import_node_util4 = require("util");
8344
+ init_local_ipc();
8345
+ execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process4.execFile);
8346
+ (function(DoctorCheckStatus2) {
8347
+ DoctorCheckStatus2["Failed"] = "failed";
8348
+ DoctorCheckStatus2["Passed"] = "passed";
8349
+ DoctorCheckStatus2["Warning"] = "warning";
8350
+ })(DoctorCheckStatus || (DoctorCheckStatus = {}));
7785
8351
  }
7786
- const candidates = await automaticManagerCandidates(store, capabilities);
7787
- const failures = [];
7788
- for (const manager of candidates) {
7789
- try {
7790
- await replaceConfiguredManager(store, manager, options, runtime);
7791
- return {
7792
- detail: automaticSelectionDetail(manager),
7793
- installed: true,
7794
- manager
7795
- };
7796
- } catch (error) {
7797
- failures.push(`${manager}: ${error instanceof Error ? error.message : String(error)}`);
7798
- await uninstallManagerIgnoringFailure(manager, store, runtime);
8352
+ });
8353
+
8354
+ // ../machine-connector/dist/runtime/machine-manager.js
8355
+ function machineManagerActions() {
8356
+ return [
8357
+ {
8358
+ action: MachineManagerAction.Refresh,
8359
+ label: "Refresh now"
8360
+ },
8361
+ {
8362
+ action: MachineManagerAction.Connect,
8363
+ label: "Pair a new machine connection"
8364
+ },
8365
+ {
8366
+ action: MachineManagerAction.Disconnect,
8367
+ label: "Disconnect the selected connection"
8368
+ },
8369
+ {
8370
+ action: MachineManagerAction.Doctor,
8371
+ label: "Run diagnostics"
8372
+ },
8373
+ {
8374
+ action: MachineManagerAction.Logs,
8375
+ label: "Open recent logs"
8376
+ },
8377
+ {
8378
+ action: MachineManagerAction.ServiceInstall,
8379
+ label: "Install the Connector service"
8380
+ },
8381
+ {
8382
+ action: MachineManagerAction.ServiceRestart,
8383
+ label: "Restart the Connector service"
8384
+ },
8385
+ {
8386
+ action: MachineManagerAction.ServiceStop,
8387
+ label: "Stop the Connector service"
8388
+ },
8389
+ {
8390
+ action: MachineManagerAction.ServiceUninstall,
8391
+ label: "Uninstall the Connector service"
8392
+ },
8393
+ {
8394
+ action: MachineManagerAction.Quit,
8395
+ label: "Quit"
7799
8396
  }
8397
+ ];
8398
+ }
8399
+ function ensureInteractiveTerminal(inputIsTty, outputIsTty) {
8400
+ if (!inputIsTty || !outputIsTty) {
8401
+ throw new Error("moxt machine manager requires an interactive TTY. Use `moxt machine status`, `logs`, or `doctor` in non-interactive scripts.");
7800
8402
  }
7801
- await persistServiceManager(store, UserServiceManager.None);
7802
- return {
7803
- detail: failures.length === 0 ? selection.detail : `Automatic background service setup failed (${failures.join("; ")}). Pairing is complete, but the Connector must be started manually.`,
7804
- installed: false,
7805
- manager: UserServiceManager.None
7806
- };
7807
8403
  }
7808
- function createServiceEnvironment(options) {
7809
- const inheritedPath = options.environment.PATH ?? process.env.PATH ?? "";
7810
- const nodeDirectory = (0, import_node_path7.dirname)(options.nodePath);
7811
- const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path7.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
8404
+ async function collectMachineManagerSnapshot(store, depth) {
8405
+ const connections = await store.listConnections();
8406
+ const jobs = await store.listJobs();
8407
+ const serviceManager = (await store.readServiceManager()).value;
8408
+ const runtime = {};
8409
+ try {
8410
+ runtime.value = (await requestRuntimeStatus(store)).status;
8411
+ } catch {
8412
+ runtime.value = void 0;
8413
+ }
8414
+ const checks = depth === MachineManagerSnapshotDepth.WithDoctor ? await runMachineDoctor(store) : [];
7812
8415
  return {
7813
- ...options.environment,
7814
- HOME: options.environment.HOME ?? process.env.HOME ?? (0, import_node_os6.homedir)(),
7815
- PATH: pathEntries.join(import_node_path7.delimiter)
8416
+ checks,
8417
+ connections: connections.map(toManagerConnection),
8418
+ jobs: jobs.map(toManagerJob).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
8419
+ logLines: await readRecentLogLines(store),
8420
+ refreshedAt: (/* @__PURE__ */ new Date()).toISOString(),
8421
+ runtime: runtime.value,
8422
+ serviceManager: serviceManager?.manager
7816
8423
  };
7817
8424
  }
7818
- async function restartUserService(store, runtime = defaultServiceManagerRuntime) {
7819
- const manager = await configuredServiceManager(store, runtime);
7820
- await restartManager(manager, store, runtime);
7821
- return manager;
7822
- }
7823
- async function stopUserService(store, runtime = defaultServiceManagerRuntime) {
7824
- const manager = await configuredServiceManager(store, runtime);
7825
- await stopManager(manager, store, runtime);
7826
- return manager;
7827
- }
7828
- async function uninstallUserService(store, runtime = defaultServiceManagerRuntime) {
7829
- const manager = await configuredServiceManager(store, runtime);
7830
- await uninstallManager(manager, store, runtime);
7831
- await store.removeServiceManager();
7832
- return manager;
7833
- }
7834
- async function automaticManagerCandidates(store, capabilities) {
7835
- const candidates = [];
7836
- const storedManager = await readStoredServiceManager(store);
7837
- if (storedManager !== UserServiceManager.None && managerIsAvailable(storedManager, capabilities)) {
7838
- candidates.push(storedManager);
7839
- }
7840
- if (capabilities.operatingSystem === "darwin" && !candidates.includes(UserServiceManager.Launchd)) {
7841
- candidates.push(UserServiceManager.Launchd);
7842
- }
7843
- if (capabilities.systemdUserAvailable && !candidates.includes(UserServiceManager.Systemd)) {
7844
- candidates.push(UserServiceManager.Systemd);
8425
+ function renderMachineManager(snapshot, state, requestedWidth, requestedHeight) {
8426
+ const width = Math.max(24, requestedWidth);
8427
+ const height = Math.max(8, requestedHeight);
8428
+ const lines = [];
8429
+ const online = snapshot.runtime !== void 0;
8430
+ lines.push(styledLine(` MOXT MACHINE MANAGER ${online ? "ONLINE" : "OFFLINE"} ${snapshot.serviceManager ?? "no service"}`, width, styleHeader));
8431
+ lines.push(fitLine(renderTabs(state.view), width));
8432
+ lines.push(repeatCharacter("\u2500", width));
8433
+ const contentHeight = Math.max(1, height - 5);
8434
+ const content3 = state.actionMenuOpen ? renderActions(state) : renderView(snapshot, state);
8435
+ for (const line of content3.slice(0, contentHeight)) {
8436
+ lines.push(fitLine(line, width));
7845
8437
  }
7846
- if (capabilities.supervisorAvailable && !candidates.includes(UserServiceManager.Supervisor)) {
7847
- candidates.push(UserServiceManager.Supervisor);
8438
+ while (lines.length < height - 2) {
8439
+ lines.push(" ".repeat(width));
7848
8440
  }
7849
- return candidates;
8441
+ lines.push(repeatCharacter("\u2500", width));
8442
+ lines.push(fitLine(state.message ?? "[A] Actions [Tab/1-5] View [Up/Down] Select [R] Refresh [Q] Quit", width));
8443
+ return lines.slice(0, height).join("\n");
7850
8444
  }
7851
- async function replaceConfiguredManager(store, manager, options, runtime) {
7852
- const configuredManager = await readStoredServiceManager(store);
7853
- if (configuredManager !== UserServiceManager.None && configuredManager !== manager) {
7854
- await uninstallManagerIgnoringFailure(configuredManager, store, runtime);
7855
- }
7856
- await installManager(manager, store, options, runtime);
7857
- await persistServiceManager(store, manager);
8445
+ async function runMachineManager(store, commandRunner) {
8446
+ ensureInteractiveTerminal(Boolean(process.stdin.isTTY), Boolean(process.stdout.isTTY));
8447
+ const manager = new InteractiveMachineManager(store, commandRunner);
8448
+ await manager.run();
7858
8449
  }
7859
- async function installManager(manager, store, options, runtime) {
7860
- if (manager === UserServiceManager.Launchd) {
7861
- await installLaunchAgent(store, options, runtime);
7862
- return;
7863
- }
7864
- if (manager === UserServiceManager.Systemd) {
7865
- await installSystemdUserService(store, options, runtime);
7866
- return;
7867
- }
7868
- if (manager === UserServiceManager.Supervisor) {
7869
- await installSupervisorUserService(store, options, runtime);
7870
- return;
7871
- }
8450
+ function renderTabs(selected) {
8451
+ const labels = [
8452
+ "1 Overview",
8453
+ "2 Connections",
8454
+ "3 Jobs",
8455
+ "4 Logs",
8456
+ "5 Doctor"
8457
+ ];
8458
+ return labels.map((label, index2) => index2 === selected ? `[${label}]` : ` ${label} `).join(" ");
7872
8459
  }
7873
- async function restartManager(manager, store, runtime) {
7874
- if (manager === UserServiceManager.None) {
7875
- return;
8460
+ function renderView(snapshot, state) {
8461
+ if (state.view === MachineManagerView.Overview) {
8462
+ return renderOverview(snapshot);
7876
8463
  }
7877
- if (manager === UserServiceManager.Launchd) {
7878
- await runtime.run("launchctl", [
7879
- "kickstart",
7880
- "-k",
7881
- `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7882
- ]);
7883
- return;
8464
+ if (state.view === MachineManagerView.Connections) {
8465
+ return renderConnections(snapshot, state.selectedRowIndex);
7884
8466
  }
7885
- if (manager === UserServiceManager.Systemd) {
7886
- await runtime.run("systemctl", [
7887
- "--user",
7888
- "restart",
7889
- "moxt-machine-connector.service"
7890
- ]);
7891
- return;
8467
+ if (state.view === MachineManagerView.Jobs) {
8468
+ return renderJobs(snapshot, state.selectedRowIndex);
7892
8469
  }
7893
- await restartSupervisorUserService(store, runtime);
8470
+ if (state.view === MachineManagerView.Logs) {
8471
+ return renderLogs(snapshot);
8472
+ }
8473
+ return renderDoctor(snapshot);
7894
8474
  }
7895
- async function stopManager(manager, store, runtime) {
7896
- if (manager === UserServiceManager.None) {
7897
- return;
8475
+ function renderOverview(snapshot) {
8476
+ const runtime = snapshot.runtime;
8477
+ const lines = [
8478
+ "",
8479
+ ` Daemon ${runtime ? `ONLINE PID ${runtime.pid} v${runtime.version}` : "OFFLINE"}`,
8480
+ ` Service ${snapshot.serviceManager ?? "not installed"}`,
8481
+ ` Connections ${snapshot.connections.length}`,
8482
+ ` Active Jobs ${runtime?.activeJobs.length ?? 0}`,
8483
+ ` Stored Jobs ${snapshot.jobs.length}`,
8484
+ ` Refreshed ${formatTimestamp(snapshot.refreshedAt)}`,
8485
+ ""
8486
+ ];
8487
+ if (snapshot.connections.length === 0) {
8488
+ lines.push(' No connections. Press A and choose "Pair a new machine connection".');
8489
+ return lines;
7898
8490
  }
7899
- if (manager === UserServiceManager.Launchd) {
7900
- await runtime.run("launchctl", [
7901
- "bootout",
7902
- `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7903
- ]);
7904
- return;
8491
+ lines.push(" Connected roots");
8492
+ for (const connection of snapshot.connections) {
8493
+ lines.push(` ${connection.machineName} ${connection.rootPath}`);
7905
8494
  }
7906
- if (manager === UserServiceManager.Systemd) {
7907
- await runtime.run("systemctl", [
7908
- "--user",
7909
- "stop",
7910
- "moxt-machine-connector.service"
7911
- ]);
7912
- return;
8495
+ return lines;
8496
+ }
8497
+ function renderConnections(snapshot, selectedRowIndex) {
8498
+ if (snapshot.connections.length === 0) {
8499
+ return ["", " No connections", " Press A to pair a machine."];
7913
8500
  }
7914
- await runCommandIgnoringFailure(runtime, "supervisorctl", [
7915
- "-c",
7916
- supervisorConfigPath(store),
7917
- "stop",
7918
- supervisorProgramName
7919
- ]);
8501
+ const lines = [
8502
+ " MACHINE ROOT WORKSPACE / TARGET"
8503
+ ];
8504
+ snapshot.connections.forEach((connection, index2) => {
8505
+ const marker = index2 === selectedRowIndex ? ">" : " ";
8506
+ lines.push(`${marker} ${connection.machineName} ${connection.rootPath} ${connection.workspaceId} / ${connection.targetId}`);
8507
+ lines.push(` ${connection.connectionId} ${connection.relayOrigin}`);
8508
+ });
8509
+ return lines;
7920
8510
  }
7921
- async function uninstallManager(manager, store, runtime) {
7922
- if (manager === UserServiceManager.None) {
7923
- return;
8511
+ function renderJobs(snapshot, selectedRowIndex) {
8512
+ if (snapshot.jobs.length === 0) {
8513
+ return ["", " No Jobs have been stored on this machine."];
7924
8514
  }
7925
- if (manager === UserServiceManager.Launchd) {
7926
- await runCommandIgnoringFailure(runtime, "launchctl", [
7927
- "bootout",
7928
- `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7929
- ]);
7930
- await (0, import_promises13.rm)(launchAgentPath(), { force: true });
7931
- return;
8515
+ const lines = [" STATUS KIND JOB / COMMAND"];
8516
+ snapshot.jobs.forEach((job, index2) => {
8517
+ const marker = index2 === selectedRowIndex ? ">" : " ";
8518
+ lines.push(`${marker} ${job.status ?? job.phase} ${job.kind} ${job.command ?? job.jobId}`);
8519
+ lines.push(` ${job.jobId} ${job.relativeWorkingDirectory} ${formatTimestamp(job.updatedAt)}`);
8520
+ });
8521
+ return lines;
8522
+ }
8523
+ function renderLogs(snapshot) {
8524
+ if (snapshot.logLines.length === 0) {
8525
+ return ["", " No Connector logs are available."];
7932
8526
  }
7933
- if (manager === UserServiceManager.Systemd) {
7934
- await runCommandIgnoringFailure(runtime, "systemctl", [
7935
- "--user",
7936
- "disable",
7937
- "--now",
7938
- "moxt-machine-connector.service"
7939
- ]);
7940
- await (0, import_promises13.rm)(systemdUnitPath(), { force: true });
7941
- await runCommandIgnoringFailure(runtime, "systemctl", [
7942
- "--user",
7943
- "daemon-reload"
7944
- ]);
7945
- return;
8527
+ return snapshot.logLines.map((line) => ` ${line}`);
8528
+ }
8529
+ function renderDoctor(snapshot) {
8530
+ if (snapshot.checks.length === 0) {
8531
+ return [
8532
+ "",
8533
+ " Diagnostics have not run yet.",
8534
+ ' Press A and choose "Run diagnostics".'
8535
+ ];
7946
8536
  }
7947
- await runCommandIgnoringFailure(runtime, "supervisorctl", [
7948
- "-c",
7949
- supervisorConfigPath(store),
7950
- "stop",
7951
- supervisorProgramName
7952
- ]);
7953
- await runCommandIgnoringFailure(runtime, "supervisorctl", ["-c", supervisorConfigPath(store), "shutdown"]);
7954
- await (0, import_promises13.rm)(supervisorDirectory(store), {
7955
- force: true,
7956
- recursive: true
8537
+ return snapshot.checks.map((check) => ` ${check.status.padEnd(7)} ${check.name}: ${check.detail}`);
8538
+ }
8539
+ function renderActions(state) {
8540
+ const lines = [
8541
+ " Actions",
8542
+ " Use Up/Down and Enter. Esc closes this menu.",
8543
+ ""
8544
+ ];
8545
+ machineManagerActions().forEach((definition2, index2) => {
8546
+ const selected = index2 === state.selectedActionIndex;
8547
+ const line = `${selected ? ">" : " "} ${definition2.label}`;
8548
+ lines.push(selected ? `${styleSelected}${line}${styleReset}` : line);
7957
8549
  });
8550
+ return lines;
7958
8551
  }
7959
- async function configuredServiceManager(store, runtime) {
7960
- const storedManager = await readStoredServiceManager(store);
7961
- if (storedManager !== UserServiceManager.None) {
7962
- return storedManager;
8552
+ function rowCountForView(snapshot, view) {
8553
+ if (view === MachineManagerView.Connections) {
8554
+ return snapshot.connections.length;
7963
8555
  }
7964
- const stored = await store.readServiceManager();
7965
- if (stored.value) {
7966
- return UserServiceManager.None;
8556
+ if (view === MachineManagerView.Jobs) {
8557
+ return snapshot.jobs.length;
7967
8558
  }
7968
- const capabilities = await detectServiceManagerCapabilities(runtime);
7969
- return selectUserServiceManager(ServiceManagerPreference.Auto, capabilities).manager;
8559
+ return 0;
7970
8560
  }
7971
- async function readStoredServiceManager(store) {
7972
- const stored = await store.readServiceManager();
7973
- if (!stored.value) {
7974
- return UserServiceManager.None;
7975
- }
7976
- return parseStoredServiceManager(stored.value.manager);
8561
+ function toManagerConnection(connection) {
8562
+ return {
8563
+ connectionId: connection.connectionId,
8564
+ machineName: connection.machineName,
8565
+ relayOrigin: connection.relayOrigin,
8566
+ rootDisplayName: connection.rootDisplayName,
8567
+ rootPath: connection.rootPath,
8568
+ targetId: connection.targetId,
8569
+ targetKind: connection.targetKind,
8570
+ workspaceId: connection.workspaceId
8571
+ };
7977
8572
  }
7978
- function parseStoredServiceManager(value) {
7979
- if (value === UserServiceManager.Launchd) {
7980
- return UserServiceManager.Launchd;
8573
+ function toManagerJob(job) {
8574
+ return {
8575
+ command: formatPersistedCommand(job).value,
8576
+ connectionId: job.connectionId,
8577
+ jobId: job.claim.jobId,
8578
+ kind: job.claim.kind,
8579
+ phase: job.phase,
8580
+ relativeWorkingDirectory: job.claim.relativeWorkingDirectory,
8581
+ status: job.finalStatus,
8582
+ updatedAt: job.updatedAt
8583
+ };
8584
+ }
8585
+ function formatPersistedCommand(job) {
8586
+ if (job.claim.kind !== "command") {
8587
+ return {};
7981
8588
  }
7982
- if (value === UserServiceManager.Systemd) {
7983
- return UserServiceManager.Systemd;
8589
+ if (!isRecord3(job.claim.requestPayload)) {
8590
+ return {};
7984
8591
  }
7985
- if (value === UserServiceManager.Supervisor) {
7986
- return UserServiceManager.Supervisor;
8592
+ const executable = job.claim.requestPayload.executable;
8593
+ const argumentsValue = job.claim.requestPayload.arguments;
8594
+ if (typeof executable !== "string" || !Array.isArray(argumentsValue) || !argumentsValue.every((argument) => typeof argument === "string")) {
8595
+ return {};
7987
8596
  }
7988
- if (value === UserServiceManager.None) {
7989
- return UserServiceManager.None;
8597
+ return {
8598
+ value: [executable, ...argumentsValue].map(formatCommandArgument).join(" ")
8599
+ };
8600
+ }
8601
+ function formatCommandArgument(value) {
8602
+ return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : JSON.stringify(value);
8603
+ }
8604
+ async function readRecentLogLines(store) {
8605
+ const normal = await readOptionalFile(store.runtimeLogPath());
8606
+ const errors = await readOptionalFile(store.runtimeErrorLogPath());
8607
+ return [...normal.split("\n"), ...errors.split("\n")].filter((line) => line.length > 0).slice(-maximumLogLines);
8608
+ }
8609
+ async function readOptionalFile(path4) {
8610
+ try {
8611
+ return await (0, import_promises14.readFile)(path4, "utf8");
8612
+ } catch (error) {
8613
+ if (isMissingFile(error)) {
8614
+ return "";
8615
+ }
8616
+ throw error;
7990
8617
  }
7991
- throw new Error(`Unsupported stored service manager: ${value}`);
7992
8618
  }
7993
- async function persistServiceManager(store, manager) {
7994
- await store.writeServiceManager({
7995
- manager,
7996
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
7997
- });
8619
+ async function questionWithDefault(reader, label, defaultValue) {
8620
+ const suffix = defaultValue.length > 0 ? ` [${defaultValue}]` : "";
8621
+ const answer = (await reader.question(`${label}${suffix}: `)).trim();
8622
+ return answer.length > 0 ? answer : defaultValue;
7998
8623
  }
7999
- function managerIsAvailable(manager, capabilities) {
8000
- if (manager === UserServiceManager.Launchd) {
8001
- return capabilities.operatingSystem === "darwin";
8624
+ function appendOption(argumentsList, name, value) {
8625
+ if (value.length > 0) {
8626
+ argumentsList.push(name, value);
8002
8627
  }
8003
- if (manager === UserServiceManager.Systemd) {
8004
- return capabilities.systemdUserAvailable;
8628
+ }
8629
+ function styledLine(value, width, style) {
8630
+ return `${style}${fitLine(value, width)}${styleReset}`;
8631
+ }
8632
+ function fitLine(value, width) {
8633
+ const plainValue = stripAnsi(value);
8634
+ if (plainValue.length > width) {
8635
+ if (width <= 1) {
8636
+ return plainValue.slice(0, width);
8637
+ }
8638
+ return `${plainValue.slice(0, width - 1)}\u2026`;
8005
8639
  }
8006
- if (manager === UserServiceManager.Supervisor) {
8007
- return capabilities.supervisorAvailable;
8640
+ if (value.includes("\x1B[")) {
8641
+ return value;
8008
8642
  }
8009
- return false;
8643
+ return value.padEnd(width);
8010
8644
  }
8011
- function automaticSelectionDetail(manager) {
8012
- if (manager === UserServiceManager.Launchd) {
8013
- return "Automatically selected the macOS LaunchAgent service manager.";
8645
+ function stripAnsi(value) {
8646
+ return value.replaceAll(styleHeader, "").replaceAll(styleSelected, "").replaceAll(styleReset, "");
8647
+ }
8648
+ function repeatCharacter(value, count) {
8649
+ return value.repeat(count);
8650
+ }
8651
+ function wrapIndex(value, count) {
8652
+ return (value % count + count) % count;
8653
+ }
8654
+ function formatTimestamp(value) {
8655
+ const timestamp = Date.parse(value);
8656
+ if (Number.isNaN(timestamp)) {
8657
+ return value;
8014
8658
  }
8015
- if (manager === UserServiceManager.Systemd) {
8016
- return "Automatically selected the systemd user service manager.";
8659
+ return new Date(timestamp).toLocaleString();
8660
+ }
8661
+ function isRecord3(value) {
8662
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8663
+ }
8664
+ function isMissingFile(error) {
8665
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
8666
+ }
8667
+ function errorMessage4(error) {
8668
+ return error instanceof Error ? error.message : String(error);
8669
+ }
8670
+ var import_promises14, import_promises15, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
8671
+ var init_machine_manager = __esm({
8672
+ "../machine-connector/dist/runtime/machine-manager.js"() {
8673
+ "use strict";
8674
+ init_cjs_shims();
8675
+ import_promises14 = require("fs/promises");
8676
+ import_promises15 = require("readline/promises");
8677
+ import_node_readline = require("readline");
8678
+ init_doctor();
8679
+ init_local_ipc();
8680
+ alternateScreenEnter = "\x1B[?1049h";
8681
+ alternateScreenExit = "\x1B[?1049l";
8682
+ clearScreen = "\x1B[2J\x1B[H";
8683
+ cursorHide = "\x1B[?25l";
8684
+ cursorShow = "\x1B[?25h";
8685
+ styleReset = "\x1B[0m";
8686
+ styleHeader = "\x1B[1;30;46m";
8687
+ styleSelected = "\x1B[30;47m";
8688
+ refreshIntervalMilliseconds = 1e3;
8689
+ maximumLogLines = 200;
8690
+ (function(MachineManagerView2) {
8691
+ MachineManagerView2[MachineManagerView2["Overview"] = 0] = "Overview";
8692
+ MachineManagerView2[MachineManagerView2["Connections"] = 1] = "Connections";
8693
+ MachineManagerView2[MachineManagerView2["Jobs"] = 2] = "Jobs";
8694
+ MachineManagerView2[MachineManagerView2["Logs"] = 3] = "Logs";
8695
+ MachineManagerView2[MachineManagerView2["Doctor"] = 4] = "Doctor";
8696
+ })(MachineManagerView || (MachineManagerView = {}));
8697
+ (function(MachineManagerAction2) {
8698
+ MachineManagerAction2["Refresh"] = "refresh";
8699
+ MachineManagerAction2["Connect"] = "connect";
8700
+ MachineManagerAction2["Disconnect"] = "disconnect";
8701
+ MachineManagerAction2["Doctor"] = "doctor";
8702
+ MachineManagerAction2["Logs"] = "logs";
8703
+ MachineManagerAction2["ServiceInstall"] = "service_install";
8704
+ MachineManagerAction2["ServiceRestart"] = "service_restart";
8705
+ MachineManagerAction2["ServiceStop"] = "service_stop";
8706
+ MachineManagerAction2["ServiceUninstall"] = "service_uninstall";
8707
+ MachineManagerAction2["Quit"] = "quit";
8708
+ })(MachineManagerAction || (MachineManagerAction = {}));
8709
+ (function(MachineManagerSnapshotDepth2) {
8710
+ MachineManagerSnapshotDepth2["Basic"] = "basic";
8711
+ MachineManagerSnapshotDepth2["WithDoctor"] = "with_doctor";
8712
+ })(MachineManagerSnapshotDepth || (MachineManagerSnapshotDepth = {}));
8713
+ InteractiveMachineManager = class {
8714
+ store;
8715
+ commandRunner;
8716
+ checks = [];
8717
+ refreshTimer;
8718
+ refreshing = false;
8719
+ resolveRun;
8720
+ snapshot = {
8721
+ checks: [],
8722
+ connections: [],
8723
+ jobs: [],
8724
+ logLines: [],
8725
+ refreshedAt: (/* @__PURE__ */ new Date()).toISOString()
8726
+ };
8727
+ state = {
8728
+ actionMenuOpen: false,
8729
+ selectedActionIndex: 0,
8730
+ selectedRowIndex: 0,
8731
+ view: MachineManagerView.Overview
8732
+ };
8733
+ stopped = false;
8734
+ terminalSuspended = true;
8735
+ constructor(store, commandRunner) {
8736
+ this.store = store;
8737
+ this.commandRunner = commandRunner;
8738
+ }
8739
+ async run() {
8740
+ await this.refresh(MachineManagerSnapshotDepth.Basic);
8741
+ this.enterTerminal();
8742
+ try {
8743
+ await new Promise((resolvePromise) => {
8744
+ this.resolveRun = resolvePromise;
8745
+ });
8746
+ } finally {
8747
+ this.leaveTerminal();
8748
+ }
8749
+ }
8750
+ enterTerminal() {
8751
+ (0, import_node_readline.emitKeypressEvents)(process.stdin);
8752
+ process.stdin.setRawMode(true);
8753
+ process.stdin.resume();
8754
+ process.stdin.on("keypress", this.onKeypress);
8755
+ process.stdout.on("resize", this.onResize);
8756
+ process.on("SIGINT", this.onTerminationSignal);
8757
+ process.on("SIGTERM", this.onTerminationSignal);
8758
+ process.stdout.write(`${alternateScreenEnter}${cursorHide}${clearScreen}`);
8759
+ this.terminalSuspended = false;
8760
+ this.refreshTimer = setInterval(() => {
8761
+ void this.refresh(MachineManagerSnapshotDepth.Basic);
8762
+ }, refreshIntervalMilliseconds);
8763
+ this.render();
8764
+ }
8765
+ leaveTerminal() {
8766
+ if (this.refreshTimer) {
8767
+ clearInterval(this.refreshTimer);
8768
+ this.refreshTimer = void 0;
8769
+ }
8770
+ process.stdin.off("keypress", this.onKeypress);
8771
+ process.stdout.off("resize", this.onResize);
8772
+ process.off("SIGINT", this.onTerminationSignal);
8773
+ process.off("SIGTERM", this.onTerminationSignal);
8774
+ if (process.stdin.isTTY) {
8775
+ process.stdin.setRawMode(false);
8776
+ }
8777
+ process.stdin.pause();
8778
+ process.stdout.write(`${cursorShow}${styleReset}${alternateScreenExit}`);
8779
+ }
8780
+ onResize = () => {
8781
+ this.render();
8782
+ };
8783
+ onTerminationSignal = () => {
8784
+ this.stop();
8785
+ };
8786
+ onKeypress = (text3, key) => {
8787
+ if (key.ctrl && key.name === "c") {
8788
+ this.stop();
8789
+ return;
8790
+ }
8791
+ if (key.name === "q" || text3 === "q") {
8792
+ this.stop();
8793
+ return;
8794
+ }
8795
+ if (key.name === "a" || text3 === "a" || text3 === "?") {
8796
+ this.state.actionMenuOpen = !this.state.actionMenuOpen;
8797
+ this.state.message = void 0;
8798
+ this.render();
8799
+ return;
8800
+ }
8801
+ if (key.name === "escape") {
8802
+ this.state.actionMenuOpen = false;
8803
+ this.render();
8804
+ return;
8805
+ }
8806
+ if (key.name === "up") {
8807
+ this.moveSelection(-1);
8808
+ return;
8809
+ }
8810
+ if (key.name === "down") {
8811
+ this.moveSelection(1);
8812
+ return;
8813
+ }
8814
+ if (key.name === "return" && this.state.actionMenuOpen) {
8815
+ void this.executeSelectedAction();
8816
+ return;
8817
+ }
8818
+ if (key.name === "tab" || key.name === "right") {
8819
+ this.changeView(1);
8820
+ return;
8821
+ }
8822
+ if (key.name === "left") {
8823
+ this.changeView(-1);
8824
+ return;
8825
+ }
8826
+ if (text3 === "r") {
8827
+ void this.refresh(MachineManagerSnapshotDepth.Basic);
8828
+ return;
8829
+ }
8830
+ const viewNumber = Number(text3);
8831
+ if (Number.isInteger(viewNumber) && viewNumber >= 1 && viewNumber <= 5) {
8832
+ this.state.view = viewNumber - 1;
8833
+ this.state.selectedRowIndex = 0;
8834
+ this.state.actionMenuOpen = false;
8835
+ this.render();
8836
+ }
8837
+ };
8838
+ moveSelection(delta) {
8839
+ const rowCount = this.state.actionMenuOpen ? machineManagerActions().length : rowCountForView(this.snapshot, this.state.view);
8840
+ if (rowCount === 0) {
8841
+ return;
8842
+ }
8843
+ if (this.state.actionMenuOpen) {
8844
+ this.state.selectedActionIndex = wrapIndex(this.state.selectedActionIndex + delta, rowCount);
8845
+ } else {
8846
+ this.state.selectedRowIndex = wrapIndex(this.state.selectedRowIndex + delta, rowCount);
8847
+ }
8848
+ this.render();
8849
+ }
8850
+ changeView(delta) {
8851
+ this.state.view = wrapIndex(this.state.view + delta, 5);
8852
+ this.state.selectedRowIndex = 0;
8853
+ this.state.actionMenuOpen = false;
8854
+ this.state.message = void 0;
8855
+ this.render();
8856
+ }
8857
+ async refresh(depth) {
8858
+ if (this.refreshing || this.stopped) {
8859
+ return;
8860
+ }
8861
+ this.refreshing = true;
8862
+ try {
8863
+ const snapshot = await collectMachineManagerSnapshot(this.store, depth);
8864
+ if (snapshot.checks.length > 0) {
8865
+ this.checks = snapshot.checks;
8866
+ }
8867
+ this.snapshot = {
8868
+ ...snapshot,
8869
+ checks: this.checks
8870
+ };
8871
+ this.state.message = void 0;
8872
+ } catch (error) {
8873
+ this.state.message = errorMessage4(error);
8874
+ } finally {
8875
+ this.refreshing = false;
8876
+ this.render();
8877
+ }
8878
+ }
8879
+ render() {
8880
+ if (this.stopped || this.terminalSuspended || !process.stdout.isTTY) {
8881
+ return;
8882
+ }
8883
+ process.stdout.write(`${clearScreen}${renderMachineManager(this.snapshot, this.state, process.stdout.columns ?? 80, process.stdout.rows ?? 24)}`);
8884
+ }
8885
+ async executeSelectedAction() {
8886
+ const definition2 = machineManagerActions()[this.state.selectedActionIndex];
8887
+ this.state.actionMenuOpen = false;
8888
+ if (definition2.action === MachineManagerAction.Quit) {
8889
+ this.stop();
8890
+ return;
8891
+ }
8892
+ if (definition2.action === MachineManagerAction.Refresh) {
8893
+ await this.refresh(MachineManagerSnapshotDepth.Basic);
8894
+ return;
8895
+ }
8896
+ if (definition2.action === MachineManagerAction.Doctor) {
8897
+ this.state.view = MachineManagerView.Doctor;
8898
+ await this.refresh(MachineManagerSnapshotDepth.WithDoctor);
8899
+ return;
8900
+ }
8901
+ if (definition2.action === MachineManagerAction.Logs) {
8902
+ this.state.view = MachineManagerView.Logs;
8903
+ await this.refresh(MachineManagerSnapshotDepth.Basic);
8904
+ return;
8905
+ }
8906
+ await this.runCommandAction(definition2.action);
8907
+ }
8908
+ async runCommandAction(action) {
8909
+ this.suspendTerminal();
8910
+ const reader = (0, import_promises15.createInterface)({
8911
+ input: process.stdin,
8912
+ output: process.stdout
8913
+ });
8914
+ try {
8915
+ const argumentsList = await this.buildCommandArguments(reader, action);
8916
+ if (argumentsList.length > 0) {
8917
+ await this.commandRunner.run(argumentsList);
8918
+ }
8919
+ } catch (error) {
8920
+ process.stdout.write(`
8921
+ Error: ${errorMessage4(error)}
8922
+ `);
8923
+ }
8924
+ await reader.question("\nPress Enter to return to the manager...");
8925
+ reader.close();
8926
+ this.resumeTerminal();
8927
+ await this.refresh(MachineManagerSnapshotDepth.Basic);
8928
+ }
8929
+ suspendTerminal() {
8930
+ this.terminalSuspended = true;
8931
+ process.stdin.off("keypress", this.onKeypress);
8932
+ process.stdout.off("resize", this.onResize);
8933
+ process.stdin.setRawMode(false);
8934
+ process.stdout.write(`${cursorShow}${styleReset}${alternateScreenExit}`);
8935
+ }
8936
+ resumeTerminal() {
8937
+ (0, import_node_readline.emitKeypressEvents)(process.stdin);
8938
+ process.stdin.setRawMode(true);
8939
+ process.stdin.resume();
8940
+ process.stdin.on("keypress", this.onKeypress);
8941
+ process.stdout.on("resize", this.onResize);
8942
+ process.stdout.write(`${alternateScreenEnter}${cursorHide}${clearScreen}`);
8943
+ this.terminalSuspended = false;
8944
+ }
8945
+ async buildCommandArguments(reader, action) {
8946
+ if (action === MachineManagerAction.Connect) {
8947
+ return await this.buildConnectArguments(reader);
8948
+ }
8949
+ if (action === MachineManagerAction.Disconnect) {
8950
+ return await this.buildDisconnectArguments(reader);
8951
+ }
8952
+ if (action === MachineManagerAction.ServiceInstall) {
8953
+ const manager = await questionWithDefault(reader, "Service manager (auto/systemd/supervisor/none)", "auto");
8954
+ return ["service", "install", "--service-manager", manager];
8955
+ }
8956
+ if (action === MachineManagerAction.ServiceRestart) {
8957
+ return ["service", "restart"];
8958
+ }
8959
+ if (action === MachineManagerAction.ServiceStop) {
8960
+ return ["service", "stop"];
8961
+ }
8962
+ if (action === MachineManagerAction.ServiceUninstall) {
8963
+ return ["service", "uninstall"];
8964
+ }
8965
+ return [];
8966
+ }
8967
+ async buildConnectArguments(reader) {
8968
+ const code = (await reader.question("Pairing code: ")).trim();
8969
+ if (code.length === 0) {
8970
+ throw new Error("Pairing code is required");
8971
+ }
8972
+ const root = await questionWithDefault(reader, "Working root", process.cwd());
8973
+ const relay = (await reader.question("Relay origin (leave blank for the default): ")).trim();
8974
+ const name = (await reader.question("Machine name (leave blank for the hostname): ")).trim();
8975
+ const serviceManager = await questionWithDefault(reader, "Service manager (auto/systemd/supervisor/none)", "auto");
8976
+ const noOpen = (await reader.question("Skip opening the confirmation page? [y/N]: ")).trim().toLowerCase();
8977
+ const argumentsList = [
8978
+ "connect",
8979
+ "--code",
8980
+ code,
8981
+ "--root",
8982
+ root,
8983
+ "--service-manager",
8984
+ serviceManager
8985
+ ];
8986
+ appendOption(argumentsList, "--relay", relay);
8987
+ appendOption(argumentsList, "--name", name);
8988
+ if (noOpen === "y" || noOpen === "yes") {
8989
+ argumentsList.push("--no-open");
8990
+ }
8991
+ return argumentsList;
8992
+ }
8993
+ async buildDisconnectArguments(reader) {
8994
+ const selected = this.snapshot.connections[this.state.selectedRowIndex];
8995
+ const connectionId = await questionWithDefault(reader, "Connection ID", selected?.connectionId ?? "");
8996
+ if (connectionId.length === 0) {
8997
+ throw new Error("Connection ID is required");
8998
+ }
8999
+ const confirmed = (await reader.question(`Disconnect ${connectionId}? [y/N]: `)).trim().toLowerCase();
9000
+ if (confirmed !== "y" && confirmed !== "yes") {
9001
+ return [];
9002
+ }
9003
+ const localOnly = (await reader.question("Remove local state without contacting Moxt? [y/N]: ")).trim().toLowerCase();
9004
+ const argumentsList = ["disconnect", "--connection", connectionId];
9005
+ if (localOnly === "y" || localOnly === "yes") {
9006
+ argumentsList.push("--local-only");
9007
+ }
9008
+ return argumentsList;
9009
+ }
9010
+ stop() {
9011
+ if (this.stopped) {
9012
+ return;
9013
+ }
9014
+ this.stopped = true;
9015
+ this.resolveRun?.();
9016
+ }
9017
+ };
8017
9018
  }
8018
- return "Automatically selected the Supervisor service manager.";
8019
- }
8020
- async function installLaunchAgent(store, options, runtime) {
8021
- const path4 = launchAgentPath();
8022
- await (0, import_promises13.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
8023
- const programArguments = [
8024
- options.nodePath,
8025
- (0, import_node_path7.resolve)(options.entrypointPath),
8026
- ...options.commandArguments
8027
- ];
8028
- const plist = `<?xml version="1.0" encoding="UTF-8"?>
8029
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
8030
- <plist version="1.0">
8031
- <dict>
8032
- <key>Label</key>
8033
- <string>${launchAgentLabel}</string>
8034
- <key>ProgramArguments</key>
8035
- <array>
8036
- ${programArguments.map((argument) => ` <string>${escapeXml(argument)}</string>`).join("\n")}
8037
- </array>
8038
- <key>RunAtLoad</key>
8039
- <true/>
8040
- <key>KeepAlive</key>
8041
- <true/>
8042
- <key>EnvironmentVariables</key>
8043
- <dict>
8044
- ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeXml(name)}</key>
8045
- <string>${escapeXml(value)}</string>`).join("\n")}
8046
- </dict>
8047
- <key>ProcessType</key>
8048
- <string>Background</string>
8049
- <key>StandardOutPath</key>
8050
- <string>${escapeXml(store.runtimeLogPath())}</string>
8051
- <key>StandardErrorPath</key>
8052
- <string>${escapeXml(store.runtimeErrorLogPath())}</string>
8053
- </dict>
8054
- </plist>
8055
- `;
8056
- await (0, import_promises13.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
8057
- const domain = `gui/${process.getuid?.() ?? 0}`;
8058
- await runCommandIgnoringFailure(runtime, "launchctl", [
8059
- "bootout",
8060
- domain,
8061
- path4
8062
- ]);
8063
- await runtime.run("launchctl", ["bootstrap", domain, path4]);
8064
- await runtime.run("launchctl", [
8065
- "kickstart",
8066
- "-k",
8067
- `${domain}/${launchAgentLabel}`
8068
- ]);
8069
- }
8070
- async function installSystemdUserService(store, options, runtime) {
8071
- const path4 = systemdUnitPath();
8072
- await (0, import_promises13.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
8073
- const command = [
8074
- options.nodePath,
8075
- (0, import_node_path7.resolve)(options.entrypointPath),
8076
- ...options.commandArguments
8077
- ].map(escapeSystemdArgument).join(" ");
8078
- const unit = `[Unit]
8079
- Description=Moxt Machine Connector
8080
- After=network-online.target
8081
- Wants=network-online.target
8082
-
8083
- [Service]
8084
- Type=simple
8085
- ExecStart=${command}
8086
- Restart=always
8087
- RestartSec=3
8088
- NoNewPrivileges=true
8089
- ${Object.entries(options.environment).map(([name, value]) => `Environment=${escapeSystemdEnvironment(name)}=${escapeSystemdEnvironment(value)}`).join("\n")}
9019
+ });
8090
9020
 
8091
- [Install]
8092
- WantedBy=default.target
8093
- `;
8094
- await (0, import_promises13.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
8095
- await runtime.run("systemctl", ["--user", "daemon-reload"]);
8096
- await runtime.run("systemctl", [
8097
- "--user",
8098
- "enable",
8099
- "--now",
8100
- "moxt-machine-connector.service"
8101
- ]);
8102
- await runCommandIgnoringFailure(runtime, "loginctl", [
8103
- "enable-linger",
8104
- (0, import_node_os6.userInfo)().username
8105
- ]);
8106
- }
8107
- async function installSupervisorUserService(store, options, runtime) {
8108
- const directory = supervisorDirectory(store);
8109
- const configPath = supervisorConfigPath(store);
8110
- await (0, import_promises13.mkdir)(directory, { recursive: true, mode: 448 });
8111
- await (0, import_promises13.writeFile)(configPath, createSupervisorConfiguration(store, options), {
8112
- encoding: "utf8",
8113
- mode: 384
8114
- });
8115
- const supervisorWasRunning = await supervisorIsRunning(store, runtime);
8116
- if (!supervisorWasRunning) {
8117
- await (0, import_promises13.rm)(supervisorSocketPath(store), { force: true });
8118
- await (0, import_promises13.rm)(supervisorPidPath(store), { force: true });
8119
- await runtime.run("supervisord", ["-c", configPath]);
8120
- await waitForSupervisorControl(store, runtime);
8121
- return;
9021
+ // ../machine-connector/dist/runtime/device-identity.js
9022
+ async function ensureMachineIdentity(store) {
9023
+ const existingIdentity = (await store.readIdentity()).value;
9024
+ const existingPrivateKey = (await store.readPrivateKey()).value;
9025
+ if (existingIdentity && existingPrivateKey) {
9026
+ return {
9027
+ identity: existingIdentity,
9028
+ privateKeyPem: existingPrivateKey
9029
+ };
8122
9030
  }
8123
- await runtime.run("supervisorctl", ["-c", configPath, "reread"]);
8124
- await runtime.run("supervisorctl", ["-c", configPath, "update"]);
8125
- await restartSupervisorUserService(store, runtime);
8126
- }
8127
- function createSupervisorConfiguration(store, options) {
8128
- const command = [
8129
- options.nodePath,
8130
- (0, import_node_path7.resolve)(options.entrypointPath),
8131
- ...options.commandArguments
8132
- ].map(escapeSupervisorArgument).join(" ");
8133
- const environment = Object.entries(options.environment).map(([name, value]) => `${name}="${escapeSupervisorEnvironment(value)}"`).join(",");
8134
- return `[unix_http_server]
8135
- file=${supervisorSocketPath(store)}
8136
- chmod=0600
8137
-
8138
- [supervisord]
8139
- logfile=${supervisorLogPath(store)}
8140
- pidfile=${supervisorPidPath(store)}
8141
- childlogdir=${supervisorDirectory(store)}
8142
- nodaemon=false
8143
- minfds=1024
8144
- minprocs=200
8145
-
8146
- [rpcinterface:supervisor]
8147
- supervisor.rpcinterface_factory=supervisor.rpcinterface:make_main_rpcinterface
8148
-
8149
- [supervisorctl]
8150
- serverurl=unix://${supervisorSocketPath(store)}
8151
-
8152
- [program:${supervisorProgramName}]
8153
- command=${command}
8154
- directory=${escapeSupervisorPath((0, import_node_path7.dirname)((0, import_node_path7.resolve)(options.entrypointPath)))}
8155
- environment=${environment}
8156
- autostart=true
8157
- autorestart=true
8158
- startsecs=3
8159
- startretries=10
8160
- stopsignal=TERM
8161
- stopasgroup=true
8162
- killasgroup=true
8163
- stopwaitsecs=20
8164
- stdout_logfile=${escapeSupervisorPath(store.runtimeLogPath())}
8165
- stderr_logfile=${escapeSupervisorPath(store.runtimeErrorLogPath())}
8166
- stdout_logfile_maxbytes=20MB
8167
- stderr_logfile_maxbytes=20MB
8168
- stdout_logfile_backups=3
8169
- stderr_logfile_backups=3
8170
- `;
9031
+ const keyPair = await generateKeyPairAsync("rsa", {
9032
+ modulusLength: 4096,
9033
+ privateKeyEncoding: {
9034
+ format: "pem",
9035
+ type: "pkcs8"
9036
+ },
9037
+ publicKeyEncoding: {
9038
+ format: "pem",
9039
+ type: "spki"
9040
+ }
9041
+ });
9042
+ const identity = {
9043
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
9044
+ deviceKeyFingerprint: (0, import_node_crypto6.createHash)("sha256").update(keyPair.publicKey, "utf8").digest("hex"),
9045
+ publicKeyPem: keyPair.publicKey
9046
+ };
9047
+ await store.writePrivateKey(keyPair.privateKey);
9048
+ await store.writeIdentity(identity);
9049
+ return {
9050
+ identity,
9051
+ privateKeyPem: keyPair.privateKey
9052
+ };
8171
9053
  }
8172
- async function restartSupervisorUserService(store, runtime) {
8173
- const configPath = supervisorConfigPath(store);
8174
- if (!await supervisorIsRunning(store, runtime)) {
8175
- await (0, import_promises13.rm)(supervisorSocketPath(store), { force: true });
8176
- await (0, import_promises13.rm)(supervisorPidPath(store), { force: true });
8177
- await runtime.run("supervisord", ["-c", configPath]);
8178
- await waitForSupervisorControl(store, runtime);
8179
- return;
8180
- }
8181
- try {
8182
- await runtime.run("supervisorctl", [
8183
- "-c",
8184
- configPath,
8185
- "restart",
8186
- supervisorProgramName
8187
- ]);
8188
- } catch {
8189
- await runtime.run("supervisorctl", [
8190
- "-c",
8191
- configPath,
8192
- "start",
8193
- supervisorProgramName
8194
- ]);
9054
+ function decryptPairingCredentials(privateKeyPem, encryptedCredentials) {
9055
+ const serializedEnvelope = Buffer.from(encryptedCredentials, "base64url").toString("utf8");
9056
+ const envelope = JSON.parse(serializedEnvelope);
9057
+ if (envelope.version !== 1 || envelope.algorithm !== "RSA-OAEP-256+A256GCM") {
9058
+ throw new Error("Unsupported Local Machine credentials envelope");
8195
9059
  }
8196
- }
8197
- async function supervisorIsRunning(store, runtime) {
8198
- return await commandSucceeds(runtime, "supervisorctl", [
8199
- "-c",
8200
- supervisorConfigPath(store),
8201
- "pid"
9060
+ const encryptionKey = (0, import_node_crypto6.privateDecrypt)({
9061
+ key: privateKeyPem,
9062
+ oaepHash: "sha256",
9063
+ padding: import_node_crypto6.constants.RSA_PKCS1_OAEP_PADDING
9064
+ }, Buffer.from(envelope.encryptedKey, "base64url"));
9065
+ const decipher = (0, import_node_crypto6.createDecipheriv)("aes-256-gcm", encryptionKey, Buffer.from(envelope.initializationVector, "base64url"));
9066
+ decipher.setAuthTag(Buffer.from(envelope.authenticationTag, "base64url"));
9067
+ const decrypted = Buffer.concat([
9068
+ decipher.update(Buffer.from(envelope.ciphertext, "base64url")),
9069
+ decipher.final()
8202
9070
  ]);
9071
+ return JSON.parse(decrypted.toString("utf8"));
8203
9072
  }
8204
- async function waitForSupervisorControl(store, runtime) {
8205
- const deadline = Date.now() + 5e3;
8206
- while (Date.now() < deadline) {
8207
- if (await supervisorIsRunning(store, runtime)) {
8208
- return;
8209
- }
8210
- await delay4(100);
9073
+ var import_node_crypto6, import_node_util5, generateKeyPairAsync;
9074
+ var init_device_identity = __esm({
9075
+ "../machine-connector/dist/runtime/device-identity.js"() {
9076
+ "use strict";
9077
+ init_cjs_shims();
9078
+ import_node_crypto6 = require("crypto");
9079
+ import_node_util5 = require("util");
9080
+ generateKeyPairAsync = (0, import_node_util5.promisify)(import_node_crypto6.generateKeyPair);
8211
9081
  }
8212
- throw new Error("Supervisor did not become ready within 5 seconds");
8213
- }
8214
- function launchAgentPath() {
8215
- return (0, import_node_path7.join)((0, import_node_os6.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
8216
- }
8217
- function systemdUnitPath() {
8218
- const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path7.join)((0, import_node_os6.homedir)(), ".config");
8219
- return (0, import_node_path7.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
8220
- }
8221
- function supervisorDirectory(store) {
8222
- return (0, import_node_path7.join)(store.baseDirectory, "supervisor");
8223
- }
8224
- function supervisorConfigPath(store) {
8225
- return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.conf");
8226
- }
8227
- function supervisorSocketPath(store) {
8228
- return (0, import_node_path7.join)(supervisorDirectory(store), "supervisor.sock");
8229
- }
8230
- function supervisorPidPath(store) {
8231
- return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.pid");
8232
- }
8233
- function supervisorLogPath(store) {
8234
- return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.log");
8235
- }
8236
- async function commandSucceeds(runtime, command, argumentsList) {
8237
- try {
8238
- await runtime.run(command, argumentsList);
8239
- return true;
8240
- } catch {
8241
- return false;
9082
+ });
9083
+
9084
+ // ../machine-connector/dist/runtime/pairing.js
9085
+ async function pairMachine(store, options) {
9086
+ await store.initialize();
9087
+ const canonicalRoot = await store.getCanonicalRoot(options.rootPath);
9088
+ const identity = await ensureMachineIdentity(store);
9089
+ const machineName = options.machineName ?? (0, import_node_os6.hostname)();
9090
+ const operatingSystem = getOperatingSystem();
9091
+ const rootHandle = (0, import_node_crypto7.createHash)("sha256").update(identity.identity.deviceKeyFingerprint, "utf8").update("\0").update(canonicalRoot, "utf8").digest("base64url");
9092
+ const client = new PairingRelayClient(options.relayOrigin);
9093
+ const proposal = await client.propose({
9094
+ connectionCode: options.connectionCode,
9095
+ connectorVersion,
9096
+ devicePublicKey: identity.identity.publicKeyPem,
9097
+ machineName,
9098
+ operatingSystem,
9099
+ protocolVersion: machineProtocolVersion,
9100
+ rootDisplayName: (0, import_node_path9.basename)(canonicalRoot),
9101
+ rootHandle
9102
+ });
9103
+ options.onConfirmation?.(proposal.confirmationUrl);
9104
+ if (!options.noOpen) {
9105
+ openBrowser(proposal.confirmationUrl);
8242
9106
  }
8243
- }
8244
- async function runCommandIgnoringFailure(runtime, command, argumentsList) {
8245
- try {
8246
- await runtime.run(command, argumentsList);
8247
- } catch {
8248
- return;
9107
+ while (Date.parse(proposal.expiresAt) > Date.now()) {
9108
+ const status = await client.pollStatus({
9109
+ pairingIntentId: proposal.pairingIntentId,
9110
+ pollingToken: proposal.pollingToken
9111
+ });
9112
+ if (status.status === connectedPairingStatus) {
9113
+ if (!status.encryptedCredentials) {
9114
+ throw new Error("Pairing completed without encrypted Connector credentials");
9115
+ }
9116
+ const credentials = decryptPairingCredentials(identity.privateKeyPem, status.encryptedCredentials);
9117
+ const connection = {
9118
+ accessToken: credentials.accessToken,
9119
+ accessTokenExpiresAt: credentials.accessTokenExpiresAt,
9120
+ connectionId: credentials.connectionId,
9121
+ connectorVersion,
9122
+ heartbeatIntervalSeconds: credentials.heartbeatIntervalSeconds,
9123
+ machineId: credentials.machineId,
9124
+ machineName,
9125
+ operatingSystem,
9126
+ refreshToken: credentials.refreshToken,
9127
+ relayOrigin: options.relayOrigin.replace(/\/+$/, ""),
9128
+ rootDisplayName: (0, import_node_path9.basename)(canonicalRoot),
9129
+ rootHandle,
9130
+ rootPath: canonicalRoot,
9131
+ targetId: credentials.targetId,
9132
+ targetKind: credentials.targetKind,
9133
+ workspaceId: credentials.workspaceId
9134
+ };
9135
+ await store.saveConnection(connection);
9136
+ return {
9137
+ confirmationUrl: proposal.confirmationUrl,
9138
+ connection
9139
+ };
9140
+ }
9141
+ if (status.status === rejectedPairingStatus || status.status === expiredPairingStatus) {
9142
+ throw new Error(status.status === rejectedPairingStatus ? "Local Machine pairing was rejected" : "Local Machine pairing expired");
9143
+ }
9144
+ await delay7(pairingPollMilliseconds);
8249
9145
  }
9146
+ throw new Error("Local Machine pairing expired");
8250
9147
  }
8251
- async function uninstallManagerIgnoringFailure(manager, store, runtime) {
8252
- try {
8253
- await uninstallManager(manager, store, runtime);
8254
- } catch {
8255
- return;
9148
+ function getOperatingSystem() {
9149
+ if ((0, import_node_os6.platform)() === "darwin") {
9150
+ return MachineOperatingSystem.MacOS;
8256
9151
  }
9152
+ if ((0, import_node_os6.platform)() === "linux") {
9153
+ return MachineOperatingSystem.Linux;
9154
+ }
9155
+ return MachineOperatingSystem.Windows;
8257
9156
  }
8258
- function escapeXml(value) {
8259
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
8260
- }
8261
- function escapeSystemdArgument(value) {
8262
- return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
8263
- }
8264
- function escapeSystemdEnvironment(value) {
8265
- return value.replaceAll("%", "%%").replaceAll(" ", "\\x20");
8266
- }
8267
- function escapeSupervisorArgument(value) {
8268
- return `"${escapeSupervisorValue(value)}"`;
8269
- }
8270
- function escapeSupervisorEnvironment(value) {
8271
- return escapeSupervisorValue(value);
8272
- }
8273
- function escapeSupervisorPath(value) {
8274
- return value.replaceAll("%", "%%");
8275
- }
8276
- function escapeSupervisorValue(value) {
8277
- return value.replaceAll("%", "%%").replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n");
9157
+ function openBrowser(url) {
9158
+ const command = (0, import_node_os6.platform)() === "darwin" ? "open" : "xdg-open";
9159
+ const child = (0, import_node_child_process5.execFile)(command, [url], () => void 0);
9160
+ child.unref();
8278
9161
  }
8279
- function delay4(milliseconds) {
9162
+ function delay7(milliseconds) {
8280
9163
  return new Promise((resolvePromise) => {
8281
9164
  setTimeout(resolvePromise, milliseconds);
8282
9165
  });
8283
9166
  }
8284
- var import_node_child_process4, import_promises13, import_node_os6, import_node_path7, import_node_util4, execFileAsync2, launchAgentLabel, supervisorProgramName, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
8285
- var init_service_manager = __esm({
8286
- "../machine-connector/dist/runtime/service-manager.js"() {
9167
+ var import_node_child_process5, import_node_crypto7, import_node_os6, import_node_path9, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
9168
+ var init_pairing = __esm({
9169
+ "../machine-connector/dist/runtime/pairing.js"() {
8287
9170
  "use strict";
8288
9171
  init_cjs_shims();
8289
- import_node_child_process4 = require("child_process");
8290
- import_promises13 = require("fs/promises");
9172
+ import_node_child_process5 = require("child_process");
9173
+ import_node_crypto7 = require("crypto");
8291
9174
  import_node_os6 = require("os");
8292
- import_node_path7 = require("path");
8293
- import_node_util4 = require("util");
8294
- execFileAsync2 = (0, import_node_util4.promisify)(import_node_child_process4.execFile);
8295
- launchAgentLabel = "ai.moxt.machine-connector";
8296
- supervisorProgramName = "moxt-machine-connector";
8297
- (function(ServiceManagerPreference2) {
8298
- ServiceManagerPreference2["Auto"] = "auto";
8299
- ServiceManagerPreference2["None"] = "none";
8300
- ServiceManagerPreference2["Supervisor"] = "supervisor";
8301
- ServiceManagerPreference2["Systemd"] = "systemd";
8302
- })(ServiceManagerPreference || (ServiceManagerPreference = {}));
8303
- (function(UserServiceManager2) {
8304
- UserServiceManager2["Launchd"] = "launchd";
8305
- UserServiceManager2["None"] = "none";
8306
- UserServiceManager2["Supervisor"] = "supervisor";
8307
- UserServiceManager2["Systemd"] = "systemd";
8308
- })(UserServiceManager || (UserServiceManager = {}));
8309
- defaultServiceManagerRuntime = {
8310
- operatingSystem: (0, import_node_os6.platform)(),
8311
- async run(command, argumentsList) {
8312
- const result = await execFileAsync2(command, argumentsList, {
8313
- encoding: "utf8"
8314
- });
8315
- return {
8316
- stderr: String(result.stderr),
8317
- stdout: String(result.stdout)
8318
- };
8319
- }
8320
- };
9175
+ import_node_path9 = require("path");
9176
+ init_contracts();
9177
+ init_version();
9178
+ init_enums();
9179
+ init_device_identity();
9180
+ init_relay_client();
9181
+ connectedPairingStatus = 3;
9182
+ rejectedPairingStatus = 4;
9183
+ expiredPairingStatus = 5;
9184
+ pairingPollMilliseconds = 2e3;
8321
9185
  }
8322
9186
  });
8323
9187
 
@@ -8356,7 +9220,11 @@ async function runMachineCli(argumentsList, entrypoint) {
8356
9220
  return;
8357
9221
  }
8358
9222
  if (command === "daemon") {
8359
- await daemonCommand(store);
9223
+ await daemonCommand(store, entrypoint);
9224
+ return;
9225
+ }
9226
+ if (command === "daemon-reconcile") {
9227
+ await daemonReconcileCommand(store, commandArguments, entrypoint);
8360
9228
  return;
8361
9229
  }
8362
9230
  if (command === "service") {
@@ -8368,7 +9236,7 @@ async function runMachineCli(argumentsList, entrypoint) {
8368
9236
  async function connectCommand(store, argumentsList, entrypoint) {
8369
9237
  const options = parseOptions(argumentsList);
8370
9238
  const connectionCode = requiredOption(options, "code");
8371
- const rootPath = (0, import_node_path8.resolve)(options.root ?? process.cwd());
9239
+ const rootPath = (0, import_node_path10.resolve)(options.root ?? process.cwd());
8372
9240
  const serviceManagerPreference = requestedServiceManagerPreference(options);
8373
9241
  await validateExplicitServiceManagerPreference(serviceManagerPreference);
8374
9242
  writeLine("Internal Full Host Access: enabled");
@@ -8496,8 +9364,10 @@ async function disconnectCommand(store, argumentsList) {
8496
9364
  }
8497
9365
  writeLine(`Disconnected Local Machine connection ${connectionId}.`);
8498
9366
  }
8499
- async function daemonCommand(store) {
8500
- const daemon = new MachineConnectorDaemon(store);
9367
+ async function daemonCommand(store, entrypoint) {
9368
+ const daemon = new MachineConnectorDaemon(store, {
9369
+ cliVersion: entrypoint.cliVersion
9370
+ });
8501
9371
  process.once("SIGINT", () => {
8502
9372
  void daemon.stop();
8503
9373
  });
@@ -8506,6 +9376,31 @@ async function daemonCommand(store) {
8506
9376
  });
8507
9377
  await daemon.start();
8508
9378
  }
9379
+ async function daemonReconcileCommand(store, argumentsList, entrypoint) {
9380
+ const options = parseOptions(argumentsList);
9381
+ if (!entrypoint.cliVersion) {
9382
+ throw new Error("The CLI version is required to reconcile the managed daemon");
9383
+ }
9384
+ try {
9385
+ const result = await reconcileManagedDaemon({
9386
+ ...entrypoint,
9387
+ cliVersion: entrypoint.cliVersion,
9388
+ onActiveJobs: (count) => {
9389
+ writeErrorLine(`Warning: restarting the managed Connector will interrupt ${count} active ${count === 1 ? "Job" : "Jobs"}.`);
9390
+ }
9391
+ }, store);
9392
+ if (options.report === "true" && result.outcome === DaemonReconcileOutcome.Restarted) {
9393
+ writeErrorLine(`Managed Connector restarted with ${result.manager} and CLI ${entrypoint.cliVersion}.`);
9394
+ }
9395
+ } catch (error) {
9396
+ if (error instanceof DaemonRefreshError) {
9397
+ writeErrorLine(`Warning: CLI update succeeded, but managed Connector refresh failed during ${error.stage}: ${error.message}. Run \`moxt machine service restart\`.`);
9398
+ process.exitCode = 1;
9399
+ return;
9400
+ }
9401
+ throw error;
9402
+ }
9403
+ }
8509
9404
  async function serviceCommand(store, argumentsList, entrypoint) {
8510
9405
  const action = argumentsList[0] ?? "install";
8511
9406
  const options = parseOptions(argumentsList.slice(1));
@@ -8570,6 +9465,10 @@ function requiredOption(options, name) {
8570
9465
  }
8571
9466
  return value;
8572
9467
  }
9468
+ function writeErrorLine(value) {
9469
+ process.stderr.write(`${value}
9470
+ `);
9471
+ }
8573
9472
  function requestedServiceManagerPreference(options) {
8574
9473
  const requestedValue = options["service-manager"] ?? ServiceManagerPreference.Auto;
8575
9474
  if (process.env.MOXT_MACHINE_SKIP_SERVICE === "1" && requestedValue === ServiceManagerPreference.Auto) {
@@ -8597,14 +9496,14 @@ async function waitForDaemonOnline(store) {
8597
9496
  return;
8598
9497
  }
8599
9498
  } catch {
8600
- await delay5(500);
9499
+ await delay8(500);
8601
9500
  }
8602
9501
  }
8603
9502
  throw new Error("The service was installed but the Connector did not become online within 30 seconds");
8604
9503
  }
8605
9504
  async function readOptionalFile2(path4) {
8606
9505
  try {
8607
- return await (0, import_promises14.readFile)(path4, "utf8");
9506
+ return await (0, import_promises16.readFile)(path4, "utf8");
8608
9507
  } catch {
8609
9508
  return "";
8610
9509
  }
@@ -8627,19 +9526,20 @@ function writeLine(message) {
8627
9526
  process.stdout.write(`${message}
8628
9527
  `);
8629
9528
  }
8630
- function delay5(milliseconds) {
9529
+ function delay8(milliseconds) {
8631
9530
  return new Promise((resolvePromise) => {
8632
9531
  setTimeout(resolvePromise, milliseconds);
8633
9532
  });
8634
9533
  }
8635
- var import_promises14, import_node_path8, defaultRelayOrigin;
9534
+ var import_promises16, import_node_path10, defaultRelayOrigin;
8636
9535
  var init_cli = __esm({
8637
9536
  "../machine-connector/dist/cli.js"() {
8638
9537
  "use strict";
8639
9538
  init_cjs_shims();
8640
- import_promises14 = require("fs/promises");
8641
- import_node_path8 = require("path");
9539
+ import_promises16 = require("fs/promises");
9540
+ import_node_path10 = require("path");
8642
9541
  init_daemon();
9542
+ init_daemon_reconcile();
8643
9543
  init_doctor();
8644
9544
  init_local_ipc();
8645
9545
  init_machine_manager();
@@ -8654,6 +9554,8 @@ var init_cli = __esm({
8654
9554
  // ../machine-connector/dist/index.js
8655
9555
  var dist_exports = {};
8656
9556
  __export(dist_exports, {
9557
+ DaemonReconcileOutcome: () => DaemonReconcileOutcome,
9558
+ DaemonRefreshError: () => DaemonRefreshError,
8657
9559
  DoctorCheckStatus: () => DoctorCheckStatus,
8658
9560
  LocalIpcServer: () => LocalIpcServer,
8659
9561
  MachineClaudePermissionMode: () => MachineClaudePermissionMode,
@@ -8702,8 +9604,12 @@ __export(dist_exports, {
8702
9604
  isTerminalJobStatus: () => isTerminalJobStatus,
8703
9605
  machineManagerActions: () => machineManagerActions,
8704
9606
  machineProtocolVersion: () => machineProtocolVersion,
9607
+ managedServiceOwnsProcess: () => managedServiceOwnsProcess,
8705
9608
  pairMachine: () => pairMachine,
8706
9609
  parseServiceManagerPreference: () => parseServiceManagerPreference,
9610
+ reconcileManagedDaemon: () => reconcileManagedDaemon,
9611
+ recordedServiceManager: () => recordedServiceManager,
9612
+ refreshManagedUserService: () => refreshManagedUserService,
8707
9613
  renderMachineManager: () => renderMachineManager,
8708
9614
  requestRuntimeStatus: () => requestRuntimeStatus,
8709
9615
  resolveWorkingDirectory: () => resolveWorkingDirectory,
@@ -8723,6 +9629,7 @@ var init_dist = __esm({
8723
9629
  init_v1();
8724
9630
  init_cli();
8725
9631
  init_daemon();
9632
+ init_daemon_reconcile();
8726
9633
  init_claude_executor();
8727
9634
  init_doctor();
8728
9635
  init_local_ipc();
@@ -8911,7 +9818,7 @@ function getApiKeyOrUndefined() {
8911
9818
 
8912
9819
  // src/utils/http.ts
8913
9820
  function getUserAgent() {
8914
- return `moxt-cli/${"0.8.0"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
9821
+ return `moxt-cli/${"0.8.2"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
8915
9822
  }
8916
9823
  async function sendRequest(method, path4, init) {
8917
9824
  const response = await fetch(`${getApiBaseUrl()}${path4}`, {
@@ -9087,8 +9994,8 @@ function readCommentContentFile(path4) {
9087
9994
  if (!fs.existsSync(path4)) {
9088
9995
  throw new FileCommentOptionsError(`Error: comment content file not found: ${path4}`);
9089
9996
  }
9090
- const stat2 = fs.statSync(path4);
9091
- if (!stat2.isFile()) {
9997
+ const stat3 = fs.statSync(path4);
9998
+ if (!stat3.isFile()) {
9092
9999
  throw new FileCommentOptionsError(`Error: comment content path is not a file: ${path4}`);
9093
10000
  }
9094
10001
  const buffer2 = fs.readFileSync(path4);
@@ -9762,8 +10669,8 @@ var FileTokenizer = class _FileTokenizer extends AbstractTokenizer {
9762
10669
  */
9763
10670
  static async fromFile(sourceFilePath) {
9764
10671
  const fileHandle = await (0, import_promises.open)(sourceFilePath, "r");
9765
- const stat2 = await fileHandle.stat();
9766
- return new _FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat2.size } });
10672
+ const stat3 = await fileHandle.stat();
10673
+ return new _FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat3.size } });
9767
10674
  }
9768
10675
  constructor(fileHandle, options) {
9769
10676
  super(options);
@@ -15309,10 +16216,10 @@ function resolveAll(constructs2, events, context) {
15309
16216
  const called = [];
15310
16217
  let index2 = -1;
15311
16218
  while (++index2 < constructs2.length) {
15312
- const resolve6 = constructs2[index2].resolveAll;
15313
- if (resolve6 && !called.includes(resolve6)) {
15314
- events = resolve6(events, context);
15315
- called.push(resolve6);
16219
+ const resolve8 = constructs2[index2].resolveAll;
16220
+ if (resolve8 && !called.includes(resolve8)) {
16221
+ events = resolve8(events, context);
16222
+ called.push(resolve8);
15316
16223
  }
15317
16224
  }
15318
16225
  return events;
@@ -20552,7 +21459,7 @@ var serviceManagerOption = new Option(
20552
21459
  "--service-manager <manager>",
20553
21460
  "Background service manager: auto, systemd, supervisor, or none"
20554
21461
  ).choices(["auto", "systemd", "supervisor", "none"]).default("auto");
20555
- function registerMachineCommand(program3) {
21462
+ function registerMachineCommand(program3, cliVersion) {
20556
21463
  const machine = program3.command("machine").description("Connect and operate a Local Machine");
20557
21464
  machine.command("connect").description(
20558
21465
  "Pair this machine and install the background Connector service"
@@ -20625,15 +21532,22 @@ function registerMachineCommand(program3) {
20625
21532
  machine.command("daemon", { hidden: true }).description("Run the Connector daemon").action(async () => {
20626
21533
  await runConnectorCli(["daemon"]);
20627
21534
  });
20628
- }
20629
- async function runConnectorCli(argumentsList) {
20630
- const { runMachineCli: runMachineCli2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
20631
- await runMachineCli2(argumentsList, {
20632
- commandArguments: ["machine", "daemon"],
20633
- entrypointPath: process.argv[1],
20634
- environment: {},
20635
- nodePath: process.execPath
21535
+ machine.command("daemon-reconcile", { hidden: true }).option("--report").action(async (options) => {
21536
+ await runConnectorCli([
21537
+ "daemon-reconcile",
21538
+ ...options.report ? ["--report"] : []
21539
+ ]);
20636
21540
  });
21541
+ async function runConnectorCli(argumentsList) {
21542
+ const { runMachineCli: runMachineCli2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
21543
+ await runMachineCli2(argumentsList, {
21544
+ cliVersion,
21545
+ commandArguments: ["machine", "daemon"],
21546
+ entrypointPath: process.argv[1],
21547
+ environment: {},
21548
+ nodePath: process.execPath
21549
+ });
21550
+ }
20637
21551
  }
20638
21552
  function appendOption2(argumentsList, flag, value) {
20639
21553
  if (value) {
@@ -20891,7 +21805,7 @@ init_cjs_shims();
20891
21805
 
20892
21806
  // src/update/install.ts
20893
21807
  init_cjs_shims();
20894
- var import_node_child_process5 = require("child_process");
21808
+ var import_node_child_process6 = require("child_process");
20895
21809
  var import_node_fs2 = require("fs");
20896
21810
  var path3 = __toESM(require("path"), 1);
20897
21811
 
@@ -21007,7 +21921,7 @@ function runUpgrade(channel, targetVersion) {
21007
21921
  }
21008
21922
  process.stderr.write(`Updating via \`${display}\`...
21009
21923
  `);
21010
- const installation = (0, import_node_child_process5.spawnSync)(plan.command, plan.args, {
21924
+ const installation = (0, import_node_child_process6.spawnSync)(plan.command, plan.args, {
21011
21925
  encoding: "utf8",
21012
21926
  env: process.env,
21013
21927
  maxBuffer: 10 * 1024 * 1024,
@@ -21022,7 +21936,7 @@ function runUpgrade(channel, targetVersion) {
21022
21936
  success: false
21023
21937
  };
21024
21938
  }
21025
- const verification = (0, import_node_child_process5.spawnSync)("moxt", ["--version"], {
21939
+ const verification = (0, import_node_child_process6.spawnSync)("moxt", ["--version"], {
21026
21940
  encoding: "utf8",
21027
21941
  env: process.env,
21028
21942
  maxBuffer: 1024 * 1024,
@@ -21036,7 +21950,35 @@ function runUpgrade(channel, targetVersion) {
21036
21950
  success: false
21037
21951
  };
21038
21952
  }
21039
- return { installedVersion, success: true };
21953
+ const daemonRefresh = (0, import_node_child_process6.spawnSync)(
21954
+ "moxt",
21955
+ ["machine", "daemon-reconcile", "--report"],
21956
+ {
21957
+ encoding: "utf8",
21958
+ env: process.env,
21959
+ maxBuffer: 10 * 1024 * 1024,
21960
+ shell: false
21961
+ }
21962
+ );
21963
+ forwardToStderr(daemonRefresh.stdout);
21964
+ forwardToStderr(daemonRefresh.stderr);
21965
+ if (daemonRefresh.error || daemonRefresh.status !== 0) {
21966
+ if (!daemonRefresh.stderr) {
21967
+ process.stderr.write(
21968
+ "Warning: CLI update succeeded, but managed Connector refresh failed during invocation. Run `moxt machine service restart`.\n"
21969
+ );
21970
+ }
21971
+ return {
21972
+ daemonRefreshSucceeded: false,
21973
+ installedVersion,
21974
+ success: true
21975
+ };
21976
+ }
21977
+ return {
21978
+ daemonRefreshSucceeded: true,
21979
+ installedVersion,
21980
+ success: true
21981
+ };
21040
21982
  }
21041
21983
  function detectInstallMethod() {
21042
21984
  const userAgentMethod = packageManagerFromUserAgent(process.env.npm_config_user_agent);
@@ -21312,7 +22254,7 @@ function registerWorkspaceCommand(program3) {
21312
22254
  // src/commands/workflow.ts
21313
22255
  init_cjs_shims();
21314
22256
  var fs5 = __toESM(require("fs"), 1);
21315
- var import_node_util5 = require("util");
22257
+ var import_node_util6 = require("util");
21316
22258
  var MAX_DESC_LENGTH = 5e3;
21317
22259
  var MAX_COMMENT_CONTENT_LENGTH = 5e3;
21318
22260
  var MAX_COMMENT_CONTENT_BYTES = MAX_COMMENT_CONTENT_LENGTH * 4;
@@ -21407,8 +22349,8 @@ function readDescFile(path4) {
21407
22349
  if (!fs5.existsSync(path4)) {
21408
22350
  throw new WorkflowOptionsError(`Error: desc file not found: ${path4}`);
21409
22351
  }
21410
- const stat2 = fs5.statSync(path4);
21411
- if (!stat2.isFile()) {
22352
+ const stat3 = fs5.statSync(path4);
22353
+ if (!stat3.isFile()) {
21412
22354
  throw new WorkflowOptionsError(`Error: desc file is not a file: ${path4}`);
21413
22355
  }
21414
22356
  const buffer2 = fs5.readFileSync(path4);
@@ -21425,11 +22367,11 @@ function readCommentContentFile2(path4) {
21425
22367
  if (!fs5.existsSync(path4)) {
21426
22368
  throw new WorkflowOptionsError(`Error: comment content file not found: ${path4}`);
21427
22369
  }
21428
- const stat2 = fs5.statSync(path4);
21429
- if (!stat2.isFile()) {
22370
+ const stat3 = fs5.statSync(path4);
22371
+ if (!stat3.isFile()) {
21430
22372
  throw new WorkflowOptionsError(`Error: comment content path is not a file: ${path4}`);
21431
22373
  }
21432
- if (stat2.size > MAX_COMMENT_CONTENT_BYTES) {
22374
+ if (stat3.size > MAX_COMMENT_CONTENT_BYTES) {
21433
22375
  throw new WorkflowOptionsError(
21434
22376
  `Error: comment content file must be at most ${MAX_COMMENT_CONTENT_LENGTH} characters.`
21435
22377
  );
@@ -21443,7 +22385,7 @@ function readCommentContentFile2(path4) {
21443
22385
  }
21444
22386
  let content3;
21445
22387
  try {
21446
- content3 = new import_node_util5.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer2);
22388
+ content3 = new import_node_util6.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer2);
21447
22389
  } catch {
21448
22390
  throw new WorkflowOptionsError("Error: comment content file must contain valid UTF-8 text.");
21449
22391
  }
@@ -21478,6 +22420,30 @@ function parseAssigneeBody(options, allowClear) {
21478
22420
  if (teammateId !== void 0) return { assigneeAiTeammateId: teammateId };
21479
22421
  return {};
21480
22422
  }
22423
+ function parseTaskListFilterQuery(options) {
22424
+ const filterOwnerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
22425
+ const filterPriority = parsePriority(options.priority);
22426
+ const filterAssigneeHumanId = parseOptionalPositiveInteger(options.assigneeHumanId, "--assignee-human-id");
22427
+ const filterAssigneeAssistantId = parseOptionalPositiveInteger(
22428
+ options.assigneeAssistantId,
22429
+ "--assignee-assistant-id"
22430
+ );
22431
+ const filterAssigneeTeammateId = parseOptionalPositiveInteger(
22432
+ options.assigneeTeammateId,
22433
+ "--assignee-teammate-id"
22434
+ );
22435
+ const assigneeFilterCount = (filterAssigneeHumanId !== void 0 ? 1 : 0) + (filterAssigneeAssistantId !== void 0 ? 1 : 0) + (filterAssigneeTeammateId !== void 0 ? 1 : 0);
22436
+ if (assigneeFilterCount > 1) {
22437
+ throw new WorkflowOptionsError("Error: assignee filter options are mutually exclusive.");
22438
+ }
22439
+ return {
22440
+ filterOwnerHumanId,
22441
+ filterPriority,
22442
+ filterAssigneeHumanId,
22443
+ filterAssigneeAssistantId,
22444
+ filterAssigneeTeammateId
22445
+ };
22446
+ }
21481
22447
  function parsePreferredAssigneeBody(options) {
21482
22448
  const hasClear = options.clearPreferredAssignee === true;
21483
22449
  const humanId = parseOptionalPositiveInteger(options.preferredHumanId, "--preferred-human-id");
@@ -21951,17 +22917,20 @@ function registerTransitionCommands(workflow) {
21951
22917
  function registerTaskCommands(workflow) {
21952
22918
  const task = workflow.command("task").description("Workflow task operations");
21953
22919
  addWorkspaceOption(
21954
- 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", "20").option("--cursor <cursor>", "Pagination cursor")
22920
+ 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")
21955
22921
  ).action(
21956
22922
  async (options) => {
21957
- const query = runOrExit4(() => buildQuery({
21958
- scope: parseTaskScope(options.scope),
21959
- limit: parseSearchLimit(options.limit, 20, 100),
21960
- cursor: options.cursor,
21961
- workflowFileId: options.workflowFileId
21962
- }));
22923
+ const query = runOrExit4(
22924
+ () => buildQuery({
22925
+ scope: parseTaskScope(options.scope),
22926
+ limit: parseSearchLimit(options.limit, 50, 100),
22927
+ cursor: options.cursor,
22928
+ workflowFileId: options.workflowFileId,
22929
+ ...parseTaskListFilterQuery(options)
22930
+ })
22931
+ );
21963
22932
  startSpinner("Fetching workflow tasks...");
21964
- const response = await httpGet(`/workspaces/${options.workspace}/workflow-tasks-v2${query}`);
22933
+ const response = await httpGet(`/workspaces/${options.workspace}/workflow-tasks-v3${query}`);
21965
22934
  if (!response.ok) {
21966
22935
  stopSpinner(false, "Failed");
21967
22936
  failResponse(response);
@@ -22326,7 +23295,7 @@ function createProgram(version) {
22326
23295
  registerWorkspaceCommand(program3);
22327
23296
  registerFileCommand(program3);
22328
23297
  registerMemoryCommand(program3);
22329
- registerMachineCommand(program3);
23298
+ registerMachineCommand(program3, version);
22330
23299
  registerWorkflowCommand(program3);
22331
23300
  registerMiniappCommand(program3);
22332
23301
  registerTelemetryCommand(program3);
@@ -22342,7 +23311,7 @@ var FLUSH_TIMEOUT_MS = 3e3;
22342
23311
  var MAX_BATCH_SIZE = 100;
22343
23312
  function commonLabels() {
22344
23313
  return {
22345
- cli_version: "0.8.0",
23314
+ cli_version: "0.8.2",
22346
23315
  node_version: process.versions.node,
22347
23316
  os: (0, import_node_os7.platform)(),
22348
23317
  arch: (0, import_node_os7.arch)(),
@@ -22388,7 +23357,7 @@ async function flush() {
22388
23357
  }
22389
23358
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
22390
23359
  const payload = {
22391
- release_id: "0.8.0",
23360
+ release_id: "0.8.2",
22392
23361
  client_type: "cli",
22393
23362
  metric_data_list: batch.map((m) => ({
22394
23363
  profile: "cli",
@@ -22589,7 +23558,7 @@ function registryWorker() {
22589
23558
 
22590
23559
  // src/update/prompt.ts
22591
23560
  init_cjs_shims();
22592
- var import_promises15 = require("readline/promises");
23561
+ var import_promises17 = require("readline/promises");
22593
23562
  async function promptForUpdate(input, output, currentVersion, latestVersion, timeoutMs) {
22594
23563
  output.write(`
22595
23564
  A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion}
@@ -22602,7 +23571,7 @@ A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion
22602
23571
  const controller = new AbortController();
22603
23572
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
22604
23573
  timeout.unref();
22605
- const readline = (0, import_promises15.createInterface)({ input, output, terminal: true });
23574
+ const readline = (0, import_promises17.createInterface)({ input, output, terminal: true });
22606
23575
  try {
22607
23576
  const answer = await readline.question("", { signal: controller.signal });
22608
23577
  if (answer.trim() === "1") return "update";
@@ -22703,9 +23672,69 @@ function commandPath2(command) {
22703
23672
  return names;
22704
23673
  }
22705
23674
 
23675
+ // src/update/daemon-reconcile-hook.ts
23676
+ init_cjs_shims();
23677
+ var import_node_path11 = require("path");
23678
+ function installDaemonReconcileHook(program3, cliVersion) {
23679
+ program3.hook("preAction", async (_thisCommand, actionCommand) => {
23680
+ if (!isEligible2(actionCommand)) return;
23681
+ const entrypointPath = process.argv[1];
23682
+ if (!entrypointPath) return;
23683
+ const {
23684
+ DaemonRefreshError: DaemonRefreshError2,
23685
+ reconcileManagedDaemon: reconcileManagedDaemon2
23686
+ } = await Promise.resolve().then(() => (init_dist(), dist_exports));
23687
+ try {
23688
+ await reconcileManagedDaemon2({
23689
+ cliVersion,
23690
+ commandArguments: ["machine", "daemon"],
23691
+ entrypointPath: (0, import_node_path11.resolve)(entrypointPath),
23692
+ environment: {},
23693
+ nodePath: (0, import_node_path11.resolve)(process.execPath),
23694
+ onActiveJobs: (count) => {
23695
+ process.stderr.write(
23696
+ `Warning: restarting the managed Connector will interrupt ${count} active ${count === 1 ? "Job" : "Jobs"}.
23697
+ `
23698
+ );
23699
+ }
23700
+ });
23701
+ } catch (error) {
23702
+ if (error instanceof DaemonRefreshError2) {
23703
+ process.stderr.write(
23704
+ `Warning: managed Connector refresh failed during ${error.stage}: ${error.message}. Run \`moxt machine service restart\`.
23705
+ `
23706
+ );
23707
+ return;
23708
+ }
23709
+ process.stderr.write(
23710
+ `Warning: managed Connector refresh could not be prepared: ${error instanceof Error ? error.message : String(error)}. Run \`moxt machine service restart\`.
23711
+ `
23712
+ );
23713
+ }
23714
+ });
23715
+ }
23716
+ function isEligible2(actionCommand) {
23717
+ const path4 = commandPath3(actionCommand);
23718
+ if (path4[0] === "upgrade" || path4[0] === "telemetry") return false;
23719
+ if (path4[0] === "machine" && path4[1] === "daemon") return false;
23720
+ if (path4[0] === "machine" && path4[1] === "daemon-reconcile") return false;
23721
+ if (path4[0] === "machine" && path4[1] === "service") return false;
23722
+ return true;
23723
+ }
23724
+ function commandPath3(command) {
23725
+ const names = [];
23726
+ let current2 = command;
23727
+ while (current2?.parent) {
23728
+ names.unshift(current2.name());
23729
+ current2 = current2.parent;
23730
+ }
23731
+ return names;
23732
+ }
23733
+
22706
23734
  // src/index.ts
22707
- var program2 = createProgram("0.8.0");
22708
- installUpdateHook(program2, "0.8.0");
23735
+ var program2 = createProgram("0.8.2");
23736
+ installDaemonReconcileHook(program2, "0.8.2");
23737
+ installUpdateHook(program2, "0.8.2");
22709
23738
  instrumentProgram(program2);
22710
23739
  installExitHandler();
22711
23740
  program2.parseAsync(process.argv).then(async () => {