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

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
@@ -4849,6 +4849,118 @@ var init_claude_executor = __esm({
4849
4849
  }
4850
4850
  });
4851
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
+
4852
4964
  // ../machine-connector/dist/runtime/codex-executor.js
4853
4965
  async function executeCodexStart(workingDirectory, runtimeDirectory, environment, spec, callbacks) {
4854
4966
  const outputPath = createOutputPath(runtimeDirectory);
@@ -5270,6 +5382,202 @@ var init_execution_cancellation = __esm({
5270
5382
  }
5271
5383
  });
5272
5384
 
5385
+ // ../machine-connector/dist/runtime/local-ipc.js
5386
+ async function requestRuntimeStatus(store, timeoutMilliseconds = 1e3) {
5387
+ return await requestLocalIpc(store, "status", timeoutMilliseconds);
5388
+ }
5389
+ async function requestEnvironmentRefresh(store, timeoutMilliseconds = 1e4) {
5390
+ return await requestLocalIpc(store, "environment_refresh", timeoutMilliseconds);
5391
+ }
5392
+ async function requestLocalIpc(store, action, timeoutMilliseconds) {
5393
+ return await new Promise((resolvePromise, rejectPromise) => {
5394
+ const socket = (0, import_node_net.createConnection)(store.runtimeSocketPath());
5395
+ let responseText = "";
5396
+ socket.setEncoding("utf8");
5397
+ socket.once("error", rejectPromise);
5398
+ socket.setTimeout(timeoutMilliseconds, () => {
5399
+ socket.destroy(new Error(`Runtime status timed out after ${timeoutMilliseconds}ms`));
5400
+ });
5401
+ socket.on("data", (chunk) => {
5402
+ responseText += chunk;
5403
+ });
5404
+ socket.once("close", () => {
5405
+ try {
5406
+ resolvePromise(JSON.parse(responseText.trim()));
5407
+ } catch (error) {
5408
+ rejectPromise(error);
5409
+ }
5410
+ });
5411
+ socket.once("connect", () => {
5412
+ socket.write(`${JSON.stringify({ action })}
5413
+ `);
5414
+ });
5415
+ });
5416
+ }
5417
+ var import_promises5, import_node_net, import_node_os2, LocalIpcServer;
5418
+ var init_local_ipc = __esm({
5419
+ "../machine-connector/dist/runtime/local-ipc.js"() {
5420
+ "use strict";
5421
+ init_cjs_shims();
5422
+ import_promises5 = require("fs/promises");
5423
+ import_node_net = require("net");
5424
+ import_node_os2 = require("os");
5425
+ LocalIpcServer = class {
5426
+ store;
5427
+ getStatus;
5428
+ refreshEnvironment;
5429
+ server;
5430
+ constructor(store, getStatus, refreshEnvironment) {
5431
+ this.store = store;
5432
+ this.getStatus = getStatus;
5433
+ this.refreshEnvironment = refreshEnvironment;
5434
+ }
5435
+ async start() {
5436
+ const socketPath = this.store.runtimeSocketPath();
5437
+ if ((0, import_node_os2.platform)() !== "win32") {
5438
+ await (0, import_promises5.rm)(socketPath, { force: true });
5439
+ }
5440
+ this.server = (0, import_node_net.createServer)((socket) => {
5441
+ let requestText = "";
5442
+ let handled = false;
5443
+ socket.setEncoding("utf8");
5444
+ socket.on("data", (chunk) => {
5445
+ requestText += chunk;
5446
+ if (handled || !requestText.includes("\n")) {
5447
+ return;
5448
+ }
5449
+ handled = true;
5450
+ void this.handleRequest(requestText).then((response) => {
5451
+ socket.end(`${JSON.stringify(response)}
5452
+ `);
5453
+ });
5454
+ });
5455
+ });
5456
+ await new Promise((resolvePromise, rejectPromise) => {
5457
+ this.server?.once("error", rejectPromise);
5458
+ this.server?.listen(socketPath, resolvePromise);
5459
+ });
5460
+ if ((0, import_node_os2.platform)() !== "win32") {
5461
+ await (0, import_promises5.chmod)(socketPath, 384);
5462
+ }
5463
+ }
5464
+ async close() {
5465
+ if (!this.server) {
5466
+ return;
5467
+ }
5468
+ await new Promise((resolvePromise) => {
5469
+ this.server?.close(() => resolvePromise());
5470
+ });
5471
+ if ((0, import_node_os2.platform)() !== "win32") {
5472
+ await (0, import_promises5.rm)(this.store.runtimeSocketPath(), { force: true });
5473
+ }
5474
+ }
5475
+ async handleRequest(requestText) {
5476
+ try {
5477
+ const request2 = JSON.parse(requestText.trim());
5478
+ if (request2.action === "status") {
5479
+ return { status: this.getStatus() };
5480
+ }
5481
+ if (request2.action === "environment_refresh") {
5482
+ if (!this.refreshEnvironment) {
5483
+ return { error: "Environment refresh is unavailable" };
5484
+ }
5485
+ return {
5486
+ environmentRefresh: await this.refreshEnvironment()
5487
+ };
5488
+ }
5489
+ return { error: `Unsupported IPC action: ${request2.action}` };
5490
+ } catch (error) {
5491
+ return {
5492
+ error: error instanceof Error ? error.message : "Invalid IPC request"
5493
+ };
5494
+ }
5495
+ }
5496
+ };
5497
+ }
5498
+ });
5499
+
5500
+ // ../machine-connector/dist/runtime/execution-context.js
5501
+ function createLocalMachineJobExecutionContext(connectorInstanceId, runtimeDirectory) {
5502
+ if (!connectorInstanceId) {
5503
+ throw new Error("Connector instance ID is required");
5504
+ }
5505
+ return {
5506
+ connectorInstanceId,
5507
+ kind: "local_machine_job",
5508
+ runtimeDirectory: (0, import_node_path4.resolve)(runtimeDirectory)
5509
+ };
5510
+ }
5511
+ function serializeLocalMachineJobExecutionContext(context) {
5512
+ return `${localMachineJobPrefix}${Buffer.from(JSON.stringify(context), "utf8").toString("base64url")}`;
5513
+ }
5514
+ function parseLocalMachineJobExecutionContext(value) {
5515
+ if (!value?.startsWith(localMachineJobPrefix))
5516
+ return void 0;
5517
+ try {
5518
+ const decoded = JSON.parse(Buffer.from(value.slice(localMachineJobPrefix.length), "base64url").toString("utf8"));
5519
+ if (decoded.kind !== "local_machine_job" || typeof decoded.connectorInstanceId !== "string" || decoded.connectorInstanceId.length === 0 || typeof decoded.runtimeDirectory !== "string" || decoded.runtimeDirectory.length === 0 || (0, import_node_path4.resolve)(decoded.runtimeDirectory) !== decoded.runtimeDirectory) {
5520
+ return void 0;
5521
+ }
5522
+ return decoded;
5523
+ } catch {
5524
+ return void 0;
5525
+ }
5526
+ }
5527
+ async function localMachineJobTargetRelationship(store, value = process.env[machineExecutionContextEnvironmentName]) {
5528
+ const context = parseLocalMachineJobExecutionContext(value);
5529
+ if (!context)
5530
+ return void 0;
5531
+ const targetRuntimeDirectory = (0, import_node_path4.resolve)(store.baseDirectory);
5532
+ const carryingRuntimeDirectory = (0, import_node_path4.resolve)(context.runtimeDirectory);
5533
+ if (targetRuntimeDirectory !== carryingRuntimeDirectory) {
5534
+ try {
5535
+ const [canonicalTarget, canonicalCarrying] = await Promise.all([
5536
+ canonicalizePotentialRuntimeDirectory(targetRuntimeDirectory),
5537
+ canonicalizePotentialRuntimeDirectory(carryingRuntimeDirectory)
5538
+ ]);
5539
+ if (canonicalTarget !== canonicalCarrying) {
5540
+ return "different_runtime";
5541
+ }
5542
+ } catch {
5543
+ return "same_runtime_stale_or_unreachable";
5544
+ }
5545
+ }
5546
+ try {
5547
+ const status = (await requestRuntimeStatus(store)).status;
5548
+ if (status?.connectorInstanceId === context.connectorInstanceId) {
5549
+ return "matching_instance";
5550
+ }
5551
+ } catch {
5552
+ }
5553
+ return "same_runtime_stale_or_unreachable";
5554
+ }
5555
+ async function canonicalizePotentialRuntimeDirectory(path4) {
5556
+ try {
5557
+ return await (0, import_promises6.realpath)(path4);
5558
+ } catch (error) {
5559
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") {
5560
+ throw error;
5561
+ }
5562
+ const parent = (0, import_node_path4.dirname)(path4);
5563
+ if (parent === path4)
5564
+ return path4;
5565
+ return (0, import_node_path4.join)(await canonicalizePotentialRuntimeDirectory(parent), (0, import_node_path4.basename)(path4));
5566
+ }
5567
+ }
5568
+ var import_promises6, import_node_path4, machineExecutionContextEnvironmentName, localMachineJobPrefix;
5569
+ var init_execution_context = __esm({
5570
+ "../machine-connector/dist/runtime/execution-context.js"() {
5571
+ "use strict";
5572
+ init_cjs_shims();
5573
+ import_promises6 = require("fs/promises");
5574
+ import_node_path4 = require("path");
5575
+ init_local_ipc();
5576
+ machineExecutionContextEnvironmentName = "MOXT_MACHINE_EXECUTION_CONTEXT";
5577
+ localMachineJobPrefix = "local_machine_job:v1:";
5578
+ }
5579
+ });
5580
+
5273
5581
  // ../machine-connector/dist/runtime/image-viewer.js
5274
5582
  async function viewLocalMachineImage(rootPath, relativeImagePath) {
5275
5583
  validateRelativeImagePath(relativeImagePath);
@@ -5296,41 +5604,41 @@ async function viewLocalMachineImage(rootPath, relativeImagePath) {
5296
5604
  }
5297
5605
  async function resolvePairedRoot(rootPath) {
5298
5606
  try {
5299
- return await (0, import_promises5.realpath)(rootPath);
5607
+ return await (0, import_promises7.realpath)(rootPath);
5300
5608
  } catch {
5301
5609
  throw new Error("Paired Local Machine root is unavailable");
5302
5610
  }
5303
5611
  }
5304
5612
  async function resolveImagePath(canonicalRoot, relativeImagePath) {
5305
5613
  try {
5306
- return await (0, import_promises5.realpath)((0, import_node_path4.resolve)(canonicalRoot, relativeImagePath));
5614
+ return await (0, import_promises7.realpath)((0, import_node_path5.resolve)(canonicalRoot, relativeImagePath));
5307
5615
  } catch {
5308
5616
  throw new Error(`Image could not be read: ${relativeImagePath}`);
5309
5617
  }
5310
5618
  }
5311
5619
  async function statImage(canonicalImage, relativeImagePath) {
5312
5620
  try {
5313
- return await (0, import_promises5.stat)(canonicalImage);
5621
+ return await (0, import_promises7.stat)(canonicalImage);
5314
5622
  } catch {
5315
5623
  throw new Error(`Image could not be read: ${relativeImagePath}`);
5316
5624
  }
5317
5625
  }
5318
5626
  async function readImageBytes(canonicalImage, relativeImagePath) {
5319
5627
  try {
5320
- return await (0, import_promises5.readFile)(canonicalImage);
5628
+ return await (0, import_promises7.readFile)(canonicalImage);
5321
5629
  } catch {
5322
5630
  throw new Error(`Image could not be read: ${relativeImagePath}`);
5323
5631
  }
5324
5632
  }
5325
5633
  function validateRelativeImagePath(path4) {
5326
5634
  const segments = path4.split(/[\\/]/);
5327
- if (path4.length === 0 || path4.length > 4096 || path4.includes("\0") || (0, import_node_path4.isAbsolute)(path4) || import_node_path4.win32.isAbsolute(path4) || segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
5635
+ if (path4.length === 0 || path4.length > 4096 || path4.includes("\0") || (0, import_node_path5.isAbsolute)(path4) || import_node_path5.win32.isAbsolute(path4) || segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
5328
5636
  throw new Error(`Invalid relative image path: ${path4}`);
5329
5637
  }
5330
5638
  }
5331
5639
  function requireInsideRoot(canonicalRoot, canonicalImage) {
5332
- const relativePath = (0, import_node_path4.relative)(canonicalRoot, canonicalImage);
5333
- if (relativePath === ".." || relativePath.startsWith(`..${import_node_path4.sep}`) || (0, import_node_path4.isAbsolute)(relativePath)) {
5640
+ const relativePath = (0, import_node_path5.relative)(canonicalRoot, canonicalImage);
5641
+ if (relativePath === ".." || relativePath.startsWith(`..${import_node_path5.sep}`) || (0, import_node_path5.isAbsolute)(relativePath)) {
5334
5642
  throw new Error("Image path escapes paired root");
5335
5643
  }
5336
5644
  }
@@ -5530,147 +5838,32 @@ function startsWithAscii(bytes, offset, text3) {
5530
5838
  }
5531
5839
  return true;
5532
5840
  }
5533
- var import_promises5, import_node_path4, maximumLocalMachineImageBytes;
5841
+ var import_promises7, import_node_path5, maximumLocalMachineImageBytes;
5534
5842
  var init_image_viewer = __esm({
5535
5843
  "../machine-connector/dist/runtime/image-viewer.js"() {
5536
5844
  "use strict";
5537
5845
  init_cjs_shims();
5538
- import_promises5 = require("fs/promises");
5539
- import_node_path4 = require("path");
5846
+ import_promises7 = require("fs/promises");
5847
+ import_node_path5 = require("path");
5540
5848
  maximumLocalMachineImageBytes = 1e7;
5541
5849
  }
5542
5850
  });
5543
5851
 
5544
- // ../machine-connector/dist/runtime/local-ipc.js
5545
- async function requestRuntimeStatus(store, timeoutMilliseconds = 1e3) {
5546
- return await requestLocalIpc(store, "status", timeoutMilliseconds);
5547
- }
5548
- async function requestEnvironmentRefresh(store, timeoutMilliseconds = 1e4) {
5549
- return await requestLocalIpc(store, "environment_refresh", timeoutMilliseconds);
5550
- }
5551
- async function requestLocalIpc(store, action, timeoutMilliseconds) {
5552
- return await new Promise((resolvePromise, rejectPromise) => {
5553
- const socket = (0, import_node_net.createConnection)(store.runtimeSocketPath());
5554
- let responseText = "";
5555
- socket.setEncoding("utf8");
5556
- socket.once("error", rejectPromise);
5557
- socket.setTimeout(timeoutMilliseconds, () => {
5558
- socket.destroy(new Error(`Runtime status timed out after ${timeoutMilliseconds}ms`));
5559
- });
5560
- socket.on("data", (chunk) => {
5561
- responseText += chunk;
5562
- });
5563
- socket.once("close", () => {
5564
- try {
5565
- resolvePromise(JSON.parse(responseText.trim()));
5566
- } catch (error) {
5567
- rejectPromise(error);
5568
- }
5569
- });
5570
- socket.once("connect", () => {
5571
- socket.write(`${JSON.stringify({ action })}
5572
- `);
5573
- });
5574
- });
5575
- }
5576
- var import_promises6, import_node_net, import_node_os2, LocalIpcServer;
5577
- var init_local_ipc = __esm({
5578
- "../machine-connector/dist/runtime/local-ipc.js"() {
5579
- "use strict";
5580
- init_cjs_shims();
5581
- import_promises6 = require("fs/promises");
5582
- import_node_net = require("net");
5583
- import_node_os2 = require("os");
5584
- LocalIpcServer = class {
5585
- store;
5586
- getStatus;
5587
- refreshEnvironment;
5588
- server;
5589
- constructor(store, getStatus, refreshEnvironment) {
5590
- this.store = store;
5591
- this.getStatus = getStatus;
5592
- this.refreshEnvironment = refreshEnvironment;
5593
- }
5594
- async start() {
5595
- const socketPath = this.store.runtimeSocketPath();
5596
- if ((0, import_node_os2.platform)() !== "win32") {
5597
- await (0, import_promises6.rm)(socketPath, { force: true });
5598
- }
5599
- this.server = (0, import_node_net.createServer)((socket) => {
5600
- let requestText = "";
5601
- let handled = false;
5602
- socket.setEncoding("utf8");
5603
- socket.on("data", (chunk) => {
5604
- requestText += chunk;
5605
- if (handled || !requestText.includes("\n")) {
5606
- return;
5607
- }
5608
- handled = true;
5609
- void this.handleRequest(requestText).then((response) => {
5610
- socket.end(`${JSON.stringify(response)}
5611
- `);
5612
- });
5613
- });
5614
- });
5615
- await new Promise((resolvePromise, rejectPromise) => {
5616
- this.server?.once("error", rejectPromise);
5617
- this.server?.listen(socketPath, resolvePromise);
5618
- });
5619
- if ((0, import_node_os2.platform)() !== "win32") {
5620
- await (0, import_promises6.chmod)(socketPath, 384);
5621
- }
5622
- }
5623
- async close() {
5624
- if (!this.server) {
5625
- return;
5626
- }
5627
- await new Promise((resolvePromise) => {
5628
- this.server?.close(() => resolvePromise());
5629
- });
5630
- if ((0, import_node_os2.platform)() !== "win32") {
5631
- await (0, import_promises6.rm)(this.store.runtimeSocketPath(), { force: true });
5632
- }
5633
- }
5634
- async handleRequest(requestText) {
5635
- try {
5636
- const request2 = JSON.parse(requestText.trim());
5637
- if (request2.action === "status") {
5638
- return { status: this.getStatus() };
5639
- }
5640
- if (request2.action === "environment_refresh") {
5641
- if (!this.refreshEnvironment) {
5642
- return { error: "Environment refresh is unavailable" };
5643
- }
5644
- return {
5645
- environmentRefresh: await this.refreshEnvironment()
5646
- };
5647
- }
5648
- return { error: `Unsupported IPC action: ${request2.action}` };
5649
- } catch (error) {
5650
- return {
5651
- error: error instanceof Error ? error.message : "Invalid IPC request"
5652
- };
5653
- }
5654
- }
5655
- };
5656
- }
5657
- });
5658
-
5659
5852
  // ../machine-connector/dist/runtime/process-lock.js
5660
5853
  async function createCompleteLock(path4, record2) {
5661
- await (0, import_promises7.mkdir)(path4, { mode: 448 });
5854
+ await (0, import_promises8.mkdir)(path4, { mode: 448 });
5662
5855
  let metadata;
5663
5856
  try {
5664
- metadata = await (0, import_promises7.stat)(path4);
5857
+ metadata = await (0, import_promises8.stat)(path4);
5665
5858
  } catch (error) {
5666
5859
  if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5667
5860
  throw nodeError("EEXIST", "Lock directory changed while publishing");
5668
5861
  }
5669
5862
  throw error;
5670
5863
  }
5671
- const ownerPath = (0, import_node_path5.join)(path4, `${metadata.dev}.${metadata.ino}.${record2.pid}.${record2.token}.owner`);
5864
+ const ownerPath = (0, import_node_path6.join)(path4, `${metadata.dev}.${metadata.ino}.${record2.pid}.${record2.token}.owner`);
5672
5865
  try {
5673
- await (0, import_promises7.writeFile)(ownerPath, `${JSON.stringify(record2)}
5866
+ await (0, import_promises8.writeFile)(ownerPath, `${JSON.stringify(record2)}
5674
5867
  `, {
5675
5868
  encoding: "utf8",
5676
5869
  flag: "wx",
@@ -5678,7 +5871,7 @@ async function createCompleteLock(path4, record2) {
5678
5871
  });
5679
5872
  let current2;
5680
5873
  try {
5681
- current2 = await (0, import_promises7.stat)(path4);
5874
+ current2 = await (0, import_promises8.stat)(path4);
5682
5875
  } catch (error) {
5683
5876
  if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5684
5877
  throw nodeError("EEXIST", "Lock directory changed while publishing");
@@ -5701,7 +5894,7 @@ async function createCompleteLock(path4, record2) {
5701
5894
  async function readLockState(path4) {
5702
5895
  let metadata;
5703
5896
  try {
5704
- metadata = await (0, import_promises7.stat)(path4);
5897
+ metadata = await (0, import_promises8.stat)(path4);
5705
5898
  } catch (error) {
5706
5899
  if (isNodeErrorCode2(error, "ENOENT"))
5707
5900
  return void 0;
@@ -5716,7 +5909,7 @@ async function readLockState(path4) {
5716
5909
  const ownerPrefix = `${metadata.dev}.${metadata.ino}.`;
5717
5910
  let names;
5718
5911
  try {
5719
- names = await (0, import_promises7.readdir)(path4);
5912
+ names = await (0, import_promises8.readdir)(path4);
5720
5913
  } catch (error) {
5721
5914
  if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5722
5915
  return void 0;
@@ -5726,7 +5919,7 @@ async function readLockState(path4) {
5726
5919
  const ownerName = names.find((name) => name.startsWith(ownerPrefix) && name.endsWith(".owner"));
5727
5920
  if (!ownerName)
5728
5921
  return { metadata };
5729
- const ownerPath = (0, import_node_path5.join)(path4, ownerName);
5922
+ const ownerPath = (0, import_node_path6.join)(path4, ownerName);
5730
5923
  return {
5731
5924
  metadata,
5732
5925
  ownerPath,
@@ -5735,7 +5928,7 @@ async function readLockState(path4) {
5735
5928
  }
5736
5929
  async function readRecord(path4) {
5737
5930
  try {
5738
- const parsed = JSON.parse(await (0, import_promises7.readFile)(path4, "utf8"));
5931
+ const parsed = JSON.parse(await (0, import_promises8.readFile)(path4, "utf8"));
5739
5932
  if (typeof parsed.createdAt !== "number" || !Number.isFinite(parsed.createdAt) || typeof parsed.pid !== "number" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0 || typeof parsed.token !== "string" || parsed.token.length === 0) {
5740
5933
  return void 0;
5741
5934
  }
@@ -5757,7 +5950,7 @@ async function removeLockIfTokenMatches(path4, token) {
5757
5950
  return;
5758
5951
  }
5759
5952
  try {
5760
- await (0, import_promises7.rm)(path4);
5953
+ await (0, import_promises8.rm)(path4);
5761
5954
  } catch (error) {
5762
5955
  if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "EISDIR") || isNodeErrorCode2(error, "ERR_FS_EISDIR") || isNodeErrorCode2(error, "EPERM")) {
5763
5956
  return;
@@ -5781,7 +5974,7 @@ async function removeStaleIncompleteLock(path4, metadata) {
5781
5974
  }
5782
5975
  if (!metadata.isDirectory()) {
5783
5976
  try {
5784
- await (0, import_promises7.rm)(path4);
5977
+ await (0, import_promises8.rm)(path4);
5785
5978
  return true;
5786
5979
  } catch (error) {
5787
5980
  if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "EISDIR") || isNodeErrorCode2(error, "ERR_FS_EISDIR") || isNodeErrorCode2(error, "EPERM")) {
@@ -5793,7 +5986,7 @@ async function removeStaleIncompleteLock(path4, metadata) {
5793
5986
  const ownerPrefix = `${metadata.dev}.${metadata.ino}.`;
5794
5987
  let names;
5795
5988
  try {
5796
- names = await (0, import_promises7.readdir)(path4);
5989
+ names = await (0, import_promises8.readdir)(path4);
5797
5990
  } catch (error) {
5798
5991
  if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5799
5992
  return false;
@@ -5810,7 +6003,7 @@ async function removeStaleIncompleteLock(path4, metadata) {
5810
6003
  deadOwnerNames.push(name);
5811
6004
  }
5812
6005
  for (const name of deadOwnerNames) {
5813
- await removeFileIfPresent((0, import_node_path5.join)(path4, name));
6006
+ await removeFileIfPresent((0, import_node_path6.join)(path4, name));
5814
6007
  }
5815
6008
  return await removeEmptyDirectory(path4);
5816
6009
  }
@@ -5827,11 +6020,11 @@ function directoryOwnerProcessId(ownerPrefix, ownerName) {
5827
6020
  return processId;
5828
6021
  }
5829
6022
  async function removeStalePendingLockCandidates(path4) {
5830
- const directory = (0, import_node_path5.dirname)(path4);
5831
- const lockName = (0, import_node_path5.basename)(path4);
6023
+ const directory = (0, import_node_path6.dirname)(path4);
6024
+ const lockName = (0, import_node_path6.basename)(path4);
5832
6025
  let names;
5833
6026
  try {
5834
- names = await (0, import_promises7.readdir)(directory);
6027
+ names = await (0, import_promises8.readdir)(directory);
5835
6028
  } catch (error) {
5836
6029
  if (isNodeErrorCode2(error, "ENOENT"))
5837
6030
  return;
@@ -5840,7 +6033,7 @@ async function removeStalePendingLockCandidates(path4) {
5840
6033
  for (const name of names) {
5841
6034
  if (!isPendingLockCandidateName(lockName, name))
5842
6035
  continue;
5843
- await removeOldUnchangedFile((0, import_node_path5.join)(directory, name));
6036
+ await removeOldUnchangedFile((0, import_node_path6.join)(directory, name));
5844
6037
  }
5845
6038
  }
5846
6039
  function isPendingLockCandidateName(lockName, name) {
@@ -5860,7 +6053,7 @@ function isPendingLockCandidateName(lockName, name) {
5860
6053
  async function removeOldUnchangedFile(path4) {
5861
6054
  let metadata;
5862
6055
  try {
5863
- metadata = await (0, import_promises7.stat)(path4);
6056
+ metadata = await (0, import_promises8.stat)(path4);
5864
6057
  } catch (error) {
5865
6058
  return isNodeErrorCode2(error, "ENOENT");
5866
6059
  }
@@ -5869,18 +6062,18 @@ async function removeOldUnchangedFile(path4) {
5869
6062
  }
5870
6063
  let current2;
5871
6064
  try {
5872
- current2 = await (0, import_promises7.stat)(path4);
6065
+ current2 = await (0, import_promises8.stat)(path4);
5873
6066
  } catch (error) {
5874
6067
  return isNodeErrorCode2(error, "ENOENT");
5875
6068
  }
5876
6069
  if (!sameFileMetadata(metadata, current2))
5877
6070
  return false;
5878
- await (0, import_promises7.rm)(path4, { force: true });
6071
+ await (0, import_promises8.rm)(path4, { force: true });
5879
6072
  return true;
5880
6073
  }
5881
6074
  async function removeEmptyDirectory(path4) {
5882
6075
  try {
5883
- await (0, import_promises7.rmdir)(path4);
6076
+ await (0, import_promises8.rmdir)(path4);
5884
6077
  return true;
5885
6078
  } catch (error) {
5886
6079
  if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTEMPTY") || isNodeErrorCode2(error, "EEXIST") || isNodeErrorCode2(error, "ENOTDIR")) {
@@ -5891,7 +6084,7 @@ async function removeEmptyDirectory(path4) {
5891
6084
  }
5892
6085
  async function removeFileIfPresent(path4) {
5893
6086
  try {
5894
- await (0, import_promises7.rm)(path4, { force: true });
6087
+ await (0, import_promises8.rm)(path4, { force: true });
5895
6088
  } catch (error) {
5896
6089
  if (isNodeErrorCode2(error, "ENOENT") || isNodeErrorCode2(error, "ENOTDIR")) {
5897
6090
  return;
@@ -5922,14 +6115,14 @@ function nodeError(code, message) {
5922
6115
  function delay3(milliseconds) {
5923
6116
  return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
5924
6117
  }
5925
- var import_node_crypto4, import_promises7, import_node_path5, incompleteLockStaleMilliseconds, ProcessLock;
6118
+ var import_node_crypto4, import_promises8, import_node_path6, incompleteLockStaleMilliseconds, ProcessLock;
5926
6119
  var init_process_lock = __esm({
5927
6120
  "../machine-connector/dist/runtime/process-lock.js"() {
5928
6121
  "use strict";
5929
6122
  init_cjs_shims();
5930
6123
  import_node_crypto4 = require("crypto");
5931
- import_promises7 = require("fs/promises");
5932
- import_node_path5 = require("path");
6124
+ import_promises8 = require("fs/promises");
6125
+ import_node_path6 = require("path");
5933
6126
  incompleteLockStaleMilliseconds = 3e4;
5934
6127
  ProcessLock = class _ProcessLock {
5935
6128
  path;
@@ -5984,7 +6177,7 @@ var init_process_lock = __esm({
5984
6177
  function sanitizeEnvironment(source) {
5985
6178
  const environment = createEnvironmentMap();
5986
6179
  for (const [name, value] of Object.entries(source)) {
5987
- if (value === void 0 || isConnectorCredentialName(name)) {
6180
+ if (value === void 0 || direnvSessionStateNames.has(name) || name === machineExecutionContextEnvironmentName || isConnectorCredentialName(name)) {
5988
6181
  continue;
5989
6182
  }
5990
6183
  environment[name] = value;
@@ -6057,7 +6250,7 @@ function parseDirenvJson(text3) {
6057
6250
  function sanitizeDirenvExports(source) {
6058
6251
  const exports2 = createEnvironmentMap();
6059
6252
  for (const [name, value] of Object.entries(source)) {
6060
- if (!isConnectorCredentialName(name)) {
6253
+ if (name !== machineExecutionContextEnvironmentName && !isConnectorCredentialName(name)) {
6061
6254
  exports2[name] = value;
6062
6255
  }
6063
6256
  }
@@ -6069,30 +6262,30 @@ function isConnectorCredentialName(name) {
6069
6262
  return name.startsWith("MOXT_MACHINE_") && /(?:^|_)(?:TOKEN|SECRET|CREDENTIALS?|PASSWORD|PRIVATE_KEY)(?:_|$)/.test(name.slice("MOXT_MACHINE_".length));
6070
6263
  }
6071
6264
  async function validateShell(shellPath) {
6072
- if (!(0, import_node_path6.isAbsolute)(shellPath))
6265
+ if (!(0, import_node_path7.isAbsolute)(shellPath))
6073
6266
  throw new Error("default shell is not absolute");
6074
6267
  const canonicalPath = await validateExecutable(shellPath);
6075
- const shellName = (0, import_node_path6.basename)(canonicalPath);
6268
+ const shellName = (0, import_node_path7.basename)(canonicalPath);
6076
6269
  if (shellName !== "bash" && shellName !== "zsh") {
6077
6270
  throw new Error("default shell is not Bash or Zsh");
6078
6271
  }
6079
6272
  return canonicalPath;
6080
6273
  }
6081
6274
  async function validateExecutable(path4) {
6082
- const canonicalPath = await (0, import_promises8.realpath)(path4);
6083
- const metadata = await (0, import_promises8.stat)(canonicalPath);
6275
+ const canonicalPath = await (0, import_promises9.realpath)(path4);
6276
+ const metadata = await (0, import_promises9.stat)(canonicalPath);
6084
6277
  if (!metadata.isFile())
6085
6278
  throw new Error("executable is not a regular file");
6086
- await (0, import_promises8.access)(canonicalPath, import_promises8.constants.X_OK);
6279
+ await (0, import_promises9.access)(canonicalPath, import_promises9.constants.X_OK);
6087
6280
  return canonicalPath;
6088
6281
  }
6089
6282
  async function findExecutable(name, pathValue) {
6090
- for (const directory of (pathValue ?? "").split(import_node_path6.delimiter)) {
6091
- if (!(0, import_node_path6.isAbsolute)(directory))
6283
+ for (const directory of (pathValue ?? "").split(import_node_path7.delimiter)) {
6284
+ if (!(0, import_node_path7.isAbsolute)(directory))
6092
6285
  continue;
6093
6286
  try {
6094
- const candidate = await validateExecutable((0, import_node_path6.join)(directory, name));
6095
- if ((0, import_node_path6.basename)(candidate) === name)
6287
+ const candidate = await validateExecutable((0, import_node_path7.join)(directory, name));
6288
+ if ((0, import_node_path7.basename)(candidate) === name)
6096
6289
  return candidate;
6097
6290
  } catch {
6098
6291
  }
@@ -6102,9 +6295,9 @@ async function findExecutable(name, pathValue) {
6102
6295
  async function findNearestEnvrc(canonicalRoot, canonicalWorkingDirectory) {
6103
6296
  let directory = canonicalWorkingDirectory;
6104
6297
  while (true) {
6105
- const candidate = (0, import_node_path6.join)(directory, ".envrc");
6298
+ const candidate = (0, import_node_path7.join)(directory, ".envrc");
6106
6299
  try {
6107
- const metadata = await (0, import_promises8.stat)(candidate);
6300
+ const metadata = await (0, import_promises9.stat)(candidate);
6108
6301
  if (!metadata.isFile()) {
6109
6302
  throw new JobEnvironmentError("direnv_malformed");
6110
6303
  }
@@ -6115,7 +6308,7 @@ async function findNearestEnvrc(canonicalRoot, canonicalWorkingDirectory) {
6115
6308
  }
6116
6309
  if (directory === canonicalRoot)
6117
6310
  return void 0;
6118
- const parent = (0, import_node_path6.dirname)(directory);
6311
+ const parent = (0, import_node_path7.dirname)(directory);
6119
6312
  if (parent === directory)
6120
6313
  return void 0;
6121
6314
  directory = parent;
@@ -6263,21 +6456,28 @@ function degradedCapture(category) {
6263
6456
  function isNodeError(error, code) {
6264
6457
  return error instanceof Error && "code" in error && error.code === code;
6265
6458
  }
6266
- var import_node_child_process2, import_promises8, import_node_os3, import_node_path6, defaultCaptureTimeoutMilliseconds, defaultCaptureOutputLimitBytes, defaultDirenvTimeoutMilliseconds, defaultDirenvOutputLimitBytes, shellCaptureScript, environmentNamePattern, JobEnvironmentError, JobEnvironmentCancelledError, ShellEnvironmentManager;
6459
+ var import_node_child_process2, import_promises9, import_node_os3, import_node_path7, defaultCaptureTimeoutMilliseconds, defaultCaptureOutputLimitBytes, defaultDirenvTimeoutMilliseconds, defaultDirenvOutputLimitBytes, shellCaptureScript, environmentNamePattern, direnvSessionStateNames, JobEnvironmentError, JobEnvironmentCancelledError, ShellEnvironmentManager;
6267
6460
  var init_shell_environment = __esm({
6268
6461
  "../machine-connector/dist/runtime/shell-environment.js"() {
6269
6462
  "use strict";
6270
6463
  init_cjs_shims();
6271
6464
  import_node_child_process2 = require("child_process");
6272
- import_promises8 = require("fs/promises");
6465
+ import_promises9 = require("fs/promises");
6273
6466
  import_node_os3 = require("os");
6274
- import_node_path6 = require("path");
6467
+ import_node_path7 = require("path");
6468
+ init_execution_context();
6275
6469
  defaultCaptureTimeoutMilliseconds = 5e3;
6276
6470
  defaultCaptureOutputLimitBytes = 1048576;
6277
6471
  defaultDirenvTimeoutMilliseconds = 5e3;
6278
6472
  defaultDirenvOutputLimitBytes = 1048576;
6279
6473
  shellCaptureScript = `exec "$1" -e 'for (const [name, value] of Object.entries(process.env)) process.stdout.write(name + "=" + value + "\\0")'`;
6280
6474
  environmentNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
6475
+ direnvSessionStateNames = /* @__PURE__ */ new Set([
6476
+ "DIRENV_DIFF",
6477
+ "DIRENV_DIR",
6478
+ "DIRENV_FILE",
6479
+ "DIRENV_WATCHES"
6480
+ ]);
6281
6481
  JobEnvironmentError = class extends Error {
6282
6482
  category;
6283
6483
  constructor(category) {
@@ -6331,19 +6531,24 @@ var init_shell_environment = __esm({
6331
6531
  status() {
6332
6532
  return { ...this.currentStatus };
6333
6533
  }
6334
- async resolveForJob(canonicalRoot, canonicalWorkingDirectory, explicitEnvironment, cancellationSignal) {
6335
- throwIfCancelled(cancellationSignal);
6336
- const relativeWorkingDirectory = (0, import_node_path6.relative)(canonicalRoot, canonicalWorkingDirectory);
6337
- if (relativeWorkingDirectory === ".." || relativeWorkingDirectory.startsWith(`..${import_node_path6.sep}`) || (0, import_node_path6.isAbsolute)(relativeWorkingDirectory)) {
6534
+ async resolveForJob(canonicalRoot, canonicalWorkingDirectory, explicitEnvironment, options) {
6535
+ throwIfCancelled(options.cancellationSignal);
6536
+ if (Object.hasOwn(explicitEnvironment, machineExecutionContextEnvironmentName)) {
6537
+ throw new JobEnvironmentError("reserved_environment");
6538
+ }
6539
+ const executionContextValue = serializeLocalMachineJobExecutionContext(options.executionContext);
6540
+ const relativeWorkingDirectory = (0, import_node_path7.relative)(canonicalRoot, canonicalWorkingDirectory);
6541
+ if (relativeWorkingDirectory === ".." || relativeWorkingDirectory.startsWith(`..${import_node_path7.sep}`) || (0, import_node_path7.isAbsolute)(relativeWorkingDirectory)) {
6338
6542
  throw new JobEnvironmentError("direnv_malformed");
6339
6543
  }
6340
6544
  const baseSnapshot = this.currentEnvironment;
6341
6545
  const envrcPath = await findNearestEnvrc(canonicalRoot, canonicalWorkingDirectory);
6342
- throwIfCancelled(cancellationSignal);
6546
+ throwIfCancelled(options.cancellationSignal);
6343
6547
  if (!envrcPath) {
6344
6548
  return freezeEnvironment({
6345
6549
  ...baseSnapshot,
6346
- ...explicitEnvironment
6550
+ ...explicitEnvironment,
6551
+ [machineExecutionContextEnvironmentName]: executionContextValue
6347
6552
  });
6348
6553
  }
6349
6554
  const direnvExecutable = await findExecutable("direnv", baseSnapshot.PATH);
@@ -6353,11 +6558,14 @@ var init_shell_environment = __esm({
6353
6558
  const result = await executeBounded({
6354
6559
  argumentsList: ["export", "json"],
6355
6560
  cwd: canonicalWorkingDirectory,
6356
- environment: baseSnapshot,
6561
+ environment: {
6562
+ ...baseSnapshot,
6563
+ [machineExecutionContextEnvironmentName]: executionContextValue
6564
+ },
6357
6565
  executable: direnvExecutable,
6358
6566
  outputLimitBytes: this.direnvOutputLimitBytes,
6359
6567
  timeoutMilliseconds: this.direnvTimeoutMilliseconds,
6360
- cancellationSignal
6568
+ cancellationSignal: options.cancellationSignal
6361
6569
  });
6362
6570
  if (result.outcome === "cancelled") {
6363
6571
  throw new JobEnvironmentCancelledError();
@@ -6377,7 +6585,8 @@ var init_shell_environment = __esm({
6377
6585
  }
6378
6586
  let parsedExports;
6379
6587
  try {
6380
- parsedExports = parseDirenvJson(decodeUtf8(result.stdout, "direnv_malformed"));
6588
+ const output = decodeUtf8(result.stdout, "direnv_malformed");
6589
+ parsedExports = output.trim().length === 0 ? createEnvironmentMap() : parseDirenvJson(output);
6381
6590
  } catch {
6382
6591
  throw new JobEnvironmentError("direnv_malformed");
6383
6592
  }
@@ -6392,7 +6601,8 @@ var init_shell_environment = __esm({
6392
6601
  }
6393
6602
  return freezeEnvironment({
6394
6603
  ...environment,
6395
- ...explicitEnvironment
6604
+ ...explicitEnvironment,
6605
+ [machineExecutionContextEnvironmentName]: executionContextValue
6396
6606
  });
6397
6607
  }
6398
6608
  async capture() {
@@ -6644,12 +6854,12 @@ var init_relay_client = __esm({
6644
6854
  });
6645
6855
 
6646
6856
  // ../machine-connector/dist/runtime/runtime-logger.js
6647
- var import_promises9, RuntimeLogger;
6857
+ var import_promises10, RuntimeLogger;
6648
6858
  var init_runtime_logger = __esm({
6649
6859
  "../machine-connector/dist/runtime/runtime-logger.js"() {
6650
6860
  "use strict";
6651
6861
  init_cjs_shims();
6652
- import_promises9 = require("fs/promises");
6862
+ import_promises10 = require("fs/promises");
6653
6863
  RuntimeLogger = class {
6654
6864
  store;
6655
6865
  constructor(store) {
@@ -6663,7 +6873,7 @@ var init_runtime_logger = __esm({
6663
6873
  await this.write("error", message, metadata, this.store.runtimeErrorLogPath());
6664
6874
  }
6665
6875
  async write(level, message, metadata, path4) {
6666
- await (0, import_promises9.appendFile)(path4, `${JSON.stringify({
6876
+ await (0, import_promises10.appendFile)(path4, `${JSON.stringify({
6667
6877
  level,
6668
6878
  message,
6669
6879
  metadata,
@@ -6686,10 +6896,10 @@ function defaultRuntimeDirectory() {
6686
6896
  }
6687
6897
  const homeDirectory = process.env.HOME ?? (0, import_node_os4.homedir)();
6688
6898
  if ((0, import_node_os4.platform)() === "darwin") {
6689
- return (0, import_node_path7.join)(homeDirectory, "Library", "Application Support", "Moxt", "Machine Connector");
6899
+ return (0, import_node_path8.join)(homeDirectory, "Library", "Application Support", "Moxt", "Machine Connector");
6690
6900
  }
6691
- const stateHome = process.env.XDG_STATE_HOME ?? (0, import_node_path7.join)(homeDirectory, ".local", "state");
6692
- return (0, import_node_path7.join)(stateHome, "moxt", "machine-connector");
6901
+ const stateHome = process.env.XDG_STATE_HOME ?? (0, import_node_path8.join)(homeDirectory, ".local", "state");
6902
+ return (0, import_node_path8.join)(stateHome, "moxt", "machine-connector");
6693
6903
  }
6694
6904
  function isNodeErrorCode3(error, expectedCode) {
6695
6905
  if (!(error instanceof Error) || !("code" in error)) {
@@ -6697,14 +6907,14 @@ function isNodeErrorCode3(error, expectedCode) {
6697
6907
  }
6698
6908
  return error.code === expectedCode;
6699
6909
  }
6700
- var import_promises10, import_node_os4, import_node_path7, privateFileMode, privateDirectoryMode, MachineRuntimeStore;
6910
+ var import_promises11, import_node_os4, import_node_path8, privateFileMode, privateDirectoryMode, MachineRuntimeStore;
6701
6911
  var init_store = __esm({
6702
6912
  "../machine-connector/dist/runtime/store.js"() {
6703
6913
  "use strict";
6704
6914
  init_cjs_shims();
6705
- import_promises10 = require("fs/promises");
6915
+ import_promises11 = require("fs/promises");
6706
6916
  import_node_os4 = require("os");
6707
- import_node_path7 = require("path");
6917
+ import_node_path8 = require("path");
6708
6918
  privateFileMode = 384;
6709
6919
  privateDirectoryMode = 448;
6710
6920
  MachineRuntimeStore = class {
@@ -6713,20 +6923,20 @@ var init_store = __esm({
6713
6923
  this.baseDirectory = baseDirectory;
6714
6924
  }
6715
6925
  async initialize() {
6716
- await (0, import_promises10.mkdir)(this.jobsDirectory(), {
6926
+ await (0, import_promises11.mkdir)(this.jobsDirectory(), {
6717
6927
  mode: privateDirectoryMode,
6718
6928
  recursive: true
6719
6929
  });
6720
- await (0, import_promises10.mkdir)(this.detachedProcessesDirectory(), {
6930
+ await (0, import_promises11.mkdir)(this.detachedProcessesDirectory(), {
6721
6931
  mode: privateDirectoryMode,
6722
6932
  recursive: true
6723
6933
  });
6724
- await (0, import_promises10.chmod)(this.baseDirectory, privateDirectoryMode);
6725
- await (0, import_promises10.chmod)(this.jobsDirectory(), privateDirectoryMode);
6726
- await (0, import_promises10.chmod)(this.detachedProcessesDirectory(), privateDirectoryMode);
6934
+ await (0, import_promises11.chmod)(this.baseDirectory, privateDirectoryMode);
6935
+ await (0, import_promises11.chmod)(this.jobsDirectory(), privateDirectoryMode);
6936
+ await (0, import_promises11.chmod)(this.detachedProcessesDirectory(), privateDirectoryMode);
6727
6937
  }
6728
6938
  async getCanonicalRoot(rootPath) {
6729
- return await (0, import_promises10.realpath)(rootPath);
6939
+ return await (0, import_promises11.realpath)(rootPath);
6730
6940
  }
6731
6941
  async readIdentity() {
6732
6942
  return await this.readOptionalJson(this.identityPath());
@@ -6769,7 +6979,7 @@ var init_store = __esm({
6769
6979
  await this.writePrivateJson(this.serviceManagerPath(), serviceManager);
6770
6980
  }
6771
6981
  async removeServiceManager() {
6772
- await (0, import_promises10.rm)(this.serviceManagerPath(), { force: true });
6982
+ await (0, import_promises11.rm)(this.serviceManagerPath(), { force: true });
6773
6983
  }
6774
6984
  async readJob(jobId) {
6775
6985
  return await this.readOptionalJson(this.jobPath(jobId));
@@ -6780,7 +6990,7 @@ var init_store = __esm({
6780
6990
  async listJobs() {
6781
6991
  let names = [];
6782
6992
  try {
6783
- names = await (0, import_promises10.readdir)(this.jobsDirectory());
6993
+ names = await (0, import_promises11.readdir)(this.jobsDirectory());
6784
6994
  } catch (error) {
6785
6995
  if (isNodeErrorCode3(error, "ENOENT")) {
6786
6996
  return [];
@@ -6789,7 +6999,7 @@ var init_store = __esm({
6789
6999
  }
6790
7000
  const jobs = [];
6791
7001
  for (const name of names.filter((entry) => entry.endsWith(".json"))) {
6792
- const job = await this.readOptionalJson((0, import_node_path7.join)(this.jobsDirectory(), name));
7002
+ const job = await this.readOptionalJson((0, import_node_path8.join)(this.jobsDirectory(), name));
6793
7003
  if (job.value) {
6794
7004
  jobs.push(job.value);
6795
7005
  }
@@ -6797,7 +7007,7 @@ var init_store = __esm({
6797
7007
  return jobs;
6798
7008
  }
6799
7009
  async deleteJob(jobId) {
6800
- await (0, import_promises10.rm)(this.jobPath(jobId), { force: true });
7010
+ await (0, import_promises11.rm)(this.jobPath(jobId), { force: true });
6801
7011
  }
6802
7012
  async writeDetachedProcess(resource) {
6803
7013
  await this.writePrivateJson(this.detachedProcessPath(resource.jobId), resource);
@@ -6805,7 +7015,7 @@ var init_store = __esm({
6805
7015
  async listDetachedProcesses() {
6806
7016
  let names = [];
6807
7017
  try {
6808
- names = await (0, import_promises10.readdir)(this.detachedProcessesDirectory());
7018
+ names = await (0, import_promises11.readdir)(this.detachedProcessesDirectory());
6809
7019
  } catch (error) {
6810
7020
  if (isNodeErrorCode3(error, "ENOENT")) {
6811
7021
  return [];
@@ -6814,7 +7024,7 @@ var init_store = __esm({
6814
7024
  }
6815
7025
  const resources = [];
6816
7026
  for (const name of names.filter((entry) => entry.endsWith(".json"))) {
6817
- const resource = await this.readOptionalJson((0, import_node_path7.join)(this.detachedProcessesDirectory(), name));
7027
+ const resource = await this.readOptionalJson((0, import_node_path8.join)(this.detachedProcessesDirectory(), name));
6818
7028
  if (resource.value) {
6819
7029
  resources.push(resource.value);
6820
7030
  }
@@ -6822,52 +7032,52 @@ var init_store = __esm({
6822
7032
  return resources;
6823
7033
  }
6824
7034
  async deleteDetachedProcess(jobId) {
6825
- await (0, import_promises10.rm)(this.detachedProcessPath(jobId), { force: true });
7035
+ await (0, import_promises11.rm)(this.detachedProcessPath(jobId), { force: true });
6826
7036
  }
6827
7037
  runtimeLogPath() {
6828
- return (0, import_node_path7.join)(this.baseDirectory, "machine-connector.log");
7038
+ return (0, import_node_path8.join)(this.baseDirectory, "machine-connector.log");
6829
7039
  }
6830
7040
  runtimeErrorLogPath() {
6831
- return (0, import_node_path7.join)(this.baseDirectory, "machine-connector.error.log");
7041
+ return (0, import_node_path8.join)(this.baseDirectory, "machine-connector.error.log");
6832
7042
  }
6833
7043
  runtimeStatusPath() {
6834
- return (0, import_node_path7.join)(this.baseDirectory, "runtime-status.json");
7044
+ return (0, import_node_path8.join)(this.baseDirectory, "runtime-status.json");
6835
7045
  }
6836
7046
  runtimeSocketPath() {
6837
7047
  if ((0, import_node_os4.platform)() === "win32") {
6838
7048
  return String.raw`\\.\pipe\moxt-machine-connector`;
6839
7049
  }
6840
- return (0, import_node_path7.join)(this.baseDirectory, "machine-connector.sock");
7050
+ return (0, import_node_path8.join)(this.baseDirectory, "machine-connector.sock");
6841
7051
  }
6842
7052
  daemonLockPath() {
6843
- return (0, import_node_path7.join)(this.baseDirectory, "daemon.lock");
7053
+ return (0, import_node_path8.join)(this.baseDirectory, "daemon.lock");
6844
7054
  }
6845
7055
  reconcileLockPath() {
6846
- return (0, import_node_path7.join)(this.baseDirectory, "daemon-reconcile.lock");
7056
+ return (0, import_node_path8.join)(this.baseDirectory, "daemon-reconcile.lock");
6847
7057
  }
6848
7058
  connectionsPath() {
6849
- return (0, import_node_path7.join)(this.baseDirectory, "connections.json");
7059
+ return (0, import_node_path8.join)(this.baseDirectory, "connections.json");
6850
7060
  }
6851
7061
  detachedProcessesDirectory() {
6852
- return (0, import_node_path7.join)(this.baseDirectory, "detached-processes");
7062
+ return (0, import_node_path8.join)(this.baseDirectory, "detached-processes");
6853
7063
  }
6854
7064
  detachedProcessPath(jobId) {
6855
- return (0, import_node_path7.join)(this.detachedProcessesDirectory(), `${jobId}.json`);
7065
+ return (0, import_node_path8.join)(this.detachedProcessesDirectory(), `${jobId}.json`);
6856
7066
  }
6857
7067
  identityPath() {
6858
- return (0, import_node_path7.join)(this.baseDirectory, "identity.json");
7068
+ return (0, import_node_path8.join)(this.baseDirectory, "identity.json");
6859
7069
  }
6860
7070
  serviceManagerPath() {
6861
- return (0, import_node_path7.join)(this.baseDirectory, "service-manager.json");
7071
+ return (0, import_node_path8.join)(this.baseDirectory, "service-manager.json");
6862
7072
  }
6863
7073
  privateKeyPath() {
6864
- return (0, import_node_path7.join)(this.baseDirectory, "device-private-key.pem");
7074
+ return (0, import_node_path8.join)(this.baseDirectory, "device-private-key.pem");
6865
7075
  }
6866
7076
  jobsDirectory() {
6867
- return (0, import_node_path7.join)(this.baseDirectory, "jobs");
7077
+ return (0, import_node_path8.join)(this.baseDirectory, "jobs");
6868
7078
  }
6869
7079
  jobPath(jobId) {
6870
- return (0, import_node_path7.join)(this.jobsDirectory(), `${jobId}.json`);
7080
+ return (0, import_node_path8.join)(this.jobsDirectory(), `${jobId}.json`);
6871
7081
  }
6872
7082
  async readOptionalJson(path4) {
6873
7083
  const content3 = await this.readOptionalText(path4);
@@ -6878,7 +7088,7 @@ var init_store = __esm({
6878
7088
  }
6879
7089
  async readOptionalText(path4) {
6880
7090
  try {
6881
- return { value: await (0, import_promises10.readFile)(path4, "utf8") };
7091
+ return { value: await (0, import_promises11.readFile)(path4, "utf8") };
6882
7092
  } catch (error) {
6883
7093
  if (isNodeErrorCode3(error, "ENOENT")) {
6884
7094
  return {};
@@ -6891,17 +7101,17 @@ var init_store = __esm({
6891
7101
  `);
6892
7102
  }
6893
7103
  async writePrivateText(path4, value) {
6894
- await (0, import_promises10.mkdir)((0, import_node_path7.dirname)(path4), {
7104
+ await (0, import_promises11.mkdir)((0, import_node_path8.dirname)(path4), {
6895
7105
  mode: privateDirectoryMode,
6896
7106
  recursive: true
6897
7107
  });
6898
7108
  const temporaryPath = `${path4}.${process.pid}.tmp`;
6899
- await (0, import_promises10.writeFile)(temporaryPath, value, {
7109
+ await (0, import_promises11.writeFile)(temporaryPath, value, {
6900
7110
  encoding: "utf8",
6901
7111
  mode: privateFileMode
6902
7112
  });
6903
- await (0, import_promises10.chmod)(temporaryPath, privateFileMode);
6904
- await (0, import_promises10.rename)(temporaryPath, path4);
7113
+ await (0, import_promises11.chmod)(temporaryPath, privateFileMode);
7114
+ await (0, import_promises11.rename)(temporaryPath, path4);
6905
7115
  }
6906
7116
  };
6907
7117
  }
@@ -6931,7 +7141,7 @@ function delay4(milliseconds) {
6931
7141
  setTimeout(resolvePromise, milliseconds);
6932
7142
  });
6933
7143
  }
6934
- var import_node_os5, import_node_crypto5, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
7144
+ var import_node_os5, import_node_crypto5, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, commandOutputBatchMaxBytes, commandOutputFlushIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
6935
7145
  var init_daemon = __esm({
6936
7146
  "../machine-connector/dist/runtime/daemon.js"() {
6937
7147
  "use strict";
@@ -6941,9 +7151,11 @@ var init_daemon = __esm({
6941
7151
  init_enums();
6942
7152
  init_contracts();
6943
7153
  init_claude_executor();
7154
+ init_command_output_batcher();
6944
7155
  init_codex_executor();
6945
7156
  init_durable_job();
6946
7157
  init_execution_cancellation();
7158
+ init_execution_context();
6947
7159
  init_image_viewer();
6948
7160
  init_local_ipc();
6949
7161
  init_process_lock();
@@ -6957,6 +7169,8 @@ var init_daemon = __esm({
6957
7169
  claimTimeoutSeconds = 30;
6958
7170
  controlTimeoutSeconds = 30;
6959
7171
  eventUploadIntervalMilliseconds = 500;
7172
+ commandOutputBatchMaxBytes = 4 * 1024;
7173
+ commandOutputFlushIntervalMilliseconds = 250;
6960
7174
  agentOutputLimitBytes = 2e6;
6961
7175
  defaultLeaseSeconds = 90;
6962
7176
  defaultNetworkRetryMilliseconds = 2e3;
@@ -7269,6 +7483,7 @@ var init_daemon = __esm({
7269
7483
  activeJob.cancellation.wait().then(() => this.cancellationResult(activeJob))
7270
7484
  ]);
7271
7485
  void execution.catch(() => void 0);
7486
+ await activeJob.commandOutputBatcher?.flush();
7272
7487
  const detachedProcessHandle = "detachedProcessHandle" in executionResult ? executionResult.detachedProcessHandle : void 0;
7273
7488
  if (detachedProcessHandle) {
7274
7489
  let resourceRecorded = false;
@@ -7308,6 +7523,11 @@ var init_daemon = __esm({
7308
7523
  if (!durableJob) {
7309
7524
  return;
7310
7525
  }
7526
+ try {
7527
+ await activeJob.commandOutputBatcher?.flush();
7528
+ } catch (flushError) {
7529
+ await this.logger.error(`Failed to flush command output for Job ${claim.jobId}`, flushError);
7530
+ }
7311
7531
  const message = error instanceof Error ? error.message : "Unknown Connector error";
7312
7532
  await durableJob.markTerminal({
7313
7533
  exitCode: -1,
@@ -7327,7 +7547,10 @@ var init_daemon = __esm({
7327
7547
  const canSpawn = activeJob.cancellation.canSpawn.bind(activeJob.cancellation);
7328
7548
  const resolveEnvironment = async (workingDirectory2, explicitEnvironment) => {
7329
7549
  try {
7330
- return await this.shellEnvironmentManager.resolveForJob(activeJob.connection.rootPath, workingDirectory2, explicitEnvironment, activeJob.cancellation.signal());
7550
+ return await this.shellEnvironmentManager.resolveForJob(activeJob.connection.rootPath, workingDirectory2, explicitEnvironment, {
7551
+ cancellationSignal: activeJob.cancellation.signal(),
7552
+ executionContext: createLocalMachineJobExecutionContext(this.connectorInstanceId, this.store.baseDirectory)
7553
+ });
7331
7554
  } catch (error) {
7332
7555
  if (error instanceof JobEnvironmentCancelledError) {
7333
7556
  return void 0;
@@ -7345,20 +7568,35 @@ var init_daemon = __esm({
7345
7568
  if (!environment2 || !canSpawn()) {
7346
7569
  return this.cancellationResult(activeJob);
7347
7570
  }
7348
- const result = await executeProcess(request2.executable, request2.arguments, workingDirectory2, environment2, request2.stdin, request2.timeoutSeconds, {
7349
- canSpawn,
7350
- onOutput: async (output) => {
7351
- if (activeJob.cancellation.currentReason() !== void 0) {
7352
- return;
7353
- }
7354
- await durableJob.appendOutput(output.stream, output.text, request2.outputLimitBytes);
7355
- },
7356
- onSpawn: registerProcess
7571
+ const outputBatcher = new CommandOutputBatcher({
7572
+ flushIntervalMilliseconds: commandOutputFlushIntervalMilliseconds,
7573
+ maxBytes: commandOutputBatchMaxBytes,
7574
+ write: async (stream, text3) => {
7575
+ await durableJob.appendOutput(stream, text3, request2.outputLimitBytes);
7576
+ }
7357
7577
  });
7358
- return {
7359
- ...result,
7360
- result: { exitCode: result.exitCode }
7361
- };
7578
+ activeJob.commandOutputBatcher = outputBatcher;
7579
+ try {
7580
+ const result = await executeProcess(request2.executable, request2.arguments, workingDirectory2, environment2, request2.stdin, request2.timeoutSeconds, {
7581
+ canSpawn,
7582
+ onOutput: async (output) => {
7583
+ if (activeJob.cancellation.currentReason() !== void 0) {
7584
+ return;
7585
+ }
7586
+ await outputBatcher.append(output.stream, output.text);
7587
+ },
7588
+ onSpawn: registerProcess
7589
+ });
7590
+ return {
7591
+ ...result,
7592
+ result: { exitCode: result.exitCode }
7593
+ };
7594
+ } finally {
7595
+ await outputBatcher.flush();
7596
+ if (activeJob.commandOutputBatcher === outputBatcher) {
7597
+ activeJob.commandOutputBatcher = void 0;
7598
+ }
7599
+ }
7362
7600
  }
7363
7601
  if (claim.kind === MachineJobKind.ViewImage) {
7364
7602
  const request2 = claim.requestPayload;
@@ -7852,6 +8090,7 @@ async function validateServiceManagerPreference(preference, runtime = defaultSer
7852
8090
  return selectUserServiceManager(preference, capabilities);
7853
8091
  }
7854
8092
  async function installUserService(store, request2, runtime = defaultServiceManagerRuntime) {
8093
+ await assertManagedServiceProvenance(store, request2.options.entrypointPath);
7855
8094
  if (request2.preference === ServiceManagerPreference.None) {
7856
8095
  const configuredManager = await readStoredServiceManager(store);
7857
8096
  if (configuredManager !== UserServiceManager.None) {
@@ -7913,12 +8152,12 @@ async function installUserService(store, request2, runtime = defaultServiceManag
7913
8152
  }
7914
8153
  function createServiceEnvironment(options) {
7915
8154
  const inheritedPath = options.environment.PATH ?? process.env.PATH ?? "";
7916
- const nodeDirectory = (0, import_node_path8.dirname)(options.nodePath);
7917
- const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path8.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
8155
+ const nodeDirectory = (0, import_node_path9.dirname)(options.nodePath);
8156
+ const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path9.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
7918
8157
  return {
7919
8158
  ...options.environment,
7920
8159
  HOME: options.environment.HOME ?? process.env.HOME ?? (0, import_node_os6.homedir)(),
7921
- PATH: pathEntries.join(import_node_path8.delimiter)
8160
+ PATH: pathEntries.join(import_node_path9.delimiter)
7922
8161
  };
7923
8162
  }
7924
8163
  async function restartUserService(store, runtime = defaultServiceManagerRuntime) {
@@ -7930,6 +8169,7 @@ async function refreshManagedUserService(store, options, runtime = defaultServic
7930
8169
  const manager = await readStoredServiceManager(store);
7931
8170
  if (manager === UserServiceManager.None)
7932
8171
  return void 0;
8172
+ await assertManagedServiceProvenance(store, options.entrypointPath);
7933
8173
  const snapshot = await readManagedServiceDefinition(manager, store);
7934
8174
  if (snapshot === void 0) {
7935
8175
  throw new Error(`The recorded ${manager} service definition does not exist`);
@@ -7949,12 +8189,12 @@ async function refreshManagedUserService(store, options, runtime = defaultServic
7949
8189
  if (manager === UserServiceManager.Systemd) {
7950
8190
  await restartManager(manager, store, runtime);
7951
8191
  }
7952
- await persistServiceManager(store, manager);
8192
+ await persistServiceManager(store, manager, options.entrypointPath);
7953
8193
  } catch (error) {
7954
8194
  try {
7955
8195
  await rollback();
7956
8196
  } catch (rollbackError) {
7957
- throw new Error(`${errorMessage(error)}; restoring the previous ${manager} definition also failed: ${errorMessage(rollbackError)}`, { cause: error });
8197
+ throw new Error(`${errorMessage2(error)}; restoring the previous ${manager} definition also failed: ${errorMessage2(rollbackError)}`, { cause: error });
7958
8198
  }
7959
8199
  throw error;
7960
8200
  }
@@ -8028,7 +8268,7 @@ async function replaceConfiguredManager(store, manager, options, runtime) {
8028
8268
  await uninstallManagerIgnoringFailure(configuredManager, store, runtime);
8029
8269
  }
8030
8270
  await installManager(manager, store, options, runtime);
8031
- await persistServiceManager(store, manager);
8271
+ await persistServiceManager(store, manager, options.entrypointPath);
8032
8272
  }
8033
8273
  async function installManager(manager, store, options, runtime) {
8034
8274
  if (manager === UserServiceManager.Launchd) {
@@ -8101,7 +8341,7 @@ async function uninstallManager(manager, store, runtime) {
8101
8341
  "bootout",
8102
8342
  `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
8103
8343
  ]);
8104
- await (0, import_promises11.rm)(launchAgentPath(), { force: true });
8344
+ await (0, import_promises12.rm)(launchAgentPath(), { force: true });
8105
8345
  return;
8106
8346
  }
8107
8347
  if (manager === UserServiceManager.Systemd) {
@@ -8111,7 +8351,7 @@ async function uninstallManager(manager, store, runtime) {
8111
8351
  "--now",
8112
8352
  "moxt-machine-connector.service"
8113
8353
  ]);
8114
- await (0, import_promises11.rm)(systemdUnitPath(), { force: true });
8354
+ await (0, import_promises12.rm)(systemdUnitPath(), { force: true });
8115
8355
  await runCommandIgnoringFailure(runtime, "systemctl", [
8116
8356
  "--user",
8117
8357
  "daemon-reload"
@@ -8125,7 +8365,7 @@ async function uninstallManager(manager, store, runtime) {
8125
8365
  supervisorProgramName
8126
8366
  ]);
8127
8367
  await runCommandIgnoringFailure(runtime, "supervisorctl", ["-c", supervisorConfigPath(store), "shutdown"]);
8128
- await (0, import_promises11.rm)(supervisorDirectory(store), {
8368
+ await (0, import_promises12.rm)(supervisorDirectory(store), {
8129
8369
  force: true,
8130
8370
  recursive: true
8131
8371
  });
@@ -8151,7 +8391,7 @@ async function readStoredServiceManager(store) {
8151
8391
  }
8152
8392
  async function readManagedServiceDefinition(manager, store) {
8153
8393
  try {
8154
- return await (0, import_promises11.readFile)(managedServiceDefinitionPath(manager, store), "utf8");
8394
+ return await (0, import_promises12.readFile)(managedServiceDefinitionPath(manager, store), "utf8");
8155
8395
  } catch (error) {
8156
8396
  if (isNodeErrorCode4(error, "ENOENT"))
8157
8397
  return void 0;
@@ -8160,8 +8400,8 @@ async function readManagedServiceDefinition(manager, store) {
8160
8400
  }
8161
8401
  async function restoreManagedServiceDefinition(manager, store, definition2, runtime) {
8162
8402
  const path4 = managedServiceDefinitionPath(manager, store);
8163
- await (0, import_promises11.mkdir)((0, import_node_path8.dirname)(path4), { recursive: true });
8164
- await (0, import_promises11.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
8403
+ await (0, import_promises12.mkdir)((0, import_node_path9.dirname)(path4), { recursive: true });
8404
+ await (0, import_promises12.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
8165
8405
  if (manager === UserServiceManager.Launchd) {
8166
8406
  const domain = `gui/${process.getuid?.() ?? 0}`;
8167
8407
  await runCommandIgnoringFailure(runtime, "launchctl", [
@@ -8207,12 +8447,44 @@ function parseProcessId(value) {
8207
8447
  const processId = Number.parseInt(value.trim(), 10);
8208
8448
  return Number.isSafeInteger(processId) && processId > 0 ? processId : void 0;
8209
8449
  }
8210
- async function persistServiceManager(store, manager) {
8450
+ async function persistServiceManager(store, manager, managedEntrypointPath) {
8211
8451
  await store.writeServiceManager({
8452
+ ...managedEntrypointPath ? { managedEntrypointPath: (0, import_node_path9.resolve)(managedEntrypointPath) } : {},
8212
8453
  manager,
8213
8454
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
8214
8455
  });
8215
8456
  }
8457
+ async function assertManagedServiceProvenance(store, candidateEntrypointPath) {
8458
+ const stored = (await store.readServiceManager()).value;
8459
+ if (!stored || stored.manager === UserServiceManager.None)
8460
+ return;
8461
+ const candidate = (0, import_node_path9.resolve)(candidateEntrypointPath);
8462
+ if (stored.managedEntrypointPath) {
8463
+ if ((0, import_node_path9.resolve)(stored.managedEntrypointPath) !== candidate) {
8464
+ throw new Error("The managed Connector belongs to a different CLI installation. Run service install from the owning CLI to transfer management.");
8465
+ }
8466
+ return;
8467
+ }
8468
+ if (await isInsideSourceCheckout(candidate)) {
8469
+ throw new Error("A source-checkout CLI cannot replace a legacy managed Connector without recorded installation provenance. Use a separate MOXT_MACHINE_HOME for development.");
8470
+ }
8471
+ }
8472
+ async function isInsideSourceCheckout(path4) {
8473
+ let directory = (0, import_node_path9.dirname)(path4);
8474
+ while (true) {
8475
+ try {
8476
+ await (0, import_promises12.stat)((0, import_node_path9.join)(directory, ".git"));
8477
+ return true;
8478
+ } catch (error) {
8479
+ if (!isNodeErrorCode4(error, "ENOENT"))
8480
+ throw error;
8481
+ }
8482
+ const parent = (0, import_node_path9.dirname)(directory);
8483
+ if (parent === directory)
8484
+ return false;
8485
+ directory = parent;
8486
+ }
8487
+ }
8216
8488
  function managerIsAvailable(manager, capabilities) {
8217
8489
  if (manager === UserServiceManager.Launchd) {
8218
8490
  return capabilities.operatingSystem === "darwin";
@@ -8236,10 +8508,10 @@ function automaticSelectionDetail(manager) {
8236
8508
  }
8237
8509
  async function installLaunchAgent(store, options, runtime) {
8238
8510
  const path4 = launchAgentPath();
8239
- await (0, import_promises11.mkdir)((0, import_node_path8.dirname)(path4), { recursive: true });
8511
+ await (0, import_promises12.mkdir)((0, import_node_path9.dirname)(path4), { recursive: true });
8240
8512
  const programArguments = [
8241
8513
  options.nodePath,
8242
- (0, import_node_path8.resolve)(options.entrypointPath),
8514
+ (0, import_node_path9.resolve)(options.entrypointPath),
8243
8515
  ...options.commandArguments
8244
8516
  ];
8245
8517
  const plist = `<?xml version="1.0" encoding="UTF-8"?>
@@ -8270,7 +8542,7 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
8270
8542
  </dict>
8271
8543
  </plist>
8272
8544
  `;
8273
- await (0, import_promises11.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
8545
+ await (0, import_promises12.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
8274
8546
  const domain = `gui/${process.getuid?.() ?? 0}`;
8275
8547
  await runCommandIgnoringFailure(runtime, "launchctl", [
8276
8548
  "bootout",
@@ -8286,10 +8558,10 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
8286
8558
  }
8287
8559
  async function installSystemdUserService(store, options, runtime) {
8288
8560
  const path4 = systemdUnitPath();
8289
- await (0, import_promises11.mkdir)((0, import_node_path8.dirname)(path4), { recursive: true });
8561
+ await (0, import_promises12.mkdir)((0, import_node_path9.dirname)(path4), { recursive: true });
8290
8562
  const command = [
8291
8563
  options.nodePath,
8292
- (0, import_node_path8.resolve)(options.entrypointPath),
8564
+ (0, import_node_path9.resolve)(options.entrypointPath),
8293
8565
  ...options.commandArguments
8294
8566
  ].map(escapeSystemdArgument).join(" ");
8295
8567
  const unit = `[Unit]
@@ -8308,7 +8580,7 @@ ${Object.entries(options.environment).map(([name, value]) => `Environment=${esca
8308
8580
  [Install]
8309
8581
  WantedBy=default.target
8310
8582
  `;
8311
- await (0, import_promises11.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
8583
+ await (0, import_promises12.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
8312
8584
  await runtime.run("systemctl", ["--user", "daemon-reload"]);
8313
8585
  await runtime.run("systemctl", [
8314
8586
  "--user",
@@ -8324,17 +8596,14 @@ WantedBy=default.target
8324
8596
  async function installSupervisorUserService(store, options, runtime) {
8325
8597
  const directory = supervisorDirectory(store);
8326
8598
  const configPath = supervisorConfigPath(store);
8327
- await (0, import_promises11.mkdir)(directory, { recursive: true, mode: 448 });
8328
- await (0, import_promises11.writeFile)(configPath, createSupervisorConfiguration(store, options), {
8599
+ await (0, import_promises12.mkdir)(directory, { recursive: true, mode: 448 });
8600
+ await (0, import_promises12.writeFile)(configPath, createSupervisorConfiguration(store, options), {
8329
8601
  encoding: "utf8",
8330
8602
  mode: 384
8331
8603
  });
8332
8604
  const supervisorWasRunning = await supervisorIsRunning(store, runtime);
8333
8605
  if (!supervisorWasRunning) {
8334
- await (0, import_promises11.rm)(supervisorSocketPath(store), { force: true });
8335
- await (0, import_promises11.rm)(supervisorPidPath(store), { force: true });
8336
- await runtime.run("supervisord", ["-c", configPath]);
8337
- await waitForSupervisorControl(store, runtime);
8606
+ await startSupervisorUserService(store, runtime);
8338
8607
  return;
8339
8608
  }
8340
8609
  await reloadSupervisorConfiguration(store, runtime);
@@ -8342,7 +8611,7 @@ async function installSupervisorUserService(store, options, runtime) {
8342
8611
  function createSupervisorConfiguration(store, options) {
8343
8612
  const command = [
8344
8613
  options.nodePath,
8345
- (0, import_node_path8.resolve)(options.entrypointPath),
8614
+ (0, import_node_path9.resolve)(options.entrypointPath),
8346
8615
  ...options.commandArguments
8347
8616
  ].map(escapeSupervisorArgument).join(" ");
8348
8617
  const environment = Object.entries(options.environment).map(([name, value]) => `${name}="${escapeSupervisorEnvironment(value)}"`).join(",");
@@ -8366,16 +8635,16 @@ serverurl=unix://${supervisorSocketPath(store)}
8366
8635
 
8367
8636
  [program:${supervisorProgramName}]
8368
8637
  command=${command}
8369
- directory=${escapeSupervisorPath((0, import_node_path8.dirname)((0, import_node_path8.resolve)(options.entrypointPath)))}
8638
+ directory=${escapeSupervisorPath((0, import_node_path9.dirname)((0, import_node_path9.resolve)(options.entrypointPath)))}
8370
8639
  environment=${environment}
8371
8640
  autostart=true
8372
8641
  autorestart=true
8373
- startsecs=3
8374
- startretries=10
8642
+ startsecs=${supervisorProgramStartSeconds}
8643
+ startretries=${supervisorProgramStartRetries}
8375
8644
  stopsignal=TERM
8376
8645
  stopasgroup=true
8377
8646
  killasgroup=true
8378
- stopwaitsecs=20
8647
+ stopwaitsecs=${supervisorProgramStopWaitSeconds}
8379
8648
  stdout_logfile=${escapeSupervisorPath(store.runtimeLogPath())}
8380
8649
  stderr_logfile=${escapeSupervisorPath(store.runtimeErrorLogPath())}
8381
8650
  stdout_logfile_maxbytes=20MB
@@ -8386,28 +8655,27 @@ stderr_logfile_backups=3
8386
8655
  }
8387
8656
  async function restartSupervisorUserService(store, runtime) {
8388
8657
  const configPath = supervisorConfigPath(store);
8389
- if (!await supervisorIsRunning(store, runtime)) {
8390
- await (0, import_promises11.rm)(supervisorSocketPath(store), { force: true });
8391
- await (0, import_promises11.rm)(supervisorPidPath(store), { force: true });
8392
- await runtime.run("supervisord", ["-c", configPath]);
8393
- await waitForSupervisorControl(store, runtime);
8394
- return;
8395
- }
8396
- try {
8658
+ const supervisorProcessId = await currentSupervisorProcessId(store, runtime);
8659
+ const connectorProcessId = await currentSupervisorProgramProcessId(store, runtime);
8660
+ if (supervisorProcessId !== void 0) {
8397
8661
  await runtime.run("supervisorctl", [
8398
8662
  "-c",
8399
8663
  configPath,
8400
- "restart",
8401
- supervisorProgramName
8402
- ]);
8403
- } catch {
8404
- await runtime.run("supervisorctl", [
8405
- "-c",
8406
- configPath,
8407
- "start",
8408
- supervisorProgramName
8664
+ "shutdown"
8409
8665
  ]);
8666
+ await waitForSupervisorExit(store, runtime, supervisorProcessId);
8410
8667
  }
8668
+ await startSupervisorUserService(store, runtime, supervisorProcessId, connectorProcessId);
8669
+ }
8670
+ async function startSupervisorUserService(store, runtime, previousSupervisorProcessId, previousConnectorProcessId) {
8671
+ await (0, import_promises12.rm)(supervisorSocketPath(store), { force: true });
8672
+ await (0, import_promises12.rm)(supervisorPidPath(store), { force: true });
8673
+ await runtime.run("supervisord", ["-c", supervisorConfigPath(store)], {
8674
+ environment: sanitizeEnvironment(process.env),
8675
+ timeoutMilliseconds: serviceManagerMutationTimeoutMilliseconds
8676
+ });
8677
+ await waitForSupervisorControl(store, runtime, previousSupervisorProcessId);
8678
+ await waitForSupervisorProgram(store, runtime, previousConnectorProcessId);
8411
8679
  }
8412
8680
  async function reloadSupervisorConfiguration(store, runtime) {
8413
8681
  const configPath = supervisorConfigPath(store);
@@ -8447,43 +8715,109 @@ async function reloadSupervisorConfiguration(store, runtime) {
8447
8715
  ]);
8448
8716
  }
8449
8717
  async function supervisorIsRunning(store, runtime) {
8450
- return await commandSucceeds(runtime, "supervisorctl", [
8451
- "-c",
8452
- supervisorConfigPath(store),
8453
- "pid"
8454
- ]);
8718
+ return await currentSupervisorProcessId(store, runtime) !== void 0;
8455
8719
  }
8456
- async function waitForSupervisorControl(store, runtime) {
8457
- const deadline = Date.now() + 5e3;
8458
- while (Date.now() < deadline) {
8459
- if (await supervisorIsRunning(store, runtime)) {
8720
+ async function waitForSupervisorControl(store, runtime, previousProcessId) {
8721
+ const deadline = serviceManagerCurrentTime(runtime) + supervisorControlTimeoutMilliseconds;
8722
+ while (serviceManagerCurrentTime(runtime) < deadline) {
8723
+ const processId = await currentSupervisorProcessId(store, runtime);
8724
+ if (processId !== void 0 && processId !== previousProcessId) {
8725
+ return;
8726
+ }
8727
+ await serviceManagerDelay(runtime, 100);
8728
+ }
8729
+ throw new Error(`Supervisor did not become ready within ${supervisorControlTimeoutMilliseconds / 1e3} seconds`);
8730
+ }
8731
+ async function waitForSupervisorExit(store, runtime, processId) {
8732
+ const deadline = serviceManagerCurrentTime(runtime) + supervisorExitTimeoutMilliseconds;
8733
+ while (serviceManagerCurrentTime(runtime) < deadline) {
8734
+ if (!await supervisorIsRunning(store, runtime) && !serviceProcessIsRunning(runtime, processId)) {
8460
8735
  return;
8461
8736
  }
8462
- await delay5(100);
8737
+ await serviceManagerDelay(runtime, 100);
8738
+ }
8739
+ throw new Error(`Supervisor did not exit within ${supervisorExitTimeoutMilliseconds / 1e3} seconds`);
8740
+ }
8741
+ function serviceProcessIsRunning(runtime, processId) {
8742
+ if (runtime.processIsRunning)
8743
+ return runtime.processIsRunning(processId);
8744
+ return localProcessIsRunning(processId);
8745
+ }
8746
+ function localProcessIsRunning(processId) {
8747
+ try {
8748
+ process.kill(processId, 0);
8749
+ return true;
8750
+ } catch (error) {
8751
+ if (isNodeErrorCode4(error, "ESRCH"))
8752
+ return false;
8753
+ throw error;
8754
+ }
8755
+ }
8756
+ async function waitForSupervisorProgram(store, runtime, previousProcessId) {
8757
+ const deadline = serviceManagerCurrentTime(runtime) + supervisorProgramStartTimeoutMilliseconds;
8758
+ while (serviceManagerCurrentTime(runtime) < deadline) {
8759
+ const processId = await currentSupervisorProgramProcessId(store, runtime);
8760
+ if (processId !== void 0 && processId !== previousProcessId)
8761
+ return;
8762
+ await serviceManagerDelay(runtime, 100);
8763
+ }
8764
+ throw new Error(`Moxt Machine Connector did not become ready under Supervisor within ${supervisorProgramStartTimeoutMilliseconds / 1e3} seconds`);
8765
+ }
8766
+ async function currentSupervisorProcessId(store, runtime) {
8767
+ try {
8768
+ const result = await runServiceProbe(runtime, "supervisorctl", [
8769
+ "-c",
8770
+ supervisorConfigPath(store),
8771
+ "pid"
8772
+ ]);
8773
+ const processId = parseProcessId(result.stdout);
8774
+ if (processId !== void 0)
8775
+ return processId;
8776
+ } catch {
8777
+ }
8778
+ try {
8779
+ const processId = parseProcessId(await (0, import_promises12.readFile)(supervisorPidPath(store), "utf8"));
8780
+ return processId !== void 0 && serviceProcessIsRunning(runtime, processId) ? processId : void 0;
8781
+ } catch (error) {
8782
+ if (isNodeErrorCode4(error, "ENOENT"))
8783
+ return void 0;
8784
+ throw error;
8785
+ }
8786
+ }
8787
+ async function currentSupervisorProgramProcessId(store, runtime) {
8788
+ try {
8789
+ const result = await runServiceProbe(runtime, "supervisorctl", [
8790
+ "-c",
8791
+ supervisorConfigPath(store),
8792
+ "pid",
8793
+ supervisorProgramName
8794
+ ]);
8795
+ return parseProcessId(result.stdout);
8796
+ } catch {
8797
+ return void 0;
8463
8798
  }
8464
- throw new Error("Supervisor did not become ready within 5 seconds");
8465
8799
  }
8466
8800
  function launchAgentPath() {
8467
- return (0, import_node_path8.join)(process.env.HOME ?? (0, import_node_os6.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
8801
+ return (0, import_node_path9.join)(process.env.HOME ?? (0, import_node_os6.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
8468
8802
  }
8469
8803
  function systemdUnitPath() {
8470
- const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path8.join)(process.env.HOME ?? (0, import_node_os6.homedir)(), ".config");
8471
- return (0, import_node_path8.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
8804
+ const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path9.join)(process.env.HOME ?? (0, import_node_os6.homedir)(), ".config");
8805
+ return (0, import_node_path9.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
8472
8806
  }
8473
8807
  function supervisorDirectory(store) {
8474
- return (0, import_node_path8.join)(store.baseDirectory, "supervisor");
8808
+ return (0, import_node_path9.join)(store.baseDirectory, "supervisor");
8475
8809
  }
8476
8810
  function supervisorConfigPath(store) {
8477
- return (0, import_node_path8.join)(supervisorDirectory(store), "supervisord.conf");
8811
+ return (0, import_node_path9.join)(supervisorDirectory(store), "supervisord.conf");
8478
8812
  }
8479
8813
  function supervisorSocketPath(store) {
8480
- return (0, import_node_path8.join)(supervisorDirectory(store), "supervisor.sock");
8814
+ return (0, import_node_path9.join)(supervisorDirectory(store), "supervisor.sock");
8481
8815
  }
8482
8816
  function supervisorPidPath(store) {
8483
- return (0, import_node_path8.join)(supervisorDirectory(store), "supervisord.pid");
8817
+ return (0, import_node_path9.join)(supervisorDirectory(store), "supervisord.pid");
8484
8818
  }
8485
8819
  function supervisorLogPath(store) {
8486
- return (0, import_node_path8.join)(supervisorDirectory(store), "supervisord.log");
8820
+ return (0, import_node_path9.join)(supervisorDirectory(store), "supervisord.log");
8487
8821
  }
8488
8822
  async function commandSucceeds(runtime, command, argumentsList) {
8489
8823
  try {
@@ -8533,7 +8867,7 @@ function escapeSupervisorPath(value) {
8533
8867
  function escapeSupervisorValue(value) {
8534
8868
  return value.replaceAll("%", "%%").replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n");
8535
8869
  }
8536
- function errorMessage(error) {
8870
+ function errorMessage2(error) {
8537
8871
  return error instanceof Error ? error.message : String(error);
8538
8872
  }
8539
8873
  function isNodeErrorCode4(error, expectedCode) {
@@ -8544,21 +8878,35 @@ function delay5(milliseconds) {
8544
8878
  setTimeout(resolvePromise, milliseconds);
8545
8879
  });
8546
8880
  }
8547
- var import_node_child_process3, import_promises11, import_node_os6, import_node_path8, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerProbeTimeoutMilliseconds, serviceManagerMutationTimeoutMilliseconds, supervisorProgramName, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
8881
+ function serviceManagerCurrentTime(runtime) {
8882
+ return runtime.currentTimeMilliseconds?.() ?? Date.now();
8883
+ }
8884
+ async function serviceManagerDelay(runtime, milliseconds) {
8885
+ await (runtime.delay?.(milliseconds) ?? delay5(milliseconds));
8886
+ }
8887
+ var import_node_child_process3, import_promises12, import_node_os6, import_node_path9, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerProbeTimeoutMilliseconds, serviceManagerMutationTimeoutMilliseconds, supervisorProgramName, supervisorControlTimeoutMilliseconds, supervisorProgramStartSeconds, supervisorProgramStartRetries, supervisorProgramStopWaitSeconds, supervisorLifecycleBufferMilliseconds, supervisorExitTimeoutMilliseconds, supervisorProgramStartTimeoutMilliseconds, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
8548
8888
  var init_service_manager = __esm({
8549
8889
  "../machine-connector/dist/runtime/service-manager.js"() {
8550
8890
  "use strict";
8551
8891
  init_cjs_shims();
8552
8892
  import_node_child_process3 = require("child_process");
8553
- import_promises11 = require("fs/promises");
8893
+ import_promises12 = require("fs/promises");
8554
8894
  import_node_os6 = require("os");
8555
- import_node_path8 = require("path");
8895
+ import_node_path9 = require("path");
8556
8896
  import_node_util2 = require("util");
8897
+ init_shell_environment();
8557
8898
  execFileAsync = (0, import_node_util2.promisify)(import_node_child_process3.execFile);
8558
8899
  launchAgentLabel = "ai.moxt.machine-connector";
8559
8900
  serviceManagerProbeTimeoutMilliseconds = 5e3;
8560
8901
  serviceManagerMutationTimeoutMilliseconds = 3e4;
8561
8902
  supervisorProgramName = "moxt-machine-connector";
8903
+ supervisorControlTimeoutMilliseconds = 5e3;
8904
+ supervisorProgramStartSeconds = 3;
8905
+ supervisorProgramStartRetries = 10;
8906
+ supervisorProgramStopWaitSeconds = 20;
8907
+ supervisorLifecycleBufferMilliseconds = 5e3;
8908
+ supervisorExitTimeoutMilliseconds = supervisorProgramStopWaitSeconds * 1e3 + supervisorLifecycleBufferMilliseconds;
8909
+ supervisorProgramStartTimeoutMilliseconds = supervisorProgramStartSeconds * supervisorProgramStartRetries * 1e3 + supervisorLifecycleBufferMilliseconds;
8562
8910
  (function(ServiceManagerPreference2) {
8563
8911
  ServiceManagerPreference2["Auto"] = "auto";
8564
8912
  ServiceManagerPreference2["None"] = "none";
@@ -8573,9 +8921,13 @@ var init_service_manager = __esm({
8573
8921
  })(UserServiceManager || (UserServiceManager = {}));
8574
8922
  defaultServiceManagerRuntime = {
8575
8923
  operatingSystem: (0, import_node_os6.platform)(),
8924
+ processIsRunning(processId) {
8925
+ return localProcessIsRunning(processId);
8926
+ },
8576
8927
  async run(command, argumentsList, options) {
8577
8928
  const result = await execFileAsync(command, argumentsList, {
8578
8929
  encoding: "utf8",
8930
+ env: options?.environment,
8579
8931
  killSignal: "SIGKILL",
8580
8932
  timeout: options?.timeoutMilliseconds ?? serviceManagerMutationTimeoutMilliseconds
8581
8933
  });
@@ -8611,7 +8963,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
8611
8963
  try {
8612
8964
  managerOwnsProcess = await managedServiceOwnsProcess(manager, initial.pid, store);
8613
8965
  } catch (error) {
8614
- throw new DaemonRefreshError("ownership", `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage2(error)}`, { cause: error });
8966
+ throw new DaemonRefreshError("ownership", `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage3(error)}`, { cause: error });
8615
8967
  }
8616
8968
  if (!managerOwnsProcess) {
8617
8969
  return { outcome: DaemonReconcileOutcome.Skipped };
@@ -8619,7 +8971,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
8619
8971
  try {
8620
8972
  await validateCliEntrypoint(options, store);
8621
8973
  } catch (error) {
8622
- throw new DaemonRefreshError("validation", errorMessage2(error), {
8974
+ throw new DaemonRefreshError("validation", errorMessage3(error), {
8623
8975
  cause: error
8624
8976
  });
8625
8977
  }
@@ -8630,9 +8982,9 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
8630
8982
  try {
8631
8983
  refresh = await refreshManagedUserService(store, {
8632
8984
  commandArguments: [...options.commandArguments],
8633
- entrypointPath: (0, import_node_path9.resolve)(options.entrypointPath),
8985
+ entrypointPath: (0, import_node_path10.resolve)(options.entrypointPath),
8634
8986
  environment: { ...options.environment },
8635
- nodePath: (0, import_node_path9.resolve)(options.nodePath)
8987
+ nodePath: (0, import_node_path10.resolve)(options.nodePath)
8636
8988
  });
8637
8989
  if (!refresh) {
8638
8990
  throw new Error("The Connector service is no longer managed by Moxt");
@@ -8652,7 +9004,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
8652
9004
  try {
8653
9005
  await refresh.rollback();
8654
9006
  } catch (error) {
8655
- throw new DaemonRefreshError("verification", `${verificationMessage}; restoring the previous service definition also failed: ${errorMessage2(error)}`, { cause: error });
9007
+ throw new DaemonRefreshError("verification", `${verificationMessage}; restoring the previous service definition also failed: ${errorMessage3(error)}`, { cause: error });
8656
9008
  }
8657
9009
  throw new DaemonRefreshError("verification", verificationMessage);
8658
9010
  } finally {
@@ -8660,13 +9012,14 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
8660
9012
  }
8661
9013
  }
8662
9014
  async function validateCliEntrypoint(options, store) {
9015
+ await assertManagedServiceProvenance(store, options.entrypointPath);
8663
9016
  if (options.commandArguments.length !== 2 || options.commandArguments[0] !== "machine" || options.commandArguments[1] !== "daemon") {
8664
9017
  throw new Error("The managed daemon command must be `machine daemon`");
8665
9018
  }
8666
- const nodePath = await (0, import_promises12.realpath)((0, import_node_path9.resolve)(options.nodePath));
8667
- const entrypointPath = await (0, import_promises12.realpath)((0, import_node_path9.resolve)(options.entrypointPath));
8668
- await (0, import_promises12.access)(nodePath, import_promises12.constants.X_OK);
8669
- await (0, import_promises12.access)(entrypointPath, import_promises12.constants.R_OK);
9019
+ const nodePath = await (0, import_promises13.realpath)((0, import_node_path10.resolve)(options.nodePath));
9020
+ const entrypointPath = await (0, import_promises13.realpath)((0, import_node_path10.resolve)(options.entrypointPath));
9021
+ await (0, import_promises13.access)(nodePath, import_promises13.constants.X_OK);
9022
+ await (0, import_promises13.access)(entrypointPath, import_promises13.constants.R_OK);
8670
9023
  const probe = await execFileAsync2(nodePath, [entrypointPath, "--version"], {
8671
9024
  encoding: "utf8",
8672
9025
  env: {
@@ -8696,17 +9049,17 @@ async function reachableRuntimeStatus(store) {
8696
9049
  function delay6(milliseconds) {
8697
9050
  return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
8698
9051
  }
8699
- function errorMessage2(error) {
9052
+ function errorMessage3(error) {
8700
9053
  return error instanceof Error ? error.message : String(error);
8701
9054
  }
8702
- var import_node_child_process4, import_promises12, import_node_path9, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshError;
9055
+ var import_node_child_process4, import_promises13, import_node_path10, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshError;
8703
9056
  var init_daemon_reconcile = __esm({
8704
9057
  "../machine-connector/dist/runtime/daemon-reconcile.js"() {
8705
9058
  "use strict";
8706
9059
  init_cjs_shims();
8707
9060
  import_node_child_process4 = require("child_process");
8708
- import_promises12 = require("fs/promises");
8709
- import_node_path9 = require("path");
9061
+ import_promises13 = require("fs/promises");
9062
+ import_node_path10 = require("path");
8710
9063
  import_node_util3 = require("util");
8711
9064
  init_local_ipc();
8712
9065
  init_process_lock();
@@ -8755,14 +9108,14 @@ async function runMachineDoctor(store) {
8755
9108
  }
8756
9109
  } catch (error) {
8757
9110
  checks.push({
8758
- detail: errorMessage3(error),
9111
+ detail: errorMessage4(error),
8759
9112
  name: "daemon",
8760
9113
  status: DoctorCheckStatus.Failed
8761
9114
  });
8762
9115
  }
8763
9116
  for (const connection of connections) {
8764
9117
  try {
8765
- await (0, import_promises13.access)(connection.rootPath, import_node_fs.constants.R_OK | import_node_fs.constants.X_OK);
9118
+ await (0, import_promises14.access)(connection.rootPath, import_node_fs.constants.R_OK | import_node_fs.constants.X_OK);
8766
9119
  checks.push({
8767
9120
  detail: connection.rootPath,
8768
9121
  name: `root:${connection.connectionId}`,
@@ -8770,14 +9123,14 @@ async function runMachineDoctor(store) {
8770
9123
  });
8771
9124
  } catch (error) {
8772
9125
  checks.push({
8773
- detail: errorMessage3(error),
9126
+ detail: errorMessage4(error),
8774
9127
  name: `root:${connection.connectionId}`,
8775
9128
  status: DoctorCheckStatus.Failed
8776
9129
  });
8777
9130
  }
8778
9131
  const relayUrl = new URL(connection.relayOrigin);
8779
9132
  try {
8780
- const address = await (0, import_promises14.lookup)(relayUrl.hostname);
9133
+ const address = await (0, import_promises15.lookup)(relayUrl.hostname);
8781
9134
  checks.push({
8782
9135
  detail: `${relayUrl.hostname} resolves to ${address.address}`,
8783
9136
  name: `dns:${connection.connectionId}`,
@@ -8785,7 +9138,7 @@ async function runMachineDoctor(store) {
8785
9138
  });
8786
9139
  } catch (error) {
8787
9140
  checks.push({
8788
- detail: errorMessage3(error),
9141
+ detail: errorMessage4(error),
8789
9142
  name: `dns:${connection.connectionId}`,
8790
9143
  status: DoctorCheckStatus.Failed
8791
9144
  });
@@ -8809,7 +9162,7 @@ async function runMachineDoctor(store) {
8809
9162
  });
8810
9163
  } catch (error) {
8811
9164
  checks.push({
8812
- detail: errorMessage3(error),
9165
+ detail: errorMessage4(error),
8813
9166
  name: `tls:${connection.connectionId}`,
8814
9167
  status: DoctorCheckStatus.Failed
8815
9168
  });
@@ -8835,7 +9188,7 @@ async function runMachineDoctor(store) {
8835
9188
  });
8836
9189
  } catch (error) {
8837
9190
  checks.push({
8838
- detail: errorMessage3(error),
9191
+ detail: errorMessage4(error),
8839
9192
  name: "codex",
8840
9193
  status: DoctorCheckStatus.Warning
8841
9194
  });
@@ -8849,25 +9202,25 @@ async function runMachineDoctor(store) {
8849
9202
  });
8850
9203
  } catch (error) {
8851
9204
  checks.push({
8852
- detail: errorMessage3(error),
9205
+ detail: errorMessage4(error),
8853
9206
  name: "claude",
8854
9207
  status: DoctorCheckStatus.Warning
8855
9208
  });
8856
9209
  }
8857
9210
  return checks;
8858
9211
  }
8859
- function errorMessage3(error) {
9212
+ function errorMessage4(error) {
8860
9213
  return error instanceof Error ? error.message : String(error);
8861
9214
  }
8862
- var import_node_child_process5, import_promises13, import_node_fs, import_promises14, import_node_util4, execFileAsync3, DoctorCheckStatus;
9215
+ var import_node_child_process5, import_promises14, import_node_fs, import_promises15, import_node_util4, execFileAsync3, DoctorCheckStatus;
8863
9216
  var init_doctor = __esm({
8864
9217
  "../machine-connector/dist/runtime/doctor.js"() {
8865
9218
  "use strict";
8866
9219
  init_cjs_shims();
8867
9220
  import_node_child_process5 = require("child_process");
8868
- import_promises13 = require("fs/promises");
9221
+ import_promises14 = require("fs/promises");
8869
9222
  import_node_fs = require("fs");
8870
- import_promises14 = require("dns/promises");
9223
+ import_promises15 = require("dns/promises");
8871
9224
  import_node_util4 = require("util");
8872
9225
  init_local_ipc();
8873
9226
  execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process5.execFile);
@@ -9136,7 +9489,7 @@ async function readRecentLogLines(store) {
9136
9489
  }
9137
9490
  async function readOptionalFile(path4) {
9138
9491
  try {
9139
- return await (0, import_promises15.readFile)(path4, "utf8");
9492
+ return await (0, import_promises16.readFile)(path4, "utf8");
9140
9493
  } catch (error) {
9141
9494
  if (isMissingFile(error)) {
9142
9495
  return "";
@@ -9192,16 +9545,16 @@ function isRecord3(value) {
9192
9545
  function isMissingFile(error) {
9193
9546
  return error instanceof Error && "code" in error && error.code === "ENOENT";
9194
9547
  }
9195
- function errorMessage4(error) {
9548
+ function errorMessage5(error) {
9196
9549
  return error instanceof Error ? error.message : String(error);
9197
9550
  }
9198
- var import_promises15, import_promises16, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
9551
+ var import_promises16, import_promises17, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
9199
9552
  var init_machine_manager = __esm({
9200
9553
  "../machine-connector/dist/runtime/machine-manager.js"() {
9201
9554
  "use strict";
9202
9555
  init_cjs_shims();
9203
- import_promises15 = require("fs/promises");
9204
- import_promises16 = require("readline/promises");
9556
+ import_promises16 = require("fs/promises");
9557
+ import_promises17 = require("readline/promises");
9205
9558
  import_node_readline = require("readline");
9206
9559
  init_doctor();
9207
9560
  init_local_ipc();
@@ -9398,7 +9751,7 @@ var init_machine_manager = __esm({
9398
9751
  };
9399
9752
  this.state.message = void 0;
9400
9753
  } catch (error) {
9401
- this.state.message = errorMessage4(error);
9754
+ this.state.message = errorMessage5(error);
9402
9755
  } finally {
9403
9756
  this.refreshing = false;
9404
9757
  this.render();
@@ -9435,7 +9788,7 @@ var init_machine_manager = __esm({
9435
9788
  }
9436
9789
  async runCommandAction(action) {
9437
9790
  this.suspendTerminal();
9438
- const reader = (0, import_promises16.createInterface)({
9791
+ const reader = (0, import_promises17.createInterface)({
9439
9792
  input: process.stdin,
9440
9793
  output: process.stdout
9441
9794
  });
@@ -9446,7 +9799,7 @@ var init_machine_manager = __esm({
9446
9799
  }
9447
9800
  } catch (error) {
9448
9801
  process.stdout.write(`
9449
- Error: ${errorMessage4(error)}
9802
+ Error: ${errorMessage5(error)}
9450
9803
  `);
9451
9804
  }
9452
9805
  await reader.question("\nPress Enter to return to the manager...");
@@ -9625,7 +9978,7 @@ async function pairMachine(store, options) {
9625
9978
  machineName,
9626
9979
  operatingSystem,
9627
9980
  protocolVersion: machineProtocolVersion,
9628
- rootDisplayName: (0, import_node_path10.basename)(canonicalRoot),
9981
+ rootDisplayName: (0, import_node_path11.basename)(canonicalRoot),
9629
9982
  rootHandle
9630
9983
  });
9631
9984
  options.onConfirmation?.(proposal.confirmationUrl);
@@ -9653,7 +10006,7 @@ async function pairMachine(store, options) {
9653
10006
  operatingSystem,
9654
10007
  refreshToken: credentials.refreshToken,
9655
10008
  relayOrigin: options.relayOrigin.replace(/\/+$/, ""),
9656
- rootDisplayName: (0, import_node_path10.basename)(canonicalRoot),
10009
+ rootDisplayName: (0, import_node_path11.basename)(canonicalRoot),
9657
10010
  rootHandle,
9658
10011
  rootPath: canonicalRoot,
9659
10012
  targetId: credentials.targetId,
@@ -9692,7 +10045,7 @@ function delay7(milliseconds) {
9692
10045
  setTimeout(resolvePromise, milliseconds);
9693
10046
  });
9694
10047
  }
9695
- var import_node_child_process6, import_node_crypto7, import_node_os7, import_node_path10, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
10048
+ var import_node_child_process6, import_node_crypto7, import_node_os7, import_node_path11, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
9696
10049
  var init_pairing = __esm({
9697
10050
  "../machine-connector/dist/runtime/pairing.js"() {
9698
10051
  "use strict";
@@ -9700,7 +10053,7 @@ var init_pairing = __esm({
9700
10053
  import_node_child_process6 = require("child_process");
9701
10054
  import_node_crypto7 = require("crypto");
9702
10055
  import_node_os7 = require("os");
9703
- import_node_path10 = require("path");
10056
+ import_node_path11 = require("path");
9704
10057
  init_contracts();
9705
10058
  init_version();
9706
10059
  init_enums();
@@ -9718,6 +10071,7 @@ async function runMachineCli(argumentsList, entrypoint) {
9718
10071
  const command = argumentsList[0] ?? "help";
9719
10072
  const commandArguments = argumentsList.slice(1);
9720
10073
  const store = new MachineRuntimeStore();
10074
+ await rejectCarryingConnectorMutation(store, command, commandArguments);
9721
10075
  await store.initialize();
9722
10076
  if (command === "connect") {
9723
10077
  await connectCommand(store, commandArguments, entrypoint);
@@ -9765,10 +10119,29 @@ async function runMachineCli(argumentsList, entrypoint) {
9765
10119
  }
9766
10120
  writeHelp();
9767
10121
  }
10122
+ async function rejectCarryingConnectorMutation(store, command, commandArguments) {
10123
+ if (!isMachineLifecycleMutation(command, commandArguments))
10124
+ return;
10125
+ const relationship = await localMachineJobTargetRelationship(store);
10126
+ if (relationship === void 0 || relationship === "different_runtime") {
10127
+ return;
10128
+ }
10129
+ throw new Error("A Local Machine Job cannot mutate the Connector carrying it. Set MOXT_MACHINE_HOME to a separate isolated runtime to manage a development Connector.");
10130
+ }
10131
+ function isMachineLifecycleMutation(command, commandArguments) {
10132
+ if (command === "daemon" || command === "daemon-reconcile")
10133
+ return true;
10134
+ if (command === "connect" || command === "disconnect")
10135
+ return true;
10136
+ if (command !== "service")
10137
+ return false;
10138
+ const action = commandArguments[0] ?? "install";
10139
+ return ["install", "restart", "stop", "uninstall"].includes(action);
10140
+ }
9768
10141
  async function connectCommand(store, argumentsList, entrypoint) {
9769
10142
  const options = parseOptions(argumentsList);
9770
10143
  const connectionCode = requiredOption(options, "code");
9771
- const rootPath = (0, import_node_path11.resolve)(options.root ?? process.cwd());
10144
+ const rootPath = (0, import_node_path12.resolve)(options.root ?? process.cwd());
9772
10145
  const serviceManagerPreference = requestedServiceManagerPreference(options);
9773
10146
  await validateExplicitServiceManagerPreference(serviceManagerPreference);
9774
10147
  writeLine("Internal Full Host Access: enabled");
@@ -10053,7 +10426,7 @@ async function waitForDaemonOnline(store) {
10053
10426
  }
10054
10427
  async function readOptionalFile2(path4) {
10055
10428
  try {
10056
- return await (0, import_promises17.readFile)(path4, "utf8");
10429
+ return await (0, import_promises18.readFile)(path4, "utf8");
10057
10430
  } catch {
10058
10431
  return "";
10059
10432
  }
@@ -10082,16 +10455,17 @@ function delay8(milliseconds) {
10082
10455
  setTimeout(resolvePromise, milliseconds);
10083
10456
  });
10084
10457
  }
10085
- var import_promises17, import_node_path11, defaultRelayOrigin;
10458
+ var import_promises18, import_node_path12, defaultRelayOrigin;
10086
10459
  var init_cli = __esm({
10087
10460
  "../machine-connector/dist/cli.js"() {
10088
10461
  "use strict";
10089
10462
  init_cjs_shims();
10090
- import_promises17 = require("fs/promises");
10091
- import_node_path11 = require("path");
10463
+ import_promises18 = require("fs/promises");
10464
+ import_node_path12 = require("path");
10092
10465
  init_daemon();
10093
10466
  init_daemon_reconcile();
10094
10467
  init_doctor();
10468
+ init_execution_context();
10095
10469
  init_local_ipc();
10096
10470
  init_machine_manager();
10097
10471
  init_pairing();
@@ -10138,12 +10512,14 @@ __export(dist_exports, {
10138
10512
  UserServiceManager: () => UserServiceManager,
10139
10513
  assertClientRequestId: () => assertClientRequestId,
10140
10514
  assertContiguousJobEvents: () => assertContiguousJobEvents,
10515
+ assertManagedServiceProvenance: () => assertManagedServiceProvenance,
10141
10516
  assertPositiveGeneration: () => assertPositiveGeneration,
10142
10517
  assertProtocolVersion: () => assertProtocolVersion,
10143
10518
  assertRelativeWorkingDirectory: () => assertRelativeWorkingDirectory,
10144
10519
  assertValidJobTransition: () => assertValidJobTransition,
10145
10520
  assertWaitTimeout: () => assertWaitTimeout,
10146
10521
  collectMachineManagerSnapshot: () => collectMachineManagerSnapshot,
10522
+ createLocalMachineJobExecutionContext: () => createLocalMachineJobExecutionContext,
10147
10523
  createServiceEnvironment: () => createServiceEnvironment,
10148
10524
  createSupervisorConfiguration: () => createSupervisorConfiguration,
10149
10525
  defaultRuntimeDirectory: () => defaultRuntimeDirectory,
@@ -10153,10 +10529,13 @@ __export(dist_exports, {
10153
10529
  executeClaudeStart: () => executeClaudeStart,
10154
10530
  installUserService: () => installUserService,
10155
10531
  isTerminalJobStatus: () => isTerminalJobStatus,
10532
+ localMachineJobTargetRelationship: () => localMachineJobTargetRelationship,
10533
+ machineExecutionContextEnvironmentName: () => machineExecutionContextEnvironmentName,
10156
10534
  machineManagerActions: () => machineManagerActions,
10157
10535
  machineProtocolVersion: () => machineProtocolVersion,
10158
10536
  managedServiceOwnsProcess: () => managedServiceOwnsProcess,
10159
10537
  pairMachine: () => pairMachine,
10538
+ parseLocalMachineJobExecutionContext: () => parseLocalMachineJobExecutionContext,
10160
10539
  parseServiceManagerPreference: () => parseServiceManagerPreference,
10161
10540
  reconcileManagedDaemon: () => reconcileManagedDaemon,
10162
10541
  recordedServiceManager: () => recordedServiceManager,
@@ -10170,6 +10549,7 @@ __export(dist_exports, {
10170
10549
  runMachineDoctor: () => runMachineDoctor,
10171
10550
  runMachineManager: () => runMachineManager,
10172
10551
  selectUserServiceManager: () => selectUserServiceManager,
10552
+ serializeLocalMachineJobExecutionContext: () => serializeLocalMachineJobExecutionContext,
10173
10553
  stopUserService: () => stopUserService,
10174
10554
  uninstallUserService: () => uninstallUserService,
10175
10555
  validateServiceManagerPreference: () => validateServiceManagerPreference
@@ -10184,6 +10564,7 @@ var init_dist = __esm({
10184
10564
  init_daemon_reconcile();
10185
10565
  init_claude_executor();
10186
10566
  init_doctor();
10567
+ init_execution_context();
10187
10568
  init_local_ipc();
10188
10569
  init_machine_manager();
10189
10570
  init_pairing();
@@ -10370,10 +10751,10 @@ function getApiKeyOrUndefined() {
10370
10751
 
10371
10752
  // src/utils/http.ts
10372
10753
  function getUserAgent() {
10373
- return `moxt-cli/${"0.9.0-beta.1"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
10754
+ return `moxt-cli/${"0.9.0-beta.3"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
10374
10755
  }
10375
10756
  async function sendRequest(method, path4, init) {
10376
- const response = await fetch(`${getApiBaseUrl()}${path4}`, {
10757
+ return await fetch(`${getApiBaseUrl()}${path4}`, {
10377
10758
  method,
10378
10759
  headers: {
10379
10760
  Authorization: `Bearer ${getApiKey()}`,
@@ -10382,6 +10763,9 @@ async function sendRequest(method, path4, init) {
10382
10763
  },
10383
10764
  body: init.body
10384
10765
  });
10766
+ }
10767
+ async function sendRequestOrExitOnAuthenticationFailure(method, path4, init) {
10768
+ const response = await sendRequest(method, path4, init);
10385
10769
  if (response.status === 401) {
10386
10770
  console.error("Authentication failed. Check your MOXT_API_KEY.");
10387
10771
  console.error("Get a new key at: https://moxt.ai");
@@ -10390,11 +10774,16 @@ async function sendRequest(method, path4, init) {
10390
10774
  return response;
10391
10775
  }
10392
10776
  async function fetchApi(method, path4, body) {
10393
- return await sendRequest(method, path4, {
10777
+ return await sendRequestOrExitOnAuthenticationFailure(method, path4, {
10394
10778
  headers: { "Content-Type": "application/json" },
10395
10779
  body: body ? JSON.stringify(body) : void 0
10396
10780
  });
10397
10781
  }
10782
+ async function fetchApiIncludingUnauthorized(method, path4) {
10783
+ return await sendRequest(method, path4, {
10784
+ headers: { "Content-Type": "application/json" }
10785
+ });
10786
+ }
10398
10787
  async function toApiResponse(response) {
10399
10788
  const contentType = response.headers.get("content-type");
10400
10789
  const data = contentType?.includes("application/json") ? await response.json() : await response.text();
@@ -10410,6 +10799,9 @@ async function request(method, path4, body) {
10410
10799
  async function httpGet(path4) {
10411
10800
  return request("GET", path4);
10412
10801
  }
10802
+ async function httpGetIncludingUnauthorized(path4) {
10803
+ return await toApiResponse(await fetchApiIncludingUnauthorized("GET", path4));
10804
+ }
10413
10805
  async function httpPut(path4, body) {
10414
10806
  return request("PUT", path4, body);
10415
10807
  }
@@ -10432,7 +10824,7 @@ async function httpRaw(method, path4, body) {
10432
10824
  };
10433
10825
  }
10434
10826
  async function httpPostMultipart(path4, formData) {
10435
- return await toApiResponse(await sendRequest("POST", path4, { body: formData }));
10827
+ return await toApiResponse(await sendRequestOrExitOnAuthenticationFailure("POST", path4, { body: formData }));
10436
10828
  }
10437
10829
 
10438
10830
  // src/utils/output.ts
@@ -10546,8 +10938,8 @@ function readCommentContentFile(path4) {
10546
10938
  if (!fs.existsSync(path4)) {
10547
10939
  throw new FileCommentOptionsError(`Error: comment content file not found: ${path4}`);
10548
10940
  }
10549
- const stat4 = fs.statSync(path4);
10550
- if (!stat4.isFile()) {
10941
+ const stat5 = fs.statSync(path4);
10942
+ if (!stat5.isFile()) {
10551
10943
  throw new FileCommentOptionsError(`Error: comment content path is not a file: ${path4}`);
10552
10944
  }
10553
10945
  const buffer2 = fs.readFileSync(path4);
@@ -11221,8 +11613,8 @@ var FileTokenizer = class _FileTokenizer extends AbstractTokenizer {
11221
11613
  */
11222
11614
  static async fromFile(sourceFilePath) {
11223
11615
  const fileHandle = await (0, import_promises.open)(sourceFilePath, "r");
11224
- const stat4 = await fileHandle.stat();
11225
- return new _FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat4.size } });
11616
+ const stat5 = await fileHandle.stat();
11617
+ return new _FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat5.size } });
11226
11618
  }
11227
11619
  constructor(fileHandle, options) {
11228
11620
  super(options);
@@ -16768,10 +17160,10 @@ function resolveAll(constructs2, events, context) {
16768
17160
  const called = [];
16769
17161
  let index2 = -1;
16770
17162
  while (++index2 < constructs2.length) {
16771
- const resolve8 = constructs2[index2].resolveAll;
16772
- if (resolve8 && !called.includes(resolve8)) {
16773
- events = resolve8(events, context);
16774
- called.push(resolve8);
17163
+ const resolve9 = constructs2[index2].resolveAll;
17164
+ if (resolve9 && !called.includes(resolve9)) {
17165
+ events = resolve9(events, context);
17166
+ called.push(resolve9);
16775
17167
  }
16776
17168
  }
16777
17169
  return events;
@@ -21681,6 +22073,31 @@ function runOrExit2(fn) {
21681
22073
  }
21682
22074
 
21683
22075
  // src/commands/file.ts
22076
+ function exitFileReadJson(error) {
22077
+ console.error(JSON.stringify({ error }));
22078
+ process.exit(1);
22079
+ }
22080
+ function runFileReadResolverOrExit(fn, outputMode) {
22081
+ if (outputMode === "text") {
22082
+ return runOrExit2(fn);
22083
+ }
22084
+ try {
22085
+ return fn();
22086
+ } catch (error) {
22087
+ if (error instanceof SpaceOptionsError) {
22088
+ exitFileReadJson({
22089
+ code: "invalid_arguments",
22090
+ message: error.message.replace(/^Error:\s*/, ""),
22091
+ status: null,
22092
+ details: null
22093
+ });
22094
+ }
22095
+ throw error;
22096
+ }
22097
+ }
22098
+ function errorMessage(error) {
22099
+ return error instanceof Error ? error.message : String(error);
22100
+ }
21684
22101
  async function uploadLocalImage(asset) {
21685
22102
  const formData = new FormData();
21686
22103
  formData.append("file", new Blob([new Uint8Array(asset.bytes)], { type: asset.mimeType }), asset.fileName);
@@ -21798,26 +22215,70 @@ function registerFileCommand(program3) {
21798
22215
  }
21799
22216
  }
21800
22217
  });
21801
- 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) => {
21802
- const mode = runOrExit2(() => resolveReadMode(options));
21803
- startSpinner("Reading file...");
22218
+ 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) => {
22219
+ const outputMode = options.json ? "json" : "text";
22220
+ const mode = runFileReadResolverOrExit(() => resolveReadMode(options), outputMode);
21804
22221
  let response;
21805
22222
  let displayPath;
22223
+ let requestPath;
21806
22224
  if (mode.kind === "by-url") {
21807
22225
  displayPath = mode.url;
21808
- response = await httpGet(
21809
- `/files/read-by-url?url=${encodeURIComponent(mode.url)}`
21810
- );
22226
+ requestPath = `/files/read-by-url?url=${encodeURIComponent(mode.url)}`;
21811
22227
  } else {
21812
22228
  displayPath = mode.path;
21813
- const spaceParams = runOrExit2(() => resolveSpaceSelector(options));
21814
- const qs = buildFileQueryString(mode.path, spaceParams);
21815
- response = await httpGet(
21816
- `/workspaces/${mode.workspace}/files/read${qs}`
22229
+ const spaceParams = runFileReadResolverOrExit(
22230
+ () => resolveSpaceSelector(options),
22231
+ outputMode
21817
22232
  );
22233
+ const qs = buildFileQueryString(mode.path, spaceParams);
22234
+ requestPath = `/workspaces/${mode.workspace}/files/read${qs}`;
22235
+ }
22236
+ if (options.json && getApiKeyOrUndefined() === void 0) {
22237
+ exitFileReadJson({
22238
+ code: "configuration_error",
22239
+ message: "MOXT_API_KEY environment variable is not set.",
22240
+ status: null,
22241
+ details: null
22242
+ });
22243
+ }
22244
+ try {
22245
+ response = options.json ? await httpGetIncludingUnauthorized(requestPath) : await httpGet(requestPath);
22246
+ } catch (error) {
22247
+ if (options.json) {
22248
+ exitFileReadJson({
22249
+ code: "request_failed",
22250
+ message: `File read request failed: ${errorMessage(error)}`,
22251
+ status: null,
22252
+ details: null
22253
+ });
22254
+ }
22255
+ throw error;
21818
22256
  }
21819
22257
  if (!response.ok) {
21820
- stopSpinner(false, "Failed");
22258
+ if (options.json) {
22259
+ if (response.status === 401) {
22260
+ exitFileReadJson({
22261
+ code: "authentication_failed",
22262
+ message: "Authentication failed. Check your MOXT_API_KEY.",
22263
+ status: response.status,
22264
+ details: response.data
22265
+ });
22266
+ }
22267
+ if (response.status === 404) {
22268
+ exitFileReadJson({
22269
+ code: "not_found",
22270
+ message: `${displayPath} does not exist`,
22271
+ status: response.status,
22272
+ details: response.data
22273
+ });
22274
+ }
22275
+ exitFileReadJson({
22276
+ code: "api_error",
22277
+ message: `File read failed with HTTP status ${response.status}.`,
22278
+ status: response.status,
22279
+ details: response.data
22280
+ });
22281
+ }
21821
22282
  if (response.status === 404) {
21822
22283
  print(`${colors.red}\u2620 ${displayPath} does not exist${colors.reset}`);
21823
22284
  } else {
@@ -21827,12 +22288,22 @@ function registerFileCommand(program3) {
21827
22288
  }
21828
22289
  const { type, content: content3 } = response.data;
21829
22290
  if (type === "directory") {
21830
- stopSpinner(false, "Failed");
22291
+ if (options.json) {
22292
+ exitFileReadJson({
22293
+ code: "not_a_file",
22294
+ message: `${displayPath} is a directory`,
22295
+ status: null,
22296
+ details: null
22297
+ });
22298
+ }
21831
22299
  print(`${colors.red}\u2620 ${displayPath} is a directory${colors.reset}`);
21832
22300
  process.exit(1);
21833
22301
  }
21834
- stopSpinner(true, "Done");
21835
- print(content3 ?? "");
22302
+ if (options.json) {
22303
+ print(JSON.stringify(response.data));
22304
+ } else {
22305
+ process.stdout.write(content3);
22306
+ }
21836
22307
  });
21837
22308
  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(
21838
22309
  async (options) => {
@@ -22901,8 +23372,8 @@ function readDescFile(path4) {
22901
23372
  if (!fs5.existsSync(path4)) {
22902
23373
  throw new WorkflowOptionsError(`Error: desc file not found: ${path4}`);
22903
23374
  }
22904
- const stat4 = fs5.statSync(path4);
22905
- if (!stat4.isFile()) {
23375
+ const stat5 = fs5.statSync(path4);
23376
+ if (!stat5.isFile()) {
22906
23377
  throw new WorkflowOptionsError(`Error: desc file is not a file: ${path4}`);
22907
23378
  }
22908
23379
  const buffer2 = fs5.readFileSync(path4);
@@ -22919,11 +23390,11 @@ function readCommentContentFile2(path4) {
22919
23390
  if (!fs5.existsSync(path4)) {
22920
23391
  throw new WorkflowOptionsError(`Error: comment content file not found: ${path4}`);
22921
23392
  }
22922
- const stat4 = fs5.statSync(path4);
22923
- if (!stat4.isFile()) {
23393
+ const stat5 = fs5.statSync(path4);
23394
+ if (!stat5.isFile()) {
22924
23395
  throw new WorkflowOptionsError(`Error: comment content path is not a file: ${path4}`);
22925
23396
  }
22926
- if (stat4.size > MAX_COMMENT_CONTENT_BYTES) {
23397
+ if (stat5.size > MAX_COMMENT_CONTENT_BYTES) {
22927
23398
  throw new WorkflowOptionsError(
22928
23399
  `Error: comment content file must be at most ${MAX_COMMENT_CONTENT_LENGTH} characters.`
22929
23400
  );
@@ -23863,7 +24334,7 @@ var FLUSH_TIMEOUT_MS = 3e3;
23863
24334
  var MAX_BATCH_SIZE = 100;
23864
24335
  function commonLabels() {
23865
24336
  return {
23866
- cli_version: "0.9.0-beta.1",
24337
+ cli_version: "0.9.0-beta.3",
23867
24338
  node_version: process.versions.node,
23868
24339
  os: (0, import_node_os8.platform)(),
23869
24340
  arch: (0, import_node_os8.arch)(),
@@ -23909,7 +24380,7 @@ async function flush() {
23909
24380
  }
23910
24381
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
23911
24382
  const payload = {
23912
- release_id: "0.9.0-beta.1",
24383
+ release_id: "0.9.0-beta.3",
23913
24384
  client_type: "cli",
23914
24385
  metric_data_list: batch.map((m) => ({
23915
24386
  profile: "cli",
@@ -24110,7 +24581,7 @@ function registryWorker() {
24110
24581
 
24111
24582
  // src/update/prompt.ts
24112
24583
  init_cjs_shims();
24113
- var import_promises18 = require("readline/promises");
24584
+ var import_promises19 = require("readline/promises");
24114
24585
  async function promptForUpdate(input, output, currentVersion, latestVersion, timeoutMs) {
24115
24586
  output.write(`
24116
24587
  A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion}
@@ -24123,7 +24594,7 @@ A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion
24123
24594
  const controller = new AbortController();
24124
24595
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
24125
24596
  timeout.unref();
24126
- const readline = (0, import_promises18.createInterface)({ input, output, terminal: true });
24597
+ const readline = (0, import_promises19.createInterface)({ input, output, terminal: true });
24127
24598
  try {
24128
24599
  const answer = await readline.question("", { signal: controller.signal });
24129
24600
  if (answer.trim() === "1") return "update";
@@ -24226,7 +24697,7 @@ function commandPath2(command) {
24226
24697
 
24227
24698
  // src/update/daemon-reconcile-hook.ts
24228
24699
  init_cjs_shims();
24229
- var import_node_path12 = require("path");
24700
+ var import_node_path13 = require("path");
24230
24701
  function installDaemonReconcileHook(program3, cliVersion) {
24231
24702
  program3.hook("preAction", async (_thisCommand, actionCommand) => {
24232
24703
  if (!isEligible2(actionCommand)) return;
@@ -24234,15 +24705,23 @@ function installDaemonReconcileHook(program3, cliVersion) {
24234
24705
  if (!entrypointPath) return;
24235
24706
  const {
24236
24707
  DaemonRefreshError: DaemonRefreshError2,
24708
+ localMachineJobTargetRelationship: localMachineJobTargetRelationship2,
24709
+ MachineRuntimeStore: MachineRuntimeStore2,
24237
24710
  reconcileManagedDaemon: reconcileManagedDaemon2
24238
24711
  } = await Promise.resolve().then(() => (init_dist(), dist_exports));
24712
+ const relationship = await localMachineJobTargetRelationship2(
24713
+ new MachineRuntimeStore2()
24714
+ );
24715
+ if (relationship === "matching_instance" || relationship === "same_runtime_stale_or_unreachable") {
24716
+ return;
24717
+ }
24239
24718
  try {
24240
24719
  await reconcileManagedDaemon2({
24241
24720
  cliVersion,
24242
24721
  commandArguments: ["machine", "daemon"],
24243
- entrypointPath: (0, import_node_path12.resolve)(entrypointPath),
24722
+ entrypointPath: (0, import_node_path13.resolve)(entrypointPath),
24244
24723
  environment: {},
24245
- nodePath: (0, import_node_path12.resolve)(process.execPath),
24724
+ nodePath: (0, import_node_path13.resolve)(process.execPath),
24246
24725
  onActiveJobs: (count) => {
24247
24726
  process.stderr.write(
24248
24727
  `Warning: restarting the managed Connector will interrupt ${count} active ${count === 1 ? "Job" : "Jobs"}.
@@ -24284,9 +24763,9 @@ function commandPath3(command) {
24284
24763
  }
24285
24764
 
24286
24765
  // src/index.ts
24287
- var program2 = createProgram("0.9.0-beta.1");
24288
- installDaemonReconcileHook(program2, "0.9.0-beta.1");
24289
- installUpdateHook(program2, "0.9.0-beta.1");
24766
+ var program2 = createProgram("0.9.0-beta.3");
24767
+ installDaemonReconcileHook(program2, "0.9.0-beta.3");
24768
+ installUpdateHook(program2, "0.9.0-beta.3");
24290
24769
  instrumentProgram(program2);
24291
24770
  installExitHandler();
24292
24771
  program2.parseAsync(process.argv).then(async () => {