@moxt-ai/cli 0.8.0-beta.5 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -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,189 @@ var init_local_ipc = __esm({
5541
5649
  }
5542
5650
  });
5543
5651
 
5652
+ // ../machine-connector/dist/runtime/process-lock.js
5653
+ async function removeStalePendingLockCandidates(path4) {
5654
+ const directory = (0, import_node_path5.dirname)(path4);
5655
+ const lockName = (0, import_node_path5.basename)(path4);
5656
+ let names;
5657
+ try {
5658
+ names = await (0, import_promises7.readdir)(directory);
5659
+ } catch (error) {
5660
+ if (isNodeErrorCode2(error, "ENOENT"))
5661
+ return;
5662
+ throw error;
5663
+ }
5664
+ for (const name of names) {
5665
+ if (!isPendingLockCandidateName(lockName, name))
5666
+ continue;
5667
+ await removeOldUnchangedFile((0, import_node_path5.join)(directory, name));
5668
+ }
5669
+ }
5670
+ function isPendingLockCandidateName(lockName, name) {
5671
+ const prefix = `${lockName}.`;
5672
+ const suffix = ".pending";
5673
+ if (!name.startsWith(prefix) || !name.endsWith(suffix))
5674
+ return false;
5675
+ const identity = name.slice(prefix.length, -suffix.length);
5676
+ const separator = identity.indexOf(".");
5677
+ if (separator <= 0 || identity.indexOf(".", separator + 1) >= 0) {
5678
+ return false;
5679
+ }
5680
+ const processId = Number(identity.slice(0, separator));
5681
+ const token = identity.slice(separator + 1);
5682
+ 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);
5683
+ }
5684
+ async function removeOldUnchangedFile(path4) {
5685
+ let metadata;
5686
+ try {
5687
+ metadata = await (0, import_promises7.stat)(path4);
5688
+ } catch (error) {
5689
+ return isNodeErrorCode2(error, "ENOENT");
5690
+ }
5691
+ if (Date.now() - metadata.mtimeMs < incompleteLockStaleMilliseconds) {
5692
+ return false;
5693
+ }
5694
+ let current2;
5695
+ try {
5696
+ current2 = await (0, import_promises7.stat)(path4);
5697
+ } catch (error) {
5698
+ return isNodeErrorCode2(error, "ENOENT");
5699
+ }
5700
+ if (!sameFileMetadata(metadata, current2))
5701
+ return false;
5702
+ await (0, import_promises7.rm)(path4, { force: true });
5703
+ return true;
5704
+ }
5705
+ async function createCompleteLock(path4, record2) {
5706
+ const candidatePath = `${path4}.${record2.pid}.${record2.token}.pending`;
5707
+ try {
5708
+ await (0, import_promises7.writeFile)(candidatePath, `${JSON.stringify(record2)}
5709
+ `, {
5710
+ encoding: "utf8",
5711
+ flag: "wx",
5712
+ mode: 384
5713
+ });
5714
+ await (0, import_promises7.link)(candidatePath, path4);
5715
+ } finally {
5716
+ await (0, import_promises7.rm)(candidatePath, { force: true });
5717
+ }
5718
+ }
5719
+ async function readLockRecord(path4) {
5720
+ try {
5721
+ const parsed = JSON.parse(await (0, import_promises7.readFile)(path4, "utf8"));
5722
+ if (typeof parsed.createdAt !== "number" || !Number.isFinite(parsed.createdAt) || typeof parsed.pid !== "number" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0 || typeof parsed.token !== "string" || parsed.token.length === 0) {
5723
+ return void 0;
5724
+ }
5725
+ return parsed;
5726
+ } catch (error) {
5727
+ if (isNodeErrorCode2(error, "ENOENT"))
5728
+ return void 0;
5729
+ if (error instanceof SyntaxError)
5730
+ return void 0;
5731
+ throw error;
5732
+ }
5733
+ }
5734
+ async function removeLockIfTokenMatches(path4, token) {
5735
+ const current2 = await readLockRecord(path4);
5736
+ if (current2?.token === token)
5737
+ await (0, import_promises7.rm)(path4, { force: true });
5738
+ }
5739
+ async function removeStaleIncompleteLock(path4) {
5740
+ let metadata;
5741
+ try {
5742
+ metadata = await (0, import_promises7.stat)(path4);
5743
+ } catch (error) {
5744
+ return isNodeErrorCode2(error, "ENOENT");
5745
+ }
5746
+ if (Date.now() - metadata.mtimeMs < incompleteLockStaleMilliseconds) {
5747
+ return false;
5748
+ }
5749
+ if (await readLockRecord(path4))
5750
+ return false;
5751
+ let current2;
5752
+ try {
5753
+ current2 = await (0, import_promises7.stat)(path4);
5754
+ } catch (error) {
5755
+ return isNodeErrorCode2(error, "ENOENT");
5756
+ }
5757
+ if (!sameFileMetadata(metadata, current2))
5758
+ return false;
5759
+ await (0, import_promises7.rm)(path4, { force: true });
5760
+ return true;
5761
+ }
5762
+ function sameFileMetadata(first, second) {
5763
+ return first.dev === second.dev && first.ino === second.ino && first.mtimeMs === second.mtimeMs && first.size === second.size;
5764
+ }
5765
+ function processIsAlive(pid) {
5766
+ try {
5767
+ process.kill(pid, 0);
5768
+ return true;
5769
+ } catch (error) {
5770
+ return !isNodeErrorCode2(error, "ESRCH");
5771
+ }
5772
+ }
5773
+ function isNodeErrorCode2(error, expectedCode) {
5774
+ return error instanceof Error && "code" in error && error.code === expectedCode;
5775
+ }
5776
+ function delay3(milliseconds) {
5777
+ return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
5778
+ }
5779
+ var import_node_crypto4, import_promises7, import_node_path5, incompleteLockStaleMilliseconds, ProcessLock;
5780
+ var init_process_lock = __esm({
5781
+ "../machine-connector/dist/runtime/process-lock.js"() {
5782
+ "use strict";
5783
+ init_cjs_shims();
5784
+ import_node_crypto4 = require("crypto");
5785
+ import_promises7 = require("fs/promises");
5786
+ import_node_path5 = require("path");
5787
+ incompleteLockStaleMilliseconds = 3e4;
5788
+ ProcessLock = class _ProcessLock {
5789
+ path;
5790
+ token;
5791
+ released = false;
5792
+ constructor(path4, token) {
5793
+ this.path = path4;
5794
+ this.token = token;
5795
+ }
5796
+ static async acquire(path4, options) {
5797
+ await removeStalePendingLockCandidates(path4);
5798
+ const deadline = Date.now() + options.timeoutMilliseconds;
5799
+ const token = (0, import_node_crypto4.randomUUID)();
5800
+ while (true) {
5801
+ try {
5802
+ await createCompleteLock(path4, {
5803
+ createdAt: Date.now(),
5804
+ pid: process.pid,
5805
+ token
5806
+ });
5807
+ return new _ProcessLock(path4, token);
5808
+ } catch (error) {
5809
+ if (!isNodeErrorCode2(error, "EEXIST"))
5810
+ throw error;
5811
+ }
5812
+ const existing = await readLockRecord(path4);
5813
+ if (existing && !processIsAlive(existing.pid)) {
5814
+ await removeLockIfTokenMatches(path4, existing.token);
5815
+ continue;
5816
+ }
5817
+ if (!existing && await removeStaleIncompleteLock(path4)) {
5818
+ continue;
5819
+ }
5820
+ if (Date.now() >= deadline)
5821
+ return void 0;
5822
+ await delay3(Math.min(50, Math.max(1, deadline - Date.now())));
5823
+ }
5824
+ }
5825
+ async release() {
5826
+ if (this.released)
5827
+ return;
5828
+ this.released = true;
5829
+ await removeLockIfTokenMatches(this.path, this.token);
5830
+ }
5831
+ };
5832
+ }
5833
+ });
5834
+
5544
5835
  // ../machine-connector/dist/runtime/version.js
5545
5836
  var connectorVersion;
5546
5837
  var init_version = __esm({
@@ -5728,12 +6019,12 @@ var init_relay_client = __esm({
5728
6019
  });
5729
6020
 
5730
6021
  // ../machine-connector/dist/runtime/runtime-logger.js
5731
- var import_promises7, RuntimeLogger;
6022
+ var import_promises8, RuntimeLogger;
5732
6023
  var init_runtime_logger = __esm({
5733
6024
  "../machine-connector/dist/runtime/runtime-logger.js"() {
5734
6025
  "use strict";
5735
6026
  init_cjs_shims();
5736
- import_promises7 = require("fs/promises");
6027
+ import_promises8 = require("fs/promises");
5737
6028
  RuntimeLogger = class {
5738
6029
  store;
5739
6030
  constructor(store) {
@@ -5747,7 +6038,7 @@ var init_runtime_logger = __esm({
5747
6038
  await this.write("error", message, metadata, this.store.runtimeErrorLogPath());
5748
6039
  }
5749
6040
  async write(level, message, metadata, path4) {
5750
- await (0, import_promises7.appendFile)(path4, `${JSON.stringify({
6041
+ await (0, import_promises8.appendFile)(path4, `${JSON.stringify({
5751
6042
  level,
5752
6043
  message,
5753
6044
  metadata,
@@ -5768,26 +6059,27 @@ function defaultRuntimeDirectory() {
5768
6059
  if (override) {
5769
6060
  return override;
5770
6061
  }
6062
+ const homeDirectory = process.env.HOME ?? (0, import_node_os3.homedir)();
5771
6063
  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");
6064
+ return (0, import_node_path6.join)(homeDirectory, "Library", "Application Support", "Moxt", "Machine Connector");
5773
6065
  }
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");
6066
+ const stateHome = process.env.XDG_STATE_HOME ?? (0, import_node_path6.join)(homeDirectory, ".local", "state");
6067
+ return (0, import_node_path6.join)(stateHome, "moxt", "machine-connector");
5776
6068
  }
5777
- function isNodeErrorCode2(error, expectedCode) {
6069
+ function isNodeErrorCode3(error, expectedCode) {
5778
6070
  if (!(error instanceof Error) || !("code" in error)) {
5779
6071
  return false;
5780
6072
  }
5781
6073
  return error.code === expectedCode;
5782
6074
  }
5783
- var import_promises8, import_node_os3, import_node_path5, privateFileMode, privateDirectoryMode, MachineRuntimeStore;
6075
+ var import_promises9, import_node_os3, import_node_path6, privateFileMode, privateDirectoryMode, MachineRuntimeStore;
5784
6076
  var init_store = __esm({
5785
6077
  "../machine-connector/dist/runtime/store.js"() {
5786
6078
  "use strict";
5787
6079
  init_cjs_shims();
5788
- import_promises8 = require("fs/promises");
6080
+ import_promises9 = require("fs/promises");
5789
6081
  import_node_os3 = require("os");
5790
- import_node_path5 = require("path");
6082
+ import_node_path6 = require("path");
5791
6083
  privateFileMode = 384;
5792
6084
  privateDirectoryMode = 448;
5793
6085
  MachineRuntimeStore = class {
@@ -5796,15 +6088,20 @@ var init_store = __esm({
5796
6088
  this.baseDirectory = baseDirectory;
5797
6089
  }
5798
6090
  async initialize() {
5799
- await (0, import_promises8.mkdir)(this.jobsDirectory(), {
6091
+ await (0, import_promises9.mkdir)(this.jobsDirectory(), {
6092
+ mode: privateDirectoryMode,
6093
+ recursive: true
6094
+ });
6095
+ await (0, import_promises9.mkdir)(this.detachedProcessesDirectory(), {
5800
6096
  mode: privateDirectoryMode,
5801
6097
  recursive: true
5802
6098
  });
5803
- await (0, import_promises8.chmod)(this.baseDirectory, privateDirectoryMode);
5804
- await (0, import_promises8.chmod)(this.jobsDirectory(), privateDirectoryMode);
6099
+ await (0, import_promises9.chmod)(this.baseDirectory, privateDirectoryMode);
6100
+ await (0, import_promises9.chmod)(this.jobsDirectory(), privateDirectoryMode);
6101
+ await (0, import_promises9.chmod)(this.detachedProcessesDirectory(), privateDirectoryMode);
5805
6102
  }
5806
6103
  async getCanonicalRoot(rootPath) {
5807
- return await (0, import_promises8.realpath)(rootPath);
6104
+ return await (0, import_promises9.realpath)(rootPath);
5808
6105
  }
5809
6106
  async readIdentity() {
5810
6107
  return await this.readOptionalJson(this.identityPath());
@@ -5847,7 +6144,7 @@ var init_store = __esm({
5847
6144
  await this.writePrivateJson(this.serviceManagerPath(), serviceManager);
5848
6145
  }
5849
6146
  async removeServiceManager() {
5850
- await (0, import_promises8.rm)(this.serviceManagerPath(), { force: true });
6147
+ await (0, import_promises9.rm)(this.serviceManagerPath(), { force: true });
5851
6148
  }
5852
6149
  async readJob(jobId) {
5853
6150
  return await this.readOptionalJson(this.jobPath(jobId));
@@ -5858,16 +6155,16 @@ var init_store = __esm({
5858
6155
  async listJobs() {
5859
6156
  let names = [];
5860
6157
  try {
5861
- names = await (0, import_promises8.readdir)(this.jobsDirectory());
6158
+ names = await (0, import_promises9.readdir)(this.jobsDirectory());
5862
6159
  } catch (error) {
5863
- if (isNodeErrorCode2(error, "ENOENT")) {
6160
+ if (isNodeErrorCode3(error, "ENOENT")) {
5864
6161
  return [];
5865
6162
  }
5866
6163
  throw error;
5867
6164
  }
5868
6165
  const jobs = [];
5869
6166
  for (const name of names.filter((entry) => entry.endsWith(".json"))) {
5870
- const job = await this.readOptionalJson((0, import_node_path5.join)(this.jobsDirectory(), name));
6167
+ const job = await this.readOptionalJson((0, import_node_path6.join)(this.jobsDirectory(), name));
5871
6168
  if (job.value) {
5872
6169
  jobs.push(job.value);
5873
6170
  }
@@ -5875,40 +6172,77 @@ var init_store = __esm({
5875
6172
  return jobs;
5876
6173
  }
5877
6174
  async deleteJob(jobId) {
5878
- await (0, import_promises8.rm)(this.jobPath(jobId), { force: true });
6175
+ await (0, import_promises9.rm)(this.jobPath(jobId), { force: true });
6176
+ }
6177
+ async writeDetachedProcess(resource) {
6178
+ await this.writePrivateJson(this.detachedProcessPath(resource.jobId), resource);
6179
+ }
6180
+ async listDetachedProcesses() {
6181
+ let names = [];
6182
+ try {
6183
+ names = await (0, import_promises9.readdir)(this.detachedProcessesDirectory());
6184
+ } catch (error) {
6185
+ if (isNodeErrorCode3(error, "ENOENT")) {
6186
+ return [];
6187
+ }
6188
+ throw error;
6189
+ }
6190
+ const resources = [];
6191
+ for (const name of names.filter((entry) => entry.endsWith(".json"))) {
6192
+ const resource = await this.readOptionalJson((0, import_node_path6.join)(this.detachedProcessesDirectory(), name));
6193
+ if (resource.value) {
6194
+ resources.push(resource.value);
6195
+ }
6196
+ }
6197
+ return resources;
6198
+ }
6199
+ async deleteDetachedProcess(jobId) {
6200
+ await (0, import_promises9.rm)(this.detachedProcessPath(jobId), { force: true });
5879
6201
  }
5880
6202
  runtimeLogPath() {
5881
- return (0, import_node_path5.join)(this.baseDirectory, "machine-connector.log");
6203
+ return (0, import_node_path6.join)(this.baseDirectory, "machine-connector.log");
5882
6204
  }
5883
6205
  runtimeErrorLogPath() {
5884
- return (0, import_node_path5.join)(this.baseDirectory, "machine-connector.error.log");
6206
+ return (0, import_node_path6.join)(this.baseDirectory, "machine-connector.error.log");
5885
6207
  }
5886
6208
  runtimeStatusPath() {
5887
- return (0, import_node_path5.join)(this.baseDirectory, "runtime-status.json");
6209
+ return (0, import_node_path6.join)(this.baseDirectory, "runtime-status.json");
5888
6210
  }
5889
6211
  runtimeSocketPath() {
5890
6212
  if ((0, import_node_os3.platform)() === "win32") {
5891
6213
  return String.raw`\\.\pipe\moxt-machine-connector`;
5892
6214
  }
5893
- return (0, import_node_path5.join)(this.baseDirectory, "machine-connector.sock");
6215
+ return (0, import_node_path6.join)(this.baseDirectory, "machine-connector.sock");
6216
+ }
6217
+ daemonLockPath() {
6218
+ return (0, import_node_path6.join)(this.baseDirectory, "daemon.lock");
6219
+ }
6220
+ reconcileLockPath() {
6221
+ return (0, import_node_path6.join)(this.baseDirectory, "daemon-reconcile.lock");
5894
6222
  }
5895
6223
  connectionsPath() {
5896
- return (0, import_node_path5.join)(this.baseDirectory, "connections.json");
6224
+ return (0, import_node_path6.join)(this.baseDirectory, "connections.json");
6225
+ }
6226
+ detachedProcessesDirectory() {
6227
+ return (0, import_node_path6.join)(this.baseDirectory, "detached-processes");
6228
+ }
6229
+ detachedProcessPath(jobId) {
6230
+ return (0, import_node_path6.join)(this.detachedProcessesDirectory(), `${jobId}.json`);
5897
6231
  }
5898
6232
  identityPath() {
5899
- return (0, import_node_path5.join)(this.baseDirectory, "identity.json");
6233
+ return (0, import_node_path6.join)(this.baseDirectory, "identity.json");
5900
6234
  }
5901
6235
  serviceManagerPath() {
5902
- return (0, import_node_path5.join)(this.baseDirectory, "service-manager.json");
6236
+ return (0, import_node_path6.join)(this.baseDirectory, "service-manager.json");
5903
6237
  }
5904
6238
  privateKeyPath() {
5905
- return (0, import_node_path5.join)(this.baseDirectory, "device-private-key.pem");
6239
+ return (0, import_node_path6.join)(this.baseDirectory, "device-private-key.pem");
5906
6240
  }
5907
6241
  jobsDirectory() {
5908
- return (0, import_node_path5.join)(this.baseDirectory, "jobs");
6242
+ return (0, import_node_path6.join)(this.baseDirectory, "jobs");
5909
6243
  }
5910
6244
  jobPath(jobId) {
5911
- return (0, import_node_path5.join)(this.jobsDirectory(), `${jobId}.json`);
6245
+ return (0, import_node_path6.join)(this.jobsDirectory(), `${jobId}.json`);
5912
6246
  }
5913
6247
  async readOptionalJson(path4) {
5914
6248
  const content3 = await this.readOptionalText(path4);
@@ -5919,9 +6253,9 @@ var init_store = __esm({
5919
6253
  }
5920
6254
  async readOptionalText(path4) {
5921
6255
  try {
5922
- return { value: await (0, import_promises8.readFile)(path4, "utf8") };
6256
+ return { value: await (0, import_promises9.readFile)(path4, "utf8") };
5923
6257
  } catch (error) {
5924
- if (isNodeErrorCode2(error, "ENOENT")) {
6258
+ if (isNodeErrorCode3(error, "ENOENT")) {
5925
6259
  return {};
5926
6260
  }
5927
6261
  throw error;
@@ -5932,17 +6266,17 @@ var init_store = __esm({
5932
6266
  `);
5933
6267
  }
5934
6268
  async writePrivateText(path4, value) {
5935
- await (0, import_promises8.mkdir)((0, import_node_path5.dirname)(path4), {
6269
+ await (0, import_promises9.mkdir)((0, import_node_path6.dirname)(path4), {
5936
6270
  mode: privateDirectoryMode,
5937
6271
  recursive: true
5938
6272
  });
5939
6273
  const temporaryPath = `${path4}.${process.pid}.tmp`;
5940
- await (0, import_promises8.writeFile)(temporaryPath, value, {
6274
+ await (0, import_promises9.writeFile)(temporaryPath, value, {
5941
6275
  encoding: "utf8",
5942
6276
  mode: privateFileMode
5943
6277
  });
5944
- await (0, import_promises8.chmod)(temporaryPath, privateFileMode);
5945
- await (0, import_promises8.rename)(temporaryPath, path4);
6278
+ await (0, import_promises9.chmod)(temporaryPath, privateFileMode);
6279
+ await (0, import_promises9.rename)(temporaryPath, path4);
5946
6280
  }
5947
6281
  };
5948
6282
  }
@@ -5962,23 +6296,23 @@ async function withDeadline(operation, deadline) {
5962
6296
  }
5963
6297
  return await Promise.race([
5964
6298
  operation,
5965
- delay2(remaining).then(() => {
6299
+ delay4(remaining).then(() => {
5966
6300
  throw new Error("Operation exceeded its foreground deadline");
5967
6301
  })
5968
6302
  ]);
5969
6303
  }
5970
- function delay2(milliseconds) {
6304
+ function delay4(milliseconds) {
5971
6305
  return new Promise((resolvePromise) => {
5972
6306
  setTimeout(resolvePromise, milliseconds);
5973
6307
  });
5974
6308
  }
5975
- var import_node_os4, import_node_crypto4, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
6309
+ var import_node_os4, import_node_crypto5, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
5976
6310
  var init_daemon = __esm({
5977
6311
  "../machine-connector/dist/runtime/daemon.js"() {
5978
6312
  "use strict";
5979
6313
  init_cjs_shims();
5980
6314
  import_node_os4 = require("os");
5981
- import_node_crypto4 = require("crypto");
6315
+ import_node_crypto5 = require("crypto");
5982
6316
  init_enums();
5983
6317
  init_contracts();
5984
6318
  init_claude_executor();
@@ -5987,6 +6321,7 @@ var init_daemon = __esm({
5987
6321
  init_execution_cancellation();
5988
6322
  init_image_viewer();
5989
6323
  init_local_ipc();
6324
+ init_process_lock();
5990
6325
  init_process_executor();
5991
6326
  init_relay_client();
5992
6327
  init_runtime_logger();
@@ -6015,12 +6350,13 @@ var init_daemon = __esm({
6015
6350
  MachineConnectorDaemon = class {
6016
6351
  store;
6017
6352
  activeJobs = /* @__PURE__ */ new Map();
6018
- connectorInstanceId = (0, import_node_crypto4.randomUUID)();
6353
+ connectorInstanceId = (0, import_node_crypto5.randomUUID)();
6019
6354
  executionTasks = /* @__PURE__ */ new Set();
6020
6355
  logger;
6021
6356
  relayClients = /* @__PURE__ */ new Map();
6022
6357
  startedAt = (/* @__PURE__ */ new Date()).toISOString();
6023
6358
  connections = [];
6359
+ daemonLock;
6024
6360
  ipcServer;
6025
6361
  stopping = false;
6026
6362
  leaseSafetyMarginMilliseconds;
@@ -6028,9 +6364,11 @@ var init_daemon = __esm({
6028
6364
  networkRetryMilliseconds;
6029
6365
  random;
6030
6366
  terminalForegroundBudgetMilliseconds;
6367
+ cliVersion;
6031
6368
  constructor(store = new MachineRuntimeStore(), options = {}) {
6032
6369
  this.store = store;
6033
6370
  this.logger = new RuntimeLogger(store);
6371
+ this.cliVersion = options.cliVersion;
6034
6372
  this.leaseSafetyMarginMilliseconds = options.leaseSafetyMarginMilliseconds ?? defaultLeaseSafetyMarginMilliseconds;
6035
6373
  this.leaseSeconds = options.leaseSeconds ?? defaultLeaseSeconds;
6036
6374
  this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds;
@@ -6042,22 +6380,33 @@ var init_daemon = __esm({
6042
6380
  throw new Error("Moxt Machine Connector must run as an unprivileged user");
6043
6381
  }
6044
6382
  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");
6383
+ this.daemonLock = await ProcessLock.acquire(this.store.daemonLockPath(), { timeoutMilliseconds: 1e3 });
6384
+ if (!this.daemonLock) {
6385
+ throw new Error("Another Moxt Machine Connector daemon is already running or starting");
6386
+ }
6387
+ try {
6388
+ await this.recoverInterruptedJobs();
6389
+ this.ipcServer = new LocalIpcServer(this.store, () => this.getStatus());
6390
+ await this.ipcServer.start();
6391
+ await this.logger.info("Moxt Machine Connector started", {
6392
+ connectorInstanceId: this.connectorInstanceId,
6393
+ hostname: (0, import_node_os4.hostname)(),
6394
+ version: connectorVersion
6395
+ });
6396
+ this.connections = await this.store.listConnections();
6397
+ if (this.connections.length === 0) {
6398
+ await this.logger.info("No Local Machine connections are configured");
6399
+ }
6400
+ await Promise.all(this.connections.map(async (connection) => {
6401
+ await this.runConnection(connection);
6402
+ }));
6403
+ await this.waitForExecutionTasks();
6404
+ } catch (error) {
6405
+ await this.ipcServer?.close();
6406
+ this.ipcServer = void 0;
6407
+ await this.releaseDaemonLock();
6408
+ throw error;
6056
6409
  }
6057
- await Promise.all(this.connections.map(async (connection) => {
6058
- await this.runConnection(connection);
6059
- }));
6060
- await this.waitForExecutionTasks();
6061
6410
  }
6062
6411
  async stop() {
6063
6412
  this.stopping = true;
@@ -6065,6 +6414,8 @@ var init_daemon = __esm({
6065
6414
  await activeJob.cancellation.request(ExecutionCancellationReason.Stopping);
6066
6415
  }));
6067
6416
  await this.ipcServer?.close();
6417
+ this.ipcServer = void 0;
6418
+ await this.releaseDaemonLock();
6068
6419
  await this.logger.info("Moxt Machine Connector stopped");
6069
6420
  }
6070
6421
  getStatus() {
@@ -6078,6 +6429,7 @@ var init_daemon = __esm({
6078
6429
  relativeWorkingDirectory: activeJob.claim.relativeWorkingDirectory
6079
6430
  };
6080
6431
  }),
6432
+ ...this.cliVersion ? { cliVersion: this.cliVersion } : {},
6081
6433
  connections: this.connections.map((connection) => ({
6082
6434
  connectionId: connection.connectionId,
6083
6435
  machineName: connection.machineName,
@@ -6245,6 +6597,36 @@ var init_daemon = __esm({
6245
6597
  activeJob.cancellation.wait().then(() => this.cancellationResult(activeJob))
6246
6598
  ]);
6247
6599
  void execution.catch(() => void 0);
6600
+ const detachedProcessHandle = "detachedProcessHandle" in executionResult ? executionResult.detachedProcessHandle : void 0;
6601
+ if (detachedProcessHandle) {
6602
+ let resourceRecorded = false;
6603
+ try {
6604
+ await this.store.writeDetachedProcess({
6605
+ connectionId: activeJob.connection.connectionId,
6606
+ jobId: claim.jobId,
6607
+ processGroupId: detachedProcessHandle.processGroupId(),
6608
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString(),
6609
+ relativeWorkingDirectory: claim.relativeWorkingDirectory
6610
+ });
6611
+ resourceRecorded = true;
6612
+ } catch (error) {
6613
+ await this.logger.error(`Failed to record detached process for Job ${claim.jobId}`, error);
6614
+ }
6615
+ if (!activeJob.cancellation.release(detachedProcessHandle)) {
6616
+ if (resourceRecorded) {
6617
+ try {
6618
+ await this.store.deleteDetachedProcess(claim.jobId);
6619
+ } catch (error) {
6620
+ await this.logger.error(`Failed to remove detached process record for cancelled Job ${claim.jobId}`, error);
6621
+ }
6622
+ }
6623
+ await detachedProcessHandle.cancel();
6624
+ await durableJob.markTerminal(this.cancellationResult(activeJob));
6625
+ await this.finishTerminalUpload(activeJob);
6626
+ await Promise.all([uploadLoop, leaseLoop]);
6627
+ return;
6628
+ }
6629
+ }
6248
6630
  await durableJob.markTerminal(executionResult);
6249
6631
  await this.finishTerminalUpload(activeJob);
6250
6632
  await Promise.all([uploadLoop, leaseLoop]);
@@ -6602,7 +6984,7 @@ var init_daemon = __esm({
6602
6984
  async waitUntilStop(milliseconds) {
6603
6985
  const deadline = Date.now() + milliseconds;
6604
6986
  while (!this.stopping && Date.now() < deadline) {
6605
- await delay2(Math.min(250, deadline - Date.now()));
6987
+ await delay4(Math.min(250, deadline - Date.now()));
6606
6988
  }
6607
6989
  }
6608
6990
  cancellationResult(activeJob) {
@@ -6626,6 +7008,10 @@ var init_daemon = __esm({
6626
7008
  }
6627
7009
  return activeJob.durableJob;
6628
7010
  }
7011
+ async releaseDaemonLock() {
7012
+ await this.daemonLock?.release();
7013
+ this.daemonLock = void 0;
7014
+ }
6629
7015
  async recoverInterruptedJobs() {
6630
7016
  const jobs = await this.store.listJobs();
6631
7017
  for (const job of jobs) {
@@ -6665,1659 +7051,1918 @@ var init_daemon = __esm({
6665
7051
  }
6666
7052
  });
6667
7053
 
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
- });
7054
+ // ../machine-connector/dist/runtime/service-manager.js
7055
+ function parseServiceManagerPreference(value) {
7056
+ if (value === ServiceManagerPreference.Auto) {
7057
+ return ServiceManagerPreference.Auto;
6690
7058
  }
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
- });
7059
+ if (value === ServiceManagerPreference.Systemd) {
7060
+ return ServiceManagerPreference.Systemd;
7061
+ }
7062
+ if (value === ServiceManagerPreference.Supervisor) {
7063
+ return ServiceManagerPreference.Supervisor;
7064
+ }
7065
+ if (value === ServiceManagerPreference.None) {
7066
+ return ServiceManagerPreference.None;
7067
+ }
7068
+ throw new Error(`Unsupported service manager: ${value}`);
7069
+ }
7070
+ function selectUserServiceManager(preference, capabilities) {
7071
+ if (preference === ServiceManagerPreference.None) {
7072
+ return {
7073
+ detail: "Background service installation was explicitly disabled.",
7074
+ manager: UserServiceManager.None
7075
+ };
7076
+ }
7077
+ if (capabilities.operatingSystem === "darwin") {
7078
+ if (preference !== ServiceManagerPreference.Auto) {
7079
+ throw new Error(`${preference} service management is supported only on Linux`);
6705
7080
  }
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
- });
7081
+ return {
7082
+ detail: "Using the macOS LaunchAgent service manager.",
7083
+ manager: UserServiceManager.Launchd
7084
+ };
7085
+ }
7086
+ if (capabilities.operatingSystem !== "linux") {
7087
+ if (preference === ServiceManagerPreference.Auto) {
7088
+ return {
7089
+ detail: "No supported background service manager is available on this platform.",
7090
+ manager: UserServiceManager.None
7091
+ };
6744
7092
  }
7093
+ throw new Error(`${preference} service management is supported only on Linux`);
6745
7094
  }
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
- });
7095
+ if (preference === ServiceManagerPreference.Systemd) {
7096
+ if (!capabilities.systemdUserAvailable) {
7097
+ throw new Error("The systemd user service manager is not available in this environment");
7098
+ }
7099
+ return {
7100
+ detail: "Using the systemd user service manager.",
7101
+ manager: UserServiceManager.Systemd
7102
+ };
6770
7103
  }
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
- });
7104
+ if (preference === ServiceManagerPreference.Supervisor) {
7105
+ if (!capabilities.supervisorAvailable) {
7106
+ throw new Error("Supervisor is not available; install supervisord and supervisorctl or choose another service manager");
7107
+ }
7108
+ return {
7109
+ detail: "Using the Supervisor service manager.",
7110
+ manager: UserServiceManager.Supervisor
7111
+ };
6784
7112
  }
6785
- return checks;
6786
- }
6787
- function errorMessage(error) {
6788
- return error instanceof Error ? error.message : String(error);
6789
- }
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 = {}));
7113
+ if (capabilities.systemdUserAvailable) {
7114
+ return {
7115
+ detail: "Automatically selected the systemd user service manager.",
7116
+ manager: UserServiceManager.Systemd
7117
+ };
6807
7118
  }
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"
6852
- }
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.");
7119
+ if (capabilities.supervisorAvailable) {
7120
+ return {
7121
+ detail: "Automatically selected the Supervisor service manager.",
7122
+ manager: UserServiceManager.Supervisor
7123
+ };
6858
7124
  }
7125
+ return {
7126
+ detail: "No supported background service manager is available. Pairing is complete, but the Connector must be started manually.",
7127
+ manager: UserServiceManager.None
7128
+ };
6859
7129
  }
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;
7130
+ async function detectServiceManagerCapabilities(runtime = defaultServiceManagerRuntime) {
7131
+ if (runtime.operatingSystem !== "linux") {
7132
+ return {
7133
+ operatingSystem: runtime.operatingSystem,
7134
+ supervisorAvailable: false,
7135
+ systemdUserAvailable: false
7136
+ };
6869
7137
  }
6870
- const checks = depth === MachineManagerSnapshotDepth.WithDoctor ? await runMachineDoctor(store) : [];
7138
+ const systemdUserAvailable = await commandSucceeds(runtime, "systemctl", ["--user", "show-environment"]);
7139
+ const supervisordAvailable = await commandSucceeds(runtime, "supervisord", ["--version"]);
7140
+ const supervisorctlAvailable = await commandSucceeds(runtime, "supervisorctl", ["-h"]);
6871
7141
  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
7142
+ operatingSystem: runtime.operatingSystem,
7143
+ supervisorAvailable: supervisordAvailable && supervisorctlAvailable,
7144
+ systemdUserAvailable
6879
7145
  };
6880
7146
  }
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));
7147
+ async function validateServiceManagerPreference(preference, runtime = defaultServiceManagerRuntime) {
7148
+ if (preference === ServiceManagerPreference.None) {
7149
+ return selectUserServiceManager(preference, {
7150
+ operatingSystem: runtime.operatingSystem,
7151
+ supervisorAvailable: false,
7152
+ systemdUserAvailable: false
7153
+ });
6896
7154
  }
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();
6905
- }
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(" ");
7155
+ const capabilities = await detectServiceManagerCapabilities(runtime);
7156
+ return selectUserServiceManager(preference, capabilities);
6915
7157
  }
6916
- function renderView(snapshot, state) {
6917
- if (state.view === MachineManagerView.Overview) {
6918
- return renderOverview(snapshot);
7158
+ async function installUserService(store, request2, runtime = defaultServiceManagerRuntime) {
7159
+ if (request2.preference === ServiceManagerPreference.None) {
7160
+ const configuredManager = await readStoredServiceManager(store);
7161
+ if (configuredManager !== UserServiceManager.None) {
7162
+ await uninstallManager(configuredManager, store, runtime);
7163
+ }
7164
+ await persistServiceManager(store, UserServiceManager.None);
7165
+ return {
7166
+ detail: "Background service installation was explicitly disabled.",
7167
+ installed: false,
7168
+ manager: UserServiceManager.None
7169
+ };
6919
7170
  }
6920
- if (state.view === MachineManagerView.Connections) {
6921
- return renderConnections(snapshot, state.selectedRowIndex);
7171
+ const options = {
7172
+ ...request2.options,
7173
+ environment: {
7174
+ ...createServiceEnvironment(request2.options),
7175
+ MOXT_MACHINE_HOME: store.baseDirectory
7176
+ }
7177
+ };
7178
+ const capabilities = await detectServiceManagerCapabilities(runtime);
7179
+ const selection = selectUserServiceManager(request2.preference, capabilities);
7180
+ if (selection.manager === UserServiceManager.None) {
7181
+ await persistServiceManager(store, UserServiceManager.None);
7182
+ return {
7183
+ detail: selection.detail,
7184
+ installed: false,
7185
+ manager: UserServiceManager.None
7186
+ };
6922
7187
  }
6923
- if (state.view === MachineManagerView.Jobs) {
6924
- return renderJobs(snapshot, state.selectedRowIndex);
6925
- }
6926
- if (state.view === MachineManagerView.Logs) {
6927
- return renderLogs(snapshot);
6928
- }
6929
- return renderDoctor(snapshot);
6930
- }
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;
6946
- }
6947
- lines.push(" Connected roots");
6948
- for (const connection of snapshot.connections) {
6949
- lines.push(` ${connection.machineName} ${connection.rootPath}`);
6950
- }
6951
- return lines;
6952
- }
6953
- function renderConnections(snapshot, selectedRowIndex) {
6954
- if (snapshot.connections.length === 0) {
6955
- return ["", " No connections", " Press A to pair a machine."];
6956
- }
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."];
6970
- }
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."];
6982
- }
6983
- return snapshot.logLines.map((line) => ` ${line}`);
6984
- }
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}`);
6994
- }
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;
7007
- }
7008
- function rowCountForView(snapshot, view) {
7009
- if (view === MachineManagerView.Connections) {
7010
- return snapshot.connections.length;
7188
+ if (request2.preference !== ServiceManagerPreference.Auto) {
7189
+ await replaceConfiguredManager(store, selection.manager, options, runtime);
7190
+ return {
7191
+ detail: selection.detail,
7192
+ installed: true,
7193
+ manager: selection.manager
7194
+ };
7011
7195
  }
7012
- if (view === MachineManagerView.Jobs) {
7013
- return snapshot.jobs.length;
7196
+ const candidates = await automaticManagerCandidates(store, capabilities);
7197
+ const failures = [];
7198
+ for (const manager of candidates) {
7199
+ try {
7200
+ await replaceConfiguredManager(store, manager, options, runtime);
7201
+ return {
7202
+ detail: automaticSelectionDetail(manager),
7203
+ installed: true,
7204
+ manager
7205
+ };
7206
+ } catch (error) {
7207
+ failures.push(`${manager}: ${error instanceof Error ? error.message : String(error)}`);
7208
+ await uninstallManagerIgnoringFailure(manager, store, runtime);
7209
+ }
7014
7210
  }
7015
- return 0;
7016
- }
7017
- function toManagerConnection(connection) {
7211
+ await persistServiceManager(store, UserServiceManager.None);
7018
7212
  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
7213
+ detail: failures.length === 0 ? selection.detail : `Automatic background service setup failed (${failures.join("; ")}). Pairing is complete, but the Connector must be started manually.`,
7214
+ installed: false,
7215
+ manager: UserServiceManager.None
7027
7216
  };
7028
7217
  }
7029
- function toManagerJob(job) {
7218
+ function createServiceEnvironment(options) {
7219
+ const inheritedPath = options.environment.PATH ?? process.env.PATH ?? "";
7220
+ const nodeDirectory = (0, import_node_path7.dirname)(options.nodePath);
7221
+ const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path7.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
7030
7222
  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
7223
+ ...options.environment,
7224
+ HOME: options.environment.HOME ?? process.env.HOME ?? (0, import_node_os5.homedir)(),
7225
+ PATH: pathEntries.join(import_node_path7.delimiter)
7039
7226
  };
7040
7227
  }
7041
- function formatPersistedCommand(job) {
7042
- if (job.claim.kind !== "command") {
7043
- return {};
7044
- }
7045
- if (!isRecord3(job.claim.requestPayload)) {
7046
- return {};
7047
- }
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 {};
7228
+ async function restartUserService(store, runtime = defaultServiceManagerRuntime) {
7229
+ const manager = await configuredServiceManager(store, runtime);
7230
+ await restartManager(manager, store, runtime);
7231
+ return manager;
7232
+ }
7233
+ async function refreshManagedUserService(store, options, runtime = defaultServiceManagerRuntime) {
7234
+ const manager = await readStoredServiceManager(store);
7235
+ if (manager === UserServiceManager.None)
7236
+ return void 0;
7237
+ const snapshot = await readManagedServiceDefinition(manager, store);
7238
+ if (snapshot === void 0) {
7239
+ throw new Error(`The recorded ${manager} service definition does not exist`);
7052
7240
  }
7053
- return {
7054
- value: [executable, ...argumentsValue].map(formatCommandArgument).join(" ")
7241
+ const refreshedOptions = {
7242
+ ...options,
7243
+ environment: {
7244
+ ...createServiceEnvironment(options),
7245
+ MOXT_MACHINE_HOME: store.baseDirectory
7246
+ }
7247
+ };
7248
+ const rollback = async () => {
7249
+ await restoreManagedServiceDefinition(manager, store, snapshot, runtime);
7055
7250
  };
7056
- }
7057
- function formatCommandArgument(value) {
7058
- return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : JSON.stringify(value);
7059
- }
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);
7064
- }
7065
- async function readOptionalFile(path4) {
7066
7251
  try {
7067
- return await (0, import_promises11.readFile)(path4, "utf8");
7252
+ await installManager(manager, store, refreshedOptions, runtime);
7253
+ if (manager === UserServiceManager.Systemd) {
7254
+ await restartManager(manager, store, runtime);
7255
+ }
7256
+ await persistServiceManager(store, manager);
7068
7257
  } catch (error) {
7069
- if (isMissingFile(error)) {
7070
- return "";
7258
+ try {
7259
+ await rollback();
7260
+ } catch (rollbackError) {
7261
+ throw new Error(`${errorMessage(error)}; restoring the previous ${manager} definition also failed: ${errorMessage(rollbackError)}`, { cause: error });
7071
7262
  }
7072
7263
  throw error;
7073
7264
  }
7265
+ return { manager, rollback };
7074
7266
  }
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);
7083
- }
7084
- }
7085
- function styledLine(value, width, style) {
7086
- return `${style}${fitLine(value, width)}${styleReset}`;
7087
- }
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);
7267
+ async function managedServiceOwnsProcess(manager, processId, store, runtime = defaultServiceManagerRuntime) {
7268
+ try {
7269
+ if (manager === UserServiceManager.Launchd) {
7270
+ const result = await runtime.run("launchctl", [
7271
+ "print",
7272
+ `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7273
+ ]);
7274
+ const match = /(?:^|\s)pid\s*=\s*(\d+)(?:\s|$)/m.exec(result.stdout);
7275
+ return match ? Number(match[1]) === processId : false;
7276
+ }
7277
+ if (manager === UserServiceManager.Systemd) {
7278
+ const result = await runtime.run("systemctl", [
7279
+ "--user",
7280
+ "show",
7281
+ "--property",
7282
+ "MainPID",
7283
+ "--value",
7284
+ "moxt-machine-connector.service"
7285
+ ]);
7286
+ return parseProcessId(result.stdout) === processId;
7287
+ }
7288
+ if (manager === UserServiceManager.Supervisor) {
7289
+ const result = await runtime.run("supervisorctl", [
7290
+ "-c",
7291
+ supervisorConfigPath(store),
7292
+ "pid",
7293
+ supervisorProgramName
7294
+ ]);
7295
+ return parseProcessId(result.stdout) === processId;
7093
7296
  }
7094
- return `${plainValue.slice(0, width - 1)}\u2026`;
7095
- }
7096
- if (value.includes("\x1B[")) {
7097
- return value;
7297
+ return false;
7298
+ } catch {
7299
+ return false;
7098
7300
  }
7099
- return value.padEnd(width);
7100
7301
  }
7101
- function stripAnsi(value) {
7102
- return value.replaceAll(styleHeader, "").replaceAll(styleSelected, "").replaceAll(styleReset, "");
7302
+ async function recordedServiceManager(store) {
7303
+ return await readStoredServiceManager(store);
7103
7304
  }
7104
- function repeatCharacter(value, count) {
7105
- return value.repeat(count);
7305
+ async function stopUserService(store, runtime = defaultServiceManagerRuntime) {
7306
+ const manager = await configuredServiceManager(store, runtime);
7307
+ await stopManager(manager, store, runtime);
7308
+ return manager;
7106
7309
  }
7107
- function wrapIndex(value, count) {
7108
- return (value % count + count) % count;
7310
+ async function uninstallUserService(store, runtime = defaultServiceManagerRuntime) {
7311
+ const manager = await configuredServiceManager(store, runtime);
7312
+ await uninstallManager(manager, store, runtime);
7313
+ await store.removeServiceManager();
7314
+ return manager;
7109
7315
  }
7110
- function formatTimestamp(value) {
7111
- const timestamp = Date.parse(value);
7112
- if (Number.isNaN(timestamp)) {
7113
- return value;
7316
+ async function automaticManagerCandidates(store, capabilities) {
7317
+ const candidates = [];
7318
+ const storedManager = await readStoredServiceManager(store);
7319
+ if (storedManager !== UserServiceManager.None && managerIsAvailable(storedManager, capabilities)) {
7320
+ candidates.push(storedManager);
7114
7321
  }
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";
7322
+ if (capabilities.operatingSystem === "darwin" && !candidates.includes(UserServiceManager.Launchd)) {
7323
+ candidates.push(UserServiceManager.Launchd);
7324
+ }
7325
+ if (capabilities.systemdUserAvailable && !candidates.includes(UserServiceManager.Systemd)) {
7326
+ candidates.push(UserServiceManager.Systemd);
7327
+ }
7328
+ if (capabilities.supervisorAvailable && !candidates.includes(UserServiceManager.Supervisor)) {
7329
+ candidates.push(UserServiceManager.Supervisor);
7330
+ }
7331
+ return candidates;
7122
7332
  }
7123
- function errorMessage2(error) {
7124
- return error instanceof Error ? error.message : String(error);
7333
+ async function replaceConfiguredManager(store, manager, options, runtime) {
7334
+ const configuredManager = await readStoredServiceManager(store);
7335
+ if (configuredManager !== UserServiceManager.None && configuredManager !== manager) {
7336
+ await uninstallManagerIgnoringFailure(configuredManager, store, runtime);
7337
+ }
7338
+ await installManager(manager, store, options, runtime);
7339
+ await persistServiceManager(store, manager);
7125
7340
  }
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
- };
7341
+ async function installManager(manager, store, options, runtime) {
7342
+ if (manager === UserServiceManager.Launchd) {
7343
+ await installLaunchAgent(store, options, runtime);
7344
+ return;
7345
+ }
7346
+ if (manager === UserServiceManager.Systemd) {
7347
+ await installSystemdUserService(store, options, runtime);
7348
+ return;
7349
+ }
7350
+ if (manager === UserServiceManager.Supervisor) {
7351
+ await installSupervisorUserService(store, options, runtime);
7352
+ return;
7353
+ }
7354
+ }
7355
+ async function restartManager(manager, store, runtime) {
7356
+ if (manager === UserServiceManager.None) {
7357
+ return;
7358
+ }
7359
+ if (manager === UserServiceManager.Launchd) {
7360
+ await runtime.run("launchctl", [
7361
+ "kickstart",
7362
+ "-k",
7363
+ `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7364
+ ]);
7365
+ return;
7366
+ }
7367
+ if (manager === UserServiceManager.Systemd) {
7368
+ await runtime.run("systemctl", [
7369
+ "--user",
7370
+ "restart",
7371
+ "moxt-machine-connector.service"
7372
+ ]);
7373
+ return;
7374
+ }
7375
+ await restartSupervisorUserService(store, runtime);
7376
+ }
7377
+ async function stopManager(manager, store, runtime) {
7378
+ if (manager === UserServiceManager.None) {
7379
+ return;
7380
+ }
7381
+ if (manager === UserServiceManager.Launchd) {
7382
+ await runtime.run("launchctl", [
7383
+ "bootout",
7384
+ `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7385
+ ]);
7386
+ return;
7387
+ }
7388
+ if (manager === UserServiceManager.Systemd) {
7389
+ await runtime.run("systemctl", [
7390
+ "--user",
7391
+ "stop",
7392
+ "moxt-machine-connector.service"
7393
+ ]);
7394
+ return;
7395
+ }
7396
+ await runCommandIgnoringFailure(runtime, "supervisorctl", [
7397
+ "-c",
7398
+ supervisorConfigPath(store),
7399
+ "stop",
7400
+ supervisorProgramName
7401
+ ]);
7402
+ }
7403
+ async function uninstallManager(manager, store, runtime) {
7404
+ if (manager === UserServiceManager.None) {
7405
+ return;
7406
+ }
7407
+ if (manager === UserServiceManager.Launchd) {
7408
+ await runCommandIgnoringFailure(runtime, "launchctl", [
7409
+ "bootout",
7410
+ `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7411
+ ]);
7412
+ await (0, import_promises10.rm)(launchAgentPath(), { force: true });
7413
+ return;
7414
+ }
7415
+ if (manager === UserServiceManager.Systemd) {
7416
+ await runCommandIgnoringFailure(runtime, "systemctl", [
7417
+ "--user",
7418
+ "disable",
7419
+ "--now",
7420
+ "moxt-machine-connector.service"
7421
+ ]);
7422
+ await (0, import_promises10.rm)(systemdUnitPath(), { force: true });
7423
+ await runCommandIgnoringFailure(runtime, "systemctl", [
7424
+ "--user",
7425
+ "daemon-reload"
7426
+ ]);
7427
+ return;
7428
+ }
7429
+ await runCommandIgnoringFailure(runtime, "supervisorctl", [
7430
+ "-c",
7431
+ supervisorConfigPath(store),
7432
+ "stop",
7433
+ supervisorProgramName
7434
+ ]);
7435
+ await runCommandIgnoringFailure(runtime, "supervisorctl", ["-c", supervisorConfigPath(store), "shutdown"]);
7436
+ await (0, import_promises10.rm)(supervisorDirectory(store), {
7437
+ force: true,
7438
+ recursive: true
7439
+ });
7440
+ }
7441
+ async function configuredServiceManager(store, runtime) {
7442
+ const storedManager = await readStoredServiceManager(store);
7443
+ if (storedManager !== UserServiceManager.None) {
7444
+ return storedManager;
7474
7445
  }
7475
- });
7476
-
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
- };
7446
+ const stored = await store.readServiceManager();
7447
+ if (stored.value) {
7448
+ return UserServiceManager.None;
7486
7449
  }
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
- }
7450
+ const capabilities = await detectServiceManagerCapabilities(runtime);
7451
+ return selectUserServiceManager(ServiceManagerPreference.Auto, capabilities).manager;
7452
+ }
7453
+ async function readStoredServiceManager(store) {
7454
+ const stored = await store.readServiceManager();
7455
+ if (!stored.value) {
7456
+ return UserServiceManager.None;
7457
+ }
7458
+ return parseStoredServiceManager(stored.value.manager);
7459
+ }
7460
+ async function readManagedServiceDefinition(manager, store) {
7461
+ try {
7462
+ return await (0, import_promises10.readFile)(managedServiceDefinitionPath(manager, store), "utf8");
7463
+ } catch (error) {
7464
+ if (isNodeErrorCode4(error, "ENOENT"))
7465
+ return void 0;
7466
+ throw error;
7467
+ }
7468
+ }
7469
+ async function restoreManagedServiceDefinition(manager, store, definition2, runtime) {
7470
+ const path4 = managedServiceDefinitionPath(manager, store);
7471
+ await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
7472
+ await (0, import_promises10.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
7473
+ if (manager === UserServiceManager.Launchd) {
7474
+ const domain = `gui/${process.getuid?.() ?? 0}`;
7475
+ await runCommandIgnoringFailure(runtime, "launchctl", [
7476
+ "bootout",
7477
+ domain,
7478
+ path4
7479
+ ]);
7480
+ await runtime.run("launchctl", ["bootstrap", domain, path4]);
7481
+ } else if (manager === UserServiceManager.Systemd) {
7482
+ await runtime.run("systemctl", ["--user", "daemon-reload"]);
7483
+ } else if (manager === UserServiceManager.Supervisor) {
7484
+ await runtime.run("supervisorctl", ["-c", path4, "reread"]);
7485
+ await runtime.run("supervisorctl", ["-c", path4, "update"]);
7486
+ return;
7487
+ }
7488
+ await restartManager(manager, store, runtime);
7489
+ }
7490
+ function managedServiceDefinitionPath(manager, store) {
7491
+ if (manager === UserServiceManager.Launchd)
7492
+ return launchAgentPath();
7493
+ if (manager === UserServiceManager.Systemd)
7494
+ return systemdUnitPath();
7495
+ if (manager === UserServiceManager.Supervisor) {
7496
+ return supervisorConfigPath(store);
7497
+ }
7498
+ throw new Error("An unmanaged daemon has no service definition");
7499
+ }
7500
+ function parseStoredServiceManager(value) {
7501
+ if (value === UserServiceManager.Launchd) {
7502
+ return UserServiceManager.Launchd;
7503
+ }
7504
+ if (value === UserServiceManager.Systemd) {
7505
+ return UserServiceManager.Systemd;
7506
+ }
7507
+ if (value === UserServiceManager.Supervisor) {
7508
+ return UserServiceManager.Supervisor;
7509
+ }
7510
+ if (value === UserServiceManager.None) {
7511
+ return UserServiceManager.None;
7512
+ }
7513
+ throw new Error(`Unsupported stored service manager: ${value}`);
7514
+ }
7515
+ function parseProcessId(value) {
7516
+ const processId = Number.parseInt(value.trim(), 10);
7517
+ return Number.isSafeInteger(processId) && processId > 0 ? processId : void 0;
7518
+ }
7519
+ async function persistServiceManager(store, manager) {
7520
+ await store.writeServiceManager({
7521
+ manager,
7522
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
7497
7523
  });
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
7524
  }
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");
7525
+ function managerIsAvailable(manager, capabilities) {
7526
+ if (manager === UserServiceManager.Launchd) {
7527
+ return capabilities.operatingSystem === "darwin";
7515
7528
  }
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()
7529
+ if (manager === UserServiceManager.Systemd) {
7530
+ return capabilities.systemdUserAvailable;
7531
+ }
7532
+ if (manager === UserServiceManager.Supervisor) {
7533
+ return capabilities.supervisorAvailable;
7534
+ }
7535
+ return false;
7536
+ }
7537
+ function automaticSelectionDetail(manager) {
7538
+ if (manager === UserServiceManager.Launchd) {
7539
+ return "Automatically selected the macOS LaunchAgent service manager.";
7540
+ }
7541
+ if (manager === UserServiceManager.Systemd) {
7542
+ return "Automatically selected the systemd user service manager.";
7543
+ }
7544
+ return "Automatically selected the Supervisor service manager.";
7545
+ }
7546
+ async function installLaunchAgent(store, options, runtime) {
7547
+ const path4 = launchAgentPath();
7548
+ await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
7549
+ const programArguments = [
7550
+ options.nodePath,
7551
+ (0, import_node_path7.resolve)(options.entrypointPath),
7552
+ ...options.commandArguments
7553
+ ];
7554
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
7555
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
7556
+ <plist version="1.0">
7557
+ <dict>
7558
+ <key>Label</key>
7559
+ <string>${launchAgentLabel}</string>
7560
+ <key>ProgramArguments</key>
7561
+ <array>
7562
+ ${programArguments.map((argument) => ` <string>${escapeXml(argument)}</string>`).join("\n")}
7563
+ </array>
7564
+ <key>RunAtLoad</key>
7565
+ <true/>
7566
+ <key>KeepAlive</key>
7567
+ <true/>
7568
+ <key>EnvironmentVariables</key>
7569
+ <dict>
7570
+ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeXml(name)}</key>
7571
+ <string>${escapeXml(value)}</string>`).join("\n")}
7572
+ </dict>
7573
+ <key>ProcessType</key>
7574
+ <string>Background</string>
7575
+ <key>StandardOutPath</key>
7576
+ <string>${escapeXml(store.runtimeLogPath())}</string>
7577
+ <key>StandardErrorPath</key>
7578
+ <string>${escapeXml(store.runtimeErrorLogPath())}</string>
7579
+ </dict>
7580
+ </plist>
7581
+ `;
7582
+ await (0, import_promises10.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
7583
+ const domain = `gui/${process.getuid?.() ?? 0}`;
7584
+ await runCommandIgnoringFailure(runtime, "launchctl", [
7585
+ "bootout",
7586
+ domain,
7587
+ path4
7526
7588
  ]);
7527
- return JSON.parse(decrypted.toString("utf8"));
7589
+ await runtime.run("launchctl", ["bootstrap", domain, path4]);
7590
+ await runtime.run("launchctl", [
7591
+ "kickstart",
7592
+ "-k",
7593
+ `${domain}/${launchAgentLabel}`
7594
+ ]);
7595
+ }
7596
+ async function installSystemdUserService(store, options, runtime) {
7597
+ const path4 = systemdUnitPath();
7598
+ await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
7599
+ const command = [
7600
+ options.nodePath,
7601
+ (0, import_node_path7.resolve)(options.entrypointPath),
7602
+ ...options.commandArguments
7603
+ ].map(escapeSystemdArgument).join(" ");
7604
+ const unit = `[Unit]
7605
+ Description=Moxt Machine Connector
7606
+ After=network-online.target
7607
+ Wants=network-online.target
7608
+
7609
+ [Service]
7610
+ Type=simple
7611
+ ExecStart=${command}
7612
+ Restart=always
7613
+ RestartSec=3
7614
+ NoNewPrivileges=true
7615
+ ${Object.entries(options.environment).map(([name, value]) => `Environment=${escapeSystemdEnvironment(name)}=${escapeSystemdEnvironment(value)}`).join("\n")}
7616
+
7617
+ [Install]
7618
+ WantedBy=default.target
7619
+ `;
7620
+ await (0, import_promises10.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
7621
+ await runtime.run("systemctl", ["--user", "daemon-reload"]);
7622
+ await runtime.run("systemctl", [
7623
+ "--user",
7624
+ "enable",
7625
+ "--now",
7626
+ "moxt-machine-connector.service"
7627
+ ]);
7628
+ await runCommandIgnoringFailure(runtime, "loginctl", [
7629
+ "enable-linger",
7630
+ (0, import_node_os5.userInfo)().username
7631
+ ]);
7632
+ }
7633
+ async function installSupervisorUserService(store, options, runtime) {
7634
+ const directory = supervisorDirectory(store);
7635
+ const configPath = supervisorConfigPath(store);
7636
+ await (0, import_promises10.mkdir)(directory, { recursive: true, mode: 448 });
7637
+ await (0, import_promises10.writeFile)(configPath, createSupervisorConfiguration(store, options), {
7638
+ encoding: "utf8",
7639
+ mode: 384
7640
+ });
7641
+ const supervisorWasRunning = await supervisorIsRunning(store, runtime);
7642
+ if (!supervisorWasRunning) {
7643
+ await (0, import_promises10.rm)(supervisorSocketPath(store), { force: true });
7644
+ await (0, import_promises10.rm)(supervisorPidPath(store), { force: true });
7645
+ await runtime.run("supervisord", ["-c", configPath]);
7646
+ await waitForSupervisorControl(store, runtime);
7647
+ return;
7648
+ }
7649
+ await runtime.run("supervisorctl", ["-c", configPath, "reread"]);
7650
+ await runtime.run("supervisorctl", ["-c", configPath, "update"]);
7651
+ }
7652
+ function createSupervisorConfiguration(store, options) {
7653
+ const command = [
7654
+ options.nodePath,
7655
+ (0, import_node_path7.resolve)(options.entrypointPath),
7656
+ ...options.commandArguments
7657
+ ].map(escapeSupervisorArgument).join(" ");
7658
+ const environment = Object.entries(options.environment).map(([name, value]) => `${name}="${escapeSupervisorEnvironment(value)}"`).join(",");
7659
+ return `[unix_http_server]
7660
+ file=${supervisorSocketPath(store)}
7661
+ chmod=0600
7662
+
7663
+ [supervisord]
7664
+ logfile=${supervisorLogPath(store)}
7665
+ pidfile=${supervisorPidPath(store)}
7666
+ childlogdir=${supervisorDirectory(store)}
7667
+ nodaemon=false
7668
+ minfds=1024
7669
+ minprocs=200
7670
+
7671
+ [rpcinterface:supervisor]
7672
+ supervisor.rpcinterface_factory=supervisor.rpcinterface:make_main_rpcinterface
7673
+
7674
+ [supervisorctl]
7675
+ serverurl=unix://${supervisorSocketPath(store)}
7676
+
7677
+ [program:${supervisorProgramName}]
7678
+ command=${command}
7679
+ directory=${escapeSupervisorPath((0, import_node_path7.dirname)((0, import_node_path7.resolve)(options.entrypointPath)))}
7680
+ environment=${environment}
7681
+ autostart=true
7682
+ autorestart=true
7683
+ startsecs=3
7684
+ startretries=10
7685
+ stopsignal=TERM
7686
+ stopasgroup=true
7687
+ killasgroup=true
7688
+ stopwaitsecs=20
7689
+ stdout_logfile=${escapeSupervisorPath(store.runtimeLogPath())}
7690
+ stderr_logfile=${escapeSupervisorPath(store.runtimeErrorLogPath())}
7691
+ stdout_logfile_maxbytes=20MB
7692
+ stderr_logfile_maxbytes=20MB
7693
+ stdout_logfile_backups=3
7694
+ stderr_logfile_backups=3
7695
+ `;
7528
7696
  }
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);
7697
+ async function restartSupervisorUserService(store, runtime) {
7698
+ const configPath = supervisorConfigPath(store);
7699
+ if (!await supervisorIsRunning(store, runtime)) {
7700
+ await (0, import_promises10.rm)(supervisorSocketPath(store), { force: true });
7701
+ await (0, import_promises10.rm)(supervisorPidPath(store), { force: true });
7702
+ await runtime.run("supervisord", ["-c", configPath]);
7703
+ await waitForSupervisorControl(store, runtime);
7704
+ return;
7537
7705
  }
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);
7706
+ try {
7707
+ await runtime.run("supervisorctl", [
7708
+ "-c",
7709
+ configPath,
7710
+ "restart",
7711
+ supervisorProgramName
7712
+ ]);
7713
+ } catch {
7714
+ await runtime.run("supervisorctl", [
7715
+ "-c",
7716
+ configPath,
7717
+ "start",
7718
+ supervisorProgramName
7719
+ ]);
7562
7720
  }
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");
7721
+ }
7722
+ async function supervisorIsRunning(store, runtime) {
7723
+ return await commandSucceeds(runtime, "supervisorctl", [
7724
+ "-c",
7725
+ supervisorConfigPath(store),
7726
+ "pid"
7727
+ ]);
7728
+ }
7729
+ async function waitForSupervisorControl(store, runtime) {
7730
+ const deadline = Date.now() + 5e3;
7731
+ while (Date.now() < deadline) {
7732
+ if (await supervisorIsRunning(store, runtime)) {
7733
+ return;
7599
7734
  }
7600
- await delay3(pairingPollMilliseconds);
7735
+ await delay5(100);
7601
7736
  }
7602
- throw new Error("Local Machine pairing expired");
7737
+ throw new Error("Supervisor did not become ready within 5 seconds");
7603
7738
  }
7604
- function getOperatingSystem() {
7605
- if ((0, import_node_os5.platform)() === "darwin") {
7606
- return MachineOperatingSystem.MacOS;
7739
+ function launchAgentPath() {
7740
+ return (0, import_node_path7.join)(process.env.HOME ?? (0, import_node_os5.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
7741
+ }
7742
+ function systemdUnitPath() {
7743
+ const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path7.join)(process.env.HOME ?? (0, import_node_os5.homedir)(), ".config");
7744
+ return (0, import_node_path7.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
7745
+ }
7746
+ function supervisorDirectory(store) {
7747
+ return (0, import_node_path7.join)(store.baseDirectory, "supervisor");
7748
+ }
7749
+ function supervisorConfigPath(store) {
7750
+ return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.conf");
7751
+ }
7752
+ function supervisorSocketPath(store) {
7753
+ return (0, import_node_path7.join)(supervisorDirectory(store), "supervisor.sock");
7754
+ }
7755
+ function supervisorPidPath(store) {
7756
+ return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.pid");
7757
+ }
7758
+ function supervisorLogPath(store) {
7759
+ return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.log");
7760
+ }
7761
+ async function commandSucceeds(runtime, command, argumentsList) {
7762
+ try {
7763
+ await runtime.run(command, argumentsList);
7764
+ return true;
7765
+ } catch {
7766
+ return false;
7607
7767
  }
7608
- if ((0, import_node_os5.platform)() === "linux") {
7609
- return MachineOperatingSystem.Linux;
7768
+ }
7769
+ async function runCommandIgnoringFailure(runtime, command, argumentsList) {
7770
+ try {
7771
+ await runtime.run(command, argumentsList);
7772
+ } catch {
7773
+ return;
7610
7774
  }
7611
- return MachineOperatingSystem.Windows;
7612
7775
  }
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();
7776
+ async function uninstallManagerIgnoringFailure(manager, store, runtime) {
7777
+ try {
7778
+ await uninstallManager(manager, store, runtime);
7779
+ } catch {
7780
+ return;
7781
+ }
7617
7782
  }
7618
- function delay3(milliseconds) {
7783
+ function escapeXml(value) {
7784
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
7785
+ }
7786
+ function escapeSystemdArgument(value) {
7787
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
7788
+ }
7789
+ function escapeSystemdEnvironment(value) {
7790
+ return value.replaceAll("%", "%%").replaceAll(" ", "\\x20");
7791
+ }
7792
+ function escapeSupervisorArgument(value) {
7793
+ return `"${escapeSupervisorValue(value)}"`;
7794
+ }
7795
+ function escapeSupervisorEnvironment(value) {
7796
+ return escapeSupervisorValue(value);
7797
+ }
7798
+ function escapeSupervisorPath(value) {
7799
+ return value.replaceAll("%", "%%");
7800
+ }
7801
+ function escapeSupervisorValue(value) {
7802
+ return value.replaceAll("%", "%%").replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n");
7803
+ }
7804
+ function errorMessage(error) {
7805
+ return error instanceof Error ? error.message : String(error);
7806
+ }
7807
+ function isNodeErrorCode4(error, expectedCode) {
7808
+ return error instanceof Error && "code" in error && error.code === expectedCode;
7809
+ }
7810
+ function delay5(milliseconds) {
7619
7811
  return new Promise((resolvePromise) => {
7620
7812
  setTimeout(resolvePromise, milliseconds);
7621
7813
  });
7622
7814
  }
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"() {
7815
+ var import_node_child_process2, import_promises10, import_node_os5, import_node_path7, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerCommandTimeoutMilliseconds, supervisorProgramName, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
7816
+ var init_service_manager = __esm({
7817
+ "../machine-connector/dist/runtime/service-manager.js"() {
7626
7818
  "use strict";
7627
7819
  init_cjs_shims();
7628
- import_node_child_process3 = require("child_process");
7629
- import_node_crypto6 = require("crypto");
7820
+ import_node_child_process2 = require("child_process");
7821
+ import_promises10 = require("fs/promises");
7630
7822
  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;
7641
- }
7642
- });
7643
-
7644
- // ../machine-connector/dist/runtime/service-manager.js
7645
- function parseServiceManagerPreference(value) {
7646
- if (value === ServiceManagerPreference.Auto) {
7647
- return ServiceManagerPreference.Auto;
7648
- }
7649
- if (value === ServiceManagerPreference.Systemd) {
7650
- return ServiceManagerPreference.Systemd;
7651
- }
7652
- if (value === ServiceManagerPreference.Supervisor) {
7653
- return ServiceManagerPreference.Supervisor;
7654
- }
7655
- if (value === ServiceManagerPreference.None) {
7656
- return ServiceManagerPreference.None;
7657
- }
7658
- throw new Error(`Unsupported service manager: ${value}`);
7659
- }
7660
- function selectUserServiceManager(preference, capabilities) {
7661
- if (preference === ServiceManagerPreference.None) {
7662
- return {
7663
- detail: "Background service installation was explicitly disabled.",
7664
- manager: UserServiceManager.None
7665
- };
7666
- }
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
7823
+ import_node_path7 = require("path");
7824
+ import_node_util2 = require("util");
7825
+ execFileAsync = (0, import_node_util2.promisify)(import_node_child_process2.execFile);
7826
+ launchAgentLabel = "ai.moxt.machine-connector";
7827
+ serviceManagerCommandTimeoutMilliseconds = 5e3;
7828
+ supervisorProgramName = "moxt-machine-connector";
7829
+ (function(ServiceManagerPreference2) {
7830
+ ServiceManagerPreference2["Auto"] = "auto";
7831
+ ServiceManagerPreference2["None"] = "none";
7832
+ ServiceManagerPreference2["Supervisor"] = "supervisor";
7833
+ ServiceManagerPreference2["Systemd"] = "systemd";
7834
+ })(ServiceManagerPreference || (ServiceManagerPreference = {}));
7835
+ (function(UserServiceManager2) {
7836
+ UserServiceManager2["Launchd"] = "launchd";
7837
+ UserServiceManager2["None"] = "none";
7838
+ UserServiceManager2["Supervisor"] = "supervisor";
7839
+ UserServiceManager2["Systemd"] = "systemd";
7840
+ })(UserServiceManager || (UserServiceManager = {}));
7841
+ defaultServiceManagerRuntime = {
7842
+ operatingSystem: (0, import_node_os5.platform)(),
7843
+ async run(command, argumentsList) {
7844
+ const result = await execFileAsync(command, argumentsList, {
7845
+ encoding: "utf8",
7846
+ killSignal: "SIGKILL",
7847
+ timeout: serviceManagerCommandTimeoutMilliseconds
7848
+ });
7849
+ return {
7850
+ stderr: String(result.stderr),
7851
+ stdout: String(result.stdout)
7852
+ };
7853
+ }
7674
7854
  };
7675
7855
  }
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
- };
7856
+ });
7857
+
7858
+ // ../machine-connector/dist/runtime/daemon-reconcile.js
7859
+ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()) {
7860
+ await store.initialize();
7861
+ const lock = await ProcessLock.acquire(store.reconcileLockPath(), {
7862
+ timeoutMilliseconds: reconcileTimeoutMilliseconds
7863
+ });
7864
+ if (!lock)
7865
+ return { outcome: DaemonReconcileOutcome.Skipped };
7866
+ try {
7867
+ const initial = await reachableRuntimeStatus(store);
7868
+ if (!initial)
7869
+ return { outcome: DaemonReconcileOutcome.Skipped };
7870
+ const manager = await recordedServiceManager(store);
7871
+ if (manager === UserServiceManager.None) {
7872
+ return { outcome: DaemonReconcileOutcome.Skipped };
7682
7873
  }
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");
7874
+ if (initial.cliVersion === options.cliVersion) {
7875
+ return { manager, outcome: DaemonReconcileOutcome.Skipped };
7688
7876
  }
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");
7877
+ if (!await managedServiceOwnsProcess(manager, initial.pid, store)) {
7878
+ return { outcome: DaemonReconcileOutcome.Skipped };
7697
7879
  }
7698
- return {
7699
- detail: "Using the Supervisor service manager.",
7700
- manager: UserServiceManager.Supervisor
7701
- };
7880
+ try {
7881
+ await validateCliEntrypoint(options, store);
7882
+ } catch (error) {
7883
+ throw new DaemonRefreshError("validation", errorMessage2(error), {
7884
+ cause: error
7885
+ });
7886
+ }
7887
+ if (initial.activeJobs.length > 0) {
7888
+ options.onActiveJobs?.(initial.activeJobs.length);
7889
+ }
7890
+ let refresh;
7891
+ try {
7892
+ refresh = await refreshManagedUserService(store, {
7893
+ commandArguments: [...options.commandArguments],
7894
+ entrypointPath: (0, import_node_path8.resolve)(options.entrypointPath),
7895
+ environment: { ...options.environment },
7896
+ nodePath: (0, import_node_path8.resolve)(options.nodePath)
7897
+ });
7898
+ if (!refresh) {
7899
+ throw new Error("The Connector service is no longer managed by Moxt");
7900
+ }
7901
+ } catch (error) {
7902
+ throw new DaemonRefreshError("restart", error instanceof Error ? error.message : String(error), { cause: error });
7903
+ }
7904
+ const deadline = Date.now() + reconcileTimeoutMilliseconds;
7905
+ while (Date.now() < deadline) {
7906
+ const current2 = await reachableRuntimeStatus(store);
7907
+ if (current2?.cliVersion === options.cliVersion && current2.connectorInstanceId !== initial.connectorInstanceId) {
7908
+ return { manager, outcome: DaemonReconcileOutcome.Restarted };
7909
+ }
7910
+ await delay6(100);
7911
+ }
7912
+ const verificationMessage = `managed daemon did not report CLI ${options.cliVersion} with a new instance ID`;
7913
+ try {
7914
+ await refresh.rollback();
7915
+ } catch (error) {
7916
+ throw new DaemonRefreshError("verification", `${verificationMessage}; restoring the previous service definition also failed: ${errorMessage2(error)}`, { cause: error });
7917
+ }
7918
+ throw new DaemonRefreshError("verification", verificationMessage);
7919
+ } finally {
7920
+ await lock.release();
7702
7921
  }
7703
- if (capabilities.systemdUserAvailable) {
7704
- return {
7705
- detail: "Automatically selected the systemd user service manager.",
7706
- manager: UserServiceManager.Systemd
7707
- };
7922
+ }
7923
+ async function validateCliEntrypoint(options, store) {
7924
+ if (options.commandArguments.length !== 2 || options.commandArguments[0] !== "machine" || options.commandArguments[1] !== "daemon") {
7925
+ throw new Error("The managed daemon command must be `machine daemon`");
7708
7926
  }
7709
- if (capabilities.supervisorAvailable) {
7710
- return {
7711
- detail: "Automatically selected the Supervisor service manager.",
7712
- manager: UserServiceManager.Supervisor
7713
- };
7927
+ const nodePath = await (0, import_promises11.realpath)((0, import_node_path8.resolve)(options.nodePath));
7928
+ const entrypointPath = await (0, import_promises11.realpath)((0, import_node_path8.resolve)(options.entrypointPath));
7929
+ await (0, import_promises11.access)(nodePath, import_promises11.constants.X_OK);
7930
+ await (0, import_promises11.access)(entrypointPath, import_promises11.constants.R_OK);
7931
+ const probe = await execFileAsync2(nodePath, [entrypointPath, "--version"], {
7932
+ encoding: "utf8",
7933
+ env: {
7934
+ ...process.env,
7935
+ ...options.environment,
7936
+ MOXT_MACHINE_HOME: store.baseDirectory,
7937
+ MOXT_TELEMETRY_DISABLED: "1",
7938
+ NO_UPDATE_NOTIFIER: "1"
7939
+ },
7940
+ maxBuffer: 1024 * 1024,
7941
+ killSignal: "SIGKILL",
7942
+ timeout: 5e3
7943
+ });
7944
+ const reportedVersion = probe.stdout.trim().replace(/^v/, "");
7945
+ if (reportedVersion !== options.cliVersion) {
7946
+ throw new Error(`candidate CLI reported ${reportedVersion || "no version"} instead of ${options.cliVersion}`);
7714
7947
  }
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
7948
  }
7720
- async function detectServiceManagerCapabilities(runtime = defaultServiceManagerRuntime) {
7721
- if (runtime.operatingSystem !== "linux") {
7722
- return {
7723
- operatingSystem: runtime.operatingSystem,
7724
- supervisorAvailable: false,
7725
- systemdUserAvailable: false
7726
- };
7949
+ async function reachableRuntimeStatus(store) {
7950
+ try {
7951
+ const response = await requestRuntimeStatus(store);
7952
+ return response.status;
7953
+ } catch {
7954
+ return void 0;
7727
7955
  }
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
7956
  }
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
7743
- });
7744
- }
7745
- const capabilities = await detectServiceManagerCapabilities(runtime);
7746
- return selectUserServiceManager(preference, capabilities);
7957
+ function delay6(milliseconds) {
7958
+ return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
7747
7959
  }
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
7960
+ function errorMessage2(error) {
7961
+ return error instanceof Error ? error.message : String(error);
7962
+ }
7963
+ var import_node_child_process3, import_promises11, import_node_path8, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshError;
7964
+ var init_daemon_reconcile = __esm({
7965
+ "../machine-connector/dist/runtime/daemon-reconcile.js"() {
7966
+ "use strict";
7967
+ init_cjs_shims();
7968
+ import_node_child_process3 = require("child_process");
7969
+ import_promises11 = require("fs/promises");
7970
+ import_node_path8 = require("path");
7971
+ import_node_util3 = require("util");
7972
+ init_local_ipc();
7973
+ init_process_lock();
7974
+ init_service_manager();
7975
+ init_store();
7976
+ reconcileTimeoutMilliseconds = 12e3;
7977
+ execFileAsync2 = (0, import_node_util3.promisify)(import_node_child_process3.execFile);
7978
+ (function(DaemonReconcileOutcome2) {
7979
+ DaemonReconcileOutcome2["Restarted"] = "restarted";
7980
+ DaemonReconcileOutcome2["Skipped"] = "skipped";
7981
+ })(DaemonReconcileOutcome || (DaemonReconcileOutcome = {}));
7982
+ DaemonRefreshError = class extends Error {
7983
+ stage;
7984
+ constructor(stage, message, options) {
7985
+ super(message, options);
7986
+ this.stage = stage;
7987
+ this.name = "DaemonRefreshError";
7988
+ }
7759
7989
  };
7760
7990
  }
7761
- const options = {
7762
- ...request2.options,
7763
- environment: {
7764
- ...createServiceEnvironment(request2.options),
7765
- MOXT_MACHINE_HOME: store.baseDirectory
7991
+ });
7992
+
7993
+ // ../machine-connector/dist/runtime/doctor.js
7994
+ async function runMachineDoctor(store) {
7995
+ const checks = [];
7996
+ const connections = await store.listConnections();
7997
+ checks.push({
7998
+ detail: `${connections.length} configured connection(s)`,
7999
+ name: "configuration",
8000
+ status: connections.length > 0 ? DoctorCheckStatus.Passed : DoctorCheckStatus.Warning
8001
+ });
8002
+ try {
8003
+ const response = await requestRuntimeStatus(store);
8004
+ checks.push({
8005
+ detail: response.error ?? `PID ${response.status?.pid ?? "unknown"}`,
8006
+ name: "daemon",
8007
+ status: response.error ? DoctorCheckStatus.Failed : DoctorCheckStatus.Passed
8008
+ });
8009
+ } catch (error) {
8010
+ checks.push({
8011
+ detail: errorMessage3(error),
8012
+ name: "daemon",
8013
+ status: DoctorCheckStatus.Failed
8014
+ });
8015
+ }
8016
+ for (const connection of connections) {
8017
+ try {
8018
+ await (0, import_promises12.access)(connection.rootPath, import_node_fs.constants.R_OK | import_node_fs.constants.X_OK);
8019
+ checks.push({
8020
+ detail: connection.rootPath,
8021
+ name: `root:${connection.connectionId}`,
8022
+ status: DoctorCheckStatus.Passed
8023
+ });
8024
+ } catch (error) {
8025
+ checks.push({
8026
+ detail: errorMessage3(error),
8027
+ name: `root:${connection.connectionId}`,
8028
+ status: DoctorCheckStatus.Failed
8029
+ });
8030
+ }
8031
+ const relayUrl = new URL(connection.relayOrigin);
8032
+ try {
8033
+ const address = await (0, import_promises13.lookup)(relayUrl.hostname);
8034
+ checks.push({
8035
+ detail: `${relayUrl.hostname} resolves to ${address.address}`,
8036
+ name: `dns:${connection.connectionId}`,
8037
+ status: DoctorCheckStatus.Passed
8038
+ });
8039
+ } catch (error) {
8040
+ checks.push({
8041
+ detail: errorMessage3(error),
8042
+ name: `dns:${connection.connectionId}`,
8043
+ status: DoctorCheckStatus.Failed
8044
+ });
8045
+ }
8046
+ try {
8047
+ const response = await fetch(connection.relayOrigin, {
8048
+ method: "HEAD",
8049
+ signal: AbortSignal.timeout(1e4)
8050
+ });
8051
+ checks.push({
8052
+ detail: `TLS and HTTPS succeeded with status ${response.status}`,
8053
+ name: `tls:${connection.connectionId}`,
8054
+ status: DoctorCheckStatus.Passed
8055
+ });
8056
+ const serverDate = response.headers.get("date");
8057
+ const clockDifference = serverDate ? Math.abs(Date.parse(serverDate) - Date.now()) : 0;
8058
+ checks.push({
8059
+ detail: serverDate ? `${Math.round(clockDifference / 1e3)} second clock difference` : "Relay did not return a Date header",
8060
+ name: `clock:${connection.connectionId}`,
8061
+ status: serverDate && clockDifference > 3e5 ? DoctorCheckStatus.Warning : DoctorCheckStatus.Passed
8062
+ });
8063
+ } catch (error) {
8064
+ checks.push({
8065
+ detail: errorMessage3(error),
8066
+ name: `tls:${connection.connectionId}`,
8067
+ status: DoctorCheckStatus.Failed
8068
+ });
7766
8069
  }
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
8070
  }
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
- };
8071
+ const proxy = process.env.HTTPS_PROXY ?? process.env.https_proxy ?? process.env.ALL_PROXY ?? process.env.all_proxy;
8072
+ checks.push({
8073
+ detail: proxy ? "A process-level proxy is configured" : "Direct outbound HTTPS",
8074
+ name: "proxy",
8075
+ status: proxy ? DoctorCheckStatus.Warning : DoctorCheckStatus.Passed
8076
+ });
8077
+ checks.push({
8078
+ detail: "HTTPS long-poll is authoritative; optional WSS wakeup is not required",
8079
+ name: "transport",
8080
+ status: DoctorCheckStatus.Passed
8081
+ });
8082
+ try {
8083
+ const result = await execFileAsync3(process.env.MOXT_CODEX_PATH ?? "codex", ["--version"]);
8084
+ checks.push({
8085
+ detail: result.stdout.trim(),
8086
+ name: "codex",
8087
+ status: DoctorCheckStatus.Passed
8088
+ });
8089
+ } catch (error) {
8090
+ checks.push({
8091
+ detail: errorMessage3(error),
8092
+ name: "codex",
8093
+ status: DoctorCheckStatus.Warning
8094
+ });
8095
+ }
8096
+ try {
8097
+ const result = await execFileAsync3(process.env.MOXT_CLAUDE_PATH ?? "claude", ["--version"]);
8098
+ checks.push({
8099
+ detail: result.stdout.trim(),
8100
+ name: "claude",
8101
+ status: DoctorCheckStatus.Passed
8102
+ });
8103
+ } catch (error) {
8104
+ checks.push({
8105
+ detail: errorMessage3(error),
8106
+ name: "claude",
8107
+ status: DoctorCheckStatus.Warning
8108
+ });
8109
+ }
8110
+ return checks;
8111
+ }
8112
+ function errorMessage3(error) {
8113
+ return error instanceof Error ? error.message : String(error);
8114
+ }
8115
+ var import_node_child_process4, import_promises12, import_node_fs, import_promises13, import_node_util4, execFileAsync3, DoctorCheckStatus;
8116
+ var init_doctor = __esm({
8117
+ "../machine-connector/dist/runtime/doctor.js"() {
8118
+ "use strict";
8119
+ init_cjs_shims();
8120
+ import_node_child_process4 = require("child_process");
8121
+ import_promises12 = require("fs/promises");
8122
+ import_node_fs = require("fs");
8123
+ import_promises13 = require("dns/promises");
8124
+ import_node_util4 = require("util");
8125
+ init_local_ipc();
8126
+ execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process4.execFile);
8127
+ (function(DoctorCheckStatus2) {
8128
+ DoctorCheckStatus2["Failed"] = "failed";
8129
+ DoctorCheckStatus2["Passed"] = "passed";
8130
+ DoctorCheckStatus2["Warning"] = "warning";
8131
+ })(DoctorCheckStatus || (DoctorCheckStatus = {}));
7785
8132
  }
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);
8133
+ });
8134
+
8135
+ // ../machine-connector/dist/runtime/machine-manager.js
8136
+ function machineManagerActions() {
8137
+ return [
8138
+ {
8139
+ action: MachineManagerAction.Refresh,
8140
+ label: "Refresh now"
8141
+ },
8142
+ {
8143
+ action: MachineManagerAction.Connect,
8144
+ label: "Pair a new machine connection"
8145
+ },
8146
+ {
8147
+ action: MachineManagerAction.Disconnect,
8148
+ label: "Disconnect the selected connection"
8149
+ },
8150
+ {
8151
+ action: MachineManagerAction.Doctor,
8152
+ label: "Run diagnostics"
8153
+ },
8154
+ {
8155
+ action: MachineManagerAction.Logs,
8156
+ label: "Open recent logs"
8157
+ },
8158
+ {
8159
+ action: MachineManagerAction.ServiceInstall,
8160
+ label: "Install the Connector service"
8161
+ },
8162
+ {
8163
+ action: MachineManagerAction.ServiceRestart,
8164
+ label: "Restart the Connector service"
8165
+ },
8166
+ {
8167
+ action: MachineManagerAction.ServiceStop,
8168
+ label: "Stop the Connector service"
8169
+ },
8170
+ {
8171
+ action: MachineManagerAction.ServiceUninstall,
8172
+ label: "Uninstall the Connector service"
8173
+ },
8174
+ {
8175
+ action: MachineManagerAction.Quit,
8176
+ label: "Quit"
7799
8177
  }
8178
+ ];
8179
+ }
8180
+ function ensureInteractiveTerminal(inputIsTty, outputIsTty) {
8181
+ if (!inputIsTty || !outputIsTty) {
8182
+ throw new Error("moxt machine manager requires an interactive TTY. Use `moxt machine status`, `logs`, or `doctor` in non-interactive scripts.");
7800
8183
  }
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
8184
  }
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);
8185
+ async function collectMachineManagerSnapshot(store, depth) {
8186
+ const connections = await store.listConnections();
8187
+ const jobs = await store.listJobs();
8188
+ const serviceManager = (await store.readServiceManager()).value;
8189
+ const runtime = {};
8190
+ try {
8191
+ runtime.value = (await requestRuntimeStatus(store)).status;
8192
+ } catch {
8193
+ runtime.value = void 0;
8194
+ }
8195
+ const checks = depth === MachineManagerSnapshotDepth.WithDoctor ? await runMachineDoctor(store) : [];
7812
8196
  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)
8197
+ checks,
8198
+ connections: connections.map(toManagerConnection),
8199
+ jobs: jobs.map(toManagerJob).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
8200
+ logLines: await readRecentLogLines(store),
8201
+ refreshedAt: (/* @__PURE__ */ new Date()).toISOString(),
8202
+ runtime: runtime.value,
8203
+ serviceManager: serviceManager?.manager
7816
8204
  };
7817
8205
  }
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);
8206
+ function renderMachineManager(snapshot, state, requestedWidth, requestedHeight) {
8207
+ const width = Math.max(24, requestedWidth);
8208
+ const height = Math.max(8, requestedHeight);
8209
+ const lines = [];
8210
+ const online = snapshot.runtime !== void 0;
8211
+ lines.push(styledLine(` MOXT MACHINE MANAGER ${online ? "ONLINE" : "OFFLINE"} ${snapshot.serviceManager ?? "no service"}`, width, styleHeader));
8212
+ lines.push(fitLine(renderTabs(state.view), width));
8213
+ lines.push(repeatCharacter("\u2500", width));
8214
+ const contentHeight = Math.max(1, height - 5);
8215
+ const content3 = state.actionMenuOpen ? renderActions(state) : renderView(snapshot, state);
8216
+ for (const line of content3.slice(0, contentHeight)) {
8217
+ lines.push(fitLine(line, width));
7845
8218
  }
7846
- if (capabilities.supervisorAvailable && !candidates.includes(UserServiceManager.Supervisor)) {
7847
- candidates.push(UserServiceManager.Supervisor);
8219
+ while (lines.length < height - 2) {
8220
+ lines.push(" ".repeat(width));
7848
8221
  }
7849
- return candidates;
8222
+ lines.push(repeatCharacter("\u2500", width));
8223
+ lines.push(fitLine(state.message ?? "[A] Actions [Tab/1-5] View [Up/Down] Select [R] Refresh [Q] Quit", width));
8224
+ return lines.slice(0, height).join("\n");
7850
8225
  }
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);
8226
+ async function runMachineManager(store, commandRunner) {
8227
+ ensureInteractiveTerminal(Boolean(process.stdin.isTTY), Boolean(process.stdout.isTTY));
8228
+ const manager = new InteractiveMachineManager(store, commandRunner);
8229
+ await manager.run();
7858
8230
  }
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
- }
8231
+ function renderTabs(selected) {
8232
+ const labels = [
8233
+ "1 Overview",
8234
+ "2 Connections",
8235
+ "3 Jobs",
8236
+ "4 Logs",
8237
+ "5 Doctor"
8238
+ ];
8239
+ return labels.map((label, index2) => index2 === selected ? `[${label}]` : ` ${label} `).join(" ");
7872
8240
  }
7873
- async function restartManager(manager, store, runtime) {
7874
- if (manager === UserServiceManager.None) {
7875
- return;
8241
+ function renderView(snapshot, state) {
8242
+ if (state.view === MachineManagerView.Overview) {
8243
+ return renderOverview(snapshot);
7876
8244
  }
7877
- if (manager === UserServiceManager.Launchd) {
7878
- await runtime.run("launchctl", [
7879
- "kickstart",
7880
- "-k",
7881
- `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7882
- ]);
7883
- return;
8245
+ if (state.view === MachineManagerView.Connections) {
8246
+ return renderConnections(snapshot, state.selectedRowIndex);
7884
8247
  }
7885
- if (manager === UserServiceManager.Systemd) {
7886
- await runtime.run("systemctl", [
7887
- "--user",
7888
- "restart",
7889
- "moxt-machine-connector.service"
7890
- ]);
7891
- return;
8248
+ if (state.view === MachineManagerView.Jobs) {
8249
+ return renderJobs(snapshot, state.selectedRowIndex);
7892
8250
  }
7893
- await restartSupervisorUserService(store, runtime);
8251
+ if (state.view === MachineManagerView.Logs) {
8252
+ return renderLogs(snapshot);
8253
+ }
8254
+ return renderDoctor(snapshot);
7894
8255
  }
7895
- async function stopManager(manager, store, runtime) {
7896
- if (manager === UserServiceManager.None) {
7897
- return;
8256
+ function renderOverview(snapshot) {
8257
+ const runtime = snapshot.runtime;
8258
+ const lines = [
8259
+ "",
8260
+ ` Daemon ${runtime ? `ONLINE PID ${runtime.pid} v${runtime.version}` : "OFFLINE"}`,
8261
+ ` Service ${snapshot.serviceManager ?? "not installed"}`,
8262
+ ` Connections ${snapshot.connections.length}`,
8263
+ ` Active Jobs ${runtime?.activeJobs.length ?? 0}`,
8264
+ ` Stored Jobs ${snapshot.jobs.length}`,
8265
+ ` Refreshed ${formatTimestamp(snapshot.refreshedAt)}`,
8266
+ ""
8267
+ ];
8268
+ if (snapshot.connections.length === 0) {
8269
+ lines.push(' No connections. Press A and choose "Pair a new machine connection".');
8270
+ return lines;
7898
8271
  }
7899
- if (manager === UserServiceManager.Launchd) {
7900
- await runtime.run("launchctl", [
7901
- "bootout",
7902
- `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7903
- ]);
7904
- return;
8272
+ lines.push(" Connected roots");
8273
+ for (const connection of snapshot.connections) {
8274
+ lines.push(` ${connection.machineName} ${connection.rootPath}`);
7905
8275
  }
7906
- if (manager === UserServiceManager.Systemd) {
7907
- await runtime.run("systemctl", [
7908
- "--user",
7909
- "stop",
7910
- "moxt-machine-connector.service"
7911
- ]);
7912
- return;
8276
+ return lines;
8277
+ }
8278
+ function renderConnections(snapshot, selectedRowIndex) {
8279
+ if (snapshot.connections.length === 0) {
8280
+ return ["", " No connections", " Press A to pair a machine."];
7913
8281
  }
7914
- await runCommandIgnoringFailure(runtime, "supervisorctl", [
7915
- "-c",
7916
- supervisorConfigPath(store),
7917
- "stop",
7918
- supervisorProgramName
7919
- ]);
8282
+ const lines = [
8283
+ " MACHINE ROOT WORKSPACE / TARGET"
8284
+ ];
8285
+ snapshot.connections.forEach((connection, index2) => {
8286
+ const marker = index2 === selectedRowIndex ? ">" : " ";
8287
+ lines.push(`${marker} ${connection.machineName} ${connection.rootPath} ${connection.workspaceId} / ${connection.targetId}`);
8288
+ lines.push(` ${connection.connectionId} ${connection.relayOrigin}`);
8289
+ });
8290
+ return lines;
7920
8291
  }
7921
- async function uninstallManager(manager, store, runtime) {
7922
- if (manager === UserServiceManager.None) {
7923
- return;
8292
+ function renderJobs(snapshot, selectedRowIndex) {
8293
+ if (snapshot.jobs.length === 0) {
8294
+ return ["", " No Jobs have been stored on this machine."];
7924
8295
  }
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;
8296
+ const lines = [" STATUS KIND JOB / COMMAND"];
8297
+ snapshot.jobs.forEach((job, index2) => {
8298
+ const marker = index2 === selectedRowIndex ? ">" : " ";
8299
+ lines.push(`${marker} ${job.status ?? job.phase} ${job.kind} ${job.command ?? job.jobId}`);
8300
+ lines.push(` ${job.jobId} ${job.relativeWorkingDirectory} ${formatTimestamp(job.updatedAt)}`);
8301
+ });
8302
+ return lines;
8303
+ }
8304
+ function renderLogs(snapshot) {
8305
+ if (snapshot.logLines.length === 0) {
8306
+ return ["", " No Connector logs are available."];
7932
8307
  }
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;
8308
+ return snapshot.logLines.map((line) => ` ${line}`);
8309
+ }
8310
+ function renderDoctor(snapshot) {
8311
+ if (snapshot.checks.length === 0) {
8312
+ return [
8313
+ "",
8314
+ " Diagnostics have not run yet.",
8315
+ ' Press A and choose "Run diagnostics".'
8316
+ ];
7946
8317
  }
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
8318
+ return snapshot.checks.map((check) => ` ${check.status.padEnd(7)} ${check.name}: ${check.detail}`);
8319
+ }
8320
+ function renderActions(state) {
8321
+ const lines = [
8322
+ " Actions",
8323
+ " Use Up/Down and Enter. Esc closes this menu.",
8324
+ ""
8325
+ ];
8326
+ machineManagerActions().forEach((definition2, index2) => {
8327
+ const selected = index2 === state.selectedActionIndex;
8328
+ const line = `${selected ? ">" : " "} ${definition2.label}`;
8329
+ lines.push(selected ? `${styleSelected}${line}${styleReset}` : line);
7957
8330
  });
8331
+ return lines;
7958
8332
  }
7959
- async function configuredServiceManager(store, runtime) {
7960
- const storedManager = await readStoredServiceManager(store);
7961
- if (storedManager !== UserServiceManager.None) {
7962
- return storedManager;
8333
+ function rowCountForView(snapshot, view) {
8334
+ if (view === MachineManagerView.Connections) {
8335
+ return snapshot.connections.length;
7963
8336
  }
7964
- const stored = await store.readServiceManager();
7965
- if (stored.value) {
7966
- return UserServiceManager.None;
8337
+ if (view === MachineManagerView.Jobs) {
8338
+ return snapshot.jobs.length;
7967
8339
  }
7968
- const capabilities = await detectServiceManagerCapabilities(runtime);
7969
- return selectUserServiceManager(ServiceManagerPreference.Auto, capabilities).manager;
8340
+ return 0;
7970
8341
  }
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);
8342
+ function toManagerConnection(connection) {
8343
+ return {
8344
+ connectionId: connection.connectionId,
8345
+ machineName: connection.machineName,
8346
+ relayOrigin: connection.relayOrigin,
8347
+ rootDisplayName: connection.rootDisplayName,
8348
+ rootPath: connection.rootPath,
8349
+ targetId: connection.targetId,
8350
+ targetKind: connection.targetKind,
8351
+ workspaceId: connection.workspaceId
8352
+ };
7977
8353
  }
7978
- function parseStoredServiceManager(value) {
7979
- if (value === UserServiceManager.Launchd) {
7980
- return UserServiceManager.Launchd;
8354
+ function toManagerJob(job) {
8355
+ return {
8356
+ command: formatPersistedCommand(job).value,
8357
+ connectionId: job.connectionId,
8358
+ jobId: job.claim.jobId,
8359
+ kind: job.claim.kind,
8360
+ phase: job.phase,
8361
+ relativeWorkingDirectory: job.claim.relativeWorkingDirectory,
8362
+ status: job.finalStatus,
8363
+ updatedAt: job.updatedAt
8364
+ };
8365
+ }
8366
+ function formatPersistedCommand(job) {
8367
+ if (job.claim.kind !== "command") {
8368
+ return {};
7981
8369
  }
7982
- if (value === UserServiceManager.Systemd) {
7983
- return UserServiceManager.Systemd;
8370
+ if (!isRecord3(job.claim.requestPayload)) {
8371
+ return {};
7984
8372
  }
7985
- if (value === UserServiceManager.Supervisor) {
7986
- return UserServiceManager.Supervisor;
8373
+ const executable = job.claim.requestPayload.executable;
8374
+ const argumentsValue = job.claim.requestPayload.arguments;
8375
+ if (typeof executable !== "string" || !Array.isArray(argumentsValue) || !argumentsValue.every((argument) => typeof argument === "string")) {
8376
+ return {};
7987
8377
  }
7988
- if (value === UserServiceManager.None) {
7989
- return UserServiceManager.None;
8378
+ return {
8379
+ value: [executable, ...argumentsValue].map(formatCommandArgument).join(" ")
8380
+ };
8381
+ }
8382
+ function formatCommandArgument(value) {
8383
+ return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : JSON.stringify(value);
8384
+ }
8385
+ async function readRecentLogLines(store) {
8386
+ const normal = await readOptionalFile(store.runtimeLogPath());
8387
+ const errors = await readOptionalFile(store.runtimeErrorLogPath());
8388
+ return [...normal.split("\n"), ...errors.split("\n")].filter((line) => line.length > 0).slice(-maximumLogLines);
8389
+ }
8390
+ async function readOptionalFile(path4) {
8391
+ try {
8392
+ return await (0, import_promises14.readFile)(path4, "utf8");
8393
+ } catch (error) {
8394
+ if (isMissingFile(error)) {
8395
+ return "";
8396
+ }
8397
+ throw error;
7990
8398
  }
7991
- throw new Error(`Unsupported stored service manager: ${value}`);
7992
8399
  }
7993
- async function persistServiceManager(store, manager) {
7994
- await store.writeServiceManager({
7995
- manager,
7996
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
7997
- });
8400
+ async function questionWithDefault(reader, label, defaultValue) {
8401
+ const suffix = defaultValue.length > 0 ? ` [${defaultValue}]` : "";
8402
+ const answer = (await reader.question(`${label}${suffix}: `)).trim();
8403
+ return answer.length > 0 ? answer : defaultValue;
7998
8404
  }
7999
- function managerIsAvailable(manager, capabilities) {
8000
- if (manager === UserServiceManager.Launchd) {
8001
- return capabilities.operatingSystem === "darwin";
8405
+ function appendOption(argumentsList, name, value) {
8406
+ if (value.length > 0) {
8407
+ argumentsList.push(name, value);
8002
8408
  }
8003
- if (manager === UserServiceManager.Systemd) {
8004
- return capabilities.systemdUserAvailable;
8409
+ }
8410
+ function styledLine(value, width, style) {
8411
+ return `${style}${fitLine(value, width)}${styleReset}`;
8412
+ }
8413
+ function fitLine(value, width) {
8414
+ const plainValue = stripAnsi(value);
8415
+ if (plainValue.length > width) {
8416
+ if (width <= 1) {
8417
+ return plainValue.slice(0, width);
8418
+ }
8419
+ return `${plainValue.slice(0, width - 1)}\u2026`;
8005
8420
  }
8006
- if (manager === UserServiceManager.Supervisor) {
8007
- return capabilities.supervisorAvailable;
8421
+ if (value.includes("\x1B[")) {
8422
+ return value;
8008
8423
  }
8009
- return false;
8424
+ return value.padEnd(width);
8010
8425
  }
8011
- function automaticSelectionDetail(manager) {
8012
- if (manager === UserServiceManager.Launchd) {
8013
- return "Automatically selected the macOS LaunchAgent service manager.";
8426
+ function stripAnsi(value) {
8427
+ return value.replaceAll(styleHeader, "").replaceAll(styleSelected, "").replaceAll(styleReset, "");
8428
+ }
8429
+ function repeatCharacter(value, count) {
8430
+ return value.repeat(count);
8431
+ }
8432
+ function wrapIndex(value, count) {
8433
+ return (value % count + count) % count;
8434
+ }
8435
+ function formatTimestamp(value) {
8436
+ const timestamp = Date.parse(value);
8437
+ if (Number.isNaN(timestamp)) {
8438
+ return value;
8014
8439
  }
8015
- if (manager === UserServiceManager.Systemd) {
8016
- return "Automatically selected the systemd user service manager.";
8440
+ return new Date(timestamp).toLocaleString();
8441
+ }
8442
+ function isRecord3(value) {
8443
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8444
+ }
8445
+ function isMissingFile(error) {
8446
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
8447
+ }
8448
+ function errorMessage4(error) {
8449
+ return error instanceof Error ? error.message : String(error);
8450
+ }
8451
+ var import_promises14, import_promises15, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
8452
+ var init_machine_manager = __esm({
8453
+ "../machine-connector/dist/runtime/machine-manager.js"() {
8454
+ "use strict";
8455
+ init_cjs_shims();
8456
+ import_promises14 = require("fs/promises");
8457
+ import_promises15 = require("readline/promises");
8458
+ import_node_readline = require("readline");
8459
+ init_doctor();
8460
+ init_local_ipc();
8461
+ alternateScreenEnter = "\x1B[?1049h";
8462
+ alternateScreenExit = "\x1B[?1049l";
8463
+ clearScreen = "\x1B[2J\x1B[H";
8464
+ cursorHide = "\x1B[?25l";
8465
+ cursorShow = "\x1B[?25h";
8466
+ styleReset = "\x1B[0m";
8467
+ styleHeader = "\x1B[1;30;46m";
8468
+ styleSelected = "\x1B[30;47m";
8469
+ refreshIntervalMilliseconds = 1e3;
8470
+ maximumLogLines = 200;
8471
+ (function(MachineManagerView2) {
8472
+ MachineManagerView2[MachineManagerView2["Overview"] = 0] = "Overview";
8473
+ MachineManagerView2[MachineManagerView2["Connections"] = 1] = "Connections";
8474
+ MachineManagerView2[MachineManagerView2["Jobs"] = 2] = "Jobs";
8475
+ MachineManagerView2[MachineManagerView2["Logs"] = 3] = "Logs";
8476
+ MachineManagerView2[MachineManagerView2["Doctor"] = 4] = "Doctor";
8477
+ })(MachineManagerView || (MachineManagerView = {}));
8478
+ (function(MachineManagerAction2) {
8479
+ MachineManagerAction2["Refresh"] = "refresh";
8480
+ MachineManagerAction2["Connect"] = "connect";
8481
+ MachineManagerAction2["Disconnect"] = "disconnect";
8482
+ MachineManagerAction2["Doctor"] = "doctor";
8483
+ MachineManagerAction2["Logs"] = "logs";
8484
+ MachineManagerAction2["ServiceInstall"] = "service_install";
8485
+ MachineManagerAction2["ServiceRestart"] = "service_restart";
8486
+ MachineManagerAction2["ServiceStop"] = "service_stop";
8487
+ MachineManagerAction2["ServiceUninstall"] = "service_uninstall";
8488
+ MachineManagerAction2["Quit"] = "quit";
8489
+ })(MachineManagerAction || (MachineManagerAction = {}));
8490
+ (function(MachineManagerSnapshotDepth2) {
8491
+ MachineManagerSnapshotDepth2["Basic"] = "basic";
8492
+ MachineManagerSnapshotDepth2["WithDoctor"] = "with_doctor";
8493
+ })(MachineManagerSnapshotDepth || (MachineManagerSnapshotDepth = {}));
8494
+ InteractiveMachineManager = class {
8495
+ store;
8496
+ commandRunner;
8497
+ checks = [];
8498
+ refreshTimer;
8499
+ refreshing = false;
8500
+ resolveRun;
8501
+ snapshot = {
8502
+ checks: [],
8503
+ connections: [],
8504
+ jobs: [],
8505
+ logLines: [],
8506
+ refreshedAt: (/* @__PURE__ */ new Date()).toISOString()
8507
+ };
8508
+ state = {
8509
+ actionMenuOpen: false,
8510
+ selectedActionIndex: 0,
8511
+ selectedRowIndex: 0,
8512
+ view: MachineManagerView.Overview
8513
+ };
8514
+ stopped = false;
8515
+ terminalSuspended = true;
8516
+ constructor(store, commandRunner) {
8517
+ this.store = store;
8518
+ this.commandRunner = commandRunner;
8519
+ }
8520
+ async run() {
8521
+ await this.refresh(MachineManagerSnapshotDepth.Basic);
8522
+ this.enterTerminal();
8523
+ try {
8524
+ await new Promise((resolvePromise) => {
8525
+ this.resolveRun = resolvePromise;
8526
+ });
8527
+ } finally {
8528
+ this.leaveTerminal();
8529
+ }
8530
+ }
8531
+ enterTerminal() {
8532
+ (0, import_node_readline.emitKeypressEvents)(process.stdin);
8533
+ process.stdin.setRawMode(true);
8534
+ process.stdin.resume();
8535
+ process.stdin.on("keypress", this.onKeypress);
8536
+ process.stdout.on("resize", this.onResize);
8537
+ process.on("SIGINT", this.onTerminationSignal);
8538
+ process.on("SIGTERM", this.onTerminationSignal);
8539
+ process.stdout.write(`${alternateScreenEnter}${cursorHide}${clearScreen}`);
8540
+ this.terminalSuspended = false;
8541
+ this.refreshTimer = setInterval(() => {
8542
+ void this.refresh(MachineManagerSnapshotDepth.Basic);
8543
+ }, refreshIntervalMilliseconds);
8544
+ this.render();
8545
+ }
8546
+ leaveTerminal() {
8547
+ if (this.refreshTimer) {
8548
+ clearInterval(this.refreshTimer);
8549
+ this.refreshTimer = void 0;
8550
+ }
8551
+ process.stdin.off("keypress", this.onKeypress);
8552
+ process.stdout.off("resize", this.onResize);
8553
+ process.off("SIGINT", this.onTerminationSignal);
8554
+ process.off("SIGTERM", this.onTerminationSignal);
8555
+ if (process.stdin.isTTY) {
8556
+ process.stdin.setRawMode(false);
8557
+ }
8558
+ process.stdin.pause();
8559
+ process.stdout.write(`${cursorShow}${styleReset}${alternateScreenExit}`);
8560
+ }
8561
+ onResize = () => {
8562
+ this.render();
8563
+ };
8564
+ onTerminationSignal = () => {
8565
+ this.stop();
8566
+ };
8567
+ onKeypress = (text3, key) => {
8568
+ if (key.ctrl && key.name === "c") {
8569
+ this.stop();
8570
+ return;
8571
+ }
8572
+ if (key.name === "q" || text3 === "q") {
8573
+ this.stop();
8574
+ return;
8575
+ }
8576
+ if (key.name === "a" || text3 === "a" || text3 === "?") {
8577
+ this.state.actionMenuOpen = !this.state.actionMenuOpen;
8578
+ this.state.message = void 0;
8579
+ this.render();
8580
+ return;
8581
+ }
8582
+ if (key.name === "escape") {
8583
+ this.state.actionMenuOpen = false;
8584
+ this.render();
8585
+ return;
8586
+ }
8587
+ if (key.name === "up") {
8588
+ this.moveSelection(-1);
8589
+ return;
8590
+ }
8591
+ if (key.name === "down") {
8592
+ this.moveSelection(1);
8593
+ return;
8594
+ }
8595
+ if (key.name === "return" && this.state.actionMenuOpen) {
8596
+ void this.executeSelectedAction();
8597
+ return;
8598
+ }
8599
+ if (key.name === "tab" || key.name === "right") {
8600
+ this.changeView(1);
8601
+ return;
8602
+ }
8603
+ if (key.name === "left") {
8604
+ this.changeView(-1);
8605
+ return;
8606
+ }
8607
+ if (text3 === "r") {
8608
+ void this.refresh(MachineManagerSnapshotDepth.Basic);
8609
+ return;
8610
+ }
8611
+ const viewNumber = Number(text3);
8612
+ if (Number.isInteger(viewNumber) && viewNumber >= 1 && viewNumber <= 5) {
8613
+ this.state.view = viewNumber - 1;
8614
+ this.state.selectedRowIndex = 0;
8615
+ this.state.actionMenuOpen = false;
8616
+ this.render();
8617
+ }
8618
+ };
8619
+ moveSelection(delta) {
8620
+ const rowCount = this.state.actionMenuOpen ? machineManagerActions().length : rowCountForView(this.snapshot, this.state.view);
8621
+ if (rowCount === 0) {
8622
+ return;
8623
+ }
8624
+ if (this.state.actionMenuOpen) {
8625
+ this.state.selectedActionIndex = wrapIndex(this.state.selectedActionIndex + delta, rowCount);
8626
+ } else {
8627
+ this.state.selectedRowIndex = wrapIndex(this.state.selectedRowIndex + delta, rowCount);
8628
+ }
8629
+ this.render();
8630
+ }
8631
+ changeView(delta) {
8632
+ this.state.view = wrapIndex(this.state.view + delta, 5);
8633
+ this.state.selectedRowIndex = 0;
8634
+ this.state.actionMenuOpen = false;
8635
+ this.state.message = void 0;
8636
+ this.render();
8637
+ }
8638
+ async refresh(depth) {
8639
+ if (this.refreshing || this.stopped) {
8640
+ return;
8641
+ }
8642
+ this.refreshing = true;
8643
+ try {
8644
+ const snapshot = await collectMachineManagerSnapshot(this.store, depth);
8645
+ if (snapshot.checks.length > 0) {
8646
+ this.checks = snapshot.checks;
8647
+ }
8648
+ this.snapshot = {
8649
+ ...snapshot,
8650
+ checks: this.checks
8651
+ };
8652
+ this.state.message = void 0;
8653
+ } catch (error) {
8654
+ this.state.message = errorMessage4(error);
8655
+ } finally {
8656
+ this.refreshing = false;
8657
+ this.render();
8658
+ }
8659
+ }
8660
+ render() {
8661
+ if (this.stopped || this.terminalSuspended || !process.stdout.isTTY) {
8662
+ return;
8663
+ }
8664
+ process.stdout.write(`${clearScreen}${renderMachineManager(this.snapshot, this.state, process.stdout.columns ?? 80, process.stdout.rows ?? 24)}`);
8665
+ }
8666
+ async executeSelectedAction() {
8667
+ const definition2 = machineManagerActions()[this.state.selectedActionIndex];
8668
+ this.state.actionMenuOpen = false;
8669
+ if (definition2.action === MachineManagerAction.Quit) {
8670
+ this.stop();
8671
+ return;
8672
+ }
8673
+ if (definition2.action === MachineManagerAction.Refresh) {
8674
+ await this.refresh(MachineManagerSnapshotDepth.Basic);
8675
+ return;
8676
+ }
8677
+ if (definition2.action === MachineManagerAction.Doctor) {
8678
+ this.state.view = MachineManagerView.Doctor;
8679
+ await this.refresh(MachineManagerSnapshotDepth.WithDoctor);
8680
+ return;
8681
+ }
8682
+ if (definition2.action === MachineManagerAction.Logs) {
8683
+ this.state.view = MachineManagerView.Logs;
8684
+ await this.refresh(MachineManagerSnapshotDepth.Basic);
8685
+ return;
8686
+ }
8687
+ await this.runCommandAction(definition2.action);
8688
+ }
8689
+ async runCommandAction(action) {
8690
+ this.suspendTerminal();
8691
+ const reader = (0, import_promises15.createInterface)({
8692
+ input: process.stdin,
8693
+ output: process.stdout
8694
+ });
8695
+ try {
8696
+ const argumentsList = await this.buildCommandArguments(reader, action);
8697
+ if (argumentsList.length > 0) {
8698
+ await this.commandRunner.run(argumentsList);
8699
+ }
8700
+ } catch (error) {
8701
+ process.stdout.write(`
8702
+ Error: ${errorMessage4(error)}
8703
+ `);
8704
+ }
8705
+ await reader.question("\nPress Enter to return to the manager...");
8706
+ reader.close();
8707
+ this.resumeTerminal();
8708
+ await this.refresh(MachineManagerSnapshotDepth.Basic);
8709
+ }
8710
+ suspendTerminal() {
8711
+ this.terminalSuspended = true;
8712
+ process.stdin.off("keypress", this.onKeypress);
8713
+ process.stdout.off("resize", this.onResize);
8714
+ process.stdin.setRawMode(false);
8715
+ process.stdout.write(`${cursorShow}${styleReset}${alternateScreenExit}`);
8716
+ }
8717
+ resumeTerminal() {
8718
+ (0, import_node_readline.emitKeypressEvents)(process.stdin);
8719
+ process.stdin.setRawMode(true);
8720
+ process.stdin.resume();
8721
+ process.stdin.on("keypress", this.onKeypress);
8722
+ process.stdout.on("resize", this.onResize);
8723
+ process.stdout.write(`${alternateScreenEnter}${cursorHide}${clearScreen}`);
8724
+ this.terminalSuspended = false;
8725
+ }
8726
+ async buildCommandArguments(reader, action) {
8727
+ if (action === MachineManagerAction.Connect) {
8728
+ return await this.buildConnectArguments(reader);
8729
+ }
8730
+ if (action === MachineManagerAction.Disconnect) {
8731
+ return await this.buildDisconnectArguments(reader);
8732
+ }
8733
+ if (action === MachineManagerAction.ServiceInstall) {
8734
+ const manager = await questionWithDefault(reader, "Service manager (auto/systemd/supervisor/none)", "auto");
8735
+ return ["service", "install", "--service-manager", manager];
8736
+ }
8737
+ if (action === MachineManagerAction.ServiceRestart) {
8738
+ return ["service", "restart"];
8739
+ }
8740
+ if (action === MachineManagerAction.ServiceStop) {
8741
+ return ["service", "stop"];
8742
+ }
8743
+ if (action === MachineManagerAction.ServiceUninstall) {
8744
+ return ["service", "uninstall"];
8745
+ }
8746
+ return [];
8747
+ }
8748
+ async buildConnectArguments(reader) {
8749
+ const code = (await reader.question("Pairing code: ")).trim();
8750
+ if (code.length === 0) {
8751
+ throw new Error("Pairing code is required");
8752
+ }
8753
+ const root = await questionWithDefault(reader, "Working root", process.cwd());
8754
+ const relay = (await reader.question("Relay origin (leave blank for the default): ")).trim();
8755
+ const name = (await reader.question("Machine name (leave blank for the hostname): ")).trim();
8756
+ const serviceManager = await questionWithDefault(reader, "Service manager (auto/systemd/supervisor/none)", "auto");
8757
+ const noOpen = (await reader.question("Skip opening the confirmation page? [y/N]: ")).trim().toLowerCase();
8758
+ const argumentsList = [
8759
+ "connect",
8760
+ "--code",
8761
+ code,
8762
+ "--root",
8763
+ root,
8764
+ "--service-manager",
8765
+ serviceManager
8766
+ ];
8767
+ appendOption(argumentsList, "--relay", relay);
8768
+ appendOption(argumentsList, "--name", name);
8769
+ if (noOpen === "y" || noOpen === "yes") {
8770
+ argumentsList.push("--no-open");
8771
+ }
8772
+ return argumentsList;
8773
+ }
8774
+ async buildDisconnectArguments(reader) {
8775
+ const selected = this.snapshot.connections[this.state.selectedRowIndex];
8776
+ const connectionId = await questionWithDefault(reader, "Connection ID", selected?.connectionId ?? "");
8777
+ if (connectionId.length === 0) {
8778
+ throw new Error("Connection ID is required");
8779
+ }
8780
+ const confirmed = (await reader.question(`Disconnect ${connectionId}? [y/N]: `)).trim().toLowerCase();
8781
+ if (confirmed !== "y" && confirmed !== "yes") {
8782
+ return [];
8783
+ }
8784
+ const localOnly = (await reader.question("Remove local state without contacting Moxt? [y/N]: ")).trim().toLowerCase();
8785
+ const argumentsList = ["disconnect", "--connection", connectionId];
8786
+ if (localOnly === "y" || localOnly === "yes") {
8787
+ argumentsList.push("--local-only");
8788
+ }
8789
+ return argumentsList;
8790
+ }
8791
+ stop() {
8792
+ if (this.stopped) {
8793
+ return;
8794
+ }
8795
+ this.stopped = true;
8796
+ this.resolveRun?.();
8797
+ }
8798
+ };
8017
8799
  }
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")}
8800
+ });
8090
8801
 
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;
8802
+ // ../machine-connector/dist/runtime/device-identity.js
8803
+ async function ensureMachineIdentity(store) {
8804
+ const existingIdentity = (await store.readIdentity()).value;
8805
+ const existingPrivateKey = (await store.readPrivateKey()).value;
8806
+ if (existingIdentity && existingPrivateKey) {
8807
+ return {
8808
+ identity: existingIdentity,
8809
+ privateKeyPem: existingPrivateKey
8810
+ };
8122
8811
  }
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
- `;
8812
+ const keyPair = await generateKeyPairAsync("rsa", {
8813
+ modulusLength: 4096,
8814
+ privateKeyEncoding: {
8815
+ format: "pem",
8816
+ type: "pkcs8"
8817
+ },
8818
+ publicKeyEncoding: {
8819
+ format: "pem",
8820
+ type: "spki"
8821
+ }
8822
+ });
8823
+ const identity = {
8824
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
8825
+ deviceKeyFingerprint: (0, import_node_crypto6.createHash)("sha256").update(keyPair.publicKey, "utf8").digest("hex"),
8826
+ publicKeyPem: keyPair.publicKey
8827
+ };
8828
+ await store.writePrivateKey(keyPair.privateKey);
8829
+ await store.writeIdentity(identity);
8830
+ return {
8831
+ identity,
8832
+ privateKeyPem: keyPair.privateKey
8833
+ };
8171
8834
  }
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
- ]);
8835
+ function decryptPairingCredentials(privateKeyPem, encryptedCredentials) {
8836
+ const serializedEnvelope = Buffer.from(encryptedCredentials, "base64url").toString("utf8");
8837
+ const envelope = JSON.parse(serializedEnvelope);
8838
+ if (envelope.version !== 1 || envelope.algorithm !== "RSA-OAEP-256+A256GCM") {
8839
+ throw new Error("Unsupported Local Machine credentials envelope");
8195
8840
  }
8196
- }
8197
- async function supervisorIsRunning(store, runtime) {
8198
- return await commandSucceeds(runtime, "supervisorctl", [
8199
- "-c",
8200
- supervisorConfigPath(store),
8201
- "pid"
8841
+ const encryptionKey = (0, import_node_crypto6.privateDecrypt)({
8842
+ key: privateKeyPem,
8843
+ oaepHash: "sha256",
8844
+ padding: import_node_crypto6.constants.RSA_PKCS1_OAEP_PADDING
8845
+ }, Buffer.from(envelope.encryptedKey, "base64url"));
8846
+ const decipher = (0, import_node_crypto6.createDecipheriv)("aes-256-gcm", encryptionKey, Buffer.from(envelope.initializationVector, "base64url"));
8847
+ decipher.setAuthTag(Buffer.from(envelope.authenticationTag, "base64url"));
8848
+ const decrypted = Buffer.concat([
8849
+ decipher.update(Buffer.from(envelope.ciphertext, "base64url")),
8850
+ decipher.final()
8202
8851
  ]);
8852
+ return JSON.parse(decrypted.toString("utf8"));
8203
8853
  }
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);
8854
+ var import_node_crypto6, import_node_util5, generateKeyPairAsync;
8855
+ var init_device_identity = __esm({
8856
+ "../machine-connector/dist/runtime/device-identity.js"() {
8857
+ "use strict";
8858
+ init_cjs_shims();
8859
+ import_node_crypto6 = require("crypto");
8860
+ import_node_util5 = require("util");
8861
+ generateKeyPairAsync = (0, import_node_util5.promisify)(import_node_crypto6.generateKeyPair);
8211
8862
  }
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;
8863
+ });
8864
+
8865
+ // ../machine-connector/dist/runtime/pairing.js
8866
+ async function pairMachine(store, options) {
8867
+ await store.initialize();
8868
+ const canonicalRoot = await store.getCanonicalRoot(options.rootPath);
8869
+ const identity = await ensureMachineIdentity(store);
8870
+ const machineName = options.machineName ?? (0, import_node_os6.hostname)();
8871
+ const operatingSystem = getOperatingSystem();
8872
+ const rootHandle = (0, import_node_crypto7.createHash)("sha256").update(identity.identity.deviceKeyFingerprint, "utf8").update("\0").update(canonicalRoot, "utf8").digest("base64url");
8873
+ const client = new PairingRelayClient(options.relayOrigin);
8874
+ const proposal = await client.propose({
8875
+ connectionCode: options.connectionCode,
8876
+ connectorVersion,
8877
+ devicePublicKey: identity.identity.publicKeyPem,
8878
+ machineName,
8879
+ operatingSystem,
8880
+ protocolVersion: machineProtocolVersion,
8881
+ rootDisplayName: (0, import_node_path9.basename)(canonicalRoot),
8882
+ rootHandle
8883
+ });
8884
+ options.onConfirmation?.(proposal.confirmationUrl);
8885
+ if (!options.noOpen) {
8886
+ openBrowser(proposal.confirmationUrl);
8242
8887
  }
8243
- }
8244
- async function runCommandIgnoringFailure(runtime, command, argumentsList) {
8245
- try {
8246
- await runtime.run(command, argumentsList);
8247
- } catch {
8248
- return;
8888
+ while (Date.parse(proposal.expiresAt) > Date.now()) {
8889
+ const status = await client.pollStatus({
8890
+ pairingIntentId: proposal.pairingIntentId,
8891
+ pollingToken: proposal.pollingToken
8892
+ });
8893
+ if (status.status === connectedPairingStatus) {
8894
+ if (!status.encryptedCredentials) {
8895
+ throw new Error("Pairing completed without encrypted Connector credentials");
8896
+ }
8897
+ const credentials = decryptPairingCredentials(identity.privateKeyPem, status.encryptedCredentials);
8898
+ const connection = {
8899
+ accessToken: credentials.accessToken,
8900
+ accessTokenExpiresAt: credentials.accessTokenExpiresAt,
8901
+ connectionId: credentials.connectionId,
8902
+ connectorVersion,
8903
+ heartbeatIntervalSeconds: credentials.heartbeatIntervalSeconds,
8904
+ machineId: credentials.machineId,
8905
+ machineName,
8906
+ operatingSystem,
8907
+ refreshToken: credentials.refreshToken,
8908
+ relayOrigin: options.relayOrigin.replace(/\/+$/, ""),
8909
+ rootDisplayName: (0, import_node_path9.basename)(canonicalRoot),
8910
+ rootHandle,
8911
+ rootPath: canonicalRoot,
8912
+ targetId: credentials.targetId,
8913
+ targetKind: credentials.targetKind,
8914
+ workspaceId: credentials.workspaceId
8915
+ };
8916
+ await store.saveConnection(connection);
8917
+ return {
8918
+ confirmationUrl: proposal.confirmationUrl,
8919
+ connection
8920
+ };
8921
+ }
8922
+ if (status.status === rejectedPairingStatus || status.status === expiredPairingStatus) {
8923
+ throw new Error(status.status === rejectedPairingStatus ? "Local Machine pairing was rejected" : "Local Machine pairing expired");
8924
+ }
8925
+ await delay7(pairingPollMilliseconds);
8249
8926
  }
8927
+ throw new Error("Local Machine pairing expired");
8250
8928
  }
8251
- async function uninstallManagerIgnoringFailure(manager, store, runtime) {
8252
- try {
8253
- await uninstallManager(manager, store, runtime);
8254
- } catch {
8255
- return;
8929
+ function getOperatingSystem() {
8930
+ if ((0, import_node_os6.platform)() === "darwin") {
8931
+ return MachineOperatingSystem.MacOS;
8256
8932
  }
8933
+ if ((0, import_node_os6.platform)() === "linux") {
8934
+ return MachineOperatingSystem.Linux;
8935
+ }
8936
+ return MachineOperatingSystem.Windows;
8257
8937
  }
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");
8938
+ function openBrowser(url) {
8939
+ const command = (0, import_node_os6.platform)() === "darwin" ? "open" : "xdg-open";
8940
+ const child = (0, import_node_child_process5.execFile)(command, [url], () => void 0);
8941
+ child.unref();
8278
8942
  }
8279
- function delay4(milliseconds) {
8943
+ function delay7(milliseconds) {
8280
8944
  return new Promise((resolvePromise) => {
8281
8945
  setTimeout(resolvePromise, milliseconds);
8282
8946
  });
8283
8947
  }
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"() {
8948
+ var import_node_child_process5, import_node_crypto7, import_node_os6, import_node_path9, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
8949
+ var init_pairing = __esm({
8950
+ "../machine-connector/dist/runtime/pairing.js"() {
8287
8951
  "use strict";
8288
8952
  init_cjs_shims();
8289
- import_node_child_process4 = require("child_process");
8290
- import_promises13 = require("fs/promises");
8953
+ import_node_child_process5 = require("child_process");
8954
+ import_node_crypto7 = require("crypto");
8291
8955
  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
- };
8956
+ import_node_path9 = require("path");
8957
+ init_contracts();
8958
+ init_version();
8959
+ init_enums();
8960
+ init_device_identity();
8961
+ init_relay_client();
8962
+ connectedPairingStatus = 3;
8963
+ rejectedPairingStatus = 4;
8964
+ expiredPairingStatus = 5;
8965
+ pairingPollMilliseconds = 2e3;
8321
8966
  }
8322
8967
  });
8323
8968
 
@@ -8356,7 +9001,11 @@ async function runMachineCli(argumentsList, entrypoint) {
8356
9001
  return;
8357
9002
  }
8358
9003
  if (command === "daemon") {
8359
- await daemonCommand(store);
9004
+ await daemonCommand(store, entrypoint);
9005
+ return;
9006
+ }
9007
+ if (command === "daemon-reconcile") {
9008
+ await daemonReconcileCommand(store, commandArguments, entrypoint);
8360
9009
  return;
8361
9010
  }
8362
9011
  if (command === "service") {
@@ -8368,7 +9017,7 @@ async function runMachineCli(argumentsList, entrypoint) {
8368
9017
  async function connectCommand(store, argumentsList, entrypoint) {
8369
9018
  const options = parseOptions(argumentsList);
8370
9019
  const connectionCode = requiredOption(options, "code");
8371
- const rootPath = (0, import_node_path8.resolve)(options.root ?? process.cwd());
9020
+ const rootPath = (0, import_node_path10.resolve)(options.root ?? process.cwd());
8372
9021
  const serviceManagerPreference = requestedServiceManagerPreference(options);
8373
9022
  await validateExplicitServiceManagerPreference(serviceManagerPreference);
8374
9023
  writeLine("Internal Full Host Access: enabled");
@@ -8496,8 +9145,10 @@ async function disconnectCommand(store, argumentsList) {
8496
9145
  }
8497
9146
  writeLine(`Disconnected Local Machine connection ${connectionId}.`);
8498
9147
  }
8499
- async function daemonCommand(store) {
8500
- const daemon = new MachineConnectorDaemon(store);
9148
+ async function daemonCommand(store, entrypoint) {
9149
+ const daemon = new MachineConnectorDaemon(store, {
9150
+ cliVersion: entrypoint.cliVersion
9151
+ });
8501
9152
  process.once("SIGINT", () => {
8502
9153
  void daemon.stop();
8503
9154
  });
@@ -8506,6 +9157,31 @@ async function daemonCommand(store) {
8506
9157
  });
8507
9158
  await daemon.start();
8508
9159
  }
9160
+ async function daemonReconcileCommand(store, argumentsList, entrypoint) {
9161
+ const options = parseOptions(argumentsList);
9162
+ if (!entrypoint.cliVersion) {
9163
+ throw new Error("The CLI version is required to reconcile the managed daemon");
9164
+ }
9165
+ try {
9166
+ const result = await reconcileManagedDaemon({
9167
+ ...entrypoint,
9168
+ cliVersion: entrypoint.cliVersion,
9169
+ onActiveJobs: (count) => {
9170
+ writeErrorLine(`Warning: restarting the managed Connector will interrupt ${count} active ${count === 1 ? "Job" : "Jobs"}.`);
9171
+ }
9172
+ }, store);
9173
+ if (options.report === "true" && result.outcome === DaemonReconcileOutcome.Restarted) {
9174
+ writeErrorLine(`Managed Connector restarted with ${result.manager} and CLI ${entrypoint.cliVersion}.`);
9175
+ }
9176
+ } catch (error) {
9177
+ if (error instanceof DaemonRefreshError) {
9178
+ writeErrorLine(`Warning: CLI update succeeded, but managed Connector refresh failed during ${error.stage}: ${error.message}. Run \`moxt machine service restart\`.`);
9179
+ process.exitCode = 1;
9180
+ return;
9181
+ }
9182
+ throw error;
9183
+ }
9184
+ }
8509
9185
  async function serviceCommand(store, argumentsList, entrypoint) {
8510
9186
  const action = argumentsList[0] ?? "install";
8511
9187
  const options = parseOptions(argumentsList.slice(1));
@@ -8570,6 +9246,10 @@ function requiredOption(options, name) {
8570
9246
  }
8571
9247
  return value;
8572
9248
  }
9249
+ function writeErrorLine(value) {
9250
+ process.stderr.write(`${value}
9251
+ `);
9252
+ }
8573
9253
  function requestedServiceManagerPreference(options) {
8574
9254
  const requestedValue = options["service-manager"] ?? ServiceManagerPreference.Auto;
8575
9255
  if (process.env.MOXT_MACHINE_SKIP_SERVICE === "1" && requestedValue === ServiceManagerPreference.Auto) {
@@ -8597,14 +9277,14 @@ async function waitForDaemonOnline(store) {
8597
9277
  return;
8598
9278
  }
8599
9279
  } catch {
8600
- await delay5(500);
9280
+ await delay8(500);
8601
9281
  }
8602
9282
  }
8603
9283
  throw new Error("The service was installed but the Connector did not become online within 30 seconds");
8604
9284
  }
8605
9285
  async function readOptionalFile2(path4) {
8606
9286
  try {
8607
- return await (0, import_promises14.readFile)(path4, "utf8");
9287
+ return await (0, import_promises16.readFile)(path4, "utf8");
8608
9288
  } catch {
8609
9289
  return "";
8610
9290
  }
@@ -8627,19 +9307,20 @@ function writeLine(message) {
8627
9307
  process.stdout.write(`${message}
8628
9308
  `);
8629
9309
  }
8630
- function delay5(milliseconds) {
9310
+ function delay8(milliseconds) {
8631
9311
  return new Promise((resolvePromise) => {
8632
9312
  setTimeout(resolvePromise, milliseconds);
8633
9313
  });
8634
9314
  }
8635
- var import_promises14, import_node_path8, defaultRelayOrigin;
9315
+ var import_promises16, import_node_path10, defaultRelayOrigin;
8636
9316
  var init_cli = __esm({
8637
9317
  "../machine-connector/dist/cli.js"() {
8638
9318
  "use strict";
8639
9319
  init_cjs_shims();
8640
- import_promises14 = require("fs/promises");
8641
- import_node_path8 = require("path");
9320
+ import_promises16 = require("fs/promises");
9321
+ import_node_path10 = require("path");
8642
9322
  init_daemon();
9323
+ init_daemon_reconcile();
8643
9324
  init_doctor();
8644
9325
  init_local_ipc();
8645
9326
  init_machine_manager();
@@ -8654,6 +9335,8 @@ var init_cli = __esm({
8654
9335
  // ../machine-connector/dist/index.js
8655
9336
  var dist_exports = {};
8656
9337
  __export(dist_exports, {
9338
+ DaemonReconcileOutcome: () => DaemonReconcileOutcome,
9339
+ DaemonRefreshError: () => DaemonRefreshError,
8657
9340
  DoctorCheckStatus: () => DoctorCheckStatus,
8658
9341
  LocalIpcServer: () => LocalIpcServer,
8659
9342
  MachineClaudePermissionMode: () => MachineClaudePermissionMode,
@@ -8702,8 +9385,12 @@ __export(dist_exports, {
8702
9385
  isTerminalJobStatus: () => isTerminalJobStatus,
8703
9386
  machineManagerActions: () => machineManagerActions,
8704
9387
  machineProtocolVersion: () => machineProtocolVersion,
9388
+ managedServiceOwnsProcess: () => managedServiceOwnsProcess,
8705
9389
  pairMachine: () => pairMachine,
8706
9390
  parseServiceManagerPreference: () => parseServiceManagerPreference,
9391
+ reconcileManagedDaemon: () => reconcileManagedDaemon,
9392
+ recordedServiceManager: () => recordedServiceManager,
9393
+ refreshManagedUserService: () => refreshManagedUserService,
8707
9394
  renderMachineManager: () => renderMachineManager,
8708
9395
  requestRuntimeStatus: () => requestRuntimeStatus,
8709
9396
  resolveWorkingDirectory: () => resolveWorkingDirectory,
@@ -8723,6 +9410,7 @@ var init_dist = __esm({
8723
9410
  init_v1();
8724
9411
  init_cli();
8725
9412
  init_daemon();
9413
+ init_daemon_reconcile();
8726
9414
  init_claude_executor();
8727
9415
  init_doctor();
8728
9416
  init_local_ipc();
@@ -8911,7 +9599,7 @@ function getApiKeyOrUndefined() {
8911
9599
 
8912
9600
  // src/utils/http.ts
8913
9601
  function getUserAgent() {
8914
- return `moxt-cli/${"0.8.0-beta.5"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
9602
+ return `moxt-cli/${"0.8.1"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
8915
9603
  }
8916
9604
  async function sendRequest(method, path4, init) {
8917
9605
  const response = await fetch(`${getApiBaseUrl()}${path4}`, {
@@ -9087,8 +9775,8 @@ function readCommentContentFile(path4) {
9087
9775
  if (!fs.existsSync(path4)) {
9088
9776
  throw new FileCommentOptionsError(`Error: comment content file not found: ${path4}`);
9089
9777
  }
9090
- const stat2 = fs.statSync(path4);
9091
- if (!stat2.isFile()) {
9778
+ const stat3 = fs.statSync(path4);
9779
+ if (!stat3.isFile()) {
9092
9780
  throw new FileCommentOptionsError(`Error: comment content path is not a file: ${path4}`);
9093
9781
  }
9094
9782
  const buffer2 = fs.readFileSync(path4);
@@ -9762,8 +10450,8 @@ var FileTokenizer = class _FileTokenizer extends AbstractTokenizer {
9762
10450
  */
9763
10451
  static async fromFile(sourceFilePath) {
9764
10452
  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 } });
10453
+ const stat3 = await fileHandle.stat();
10454
+ return new _FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat3.size } });
9767
10455
  }
9768
10456
  constructor(fileHandle, options) {
9769
10457
  super(options);
@@ -15309,10 +15997,10 @@ function resolveAll(constructs2, events, context) {
15309
15997
  const called = [];
15310
15998
  let index2 = -1;
15311
15999
  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);
16000
+ const resolve8 = constructs2[index2].resolveAll;
16001
+ if (resolve8 && !called.includes(resolve8)) {
16002
+ events = resolve8(events, context);
16003
+ called.push(resolve8);
15316
16004
  }
15317
16005
  }
15318
16006
  return events;
@@ -19025,7 +19713,7 @@ function compiler(options) {
19025
19713
  transforms: [],
19026
19714
  canContainEols: ["emphasis", "fragment", "heading", "paragraph", "strong"],
19027
19715
  enter: {
19028
- autolink: opener(link),
19716
+ autolink: opener(link2),
19029
19717
  autolinkProtocol: onenterdata,
19030
19718
  autolinkEmail: onenterdata,
19031
19719
  atxHeading: opener(heading),
@@ -19053,7 +19741,7 @@ function compiler(options) {
19053
19741
  htmlTextData: onenterdata,
19054
19742
  image: opener(image),
19055
19743
  label: buffer2,
19056
- link: opener(link),
19744
+ link: opener(link2),
19057
19745
  listItem: opener(listItem),
19058
19746
  listItemValue: onenterlistitemvalue,
19059
19747
  listOrdered: opener(list2, onenterlistordered),
@@ -19605,7 +20293,7 @@ function compiler(options) {
19605
20293
  alt: null
19606
20294
  };
19607
20295
  }
19608
- function link() {
20296
+ function link2() {
19609
20297
  return {
19610
20298
  type: "link",
19611
20299
  title: null,
@@ -20552,7 +21240,7 @@ var serviceManagerOption = new Option(
20552
21240
  "--service-manager <manager>",
20553
21241
  "Background service manager: auto, systemd, supervisor, or none"
20554
21242
  ).choices(["auto", "systemd", "supervisor", "none"]).default("auto");
20555
- function registerMachineCommand(program3) {
21243
+ function registerMachineCommand(program3, cliVersion) {
20556
21244
  const machine = program3.command("machine").description("Connect and operate a Local Machine");
20557
21245
  machine.command("connect").description(
20558
21246
  "Pair this machine and install the background Connector service"
@@ -20625,15 +21313,22 @@ function registerMachineCommand(program3) {
20625
21313
  machine.command("daemon", { hidden: true }).description("Run the Connector daemon").action(async () => {
20626
21314
  await runConnectorCli(["daemon"]);
20627
21315
  });
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
21316
+ machine.command("daemon-reconcile", { hidden: true }).option("--report").action(async (options) => {
21317
+ await runConnectorCli([
21318
+ "daemon-reconcile",
21319
+ ...options.report ? ["--report"] : []
21320
+ ]);
20636
21321
  });
21322
+ async function runConnectorCli(argumentsList) {
21323
+ const { runMachineCli: runMachineCli2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
21324
+ await runMachineCli2(argumentsList, {
21325
+ cliVersion,
21326
+ commandArguments: ["machine", "daemon"],
21327
+ entrypointPath: process.argv[1],
21328
+ environment: {},
21329
+ nodePath: process.execPath
21330
+ });
21331
+ }
20637
21332
  }
20638
21333
  function appendOption2(argumentsList, flag, value) {
20639
21334
  if (value) {
@@ -20891,7 +21586,7 @@ init_cjs_shims();
20891
21586
 
20892
21587
  // src/update/install.ts
20893
21588
  init_cjs_shims();
20894
- var import_node_child_process5 = require("child_process");
21589
+ var import_node_child_process6 = require("child_process");
20895
21590
  var import_node_fs2 = require("fs");
20896
21591
  var path3 = __toESM(require("path"), 1);
20897
21592
 
@@ -21007,7 +21702,7 @@ function runUpgrade(channel, targetVersion) {
21007
21702
  }
21008
21703
  process.stderr.write(`Updating via \`${display}\`...
21009
21704
  `);
21010
- const installation = (0, import_node_child_process5.spawnSync)(plan.command, plan.args, {
21705
+ const installation = (0, import_node_child_process6.spawnSync)(plan.command, plan.args, {
21011
21706
  encoding: "utf8",
21012
21707
  env: process.env,
21013
21708
  maxBuffer: 10 * 1024 * 1024,
@@ -21022,7 +21717,7 @@ function runUpgrade(channel, targetVersion) {
21022
21717
  success: false
21023
21718
  };
21024
21719
  }
21025
- const verification = (0, import_node_child_process5.spawnSync)("moxt", ["--version"], {
21720
+ const verification = (0, import_node_child_process6.spawnSync)("moxt", ["--version"], {
21026
21721
  encoding: "utf8",
21027
21722
  env: process.env,
21028
21723
  maxBuffer: 1024 * 1024,
@@ -21036,7 +21731,35 @@ function runUpgrade(channel, targetVersion) {
21036
21731
  success: false
21037
21732
  };
21038
21733
  }
21039
- return { installedVersion, success: true };
21734
+ const daemonRefresh = (0, import_node_child_process6.spawnSync)(
21735
+ "moxt",
21736
+ ["machine", "daemon-reconcile", "--report"],
21737
+ {
21738
+ encoding: "utf8",
21739
+ env: process.env,
21740
+ maxBuffer: 10 * 1024 * 1024,
21741
+ shell: false
21742
+ }
21743
+ );
21744
+ forwardToStderr(daemonRefresh.stdout);
21745
+ forwardToStderr(daemonRefresh.stderr);
21746
+ if (daemonRefresh.error || daemonRefresh.status !== 0) {
21747
+ if (!daemonRefresh.stderr) {
21748
+ process.stderr.write(
21749
+ "Warning: CLI update succeeded, but managed Connector refresh failed during invocation. Run `moxt machine service restart`.\n"
21750
+ );
21751
+ }
21752
+ return {
21753
+ daemonRefreshSucceeded: false,
21754
+ installedVersion,
21755
+ success: true
21756
+ };
21757
+ }
21758
+ return {
21759
+ daemonRefreshSucceeded: true,
21760
+ installedVersion,
21761
+ success: true
21762
+ };
21040
21763
  }
21041
21764
  function detectInstallMethod() {
21042
21765
  const userAgentMethod = packageManagerFromUserAgent(process.env.npm_config_user_agent);
@@ -21312,7 +22035,7 @@ function registerWorkspaceCommand(program3) {
21312
22035
  // src/commands/workflow.ts
21313
22036
  init_cjs_shims();
21314
22037
  var fs5 = __toESM(require("fs"), 1);
21315
- var import_node_util5 = require("util");
22038
+ var import_node_util6 = require("util");
21316
22039
  var MAX_DESC_LENGTH = 5e3;
21317
22040
  var MAX_COMMENT_CONTENT_LENGTH = 5e3;
21318
22041
  var MAX_COMMENT_CONTENT_BYTES = MAX_COMMENT_CONTENT_LENGTH * 4;
@@ -21407,8 +22130,8 @@ function readDescFile(path4) {
21407
22130
  if (!fs5.existsSync(path4)) {
21408
22131
  throw new WorkflowOptionsError(`Error: desc file not found: ${path4}`);
21409
22132
  }
21410
- const stat2 = fs5.statSync(path4);
21411
- if (!stat2.isFile()) {
22133
+ const stat3 = fs5.statSync(path4);
22134
+ if (!stat3.isFile()) {
21412
22135
  throw new WorkflowOptionsError(`Error: desc file is not a file: ${path4}`);
21413
22136
  }
21414
22137
  const buffer2 = fs5.readFileSync(path4);
@@ -21425,11 +22148,11 @@ function readCommentContentFile2(path4) {
21425
22148
  if (!fs5.existsSync(path4)) {
21426
22149
  throw new WorkflowOptionsError(`Error: comment content file not found: ${path4}`);
21427
22150
  }
21428
- const stat2 = fs5.statSync(path4);
21429
- if (!stat2.isFile()) {
22151
+ const stat3 = fs5.statSync(path4);
22152
+ if (!stat3.isFile()) {
21430
22153
  throw new WorkflowOptionsError(`Error: comment content path is not a file: ${path4}`);
21431
22154
  }
21432
- if (stat2.size > MAX_COMMENT_CONTENT_BYTES) {
22155
+ if (stat3.size > MAX_COMMENT_CONTENT_BYTES) {
21433
22156
  throw new WorkflowOptionsError(
21434
22157
  `Error: comment content file must be at most ${MAX_COMMENT_CONTENT_LENGTH} characters.`
21435
22158
  );
@@ -21443,7 +22166,7 @@ function readCommentContentFile2(path4) {
21443
22166
  }
21444
22167
  let content3;
21445
22168
  try {
21446
- content3 = new import_node_util5.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer2);
22169
+ content3 = new import_node_util6.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer2);
21447
22170
  } catch {
21448
22171
  throw new WorkflowOptionsError("Error: comment content file must contain valid UTF-8 text.");
21449
22172
  }
@@ -21478,6 +22201,28 @@ function parseAssigneeBody(options, allowClear) {
21478
22201
  if (teammateId !== void 0) return { assigneeAiTeammateId: teammateId };
21479
22202
  return {};
21480
22203
  }
22204
+ function parseTaskListFilterQuery(options) {
22205
+ const filterOwnerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
22206
+ const filterAssigneeHumanId = parseOptionalPositiveInteger(options.assigneeHumanId, "--assignee-human-id");
22207
+ const filterAssigneeAssistantId = parseOptionalPositiveInteger(
22208
+ options.assigneeAssistantId,
22209
+ "--assignee-assistant-id"
22210
+ );
22211
+ const filterAssigneeTeammateId = parseOptionalPositiveInteger(
22212
+ options.assigneeTeammateId,
22213
+ "--assignee-teammate-id"
22214
+ );
22215
+ const assigneeFilterCount = (filterAssigneeHumanId !== void 0 ? 1 : 0) + (filterAssigneeAssistantId !== void 0 ? 1 : 0) + (filterAssigneeTeammateId !== void 0 ? 1 : 0);
22216
+ if (assigneeFilterCount > 1) {
22217
+ throw new WorkflowOptionsError("Error: assignee filter options are mutually exclusive.");
22218
+ }
22219
+ return {
22220
+ filterOwnerHumanId,
22221
+ filterAssigneeHumanId,
22222
+ filterAssigneeAssistantId,
22223
+ filterAssigneeTeammateId
22224
+ };
22225
+ }
21481
22226
  function parsePreferredAssigneeBody(options) {
21482
22227
  const hasClear = options.clearPreferredAssignee === true;
21483
22228
  const humanId = parseOptionalPositiveInteger(options.preferredHumanId, "--preferred-human-id");
@@ -21951,17 +22696,20 @@ function registerTransitionCommands(workflow) {
21951
22696
  function registerTaskCommands(workflow) {
21952
22697
  const task = workflow.command("task").description("Workflow task operations");
21953
22698
  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")
22699
+ task.command("list").description("List workflow tasks").option("--workflow-file-id <workflowFileId>", "Filter by workflow file ID").option("--scope <scope>", "Task scope", "all").option("-l, --limit <limit>", "Maximum number of tasks to return", "50").option("--cursor <cursor>", "Pagination cursor").option("--owner-human-id <humanId>", "Filter by task owner human ID").option("--assignee-human-id <humanId>", "Filter by human assignee ID").option("--assignee-assistant-id <assistantId>", "Filter by AI assistant assignee ID").option("--assignee-teammate-id <teammateId>", "Filter by AI teammate assignee ID")
21955
22700
  ).action(
21956
22701
  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
- }));
22702
+ const query = runOrExit4(
22703
+ () => buildQuery({
22704
+ scope: parseTaskScope(options.scope),
22705
+ limit: parseSearchLimit(options.limit, 50, 100),
22706
+ cursor: options.cursor,
22707
+ workflowFileId: options.workflowFileId,
22708
+ ...parseTaskListFilterQuery(options)
22709
+ })
22710
+ );
21963
22711
  startSpinner("Fetching workflow tasks...");
21964
- const response = await httpGet(`/workspaces/${options.workspace}/workflow-tasks-v2${query}`);
22712
+ const response = await httpGet(`/workspaces/${options.workspace}/workflow-tasks-v3${query}`);
21965
22713
  if (!response.ok) {
21966
22714
  stopSpinner(false, "Failed");
21967
22715
  failResponse(response);
@@ -22326,7 +23074,7 @@ function createProgram(version) {
22326
23074
  registerWorkspaceCommand(program3);
22327
23075
  registerFileCommand(program3);
22328
23076
  registerMemoryCommand(program3);
22329
- registerMachineCommand(program3);
23077
+ registerMachineCommand(program3, version);
22330
23078
  registerWorkflowCommand(program3);
22331
23079
  registerMiniappCommand(program3);
22332
23080
  registerTelemetryCommand(program3);
@@ -22342,7 +23090,7 @@ var FLUSH_TIMEOUT_MS = 3e3;
22342
23090
  var MAX_BATCH_SIZE = 100;
22343
23091
  function commonLabels() {
22344
23092
  return {
22345
- cli_version: "0.8.0-beta.5",
23093
+ cli_version: "0.8.1",
22346
23094
  node_version: process.versions.node,
22347
23095
  os: (0, import_node_os7.platform)(),
22348
23096
  arch: (0, import_node_os7.arch)(),
@@ -22388,7 +23136,7 @@ async function flush() {
22388
23136
  }
22389
23137
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
22390
23138
  const payload = {
22391
- release_id: "0.8.0-beta.5",
23139
+ release_id: "0.8.1",
22392
23140
  client_type: "cli",
22393
23141
  metric_data_list: batch.map((m) => ({
22394
23142
  profile: "cli",
@@ -22589,7 +23337,7 @@ function registryWorker() {
22589
23337
 
22590
23338
  // src/update/prompt.ts
22591
23339
  init_cjs_shims();
22592
- var import_promises15 = require("readline/promises");
23340
+ var import_promises17 = require("readline/promises");
22593
23341
  async function promptForUpdate(input, output, currentVersion, latestVersion, timeoutMs) {
22594
23342
  output.write(`
22595
23343
  A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion}
@@ -22602,7 +23350,7 @@ A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion
22602
23350
  const controller = new AbortController();
22603
23351
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
22604
23352
  timeout.unref();
22605
- const readline = (0, import_promises15.createInterface)({ input, output, terminal: true });
23353
+ const readline = (0, import_promises17.createInterface)({ input, output, terminal: true });
22606
23354
  try {
22607
23355
  const answer = await readline.question("", { signal: controller.signal });
22608
23356
  if (answer.trim() === "1") return "update";
@@ -22703,9 +23451,69 @@ function commandPath2(command) {
22703
23451
  return names;
22704
23452
  }
22705
23453
 
23454
+ // src/update/daemon-reconcile-hook.ts
23455
+ init_cjs_shims();
23456
+ var import_node_path11 = require("path");
23457
+ function installDaemonReconcileHook(program3, cliVersion) {
23458
+ program3.hook("preAction", async (_thisCommand, actionCommand) => {
23459
+ if (!isEligible2(actionCommand)) return;
23460
+ const entrypointPath = process.argv[1];
23461
+ if (!entrypointPath) return;
23462
+ const {
23463
+ DaemonRefreshError: DaemonRefreshError2,
23464
+ reconcileManagedDaemon: reconcileManagedDaemon2
23465
+ } = await Promise.resolve().then(() => (init_dist(), dist_exports));
23466
+ try {
23467
+ await reconcileManagedDaemon2({
23468
+ cliVersion,
23469
+ commandArguments: ["machine", "daemon"],
23470
+ entrypointPath: (0, import_node_path11.resolve)(entrypointPath),
23471
+ environment: {},
23472
+ nodePath: (0, import_node_path11.resolve)(process.execPath),
23473
+ onActiveJobs: (count) => {
23474
+ process.stderr.write(
23475
+ `Warning: restarting the managed Connector will interrupt ${count} active ${count === 1 ? "Job" : "Jobs"}.
23476
+ `
23477
+ );
23478
+ }
23479
+ });
23480
+ } catch (error) {
23481
+ if (error instanceof DaemonRefreshError2) {
23482
+ process.stderr.write(
23483
+ `Warning: managed Connector refresh failed during ${error.stage}: ${error.message}. Run \`moxt machine service restart\`.
23484
+ `
23485
+ );
23486
+ return;
23487
+ }
23488
+ process.stderr.write(
23489
+ `Warning: managed Connector refresh could not be prepared: ${error instanceof Error ? error.message : String(error)}. Run \`moxt machine service restart\`.
23490
+ `
23491
+ );
23492
+ }
23493
+ });
23494
+ }
23495
+ function isEligible2(actionCommand) {
23496
+ const path4 = commandPath3(actionCommand);
23497
+ if (path4[0] === "upgrade" || path4[0] === "telemetry") return false;
23498
+ if (path4[0] === "machine" && path4[1] === "daemon") return false;
23499
+ if (path4[0] === "machine" && path4[1] === "daemon-reconcile") return false;
23500
+ if (path4[0] === "machine" && path4[1] === "service") return false;
23501
+ return true;
23502
+ }
23503
+ function commandPath3(command) {
23504
+ const names = [];
23505
+ let current2 = command;
23506
+ while (current2?.parent) {
23507
+ names.unshift(current2.name());
23508
+ current2 = current2.parent;
23509
+ }
23510
+ return names;
23511
+ }
23512
+
22706
23513
  // src/index.ts
22707
- var program2 = createProgram("0.8.0-beta.5");
22708
- installUpdateHook(program2, "0.8.0-beta.5");
23514
+ var program2 = createProgram("0.8.1");
23515
+ installDaemonReconcileHook(program2, "0.8.1");
23516
+ installUpdateHook(program2, "0.8.1");
22709
23517
  instrumentProgram(program2);
22710
23518
  installExitHandler();
22711
23519
  program2.parseAsync(process.argv).then(async () => {