@moxt-ai/cli 0.8.0-beta.0 → 0.8.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -551,8 +551,8 @@ var require_graceful_fs = __commonJS({
551
551
  fs10.createReadStream = createReadStream;
552
552
  fs10.createWriteStream = createWriteStream2;
553
553
  var fs$readFile = fs10.readFile;
554
- fs10.readFile = readFile4;
555
- function readFile4(path10, options, cb) {
554
+ fs10.readFile = readFile5;
555
+ function readFile5(path10, options, cb) {
556
556
  if (typeof options === "function")
557
557
  cb = options, options = null;
558
558
  return go$readFile(path10, options, cb);
@@ -2550,8 +2550,8 @@ var require_graceful_fs2 = __commonJS({
2550
2550
  fs10.createReadStream = createReadStream;
2551
2551
  fs10.createWriteStream = createWriteStream2;
2552
2552
  var fs$readFile = fs10.readFile;
2553
- fs10.readFile = readFile4;
2554
- function readFile4(path10, options, cb) {
2553
+ fs10.readFile = readFile5;
2554
+ function readFile5(path10, options, cb) {
2555
2555
  if (typeof options === "function")
2556
2556
  cb = options, options = null;
2557
2557
  return go$readFile(path10, options, cb);
@@ -5884,14 +5884,14 @@ var require_string_width = __commonJS({
5884
5884
  "node_modules/.pnpm/string-width@4.2.3/node_modules/string-width/index.js"(exports2, module2) {
5885
5885
  "use strict";
5886
5886
  init_cjs_shims();
5887
- var stripAnsi2 = require_strip_ansi();
5887
+ var stripAnsi3 = require_strip_ansi();
5888
5888
  var isFullwidthCodePoint = require_is_fullwidth_code_point();
5889
5889
  var emojiRegex = require_emoji_regex();
5890
5890
  var stringWidth2 = (string) => {
5891
5891
  if (typeof string !== "string" || string.length === 0) {
5892
5892
  return 0;
5893
5893
  }
5894
- string = stripAnsi2(string);
5894
+ string = stripAnsi3(string);
5895
5895
  if (string.length === 0) {
5896
5896
  return 0;
5897
5897
  }
@@ -9421,7 +9421,7 @@ var init_contracts = __esm({
9421
9421
  });
9422
9422
 
9423
9423
  // ../machine-connector/dist/protocol/v1/enums.js
9424
- var MachineOperatingSystem, MachineConnectionTargetKind, MachineConnectionStatus, MachinePairingStatus, MachinePairingDecision, MachineJobKind, MachineJobStatus, MachineJobWakeReason, MachineJobEventKind, MachineJobOutputStream, MachineControlCommandKind, MachineCodexPermissionMode, MachineProtocolErrorCode;
9424
+ var MachineOperatingSystem, MachineConnectionTargetKind, MachineConnectionStatus, MachinePairingStatus, MachinePairingDecision, MachineJobKind, MachineJobStatus, MachineJobWakeReason, MachineJobEventKind, MachineJobOutputStream, MachineControlCommandKind, MachineCodexPermissionMode, MachineClaudePermissionMode, MachineProtocolErrorCode;
9425
9425
  var init_enums = __esm({
9426
9426
  "../machine-connector/dist/protocol/v1/enums.js"() {
9427
9427
  "use strict";
@@ -9452,6 +9452,8 @@ var init_enums = __esm({
9452
9452
  MachinePairingDecision2["Reject"] = "reject";
9453
9453
  })(MachinePairingDecision || (MachinePairingDecision = {}));
9454
9454
  (function(MachineJobKind2) {
9455
+ MachineJobKind2["ClaudeReply"] = "claude_reply";
9456
+ MachineJobKind2["ClaudeStart"] = "claude_start";
9455
9457
  MachineJobKind2["CodexReply"] = "codex_reply";
9456
9458
  MachineJobKind2["CodexStart"] = "codex_start";
9457
9459
  MachineJobKind2["Command"] = "command";
@@ -9493,6 +9495,9 @@ var init_enums = __esm({
9493
9495
  (function(MachineCodexPermissionMode2) {
9494
9496
  MachineCodexPermissionMode2["FullAccess"] = "full_access";
9495
9497
  })(MachineCodexPermissionMode || (MachineCodexPermissionMode = {}));
9498
+ (function(MachineClaudePermissionMode2) {
9499
+ MachineClaudePermissionMode2["FullAccess"] = "full_access";
9500
+ })(MachineClaudePermissionMode || (MachineClaudePermissionMode = {}));
9496
9501
  (function(MachineProtocolErrorCode2) {
9497
9502
  MachineProtocolErrorCode2["BadProtocolVersion"] = "bad_protocol_version";
9498
9503
  MachineProtocolErrorCode2["BindingMismatch"] = "binding_mismatch";
@@ -9672,6 +9677,12 @@ async function executeCommand(rootPath, spec, callbacks) {
9672
9677
  return await executeProcess(spec.executable, spec.arguments, workingDirectory, spec.environment, spec.stdin, spec.timeoutSeconds, callbacks);
9673
9678
  }
9674
9679
  async function executeProcess(executable, argumentsList, workingDirectory, environment, stdin, timeoutSeconds, callbacks) {
9680
+ if (callbacks.canSpawn && !callbacks.canSpawn()) {
9681
+ return {
9682
+ exitCode: -1,
9683
+ status: MachineJobStatus.Cancelled
9684
+ };
9685
+ }
9675
9686
  const child = (0, import_node_child_process2.spawn)(executable, argumentsList, {
9676
9687
  cwd: workingDirectory,
9677
9688
  detached: (0, import_node_os4.platform)() !== "win32",
@@ -9731,9 +9742,31 @@ async function executeProcess(executable, argumentsList, workingDirectory, envir
9731
9742
  void handle.cancel();
9732
9743
  }, timeoutSeconds * 1e3);
9733
9744
  timeout2.unref();
9734
- const processExit = await processExitPromise;
9745
+ const completion = processExitPromise.then(async (processExit2) => {
9746
+ await outputWrites;
9747
+ return {
9748
+ kind: "process_exit",
9749
+ processExit: processExit2
9750
+ };
9751
+ });
9752
+ const cancellation = handle.waitForCancellation().then(() => ({
9753
+ kind: "cancellation_deadline"
9754
+ }));
9755
+ const outcome = await Promise.race([completion, cancellation]);
9735
9756
  clearTimeout(timeout2);
9736
- await outputWrites;
9757
+ if (outcome.kind === "cancellation_deadline") {
9758
+ void outputWrites.catch(() => void 0);
9759
+ return timedOut ? {
9760
+ exitCode: -1,
9761
+ failureCode: "timeout",
9762
+ failureMessage: `Process exceeded ${timeoutSeconds} seconds`,
9763
+ status: MachineJobStatus.Failed
9764
+ } : {
9765
+ exitCode: -1,
9766
+ status: MachineJobStatus.Cancelled
9767
+ };
9768
+ }
9769
+ const { processExit } = outcome;
9737
9770
  if (processExit.spawnError) {
9738
9771
  return {
9739
9772
  exitCode: -1,
@@ -9786,7 +9819,10 @@ async function resolveCanonicalWorkingDirectory(rootPath, relativeWorkingDirecto
9786
9819
  }
9787
9820
  async function terminateProcessTree(pid) {
9788
9821
  if ((0, import_node_os4.platform)() === "win32") {
9789
- const process11 = (0, import_node_child_process2.spawn)("taskkill", ["/pid", String(pid), "/t", "/f"], { stdio: "ignore", windowsHide: true });
9822
+ const process11 = (0, import_node_child_process2.spawn)("taskkill", ["/pid", String(pid), "/t", "/f"], {
9823
+ stdio: "ignore",
9824
+ windowsHide: true
9825
+ });
9790
9826
  await new Promise((resolvePromise) => {
9791
9827
  process11.once("close", () => resolvePromise());
9792
9828
  process11.once("error", () => resolvePromise());
@@ -9801,7 +9837,18 @@ async function terminateProcessTree(pid) {
9801
9837
  }
9802
9838
  return;
9803
9839
  }
9804
- await delay2(3e3);
9840
+ const gracefulDeadline = Date.now() + 3e3;
9841
+ while (Date.now() < gracefulDeadline) {
9842
+ try {
9843
+ process.kill(-pid, 0);
9844
+ } catch (error) {
9845
+ if (isMissingProcess(error)) {
9846
+ return;
9847
+ }
9848
+ throw error;
9849
+ }
9850
+ await delay2(Math.min(100, gracefulDeadline - Date.now()));
9851
+ }
9805
9852
  try {
9806
9853
  process.kill(-pid, "SIGKILL");
9807
9854
  } catch (error) {
@@ -9821,7 +9868,7 @@ function delay2(milliseconds) {
9821
9868
  setTimeout(resolvePromise, milliseconds);
9822
9869
  });
9823
9870
  }
9824
- var import_node_child_process2, import_promises, import_node_os4, import_node_path9, RunningProcessHandle;
9871
+ var import_node_child_process2, import_promises, import_node_os4, import_node_path9, cancellationDeadlineMilliseconds, RunningProcessHandle;
9825
9872
  var init_process_executor = __esm({
9826
9873
  "../machine-connector/dist/runtime/process-executor.js"() {
9827
9874
  "use strict";
@@ -9832,21 +9879,141 @@ var init_process_executor = __esm({
9832
9879
  import_node_path9 = require("path");
9833
9880
  init_enums();
9834
9881
  init_invariants();
9882
+ cancellationDeadlineMilliseconds = 4e3;
9835
9883
  RunningProcessHandle = class {
9836
9884
  pid;
9837
9885
  cancelled = false;
9886
+ cancellation;
9887
+ cancellationStarted;
9888
+ resolveCancellationStarted;
9838
9889
  constructor(pid) {
9839
9890
  this.pid = pid;
9891
+ this.cancellationStarted = new Promise((resolvePromise) => {
9892
+ this.resolveCancellationStarted = resolvePromise;
9893
+ });
9840
9894
  }
9841
9895
  wasCancelled() {
9842
9896
  return this.cancelled;
9843
9897
  }
9844
9898
  async cancel() {
9899
+ if (this.cancellation) {
9900
+ await this.cancellation;
9901
+ return;
9902
+ }
9845
9903
  this.cancelled = true;
9846
- await terminateProcessTree(this.pid);
9904
+ this.cancellation = Promise.race([
9905
+ terminateProcessTree(this.pid),
9906
+ delay2(cancellationDeadlineMilliseconds)
9907
+ ]);
9908
+ this.resolveCancellationStarted();
9909
+ await this.cancellation;
9910
+ }
9911
+ async waitForCancellation() {
9912
+ await this.cancellationStarted;
9913
+ await this.cancellation;
9914
+ }
9915
+ };
9916
+ }
9917
+ });
9918
+
9919
+ // ../machine-connector/dist/runtime/claude-executor.js
9920
+ async function executeClaudeStart(workingDirectory, spec, callbacks) {
9921
+ const sessionId = (0, import_node_crypto.randomUUID)();
9922
+ return await executeClaude(workingDirectory, [
9923
+ "--print",
9924
+ "--output-format",
9925
+ "stream-json",
9926
+ "--verbose",
9927
+ "--dangerously-skip-permissions",
9928
+ "--session-id",
9929
+ sessionId
9930
+ ], spec.prompt, sessionId, callbacks);
9931
+ }
9932
+ async function executeClaudeReply(workingDirectory, spec, callbacks) {
9933
+ return await executeClaude(workingDirectory, [
9934
+ "--print",
9935
+ "--output-format",
9936
+ "stream-json",
9937
+ "--verbose",
9938
+ "--dangerously-skip-permissions",
9939
+ "--resume",
9940
+ spec.threadId
9941
+ ], spec.prompt, spec.threadId, callbacks);
9942
+ }
9943
+ async function executeClaude(workingDirectory, argumentsList, prompt, expectedSessionId, callbacks) {
9944
+ const metadata = {
9945
+ threadId: expectedSessionId
9946
+ };
9947
+ let bufferedStdout = "";
9948
+ const processCallbacks = {
9949
+ canSpawn: callbacks.canSpawn,
9950
+ onOutput: async (output) => {
9951
+ await callbacks.onOutput(output.stream, output.text);
9952
+ if (output.stream !== MachineJobOutputStream.Stdout) {
9953
+ return;
9954
+ }
9955
+ bufferedStdout += output.text;
9956
+ const lines = bufferedStdout.split("\n");
9957
+ bufferedStdout = lines.pop() ?? "";
9958
+ for (const line of lines) {
9959
+ await processClaudeLine(line, metadata, callbacks);
9960
+ }
9961
+ },
9962
+ onSpawn: callbacks.onSpawn
9963
+ };
9964
+ const result = await executeProcess(process.env.MOXT_CLAUDE_PATH ?? "claude", argumentsList, workingDirectory, {}, prompt, 43200, processCallbacks);
9965
+ if (bufferedStdout.trim().length > 0) {
9966
+ await processClaudeLine(bufferedStdout, metadata, callbacks);
9967
+ }
9968
+ return {
9969
+ ...result,
9970
+ finalMessage: metadata.finalMessage,
9971
+ threadId: metadata.threadId
9972
+ };
9973
+ }
9974
+ async function processClaudeLine(line, metadata, callbacks) {
9975
+ const event = parseClaudeEvent(line).value;
9976
+ if (event === void 0) {
9977
+ return;
9978
+ }
9979
+ if (isRecord(event)) {
9980
+ if (typeof event.session_id === "string") {
9981
+ metadata.threadId = event.session_id;
9982
+ }
9983
+ if (event.type === "result" && typeof event.result === "string") {
9984
+ metadata.finalMessage = event.result;
9985
+ }
9986
+ }
9987
+ await callbacks.onEvent(event);
9988
+ }
9989
+ function parseClaudeEvent(line) {
9990
+ const trimmed = line.trim();
9991
+ if (trimmed.length === 0) {
9992
+ return {};
9993
+ }
9994
+ try {
9995
+ return { value: JSON.parse(trimmed) };
9996
+ } catch {
9997
+ return {
9998
+ value: {
9999
+ message: trimmed,
10000
+ type: "unparsed_output"
9847
10001
  }
9848
10002
  };
9849
10003
  }
10004
+ }
10005
+ function isRecord(value) {
10006
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10007
+ }
10008
+ var import_node_crypto;
10009
+ var init_claude_executor = __esm({
10010
+ "../machine-connector/dist/runtime/claude-executor.js"() {
10011
+ "use strict";
10012
+ init_cjs_shims();
10013
+ import_node_crypto = require("crypto");
10014
+ init_enums();
10015
+ init_process_executor();
10016
+ }
9850
10017
  });
9851
10018
 
9852
10019
  // ../machine-connector/dist/runtime/codex-executor.js
@@ -9880,6 +10047,7 @@ async function executeCodex(workingDirectory, outputPath, argumentsList, prompt,
9880
10047
  const executionMetadata = {};
9881
10048
  let bufferedStdout = "";
9882
10049
  const processCallbacks = {
10050
+ canSpawn: callbacks.canSpawn,
9883
10051
  onOutput: async (output) => {
9884
10052
  await callbacks.onOutput(output.stream, output.text);
9885
10053
  if (output.stream !== MachineJobOutputStream.Stdout) {
@@ -9922,7 +10090,7 @@ async function executeCodex(workingDirectory, outputPath, argumentsList, prompt,
9922
10090
  };
9923
10091
  }
9924
10092
  function createOutputPath(runtimeDirectory) {
9925
- return (0, import_node_path10.join)(runtimeDirectory, `codex-last-message-${(0, import_node_crypto.randomUUID)()}.txt`);
10093
+ return (0, import_node_path10.join)(runtimeDirectory, `codex-last-message-${(0, import_node_crypto2.randomUUID)()}.txt`);
9926
10094
  }
9927
10095
  function parseCodexEvent(line) {
9928
10096
  const trimmed = line.trim();
@@ -9941,7 +10109,7 @@ function parseCodexEvent(line) {
9941
10109
  }
9942
10110
  }
9943
10111
  function extractThreadId(event) {
9944
- if (!isRecord(event)) {
10112
+ if (!isRecord2(event)) {
9945
10113
  return {};
9946
10114
  }
9947
10115
  const directThreadId = event.thread_id;
@@ -9949,7 +10117,7 @@ function extractThreadId(event) {
9949
10117
  return { value: directThreadId };
9950
10118
  }
9951
10119
  const thread = event.thread;
9952
- if (isRecord(thread) && typeof thread.id === "string") {
10120
+ if (isRecord2(thread) && typeof thread.id === "string") {
9953
10121
  return { value: thread.id };
9954
10122
  }
9955
10123
  return {};
@@ -9964,7 +10132,7 @@ async function readOptionalOutput(path10) {
9964
10132
  throw error;
9965
10133
  }
9966
10134
  }
9967
- function isRecord(value) {
10135
+ function isRecord2(value) {
9968
10136
  return typeof value === "object" && value !== null && !Array.isArray(value);
9969
10137
  }
9970
10138
  function isNodeErrorCode(error, expectedCode) {
@@ -9973,14 +10141,14 @@ function isNodeErrorCode(error, expectedCode) {
9973
10141
  }
9974
10142
  return error.code === expectedCode;
9975
10143
  }
9976
- var import_promises2, import_node_path10, import_node_crypto;
10144
+ var import_promises2, import_node_path10, import_node_crypto2;
9977
10145
  var init_codex_executor = __esm({
9978
10146
  "../machine-connector/dist/runtime/codex-executor.js"() {
9979
10147
  "use strict";
9980
10148
  init_cjs_shims();
9981
10149
  import_promises2 = require("fs/promises");
9982
10150
  import_node_path10 = require("path");
9983
- import_node_crypto = require("crypto");
10151
+ import_node_crypto2 = require("crypto");
9984
10152
  init_enums();
9985
10153
  init_process_executor();
9986
10154
  }
@@ -10002,12 +10170,12 @@ var init_runtime_types = __esm({
10002
10170
  });
10003
10171
 
10004
10172
  // ../machine-connector/dist/runtime/durable-job.js
10005
- var import_node_crypto2, DurableMachineJob;
10173
+ var import_node_crypto3, DurableMachineJob;
10006
10174
  var init_durable_job = __esm({
10007
10175
  "../machine-connector/dist/runtime/durable-job.js"() {
10008
10176
  "use strict";
10009
10177
  init_cjs_shims();
10010
- import_node_crypto2 = require("crypto");
10178
+ import_node_crypto3 = require("crypto");
10011
10179
  init_enums();
10012
10180
  init_runtime_types();
10013
10181
  DurableMachineJob = class _DurableMachineJob {
@@ -10111,7 +10279,7 @@ var init_durable_job = __esm({
10111
10279
  addEvent(kind, payload, options) {
10112
10280
  const event = {
10113
10281
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
10114
- eventId: (0, import_node_crypto2.randomUUID)(),
10282
+ eventId: (0, import_node_crypto3.randomUUID)(),
10115
10283
  generation: this.job.claim.generation,
10116
10284
  jobId: this.job.claim.jobId,
10117
10285
  kind,
@@ -10137,6 +10305,55 @@ var init_durable_job = __esm({
10137
10305
  }
10138
10306
  });
10139
10307
 
10308
+ // ../machine-connector/dist/runtime/execution-cancellation.js
10309
+ var ExecutionCancellationReason, ExecutionCancellation;
10310
+ var init_execution_cancellation = __esm({
10311
+ "../machine-connector/dist/runtime/execution-cancellation.js"() {
10312
+ "use strict";
10313
+ init_cjs_shims();
10314
+ (function(ExecutionCancellationReason2) {
10315
+ ExecutionCancellationReason2["LeaseLost"] = "lease_lost";
10316
+ ExecutionCancellationReason2["Requested"] = "requested";
10317
+ ExecutionCancellationReason2["Stopping"] = "stopping";
10318
+ })(ExecutionCancellationReason || (ExecutionCancellationReason = {}));
10319
+ ExecutionCancellation = class {
10320
+ handle;
10321
+ reason;
10322
+ requested;
10323
+ resolveRequested;
10324
+ constructor() {
10325
+ this.requested = new Promise((resolvePromise) => {
10326
+ this.resolveRequested = resolvePromise;
10327
+ });
10328
+ }
10329
+ canSpawn() {
10330
+ return this.reason === void 0;
10331
+ }
10332
+ currentReason() {
10333
+ return this.reason;
10334
+ }
10335
+ register(handle) {
10336
+ this.handle = handle;
10337
+ if (this.reason !== void 0) {
10338
+ void handle.cancel();
10339
+ }
10340
+ }
10341
+ async request(reason) {
10342
+ if (this.reason === void 0) {
10343
+ this.reason = reason;
10344
+ this.resolveRequested(reason);
10345
+ }
10346
+ if (this.handle) {
10347
+ await this.handle.cancel();
10348
+ }
10349
+ }
10350
+ async wait() {
10351
+ return await this.requested;
10352
+ }
10353
+ };
10354
+ }
10355
+ });
10356
+
10140
10357
  // ../machine-connector/dist/runtime/local-ipc.js
10141
10358
  async function requestRuntimeStatus(store) {
10142
10359
  return await new Promise((resolvePromise, rejectPromise) => {
@@ -10230,11 +10447,21 @@ var init_local_ipc = __esm({
10230
10447
  }
10231
10448
  });
10232
10449
 
10450
+ // ../machine-connector/dist/runtime/version.js
10451
+ var connectorVersion;
10452
+ var init_version = __esm({
10453
+ "../machine-connector/dist/runtime/version.js"() {
10454
+ "use strict";
10455
+ init_cjs_shims();
10456
+ connectorVersion = "0.2.0";
10457
+ }
10458
+ });
10459
+
10233
10460
  // ../machine-connector/dist/runtime/relay-client.js
10234
10461
  async function postJson(url, body, accessToken) {
10235
10462
  const headers = {
10236
10463
  "Content-Type": "application/json",
10237
- "User-Agent": "moxt-machine-connector/0.1.0"
10464
+ "User-Agent": `moxt-machine-connector/${connectorVersion}`
10238
10465
  };
10239
10466
  if (accessToken) {
10240
10467
  headers.Authorization = `Bearer ${accessToken}`;
@@ -10282,6 +10509,7 @@ var init_relay_client = __esm({
10282
10509
  "../machine-connector/dist/runtime/relay-client.js"() {
10283
10510
  "use strict";
10284
10511
  init_cjs_shims();
10512
+ init_version();
10285
10513
  requestTimeoutMilliseconds = 65e3;
10286
10514
  RelayHttpError = class extends Error {
10287
10515
  responseBody;
@@ -10599,47 +10827,85 @@ var init_store = __esm({
10599
10827
  });
10600
10828
 
10601
10829
  // ../machine-connector/dist/runtime/daemon.js
10830
+ function isPermanentRelayFailure(error) {
10831
+ return error instanceof RelayHttpError && (error.status === 400 || error.status === 401 || error.status === 403 || error.status === 404 || error.status === 409 || error.status === 410);
10832
+ }
10833
+ async function withDeadline(operation, deadline) {
10834
+ if (deadline === void 0) {
10835
+ return await operation;
10836
+ }
10837
+ const remaining = deadline - Date.now();
10838
+ if (remaining <= 0) {
10839
+ throw new Error("Operation exceeded its foreground deadline");
10840
+ }
10841
+ return await Promise.race([
10842
+ operation,
10843
+ delay3(remaining).then(() => {
10844
+ throw new Error("Operation exceeded its foreground deadline");
10845
+ })
10846
+ ]);
10847
+ }
10602
10848
  function delay3(milliseconds) {
10603
10849
  return new Promise((resolvePromise) => {
10604
10850
  setTimeout(resolvePromise, milliseconds);
10605
10851
  });
10606
10852
  }
10607
- var import_node_os7, import_node_crypto3, connectorVersion, claimTimeoutSeconds, controlTimeoutSeconds, leaseSeconds, eventUploadIntervalMilliseconds, networkRetryMilliseconds, codexOutputLimitBytes, MachineConnectorDaemon;
10853
+ var import_node_os7, import_node_crypto4, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, MachineConnectorDaemon;
10608
10854
  var init_daemon = __esm({
10609
10855
  "../machine-connector/dist/runtime/daemon.js"() {
10610
10856
  "use strict";
10611
10857
  init_cjs_shims();
10612
10858
  import_node_os7 = require("os");
10613
- import_node_crypto3 = require("crypto");
10859
+ import_node_crypto4 = require("crypto");
10614
10860
  init_enums();
10615
10861
  init_contracts();
10862
+ init_claude_executor();
10616
10863
  init_codex_executor();
10617
10864
  init_durable_job();
10865
+ init_execution_cancellation();
10618
10866
  init_local_ipc();
10619
10867
  init_process_executor();
10620
10868
  init_relay_client();
10621
10869
  init_runtime_logger();
10622
10870
  init_runtime_types();
10623
10871
  init_store();
10624
- connectorVersion = "0.1.0";
10872
+ init_version();
10625
10873
  claimTimeoutSeconds = 30;
10626
10874
  controlTimeoutSeconds = 30;
10627
- leaseSeconds = 90;
10628
10875
  eventUploadIntervalMilliseconds = 500;
10629
- networkRetryMilliseconds = 2e3;
10630
- codexOutputLimitBytes = 2e6;
10876
+ agentOutputLimitBytes = 2e6;
10877
+ defaultLeaseSeconds = 90;
10878
+ defaultNetworkRetryMilliseconds = 2e3;
10879
+ defaultLeaseSafetyMarginMilliseconds = 1e4;
10880
+ defaultTerminalForegroundBudgetMilliseconds = 5e3;
10881
+ maximumTerminalRetryMilliseconds = 6e4;
10882
+ (function(TerminalUploadOutcome2) {
10883
+ TerminalUploadOutcome2["PermanentFailure"] = "permanent_failure";
10884
+ TerminalUploadOutcome2["RetryableFailure"] = "retryable_failure";
10885
+ TerminalUploadOutcome2["Uploaded"] = "uploaded";
10886
+ })(TerminalUploadOutcome || (TerminalUploadOutcome = {}));
10631
10887
  MachineConnectorDaemon = class {
10632
10888
  store;
10633
10889
  activeJobs = /* @__PURE__ */ new Map();
10634
- connectorInstanceId = (0, import_node_crypto3.randomUUID)();
10890
+ connectorInstanceId = (0, import_node_crypto4.randomUUID)();
10635
10891
  logger;
10636
10892
  startedAt = (/* @__PURE__ */ new Date()).toISOString();
10637
10893
  connections = [];
10638
10894
  ipcServer;
10639
10895
  stopping = false;
10640
- constructor(store = new MachineRuntimeStore()) {
10896
+ leaseSafetyMarginMilliseconds;
10897
+ leaseSeconds;
10898
+ networkRetryMilliseconds;
10899
+ random;
10900
+ terminalForegroundBudgetMilliseconds;
10901
+ constructor(store = new MachineRuntimeStore(), options = {}) {
10641
10902
  this.store = store;
10642
10903
  this.logger = new RuntimeLogger(store);
10904
+ this.leaseSafetyMarginMilliseconds = options.leaseSafetyMarginMilliseconds ?? defaultLeaseSafetyMarginMilliseconds;
10905
+ this.leaseSeconds = options.leaseSeconds ?? defaultLeaseSeconds;
10906
+ this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds;
10907
+ this.random = options.random ?? Math.random;
10908
+ this.terminalForegroundBudgetMilliseconds = options.terminalForegroundBudgetMilliseconds ?? defaultTerminalForegroundBudgetMilliseconds;
10643
10909
  }
10644
10910
  async start() {
10645
10911
  if (process.getuid?.() === 0) {
@@ -10665,9 +10931,7 @@ var init_daemon = __esm({
10665
10931
  async stop() {
10666
10932
  this.stopping = true;
10667
10933
  await Promise.all([...this.activeJobs.values()].map(async (activeJob) => {
10668
- if (activeJob.handle) {
10669
- await activeJob.handle.cancel();
10670
- }
10934
+ await activeJob.cancellation.request(ExecutionCancellationReason.Stopping);
10671
10935
  }));
10672
10936
  await this.ipcServer?.close();
10673
10937
  await this.logger.info("Moxt Machine Connector stopped");
@@ -10675,13 +10939,12 @@ var init_daemon = __esm({
10675
10939
  getStatus() {
10676
10940
  return {
10677
10941
  activeJobs: [...this.activeJobs.values()].map((activeJob) => {
10678
- const job = activeJob.durableJob.snapshot();
10679
10942
  return {
10680
10943
  connectionId: activeJob.connection.connectionId,
10681
- jobId: job.claim.jobId,
10682
- kind: job.claim.kind,
10683
- phase: job.phase,
10684
- relativeWorkingDirectory: job.claim.relativeWorkingDirectory
10944
+ jobId: activeJob.claim.jobId,
10945
+ kind: activeJob.claim.kind,
10946
+ phase: activeJob.durableJob?.snapshot().phase ?? PersistedMachineJobPhase.Claimed,
10947
+ relativeWorkingDirectory: activeJob.claim.relativeWorkingDirectory
10685
10948
  };
10686
10949
  }),
10687
10950
  connections: this.connections.map((connection) => ({
@@ -10728,16 +10991,17 @@ var init_daemon = __esm({
10728
10991
  try {
10729
10992
  const response = await relay.claim({
10730
10993
  connectorInstanceId: this.connectorInstanceId,
10731
- leaseSeconds,
10994
+ leaseSeconds: this.leaseSeconds,
10732
10995
  protocolVersion: machineProtocolVersion,
10733
10996
  timeoutSeconds: claimTimeoutSeconds
10734
10997
  });
10735
10998
  if (response.job) {
10736
- void this.executeClaim(connection, relay, response.job);
10999
+ const activeJob = this.reserveClaim(connection, relay, response.job);
11000
+ await this.executeClaim(activeJob);
10737
11001
  }
10738
11002
  } catch (error) {
10739
11003
  await this.logger.error(`Job claim failed for connection ${connection.connectionId}`, error);
10740
- await this.waitUntilStop(networkRetryMilliseconds);
11004
+ await this.waitUntilStop(this.networkRetryMilliseconds);
10741
11005
  }
10742
11006
  }
10743
11007
  }
@@ -10750,40 +11014,65 @@ var init_daemon = __esm({
10750
11014
  protocolVersion: machineProtocolVersion,
10751
11015
  timeoutSeconds: controlTimeoutSeconds
10752
11016
  });
10753
- cursor = response.nextCursor;
10754
11017
  for (const command of response.commands) {
10755
11018
  await this.handleControl(relay, command);
11019
+ cursor = command.cursor;
11020
+ }
11021
+ if (response.commands.length === 0) {
11022
+ cursor = response.nextCursor;
10756
11023
  }
10757
11024
  } catch (error) {
10758
11025
  await this.logger.error(`Control poll failed for connection ${connection.connectionId}`, error);
10759
- await this.waitUntilStop(networkRetryMilliseconds);
11026
+ await this.waitUntilStop(this.networkRetryMilliseconds);
10760
11027
  }
10761
11028
  }
10762
11029
  }
10763
- async executeClaim(connection, relay, claim) {
10764
- const durableJob = await DurableMachineJob.create(this.store, connection.connectionId, claim);
11030
+ reserveClaim(connection, relay, claim) {
10765
11031
  const activeJob = {
10766
- cancelRequested: false,
11032
+ cancellation: new ExecutionCancellation(),
11033
+ claim,
10767
11034
  connection,
10768
- durableJob,
10769
11035
  eventUploadQueue: Promise.resolve(),
11036
+ leaseExpiresAt: Date.parse(claim.leaseExpiresAt),
10770
11037
  relay
10771
11038
  };
10772
11039
  this.activeJobs.set(claim.jobId, activeJob);
11040
+ return activeJob;
11041
+ }
11042
+ async executeClaim(activeJob) {
11043
+ const { claim } = activeJob;
10773
11044
  try {
11045
+ const durableJob = await DurableMachineJob.create(this.store, activeJob.connection.connectionId, claim);
11046
+ activeJob.durableJob = durableJob;
11047
+ if (activeJob.cancellation.currentReason() !== void 0) {
11048
+ await durableJob.markTerminal(this.cancellationResult(activeJob));
11049
+ await this.finishTerminalUpload(activeJob);
11050
+ return;
11051
+ }
10774
11052
  await durableJob.markRunning();
10775
- await this.tryReportRunning(activeJob);
11053
+ const ownsLease = await this.confirmRunning(activeJob);
11054
+ if (!ownsLease) {
11055
+ await durableJob.markTerminal(this.cancellationResult(activeJob));
11056
+ await this.finishTerminalUpload(activeJob);
11057
+ return;
11058
+ }
10776
11059
  const uploadLoop = this.runEventUploadLoop(activeJob);
10777
11060
  const leaseLoop = this.runLeaseLoop(activeJob);
10778
- const executionResult = await this.runExecutor(activeJob);
11061
+ const execution = this.runExecutor(activeJob);
11062
+ const executionResult = await Promise.race([
11063
+ execution,
11064
+ activeJob.cancellation.wait().then(() => this.cancellationResult(activeJob))
11065
+ ]);
11066
+ void execution.catch(() => void 0);
10779
11067
  await durableJob.markTerminal(executionResult);
10780
- const uploaded = await this.uploadTerminal(activeJob);
11068
+ await this.finishTerminalUpload(activeJob);
10781
11069
  await Promise.all([uploadLoop, leaseLoop]);
10782
- if (uploaded) {
10783
- await durableJob.markUploaded();
10784
- }
10785
11070
  } catch (error) {
10786
11071
  await this.logger.error(`Local Machine Job ${claim.jobId} failed in Connector`, error);
11072
+ const durableJob = activeJob.durableJob;
11073
+ if (!durableJob) {
11074
+ return;
11075
+ }
10787
11076
  const message = error instanceof Error ? error.message : "Unknown Connector error";
10788
11077
  await durableJob.markTerminal({
10789
11078
  exitCode: -1,
@@ -10791,30 +11080,28 @@ var init_daemon = __esm({
10791
11080
  failureMessage: message,
10792
11081
  status: MachineJobStatus.Failed
10793
11082
  });
10794
- const uploaded = await this.uploadTerminal(activeJob);
10795
- if (uploaded) {
10796
- await durableJob.markUploaded();
10797
- }
11083
+ await this.finishTerminalUpload(activeJob);
10798
11084
  } finally {
10799
11085
  this.activeJobs.delete(claim.jobId);
10800
11086
  }
10801
11087
  }
10802
11088
  async runExecutor(activeJob) {
10803
- const claim = activeJob.durableJob.snapshot().claim;
10804
- const registerProcess = (handle) => {
10805
- activeJob.handle = handle;
10806
- if (activeJob.cancelRequested) {
10807
- void handle.cancel();
10808
- }
10809
- };
11089
+ const durableJob = this.requireDurableJob(activeJob);
11090
+ const { claim } = activeJob;
11091
+ const registerProcess = activeJob.cancellation.register.bind(activeJob.cancellation);
11092
+ const canSpawn = activeJob.cancellation.canSpawn.bind(activeJob.cancellation);
10810
11093
  if (claim.kind === MachineJobKind.Command) {
10811
11094
  const request2 = claim.requestPayload;
10812
11095
  const result = await executeCommand(activeJob.connection.rootPath, {
10813
11096
  ...request2,
10814
11097
  relativeWorkingDirectory: claim.relativeWorkingDirectory
10815
11098
  }, {
11099
+ canSpawn,
10816
11100
  onOutput: async (output) => {
10817
- await activeJob.durableJob.appendOutput(output.stream, output.text, request2.outputLimitBytes);
11101
+ if (activeJob.cancellation.currentReason() !== void 0) {
11102
+ return;
11103
+ }
11104
+ await durableJob.appendOutput(output.stream, output.text, request2.outputLimitBytes);
10818
11105
  },
10819
11106
  onSpawn: registerProcess
10820
11107
  });
@@ -10824,12 +11111,22 @@ var init_daemon = __esm({
10824
11111
  };
10825
11112
  }
10826
11113
  const workingDirectory = await resolveCanonicalWorkingDirectory(activeJob.connection.rootPath, claim.relativeWorkingDirectory);
11114
+ if (!canSpawn()) {
11115
+ return this.cancellationResult(activeJob);
11116
+ }
10827
11117
  const callbacks = {
11118
+ canSpawn,
10828
11119
  onEvent: async (event) => {
10829
- await activeJob.durableJob.appendProgress(event);
11120
+ if (activeJob.cancellation.currentReason() !== void 0) {
11121
+ return;
11122
+ }
11123
+ await durableJob.appendProgress(event);
10830
11124
  },
10831
11125
  onOutput: async (stream, text) => {
10832
- await activeJob.durableJob.appendOutput(stream, text, codexOutputLimitBytes);
11126
+ if (activeJob.cancellation.currentReason() !== void 0) {
11127
+ return;
11128
+ }
11129
+ await durableJob.appendOutput(stream, text, agentOutputLimitBytes);
10833
11130
  },
10834
11131
  onSpawn: registerProcess
10835
11132
  };
@@ -10862,82 +11159,158 @@ var init_daemon = __esm({
10862
11159
  threadId: result.threadId ?? request2.threadId
10863
11160
  };
10864
11161
  }
11162
+ if (claim.kind === MachineJobKind.ClaudeStart) {
11163
+ const request2 = claim.requestPayload;
11164
+ const result = await executeClaudeStart(workingDirectory, {
11165
+ ...request2,
11166
+ relativeWorkingDirectory: claim.relativeWorkingDirectory
11167
+ }, callbacks);
11168
+ return {
11169
+ ...result,
11170
+ result: {
11171
+ finalMessage: result.finalMessage,
11172
+ threadId: result.threadId
11173
+ }
11174
+ };
11175
+ }
11176
+ if (claim.kind === MachineJobKind.ClaudeReply) {
11177
+ const request2 = claim.requestPayload;
11178
+ const result = await executeClaudeReply(workingDirectory, {
11179
+ ...request2,
11180
+ relativeWorkingDirectory: claim.relativeWorkingDirectory
11181
+ }, callbacks);
11182
+ return {
11183
+ ...result,
11184
+ result: {
11185
+ finalMessage: result.finalMessage,
11186
+ threadId: result.threadId ?? request2.threadId
11187
+ },
11188
+ threadId: result.threadId ?? request2.threadId
11189
+ };
11190
+ }
10865
11191
  throw new Error(`Unsupported Local Machine Job kind: ${claim.kind}`);
10866
11192
  }
10867
11193
  async runEventUploadLoop(activeJob) {
11194
+ const durableJob = this.requireDurableJob(activeJob);
10868
11195
  while (!this.stopping) {
10869
- const phase = activeJob.durableJob.snapshot().phase;
10870
11196
  await this.tryFlushEvents(activeJob);
10871
- if (phase === PersistedMachineJobPhase.TerminalPendingUpload) {
11197
+ if (durableJob.snapshot().phase !== PersistedMachineJobPhase.Running) {
10872
11198
  return;
10873
11199
  }
10874
11200
  await this.waitUntilStop(eventUploadIntervalMilliseconds);
10875
11201
  }
10876
11202
  }
10877
11203
  async runLeaseLoop(activeJob) {
11204
+ let retryMilliseconds = this.networkRetryMilliseconds;
10878
11205
  while (!this.stopping) {
10879
- const shouldRenew = await this.waitForLeaseRenewal(activeJob);
10880
- if (!shouldRenew) {
11206
+ const durableJob = this.requireDurableJob(activeJob);
11207
+ if (durableJob.snapshot().phase !== PersistedMachineJobPhase.Running) {
10881
11208
  return;
10882
11209
  }
10883
- const job = activeJob.durableJob.snapshot();
11210
+ const remaining = activeJob.leaseExpiresAt - Date.now();
11211
+ if (remaining <= this.leaseSafetyMarginMilliseconds) {
11212
+ await activeJob.cancellation.request(ExecutionCancellationReason.LeaseLost);
11213
+ return;
11214
+ }
11215
+ const renewalAt = activeJob.leaseExpiresAt - this.leaseSeconds * 1e3 / 2;
11216
+ if (Date.now() < renewalAt) {
11217
+ await this.waitUntilStop(Math.min(250, renewalAt - Date.now()));
11218
+ continue;
11219
+ }
10884
11220
  try {
10885
- await activeJob.relay.renewLease({
10886
- generation: job.claim.generation,
10887
- jobId: job.claim.jobId,
10888
- leaseSeconds,
10889
- leaseToken: job.claim.leaseToken,
11221
+ const response = await activeJob.relay.renewLease({
11222
+ generation: activeJob.claim.generation,
11223
+ jobId: activeJob.claim.jobId,
11224
+ leaseSeconds: this.leaseSeconds,
11225
+ leaseToken: activeJob.claim.leaseToken,
10890
11226
  protocolVersion: machineProtocolVersion,
10891
- runToken: job.claim.runToken
11227
+ runToken: activeJob.claim.runToken
10892
11228
  });
11229
+ const leaseExpiresAt = Date.parse(response.leaseExpiresAt);
11230
+ if (!Number.isFinite(leaseExpiresAt) || leaseExpiresAt <= Date.now()) {
11231
+ throw new Error("Relay returned an invalid lease deadline");
11232
+ }
11233
+ activeJob.leaseExpiresAt = leaseExpiresAt;
11234
+ retryMilliseconds = this.networkRetryMilliseconds;
10893
11235
  } catch (error) {
10894
- await this.logger.error(`Lease renewal failed for Job ${job.claim.jobId}`, error);
11236
+ await this.logger.error(`Lease renewal failed for Job ${activeJob.claim.jobId}`, error);
11237
+ if (isPermanentRelayFailure(error)) {
11238
+ await activeJob.cancellation.request(ExecutionCancellationReason.LeaseLost);
11239
+ return;
11240
+ }
11241
+ const retryBudget = activeJob.leaseExpiresAt - Date.now() - this.leaseSafetyMarginMilliseconds;
11242
+ if (retryBudget <= 0) {
11243
+ await activeJob.cancellation.request(ExecutionCancellationReason.LeaseLost);
11244
+ return;
11245
+ }
11246
+ await this.waitUntilStop(Math.min(retryMilliseconds, retryBudget));
11247
+ retryMilliseconds = Math.min(retryMilliseconds * 2, maximumTerminalRetryMilliseconds);
10895
11248
  }
10896
11249
  }
10897
11250
  }
10898
- async uploadTerminal(activeJob) {
11251
+ async tryUploadTerminal(activeJob, budgetMilliseconds) {
11252
+ if (this.stopping) {
11253
+ return TerminalUploadOutcome.RetryableFailure;
11254
+ }
11255
+ const deadline = budgetMilliseconds === void 0 ? void 0 : Date.now() + budgetMilliseconds;
11256
+ try {
11257
+ await this.flushAllEvents(activeJob, deadline);
11258
+ const job = this.requireDurableJob(activeJob).snapshot();
11259
+ if (!job.finalStatus) {
11260
+ throw new Error(`Job ${job.claim.jobId} has no terminal status`);
11261
+ }
11262
+ await withDeadline(activeJob.relay.updateJob({
11263
+ exitCode: job.finalExitCode,
11264
+ failureCode: job.finalFailureCode,
11265
+ failureMessage: job.finalFailureMessage,
11266
+ generation: job.claim.generation,
11267
+ jobId: job.claim.jobId,
11268
+ leaseToken: job.claim.leaseToken,
11269
+ nextStatus: job.finalStatus,
11270
+ outputTruncated: job.outputTruncated,
11271
+ protocolVersion: machineProtocolVersion,
11272
+ result: job.finalResult,
11273
+ runToken: job.claim.runToken,
11274
+ threadId: job.finalThreadId
11275
+ }), deadline);
11276
+ return TerminalUploadOutcome.Uploaded;
11277
+ } catch (error) {
11278
+ await this.logger.error(`Terminal upload failed for Job ${activeJob.claim.jobId}`, error);
11279
+ return isPermanentRelayFailure(error) ? TerminalUploadOutcome.PermanentFailure : TerminalUploadOutcome.RetryableFailure;
11280
+ }
11281
+ }
11282
+ async retryTerminalUpload(activeJob) {
11283
+ let retryMilliseconds = this.networkRetryMilliseconds;
10899
11284
  while (!this.stopping) {
10900
- try {
10901
- await this.flushAllEvents(activeJob);
10902
- if (!activeJob.cancelRequested) {
10903
- await this.reportRunning(activeJob);
10904
- }
10905
- const job = activeJob.durableJob.snapshot();
10906
- if (!job.finalStatus) {
10907
- throw new Error(`Job ${job.claim.jobId} has no terminal status`);
10908
- }
10909
- await activeJob.relay.updateJob({
10910
- exitCode: job.finalExitCode,
10911
- failureCode: job.finalFailureCode,
10912
- failureMessage: job.finalFailureMessage,
10913
- generation: job.claim.generation,
10914
- jobId: job.claim.jobId,
10915
- leaseToken: job.claim.leaseToken,
10916
- nextStatus: job.finalStatus,
10917
- outputTruncated: job.outputTruncated,
10918
- protocolVersion: machineProtocolVersion,
10919
- result: job.finalResult,
10920
- runToken: job.claim.runToken,
10921
- threadId: job.finalThreadId
10922
- });
10923
- return true;
10924
- } catch (error) {
10925
- await this.logger.error(`Terminal upload failed for Job ${activeJob.durableJob.snapshot().claim.jobId}`, error);
10926
- await this.waitUntilStop(networkRetryMilliseconds);
11285
+ const jitteredDelay = retryMilliseconds * (0.75 + this.random() * 0.5);
11286
+ await this.waitUntilStop(jitteredDelay);
11287
+ const outcome = await this.tryUploadTerminal(activeJob);
11288
+ if (outcome === TerminalUploadOutcome.Uploaded || outcome === TerminalUploadOutcome.PermanentFailure) {
11289
+ await this.requireDurableJob(activeJob).markUploaded();
11290
+ return;
10927
11291
  }
11292
+ retryMilliseconds = Math.min(retryMilliseconds * 2, maximumTerminalRetryMilliseconds);
10928
11293
  }
10929
- return false;
10930
11294
  }
10931
- async flushAllEvents(activeJob) {
10932
- while (activeJob.durableJob.pendingEvents().length > 0) {
10933
- await this.flushEvents(activeJob);
11295
+ async finishTerminalUpload(activeJob) {
11296
+ const outcome = await this.tryUploadTerminal(activeJob, this.terminalForegroundBudgetMilliseconds);
11297
+ if (outcome === TerminalUploadOutcome.Uploaded || outcome === TerminalUploadOutcome.PermanentFailure) {
11298
+ await this.requireDurableJob(activeJob).markUploaded();
11299
+ return;
11300
+ }
11301
+ void this.retryTerminalUpload(activeJob);
11302
+ }
11303
+ async flushAllEvents(activeJob, deadline) {
11304
+ const durableJob = this.requireDurableJob(activeJob);
11305
+ while (durableJob.pendingEvents().length > 0) {
11306
+ await withDeadline(this.flushEvents(activeJob), deadline);
10934
11307
  }
10935
11308
  }
10936
11309
  async tryFlushEvents(activeJob) {
10937
11310
  try {
10938
11311
  await this.flushEvents(activeJob);
10939
11312
  } catch (error) {
10940
- await this.logger.error(`Event upload failed for Job ${activeJob.durableJob.snapshot().claim.jobId}`, error);
11313
+ await this.logger.error(`Event upload failed for Job ${activeJob.claim.jobId}`, error);
10941
11314
  }
10942
11315
  }
10943
11316
  async flushEvents(activeJob) {
@@ -10948,23 +11321,23 @@ var init_daemon = __esm({
10948
11321
  await nextUpload;
10949
11322
  }
10950
11323
  async flushPendingEvents(activeJob) {
10951
- const events = activeJob.durableJob.pendingEvents();
11324
+ const durableJob = this.requireDurableJob(activeJob);
11325
+ const events = durableJob.pendingEvents();
10952
11326
  if (events.length === 0) {
10953
11327
  return;
10954
11328
  }
10955
- const job = activeJob.durableJob.snapshot();
11329
+ const job = durableJob.snapshot();
11330
+ const previousAcknowledgement = job.acknowledgedSequence;
10956
11331
  const response = await activeJob.relay.appendEvents(job.claim.jobId, job.claim.generation, job.claim.leaseToken, job.claim.runToken, machineProtocolVersion, events);
10957
- await activeJob.durableJob.acknowledge(response.acknowledgedSequence);
10958
- }
10959
- async tryReportRunning(activeJob) {
10960
- try {
10961
- await this.reportRunning(activeJob);
10962
- } catch (error) {
10963
- await this.logger.error(`Running state upload failed for Job ${activeJob.durableJob.snapshot().claim.jobId}`, error);
11332
+ const acknowledgedSequence = response.acknowledgedSequence;
11333
+ const maximumSentSequence = events.at(-1)?.sequence;
11334
+ if (!Number.isInteger(acknowledgedSequence) || maximumSentSequence === void 0 || acknowledgedSequence <= previousAcknowledgement || acknowledgedSequence > maximumSentSequence) {
11335
+ throw new Error(`Relay did not advance event acknowledgement for Job ${job.claim.jobId}`);
10964
11336
  }
11337
+ await durableJob.acknowledge(acknowledgedSequence);
10965
11338
  }
10966
11339
  async reportRunning(activeJob) {
10967
- const job = activeJob.durableJob.snapshot();
11340
+ const job = this.requireDurableJob(activeJob).snapshot();
10968
11341
  await activeJob.relay.updateJob({
10969
11342
  generation: job.claim.generation,
10970
11343
  jobId: job.claim.jobId,
@@ -10975,14 +11348,33 @@ var init_daemon = __esm({
10975
11348
  runToken: job.claim.runToken
10976
11349
  });
10977
11350
  }
11351
+ async confirmRunning(activeJob) {
11352
+ let retryMilliseconds = this.networkRetryMilliseconds;
11353
+ while (!this.stopping && activeJob.cancellation.currentReason() === void 0) {
11354
+ try {
11355
+ await this.reportRunning(activeJob);
11356
+ return true;
11357
+ } catch (error) {
11358
+ await this.logger.error(`Running state upload failed for Job ${activeJob.claim.jobId}`, error);
11359
+ if (isPermanentRelayFailure(error) || activeJob.leaseExpiresAt - Date.now() - this.leaseSafetyMarginMilliseconds <= 0) {
11360
+ await activeJob.cancellation.request(ExecutionCancellationReason.LeaseLost);
11361
+ return false;
11362
+ }
11363
+ const retryBudget = activeJob.leaseExpiresAt - Date.now() - this.leaseSafetyMarginMilliseconds;
11364
+ await Promise.race([
11365
+ this.waitUntilStop(Math.min(retryMilliseconds, retryBudget)),
11366
+ activeJob.cancellation.wait()
11367
+ ]);
11368
+ retryMilliseconds = Math.min(retryMilliseconds * 2, maximumTerminalRetryMilliseconds);
11369
+ }
11370
+ }
11371
+ return false;
11372
+ }
10978
11373
  async handleControl(relay, command) {
10979
11374
  const activeJob = this.activeJobs.get(command.jobId);
10980
11375
  let outcome = MachineJobStatus.Interrupted;
10981
11376
  if (activeJob) {
10982
- activeJob.cancelRequested = true;
10983
- if (activeJob.handle) {
10984
- await activeJob.handle.cancel();
10985
- }
11377
+ await activeJob.cancellation.request(ExecutionCancellationReason.Requested);
10986
11378
  outcome = MachineJobStatus.Cancelled;
10987
11379
  }
10988
11380
  await relay.acknowledgeControl({
@@ -10994,22 +11386,33 @@ var init_daemon = __esm({
10994
11386
  hasActiveJobForConnection(connectionId) {
10995
11387
  return [...this.activeJobs.values()].some((activeJob) => activeJob.connection.connectionId === connectionId);
10996
11388
  }
10997
- async waitForLeaseRenewal(activeJob) {
10998
- const deadline = Date.now() + leaseSeconds * 1e3 / 2;
10999
- while (Date.now() < deadline) {
11000
- if (this.stopping || activeJob.durableJob.snapshot().phase === PersistedMachineJobPhase.TerminalPendingUpload) {
11001
- return false;
11002
- }
11003
- await delay3(Math.min(250, deadline - Date.now()));
11004
- }
11005
- return !this.stopping;
11006
- }
11007
11389
  async waitUntilStop(milliseconds) {
11008
11390
  const deadline = Date.now() + milliseconds;
11009
11391
  while (!this.stopping && Date.now() < deadline) {
11010
11392
  await delay3(Math.min(250, deadline - Date.now()));
11011
11393
  }
11012
11394
  }
11395
+ cancellationResult(activeJob) {
11396
+ const reason = activeJob.cancellation.currentReason();
11397
+ if (reason === ExecutionCancellationReason.LeaseLost) {
11398
+ return {
11399
+ exitCode: -1,
11400
+ failureCode: "lease_lost",
11401
+ failureMessage: "Connector stopped local execution after losing the Job lease",
11402
+ status: MachineJobStatus.Interrupted
11403
+ };
11404
+ }
11405
+ return {
11406
+ exitCode: -1,
11407
+ status: MachineJobStatus.Cancelled
11408
+ };
11409
+ }
11410
+ requireDurableJob(activeJob) {
11411
+ if (!activeJob.durableJob) {
11412
+ throw new Error(`Job ${activeJob.claim.jobId} is not durably initialized`);
11413
+ }
11414
+ return activeJob.durableJob;
11415
+ }
11013
11416
  async recoverInterruptedJobs() {
11014
11417
  const jobs = await this.store.listJobs();
11015
11418
  for (const job of jobs) {
@@ -11031,20 +11434,18 @@ var init_daemon = __esm({
11031
11434
  });
11032
11435
  }
11033
11436
  const activeJob = {
11034
- cancelRequested: job.finalStatus === MachineJobStatus.Cancelled,
11437
+ cancellation: new ExecutionCancellation(),
11438
+ claim: job.claim,
11035
11439
  connection,
11036
11440
  durableJob,
11037
11441
  eventUploadQueue: Promise.resolve(),
11442
+ leaseExpiresAt: Date.parse(job.claim.leaseExpiresAt),
11038
11443
  relay
11039
11444
  };
11040
- this.activeJobs.set(job.claim.jobId, activeJob);
11041
- void this.uploadTerminal(activeJob).then(async (uploaded) => {
11042
- if (uploaded) {
11043
- await durableJob.markUploaded();
11044
- }
11045
- }).finally(() => {
11046
- this.activeJobs.delete(job.claim.jobId);
11047
- });
11445
+ if (job.finalStatus === MachineJobStatus.Cancelled) {
11446
+ await activeJob.cancellation.request(ExecutionCancellationReason.Requested);
11447
+ }
11448
+ void this.retryTerminalUpload(activeJob);
11048
11449
  }
11049
11450
  }
11050
11451
  };
@@ -11154,6 +11555,20 @@ async function runMachineDoctor(store) {
11154
11555
  status: DoctorCheckStatus.Warning
11155
11556
  });
11156
11557
  }
11558
+ try {
11559
+ const result = await execFileAsync(process.env.MOXT_CLAUDE_PATH ?? "claude", ["--version"]);
11560
+ checks.push({
11561
+ detail: result.stdout.trim(),
11562
+ name: "claude",
11563
+ status: DoctorCheckStatus.Passed
11564
+ });
11565
+ } catch (error) {
11566
+ checks.push({
11567
+ detail: errorMessage(error),
11568
+ name: "claude",
11569
+ status: DoctorCheckStatus.Warning
11570
+ });
11571
+ }
11157
11572
  return checks;
11158
11573
  }
11159
11574
  function errorMessage(error) {
@@ -11179,6 +11594,673 @@ var init_doctor = __esm({
11179
11594
  }
11180
11595
  });
11181
11596
 
11597
+ // ../machine-connector/dist/runtime/machine-manager.js
11598
+ function machineManagerActions() {
11599
+ return [
11600
+ {
11601
+ action: MachineManagerAction.Refresh,
11602
+ label: "Refresh now"
11603
+ },
11604
+ {
11605
+ action: MachineManagerAction.Connect,
11606
+ label: "Pair a new machine connection"
11607
+ },
11608
+ {
11609
+ action: MachineManagerAction.Disconnect,
11610
+ label: "Disconnect the selected connection"
11611
+ },
11612
+ {
11613
+ action: MachineManagerAction.Doctor,
11614
+ label: "Run diagnostics"
11615
+ },
11616
+ {
11617
+ action: MachineManagerAction.Logs,
11618
+ label: "Open recent logs"
11619
+ },
11620
+ {
11621
+ action: MachineManagerAction.ServiceInstall,
11622
+ label: "Install the Connector service"
11623
+ },
11624
+ {
11625
+ action: MachineManagerAction.ServiceRestart,
11626
+ label: "Restart the Connector service"
11627
+ },
11628
+ {
11629
+ action: MachineManagerAction.ServiceStop,
11630
+ label: "Stop the Connector service"
11631
+ },
11632
+ {
11633
+ action: MachineManagerAction.ServiceUninstall,
11634
+ label: "Uninstall the Connector service"
11635
+ },
11636
+ {
11637
+ action: MachineManagerAction.Quit,
11638
+ label: "Quit"
11639
+ }
11640
+ ];
11641
+ }
11642
+ function ensureInteractiveTerminal(inputIsTty, outputIsTty) {
11643
+ if (!inputIsTty || !outputIsTty) {
11644
+ throw new Error("moxt machine manager requires an interactive TTY. Use `moxt machine status`, `logs`, or `doctor` in non-interactive scripts.");
11645
+ }
11646
+ }
11647
+ async function collectMachineManagerSnapshot(store, depth) {
11648
+ const connections = await store.listConnections();
11649
+ const jobs = await store.listJobs();
11650
+ const serviceManager = (await store.readServiceManager()).value;
11651
+ const runtime = {};
11652
+ try {
11653
+ runtime.value = (await requestRuntimeStatus(store)).status;
11654
+ } catch {
11655
+ runtime.value = void 0;
11656
+ }
11657
+ const checks = depth === MachineManagerSnapshotDepth.WithDoctor ? await runMachineDoctor(store) : [];
11658
+ return {
11659
+ checks,
11660
+ connections: connections.map(toManagerConnection),
11661
+ jobs: jobs.map(toManagerJob).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
11662
+ logLines: await readRecentLogLines(store),
11663
+ refreshedAt: (/* @__PURE__ */ new Date()).toISOString(),
11664
+ runtime: runtime.value,
11665
+ serviceManager: serviceManager?.manager
11666
+ };
11667
+ }
11668
+ function renderMachineManager(snapshot, state, requestedWidth, requestedHeight) {
11669
+ const width = Math.max(24, requestedWidth);
11670
+ const height = Math.max(8, requestedHeight);
11671
+ const lines = [];
11672
+ const online = snapshot.runtime !== void 0;
11673
+ lines.push(styledLine(` MOXT MACHINE MANAGER ${online ? "ONLINE" : "OFFLINE"} ${snapshot.serviceManager ?? "no service"}`, width, styleHeader));
11674
+ lines.push(fitLine(renderTabs(state.view), width));
11675
+ lines.push(repeatCharacter("\u2500", width));
11676
+ const contentHeight = Math.max(1, height - 5);
11677
+ const content = state.actionMenuOpen ? renderActions(state) : renderView(snapshot, state);
11678
+ for (const line of content.slice(0, contentHeight)) {
11679
+ lines.push(fitLine(line, width));
11680
+ }
11681
+ while (lines.length < height - 2) {
11682
+ lines.push(" ".repeat(width));
11683
+ }
11684
+ lines.push(repeatCharacter("\u2500", width));
11685
+ lines.push(fitLine(state.message ?? "[A] Actions [Tab/1-5] View [Up/Down] Select [R] Refresh [Q] Quit", width));
11686
+ return lines.slice(0, height).join("\n");
11687
+ }
11688
+ async function runMachineManager(store, commandRunner) {
11689
+ ensureInteractiveTerminal(Boolean(process.stdin.isTTY), Boolean(process.stdout.isTTY));
11690
+ const manager = new InteractiveMachineManager(store, commandRunner);
11691
+ await manager.run();
11692
+ }
11693
+ function renderTabs(selected) {
11694
+ const labels = [
11695
+ "1 Overview",
11696
+ "2 Connections",
11697
+ "3 Jobs",
11698
+ "4 Logs",
11699
+ "5 Doctor"
11700
+ ];
11701
+ return labels.map((label, index) => index === selected ? `[${label}]` : ` ${label} `).join(" ");
11702
+ }
11703
+ function renderView(snapshot, state) {
11704
+ if (state.view === MachineManagerView.Overview) {
11705
+ return renderOverview(snapshot);
11706
+ }
11707
+ if (state.view === MachineManagerView.Connections) {
11708
+ return renderConnections(snapshot, state.selectedRowIndex);
11709
+ }
11710
+ if (state.view === MachineManagerView.Jobs) {
11711
+ return renderJobs(snapshot, state.selectedRowIndex);
11712
+ }
11713
+ if (state.view === MachineManagerView.Logs) {
11714
+ return renderLogs(snapshot);
11715
+ }
11716
+ return renderDoctor(snapshot);
11717
+ }
11718
+ function renderOverview(snapshot) {
11719
+ const runtime = snapshot.runtime;
11720
+ const lines = [
11721
+ "",
11722
+ ` Daemon ${runtime ? `ONLINE PID ${runtime.pid} v${runtime.version}` : "OFFLINE"}`,
11723
+ ` Service ${snapshot.serviceManager ?? "not installed"}`,
11724
+ ` Connections ${snapshot.connections.length}`,
11725
+ ` Active Jobs ${runtime?.activeJobs.length ?? 0}`,
11726
+ ` Stored Jobs ${snapshot.jobs.length}`,
11727
+ ` Refreshed ${formatTimestamp(snapshot.refreshedAt)}`,
11728
+ ""
11729
+ ];
11730
+ if (snapshot.connections.length === 0) {
11731
+ lines.push(' No connections. Press A and choose "Pair a new machine connection".');
11732
+ return lines;
11733
+ }
11734
+ lines.push(" Connected roots");
11735
+ for (const connection of snapshot.connections) {
11736
+ lines.push(` ${connection.machineName} ${connection.rootPath}`);
11737
+ }
11738
+ return lines;
11739
+ }
11740
+ function renderConnections(snapshot, selectedRowIndex) {
11741
+ if (snapshot.connections.length === 0) {
11742
+ return ["", " No connections", " Press A to pair a machine."];
11743
+ }
11744
+ const lines = [
11745
+ " MACHINE ROOT WORKSPACE / TARGET"
11746
+ ];
11747
+ snapshot.connections.forEach((connection, index) => {
11748
+ const marker = index === selectedRowIndex ? ">" : " ";
11749
+ lines.push(`${marker} ${connection.machineName} ${connection.rootPath} ${connection.workspaceId} / ${connection.targetId}`);
11750
+ lines.push(` ${connection.connectionId} ${connection.relayOrigin}`);
11751
+ });
11752
+ return lines;
11753
+ }
11754
+ function renderJobs(snapshot, selectedRowIndex) {
11755
+ if (snapshot.jobs.length === 0) {
11756
+ return ["", " No Jobs have been stored on this machine."];
11757
+ }
11758
+ const lines = [" STATUS KIND JOB / COMMAND"];
11759
+ snapshot.jobs.forEach((job, index) => {
11760
+ const marker = index === selectedRowIndex ? ">" : " ";
11761
+ lines.push(`${marker} ${job.status ?? job.phase} ${job.kind} ${job.command ?? job.jobId}`);
11762
+ lines.push(` ${job.jobId} ${job.relativeWorkingDirectory} ${formatTimestamp(job.updatedAt)}`);
11763
+ });
11764
+ return lines;
11765
+ }
11766
+ function renderLogs(snapshot) {
11767
+ if (snapshot.logLines.length === 0) {
11768
+ return ["", " No Connector logs are available."];
11769
+ }
11770
+ return snapshot.logLines.map((line) => ` ${line}`);
11771
+ }
11772
+ function renderDoctor(snapshot) {
11773
+ if (snapshot.checks.length === 0) {
11774
+ return [
11775
+ "",
11776
+ " Diagnostics have not run yet.",
11777
+ ' Press A and choose "Run diagnostics".'
11778
+ ];
11779
+ }
11780
+ return snapshot.checks.map((check) => ` ${check.status.padEnd(7)} ${check.name}: ${check.detail}`);
11781
+ }
11782
+ function renderActions(state) {
11783
+ const lines = [
11784
+ " Actions",
11785
+ " Use Up/Down and Enter. Esc closes this menu.",
11786
+ ""
11787
+ ];
11788
+ machineManagerActions().forEach((definition, index) => {
11789
+ const selected = index === state.selectedActionIndex;
11790
+ const line = `${selected ? ">" : " "} ${definition.label}`;
11791
+ lines.push(selected ? `${styleSelected}${line}${styleReset}` : line);
11792
+ });
11793
+ return lines;
11794
+ }
11795
+ function rowCountForView(snapshot, view) {
11796
+ if (view === MachineManagerView.Connections) {
11797
+ return snapshot.connections.length;
11798
+ }
11799
+ if (view === MachineManagerView.Jobs) {
11800
+ return snapshot.jobs.length;
11801
+ }
11802
+ return 0;
11803
+ }
11804
+ function toManagerConnection(connection) {
11805
+ return {
11806
+ connectionId: connection.connectionId,
11807
+ machineName: connection.machineName,
11808
+ relayOrigin: connection.relayOrigin,
11809
+ rootDisplayName: connection.rootDisplayName,
11810
+ rootPath: connection.rootPath,
11811
+ targetId: connection.targetId,
11812
+ targetKind: connection.targetKind,
11813
+ workspaceId: connection.workspaceId
11814
+ };
11815
+ }
11816
+ function toManagerJob(job) {
11817
+ return {
11818
+ command: formatPersistedCommand(job).value,
11819
+ connectionId: job.connectionId,
11820
+ jobId: job.claim.jobId,
11821
+ kind: job.claim.kind,
11822
+ phase: job.phase,
11823
+ relativeWorkingDirectory: job.claim.relativeWorkingDirectory,
11824
+ status: job.finalStatus,
11825
+ updatedAt: job.updatedAt
11826
+ };
11827
+ }
11828
+ function formatPersistedCommand(job) {
11829
+ if (job.claim.kind !== "command") {
11830
+ return {};
11831
+ }
11832
+ if (!isRecord3(job.claim.requestPayload)) {
11833
+ return {};
11834
+ }
11835
+ const executable = job.claim.requestPayload.executable;
11836
+ const argumentsValue = job.claim.requestPayload.arguments;
11837
+ if (typeof executable !== "string" || !Array.isArray(argumentsValue) || !argumentsValue.every((argument) => typeof argument === "string")) {
11838
+ return {};
11839
+ }
11840
+ return {
11841
+ value: [executable, ...argumentsValue].map(formatCommandArgument).join(" ")
11842
+ };
11843
+ }
11844
+ function formatCommandArgument(value) {
11845
+ return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : JSON.stringify(value);
11846
+ }
11847
+ async function readRecentLogLines(store) {
11848
+ const normal = await readOptionalFile(store.runtimeLogPath());
11849
+ const errors = await readOptionalFile(store.runtimeErrorLogPath());
11850
+ return [...normal.split("\n"), ...errors.split("\n")].filter((line) => line.length > 0).slice(-maximumLogLines);
11851
+ }
11852
+ async function readOptionalFile(path10) {
11853
+ try {
11854
+ return await (0, import_promises8.readFile)(path10, "utf8");
11855
+ } catch (error) {
11856
+ if (isMissingFile(error)) {
11857
+ return "";
11858
+ }
11859
+ throw error;
11860
+ }
11861
+ }
11862
+ async function questionWithDefault(reader, label, defaultValue) {
11863
+ const suffix = defaultValue.length > 0 ? ` [${defaultValue}]` : "";
11864
+ const answer = (await reader.question(`${label}${suffix}: `)).trim();
11865
+ return answer.length > 0 ? answer : defaultValue;
11866
+ }
11867
+ function appendOption(argumentsList, name, value) {
11868
+ if (value.length > 0) {
11869
+ argumentsList.push(name, value);
11870
+ }
11871
+ }
11872
+ function styledLine(value, width, style) {
11873
+ return `${style}${fitLine(value, width)}${styleReset}`;
11874
+ }
11875
+ function fitLine(value, width) {
11876
+ const plainValue = stripAnsi2(value);
11877
+ if (plainValue.length > width) {
11878
+ if (width <= 1) {
11879
+ return plainValue.slice(0, width);
11880
+ }
11881
+ return `${plainValue.slice(0, width - 1)}\u2026`;
11882
+ }
11883
+ if (value.includes("\x1B[")) {
11884
+ return value;
11885
+ }
11886
+ return value.padEnd(width);
11887
+ }
11888
+ function stripAnsi2(value) {
11889
+ return value.replaceAll(styleHeader, "").replaceAll(styleSelected, "").replaceAll(styleReset, "");
11890
+ }
11891
+ function repeatCharacter(value, count) {
11892
+ return value.repeat(count);
11893
+ }
11894
+ function wrapIndex(value, count) {
11895
+ return (value % count + count) % count;
11896
+ }
11897
+ function formatTimestamp(value) {
11898
+ const timestamp = Date.parse(value);
11899
+ if (Number.isNaN(timestamp)) {
11900
+ return value;
11901
+ }
11902
+ return new Date(timestamp).toLocaleString();
11903
+ }
11904
+ function isRecord3(value) {
11905
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11906
+ }
11907
+ function isMissingFile(error) {
11908
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
11909
+ }
11910
+ function errorMessage2(error) {
11911
+ return error instanceof Error ? error.message : String(error);
11912
+ }
11913
+ var import_promises8, import_promises9, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
11914
+ var init_machine_manager = __esm({
11915
+ "../machine-connector/dist/runtime/machine-manager.js"() {
11916
+ "use strict";
11917
+ init_cjs_shims();
11918
+ import_promises8 = require("fs/promises");
11919
+ import_promises9 = require("readline/promises");
11920
+ import_node_readline = require("readline");
11921
+ init_doctor();
11922
+ init_local_ipc();
11923
+ alternateScreenEnter = "\x1B[?1049h";
11924
+ alternateScreenExit = "\x1B[?1049l";
11925
+ clearScreen = "\x1B[2J\x1B[H";
11926
+ cursorHide = "\x1B[?25l";
11927
+ cursorShow = "\x1B[?25h";
11928
+ styleReset = "\x1B[0m";
11929
+ styleHeader = "\x1B[1;30;46m";
11930
+ styleSelected = "\x1B[30;47m";
11931
+ refreshIntervalMilliseconds = 1e3;
11932
+ maximumLogLines = 200;
11933
+ (function(MachineManagerView2) {
11934
+ MachineManagerView2[MachineManagerView2["Overview"] = 0] = "Overview";
11935
+ MachineManagerView2[MachineManagerView2["Connections"] = 1] = "Connections";
11936
+ MachineManagerView2[MachineManagerView2["Jobs"] = 2] = "Jobs";
11937
+ MachineManagerView2[MachineManagerView2["Logs"] = 3] = "Logs";
11938
+ MachineManagerView2[MachineManagerView2["Doctor"] = 4] = "Doctor";
11939
+ })(MachineManagerView || (MachineManagerView = {}));
11940
+ (function(MachineManagerAction2) {
11941
+ MachineManagerAction2["Refresh"] = "refresh";
11942
+ MachineManagerAction2["Connect"] = "connect";
11943
+ MachineManagerAction2["Disconnect"] = "disconnect";
11944
+ MachineManagerAction2["Doctor"] = "doctor";
11945
+ MachineManagerAction2["Logs"] = "logs";
11946
+ MachineManagerAction2["ServiceInstall"] = "service_install";
11947
+ MachineManagerAction2["ServiceRestart"] = "service_restart";
11948
+ MachineManagerAction2["ServiceStop"] = "service_stop";
11949
+ MachineManagerAction2["ServiceUninstall"] = "service_uninstall";
11950
+ MachineManagerAction2["Quit"] = "quit";
11951
+ })(MachineManagerAction || (MachineManagerAction = {}));
11952
+ (function(MachineManagerSnapshotDepth2) {
11953
+ MachineManagerSnapshotDepth2["Basic"] = "basic";
11954
+ MachineManagerSnapshotDepth2["WithDoctor"] = "with_doctor";
11955
+ })(MachineManagerSnapshotDepth || (MachineManagerSnapshotDepth = {}));
11956
+ InteractiveMachineManager = class {
11957
+ store;
11958
+ commandRunner;
11959
+ checks = [];
11960
+ refreshTimer;
11961
+ refreshing = false;
11962
+ resolveRun;
11963
+ snapshot = {
11964
+ checks: [],
11965
+ connections: [],
11966
+ jobs: [],
11967
+ logLines: [],
11968
+ refreshedAt: (/* @__PURE__ */ new Date()).toISOString()
11969
+ };
11970
+ state = {
11971
+ actionMenuOpen: false,
11972
+ selectedActionIndex: 0,
11973
+ selectedRowIndex: 0,
11974
+ view: MachineManagerView.Overview
11975
+ };
11976
+ stopped = false;
11977
+ terminalSuspended = true;
11978
+ constructor(store, commandRunner) {
11979
+ this.store = store;
11980
+ this.commandRunner = commandRunner;
11981
+ }
11982
+ async run() {
11983
+ await this.refresh(MachineManagerSnapshotDepth.Basic);
11984
+ this.enterTerminal();
11985
+ try {
11986
+ await new Promise((resolvePromise) => {
11987
+ this.resolveRun = resolvePromise;
11988
+ });
11989
+ } finally {
11990
+ this.leaveTerminal();
11991
+ }
11992
+ }
11993
+ enterTerminal() {
11994
+ (0, import_node_readline.emitKeypressEvents)(process.stdin);
11995
+ process.stdin.setRawMode(true);
11996
+ process.stdin.resume();
11997
+ process.stdin.on("keypress", this.onKeypress);
11998
+ process.stdout.on("resize", this.onResize);
11999
+ process.on("SIGINT", this.onTerminationSignal);
12000
+ process.on("SIGTERM", this.onTerminationSignal);
12001
+ process.stdout.write(`${alternateScreenEnter}${cursorHide}${clearScreen}`);
12002
+ this.terminalSuspended = false;
12003
+ this.refreshTimer = setInterval(() => {
12004
+ void this.refresh(MachineManagerSnapshotDepth.Basic);
12005
+ }, refreshIntervalMilliseconds);
12006
+ this.render();
12007
+ }
12008
+ leaveTerminal() {
12009
+ if (this.refreshTimer) {
12010
+ clearInterval(this.refreshTimer);
12011
+ this.refreshTimer = void 0;
12012
+ }
12013
+ process.stdin.off("keypress", this.onKeypress);
12014
+ process.stdout.off("resize", this.onResize);
12015
+ process.off("SIGINT", this.onTerminationSignal);
12016
+ process.off("SIGTERM", this.onTerminationSignal);
12017
+ if (process.stdin.isTTY) {
12018
+ process.stdin.setRawMode(false);
12019
+ }
12020
+ process.stdin.pause();
12021
+ process.stdout.write(`${cursorShow}${styleReset}${alternateScreenExit}`);
12022
+ }
12023
+ onResize = () => {
12024
+ this.render();
12025
+ };
12026
+ onTerminationSignal = () => {
12027
+ this.stop();
12028
+ };
12029
+ onKeypress = (text, key) => {
12030
+ if (key.ctrl && key.name === "c") {
12031
+ this.stop();
12032
+ return;
12033
+ }
12034
+ if (key.name === "q" || text === "q") {
12035
+ this.stop();
12036
+ return;
12037
+ }
12038
+ if (key.name === "a" || text === "a" || text === "?") {
12039
+ this.state.actionMenuOpen = !this.state.actionMenuOpen;
12040
+ this.state.message = void 0;
12041
+ this.render();
12042
+ return;
12043
+ }
12044
+ if (key.name === "escape") {
12045
+ this.state.actionMenuOpen = false;
12046
+ this.render();
12047
+ return;
12048
+ }
12049
+ if (key.name === "up") {
12050
+ this.moveSelection(-1);
12051
+ return;
12052
+ }
12053
+ if (key.name === "down") {
12054
+ this.moveSelection(1);
12055
+ return;
12056
+ }
12057
+ if (key.name === "return" && this.state.actionMenuOpen) {
12058
+ void this.executeSelectedAction();
12059
+ return;
12060
+ }
12061
+ if (key.name === "tab" || key.name === "right") {
12062
+ this.changeView(1);
12063
+ return;
12064
+ }
12065
+ if (key.name === "left") {
12066
+ this.changeView(-1);
12067
+ return;
12068
+ }
12069
+ if (text === "r") {
12070
+ void this.refresh(MachineManagerSnapshotDepth.Basic);
12071
+ return;
12072
+ }
12073
+ const viewNumber = Number(text);
12074
+ if (Number.isInteger(viewNumber) && viewNumber >= 1 && viewNumber <= 5) {
12075
+ this.state.view = viewNumber - 1;
12076
+ this.state.selectedRowIndex = 0;
12077
+ this.state.actionMenuOpen = false;
12078
+ this.render();
12079
+ }
12080
+ };
12081
+ moveSelection(delta) {
12082
+ const rowCount = this.state.actionMenuOpen ? machineManagerActions().length : rowCountForView(this.snapshot, this.state.view);
12083
+ if (rowCount === 0) {
12084
+ return;
12085
+ }
12086
+ if (this.state.actionMenuOpen) {
12087
+ this.state.selectedActionIndex = wrapIndex(this.state.selectedActionIndex + delta, rowCount);
12088
+ } else {
12089
+ this.state.selectedRowIndex = wrapIndex(this.state.selectedRowIndex + delta, rowCount);
12090
+ }
12091
+ this.render();
12092
+ }
12093
+ changeView(delta) {
12094
+ this.state.view = wrapIndex(this.state.view + delta, 5);
12095
+ this.state.selectedRowIndex = 0;
12096
+ this.state.actionMenuOpen = false;
12097
+ this.state.message = void 0;
12098
+ this.render();
12099
+ }
12100
+ async refresh(depth) {
12101
+ if (this.refreshing || this.stopped) {
12102
+ return;
12103
+ }
12104
+ this.refreshing = true;
12105
+ try {
12106
+ const snapshot = await collectMachineManagerSnapshot(this.store, depth);
12107
+ if (snapshot.checks.length > 0) {
12108
+ this.checks = snapshot.checks;
12109
+ }
12110
+ this.snapshot = {
12111
+ ...snapshot,
12112
+ checks: this.checks
12113
+ };
12114
+ this.state.message = void 0;
12115
+ } catch (error) {
12116
+ this.state.message = errorMessage2(error);
12117
+ } finally {
12118
+ this.refreshing = false;
12119
+ this.render();
12120
+ }
12121
+ }
12122
+ render() {
12123
+ if (this.stopped || this.terminalSuspended || !process.stdout.isTTY) {
12124
+ return;
12125
+ }
12126
+ process.stdout.write(`${clearScreen}${renderMachineManager(this.snapshot, this.state, process.stdout.columns ?? 80, process.stdout.rows ?? 24)}`);
12127
+ }
12128
+ async executeSelectedAction() {
12129
+ const definition = machineManagerActions()[this.state.selectedActionIndex];
12130
+ this.state.actionMenuOpen = false;
12131
+ if (definition.action === MachineManagerAction.Quit) {
12132
+ this.stop();
12133
+ return;
12134
+ }
12135
+ if (definition.action === MachineManagerAction.Refresh) {
12136
+ await this.refresh(MachineManagerSnapshotDepth.Basic);
12137
+ return;
12138
+ }
12139
+ if (definition.action === MachineManagerAction.Doctor) {
12140
+ this.state.view = MachineManagerView.Doctor;
12141
+ await this.refresh(MachineManagerSnapshotDepth.WithDoctor);
12142
+ return;
12143
+ }
12144
+ if (definition.action === MachineManagerAction.Logs) {
12145
+ this.state.view = MachineManagerView.Logs;
12146
+ await this.refresh(MachineManagerSnapshotDepth.Basic);
12147
+ return;
12148
+ }
12149
+ await this.runCommandAction(definition.action);
12150
+ }
12151
+ async runCommandAction(action) {
12152
+ this.suspendTerminal();
12153
+ const reader = (0, import_promises9.createInterface)({
12154
+ input: process.stdin,
12155
+ output: process.stdout
12156
+ });
12157
+ try {
12158
+ const argumentsList = await this.buildCommandArguments(reader, action);
12159
+ if (argumentsList.length > 0) {
12160
+ await this.commandRunner.run(argumentsList);
12161
+ }
12162
+ } catch (error) {
12163
+ process.stdout.write(`
12164
+ Error: ${errorMessage2(error)}
12165
+ `);
12166
+ }
12167
+ await reader.question("\nPress Enter to return to the manager...");
12168
+ reader.close();
12169
+ this.resumeTerminal();
12170
+ await this.refresh(MachineManagerSnapshotDepth.Basic);
12171
+ }
12172
+ suspendTerminal() {
12173
+ this.terminalSuspended = true;
12174
+ process.stdin.off("keypress", this.onKeypress);
12175
+ process.stdout.off("resize", this.onResize);
12176
+ process.stdin.setRawMode(false);
12177
+ process.stdout.write(`${cursorShow}${styleReset}${alternateScreenExit}`);
12178
+ }
12179
+ resumeTerminal() {
12180
+ (0, import_node_readline.emitKeypressEvents)(process.stdin);
12181
+ process.stdin.setRawMode(true);
12182
+ process.stdin.resume();
12183
+ process.stdin.on("keypress", this.onKeypress);
12184
+ process.stdout.on("resize", this.onResize);
12185
+ process.stdout.write(`${alternateScreenEnter}${cursorHide}${clearScreen}`);
12186
+ this.terminalSuspended = false;
12187
+ }
12188
+ async buildCommandArguments(reader, action) {
12189
+ if (action === MachineManagerAction.Connect) {
12190
+ return await this.buildConnectArguments(reader);
12191
+ }
12192
+ if (action === MachineManagerAction.Disconnect) {
12193
+ return await this.buildDisconnectArguments(reader);
12194
+ }
12195
+ if (action === MachineManagerAction.ServiceInstall) {
12196
+ const manager = await questionWithDefault(reader, "Service manager (auto/systemd/supervisor/none)", "auto");
12197
+ return ["service", "install", "--service-manager", manager];
12198
+ }
12199
+ if (action === MachineManagerAction.ServiceRestart) {
12200
+ return ["service", "restart"];
12201
+ }
12202
+ if (action === MachineManagerAction.ServiceStop) {
12203
+ return ["service", "stop"];
12204
+ }
12205
+ if (action === MachineManagerAction.ServiceUninstall) {
12206
+ return ["service", "uninstall"];
12207
+ }
12208
+ return [];
12209
+ }
12210
+ async buildConnectArguments(reader) {
12211
+ const code = (await reader.question("Pairing code: ")).trim();
12212
+ if (code.length === 0) {
12213
+ throw new Error("Pairing code is required");
12214
+ }
12215
+ const root = await questionWithDefault(reader, "Working root", process.cwd());
12216
+ const relay = (await reader.question("Relay origin (leave blank for the default): ")).trim();
12217
+ const name = (await reader.question("Machine name (leave blank for the hostname): ")).trim();
12218
+ const serviceManager = await questionWithDefault(reader, "Service manager (auto/systemd/supervisor/none)", "auto");
12219
+ const noOpen = (await reader.question("Skip opening the confirmation page? [y/N]: ")).trim().toLowerCase();
12220
+ const argumentsList = [
12221
+ "connect",
12222
+ "--code",
12223
+ code,
12224
+ "--root",
12225
+ root,
12226
+ "--service-manager",
12227
+ serviceManager
12228
+ ];
12229
+ appendOption(argumentsList, "--relay", relay);
12230
+ appendOption(argumentsList, "--name", name);
12231
+ if (noOpen === "y" || noOpen === "yes") {
12232
+ argumentsList.push("--no-open");
12233
+ }
12234
+ return argumentsList;
12235
+ }
12236
+ async buildDisconnectArguments(reader) {
12237
+ const selected = this.snapshot.connections[this.state.selectedRowIndex];
12238
+ const connectionId = await questionWithDefault(reader, "Connection ID", selected?.connectionId ?? "");
12239
+ if (connectionId.length === 0) {
12240
+ throw new Error("Connection ID is required");
12241
+ }
12242
+ const confirmed = (await reader.question(`Disconnect ${connectionId}? [y/N]: `)).trim().toLowerCase();
12243
+ if (confirmed !== "y" && confirmed !== "yes") {
12244
+ return [];
12245
+ }
12246
+ const localOnly = (await reader.question("Remove local state without contacting Moxt? [y/N]: ")).trim().toLowerCase();
12247
+ const argumentsList = ["disconnect", "--connection", connectionId];
12248
+ if (localOnly === "y" || localOnly === "yes") {
12249
+ argumentsList.push("--local-only");
12250
+ }
12251
+ return argumentsList;
12252
+ }
12253
+ stop() {
12254
+ if (this.stopped) {
12255
+ return;
12256
+ }
12257
+ this.stopped = true;
12258
+ this.resolveRun?.();
12259
+ }
12260
+ };
12261
+ }
12262
+ });
12263
+
11182
12264
  // ../machine-connector/dist/runtime/device-identity.js
11183
12265
  async function ensureMachineIdentity(store) {
11184
12266
  const existingIdentity = (await store.readIdentity()).value;
@@ -11202,7 +12284,7 @@ async function ensureMachineIdentity(store) {
11202
12284
  });
11203
12285
  const identity = {
11204
12286
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
11205
- deviceKeyFingerprint: (0, import_node_crypto4.createHash)("sha256").update(keyPair.publicKey, "utf8").digest("hex"),
12287
+ deviceKeyFingerprint: (0, import_node_crypto5.createHash)("sha256").update(keyPair.publicKey, "utf8").digest("hex"),
11206
12288
  publicKeyPem: keyPair.publicKey
11207
12289
  };
11208
12290
  await store.writePrivateKey(keyPair.privateKey);
@@ -11218,12 +12300,12 @@ function decryptPairingCredentials(privateKeyPem, encryptedCredentials) {
11218
12300
  if (envelope.version !== 1 || envelope.algorithm !== "RSA-OAEP-256+A256GCM") {
11219
12301
  throw new Error("Unsupported Local Machine credentials envelope");
11220
12302
  }
11221
- const encryptionKey = (0, import_node_crypto4.privateDecrypt)({
12303
+ const encryptionKey = (0, import_node_crypto5.privateDecrypt)({
11222
12304
  key: privateKeyPem,
11223
12305
  oaepHash: "sha256",
11224
- padding: import_node_crypto4.constants.RSA_PKCS1_OAEP_PADDING
12306
+ padding: import_node_crypto5.constants.RSA_PKCS1_OAEP_PADDING
11225
12307
  }, Buffer.from(envelope.encryptedKey, "base64url"));
11226
- const decipher = (0, import_node_crypto4.createDecipheriv)("aes-256-gcm", encryptionKey, Buffer.from(envelope.initializationVector, "base64url"));
12308
+ const decipher = (0, import_node_crypto5.createDecipheriv)("aes-256-gcm", encryptionKey, Buffer.from(envelope.initializationVector, "base64url"));
11227
12309
  decipher.setAuthTag(Buffer.from(envelope.authenticationTag, "base64url"));
11228
12310
  const decrypted = Buffer.concat([
11229
12311
  decipher.update(Buffer.from(envelope.ciphertext, "base64url")),
@@ -11231,14 +12313,14 @@ function decryptPairingCredentials(privateKeyPem, encryptedCredentials) {
11231
12313
  ]);
11232
12314
  return JSON.parse(decrypted.toString("utf8"));
11233
12315
  }
11234
- var import_node_crypto4, import_node_util5, generateKeyPairAsync;
12316
+ var import_node_crypto5, import_node_util5, generateKeyPairAsync;
11235
12317
  var init_device_identity = __esm({
11236
12318
  "../machine-connector/dist/runtime/device-identity.js"() {
11237
12319
  "use strict";
11238
12320
  init_cjs_shims();
11239
- import_node_crypto4 = require("crypto");
12321
+ import_node_crypto5 = require("crypto");
11240
12322
  import_node_util5 = require("util");
11241
- generateKeyPairAsync = (0, import_node_util5.promisify)(import_node_crypto4.generateKeyPair);
12323
+ generateKeyPairAsync = (0, import_node_util5.promisify)(import_node_crypto5.generateKeyPair);
11242
12324
  }
11243
12325
  });
11244
12326
 
@@ -11249,11 +12331,11 @@ async function pairMachine(store, options) {
11249
12331
  const identity = await ensureMachineIdentity(store);
11250
12332
  const machineName = options.machineName ?? (0, import_node_os8.hostname)();
11251
12333
  const operatingSystem = getOperatingSystem();
11252
- const rootHandle = (0, import_node_crypto5.createHash)("sha256").update(identity.identity.deviceKeyFingerprint, "utf8").update("\0").update(canonicalRoot, "utf8").digest("base64url");
12334
+ const rootHandle = (0, import_node_crypto6.createHash)("sha256").update(identity.identity.deviceKeyFingerprint, "utf8").update("\0").update(canonicalRoot, "utf8").digest("base64url");
11253
12335
  const client = new PairingRelayClient(options.relayOrigin);
11254
12336
  const proposal = await client.propose({
11255
12337
  connectionCode: options.connectionCode,
11256
- connectorVersion: "0.1.0",
12338
+ connectorVersion,
11257
12339
  devicePublicKey: identity.identity.publicKeyPem,
11258
12340
  machineName,
11259
12341
  operatingSystem,
@@ -11279,7 +12361,7 @@ async function pairMachine(store, options) {
11279
12361
  accessToken: credentials.accessToken,
11280
12362
  accessTokenExpiresAt: credentials.accessTokenExpiresAt,
11281
12363
  connectionId: credentials.connectionId,
11282
- connectorVersion: "0.1.0",
12364
+ connectorVersion,
11283
12365
  heartbeatIntervalSeconds: credentials.heartbeatIntervalSeconds,
11284
12366
  machineId: credentials.machineId,
11285
12367
  machineName,
@@ -11325,16 +12407,17 @@ function delay4(milliseconds) {
11325
12407
  setTimeout(resolvePromise, milliseconds);
11326
12408
  });
11327
12409
  }
11328
- var import_node_child_process4, import_node_crypto5, import_node_os8, import_node_path12, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
12410
+ var import_node_child_process4, import_node_crypto6, import_node_os8, import_node_path12, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
11329
12411
  var init_pairing = __esm({
11330
12412
  "../machine-connector/dist/runtime/pairing.js"() {
11331
12413
  "use strict";
11332
12414
  init_cjs_shims();
11333
12415
  import_node_child_process4 = require("child_process");
11334
- import_node_crypto5 = require("crypto");
12416
+ import_node_crypto6 = require("crypto");
11335
12417
  import_node_os8 = require("os");
11336
12418
  import_node_path12 = require("path");
11337
12419
  init_contracts();
12420
+ init_version();
11338
12421
  init_enums();
11339
12422
  init_device_identity();
11340
12423
  init_relay_client();
@@ -11631,7 +12714,7 @@ async function uninstallManager(manager, store, runtime) {
11631
12714
  "bootout",
11632
12715
  `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
11633
12716
  ]);
11634
- await (0, import_promises8.rm)(launchAgentPath(), { force: true });
12717
+ await (0, import_promises10.rm)(launchAgentPath(), { force: true });
11635
12718
  return;
11636
12719
  }
11637
12720
  if (manager === UserServiceManager.Systemd) {
@@ -11641,7 +12724,7 @@ async function uninstallManager(manager, store, runtime) {
11641
12724
  "--now",
11642
12725
  "moxt-machine-connector.service"
11643
12726
  ]);
11644
- await (0, import_promises8.rm)(systemdUnitPath(), { force: true });
12727
+ await (0, import_promises10.rm)(systemdUnitPath(), { force: true });
11645
12728
  await runCommandIgnoringFailure(runtime, "systemctl", [
11646
12729
  "--user",
11647
12730
  "daemon-reload"
@@ -11655,7 +12738,7 @@ async function uninstallManager(manager, store, runtime) {
11655
12738
  supervisorProgramName
11656
12739
  ]);
11657
12740
  await runCommandIgnoringFailure(runtime, "supervisorctl", ["-c", supervisorConfigPath(store), "shutdown"]);
11658
- await (0, import_promises8.rm)(supervisorDirectory(store), {
12741
+ await (0, import_promises10.rm)(supervisorDirectory(store), {
11659
12742
  force: true,
11660
12743
  recursive: true
11661
12744
  });
@@ -11723,7 +12806,7 @@ function automaticSelectionDetail(manager) {
11723
12806
  }
11724
12807
  async function installLaunchAgent(store, options, runtime) {
11725
12808
  const path10 = launchAgentPath();
11726
- await (0, import_promises8.mkdir)((0, import_node_path13.dirname)(path10), { recursive: true });
12809
+ await (0, import_promises10.mkdir)((0, import_node_path13.dirname)(path10), { recursive: true });
11727
12810
  const programArguments = [
11728
12811
  options.nodePath,
11729
12812
  (0, import_node_path13.resolve)(options.entrypointPath),
@@ -11757,7 +12840,7 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
11757
12840
  </dict>
11758
12841
  </plist>
11759
12842
  `;
11760
- await (0, import_promises8.writeFile)(path10, plist, { encoding: "utf8", mode: 384 });
12843
+ await (0, import_promises10.writeFile)(path10, plist, { encoding: "utf8", mode: 384 });
11761
12844
  const domain = `gui/${process.getuid?.() ?? 0}`;
11762
12845
  await runCommandIgnoringFailure(runtime, "launchctl", [
11763
12846
  "bootout",
@@ -11773,7 +12856,7 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
11773
12856
  }
11774
12857
  async function installSystemdUserService(store, options, runtime) {
11775
12858
  const path10 = systemdUnitPath();
11776
- await (0, import_promises8.mkdir)((0, import_node_path13.dirname)(path10), { recursive: true });
12859
+ await (0, import_promises10.mkdir)((0, import_node_path13.dirname)(path10), { recursive: true });
11777
12860
  const command = [
11778
12861
  options.nodePath,
11779
12862
  (0, import_node_path13.resolve)(options.entrypointPath),
@@ -11795,7 +12878,7 @@ ${Object.entries(options.environment).map(([name, value]) => `Environment=${esca
11795
12878
  [Install]
11796
12879
  WantedBy=default.target
11797
12880
  `;
11798
- await (0, import_promises8.writeFile)(path10, unit, { encoding: "utf8", mode: 384 });
12881
+ await (0, import_promises10.writeFile)(path10, unit, { encoding: "utf8", mode: 384 });
11799
12882
  await runtime.run("systemctl", ["--user", "daemon-reload"]);
11800
12883
  await runtime.run("systemctl", [
11801
12884
  "--user",
@@ -11811,15 +12894,15 @@ WantedBy=default.target
11811
12894
  async function installSupervisorUserService(store, options, runtime) {
11812
12895
  const directory = supervisorDirectory(store);
11813
12896
  const configPath = supervisorConfigPath(store);
11814
- await (0, import_promises8.mkdir)(directory, { recursive: true, mode: 448 });
11815
- await (0, import_promises8.writeFile)(configPath, createSupervisorConfiguration(store, options), {
12897
+ await (0, import_promises10.mkdir)(directory, { recursive: true, mode: 448 });
12898
+ await (0, import_promises10.writeFile)(configPath, createSupervisorConfiguration(store, options), {
11816
12899
  encoding: "utf8",
11817
12900
  mode: 384
11818
12901
  });
11819
12902
  const supervisorWasRunning = await supervisorIsRunning(store, runtime);
11820
12903
  if (!supervisorWasRunning) {
11821
- await (0, import_promises8.rm)(supervisorSocketPath(store), { force: true });
11822
- await (0, import_promises8.rm)(supervisorPidPath(store), { force: true });
12904
+ await (0, import_promises10.rm)(supervisorSocketPath(store), { force: true });
12905
+ await (0, import_promises10.rm)(supervisorPidPath(store), { force: true });
11823
12906
  await runtime.run("supervisord", ["-c", configPath]);
11824
12907
  await waitForSupervisorControl(store, runtime);
11825
12908
  return;
@@ -11876,8 +12959,8 @@ stderr_logfile_backups=3
11876
12959
  async function restartSupervisorUserService(store, runtime) {
11877
12960
  const configPath = supervisorConfigPath(store);
11878
12961
  if (!await supervisorIsRunning(store, runtime)) {
11879
- await (0, import_promises8.rm)(supervisorSocketPath(store), { force: true });
11880
- await (0, import_promises8.rm)(supervisorPidPath(store), { force: true });
12962
+ await (0, import_promises10.rm)(supervisorSocketPath(store), { force: true });
12963
+ await (0, import_promises10.rm)(supervisorPidPath(store), { force: true });
11881
12964
  await runtime.run("supervisord", ["-c", configPath]);
11882
12965
  await waitForSupervisorControl(store, runtime);
11883
12966
  return;
@@ -11985,13 +13068,13 @@ function delay5(milliseconds) {
11985
13068
  setTimeout(resolvePromise, milliseconds);
11986
13069
  });
11987
13070
  }
11988
- var import_node_child_process5, import_promises8, import_node_os9, import_node_path13, import_node_util6, execFileAsync2, launchAgentLabel, supervisorProgramName, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
13071
+ var import_node_child_process5, import_promises10, import_node_os9, import_node_path13, import_node_util6, execFileAsync2, launchAgentLabel, supervisorProgramName, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
11989
13072
  var init_service_manager = __esm({
11990
13073
  "../machine-connector/dist/runtime/service-manager.js"() {
11991
13074
  "use strict";
11992
13075
  init_cjs_shims();
11993
13076
  import_node_child_process5 = require("child_process");
11994
- import_promises8 = require("fs/promises");
13077
+ import_promises10 = require("fs/promises");
11995
13078
  import_node_os9 = require("os");
11996
13079
  import_node_path13 = require("path");
11997
13080
  import_node_util6 = require("util");
@@ -12051,6 +13134,14 @@ async function runMachineCli(argumentsList, entrypoint) {
12051
13134
  await disconnectCommand(store, commandArguments);
12052
13135
  return;
12053
13136
  }
13137
+ if (command === "manager") {
13138
+ await runMachineManager(store, {
13139
+ run: async (managerArguments) => {
13140
+ await runMachineCli(managerArguments, entrypoint);
13141
+ }
13142
+ });
13143
+ return;
13144
+ }
12054
13145
  if (command === "daemon") {
12055
13146
  await daemonCommand(store);
12056
13147
  return;
@@ -12154,8 +13245,8 @@ async function statusCommand(store, argumentsList) {
12154
13245
  async function logsCommand(store, argumentsList) {
12155
13246
  const options = parseOptions(argumentsList);
12156
13247
  const lines = Number(options.lines ?? "100");
12157
- const normalLog = await readOptionalFile(store.runtimeLogPath());
12158
- const errorLog = await readOptionalFile(store.runtimeErrorLogPath());
13248
+ const normalLog = await readOptionalFile2(store.runtimeLogPath());
13249
+ const errorLog = await readOptionalFile2(store.runtimeErrorLogPath());
12159
13250
  writeLine([...normalLog.split("\n"), ...errorLog.split("\n")].filter((line) => line.length > 0).slice(-lines).join("\n"));
12160
13251
  }
12161
13252
  async function doctorCommand(store, argumentsList) {
@@ -12298,9 +13389,9 @@ async function waitForDaemonOnline(store) {
12298
13389
  }
12299
13390
  throw new Error("The service was installed but the Connector did not become online within 30 seconds");
12300
13391
  }
12301
- async function readOptionalFile(path10) {
13392
+ async function readOptionalFile2(path10) {
12302
13393
  try {
12303
- return await (0, import_promises9.readFile)(path10, "utf8");
13394
+ return await (0, import_promises11.readFile)(path10, "utf8");
12304
13395
  } catch {
12305
13396
  return "";
12306
13397
  }
@@ -12314,6 +13405,7 @@ Usage:
12314
13405
  moxt machine logs [--lines 100]
12315
13406
  moxt machine doctor [--json]
12316
13407
  moxt machine disconnect --connection <id> [--local-only]
13408
+ moxt machine manager
12317
13409
  moxt machine service install [--service-manager <auto|systemd|supervisor|none>]
12318
13410
  moxt machine service <restart|stop|uninstall>
12319
13411
  `);
@@ -12327,16 +13419,17 @@ function delay6(milliseconds) {
12327
13419
  setTimeout(resolvePromise, milliseconds);
12328
13420
  });
12329
13421
  }
12330
- var import_promises9, import_node_path14, defaultRelayOrigin;
13422
+ var import_promises11, import_node_path14, defaultRelayOrigin;
12331
13423
  var init_cli = __esm({
12332
13424
  "../machine-connector/dist/cli.js"() {
12333
13425
  "use strict";
12334
13426
  init_cjs_shims();
12335
- import_promises9 = require("fs/promises");
13427
+ import_promises11 = require("fs/promises");
12336
13428
  import_node_path14 = require("path");
12337
13429
  init_daemon();
12338
13430
  init_doctor();
12339
13431
  init_local_ipc();
13432
+ init_machine_manager();
12340
13433
  init_pairing();
12341
13434
  init_relay_client();
12342
13435
  init_service_manager();
@@ -12350,6 +13443,7 @@ var dist_exports = {};
12350
13443
  __export(dist_exports, {
12351
13444
  DoctorCheckStatus: () => DoctorCheckStatus,
12352
13445
  LocalIpcServer: () => LocalIpcServer,
13446
+ MachineClaudePermissionMode: () => MachineClaudePermissionMode,
12353
13447
  MachineCodexPermissionMode: () => MachineCodexPermissionMode,
12354
13448
  MachineConnectionStatus: () => MachineConnectionStatus,
12355
13449
  MachineConnectionTargetKind: () => MachineConnectionTargetKind,
@@ -12360,6 +13454,9 @@ __export(dist_exports, {
12360
13454
  MachineJobOutputStream: () => MachineJobOutputStream,
12361
13455
  MachineJobStatus: () => MachineJobStatus,
12362
13456
  MachineJobWakeReason: () => MachineJobWakeReason,
13457
+ MachineManagerAction: () => MachineManagerAction,
13458
+ MachineManagerSnapshotDepth: () => MachineManagerSnapshotDepth,
13459
+ MachineManagerView: () => MachineManagerView,
12363
13460
  MachineOperatingSystem: () => MachineOperatingSystem,
12364
13461
  MachinePairingDecision: () => MachinePairingDecision,
12365
13462
  MachinePairingStatus: () => MachinePairingStatus,
@@ -12379,20 +13476,27 @@ __export(dist_exports, {
12379
13476
  assertRelativeWorkingDirectory: () => assertRelativeWorkingDirectory,
12380
13477
  assertValidJobTransition: () => assertValidJobTransition,
12381
13478
  assertWaitTimeout: () => assertWaitTimeout,
13479
+ collectMachineManagerSnapshot: () => collectMachineManagerSnapshot,
12382
13480
  createServiceEnvironment: () => createServiceEnvironment,
12383
13481
  createSupervisorConfiguration: () => createSupervisorConfiguration,
12384
13482
  defaultRuntimeDirectory: () => defaultRuntimeDirectory,
12385
13483
  detectServiceManagerCapabilities: () => detectServiceManagerCapabilities,
13484
+ ensureInteractiveTerminal: () => ensureInteractiveTerminal,
13485
+ executeClaudeReply: () => executeClaudeReply,
13486
+ executeClaudeStart: () => executeClaudeStart,
12386
13487
  installUserService: () => installUserService,
12387
13488
  isTerminalJobStatus: () => isTerminalJobStatus,
13489
+ machineManagerActions: () => machineManagerActions,
12388
13490
  machineProtocolVersion: () => machineProtocolVersion,
12389
13491
  pairMachine: () => pairMachine,
12390
13492
  parseServiceManagerPreference: () => parseServiceManagerPreference,
13493
+ renderMachineManager: () => renderMachineManager,
12391
13494
  requestRuntimeStatus: () => requestRuntimeStatus,
12392
13495
  resolveWorkingDirectory: () => resolveWorkingDirectory,
12393
13496
  restartUserService: () => restartUserService,
12394
13497
  runMachineCli: () => runMachineCli,
12395
13498
  runMachineDoctor: () => runMachineDoctor,
13499
+ runMachineManager: () => runMachineManager,
12396
13500
  selectUserServiceManager: () => selectUserServiceManager,
12397
13501
  stopUserService: () => stopUserService,
12398
13502
  uninstallUserService: () => uninstallUserService,
@@ -12405,8 +13509,10 @@ var init_dist = __esm({
12405
13509
  init_v1();
12406
13510
  init_cli();
12407
13511
  init_daemon();
13512
+ init_claude_executor();
12408
13513
  init_doctor();
12409
13514
  init_local_ipc();
13515
+ init_machine_manager();
12410
13516
  init_pairing();
12411
13517
  init_relay_client();
12412
13518
  init_runtime_types();
@@ -16067,7 +17173,7 @@ function getApiKeyOrUndefined() {
16067
17173
 
16068
17174
  // src/utils/http.ts
16069
17175
  function getUserAgent() {
16070
- return `moxt-cli/${"0.8.0-beta.0"} (${(0, import_os2.platform)()}/${(0, import_os2.arch)()}) node/${process.versions.node}`;
17176
+ return `moxt-cli/${"0.8.0-beta.1"} (${(0, import_os2.platform)()}/${(0, import_os2.arch)()}) node/${process.versions.node}`;
16071
17177
  }
16072
17178
  async function fetchApi(method, path10, body) {
16073
17179
  const apiKey = getApiKey();
@@ -16754,9 +17860,9 @@ function registerMachineCommand(program3) {
16754
17860
  "--root",
16755
17861
  options.root ?? process.cwd()
16756
17862
  ];
16757
- appendOption(argumentsList, "--relay", options.relay);
16758
- appendOption(argumentsList, "--name", options.name);
16759
- appendOption(
17863
+ appendOption2(argumentsList, "--relay", options.relay);
17864
+ appendOption2(argumentsList, "--name", options.name);
17865
+ appendOption2(
16760
17866
  argumentsList,
16761
17867
  "--service-manager",
16762
17868
  options.serviceManager
@@ -16773,11 +17879,7 @@ function registerMachineCommand(program3) {
16773
17879
  ]);
16774
17880
  });
16775
17881
  machine.command("logs").description("Show recent Connector logs").option("--lines <count>", "Number of lines", "100").action(async (options) => {
16776
- await runConnectorCli([
16777
- "logs",
16778
- "--lines",
16779
- options.lines ?? "100"
16780
- ]);
17882
+ await runConnectorCli(["logs", "--lines", options.lines ?? "100"]);
16781
17883
  });
16782
17884
  machine.command("doctor").description("Diagnose the Local Machine connection").option("--json", "Emit machine-readable JSON").action(async (options) => {
16783
17885
  await runConnectorCli([
@@ -16799,6 +17901,9 @@ function registerMachineCommand(program3) {
16799
17901
  }
16800
17902
  await runConnectorCli(argumentsList);
16801
17903
  });
17904
+ machine.command("manager").description("Open the interactive Local Machine manager").action(async () => {
17905
+ await runConnectorCli(["manager"]);
17906
+ });
16802
17907
  machine.command("service").description("Manage the user-level Connector service").argument("<action>", "install, restart, stop, or uninstall").addOption(
16803
17908
  new Option(
16804
17909
  "--service-manager <manager>",
@@ -16806,7 +17911,7 @@ function registerMachineCommand(program3) {
16806
17911
  ).choices(["auto", "systemd", "supervisor", "none"]).default("auto")
16807
17912
  ).action(async (action, options) => {
16808
17913
  const argumentsList = ["service", action];
16809
- appendOption(
17914
+ appendOption2(
16810
17915
  argumentsList,
16811
17916
  "--service-manager",
16812
17917
  options.serviceManager
@@ -16826,7 +17931,7 @@ async function runConnectorCli(argumentsList) {
16826
17931
  nodePath: process.execPath
16827
17932
  });
16828
17933
  }
16829
- function appendOption(argumentsList, flag, value) {
17934
+ function appendOption2(argumentsList, flag, value) {
16830
17935
  if (value) {
16831
17936
  argumentsList.push(flag, value);
16832
17937
  }
@@ -18229,7 +19334,7 @@ var FLUSH_TIMEOUT_MS = 3e3;
18229
19334
  var MAX_BATCH_SIZE = 100;
18230
19335
  function commonLabels() {
18231
19336
  return {
18232
- cli_version: "0.8.0-beta.0",
19337
+ cli_version: "0.8.0-beta.1",
18233
19338
  node_version: process.versions.node,
18234
19339
  os: (0, import_node_os10.platform)(),
18235
19340
  arch: (0, import_node_os10.arch)(),
@@ -18275,7 +19380,7 @@ async function flush() {
18275
19380
  }
18276
19381
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
18277
19382
  const payload = {
18278
- release_id: "0.8.0-beta.0",
19383
+ release_id: "0.8.0-beta.1",
18279
19384
  client_type: "cli",
18280
19385
  metric_data_list: batch.map((m) => ({
18281
19386
  profile: "cli",
@@ -18420,9 +19525,9 @@ function installExitHandler() {
18420
19525
 
18421
19526
  // src/index.ts
18422
19527
  updateNotifier({
18423
- pkg: { name: "@moxt-ai/cli", version: "0.8.0-beta.0" }
19528
+ pkg: { name: "@moxt-ai/cli", version: "0.8.0-beta.1" }
18424
19529
  }).notify();
18425
- var program2 = createProgram("0.8.0-beta.0");
19530
+ var program2 = createProgram("0.8.0-beta.1");
18426
19531
  instrumentProgram(program2);
18427
19532
  installExitHandler();
18428
19533
  program2.parseAsync(process.argv).then(async () => {