@moxt-ai/cli 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3787,8 +3787,8 @@ var require_common = __commonJS({
3787
3787
  }
3788
3788
  return debug2;
3789
3789
  }
3790
- function extend(namespace, delimiter2) {
3791
- const newDebug = createDebug(this.namespace + (typeof delimiter2 === "undefined" ? ":" : delimiter2) + namespace);
3790
+ function extend(namespace, delimiter3) {
3791
+ const newDebug = createDebug(this.namespace + (typeof delimiter3 === "undefined" ? ":" : delimiter3) + namespace);
3792
3792
  newDebug.log = this.log;
3793
3793
  return newDebug;
3794
3794
  }
@@ -4495,10 +4495,6 @@ var init_v1 = __esm({
4495
4495
  });
4496
4496
 
4497
4497
  // ../machine-connector/dist/runtime/process-executor.js
4498
- async function executeCommand(rootPath, spec, callbacks) {
4499
- const workingDirectory = await resolveCanonicalWorkingDirectory(rootPath, spec.relativeWorkingDirectory);
4500
- return await executeProcess(spec.executable, spec.arguments, workingDirectory, spec.environment, spec.stdin, spec.timeoutSeconds, callbacks);
4501
- }
4502
4498
  async function executeProcess(executable, argumentsList, workingDirectory, environment, stdin, timeoutSeconds, callbacks) {
4503
4499
  if (callbacks.canSpawn && !callbacks.canSpawn()) {
4504
4500
  return {
@@ -4509,7 +4505,7 @@ async function executeProcess(executable, argumentsList, workingDirectory, envir
4509
4505
  const child = (0, import_node_child_process.spawn)(executable, argumentsList, {
4510
4506
  cwd: workingDirectory,
4511
4507
  detached: (0, import_node_os.platform)() !== "win32",
4512
- env: buildChildEnvironment(environment),
4508
+ env: { ...environment },
4513
4509
  shell: false,
4514
4510
  stdio: ["pipe", "pipe", "pipe"],
4515
4511
  windowsHide: true
@@ -4641,19 +4637,6 @@ async function executeProcess(executable, argumentsList, workingDirectory, envir
4641
4637
  status: processExit.exitCode === 0 ? MachineJobStatus.Succeeded : MachineJobStatus.Failed
4642
4638
  };
4643
4639
  }
4644
- function buildChildEnvironment(overrides) {
4645
- const environment = {};
4646
- for (const [name, value] of Object.entries(process.env)) {
4647
- if (name === "MOXT_MACHINE_ACCESS_TOKEN" || name === "MOXT_MACHINE_REFRESH_TOKEN" || name === "MOXT_MACHINE_DEVICE_PRIVATE_KEY" || name === "MOXT_API_TOKEN" || name === "MOXT_CLI_TOKEN") {
4648
- continue;
4649
- }
4650
- environment[name] = value;
4651
- }
4652
- return {
4653
- ...environment,
4654
- ...overrides
4655
- };
4656
- }
4657
4640
  async function resolveCanonicalWorkingDirectory(rootPath, relativeWorkingDirectory) {
4658
4641
  const canonicalRoot = await (0, import_promises3.realpath)(rootPath);
4659
4642
  const lexicalCandidate = resolveWorkingDirectory(canonicalRoot, relativeWorkingDirectory);
@@ -4767,9 +4750,9 @@ var init_process_executor = __esm({
4767
4750
  });
4768
4751
 
4769
4752
  // ../machine-connector/dist/runtime/claude-executor.js
4770
- async function executeClaudeStart(workingDirectory, spec, callbacks) {
4753
+ async function executeClaudeStart(workingDirectory, environment, spec, callbacks) {
4771
4754
  const sessionId = (0, import_node_crypto.randomUUID)();
4772
- return await executeClaude(workingDirectory, [
4755
+ return await executeClaude(workingDirectory, environment, [
4773
4756
  "--print",
4774
4757
  "--output-format",
4775
4758
  "stream-json",
@@ -4779,8 +4762,8 @@ async function executeClaudeStart(workingDirectory, spec, callbacks) {
4779
4762
  sessionId
4780
4763
  ], spec.prompt, sessionId, callbacks);
4781
4764
  }
4782
- async function executeClaudeReply(workingDirectory, spec, callbacks) {
4783
- return await executeClaude(workingDirectory, [
4765
+ async function executeClaudeReply(workingDirectory, environment, spec, callbacks) {
4766
+ return await executeClaude(workingDirectory, environment, [
4784
4767
  "--print",
4785
4768
  "--output-format",
4786
4769
  "stream-json",
@@ -4790,7 +4773,7 @@ async function executeClaudeReply(workingDirectory, spec, callbacks) {
4790
4773
  spec.threadId
4791
4774
  ], spec.prompt, spec.threadId, callbacks);
4792
4775
  }
4793
- async function executeClaude(workingDirectory, argumentsList, prompt, expectedSessionId, callbacks) {
4776
+ async function executeClaude(workingDirectory, environment, argumentsList, prompt, expectedSessionId, callbacks) {
4794
4777
  const metadata = {
4795
4778
  threadId: expectedSessionId
4796
4779
  };
@@ -4811,7 +4794,7 @@ async function executeClaude(workingDirectory, argumentsList, prompt, expectedSe
4811
4794
  },
4812
4795
  onSpawn: callbacks.onSpawn
4813
4796
  };
4814
- const result = await executeProcess(process.env.MOXT_CLAUDE_PATH ?? "claude", argumentsList, workingDirectory, {}, prompt, 43200, processCallbacks);
4797
+ const result = await executeProcess(process.env.MOXT_CLAUDE_PATH ?? "claude", argumentsList, workingDirectory, environment, prompt, 43200, processCallbacks);
4815
4798
  if (bufferedStdout.trim().length > 0) {
4816
4799
  await processClaudeLine(bufferedStdout, metadata, callbacks);
4817
4800
  }
@@ -4866,10 +4849,122 @@ var init_claude_executor = __esm({
4866
4849
  }
4867
4850
  });
4868
4851
 
4852
+ // ../machine-connector/dist/runtime/command-output-batcher.js
4853
+ function takeUtf8Head(text3, maxBytes) {
4854
+ const bytes = Buffer.from(text3, "utf8");
4855
+ if (bytes.length <= maxBytes) {
4856
+ return text3;
4857
+ }
4858
+ let end = maxBytes;
4859
+ while (end > 0 && (bytes[end] & 192) === 128) {
4860
+ end -= 1;
4861
+ }
4862
+ return bytes.subarray(0, end).toString("utf8");
4863
+ }
4864
+ var CommandOutputBatcher;
4865
+ var init_command_output_batcher = __esm({
4866
+ "../machine-connector/dist/runtime/command-output-batcher.js"() {
4867
+ "use strict";
4868
+ init_cjs_shims();
4869
+ CommandOutputBatcher = class {
4870
+ options;
4871
+ buffer;
4872
+ failure;
4873
+ flushTimer;
4874
+ writeQueue = Promise.resolve();
4875
+ constructor(options) {
4876
+ this.options = options;
4877
+ if (!Number.isInteger(options.flushIntervalMilliseconds) || options.flushIntervalMilliseconds <= 0) {
4878
+ throw new Error("Command output flush interval must be a positive integer");
4879
+ }
4880
+ if (!Number.isInteger(options.maxBytes) || options.maxBytes < 4) {
4881
+ throw new Error("Command output batch size must be at least four bytes");
4882
+ }
4883
+ }
4884
+ async append(stream, text3) {
4885
+ if (text3.length === 0) {
4886
+ return;
4887
+ }
4888
+ await this.enqueue(async () => {
4889
+ this.throwIfFailed();
4890
+ if (this.buffer !== void 0 && this.buffer.stream !== stream) {
4891
+ await this.flushBuffer();
4892
+ }
4893
+ let remaining = text3;
4894
+ while (remaining.length > 0) {
4895
+ const buffer2 = this.buffer ?? { bytes: 0, stream, text: "" };
4896
+ this.buffer = buffer2;
4897
+ const segment = takeUtf8Head(remaining, this.options.maxBytes - buffer2.bytes);
4898
+ if (segment.length === 0) {
4899
+ await this.flushBuffer();
4900
+ continue;
4901
+ }
4902
+ buffer2.text += segment;
4903
+ buffer2.bytes += Buffer.byteLength(segment, "utf8");
4904
+ remaining = remaining.slice(segment.length);
4905
+ if (buffer2.bytes === this.options.maxBytes) {
4906
+ await this.flushBuffer();
4907
+ }
4908
+ }
4909
+ this.scheduleFlush();
4910
+ });
4911
+ }
4912
+ async flush() {
4913
+ this.clearFlushTimer();
4914
+ await this.enqueue(async () => {
4915
+ this.throwIfFailed();
4916
+ await this.flushBuffer();
4917
+ });
4918
+ }
4919
+ clearFlushTimer() {
4920
+ if (this.flushTimer === void 0) {
4921
+ return;
4922
+ }
4923
+ clearTimeout(this.flushTimer);
4924
+ this.flushTimer = void 0;
4925
+ }
4926
+ enqueue(operation) {
4927
+ const nextWrite = this.writeQueue.then(operation);
4928
+ this.writeQueue = nextWrite.catch((error) => {
4929
+ this.failure ??= error;
4930
+ });
4931
+ return nextWrite;
4932
+ }
4933
+ async flushBuffer() {
4934
+ this.clearFlushTimer();
4935
+ const buffer2 = this.buffer;
4936
+ if (buffer2 === void 0) {
4937
+ return;
4938
+ }
4939
+ await this.options.write(buffer2.stream, buffer2.text);
4940
+ this.buffer = void 0;
4941
+ }
4942
+ scheduleFlush() {
4943
+ if (this.buffer === void 0 || this.flushTimer !== void 0) {
4944
+ return;
4945
+ }
4946
+ this.flushTimer = setTimeout(() => {
4947
+ this.flushTimer = void 0;
4948
+ void this.enqueue(async () => {
4949
+ this.throwIfFailed();
4950
+ await this.flushBuffer();
4951
+ }).catch(() => void 0);
4952
+ }, this.options.flushIntervalMilliseconds);
4953
+ this.flushTimer.unref();
4954
+ }
4955
+ throwIfFailed() {
4956
+ if (this.failure !== void 0) {
4957
+ throw this.failure;
4958
+ }
4959
+ }
4960
+ };
4961
+ }
4962
+ });
4963
+
4869
4964
  // ../machine-connector/dist/runtime/codex-executor.js
4870
- async function executeCodexStart(workingDirectory, runtimeDirectory, spec, callbacks) {
4965
+ async function executeCodexStart(workingDirectory, runtimeDirectory, environment, spec, callbacks) {
4871
4966
  const outputPath = createOutputPath(runtimeDirectory);
4872
- return await executeCodex(workingDirectory, outputPath, [
4967
+ return await executeCodex(workingDirectory, outputPath, environment, [
4873
4968
  "exec",
4874
4969
  "--json",
4875
4970
  "--dangerously-bypass-approvals-and-sandbox",
@@ -4879,9 +4974,9 @@ async function executeCodexStart(workingDirectory, runtimeDirectory, spec, callb
4879
4974
  "-"
4880
4975
  ], spec.prompt, callbacks);
4881
4976
  }
4882
- async function executeCodexReply(workingDirectory, runtimeDirectory, spec, callbacks) {
4977
+ async function executeCodexReply(workingDirectory, runtimeDirectory, environment, spec, callbacks) {
4883
4978
  const outputPath = createOutputPath(runtimeDirectory);
4884
- return await executeCodex(workingDirectory, outputPath, [
4979
+ return await executeCodex(workingDirectory, outputPath, environment, [
4885
4980
  "exec",
4886
4981
  "resume",
4887
4982
  "--json",
@@ -4893,7 +4988,7 @@ async function executeCodexReply(workingDirectory, runtimeDirectory, spec, callb
4893
4988
  "-"
4894
4989
  ], spec.prompt, callbacks);
4895
4990
  }
4896
- async function executeCodex(workingDirectory, outputPath, argumentsList, prompt, callbacks) {
4991
+ async function executeCodex(workingDirectory, outputPath, environment, argumentsList, prompt, callbacks) {
4897
4992
  const executionMetadata = {};
4898
4993
  const turnCompletion = createCodexTurnCompletion();
4899
4994
  let bufferedStdout = "";
@@ -4926,7 +5021,7 @@ async function executeCodex(workingDirectory, outputPath, argumentsList, prompt,
4926
5021
  return result2;
4927
5022
  })
4928
5023
  };
4929
- const result = await executeProcess(process.env.MOXT_CODEX_PATH ?? "codex", argumentsList, workingDirectory, {}, prompt, 43200, processCallbacks);
5024
+ const result = await executeProcess(process.env.MOXT_CODEX_PATH ?? "codex", argumentsList, workingDirectory, environment, prompt, 43200, processCallbacks);
4930
5025
  if (bufferedStdout.trim().length > 0) {
4931
5026
  const event = parseCodexEvent(bufferedStdout).value;
4932
5027
  if (event !== void 0) {
@@ -5238,6 +5333,7 @@ var init_execution_cancellation = __esm({
5238
5333
  ExecutionCancellationReason2["Stopping"] = "stopping";
5239
5334
  })(ExecutionCancellationReason || (ExecutionCancellationReason = {}));
5240
5335
  ExecutionCancellation = class {
5336
+ abortController = new AbortController();
5241
5337
  handle;
5242
5338
  reason;
5243
5339
  requested;
@@ -5253,6 +5349,9 @@ var init_execution_cancellation = __esm({
5253
5349
  currentReason() {
5254
5350
  return this.reason;
5255
5351
  }
5352
+ signal() {
5353
+ return this.abortController.signal;
5354
+ }
5256
5355
  register(handle) {
5257
5356
  this.handle = handle;
5258
5357
  if (this.reason !== void 0) {
@@ -5269,6 +5368,7 @@ var init_execution_cancellation = __esm({
5269
5368
  async request(reason) {
5270
5369
  if (this.reason === void 0) {
5271
5370
  this.reason = reason;
5371
+ this.abortController.abort(reason);
5272
5372
  this.resolveRequested(reason);
5273
5373
  }
5274
5374
  if (this.handle) {
@@ -5555,6 +5655,12 @@ var init_image_viewer = __esm({
5555
5655
 
5556
5656
  // ../machine-connector/dist/runtime/local-ipc.js
5557
5657
  async function requestRuntimeStatus(store, timeoutMilliseconds = 1e3) {
5658
+ return await requestLocalIpc(store, "status", timeoutMilliseconds);
5659
+ }
5660
+ async function requestEnvironmentRefresh(store, timeoutMilliseconds = 1e4) {
5661
+ return await requestLocalIpc(store, "environment_refresh", timeoutMilliseconds);
5662
+ }
5663
+ async function requestLocalIpc(store, action, timeoutMilliseconds) {
5558
5664
  return await new Promise((resolvePromise, rejectPromise) => {
5559
5665
  const socket = (0, import_node_net.createConnection)(store.runtimeSocketPath());
5560
5666
  let responseText = "";
@@ -5574,7 +5680,7 @@ async function requestRuntimeStatus(store, timeoutMilliseconds = 1e3) {
5574
5680
  }
5575
5681
  });
5576
5682
  socket.once("connect", () => {
5577
- socket.write(`${JSON.stringify({ action: "status" })}
5683
+ socket.write(`${JSON.stringify({ action })}
5578
5684
  `);
5579
5685
  });
5580
5686
  });
@@ -5590,10 +5696,12 @@ var init_local_ipc = __esm({
5590
5696
  LocalIpcServer = class {
5591
5697
  store;
5592
5698
  getStatus;
5699
+ refreshEnvironment;
5593
5700
  server;
5594
- constructor(store, getStatus) {
5701
+ constructor(store, getStatus, refreshEnvironment) {
5595
5702
  this.store = store;
5596
5703
  this.getStatus = getStatus;
5704
+ this.refreshEnvironment = refreshEnvironment;
5597
5705
  }
5598
5706
  async start() {
5599
5707
  const socketPath = this.store.runtimeSocketPath();
@@ -5602,15 +5710,18 @@ var init_local_ipc = __esm({
5602
5710
  }
5603
5711
  this.server = (0, import_node_net.createServer)((socket) => {
5604
5712
  let requestText = "";
5713
+ let handled = false;
5605
5714
  socket.setEncoding("utf8");
5606
5715
  socket.on("data", (chunk) => {
5607
5716
  requestText += chunk;
5608
- if (!requestText.includes("\n")) {
5717
+ if (handled || !requestText.includes("\n")) {
5609
5718
  return;
5610
5719
  }
5611
- const response = this.handleRequest(requestText);
5612
- socket.end(`${JSON.stringify(response)}
5720
+ handled = true;
5721
+ void this.handleRequest(requestText).then((response) => {
5722
+ socket.end(`${JSON.stringify(response)}
5613
5723
  `);
5724
+ });
5614
5725
  });
5615
5726
  });
5616
5727
  await new Promise((resolvePromise, rejectPromise) => {
@@ -5632,12 +5743,20 @@ var init_local_ipc = __esm({
5632
5743
  await (0, import_promises6.rm)(this.store.runtimeSocketPath(), { force: true });
5633
5744
  }
5634
5745
  }
5635
- handleRequest(requestText) {
5746
+ async handleRequest(requestText) {
5636
5747
  try {
5637
5748
  const request2 = JSON.parse(requestText.trim());
5638
5749
  if (request2.action === "status") {
5639
5750
  return { status: this.getStatus() };
5640
5751
  }
5752
+ if (request2.action === "environment_refresh") {
5753
+ if (!this.refreshEnvironment) {
5754
+ return { error: "Environment refresh is unavailable" };
5755
+ }
5756
+ return {
5757
+ environmentRefresh: await this.refreshEnvironment()
5758
+ };
5759
+ }
5641
5760
  return { error: `Unsupported IPC action: ${request2.action}` };
5642
5761
  } catch (error) {
5643
5762
  return {
@@ -5973,6 +6092,483 @@ var init_process_lock = __esm({
5973
6092
  }
5974
6093
  });
5975
6094
 
6095
+ // ../machine-connector/dist/runtime/shell-environment.js
6096
+ function sanitizeEnvironment(source) {
6097
+ const environment = createEnvironmentMap();
6098
+ for (const [name, value] of Object.entries(source)) {
6099
+ if (value === void 0 || isConnectorCredentialName(name)) {
6100
+ continue;
6101
+ }
6102
+ environment[name] = value;
6103
+ }
6104
+ return environment;
6105
+ }
6106
+ function parseNullSeparatedEnvironment(output) {
6107
+ if (output.length === 0 || output.at(-1) !== 0) {
6108
+ throw new Error("shell_environment_malformed");
6109
+ }
6110
+ const text3 = decodeUtf8(output, "shell_environment_malformed");
6111
+ const environment = createEnvironmentMap();
6112
+ const frames2 = text3.slice(0, -1).split("\0");
6113
+ for (const frame of frames2) {
6114
+ const separator = frame.indexOf("=");
6115
+ const name = frame.slice(0, separator);
6116
+ if (separator <= 0 || !environmentNamePattern.test(name) || Object.hasOwn(environment, name)) {
6117
+ throw new Error("shell_environment_malformed");
6118
+ }
6119
+ environment[name] = frame.slice(separator + 1);
6120
+ }
6121
+ return environment;
6122
+ }
6123
+ function parseDirenvJson(text3) {
6124
+ try {
6125
+ let index2 = skipWhitespace(text3, 0);
6126
+ if (text3[index2] !== "{")
6127
+ throw new Error("object expected");
6128
+ index2 = skipWhitespace(text3, index2 + 1);
6129
+ const exports2 = createEnvironmentMap();
6130
+ if (text3[index2] === "}") {
6131
+ index2 = skipWhitespace(text3, index2 + 1);
6132
+ if (index2 !== text3.length)
6133
+ throw new Error("trailing input");
6134
+ return exports2;
6135
+ }
6136
+ while (index2 < text3.length) {
6137
+ const key = readJsonString(text3, index2);
6138
+ if (!environmentNamePattern.test(key.value) || Object.hasOwn(exports2, key.value)) {
6139
+ throw new Error("invalid or duplicate key");
6140
+ }
6141
+ index2 = skipWhitespace(text3, key.next);
6142
+ if (text3[index2] !== ":")
6143
+ throw new Error("colon expected");
6144
+ index2 = skipWhitespace(text3, index2 + 1);
6145
+ if (text3.startsWith("null", index2)) {
6146
+ exports2[key.value] = null;
6147
+ index2 += 4;
6148
+ } else {
6149
+ const value = readJsonString(text3, index2);
6150
+ exports2[key.value] = value.value;
6151
+ index2 = value.next;
6152
+ }
6153
+ index2 = skipWhitespace(text3, index2);
6154
+ if (text3[index2] === "}") {
6155
+ index2 = skipWhitespace(text3, index2 + 1);
6156
+ if (index2 !== text3.length)
6157
+ throw new Error("trailing input");
6158
+ return exports2;
6159
+ }
6160
+ if (text3[index2] !== ",")
6161
+ throw new Error("comma expected");
6162
+ index2 = skipWhitespace(text3, index2 + 1);
6163
+ }
6164
+ throw new Error("unterminated object");
6165
+ } catch {
6166
+ throw new Error("direnv_malformed");
6167
+ }
6168
+ }
6169
+ function sanitizeDirenvExports(source) {
6170
+ const exports2 = createEnvironmentMap();
6171
+ for (const [name, value] of Object.entries(source)) {
6172
+ if (!isConnectorCredentialName(name)) {
6173
+ exports2[name] = value;
6174
+ }
6175
+ }
6176
+ return exports2;
6177
+ }
6178
+ function isConnectorCredentialName(name) {
6179
+ if (name === "MOXT_API_TOKEN" || name === "MOXT_CLI_TOKEN")
6180
+ return true;
6181
+ return name.startsWith("MOXT_MACHINE_") && /(?:^|_)(?:TOKEN|SECRET|CREDENTIALS?|PASSWORD|PRIVATE_KEY)(?:_|$)/.test(name.slice("MOXT_MACHINE_".length));
6182
+ }
6183
+ async function validateShell(shellPath) {
6184
+ if (!(0, import_node_path6.isAbsolute)(shellPath))
6185
+ throw new Error("default shell is not absolute");
6186
+ const canonicalPath = await validateExecutable(shellPath);
6187
+ const shellName = (0, import_node_path6.basename)(canonicalPath);
6188
+ if (shellName !== "bash" && shellName !== "zsh") {
6189
+ throw new Error("default shell is not Bash or Zsh");
6190
+ }
6191
+ return canonicalPath;
6192
+ }
6193
+ async function validateExecutable(path4) {
6194
+ const canonicalPath = await (0, import_promises8.realpath)(path4);
6195
+ const metadata = await (0, import_promises8.stat)(canonicalPath);
6196
+ if (!metadata.isFile())
6197
+ throw new Error("executable is not a regular file");
6198
+ await (0, import_promises8.access)(canonicalPath, import_promises8.constants.X_OK);
6199
+ return canonicalPath;
6200
+ }
6201
+ async function findExecutable(name, pathValue) {
6202
+ for (const directory of (pathValue ?? "").split(import_node_path6.delimiter)) {
6203
+ if (!(0, import_node_path6.isAbsolute)(directory))
6204
+ continue;
6205
+ try {
6206
+ const candidate = await validateExecutable((0, import_node_path6.join)(directory, name));
6207
+ if ((0, import_node_path6.basename)(candidate) === name)
6208
+ return candidate;
6209
+ } catch {
6210
+ }
6211
+ }
6212
+ return void 0;
6213
+ }
6214
+ async function findNearestEnvrc(canonicalRoot, canonicalWorkingDirectory) {
6215
+ let directory = canonicalWorkingDirectory;
6216
+ while (true) {
6217
+ const candidate = (0, import_node_path6.join)(directory, ".envrc");
6218
+ try {
6219
+ const metadata = await (0, import_promises8.stat)(candidate);
6220
+ if (!metadata.isFile()) {
6221
+ throw new JobEnvironmentError("direnv_malformed");
6222
+ }
6223
+ return candidate;
6224
+ } catch (error) {
6225
+ if (!isNodeError(error, "ENOENT"))
6226
+ throw error;
6227
+ }
6228
+ if (directory === canonicalRoot)
6229
+ return void 0;
6230
+ const parent = (0, import_node_path6.dirname)(directory);
6231
+ if (parent === directory)
6232
+ return void 0;
6233
+ directory = parent;
6234
+ }
6235
+ }
6236
+ async function executeBounded(options) {
6237
+ if (options.cancellationSignal?.aborted) {
6238
+ return {
6239
+ exitCode: -1,
6240
+ outcome: "cancelled",
6241
+ stderr: Buffer.alloc(0),
6242
+ stdout: Buffer.alloc(0)
6243
+ };
6244
+ }
6245
+ return await new Promise((resolvePromise) => {
6246
+ const child = (0, import_node_child_process2.spawn)(options.executable, options.argumentsList, {
6247
+ cwd: options.cwd,
6248
+ detached: (0, import_node_os3.platform)() !== "win32",
6249
+ env: options.environment,
6250
+ shell: false,
6251
+ stdio: ["ignore", "pipe", "pipe"],
6252
+ windowsHide: true
6253
+ });
6254
+ const stdout = [];
6255
+ const stderr = [];
6256
+ let bytes = 0;
6257
+ let outcome = "completed";
6258
+ let settled = false;
6259
+ let timeout;
6260
+ const finish = (exitCode) => {
6261
+ if (settled)
6262
+ return;
6263
+ settled = true;
6264
+ if (timeout)
6265
+ clearTimeout(timeout);
6266
+ options.cancellationSignal?.removeEventListener("abort", cancel);
6267
+ resolvePromise({
6268
+ exitCode,
6269
+ outcome,
6270
+ stderr: Buffer.concat(stderr),
6271
+ stdout: Buffer.concat(stdout)
6272
+ });
6273
+ };
6274
+ const terminateAndFinish = (terminalOutcome) => {
6275
+ if (settled || outcome !== "completed")
6276
+ return;
6277
+ outcome = terminalOutcome;
6278
+ terminateBoundedProcess(child.pid);
6279
+ child.stdout.destroy();
6280
+ child.stderr.destroy();
6281
+ finish(-1);
6282
+ };
6283
+ function cancel() {
6284
+ terminateAndFinish("cancelled");
6285
+ }
6286
+ const capture = (target) => (chunk) => {
6287
+ if (outcome !== "completed")
6288
+ return;
6289
+ bytes += chunk.length;
6290
+ if (bytes > options.outputLimitBytes) {
6291
+ terminateAndFinish("overflow");
6292
+ return;
6293
+ }
6294
+ target.push(Buffer.from(chunk));
6295
+ };
6296
+ child.stdout.on("data", capture(stdout));
6297
+ child.stderr.on("data", capture(stderr));
6298
+ child.once("error", () => {
6299
+ outcome = "spawn_failed";
6300
+ finish(-1);
6301
+ });
6302
+ child.once("close", (exitCode) => finish(exitCode ?? -1));
6303
+ timeout = setTimeout(() => terminateAndFinish("timeout"), options.timeoutMilliseconds);
6304
+ timeout.unref();
6305
+ options.cancellationSignal?.addEventListener("abort", cancel, {
6306
+ once: true
6307
+ });
6308
+ if (options.cancellationSignal?.aborted)
6309
+ cancel();
6310
+ });
6311
+ }
6312
+ function throwIfCancelled(signal) {
6313
+ if (signal?.aborted)
6314
+ throw new JobEnvironmentCancelledError();
6315
+ }
6316
+ function terminateBoundedProcess(pid) {
6317
+ if (pid === void 0)
6318
+ return;
6319
+ try {
6320
+ process.kill((0, import_node_os3.platform)() === "win32" ? pid : -pid, "SIGKILL");
6321
+ } catch (error) {
6322
+ if (isNodeError(error, "ESRCH"))
6323
+ return;
6324
+ try {
6325
+ process.kill(pid, "SIGKILL");
6326
+ } catch {
6327
+ }
6328
+ }
6329
+ }
6330
+ function readJsonString(text3, start) {
6331
+ if (text3[start] !== '"')
6332
+ throw new Error("string expected");
6333
+ let escaped = false;
6334
+ for (let index2 = start + 1; index2 < text3.length; index2 += 1) {
6335
+ const character = text3[index2];
6336
+ if (escaped) {
6337
+ escaped = false;
6338
+ continue;
6339
+ }
6340
+ if (character === "\\") {
6341
+ escaped = true;
6342
+ continue;
6343
+ }
6344
+ if (character === '"') {
6345
+ return {
6346
+ next: index2 + 1,
6347
+ value: JSON.parse(text3.slice(start, index2 + 1))
6348
+ };
6349
+ }
6350
+ }
6351
+ throw new Error("unterminated string");
6352
+ }
6353
+ function skipWhitespace(text3, start) {
6354
+ let index2 = start;
6355
+ while (/\s/.test(text3[index2] ?? ""))
6356
+ index2 += 1;
6357
+ return index2;
6358
+ }
6359
+ function decodeUtf8(value, category) {
6360
+ try {
6361
+ return new TextDecoder("utf-8", { fatal: true }).decode(value);
6362
+ } catch {
6363
+ throw new Error(category);
6364
+ }
6365
+ }
6366
+ function freezeEnvironment(environment) {
6367
+ return Object.freeze({ ...environment });
6368
+ }
6369
+ function createEnvironmentMap() {
6370
+ return /* @__PURE__ */ Object.create(null);
6371
+ }
6372
+ function degradedCapture(category) {
6373
+ return { status: { category, state: "degraded" } };
6374
+ }
6375
+ function isNodeError(error, code) {
6376
+ return error instanceof Error && "code" in error && error.code === code;
6377
+ }
6378
+ var import_node_child_process2, import_promises8, import_node_os3, import_node_path6, defaultCaptureTimeoutMilliseconds, defaultCaptureOutputLimitBytes, defaultDirenvTimeoutMilliseconds, defaultDirenvOutputLimitBytes, shellCaptureScript, environmentNamePattern, JobEnvironmentError, JobEnvironmentCancelledError, ShellEnvironmentManager;
6379
+ var init_shell_environment = __esm({
6380
+ "../machine-connector/dist/runtime/shell-environment.js"() {
6381
+ "use strict";
6382
+ init_cjs_shims();
6383
+ import_node_child_process2 = require("child_process");
6384
+ import_promises8 = require("fs/promises");
6385
+ import_node_os3 = require("os");
6386
+ import_node_path6 = require("path");
6387
+ defaultCaptureTimeoutMilliseconds = 5e3;
6388
+ defaultCaptureOutputLimitBytes = 1048576;
6389
+ defaultDirenvTimeoutMilliseconds = 5e3;
6390
+ defaultDirenvOutputLimitBytes = 1048576;
6391
+ shellCaptureScript = `exec "$1" -e 'for (const [name, value] of Object.entries(process.env)) process.stdout.write(name + "=" + value + "\\0")'`;
6392
+ environmentNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
6393
+ JobEnvironmentError = class extends Error {
6394
+ category;
6395
+ constructor(category) {
6396
+ super(`Local Machine Job environment resolution failed (${category})`);
6397
+ this.category = category;
6398
+ this.name = "JobEnvironmentError";
6399
+ }
6400
+ };
6401
+ JobEnvironmentCancelledError = class extends Error {
6402
+ constructor() {
6403
+ super("Local Machine Job environment resolution was cancelled");
6404
+ this.name = "JobEnvironmentCancelledError";
6405
+ }
6406
+ };
6407
+ ShellEnvironmentManager = class {
6408
+ captureOutputLimitBytes;
6409
+ captureTimeoutMilliseconds;
6410
+ daemonEnvironment;
6411
+ defaultShell;
6412
+ direnvOutputLimitBytes;
6413
+ direnvTimeoutMilliseconds;
6414
+ currentEnvironment;
6415
+ currentStatus = { state: "degraded" };
6416
+ refreshPromise;
6417
+ constructor(options = {}) {
6418
+ this.captureOutputLimitBytes = options.captureOutputLimitBytes ?? defaultCaptureOutputLimitBytes;
6419
+ this.captureTimeoutMilliseconds = options.captureTimeoutMilliseconds ?? defaultCaptureTimeoutMilliseconds;
6420
+ this.daemonEnvironment = freezeEnvironment(sanitizeEnvironment(options.daemonEnvironment ?? process.env));
6421
+ this.defaultShell = options.defaultShell ?? (0, import_node_os3.userInfo)().shell ?? "";
6422
+ this.direnvOutputLimitBytes = options.direnvOutputLimitBytes ?? defaultDirenvOutputLimitBytes;
6423
+ this.direnvTimeoutMilliseconds = options.direnvTimeoutMilliseconds ?? defaultDirenvTimeoutMilliseconds;
6424
+ this.currentEnvironment = this.daemonEnvironment;
6425
+ }
6426
+ async initialize() {
6427
+ const capture = await this.capture();
6428
+ this.currentEnvironment = capture.environment ?? this.daemonEnvironment;
6429
+ this.currentStatus = capture.status;
6430
+ return { ...this.currentStatus };
6431
+ }
6432
+ async refresh() {
6433
+ if (!this.refreshPromise) {
6434
+ this.refreshPromise = this.refreshOnce().finally(() => {
6435
+ this.refreshPromise = void 0;
6436
+ });
6437
+ }
6438
+ return await this.refreshPromise;
6439
+ }
6440
+ snapshot() {
6441
+ return this.currentEnvironment;
6442
+ }
6443
+ status() {
6444
+ return { ...this.currentStatus };
6445
+ }
6446
+ async resolveForJob(canonicalRoot, canonicalWorkingDirectory, explicitEnvironment, cancellationSignal) {
6447
+ throwIfCancelled(cancellationSignal);
6448
+ const relativeWorkingDirectory = (0, import_node_path6.relative)(canonicalRoot, canonicalWorkingDirectory);
6449
+ if (relativeWorkingDirectory === ".." || relativeWorkingDirectory.startsWith(`..${import_node_path6.sep}`) || (0, import_node_path6.isAbsolute)(relativeWorkingDirectory)) {
6450
+ throw new JobEnvironmentError("direnv_malformed");
6451
+ }
6452
+ const baseSnapshot = this.currentEnvironment;
6453
+ const envrcPath = await findNearestEnvrc(canonicalRoot, canonicalWorkingDirectory);
6454
+ throwIfCancelled(cancellationSignal);
6455
+ if (!envrcPath) {
6456
+ return freezeEnvironment({
6457
+ ...baseSnapshot,
6458
+ ...explicitEnvironment
6459
+ });
6460
+ }
6461
+ const direnvExecutable = await findExecutable("direnv", baseSnapshot.PATH);
6462
+ if (!direnvExecutable) {
6463
+ throw new JobEnvironmentError("direnv_missing");
6464
+ }
6465
+ const result = await executeBounded({
6466
+ argumentsList: ["export", "json"],
6467
+ cwd: canonicalWorkingDirectory,
6468
+ environment: baseSnapshot,
6469
+ executable: direnvExecutable,
6470
+ outputLimitBytes: this.direnvOutputLimitBytes,
6471
+ timeoutMilliseconds: this.direnvTimeoutMilliseconds,
6472
+ cancellationSignal
6473
+ });
6474
+ if (result.outcome === "cancelled") {
6475
+ throw new JobEnvironmentCancelledError();
6476
+ }
6477
+ if (result.outcome === "timeout") {
6478
+ throw new JobEnvironmentError("direnv_timeout");
6479
+ }
6480
+ if (result.outcome === "overflow") {
6481
+ throw new JobEnvironmentError("direnv_overflow");
6482
+ }
6483
+ if (result.outcome === "spawn_failed") {
6484
+ throw new JobEnvironmentError("direnv_spawn_failed");
6485
+ }
6486
+ if (result.exitCode !== 0) {
6487
+ const stderr = decodeUtf8(result.stderr, "direnv_malformed");
6488
+ throw new JobEnvironmentError(/blocked|not allowed|denied/i.test(stderr) ? "direnv_blocked" : "direnv_nonzero");
6489
+ }
6490
+ let parsedExports;
6491
+ try {
6492
+ parsedExports = parseDirenvJson(decodeUtf8(result.stdout, "direnv_malformed"));
6493
+ } catch {
6494
+ throw new JobEnvironmentError("direnv_malformed");
6495
+ }
6496
+ const exports2 = sanitizeDirenvExports(parsedExports);
6497
+ const environment = { ...baseSnapshot };
6498
+ for (const [name, value] of Object.entries(exports2)) {
6499
+ if (value === null) {
6500
+ delete environment[name];
6501
+ } else {
6502
+ environment[name] = value;
6503
+ }
6504
+ }
6505
+ return freezeEnvironment({
6506
+ ...environment,
6507
+ ...explicitEnvironment
6508
+ });
6509
+ }
6510
+ async capture() {
6511
+ let shell;
6512
+ try {
6513
+ shell = await validateShell(this.defaultShell);
6514
+ } catch {
6515
+ return degradedCapture("shell_environment_invalid_shell");
6516
+ }
6517
+ const result = await executeBounded({
6518
+ argumentsList: [
6519
+ "-l",
6520
+ "-i",
6521
+ "-c",
6522
+ shellCaptureScript,
6523
+ "moxt-shell-environment",
6524
+ process.execPath
6525
+ ],
6526
+ cwd: this.daemonEnvironment.HOME,
6527
+ environment: this.daemonEnvironment,
6528
+ executable: shell,
6529
+ outputLimitBytes: this.captureOutputLimitBytes,
6530
+ timeoutMilliseconds: this.captureTimeoutMilliseconds
6531
+ });
6532
+ if (result.outcome === "timeout") {
6533
+ return degradedCapture("shell_environment_timeout");
6534
+ }
6535
+ if (result.outcome === "overflow") {
6536
+ return degradedCapture("shell_environment_overflow");
6537
+ }
6538
+ if (result.outcome === "spawn_failed") {
6539
+ return degradedCapture("shell_environment_spawn_failed");
6540
+ }
6541
+ if (result.exitCode !== 0) {
6542
+ return degradedCapture("shell_environment_nonzero");
6543
+ }
6544
+ try {
6545
+ const snapshot = parseNullSeparatedEnvironment(result.stdout);
6546
+ return {
6547
+ environment: freezeEnvironment({
6548
+ ...this.daemonEnvironment,
6549
+ ...sanitizeEnvironment(snapshot)
6550
+ }),
6551
+ status: {
6552
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
6553
+ state: "captured"
6554
+ }
6555
+ };
6556
+ } catch {
6557
+ return degradedCapture("shell_environment_malformed");
6558
+ }
6559
+ }
6560
+ async refreshOnce() {
6561
+ const capture = await this.capture();
6562
+ if (capture.environment) {
6563
+ this.currentEnvironment = capture.environment;
6564
+ this.currentStatus = capture.status;
6565
+ }
6566
+ return { ...capture.status };
6567
+ }
6568
+ };
6569
+ }
6570
+ });
6571
+
5976
6572
  // ../machine-connector/dist/runtime/version.js
5977
6573
  var connectorVersion;
5978
6574
  var init_version = __esm({
@@ -6160,12 +6756,12 @@ var init_relay_client = __esm({
6160
6756
  });
6161
6757
 
6162
6758
  // ../machine-connector/dist/runtime/runtime-logger.js
6163
- var import_promises8, RuntimeLogger;
6759
+ var import_promises9, RuntimeLogger;
6164
6760
  var init_runtime_logger = __esm({
6165
6761
  "../machine-connector/dist/runtime/runtime-logger.js"() {
6166
6762
  "use strict";
6167
6763
  init_cjs_shims();
6168
- import_promises8 = require("fs/promises");
6764
+ import_promises9 = require("fs/promises");
6169
6765
  RuntimeLogger = class {
6170
6766
  store;
6171
6767
  constructor(store) {
@@ -6179,7 +6775,7 @@ var init_runtime_logger = __esm({
6179
6775
  await this.write("error", message, metadata, this.store.runtimeErrorLogPath());
6180
6776
  }
6181
6777
  async write(level, message, metadata, path4) {
6182
- await (0, import_promises8.appendFile)(path4, `${JSON.stringify({
6778
+ await (0, import_promises9.appendFile)(path4, `${JSON.stringify({
6183
6779
  level,
6184
6780
  message,
6185
6781
  metadata,
@@ -6200,12 +6796,12 @@ function defaultRuntimeDirectory() {
6200
6796
  if (override) {
6201
6797
  return override;
6202
6798
  }
6203
- const homeDirectory = process.env.HOME ?? (0, import_node_os3.homedir)();
6204
- if ((0, import_node_os3.platform)() === "darwin") {
6205
- return (0, import_node_path6.join)(homeDirectory, "Library", "Application Support", "Moxt", "Machine Connector");
6799
+ const homeDirectory = process.env.HOME ?? (0, import_node_os4.homedir)();
6800
+ if ((0, import_node_os4.platform)() === "darwin") {
6801
+ return (0, import_node_path7.join)(homeDirectory, "Library", "Application Support", "Moxt", "Machine Connector");
6206
6802
  }
6207
- const stateHome = process.env.XDG_STATE_HOME ?? (0, import_node_path6.join)(homeDirectory, ".local", "state");
6208
- return (0, import_node_path6.join)(stateHome, "moxt", "machine-connector");
6803
+ const stateHome = process.env.XDG_STATE_HOME ?? (0, import_node_path7.join)(homeDirectory, ".local", "state");
6804
+ return (0, import_node_path7.join)(stateHome, "moxt", "machine-connector");
6209
6805
  }
6210
6806
  function isNodeErrorCode3(error, expectedCode) {
6211
6807
  if (!(error instanceof Error) || !("code" in error)) {
@@ -6213,14 +6809,14 @@ function isNodeErrorCode3(error, expectedCode) {
6213
6809
  }
6214
6810
  return error.code === expectedCode;
6215
6811
  }
6216
- var import_promises9, import_node_os3, import_node_path6, privateFileMode, privateDirectoryMode, MachineRuntimeStore;
6812
+ var import_promises10, import_node_os4, import_node_path7, privateFileMode, privateDirectoryMode, MachineRuntimeStore;
6217
6813
  var init_store = __esm({
6218
6814
  "../machine-connector/dist/runtime/store.js"() {
6219
6815
  "use strict";
6220
6816
  init_cjs_shims();
6221
- import_promises9 = require("fs/promises");
6222
- import_node_os3 = require("os");
6223
- import_node_path6 = require("path");
6817
+ import_promises10 = require("fs/promises");
6818
+ import_node_os4 = require("os");
6819
+ import_node_path7 = require("path");
6224
6820
  privateFileMode = 384;
6225
6821
  privateDirectoryMode = 448;
6226
6822
  MachineRuntimeStore = class {
@@ -6229,20 +6825,20 @@ var init_store = __esm({
6229
6825
  this.baseDirectory = baseDirectory;
6230
6826
  }
6231
6827
  async initialize() {
6232
- await (0, import_promises9.mkdir)(this.jobsDirectory(), {
6828
+ await (0, import_promises10.mkdir)(this.jobsDirectory(), {
6233
6829
  mode: privateDirectoryMode,
6234
6830
  recursive: true
6235
6831
  });
6236
- await (0, import_promises9.mkdir)(this.detachedProcessesDirectory(), {
6832
+ await (0, import_promises10.mkdir)(this.detachedProcessesDirectory(), {
6237
6833
  mode: privateDirectoryMode,
6238
6834
  recursive: true
6239
6835
  });
6240
- await (0, import_promises9.chmod)(this.baseDirectory, privateDirectoryMode);
6241
- await (0, import_promises9.chmod)(this.jobsDirectory(), privateDirectoryMode);
6242
- await (0, import_promises9.chmod)(this.detachedProcessesDirectory(), privateDirectoryMode);
6836
+ await (0, import_promises10.chmod)(this.baseDirectory, privateDirectoryMode);
6837
+ await (0, import_promises10.chmod)(this.jobsDirectory(), privateDirectoryMode);
6838
+ await (0, import_promises10.chmod)(this.detachedProcessesDirectory(), privateDirectoryMode);
6243
6839
  }
6244
6840
  async getCanonicalRoot(rootPath) {
6245
- return await (0, import_promises9.realpath)(rootPath);
6841
+ return await (0, import_promises10.realpath)(rootPath);
6246
6842
  }
6247
6843
  async readIdentity() {
6248
6844
  return await this.readOptionalJson(this.identityPath());
@@ -6285,7 +6881,7 @@ var init_store = __esm({
6285
6881
  await this.writePrivateJson(this.serviceManagerPath(), serviceManager);
6286
6882
  }
6287
6883
  async removeServiceManager() {
6288
- await (0, import_promises9.rm)(this.serviceManagerPath(), { force: true });
6884
+ await (0, import_promises10.rm)(this.serviceManagerPath(), { force: true });
6289
6885
  }
6290
6886
  async readJob(jobId) {
6291
6887
  return await this.readOptionalJson(this.jobPath(jobId));
@@ -6296,7 +6892,7 @@ var init_store = __esm({
6296
6892
  async listJobs() {
6297
6893
  let names = [];
6298
6894
  try {
6299
- names = await (0, import_promises9.readdir)(this.jobsDirectory());
6895
+ names = await (0, import_promises10.readdir)(this.jobsDirectory());
6300
6896
  } catch (error) {
6301
6897
  if (isNodeErrorCode3(error, "ENOENT")) {
6302
6898
  return [];
@@ -6305,7 +6901,7 @@ var init_store = __esm({
6305
6901
  }
6306
6902
  const jobs = [];
6307
6903
  for (const name of names.filter((entry) => entry.endsWith(".json"))) {
6308
- const job = await this.readOptionalJson((0, import_node_path6.join)(this.jobsDirectory(), name));
6904
+ const job = await this.readOptionalJson((0, import_node_path7.join)(this.jobsDirectory(), name));
6309
6905
  if (job.value) {
6310
6906
  jobs.push(job.value);
6311
6907
  }
@@ -6313,7 +6909,7 @@ var init_store = __esm({
6313
6909
  return jobs;
6314
6910
  }
6315
6911
  async deleteJob(jobId) {
6316
- await (0, import_promises9.rm)(this.jobPath(jobId), { force: true });
6912
+ await (0, import_promises10.rm)(this.jobPath(jobId), { force: true });
6317
6913
  }
6318
6914
  async writeDetachedProcess(resource) {
6319
6915
  await this.writePrivateJson(this.detachedProcessPath(resource.jobId), resource);
@@ -6321,7 +6917,7 @@ var init_store = __esm({
6321
6917
  async listDetachedProcesses() {
6322
6918
  let names = [];
6323
6919
  try {
6324
- names = await (0, import_promises9.readdir)(this.detachedProcessesDirectory());
6920
+ names = await (0, import_promises10.readdir)(this.detachedProcessesDirectory());
6325
6921
  } catch (error) {
6326
6922
  if (isNodeErrorCode3(error, "ENOENT")) {
6327
6923
  return [];
@@ -6330,7 +6926,7 @@ var init_store = __esm({
6330
6926
  }
6331
6927
  const resources = [];
6332
6928
  for (const name of names.filter((entry) => entry.endsWith(".json"))) {
6333
- const resource = await this.readOptionalJson((0, import_node_path6.join)(this.detachedProcessesDirectory(), name));
6929
+ const resource = await this.readOptionalJson((0, import_node_path7.join)(this.detachedProcessesDirectory(), name));
6334
6930
  if (resource.value) {
6335
6931
  resources.push(resource.value);
6336
6932
  }
@@ -6338,52 +6934,52 @@ var init_store = __esm({
6338
6934
  return resources;
6339
6935
  }
6340
6936
  async deleteDetachedProcess(jobId) {
6341
- await (0, import_promises9.rm)(this.detachedProcessPath(jobId), { force: true });
6937
+ await (0, import_promises10.rm)(this.detachedProcessPath(jobId), { force: true });
6342
6938
  }
6343
6939
  runtimeLogPath() {
6344
- return (0, import_node_path6.join)(this.baseDirectory, "machine-connector.log");
6940
+ return (0, import_node_path7.join)(this.baseDirectory, "machine-connector.log");
6345
6941
  }
6346
6942
  runtimeErrorLogPath() {
6347
- return (0, import_node_path6.join)(this.baseDirectory, "machine-connector.error.log");
6943
+ return (0, import_node_path7.join)(this.baseDirectory, "machine-connector.error.log");
6348
6944
  }
6349
6945
  runtimeStatusPath() {
6350
- return (0, import_node_path6.join)(this.baseDirectory, "runtime-status.json");
6946
+ return (0, import_node_path7.join)(this.baseDirectory, "runtime-status.json");
6351
6947
  }
6352
6948
  runtimeSocketPath() {
6353
- if ((0, import_node_os3.platform)() === "win32") {
6949
+ if ((0, import_node_os4.platform)() === "win32") {
6354
6950
  return String.raw`\\.\pipe\moxt-machine-connector`;
6355
6951
  }
6356
- return (0, import_node_path6.join)(this.baseDirectory, "machine-connector.sock");
6952
+ return (0, import_node_path7.join)(this.baseDirectory, "machine-connector.sock");
6357
6953
  }
6358
6954
  daemonLockPath() {
6359
- return (0, import_node_path6.join)(this.baseDirectory, "daemon.lock");
6955
+ return (0, import_node_path7.join)(this.baseDirectory, "daemon.lock");
6360
6956
  }
6361
6957
  reconcileLockPath() {
6362
- return (0, import_node_path6.join)(this.baseDirectory, "daemon-reconcile.lock");
6958
+ return (0, import_node_path7.join)(this.baseDirectory, "daemon-reconcile.lock");
6363
6959
  }
6364
6960
  connectionsPath() {
6365
- return (0, import_node_path6.join)(this.baseDirectory, "connections.json");
6961
+ return (0, import_node_path7.join)(this.baseDirectory, "connections.json");
6366
6962
  }
6367
6963
  detachedProcessesDirectory() {
6368
- return (0, import_node_path6.join)(this.baseDirectory, "detached-processes");
6964
+ return (0, import_node_path7.join)(this.baseDirectory, "detached-processes");
6369
6965
  }
6370
6966
  detachedProcessPath(jobId) {
6371
- return (0, import_node_path6.join)(this.detachedProcessesDirectory(), `${jobId}.json`);
6967
+ return (0, import_node_path7.join)(this.detachedProcessesDirectory(), `${jobId}.json`);
6372
6968
  }
6373
6969
  identityPath() {
6374
- return (0, import_node_path6.join)(this.baseDirectory, "identity.json");
6970
+ return (0, import_node_path7.join)(this.baseDirectory, "identity.json");
6375
6971
  }
6376
6972
  serviceManagerPath() {
6377
- return (0, import_node_path6.join)(this.baseDirectory, "service-manager.json");
6973
+ return (0, import_node_path7.join)(this.baseDirectory, "service-manager.json");
6378
6974
  }
6379
6975
  privateKeyPath() {
6380
- return (0, import_node_path6.join)(this.baseDirectory, "device-private-key.pem");
6976
+ return (0, import_node_path7.join)(this.baseDirectory, "device-private-key.pem");
6381
6977
  }
6382
6978
  jobsDirectory() {
6383
- return (0, import_node_path6.join)(this.baseDirectory, "jobs");
6979
+ return (0, import_node_path7.join)(this.baseDirectory, "jobs");
6384
6980
  }
6385
6981
  jobPath(jobId) {
6386
- return (0, import_node_path6.join)(this.jobsDirectory(), `${jobId}.json`);
6982
+ return (0, import_node_path7.join)(this.jobsDirectory(), `${jobId}.json`);
6387
6983
  }
6388
6984
  async readOptionalJson(path4) {
6389
6985
  const content3 = await this.readOptionalText(path4);
@@ -6394,7 +6990,7 @@ var init_store = __esm({
6394
6990
  }
6395
6991
  async readOptionalText(path4) {
6396
6992
  try {
6397
- return { value: await (0, import_promises9.readFile)(path4, "utf8") };
6993
+ return { value: await (0, import_promises10.readFile)(path4, "utf8") };
6398
6994
  } catch (error) {
6399
6995
  if (isNodeErrorCode3(error, "ENOENT")) {
6400
6996
  return {};
@@ -6407,17 +7003,17 @@ var init_store = __esm({
6407
7003
  `);
6408
7004
  }
6409
7005
  async writePrivateText(path4, value) {
6410
- await (0, import_promises9.mkdir)((0, import_node_path6.dirname)(path4), {
7006
+ await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), {
6411
7007
  mode: privateDirectoryMode,
6412
7008
  recursive: true
6413
7009
  });
6414
7010
  const temporaryPath = `${path4}.${process.pid}.tmp`;
6415
- await (0, import_promises9.writeFile)(temporaryPath, value, {
7011
+ await (0, import_promises10.writeFile)(temporaryPath, value, {
6416
7012
  encoding: "utf8",
6417
7013
  mode: privateFileMode
6418
7014
  });
6419
- await (0, import_promises9.chmod)(temporaryPath, privateFileMode);
6420
- await (0, import_promises9.rename)(temporaryPath, path4);
7015
+ await (0, import_promises10.chmod)(temporaryPath, privateFileMode);
7016
+ await (0, import_promises10.rename)(temporaryPath, path4);
6421
7017
  }
6422
7018
  };
6423
7019
  }
@@ -6447,16 +7043,17 @@ function delay4(milliseconds) {
6447
7043
  setTimeout(resolvePromise, milliseconds);
6448
7044
  });
6449
7045
  }
6450
- var import_node_os4, import_node_crypto5, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
7046
+ var import_node_os5, import_node_crypto5, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, commandOutputBatchMaxBytes, commandOutputFlushIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
6451
7047
  var init_daemon = __esm({
6452
7048
  "../machine-connector/dist/runtime/daemon.js"() {
6453
7049
  "use strict";
6454
7050
  init_cjs_shims();
6455
- import_node_os4 = require("os");
7051
+ import_node_os5 = require("os");
6456
7052
  import_node_crypto5 = require("crypto");
6457
7053
  init_enums();
6458
7054
  init_contracts();
6459
7055
  init_claude_executor();
7056
+ init_command_output_batcher();
6460
7057
  init_codex_executor();
6461
7058
  init_durable_job();
6462
7059
  init_execution_cancellation();
@@ -6464,6 +7061,7 @@ var init_daemon = __esm({
6464
7061
  init_local_ipc();
6465
7062
  init_process_lock();
6466
7063
  init_process_executor();
7064
+ init_shell_environment();
6467
7065
  init_relay_client();
6468
7066
  init_runtime_logger();
6469
7067
  init_runtime_types();
@@ -6472,6 +7070,8 @@ var init_daemon = __esm({
6472
7070
  claimTimeoutSeconds = 30;
6473
7071
  controlTimeoutSeconds = 30;
6474
7072
  eventUploadIntervalMilliseconds = 500;
7073
+ commandOutputBatchMaxBytes = 4 * 1024;
7074
+ commandOutputFlushIntervalMilliseconds = 250;
6475
7075
  agentOutputLimitBytes = 2e6;
6476
7076
  defaultLeaseSeconds = 90;
6477
7077
  defaultNetworkRetryMilliseconds = 2e3;
@@ -6510,6 +7110,7 @@ var init_daemon = __esm({
6510
7110
  random;
6511
7111
  terminalForegroundBudgetMilliseconds;
6512
7112
  cliVersion;
7113
+ shellEnvironmentManager;
6513
7114
  constructor(store = new MachineRuntimeStore(), options = {}) {
6514
7115
  this.store = store;
6515
7116
  this.lifetimeSettled = new Promise((resolvePromise) => {
@@ -6520,6 +7121,7 @@ var init_daemon = __esm({
6520
7121
  });
6521
7122
  this.logger = new RuntimeLogger(store);
6522
7123
  this.cliVersion = options.cliVersion;
7124
+ this.shellEnvironmentManager = options.shellEnvironmentManager ?? new ShellEnvironmentManager();
6523
7125
  this.leaseSafetyMarginMilliseconds = options.leaseSafetyMarginMilliseconds ?? defaultLeaseSafetyMarginMilliseconds;
6524
7126
  this.leaseSeconds = options.leaseSeconds ?? defaultLeaseSeconds;
6525
7127
  this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds;
@@ -6538,14 +7140,27 @@ var init_daemon = __esm({
6538
7140
  throw new Error("Another Moxt Machine Connector daemon is already running or starting");
6539
7141
  }
6540
7142
  this.throwIfStopping();
7143
+ const shellEnvironmentStatus = await this.shellEnvironmentManager.initialize();
7144
+ await this.logger.info("Local Machine shell environment initialized", {
7145
+ category: shellEnvironmentStatus.category,
7146
+ state: shellEnvironmentStatus.state
7147
+ });
7148
+ this.throwIfStopping();
6541
7149
  await this.recoverInterruptedJobs();
6542
7150
  this.throwIfStopping();
6543
- this.ipcServer = new LocalIpcServer(this.store, () => this.getStatus());
7151
+ this.ipcServer = new LocalIpcServer(this.store, () => this.getStatus(), async () => {
7152
+ const status = await this.shellEnvironmentManager.refresh();
7153
+ await this.logger.info("Local Machine shell environment refreshed", {
7154
+ category: status.category,
7155
+ state: status.state
7156
+ });
7157
+ return status;
7158
+ });
6544
7159
  await this.ipcServer.start();
6545
7160
  this.throwIfStopping();
6546
7161
  await this.logger.info("Moxt Machine Connector started", {
6547
7162
  connectorInstanceId: this.connectorInstanceId,
6548
- hostname: (0, import_node_os4.hostname)(),
7163
+ hostname: (0, import_node_os5.hostname)(),
6549
7164
  version: connectorVersion
6550
7165
  });
6551
7166
  this.connections = await this.store.listConnections();
@@ -6611,6 +7226,7 @@ var init_daemon = __esm({
6611
7226
  connectorInstanceId: this.connectorInstanceId,
6612
7227
  pid: process.pid,
6613
7228
  startedAt: this.startedAt,
7229
+ shellEnvironment: this.shellEnvironmentManager.status(),
6614
7230
  version: connectorVersion
6615
7231
  };
6616
7232
  }
@@ -6768,6 +7384,7 @@ var init_daemon = __esm({
6768
7384
  activeJob.cancellation.wait().then(() => this.cancellationResult(activeJob))
6769
7385
  ]);
6770
7386
  void execution.catch(() => void 0);
7387
+ await activeJob.commandOutputBatcher?.flush();
6771
7388
  const detachedProcessHandle = "detachedProcessHandle" in executionResult ? executionResult.detachedProcessHandle : void 0;
6772
7389
  if (detachedProcessHandle) {
6773
7390
  let resourceRecorded = false;
@@ -6807,6 +7424,11 @@ var init_daemon = __esm({
6807
7424
  if (!durableJob) {
6808
7425
  return;
6809
7426
  }
7427
+ try {
7428
+ await activeJob.commandOutputBatcher?.flush();
7429
+ } catch (flushError) {
7430
+ await this.logger.error(`Failed to flush command output for Job ${claim.jobId}`, flushError);
7431
+ }
6810
7432
  const message = error instanceof Error ? error.message : "Unknown Connector error";
6811
7433
  await durableJob.markTerminal({
6812
7434
  exitCode: -1,
@@ -6824,25 +7446,55 @@ var init_daemon = __esm({
6824
7446
  const { claim } = activeJob;
6825
7447
  const registerProcess = activeJob.cancellation.register.bind(activeJob.cancellation);
6826
7448
  const canSpawn = activeJob.cancellation.canSpawn.bind(activeJob.cancellation);
7449
+ const resolveEnvironment = async (workingDirectory2, explicitEnvironment) => {
7450
+ try {
7451
+ return await this.shellEnvironmentManager.resolveForJob(activeJob.connection.rootPath, workingDirectory2, explicitEnvironment, activeJob.cancellation.signal());
7452
+ } catch (error) {
7453
+ if (error instanceof JobEnvironmentCancelledError) {
7454
+ return void 0;
7455
+ }
7456
+ throw error;
7457
+ }
7458
+ };
7459
+ if (!canSpawn()) {
7460
+ return this.cancellationResult(activeJob);
7461
+ }
6827
7462
  if (claim.kind === MachineJobKind.Command) {
6828
7463
  const request2 = claim.requestPayload;
6829
- const result = await executeCommand(activeJob.connection.rootPath, {
6830
- ...request2,
6831
- relativeWorkingDirectory: claim.relativeWorkingDirectory
6832
- }, {
6833
- canSpawn,
6834
- onOutput: async (output) => {
6835
- if (activeJob.cancellation.currentReason() !== void 0) {
6836
- return;
6837
- }
6838
- await durableJob.appendOutput(output.stream, output.text, request2.outputLimitBytes);
6839
- },
6840
- onSpawn: registerProcess
7464
+ const workingDirectory2 = await resolveCanonicalWorkingDirectory(activeJob.connection.rootPath, claim.relativeWorkingDirectory);
7465
+ const environment2 = await resolveEnvironment(workingDirectory2, request2.environment);
7466
+ if (!environment2 || !canSpawn()) {
7467
+ return this.cancellationResult(activeJob);
7468
+ }
7469
+ const outputBatcher = new CommandOutputBatcher({
7470
+ flushIntervalMilliseconds: commandOutputFlushIntervalMilliseconds,
7471
+ maxBytes: commandOutputBatchMaxBytes,
7472
+ write: async (stream, text3) => {
7473
+ await durableJob.appendOutput(stream, text3, request2.outputLimitBytes);
7474
+ }
6841
7475
  });
6842
- return {
6843
- ...result,
6844
- result: { exitCode: result.exitCode }
6845
- };
7476
+ activeJob.commandOutputBatcher = outputBatcher;
7477
+ try {
7478
+ const result = await executeProcess(request2.executable, request2.arguments, workingDirectory2, environment2, request2.stdin, request2.timeoutSeconds, {
7479
+ canSpawn,
7480
+ onOutput: async (output) => {
7481
+ if (activeJob.cancellation.currentReason() !== void 0) {
7482
+ return;
7483
+ }
7484
+ await outputBatcher.append(output.stream, output.text);
7485
+ },
7486
+ onSpawn: registerProcess
7487
+ });
7488
+ return {
7489
+ ...result,
7490
+ result: { exitCode: result.exitCode }
7491
+ };
7492
+ } finally {
7493
+ await outputBatcher.flush();
7494
+ if (activeJob.commandOutputBatcher === outputBatcher) {
7495
+ activeJob.commandOutputBatcher = void 0;
7496
+ }
7497
+ }
6846
7498
  }
6847
7499
  if (claim.kind === MachineJobKind.ViewImage) {
6848
7500
  const request2 = claim.requestPayload;
@@ -6856,6 +7508,10 @@ var init_daemon = __esm({
6856
7508
  if (!canSpawn()) {
6857
7509
  return this.cancellationResult(activeJob);
6858
7510
  }
7511
+ const environment = await resolveEnvironment(workingDirectory, {});
7512
+ if (!environment || !canSpawn()) {
7513
+ return this.cancellationResult(activeJob);
7514
+ }
6859
7515
  const callbacks = {
6860
7516
  canSpawn,
6861
7517
  onEvent: async (event) => {
@@ -6877,7 +7533,7 @@ var init_daemon = __esm({
6877
7533
  };
6878
7534
  if (claim.kind === MachineJobKind.CodexStart) {
6879
7535
  const request2 = claim.requestPayload;
6880
- const result = await executeCodexStart(workingDirectory, this.store.baseDirectory, {
7536
+ const result = await executeCodexStart(workingDirectory, this.store.baseDirectory, environment, {
6881
7537
  ...request2,
6882
7538
  relativeWorkingDirectory: claim.relativeWorkingDirectory
6883
7539
  }, callbacks);
@@ -6891,7 +7547,7 @@ var init_daemon = __esm({
6891
7547
  }
6892
7548
  if (claim.kind === MachineJobKind.CodexReply) {
6893
7549
  const request2 = claim.requestPayload;
6894
- const result = await executeCodexReply(workingDirectory, this.store.baseDirectory, {
7550
+ const result = await executeCodexReply(workingDirectory, this.store.baseDirectory, environment, {
6895
7551
  ...request2,
6896
7552
  relativeWorkingDirectory: claim.relativeWorkingDirectory
6897
7553
  }, callbacks);
@@ -6906,7 +7562,7 @@ var init_daemon = __esm({
6906
7562
  }
6907
7563
  if (claim.kind === MachineJobKind.ClaudeStart) {
6908
7564
  const request2 = claim.requestPayload;
6909
- const result = await executeClaudeStart(workingDirectory, {
7565
+ const result = await executeClaudeStart(workingDirectory, environment, {
6910
7566
  ...request2,
6911
7567
  relativeWorkingDirectory: claim.relativeWorkingDirectory
6912
7568
  }, callbacks);
@@ -6920,7 +7576,7 @@ var init_daemon = __esm({
6920
7576
  }
6921
7577
  if (claim.kind === MachineJobKind.ClaudeReply) {
6922
7578
  const request2 = claim.requestPayload;
6923
- const result = await executeClaudeReply(workingDirectory, {
7579
+ const result = await executeClaudeReply(workingDirectory, environment, {
6924
7580
  ...request2,
6925
7581
  relativeWorkingDirectory: claim.relativeWorkingDirectory
6926
7582
  }, callbacks);
@@ -7393,12 +8049,12 @@ async function installUserService(store, request2, runtime = defaultServiceManag
7393
8049
  }
7394
8050
  function createServiceEnvironment(options) {
7395
8051
  const inheritedPath = options.environment.PATH ?? process.env.PATH ?? "";
7396
- const nodeDirectory = (0, import_node_path7.dirname)(options.nodePath);
7397
- const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path7.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
8052
+ const nodeDirectory = (0, import_node_path8.dirname)(options.nodePath);
8053
+ const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path8.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
7398
8054
  return {
7399
8055
  ...options.environment,
7400
- HOME: options.environment.HOME ?? process.env.HOME ?? (0, import_node_os5.homedir)(),
7401
- PATH: pathEntries.join(import_node_path7.delimiter)
8056
+ HOME: options.environment.HOME ?? process.env.HOME ?? (0, import_node_os6.homedir)(),
8057
+ PATH: pathEntries.join(import_node_path8.delimiter)
7402
8058
  };
7403
8059
  }
7404
8060
  async function restartUserService(store, runtime = defaultServiceManagerRuntime) {
@@ -7434,7 +8090,7 @@ async function refreshManagedUserService(store, options, runtime = defaultServic
7434
8090
  try {
7435
8091
  await rollback();
7436
8092
  } catch (rollbackError) {
7437
- throw new Error(`${errorMessage(error)}; restoring the previous ${manager} definition also failed: ${errorMessage(rollbackError)}`, { cause: error });
8093
+ throw new Error(`${errorMessage2(error)}; restoring the previous ${manager} definition also failed: ${errorMessage2(rollbackError)}`, { cause: error });
7438
8094
  }
7439
8095
  throw error;
7440
8096
  }
@@ -7581,7 +8237,7 @@ async function uninstallManager(manager, store, runtime) {
7581
8237
  "bootout",
7582
8238
  `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
7583
8239
  ]);
7584
- await (0, import_promises10.rm)(launchAgentPath(), { force: true });
8240
+ await (0, import_promises11.rm)(launchAgentPath(), { force: true });
7585
8241
  return;
7586
8242
  }
7587
8243
  if (manager === UserServiceManager.Systemd) {
@@ -7591,7 +8247,7 @@ async function uninstallManager(manager, store, runtime) {
7591
8247
  "--now",
7592
8248
  "moxt-machine-connector.service"
7593
8249
  ]);
7594
- await (0, import_promises10.rm)(systemdUnitPath(), { force: true });
8250
+ await (0, import_promises11.rm)(systemdUnitPath(), { force: true });
7595
8251
  await runCommandIgnoringFailure(runtime, "systemctl", [
7596
8252
  "--user",
7597
8253
  "daemon-reload"
@@ -7605,7 +8261,7 @@ async function uninstallManager(manager, store, runtime) {
7605
8261
  supervisorProgramName
7606
8262
  ]);
7607
8263
  await runCommandIgnoringFailure(runtime, "supervisorctl", ["-c", supervisorConfigPath(store), "shutdown"]);
7608
- await (0, import_promises10.rm)(supervisorDirectory(store), {
8264
+ await (0, import_promises11.rm)(supervisorDirectory(store), {
7609
8265
  force: true,
7610
8266
  recursive: true
7611
8267
  });
@@ -7631,7 +8287,7 @@ async function readStoredServiceManager(store) {
7631
8287
  }
7632
8288
  async function readManagedServiceDefinition(manager, store) {
7633
8289
  try {
7634
- return await (0, import_promises10.readFile)(managedServiceDefinitionPath(manager, store), "utf8");
8290
+ return await (0, import_promises11.readFile)(managedServiceDefinitionPath(manager, store), "utf8");
7635
8291
  } catch (error) {
7636
8292
  if (isNodeErrorCode4(error, "ENOENT"))
7637
8293
  return void 0;
@@ -7640,8 +8296,8 @@ async function readManagedServiceDefinition(manager, store) {
7640
8296
  }
7641
8297
  async function restoreManagedServiceDefinition(manager, store, definition2, runtime) {
7642
8298
  const path4 = managedServiceDefinitionPath(manager, store);
7643
- await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
7644
- await (0, import_promises10.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
8299
+ await (0, import_promises11.mkdir)((0, import_node_path8.dirname)(path4), { recursive: true });
8300
+ await (0, import_promises11.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
7645
8301
  if (manager === UserServiceManager.Launchd) {
7646
8302
  const domain = `gui/${process.getuid?.() ?? 0}`;
7647
8303
  await runCommandIgnoringFailure(runtime, "launchctl", [
@@ -7716,10 +8372,10 @@ function automaticSelectionDetail(manager) {
7716
8372
  }
7717
8373
  async function installLaunchAgent(store, options, runtime) {
7718
8374
  const path4 = launchAgentPath();
7719
- await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
8375
+ await (0, import_promises11.mkdir)((0, import_node_path8.dirname)(path4), { recursive: true });
7720
8376
  const programArguments = [
7721
8377
  options.nodePath,
7722
- (0, import_node_path7.resolve)(options.entrypointPath),
8378
+ (0, import_node_path8.resolve)(options.entrypointPath),
7723
8379
  ...options.commandArguments
7724
8380
  ];
7725
8381
  const plist = `<?xml version="1.0" encoding="UTF-8"?>
@@ -7750,7 +8406,7 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
7750
8406
  </dict>
7751
8407
  </plist>
7752
8408
  `;
7753
- await (0, import_promises10.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
8409
+ await (0, import_promises11.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
7754
8410
  const domain = `gui/${process.getuid?.() ?? 0}`;
7755
8411
  await runCommandIgnoringFailure(runtime, "launchctl", [
7756
8412
  "bootout",
@@ -7766,10 +8422,10 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
7766
8422
  }
7767
8423
  async function installSystemdUserService(store, options, runtime) {
7768
8424
  const path4 = systemdUnitPath();
7769
- await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), { recursive: true });
8425
+ await (0, import_promises11.mkdir)((0, import_node_path8.dirname)(path4), { recursive: true });
7770
8426
  const command = [
7771
8427
  options.nodePath,
7772
- (0, import_node_path7.resolve)(options.entrypointPath),
8428
+ (0, import_node_path8.resolve)(options.entrypointPath),
7773
8429
  ...options.commandArguments
7774
8430
  ].map(escapeSystemdArgument).join(" ");
7775
8431
  const unit = `[Unit]
@@ -7788,7 +8444,7 @@ ${Object.entries(options.environment).map(([name, value]) => `Environment=${esca
7788
8444
  [Install]
7789
8445
  WantedBy=default.target
7790
8446
  `;
7791
- await (0, import_promises10.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
8447
+ await (0, import_promises11.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
7792
8448
  await runtime.run("systemctl", ["--user", "daemon-reload"]);
7793
8449
  await runtime.run("systemctl", [
7794
8450
  "--user",
@@ -7798,21 +8454,21 @@ WantedBy=default.target
7798
8454
  ]);
7799
8455
  await runCommandIgnoringFailure(runtime, "loginctl", [
7800
8456
  "enable-linger",
7801
- (0, import_node_os5.userInfo)().username
8457
+ (0, import_node_os6.userInfo)().username
7802
8458
  ]);
7803
8459
  }
7804
8460
  async function installSupervisorUserService(store, options, runtime) {
7805
8461
  const directory = supervisorDirectory(store);
7806
8462
  const configPath = supervisorConfigPath(store);
7807
- await (0, import_promises10.mkdir)(directory, { recursive: true, mode: 448 });
7808
- await (0, import_promises10.writeFile)(configPath, createSupervisorConfiguration(store, options), {
8463
+ await (0, import_promises11.mkdir)(directory, { recursive: true, mode: 448 });
8464
+ await (0, import_promises11.writeFile)(configPath, createSupervisorConfiguration(store, options), {
7809
8465
  encoding: "utf8",
7810
8466
  mode: 384
7811
8467
  });
7812
8468
  const supervisorWasRunning = await supervisorIsRunning(store, runtime);
7813
8469
  if (!supervisorWasRunning) {
7814
- await (0, import_promises10.rm)(supervisorSocketPath(store), { force: true });
7815
- await (0, import_promises10.rm)(supervisorPidPath(store), { force: true });
8470
+ await (0, import_promises11.rm)(supervisorSocketPath(store), { force: true });
8471
+ await (0, import_promises11.rm)(supervisorPidPath(store), { force: true });
7816
8472
  await runtime.run("supervisord", ["-c", configPath]);
7817
8473
  await waitForSupervisorControl(store, runtime);
7818
8474
  return;
@@ -7822,7 +8478,7 @@ async function installSupervisorUserService(store, options, runtime) {
7822
8478
  function createSupervisorConfiguration(store, options) {
7823
8479
  const command = [
7824
8480
  options.nodePath,
7825
- (0, import_node_path7.resolve)(options.entrypointPath),
8481
+ (0, import_node_path8.resolve)(options.entrypointPath),
7826
8482
  ...options.commandArguments
7827
8483
  ].map(escapeSupervisorArgument).join(" ");
7828
8484
  const environment = Object.entries(options.environment).map(([name, value]) => `${name}="${escapeSupervisorEnvironment(value)}"`).join(",");
@@ -7846,7 +8502,7 @@ serverurl=unix://${supervisorSocketPath(store)}
7846
8502
 
7847
8503
  [program:${supervisorProgramName}]
7848
8504
  command=${command}
7849
- directory=${escapeSupervisorPath((0, import_node_path7.dirname)((0, import_node_path7.resolve)(options.entrypointPath)))}
8505
+ directory=${escapeSupervisorPath((0, import_node_path8.dirname)((0, import_node_path8.resolve)(options.entrypointPath)))}
7850
8506
  environment=${environment}
7851
8507
  autostart=true
7852
8508
  autorestart=true
@@ -7867,8 +8523,8 @@ stderr_logfile_backups=3
7867
8523
  async function restartSupervisorUserService(store, runtime) {
7868
8524
  const configPath = supervisorConfigPath(store);
7869
8525
  if (!await supervisorIsRunning(store, runtime)) {
7870
- await (0, import_promises10.rm)(supervisorSocketPath(store), { force: true });
7871
- await (0, import_promises10.rm)(supervisorPidPath(store), { force: true });
8526
+ await (0, import_promises11.rm)(supervisorSocketPath(store), { force: true });
8527
+ await (0, import_promises11.rm)(supervisorPidPath(store), { force: true });
7872
8528
  await runtime.run("supervisord", ["-c", configPath]);
7873
8529
  await waitForSupervisorControl(store, runtime);
7874
8530
  return;
@@ -7944,26 +8600,26 @@ async function waitForSupervisorControl(store, runtime) {
7944
8600
  throw new Error("Supervisor did not become ready within 5 seconds");
7945
8601
  }
7946
8602
  function launchAgentPath() {
7947
- return (0, import_node_path7.join)(process.env.HOME ?? (0, import_node_os5.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
8603
+ return (0, import_node_path8.join)(process.env.HOME ?? (0, import_node_os6.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
7948
8604
  }
7949
8605
  function systemdUnitPath() {
7950
- const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path7.join)(process.env.HOME ?? (0, import_node_os5.homedir)(), ".config");
7951
- return (0, import_node_path7.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
8606
+ const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path8.join)(process.env.HOME ?? (0, import_node_os6.homedir)(), ".config");
8607
+ return (0, import_node_path8.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
7952
8608
  }
7953
8609
  function supervisorDirectory(store) {
7954
- return (0, import_node_path7.join)(store.baseDirectory, "supervisor");
8610
+ return (0, import_node_path8.join)(store.baseDirectory, "supervisor");
7955
8611
  }
7956
8612
  function supervisorConfigPath(store) {
7957
- return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.conf");
8613
+ return (0, import_node_path8.join)(supervisorDirectory(store), "supervisord.conf");
7958
8614
  }
7959
8615
  function supervisorSocketPath(store) {
7960
- return (0, import_node_path7.join)(supervisorDirectory(store), "supervisor.sock");
8616
+ return (0, import_node_path8.join)(supervisorDirectory(store), "supervisor.sock");
7961
8617
  }
7962
8618
  function supervisorPidPath(store) {
7963
- return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.pid");
8619
+ return (0, import_node_path8.join)(supervisorDirectory(store), "supervisord.pid");
7964
8620
  }
7965
8621
  function supervisorLogPath(store) {
7966
- return (0, import_node_path7.join)(supervisorDirectory(store), "supervisord.log");
8622
+ return (0, import_node_path8.join)(supervisorDirectory(store), "supervisord.log");
7967
8623
  }
7968
8624
  async function commandSucceeds(runtime, command, argumentsList) {
7969
8625
  try {
@@ -8013,7 +8669,7 @@ function escapeSupervisorPath(value) {
8013
8669
  function escapeSupervisorValue(value) {
8014
8670
  return value.replaceAll("%", "%%").replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n");
8015
8671
  }
8016
- function errorMessage(error) {
8672
+ function errorMessage2(error) {
8017
8673
  return error instanceof Error ? error.message : String(error);
8018
8674
  }
8019
8675
  function isNodeErrorCode4(error, expectedCode) {
@@ -8024,17 +8680,17 @@ function delay5(milliseconds) {
8024
8680
  setTimeout(resolvePromise, milliseconds);
8025
8681
  });
8026
8682
  }
8027
- var import_node_child_process2, import_promises10, import_node_os5, import_node_path7, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerProbeTimeoutMilliseconds, serviceManagerMutationTimeoutMilliseconds, supervisorProgramName, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
8683
+ var import_node_child_process3, import_promises11, import_node_os6, import_node_path8, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerProbeTimeoutMilliseconds, serviceManagerMutationTimeoutMilliseconds, supervisorProgramName, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
8028
8684
  var init_service_manager = __esm({
8029
8685
  "../machine-connector/dist/runtime/service-manager.js"() {
8030
8686
  "use strict";
8031
8687
  init_cjs_shims();
8032
- import_node_child_process2 = require("child_process");
8033
- import_promises10 = require("fs/promises");
8034
- import_node_os5 = require("os");
8035
- import_node_path7 = require("path");
8688
+ import_node_child_process3 = require("child_process");
8689
+ import_promises11 = require("fs/promises");
8690
+ import_node_os6 = require("os");
8691
+ import_node_path8 = require("path");
8036
8692
  import_node_util2 = require("util");
8037
- execFileAsync = (0, import_node_util2.promisify)(import_node_child_process2.execFile);
8693
+ execFileAsync = (0, import_node_util2.promisify)(import_node_child_process3.execFile);
8038
8694
  launchAgentLabel = "ai.moxt.machine-connector";
8039
8695
  serviceManagerProbeTimeoutMilliseconds = 5e3;
8040
8696
  serviceManagerMutationTimeoutMilliseconds = 3e4;
@@ -8052,7 +8708,7 @@ var init_service_manager = __esm({
8052
8708
  UserServiceManager2["Systemd"] = "systemd";
8053
8709
  })(UserServiceManager || (UserServiceManager = {}));
8054
8710
  defaultServiceManagerRuntime = {
8055
- operatingSystem: (0, import_node_os5.platform)(),
8711
+ operatingSystem: (0, import_node_os6.platform)(),
8056
8712
  async run(command, argumentsList, options) {
8057
8713
  const result = await execFileAsync(command, argumentsList, {
8058
8714
  encoding: "utf8",
@@ -8091,7 +8747,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
8091
8747
  try {
8092
8748
  managerOwnsProcess = await managedServiceOwnsProcess(manager, initial.pid, store);
8093
8749
  } catch (error) {
8094
- throw new DaemonRefreshError("ownership", `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage2(error)}`, { cause: error });
8750
+ throw new DaemonRefreshError("ownership", `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage3(error)}`, { cause: error });
8095
8751
  }
8096
8752
  if (!managerOwnsProcess) {
8097
8753
  return { outcome: DaemonReconcileOutcome.Skipped };
@@ -8099,7 +8755,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
8099
8755
  try {
8100
8756
  await validateCliEntrypoint(options, store);
8101
8757
  } catch (error) {
8102
- throw new DaemonRefreshError("validation", errorMessage2(error), {
8758
+ throw new DaemonRefreshError("validation", errorMessage3(error), {
8103
8759
  cause: error
8104
8760
  });
8105
8761
  }
@@ -8110,9 +8766,9 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
8110
8766
  try {
8111
8767
  refresh = await refreshManagedUserService(store, {
8112
8768
  commandArguments: [...options.commandArguments],
8113
- entrypointPath: (0, import_node_path8.resolve)(options.entrypointPath),
8769
+ entrypointPath: (0, import_node_path9.resolve)(options.entrypointPath),
8114
8770
  environment: { ...options.environment },
8115
- nodePath: (0, import_node_path8.resolve)(options.nodePath)
8771
+ nodePath: (0, import_node_path9.resolve)(options.nodePath)
8116
8772
  });
8117
8773
  if (!refresh) {
8118
8774
  throw new Error("The Connector service is no longer managed by Moxt");
@@ -8132,7 +8788,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
8132
8788
  try {
8133
8789
  await refresh.rollback();
8134
8790
  } catch (error) {
8135
- throw new DaemonRefreshError("verification", `${verificationMessage}; restoring the previous service definition also failed: ${errorMessage2(error)}`, { cause: error });
8791
+ throw new DaemonRefreshError("verification", `${verificationMessage}; restoring the previous service definition also failed: ${errorMessage3(error)}`, { cause: error });
8136
8792
  }
8137
8793
  throw new DaemonRefreshError("verification", verificationMessage);
8138
8794
  } finally {
@@ -8143,10 +8799,10 @@ async function validateCliEntrypoint(options, store) {
8143
8799
  if (options.commandArguments.length !== 2 || options.commandArguments[0] !== "machine" || options.commandArguments[1] !== "daemon") {
8144
8800
  throw new Error("The managed daemon command must be `machine daemon`");
8145
8801
  }
8146
- const nodePath = await (0, import_promises11.realpath)((0, import_node_path8.resolve)(options.nodePath));
8147
- const entrypointPath = await (0, import_promises11.realpath)((0, import_node_path8.resolve)(options.entrypointPath));
8148
- await (0, import_promises11.access)(nodePath, import_promises11.constants.X_OK);
8149
- await (0, import_promises11.access)(entrypointPath, import_promises11.constants.R_OK);
8802
+ const nodePath = await (0, import_promises12.realpath)((0, import_node_path9.resolve)(options.nodePath));
8803
+ const entrypointPath = await (0, import_promises12.realpath)((0, import_node_path9.resolve)(options.entrypointPath));
8804
+ await (0, import_promises12.access)(nodePath, import_promises12.constants.X_OK);
8805
+ await (0, import_promises12.access)(entrypointPath, import_promises12.constants.R_OK);
8150
8806
  const probe = await execFileAsync2(nodePath, [entrypointPath, "--version"], {
8151
8807
  encoding: "utf8",
8152
8808
  env: {
@@ -8176,24 +8832,24 @@ async function reachableRuntimeStatus(store) {
8176
8832
  function delay6(milliseconds) {
8177
8833
  return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
8178
8834
  }
8179
- function errorMessage2(error) {
8835
+ function errorMessage3(error) {
8180
8836
  return error instanceof Error ? error.message : String(error);
8181
8837
  }
8182
- var import_node_child_process3, import_promises11, import_node_path8, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshError;
8838
+ var import_node_child_process4, import_promises12, import_node_path9, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshError;
8183
8839
  var init_daemon_reconcile = __esm({
8184
8840
  "../machine-connector/dist/runtime/daemon-reconcile.js"() {
8185
8841
  "use strict";
8186
8842
  init_cjs_shims();
8187
- import_node_child_process3 = require("child_process");
8188
- import_promises11 = require("fs/promises");
8189
- import_node_path8 = require("path");
8843
+ import_node_child_process4 = require("child_process");
8844
+ import_promises12 = require("fs/promises");
8845
+ import_node_path9 = require("path");
8190
8846
  import_node_util3 = require("util");
8191
8847
  init_local_ipc();
8192
8848
  init_process_lock();
8193
8849
  init_service_manager();
8194
8850
  init_store();
8195
8851
  reconcileTimeoutMilliseconds = 12e3;
8196
- execFileAsync2 = (0, import_node_util3.promisify)(import_node_child_process3.execFile);
8852
+ execFileAsync2 = (0, import_node_util3.promisify)(import_node_child_process4.execFile);
8197
8853
  (function(DaemonReconcileOutcome2) {
8198
8854
  DaemonReconcileOutcome2["Restarted"] = "restarted";
8199
8855
  DaemonReconcileOutcome2["Skipped"] = "skipped";
@@ -8225,16 +8881,24 @@ async function runMachineDoctor(store) {
8225
8881
  name: "daemon",
8226
8882
  status: response.error ? DoctorCheckStatus.Failed : DoctorCheckStatus.Passed
8227
8883
  });
8884
+ if (response.status) {
8885
+ const shellEnvironment = response.status.shellEnvironment;
8886
+ checks.push({
8887
+ detail: shellEnvironment.state === "captured" ? "User shell environment captured" : `Using sanitized daemon environment (${shellEnvironment.category ?? "unavailable"})`,
8888
+ name: "shell-environment",
8889
+ status: shellEnvironment.state === "captured" ? DoctorCheckStatus.Passed : DoctorCheckStatus.Warning
8890
+ });
8891
+ }
8228
8892
  } catch (error) {
8229
8893
  checks.push({
8230
- detail: errorMessage3(error),
8894
+ detail: errorMessage4(error),
8231
8895
  name: "daemon",
8232
8896
  status: DoctorCheckStatus.Failed
8233
8897
  });
8234
8898
  }
8235
8899
  for (const connection of connections) {
8236
8900
  try {
8237
- await (0, import_promises12.access)(connection.rootPath, import_node_fs.constants.R_OK | import_node_fs.constants.X_OK);
8901
+ await (0, import_promises13.access)(connection.rootPath, import_node_fs.constants.R_OK | import_node_fs.constants.X_OK);
8238
8902
  checks.push({
8239
8903
  detail: connection.rootPath,
8240
8904
  name: `root:${connection.connectionId}`,
@@ -8242,14 +8906,14 @@ async function runMachineDoctor(store) {
8242
8906
  });
8243
8907
  } catch (error) {
8244
8908
  checks.push({
8245
- detail: errorMessage3(error),
8909
+ detail: errorMessage4(error),
8246
8910
  name: `root:${connection.connectionId}`,
8247
8911
  status: DoctorCheckStatus.Failed
8248
8912
  });
8249
8913
  }
8250
8914
  const relayUrl = new URL(connection.relayOrigin);
8251
8915
  try {
8252
- const address = await (0, import_promises13.lookup)(relayUrl.hostname);
8916
+ const address = await (0, import_promises14.lookup)(relayUrl.hostname);
8253
8917
  checks.push({
8254
8918
  detail: `${relayUrl.hostname} resolves to ${address.address}`,
8255
8919
  name: `dns:${connection.connectionId}`,
@@ -8257,7 +8921,7 @@ async function runMachineDoctor(store) {
8257
8921
  });
8258
8922
  } catch (error) {
8259
8923
  checks.push({
8260
- detail: errorMessage3(error),
8924
+ detail: errorMessage4(error),
8261
8925
  name: `dns:${connection.connectionId}`,
8262
8926
  status: DoctorCheckStatus.Failed
8263
8927
  });
@@ -8281,7 +8945,7 @@ async function runMachineDoctor(store) {
8281
8945
  });
8282
8946
  } catch (error) {
8283
8947
  checks.push({
8284
- detail: errorMessage3(error),
8948
+ detail: errorMessage4(error),
8285
8949
  name: `tls:${connection.connectionId}`,
8286
8950
  status: DoctorCheckStatus.Failed
8287
8951
  });
@@ -8307,7 +8971,7 @@ async function runMachineDoctor(store) {
8307
8971
  });
8308
8972
  } catch (error) {
8309
8973
  checks.push({
8310
- detail: errorMessage3(error),
8974
+ detail: errorMessage4(error),
8311
8975
  name: "codex",
8312
8976
  status: DoctorCheckStatus.Warning
8313
8977
  });
@@ -8321,28 +8985,28 @@ async function runMachineDoctor(store) {
8321
8985
  });
8322
8986
  } catch (error) {
8323
8987
  checks.push({
8324
- detail: errorMessage3(error),
8988
+ detail: errorMessage4(error),
8325
8989
  name: "claude",
8326
8990
  status: DoctorCheckStatus.Warning
8327
8991
  });
8328
8992
  }
8329
8993
  return checks;
8330
8994
  }
8331
- function errorMessage3(error) {
8995
+ function errorMessage4(error) {
8332
8996
  return error instanceof Error ? error.message : String(error);
8333
8997
  }
8334
- var import_node_child_process4, import_promises12, import_node_fs, import_promises13, import_node_util4, execFileAsync3, DoctorCheckStatus;
8998
+ var import_node_child_process5, import_promises13, import_node_fs, import_promises14, import_node_util4, execFileAsync3, DoctorCheckStatus;
8335
8999
  var init_doctor = __esm({
8336
9000
  "../machine-connector/dist/runtime/doctor.js"() {
8337
9001
  "use strict";
8338
9002
  init_cjs_shims();
8339
- import_node_child_process4 = require("child_process");
8340
- import_promises12 = require("fs/promises");
9003
+ import_node_child_process5 = require("child_process");
9004
+ import_promises13 = require("fs/promises");
8341
9005
  import_node_fs = require("fs");
8342
- import_promises13 = require("dns/promises");
9006
+ import_promises14 = require("dns/promises");
8343
9007
  import_node_util4 = require("util");
8344
9008
  init_local_ipc();
8345
- execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process4.execFile);
9009
+ execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process5.execFile);
8346
9010
  (function(DoctorCheckStatus2) {
8347
9011
  DoctorCheckStatus2["Failed"] = "failed";
8348
9012
  DoctorCheckStatus2["Passed"] = "passed";
@@ -8608,7 +9272,7 @@ async function readRecentLogLines(store) {
8608
9272
  }
8609
9273
  async function readOptionalFile(path4) {
8610
9274
  try {
8611
- return await (0, import_promises14.readFile)(path4, "utf8");
9275
+ return await (0, import_promises15.readFile)(path4, "utf8");
8612
9276
  } catch (error) {
8613
9277
  if (isMissingFile(error)) {
8614
9278
  return "";
@@ -8664,16 +9328,16 @@ function isRecord3(value) {
8664
9328
  function isMissingFile(error) {
8665
9329
  return error instanceof Error && "code" in error && error.code === "ENOENT";
8666
9330
  }
8667
- function errorMessage4(error) {
9331
+ function errorMessage5(error) {
8668
9332
  return error instanceof Error ? error.message : String(error);
8669
9333
  }
8670
- var import_promises14, import_promises15, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
9334
+ var import_promises15, import_promises16, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
8671
9335
  var init_machine_manager = __esm({
8672
9336
  "../machine-connector/dist/runtime/machine-manager.js"() {
8673
9337
  "use strict";
8674
9338
  init_cjs_shims();
8675
- import_promises14 = require("fs/promises");
8676
- import_promises15 = require("readline/promises");
9339
+ import_promises15 = require("fs/promises");
9340
+ import_promises16 = require("readline/promises");
8677
9341
  import_node_readline = require("readline");
8678
9342
  init_doctor();
8679
9343
  init_local_ipc();
@@ -8870,7 +9534,7 @@ var init_machine_manager = __esm({
8870
9534
  };
8871
9535
  this.state.message = void 0;
8872
9536
  } catch (error) {
8873
- this.state.message = errorMessage4(error);
9537
+ this.state.message = errorMessage5(error);
8874
9538
  } finally {
8875
9539
  this.refreshing = false;
8876
9540
  this.render();
@@ -8907,7 +9571,7 @@ var init_machine_manager = __esm({
8907
9571
  }
8908
9572
  async runCommandAction(action) {
8909
9573
  this.suspendTerminal();
8910
- const reader = (0, import_promises15.createInterface)({
9574
+ const reader = (0, import_promises16.createInterface)({
8911
9575
  input: process.stdin,
8912
9576
  output: process.stdout
8913
9577
  });
@@ -8918,7 +9582,7 @@ var init_machine_manager = __esm({
8918
9582
  }
8919
9583
  } catch (error) {
8920
9584
  process.stdout.write(`
8921
- Error: ${errorMessage4(error)}
9585
+ Error: ${errorMessage5(error)}
8922
9586
  `);
8923
9587
  }
8924
9588
  await reader.question("\nPress Enter to return to the manager...");
@@ -9086,7 +9750,7 @@ async function pairMachine(store, options) {
9086
9750
  await store.initialize();
9087
9751
  const canonicalRoot = await store.getCanonicalRoot(options.rootPath);
9088
9752
  const identity = await ensureMachineIdentity(store);
9089
- const machineName = options.machineName ?? (0, import_node_os6.hostname)();
9753
+ const machineName = options.machineName ?? (0, import_node_os7.hostname)();
9090
9754
  const operatingSystem = getOperatingSystem();
9091
9755
  const rootHandle = (0, import_node_crypto7.createHash)("sha256").update(identity.identity.deviceKeyFingerprint, "utf8").update("\0").update(canonicalRoot, "utf8").digest("base64url");
9092
9756
  const client = new PairingRelayClient(options.relayOrigin);
@@ -9097,7 +9761,7 @@ async function pairMachine(store, options) {
9097
9761
  machineName,
9098
9762
  operatingSystem,
9099
9763
  protocolVersion: machineProtocolVersion,
9100
- rootDisplayName: (0, import_node_path9.basename)(canonicalRoot),
9764
+ rootDisplayName: (0, import_node_path10.basename)(canonicalRoot),
9101
9765
  rootHandle
9102
9766
  });
9103
9767
  options.onConfirmation?.(proposal.confirmationUrl);
@@ -9125,7 +9789,7 @@ async function pairMachine(store, options) {
9125
9789
  operatingSystem,
9126
9790
  refreshToken: credentials.refreshToken,
9127
9791
  relayOrigin: options.relayOrigin.replace(/\/+$/, ""),
9128
- rootDisplayName: (0, import_node_path9.basename)(canonicalRoot),
9792
+ rootDisplayName: (0, import_node_path10.basename)(canonicalRoot),
9129
9793
  rootHandle,
9130
9794
  rootPath: canonicalRoot,
9131
9795
  targetId: credentials.targetId,
@@ -9146,17 +9810,17 @@ async function pairMachine(store, options) {
9146
9810
  throw new Error("Local Machine pairing expired");
9147
9811
  }
9148
9812
  function getOperatingSystem() {
9149
- if ((0, import_node_os6.platform)() === "darwin") {
9813
+ if ((0, import_node_os7.platform)() === "darwin") {
9150
9814
  return MachineOperatingSystem.MacOS;
9151
9815
  }
9152
- if ((0, import_node_os6.platform)() === "linux") {
9816
+ if ((0, import_node_os7.platform)() === "linux") {
9153
9817
  return MachineOperatingSystem.Linux;
9154
9818
  }
9155
9819
  return MachineOperatingSystem.Windows;
9156
9820
  }
9157
9821
  function openBrowser(url) {
9158
- const command = (0, import_node_os6.platform)() === "darwin" ? "open" : "xdg-open";
9159
- const child = (0, import_node_child_process5.execFile)(command, [url], () => void 0);
9822
+ const command = (0, import_node_os7.platform)() === "darwin" ? "open" : "xdg-open";
9823
+ const child = (0, import_node_child_process6.execFile)(command, [url], () => void 0);
9160
9824
  child.unref();
9161
9825
  }
9162
9826
  function delay7(milliseconds) {
@@ -9164,15 +9828,15 @@ function delay7(milliseconds) {
9164
9828
  setTimeout(resolvePromise, milliseconds);
9165
9829
  });
9166
9830
  }
9167
- var import_node_child_process5, import_node_crypto7, import_node_os6, import_node_path9, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
9831
+ var import_node_child_process6, import_node_crypto7, import_node_os7, import_node_path10, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
9168
9832
  var init_pairing = __esm({
9169
9833
  "../machine-connector/dist/runtime/pairing.js"() {
9170
9834
  "use strict";
9171
9835
  init_cjs_shims();
9172
- import_node_child_process5 = require("child_process");
9836
+ import_node_child_process6 = require("child_process");
9173
9837
  import_node_crypto7 = require("crypto");
9174
- import_node_os6 = require("os");
9175
- import_node_path9 = require("path");
9838
+ import_node_os7 = require("os");
9839
+ import_node_path10 = require("path");
9176
9840
  init_contracts();
9177
9841
  init_version();
9178
9842
  init_enums();
@@ -9207,6 +9871,10 @@ async function runMachineCli(argumentsList, entrypoint) {
9207
9871
  await doctorCommand(store, commandArguments);
9208
9872
  return;
9209
9873
  }
9874
+ if (command === "environment") {
9875
+ await environmentCommand(store, commandArguments);
9876
+ return;
9877
+ }
9210
9878
  if (command === "disconnect") {
9211
9879
  await disconnectCommand(store, commandArguments);
9212
9880
  return;
@@ -9236,7 +9904,7 @@ async function runMachineCli(argumentsList, entrypoint) {
9236
9904
  async function connectCommand(store, argumentsList, entrypoint) {
9237
9905
  const options = parseOptions(argumentsList);
9238
9906
  const connectionCode = requiredOption(options, "code");
9239
- const rootPath = (0, import_node_path10.resolve)(options.root ?? process.cwd());
9907
+ const rootPath = (0, import_node_path11.resolve)(options.root ?? process.cwd());
9240
9908
  const serviceManagerPreference = requestedServiceManagerPreference(options);
9241
9909
  await validateExplicitServiceManagerPreference(serviceManagerPreference);
9242
9910
  writeLine("Internal Full Host Access: enabled");
@@ -9344,6 +10012,24 @@ async function doctorCommand(store, argumentsList) {
9344
10012
  process.exitCode = 1;
9345
10013
  }
9346
10014
  }
10015
+ async function environmentCommand(store, argumentsList) {
10016
+ const action = argumentsList[0] ?? "status";
10017
+ const response = action === "refresh" ? await requestEnvironmentRefresh(store) : action === "status" ? await requestRuntimeStatus(store) : void 0;
10018
+ if (!response) {
10019
+ throw new Error(`Unsupported environment action: ${action}`);
10020
+ }
10021
+ if (response.error) {
10022
+ throw new Error(response.error);
10023
+ }
10024
+ const status = action === "refresh" ? response.environmentRefresh : response.status?.shellEnvironment;
10025
+ if (!status) {
10026
+ throw new Error("Connector did not return shell environment status");
10027
+ }
10028
+ writeLine(`Shell environment: ${status.state}${status.category ? ` (${status.category})` : ""}`);
10029
+ if (action === "refresh" && status.state === "degraded") {
10030
+ process.exitCode = 1;
10031
+ }
10032
+ }
9347
10033
  async function disconnectCommand(store, argumentsList) {
9348
10034
  const options = parseOptions(argumentsList);
9349
10035
  const connectionId = requiredOption(options, "connection");
@@ -9503,7 +10189,7 @@ async function waitForDaemonOnline(store) {
9503
10189
  }
9504
10190
  async function readOptionalFile2(path4) {
9505
10191
  try {
9506
- return await (0, import_promises16.readFile)(path4, "utf8");
10192
+ return await (0, import_promises17.readFile)(path4, "utf8");
9507
10193
  } catch {
9508
10194
  return "";
9509
10195
  }
@@ -9516,6 +10202,7 @@ Usage:
9516
10202
  moxt machine status [--json]
9517
10203
  moxt machine logs [--lines 100]
9518
10204
  moxt machine doctor [--json]
10205
+ moxt machine environment <status|refresh>
9519
10206
  moxt machine disconnect --connection <id> [--local-only]
9520
10207
  moxt machine manager
9521
10208
  moxt machine service install [--service-manager <auto|systemd|supervisor|none>]
@@ -9531,13 +10218,13 @@ function delay8(milliseconds) {
9531
10218
  setTimeout(resolvePromise, milliseconds);
9532
10219
  });
9533
10220
  }
9534
- var import_promises16, import_node_path10, defaultRelayOrigin;
10221
+ var import_promises17, import_node_path11, defaultRelayOrigin;
9535
10222
  var init_cli = __esm({
9536
10223
  "../machine-connector/dist/cli.js"() {
9537
10224
  "use strict";
9538
10225
  init_cjs_shims();
9539
- import_promises16 = require("fs/promises");
9540
- import_node_path10 = require("path");
10226
+ import_promises17 = require("fs/promises");
10227
+ import_node_path11 = require("path");
9541
10228
  init_daemon();
9542
10229
  init_daemon_reconcile();
9543
10230
  init_doctor();
@@ -9611,6 +10298,7 @@ __export(dist_exports, {
9611
10298
  recordedServiceManager: () => recordedServiceManager,
9612
10299
  refreshManagedUserService: () => refreshManagedUserService,
9613
10300
  renderMachineManager: () => renderMachineManager,
10301
+ requestEnvironmentRefresh: () => requestEnvironmentRefresh,
9614
10302
  requestRuntimeStatus: () => requestRuntimeStatus,
9615
10303
  resolveWorkingDirectory: () => resolveWorkingDirectory,
9616
10304
  restartUserService: () => restartUserService,
@@ -9818,10 +10506,10 @@ function getApiKeyOrUndefined() {
9818
10506
 
9819
10507
  // src/utils/http.ts
9820
10508
  function getUserAgent() {
9821
- return `moxt-cli/${"0.8.2"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
10509
+ return `moxt-cli/${"0.9.0"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
9822
10510
  }
9823
10511
  async function sendRequest(method, path4, init) {
9824
- const response = await fetch(`${getApiBaseUrl()}${path4}`, {
10512
+ return await fetch(`${getApiBaseUrl()}${path4}`, {
9825
10513
  method,
9826
10514
  headers: {
9827
10515
  Authorization: `Bearer ${getApiKey()}`,
@@ -9830,6 +10518,9 @@ async function sendRequest(method, path4, init) {
9830
10518
  },
9831
10519
  body: init.body
9832
10520
  });
10521
+ }
10522
+ async function sendRequestOrExitOnAuthenticationFailure(method, path4, init) {
10523
+ const response = await sendRequest(method, path4, init);
9833
10524
  if (response.status === 401) {
9834
10525
  console.error("Authentication failed. Check your MOXT_API_KEY.");
9835
10526
  console.error("Get a new key at: https://moxt.ai");
@@ -9838,11 +10529,16 @@ async function sendRequest(method, path4, init) {
9838
10529
  return response;
9839
10530
  }
9840
10531
  async function fetchApi(method, path4, body) {
9841
- return await sendRequest(method, path4, {
10532
+ return await sendRequestOrExitOnAuthenticationFailure(method, path4, {
9842
10533
  headers: { "Content-Type": "application/json" },
9843
10534
  body: body ? JSON.stringify(body) : void 0
9844
10535
  });
9845
10536
  }
10537
+ async function fetchApiIncludingUnauthorized(method, path4) {
10538
+ return await sendRequest(method, path4, {
10539
+ headers: { "Content-Type": "application/json" }
10540
+ });
10541
+ }
9846
10542
  async function toApiResponse(response) {
9847
10543
  const contentType = response.headers.get("content-type");
9848
10544
  const data = contentType?.includes("application/json") ? await response.json() : await response.text();
@@ -9858,6 +10554,9 @@ async function request(method, path4, body) {
9858
10554
  async function httpGet(path4) {
9859
10555
  return request("GET", path4);
9860
10556
  }
10557
+ async function httpGetIncludingUnauthorized(path4) {
10558
+ return await toApiResponse(await fetchApiIncludingUnauthorized("GET", path4));
10559
+ }
9861
10560
  async function httpPut(path4, body) {
9862
10561
  return request("PUT", path4, body);
9863
10562
  }
@@ -9880,7 +10579,7 @@ async function httpRaw(method, path4, body) {
9880
10579
  };
9881
10580
  }
9882
10581
  async function httpPostMultipart(path4, formData) {
9883
- return await toApiResponse(await sendRequest("POST", path4, { body: formData }));
10582
+ return await toApiResponse(await sendRequestOrExitOnAuthenticationFailure("POST", path4, { body: formData }));
9884
10583
  }
9885
10584
 
9886
10585
  // src/utils/output.ts
@@ -9994,8 +10693,8 @@ function readCommentContentFile(path4) {
9994
10693
  if (!fs.existsSync(path4)) {
9995
10694
  throw new FileCommentOptionsError(`Error: comment content file not found: ${path4}`);
9996
10695
  }
9997
- const stat3 = fs.statSync(path4);
9998
- if (!stat3.isFile()) {
10696
+ const stat4 = fs.statSync(path4);
10697
+ if (!stat4.isFile()) {
9999
10698
  throw new FileCommentOptionsError(`Error: comment content path is not a file: ${path4}`);
10000
10699
  }
10001
10700
  const buffer2 = fs.readFileSync(path4);
@@ -10669,8 +11368,8 @@ var FileTokenizer = class _FileTokenizer extends AbstractTokenizer {
10669
11368
  */
10670
11369
  static async fromFile(sourceFilePath) {
10671
11370
  const fileHandle = await (0, import_promises.open)(sourceFilePath, "r");
10672
- const stat3 = await fileHandle.stat();
10673
- return new _FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat3.size } });
11371
+ const stat4 = await fileHandle.stat();
11372
+ return new _FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat4.size } });
10674
11373
  }
10675
11374
  constructor(fileHandle, options) {
10676
11375
  super(options);
@@ -21129,6 +21828,31 @@ function runOrExit2(fn) {
21129
21828
  }
21130
21829
 
21131
21830
  // src/commands/file.ts
21831
+ function exitFileReadJson(error) {
21832
+ console.error(JSON.stringify({ error }));
21833
+ process.exit(1);
21834
+ }
21835
+ function runFileReadResolverOrExit(fn, outputMode) {
21836
+ if (outputMode === "text") {
21837
+ return runOrExit2(fn);
21838
+ }
21839
+ try {
21840
+ return fn();
21841
+ } catch (error) {
21842
+ if (error instanceof SpaceOptionsError) {
21843
+ exitFileReadJson({
21844
+ code: "invalid_arguments",
21845
+ message: error.message.replace(/^Error:\s*/, ""),
21846
+ status: null,
21847
+ details: null
21848
+ });
21849
+ }
21850
+ throw error;
21851
+ }
21852
+ }
21853
+ function errorMessage(error) {
21854
+ return error instanceof Error ? error.message : String(error);
21855
+ }
21132
21856
  async function uploadLocalImage(asset) {
21133
21857
  const formData = new FormData();
21134
21858
  formData.append("file", new Blob([new Uint8Array(asset.bytes)], { type: asset.mimeType }), asset.fileName);
@@ -21246,26 +21970,70 @@ function registerFileCommand(program3) {
21246
21970
  }
21247
21971
  }
21248
21972
  });
21249
- file.command("read").description("Read file content").option("-w, --workspace <workspaceId>", "Workspace ID").option("-s, --space <name>", "Space name (personal or teamspace name)").option("--personal", "Use personal space (default)").option("--team-space-id <teamSpaceId>", "Team space ID").option("--teammate-id <teammateId>", "Teammate ID (teammate space)").option("-p, --path <path>", "File path").option("-u, --url <url>", "Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})").action(async (options) => {
21250
- const mode = runOrExit2(() => resolveReadMode(options));
21251
- startSpinner("Reading file...");
21973
+ file.command("read").description("Read file content").option("-w, --workspace <workspaceId>", "Workspace ID").option("-s, --space <name>", "Space name (personal or teamspace name)").option("--personal", "Use personal space (default)").option("--team-space-id <teamSpaceId>", "Team space ID").option("--teammate-id <teammateId>", "Teammate ID (teammate space)").option("-p, --path <path>", "File path").option("-u, --url <url>", "Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})").option("--json", "Emit file content and metadata as JSON").action(async (options) => {
21974
+ const outputMode = options.json ? "json" : "text";
21975
+ const mode = runFileReadResolverOrExit(() => resolveReadMode(options), outputMode);
21252
21976
  let response;
21253
21977
  let displayPath;
21978
+ let requestPath;
21254
21979
  if (mode.kind === "by-url") {
21255
21980
  displayPath = mode.url;
21256
- response = await httpGet(
21257
- `/files/read-by-url?url=${encodeURIComponent(mode.url)}`
21258
- );
21981
+ requestPath = `/files/read-by-url?url=${encodeURIComponent(mode.url)}`;
21259
21982
  } else {
21260
21983
  displayPath = mode.path;
21261
- const spaceParams = runOrExit2(() => resolveSpaceSelector(options));
21262
- const qs = buildFileQueryString(mode.path, spaceParams);
21263
- response = await httpGet(
21264
- `/workspaces/${mode.workspace}/files/read${qs}`
21984
+ const spaceParams = runFileReadResolverOrExit(
21985
+ () => resolveSpaceSelector(options),
21986
+ outputMode
21265
21987
  );
21988
+ const qs = buildFileQueryString(mode.path, spaceParams);
21989
+ requestPath = `/workspaces/${mode.workspace}/files/read${qs}`;
21990
+ }
21991
+ if (options.json && getApiKeyOrUndefined() === void 0) {
21992
+ exitFileReadJson({
21993
+ code: "configuration_error",
21994
+ message: "MOXT_API_KEY environment variable is not set.",
21995
+ status: null,
21996
+ details: null
21997
+ });
21998
+ }
21999
+ try {
22000
+ response = options.json ? await httpGetIncludingUnauthorized(requestPath) : await httpGet(requestPath);
22001
+ } catch (error) {
22002
+ if (options.json) {
22003
+ exitFileReadJson({
22004
+ code: "request_failed",
22005
+ message: `File read request failed: ${errorMessage(error)}`,
22006
+ status: null,
22007
+ details: null
22008
+ });
22009
+ }
22010
+ throw error;
21266
22011
  }
21267
22012
  if (!response.ok) {
21268
- stopSpinner(false, "Failed");
22013
+ if (options.json) {
22014
+ if (response.status === 401) {
22015
+ exitFileReadJson({
22016
+ code: "authentication_failed",
22017
+ message: "Authentication failed. Check your MOXT_API_KEY.",
22018
+ status: response.status,
22019
+ details: response.data
22020
+ });
22021
+ }
22022
+ if (response.status === 404) {
22023
+ exitFileReadJson({
22024
+ code: "not_found",
22025
+ message: `${displayPath} does not exist`,
22026
+ status: response.status,
22027
+ details: response.data
22028
+ });
22029
+ }
22030
+ exitFileReadJson({
22031
+ code: "api_error",
22032
+ message: `File read failed with HTTP status ${response.status}.`,
22033
+ status: response.status,
22034
+ details: response.data
22035
+ });
22036
+ }
21269
22037
  if (response.status === 404) {
21270
22038
  print(`${colors.red}\u2620 ${displayPath} does not exist${colors.reset}`);
21271
22039
  } else {
@@ -21275,12 +22043,22 @@ function registerFileCommand(program3) {
21275
22043
  }
21276
22044
  const { type, content: content3 } = response.data;
21277
22045
  if (type === "directory") {
21278
- stopSpinner(false, "Failed");
22046
+ if (options.json) {
22047
+ exitFileReadJson({
22048
+ code: "not_a_file",
22049
+ message: `${displayPath} is a directory`,
22050
+ status: null,
22051
+ details: null
22052
+ });
22053
+ }
21279
22054
  print(`${colors.red}\u2620 ${displayPath} is a directory${colors.reset}`);
21280
22055
  process.exit(1);
21281
22056
  }
21282
- stopSpinner(true, "Done");
21283
- print(content3 ?? "");
22057
+ if (options.json) {
22058
+ print(JSON.stringify(response.data));
22059
+ } else {
22060
+ process.stdout.write(content3);
22061
+ }
21284
22062
  });
21285
22063
  file.command("put").description("Upload a file").option("-w, --workspace <workspaceId>", "Workspace ID").option("-s, --space <name>", "Space name (personal or teamspace name)").option("--personal", "Use personal space (default)").option("--team-space-id <teamSpaceId>", "Team space ID").option("--teammate-id <teammateId>", "Teammate ID (teammate space)").option("-p, --path <path>", "Remote file path").option("-u, --url <url>", "Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})").requiredOption("-l, --local-path <localPath>", "Local file path").option("-r, --recursive", "Create parent directories if needed").action(
21286
22064
  async (options) => {
@@ -21805,7 +22583,7 @@ init_cjs_shims();
21805
22583
 
21806
22584
  // src/update/install.ts
21807
22585
  init_cjs_shims();
21808
- var import_node_child_process6 = require("child_process");
22586
+ var import_node_child_process7 = require("child_process");
21809
22587
  var import_node_fs2 = require("fs");
21810
22588
  var path3 = __toESM(require("path"), 1);
21811
22589
 
@@ -21921,7 +22699,7 @@ function runUpgrade(channel, targetVersion) {
21921
22699
  }
21922
22700
  process.stderr.write(`Updating via \`${display}\`...
21923
22701
  `);
21924
- const installation = (0, import_node_child_process6.spawnSync)(plan.command, plan.args, {
22702
+ const installation = (0, import_node_child_process7.spawnSync)(plan.command, plan.args, {
21925
22703
  encoding: "utf8",
21926
22704
  env: process.env,
21927
22705
  maxBuffer: 10 * 1024 * 1024,
@@ -21936,7 +22714,7 @@ function runUpgrade(channel, targetVersion) {
21936
22714
  success: false
21937
22715
  };
21938
22716
  }
21939
- const verification = (0, import_node_child_process6.spawnSync)("moxt", ["--version"], {
22717
+ const verification = (0, import_node_child_process7.spawnSync)("moxt", ["--version"], {
21940
22718
  encoding: "utf8",
21941
22719
  env: process.env,
21942
22720
  maxBuffer: 1024 * 1024,
@@ -21950,7 +22728,7 @@ function runUpgrade(channel, targetVersion) {
21950
22728
  success: false
21951
22729
  };
21952
22730
  }
21953
- const daemonRefresh = (0, import_node_child_process6.spawnSync)(
22731
+ const daemonRefresh = (0, import_node_child_process7.spawnSync)(
21954
22732
  "moxt",
21955
22733
  ["machine", "daemon-reconcile", "--report"],
21956
22734
  {
@@ -22349,8 +23127,8 @@ function readDescFile(path4) {
22349
23127
  if (!fs5.existsSync(path4)) {
22350
23128
  throw new WorkflowOptionsError(`Error: desc file not found: ${path4}`);
22351
23129
  }
22352
- const stat3 = fs5.statSync(path4);
22353
- if (!stat3.isFile()) {
23130
+ const stat4 = fs5.statSync(path4);
23131
+ if (!stat4.isFile()) {
22354
23132
  throw new WorkflowOptionsError(`Error: desc file is not a file: ${path4}`);
22355
23133
  }
22356
23134
  const buffer2 = fs5.readFileSync(path4);
@@ -22367,11 +23145,11 @@ function readCommentContentFile2(path4) {
22367
23145
  if (!fs5.existsSync(path4)) {
22368
23146
  throw new WorkflowOptionsError(`Error: comment content file not found: ${path4}`);
22369
23147
  }
22370
- const stat3 = fs5.statSync(path4);
22371
- if (!stat3.isFile()) {
23148
+ const stat4 = fs5.statSync(path4);
23149
+ if (!stat4.isFile()) {
22372
23150
  throw new WorkflowOptionsError(`Error: comment content path is not a file: ${path4}`);
22373
23151
  }
22374
- if (stat3.size > MAX_COMMENT_CONTENT_BYTES) {
23152
+ if (stat4.size > MAX_COMMENT_CONTENT_BYTES) {
22375
23153
  throw new WorkflowOptionsError(
22376
23154
  `Error: comment content file must be at most ${MAX_COMMENT_CONTENT_LENGTH} characters.`
22377
23155
  );
@@ -23305,16 +24083,16 @@ function createProgram(version) {
23305
24083
 
23306
24084
  // src/telemetry/client.ts
23307
24085
  init_cjs_shims();
23308
- var import_node_os7 = require("os");
24086
+ var import_node_os8 = require("os");
23309
24087
  var buffer = [];
23310
24088
  var FLUSH_TIMEOUT_MS = 3e3;
23311
24089
  var MAX_BATCH_SIZE = 100;
23312
24090
  function commonLabels() {
23313
24091
  return {
23314
- cli_version: "0.8.2",
24092
+ cli_version: "0.9.0",
23315
24093
  node_version: process.versions.node,
23316
- os: (0, import_node_os7.platform)(),
23317
- arch: (0, import_node_os7.arch)(),
24094
+ os: (0, import_node_os8.platform)(),
24095
+ arch: (0, import_node_os8.arch)(),
23318
24096
  is_ci: isCiEnvironment() ? "true" : "false"
23319
24097
  };
23320
24098
  }
@@ -23357,7 +24135,7 @@ async function flush() {
23357
24135
  }
23358
24136
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
23359
24137
  const payload = {
23360
- release_id: "0.8.2",
24138
+ release_id: "0.9.0",
23361
24139
  client_type: "cli",
23362
24140
  metric_data_list: batch.map((m) => ({
23363
24141
  profile: "cli",
@@ -23558,7 +24336,7 @@ function registryWorker() {
23558
24336
 
23559
24337
  // src/update/prompt.ts
23560
24338
  init_cjs_shims();
23561
- var import_promises17 = require("readline/promises");
24339
+ var import_promises18 = require("readline/promises");
23562
24340
  async function promptForUpdate(input, output, currentVersion, latestVersion, timeoutMs) {
23563
24341
  output.write(`
23564
24342
  A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion}
@@ -23571,7 +24349,7 @@ A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion
23571
24349
  const controller = new AbortController();
23572
24350
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
23573
24351
  timeout.unref();
23574
- const readline = (0, import_promises17.createInterface)({ input, output, terminal: true });
24352
+ const readline = (0, import_promises18.createInterface)({ input, output, terminal: true });
23575
24353
  try {
23576
24354
  const answer = await readline.question("", { signal: controller.signal });
23577
24355
  if (answer.trim() === "1") return "update";
@@ -23674,7 +24452,7 @@ function commandPath2(command) {
23674
24452
 
23675
24453
  // src/update/daemon-reconcile-hook.ts
23676
24454
  init_cjs_shims();
23677
- var import_node_path11 = require("path");
24455
+ var import_node_path12 = require("path");
23678
24456
  function installDaemonReconcileHook(program3, cliVersion) {
23679
24457
  program3.hook("preAction", async (_thisCommand, actionCommand) => {
23680
24458
  if (!isEligible2(actionCommand)) return;
@@ -23688,9 +24466,9 @@ function installDaemonReconcileHook(program3, cliVersion) {
23688
24466
  await reconcileManagedDaemon2({
23689
24467
  cliVersion,
23690
24468
  commandArguments: ["machine", "daemon"],
23691
- entrypointPath: (0, import_node_path11.resolve)(entrypointPath),
24469
+ entrypointPath: (0, import_node_path12.resolve)(entrypointPath),
23692
24470
  environment: {},
23693
- nodePath: (0, import_node_path11.resolve)(process.execPath),
24471
+ nodePath: (0, import_node_path12.resolve)(process.execPath),
23694
24472
  onActiveJobs: (count) => {
23695
24473
  process.stderr.write(
23696
24474
  `Warning: restarting the managed Connector will interrupt ${count} active ${count === 1 ? "Job" : "Jobs"}.
@@ -23732,9 +24510,9 @@ function commandPath3(command) {
23732
24510
  }
23733
24511
 
23734
24512
  // src/index.ts
23735
- var program2 = createProgram("0.8.2");
23736
- installDaemonReconcileHook(program2, "0.8.2");
23737
- installUpdateHook(program2, "0.8.2");
24513
+ var program2 = createProgram("0.9.0");
24514
+ installDaemonReconcileHook(program2, "0.9.0");
24515
+ installUpdateHook(program2, "0.9.0");
23738
24516
  instrumentProgram(program2);
23739
24517
  installExitHandler();
23740
24518
  program2.parseAsync(process.argv).then(async () => {