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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -152,6 +152,10 @@ moxt file read -w <workspace-id> --teammate-id <teammateId> -p <path>
152
152
  # Read file content by URL
153
153
  moxt file read --url <moxt-url>
154
154
 
155
+ # Read file content and metadata as JSON (path or URL mode)
156
+ moxt file read -w <workspace-id> -p <path> --json
157
+ moxt file read --url <moxt-url> --json
158
+
155
159
  # Resolve the shareable browser URL for a file by path
156
160
  moxt file get-url -w <workspace-id> -p <path>
157
161
 
@@ -312,12 +316,38 @@ Workflow status type values are `1=todo`, `2=in-progress`, and `3=done`.
312
316
  | `--teammate-id <id>` | Teammate ID (teammate space) |
313
317
  | `-p, --path <path>` | File or directory path |
314
318
  | `-u, --url <url>` | Moxt file URL (e.g., `https://moxt.ai/w/{workspaceId}/{fileId}`) |
319
+ | `--json` | Emit `file read` content and metadata as JSON |
315
320
  | `-l, --local-path <path>` | Local file path (for upload) |
316
321
  | `-r, --recursive` | Create parent directories if needed (path mode only) |
317
322
 
318
323
  > **Note**: `-s`, `--personal`, `--team-space-id`, and `--teammate-id` are mutually exclusive.
319
324
  > For `file read` and `file put`, use either `--url` or `--workspace` with `--path`. They are mutually exclusive.
320
325
  > `--url` with `file put` overwrites an existing file identified by the URL; it never creates new files. Use `--recursive` is not allowed in URL mode.
326
+
327
+ #### `file read` output
328
+
329
+ Without `--json`, a successful `file read` writes only the file content to stdout. With
330
+ `--json`, success writes exactly one JSON object to stdout using this shape:
331
+
332
+ ```json
333
+ {"path":"/notes/today.md","type":"file","entries":null,"content":"Hello\n","updatedAt":1785830950000}
334
+ ```
335
+
336
+ `updatedAt` is always a non-null Unix epoch-millisecond integer for a successful JSON
337
+ read. JSON mode writes no progress or color sequences.
338
+
339
+ Every `file read --json` failure exits with status 1, leaves stdout empty, and writes
340
+ exactly one uncolored JSON object to stderr:
341
+
342
+ ```json
343
+ {"error":{"code":"not_found","message":"/missing.md does not exist","status":404,"details":{"message":"not found"}}}
344
+ ```
345
+
346
+ The `error` object always contains `code`, `message`, `status`, and `details`. `status`
347
+ is the HTTP status for API responses and `null` for local or protocol failures;
348
+ `details` is the API response body when available and otherwise `null`. Stable error
349
+ codes are `invalid_arguments`, `configuration_error`, `authentication_failed`,
350
+ `not_found`, `not_a_file`, `api_error`, and `request_failed`.
321
351
  > `file get-url` returns a stable Moxt URL (e.g., `https://moxt.ai/w/{workspaceId}/{fileId}`) for the given path; the URL is unchanged across writes to the same path and can be fed back into `file read --url` or `file put --url`.
322
352
 
323
353
  ## Configuration
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);
@@ -6931,7 +7043,7 @@ function delay4(milliseconds) {
6931
7043
  setTimeout(resolvePromise, milliseconds);
6932
7044
  });
6933
7045
  }
6934
- var import_node_os5, import_node_crypto5, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
7046
+ var import_node_os5, import_node_crypto5, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, commandOutputBatchMaxBytes, commandOutputFlushIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
6935
7047
  var init_daemon = __esm({
6936
7048
  "../machine-connector/dist/runtime/daemon.js"() {
6937
7049
  "use strict";
@@ -6941,6 +7053,7 @@ var init_daemon = __esm({
6941
7053
  init_enums();
6942
7054
  init_contracts();
6943
7055
  init_claude_executor();
7056
+ init_command_output_batcher();
6944
7057
  init_codex_executor();
6945
7058
  init_durable_job();
6946
7059
  init_execution_cancellation();
@@ -6957,6 +7070,8 @@ var init_daemon = __esm({
6957
7070
  claimTimeoutSeconds = 30;
6958
7071
  controlTimeoutSeconds = 30;
6959
7072
  eventUploadIntervalMilliseconds = 500;
7073
+ commandOutputBatchMaxBytes = 4 * 1024;
7074
+ commandOutputFlushIntervalMilliseconds = 250;
6960
7075
  agentOutputLimitBytes = 2e6;
6961
7076
  defaultLeaseSeconds = 90;
6962
7077
  defaultNetworkRetryMilliseconds = 2e3;
@@ -7269,6 +7384,7 @@ var init_daemon = __esm({
7269
7384
  activeJob.cancellation.wait().then(() => this.cancellationResult(activeJob))
7270
7385
  ]);
7271
7386
  void execution.catch(() => void 0);
7387
+ await activeJob.commandOutputBatcher?.flush();
7272
7388
  const detachedProcessHandle = "detachedProcessHandle" in executionResult ? executionResult.detachedProcessHandle : void 0;
7273
7389
  if (detachedProcessHandle) {
7274
7390
  let resourceRecorded = false;
@@ -7308,6 +7424,11 @@ var init_daemon = __esm({
7308
7424
  if (!durableJob) {
7309
7425
  return;
7310
7426
  }
7427
+ try {
7428
+ await activeJob.commandOutputBatcher?.flush();
7429
+ } catch (flushError) {
7430
+ await this.logger.error(`Failed to flush command output for Job ${claim.jobId}`, flushError);
7431
+ }
7311
7432
  const message = error instanceof Error ? error.message : "Unknown Connector error";
7312
7433
  await durableJob.markTerminal({
7313
7434
  exitCode: -1,
@@ -7345,20 +7466,35 @@ var init_daemon = __esm({
7345
7466
  if (!environment2 || !canSpawn()) {
7346
7467
  return this.cancellationResult(activeJob);
7347
7468
  }
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
7469
+ const outputBatcher = new CommandOutputBatcher({
7470
+ flushIntervalMilliseconds: commandOutputFlushIntervalMilliseconds,
7471
+ maxBytes: commandOutputBatchMaxBytes,
7472
+ write: async (stream, text3) => {
7473
+ await durableJob.appendOutput(stream, text3, request2.outputLimitBytes);
7474
+ }
7357
7475
  });
7358
- return {
7359
- ...result,
7360
- result: { exitCode: result.exitCode }
7361
- };
7476
+ activeJob.commandOutputBatcher = outputBatcher;
7477
+ try {
7478
+ const result = await executeProcess(request2.executable, request2.arguments, workingDirectory2, environment2, request2.stdin, request2.timeoutSeconds, {
7479
+ canSpawn,
7480
+ onOutput: async (output) => {
7481
+ if (activeJob.cancellation.currentReason() !== void 0) {
7482
+ return;
7483
+ }
7484
+ await outputBatcher.append(output.stream, output.text);
7485
+ },
7486
+ onSpawn: registerProcess
7487
+ });
7488
+ return {
7489
+ ...result,
7490
+ result: { exitCode: result.exitCode }
7491
+ };
7492
+ } finally {
7493
+ await outputBatcher.flush();
7494
+ if (activeJob.commandOutputBatcher === outputBatcher) {
7495
+ activeJob.commandOutputBatcher = void 0;
7496
+ }
7497
+ }
7362
7498
  }
7363
7499
  if (claim.kind === MachineJobKind.ViewImage) {
7364
7500
  const request2 = claim.requestPayload;
@@ -7954,7 +8090,7 @@ async function refreshManagedUserService(store, options, runtime = defaultServic
7954
8090
  try {
7955
8091
  await rollback();
7956
8092
  } catch (rollbackError) {
7957
- throw new Error(`${errorMessage(error)}; restoring the previous ${manager} definition also failed: ${errorMessage(rollbackError)}`, { cause: error });
8093
+ throw new Error(`${errorMessage2(error)}; restoring the previous ${manager} definition also failed: ${errorMessage2(rollbackError)}`, { cause: error });
7958
8094
  }
7959
8095
  throw error;
7960
8096
  }
@@ -8533,7 +8669,7 @@ function escapeSupervisorPath(value) {
8533
8669
  function escapeSupervisorValue(value) {
8534
8670
  return value.replaceAll("%", "%%").replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n");
8535
8671
  }
8536
- function errorMessage(error) {
8672
+ function errorMessage2(error) {
8537
8673
  return error instanceof Error ? error.message : String(error);
8538
8674
  }
8539
8675
  function isNodeErrorCode4(error, expectedCode) {
@@ -8611,7 +8747,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
8611
8747
  try {
8612
8748
  managerOwnsProcess = await managedServiceOwnsProcess(manager, initial.pid, store);
8613
8749
  } catch (error) {
8614
- throw new DaemonRefreshError("ownership", `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage2(error)}`, { cause: error });
8750
+ throw new DaemonRefreshError("ownership", `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage3(error)}`, { cause: error });
8615
8751
  }
8616
8752
  if (!managerOwnsProcess) {
8617
8753
  return { outcome: DaemonReconcileOutcome.Skipped };
@@ -8619,7 +8755,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
8619
8755
  try {
8620
8756
  await validateCliEntrypoint(options, store);
8621
8757
  } catch (error) {
8622
- throw new DaemonRefreshError("validation", errorMessage2(error), {
8758
+ throw new DaemonRefreshError("validation", errorMessage3(error), {
8623
8759
  cause: error
8624
8760
  });
8625
8761
  }
@@ -8652,7 +8788,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
8652
8788
  try {
8653
8789
  await refresh.rollback();
8654
8790
  } catch (error) {
8655
- throw new DaemonRefreshError("verification", `${verificationMessage}; restoring the previous service definition also failed: ${errorMessage2(error)}`, { cause: error });
8791
+ throw new DaemonRefreshError("verification", `${verificationMessage}; restoring the previous service definition also failed: ${errorMessage3(error)}`, { cause: error });
8656
8792
  }
8657
8793
  throw new DaemonRefreshError("verification", verificationMessage);
8658
8794
  } finally {
@@ -8696,7 +8832,7 @@ async function reachableRuntimeStatus(store) {
8696
8832
  function delay6(milliseconds) {
8697
8833
  return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
8698
8834
  }
8699
- function errorMessage2(error) {
8835
+ function errorMessage3(error) {
8700
8836
  return error instanceof Error ? error.message : String(error);
8701
8837
  }
8702
8838
  var import_node_child_process4, import_promises12, import_node_path9, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshError;
@@ -8755,7 +8891,7 @@ async function runMachineDoctor(store) {
8755
8891
  }
8756
8892
  } catch (error) {
8757
8893
  checks.push({
8758
- detail: errorMessage3(error),
8894
+ detail: errorMessage4(error),
8759
8895
  name: "daemon",
8760
8896
  status: DoctorCheckStatus.Failed
8761
8897
  });
@@ -8770,7 +8906,7 @@ async function runMachineDoctor(store) {
8770
8906
  });
8771
8907
  } catch (error) {
8772
8908
  checks.push({
8773
- detail: errorMessage3(error),
8909
+ detail: errorMessage4(error),
8774
8910
  name: `root:${connection.connectionId}`,
8775
8911
  status: DoctorCheckStatus.Failed
8776
8912
  });
@@ -8785,7 +8921,7 @@ async function runMachineDoctor(store) {
8785
8921
  });
8786
8922
  } catch (error) {
8787
8923
  checks.push({
8788
- detail: errorMessage3(error),
8924
+ detail: errorMessage4(error),
8789
8925
  name: `dns:${connection.connectionId}`,
8790
8926
  status: DoctorCheckStatus.Failed
8791
8927
  });
@@ -8809,7 +8945,7 @@ async function runMachineDoctor(store) {
8809
8945
  });
8810
8946
  } catch (error) {
8811
8947
  checks.push({
8812
- detail: errorMessage3(error),
8948
+ detail: errorMessage4(error),
8813
8949
  name: `tls:${connection.connectionId}`,
8814
8950
  status: DoctorCheckStatus.Failed
8815
8951
  });
@@ -8835,7 +8971,7 @@ async function runMachineDoctor(store) {
8835
8971
  });
8836
8972
  } catch (error) {
8837
8973
  checks.push({
8838
- detail: errorMessage3(error),
8974
+ detail: errorMessage4(error),
8839
8975
  name: "codex",
8840
8976
  status: DoctorCheckStatus.Warning
8841
8977
  });
@@ -8849,14 +8985,14 @@ async function runMachineDoctor(store) {
8849
8985
  });
8850
8986
  } catch (error) {
8851
8987
  checks.push({
8852
- detail: errorMessage3(error),
8988
+ detail: errorMessage4(error),
8853
8989
  name: "claude",
8854
8990
  status: DoctorCheckStatus.Warning
8855
8991
  });
8856
8992
  }
8857
8993
  return checks;
8858
8994
  }
8859
- function errorMessage3(error) {
8995
+ function errorMessage4(error) {
8860
8996
  return error instanceof Error ? error.message : String(error);
8861
8997
  }
8862
8998
  var import_node_child_process5, import_promises13, import_node_fs, import_promises14, import_node_util4, execFileAsync3, DoctorCheckStatus;
@@ -9192,7 +9328,7 @@ function isRecord3(value) {
9192
9328
  function isMissingFile(error) {
9193
9329
  return error instanceof Error && "code" in error && error.code === "ENOENT";
9194
9330
  }
9195
- function errorMessage4(error) {
9331
+ function errorMessage5(error) {
9196
9332
  return error instanceof Error ? error.message : String(error);
9197
9333
  }
9198
9334
  var import_promises15, import_promises16, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
@@ -9398,7 +9534,7 @@ var init_machine_manager = __esm({
9398
9534
  };
9399
9535
  this.state.message = void 0;
9400
9536
  } catch (error) {
9401
- this.state.message = errorMessage4(error);
9537
+ this.state.message = errorMessage5(error);
9402
9538
  } finally {
9403
9539
  this.refreshing = false;
9404
9540
  this.render();
@@ -9446,7 +9582,7 @@ var init_machine_manager = __esm({
9446
9582
  }
9447
9583
  } catch (error) {
9448
9584
  process.stdout.write(`
9449
- Error: ${errorMessage4(error)}
9585
+ Error: ${errorMessage5(error)}
9450
9586
  `);
9451
9587
  }
9452
9588
  await reader.question("\nPress Enter to return to the manager...");
@@ -10370,10 +10506,10 @@ function getApiKeyOrUndefined() {
10370
10506
 
10371
10507
  // src/utils/http.ts
10372
10508
  function getUserAgent() {
10373
- return `moxt-cli/${"0.9.0-beta.1"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
10509
+ return `moxt-cli/${"0.9.0-beta.2"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
10374
10510
  }
10375
10511
  async function sendRequest(method, path4, init) {
10376
- const response = await fetch(`${getApiBaseUrl()}${path4}`, {
10512
+ return await fetch(`${getApiBaseUrl()}${path4}`, {
10377
10513
  method,
10378
10514
  headers: {
10379
10515
  Authorization: `Bearer ${getApiKey()}`,
@@ -10382,6 +10518,9 @@ async function sendRequest(method, path4, init) {
10382
10518
  },
10383
10519
  body: init.body
10384
10520
  });
10521
+ }
10522
+ async function sendRequestOrExitOnAuthenticationFailure(method, path4, init) {
10523
+ const response = await sendRequest(method, path4, init);
10385
10524
  if (response.status === 401) {
10386
10525
  console.error("Authentication failed. Check your MOXT_API_KEY.");
10387
10526
  console.error("Get a new key at: https://moxt.ai");
@@ -10390,11 +10529,16 @@ async function sendRequest(method, path4, init) {
10390
10529
  return response;
10391
10530
  }
10392
10531
  async function fetchApi(method, path4, body) {
10393
- return await sendRequest(method, path4, {
10532
+ return await sendRequestOrExitOnAuthenticationFailure(method, path4, {
10394
10533
  headers: { "Content-Type": "application/json" },
10395
10534
  body: body ? JSON.stringify(body) : void 0
10396
10535
  });
10397
10536
  }
10537
+ async function fetchApiIncludingUnauthorized(method, path4) {
10538
+ return await sendRequest(method, path4, {
10539
+ headers: { "Content-Type": "application/json" }
10540
+ });
10541
+ }
10398
10542
  async function toApiResponse(response) {
10399
10543
  const contentType = response.headers.get("content-type");
10400
10544
  const data = contentType?.includes("application/json") ? await response.json() : await response.text();
@@ -10410,6 +10554,9 @@ async function request(method, path4, body) {
10410
10554
  async function httpGet(path4) {
10411
10555
  return request("GET", path4);
10412
10556
  }
10557
+ async function httpGetIncludingUnauthorized(path4) {
10558
+ return await toApiResponse(await fetchApiIncludingUnauthorized("GET", path4));
10559
+ }
10413
10560
  async function httpPut(path4, body) {
10414
10561
  return request("PUT", path4, body);
10415
10562
  }
@@ -10432,7 +10579,7 @@ async function httpRaw(method, path4, body) {
10432
10579
  };
10433
10580
  }
10434
10581
  async function httpPostMultipart(path4, formData) {
10435
- return await toApiResponse(await sendRequest("POST", path4, { body: formData }));
10582
+ return await toApiResponse(await sendRequestOrExitOnAuthenticationFailure("POST", path4, { body: formData }));
10436
10583
  }
10437
10584
 
10438
10585
  // src/utils/output.ts
@@ -21681,6 +21828,31 @@ function runOrExit2(fn) {
21681
21828
  }
21682
21829
 
21683
21830
  // src/commands/file.ts
21831
+ function exitFileReadJson(error) {
21832
+ console.error(JSON.stringify({ error }));
21833
+ process.exit(1);
21834
+ }
21835
+ function runFileReadResolverOrExit(fn, outputMode) {
21836
+ if (outputMode === "text") {
21837
+ return runOrExit2(fn);
21838
+ }
21839
+ try {
21840
+ return fn();
21841
+ } catch (error) {
21842
+ if (error instanceof SpaceOptionsError) {
21843
+ exitFileReadJson({
21844
+ code: "invalid_arguments",
21845
+ message: error.message.replace(/^Error:\s*/, ""),
21846
+ status: null,
21847
+ details: null
21848
+ });
21849
+ }
21850
+ throw error;
21851
+ }
21852
+ }
21853
+ function errorMessage(error) {
21854
+ return error instanceof Error ? error.message : String(error);
21855
+ }
21684
21856
  async function uploadLocalImage(asset) {
21685
21857
  const formData = new FormData();
21686
21858
  formData.append("file", new Blob([new Uint8Array(asset.bytes)], { type: asset.mimeType }), asset.fileName);
@@ -21798,26 +21970,70 @@ function registerFileCommand(program3) {
21798
21970
  }
21799
21971
  }
21800
21972
  });
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...");
21973
+ file.command("read").description("Read file content").option("-w, --workspace <workspaceId>", "Workspace ID").option("-s, --space <name>", "Space name (personal or teamspace name)").option("--personal", "Use personal space (default)").option("--team-space-id <teamSpaceId>", "Team space ID").option("--teammate-id <teammateId>", "Teammate ID (teammate space)").option("-p, --path <path>", "File path").option("-u, --url <url>", "Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})").option("--json", "Emit file content and metadata as JSON").action(async (options) => {
21974
+ const outputMode = options.json ? "json" : "text";
21975
+ const mode = runFileReadResolverOrExit(() => resolveReadMode(options), outputMode);
21804
21976
  let response;
21805
21977
  let displayPath;
21978
+ let requestPath;
21806
21979
  if (mode.kind === "by-url") {
21807
21980
  displayPath = mode.url;
21808
- response = await httpGet(
21809
- `/files/read-by-url?url=${encodeURIComponent(mode.url)}`
21810
- );
21981
+ requestPath = `/files/read-by-url?url=${encodeURIComponent(mode.url)}`;
21811
21982
  } else {
21812
21983
  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}`
21984
+ const spaceParams = runFileReadResolverOrExit(
21985
+ () => resolveSpaceSelector(options),
21986
+ outputMode
21817
21987
  );
21988
+ const qs = buildFileQueryString(mode.path, spaceParams);
21989
+ requestPath = `/workspaces/${mode.workspace}/files/read${qs}`;
21990
+ }
21991
+ if (options.json && getApiKeyOrUndefined() === void 0) {
21992
+ exitFileReadJson({
21993
+ code: "configuration_error",
21994
+ message: "MOXT_API_KEY environment variable is not set.",
21995
+ status: null,
21996
+ details: null
21997
+ });
21998
+ }
21999
+ try {
22000
+ response = options.json ? await httpGetIncludingUnauthorized(requestPath) : await httpGet(requestPath);
22001
+ } catch (error) {
22002
+ if (options.json) {
22003
+ exitFileReadJson({
22004
+ code: "request_failed",
22005
+ message: `File read request failed: ${errorMessage(error)}`,
22006
+ status: null,
22007
+ details: null
22008
+ });
22009
+ }
22010
+ throw error;
21818
22011
  }
21819
22012
  if (!response.ok) {
21820
- stopSpinner(false, "Failed");
22013
+ if (options.json) {
22014
+ if (response.status === 401) {
22015
+ exitFileReadJson({
22016
+ code: "authentication_failed",
22017
+ message: "Authentication failed. Check your MOXT_API_KEY.",
22018
+ status: response.status,
22019
+ details: response.data
22020
+ });
22021
+ }
22022
+ if (response.status === 404) {
22023
+ exitFileReadJson({
22024
+ code: "not_found",
22025
+ message: `${displayPath} does not exist`,
22026
+ status: response.status,
22027
+ details: response.data
22028
+ });
22029
+ }
22030
+ exitFileReadJson({
22031
+ code: "api_error",
22032
+ message: `File read failed with HTTP status ${response.status}.`,
22033
+ status: response.status,
22034
+ details: response.data
22035
+ });
22036
+ }
21821
22037
  if (response.status === 404) {
21822
22038
  print(`${colors.red}\u2620 ${displayPath} does not exist${colors.reset}`);
21823
22039
  } else {
@@ -21827,12 +22043,22 @@ function registerFileCommand(program3) {
21827
22043
  }
21828
22044
  const { type, content: content3 } = response.data;
21829
22045
  if (type === "directory") {
21830
- stopSpinner(false, "Failed");
22046
+ if (options.json) {
22047
+ exitFileReadJson({
22048
+ code: "not_a_file",
22049
+ message: `${displayPath} is a directory`,
22050
+ status: null,
22051
+ details: null
22052
+ });
22053
+ }
21831
22054
  print(`${colors.red}\u2620 ${displayPath} is a directory${colors.reset}`);
21832
22055
  process.exit(1);
21833
22056
  }
21834
- stopSpinner(true, "Done");
21835
- print(content3 ?? "");
22057
+ if (options.json) {
22058
+ print(JSON.stringify(response.data));
22059
+ } else {
22060
+ process.stdout.write(content3);
22061
+ }
21836
22062
  });
21837
22063
  file.command("put").description("Upload a file").option("-w, --workspace <workspaceId>", "Workspace ID").option("-s, --space <name>", "Space name (personal or teamspace name)").option("--personal", "Use personal space (default)").option("--team-space-id <teamSpaceId>", "Team space ID").option("--teammate-id <teammateId>", "Teammate ID (teammate space)").option("-p, --path <path>", "Remote file path").option("-u, --url <url>", "Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})").requiredOption("-l, --local-path <localPath>", "Local file path").option("-r, --recursive", "Create parent directories if needed").action(
21838
22064
  async (options) => {
@@ -23863,7 +24089,7 @@ var FLUSH_TIMEOUT_MS = 3e3;
23863
24089
  var MAX_BATCH_SIZE = 100;
23864
24090
  function commonLabels() {
23865
24091
  return {
23866
- cli_version: "0.9.0-beta.1",
24092
+ cli_version: "0.9.0-beta.2",
23867
24093
  node_version: process.versions.node,
23868
24094
  os: (0, import_node_os8.platform)(),
23869
24095
  arch: (0, import_node_os8.arch)(),
@@ -23909,7 +24135,7 @@ async function flush() {
23909
24135
  }
23910
24136
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
23911
24137
  const payload = {
23912
- release_id: "0.9.0-beta.1",
24138
+ release_id: "0.9.0-beta.2",
23913
24139
  client_type: "cli",
23914
24140
  metric_data_list: batch.map((m) => ({
23915
24141
  profile: "cli",
@@ -24284,9 +24510,9 @@ function commandPath3(command) {
24284
24510
  }
24285
24511
 
24286
24512
  // 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");
24513
+ var program2 = createProgram("0.9.0-beta.2");
24514
+ installDaemonReconcileHook(program2, "0.9.0-beta.2");
24515
+ installUpdateHook(program2, "0.9.0-beta.2");
24290
24516
  instrumentProgram(program2);
24291
24517
  installExitHandler();
24292
24518
  program2.parseAsync(process.argv).then(async () => {