@moxt-ai/cli 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -151,7 +151,64 @@ Set the following environment variables:
151
151
  | Variable | Description |
152
152
  |----------|-------------|
153
153
  | `MOXT_API_KEY` | Your Moxt API key |
154
- | `MOXT_API_URL` | API endpoint (default: `https://api.moxt.ai`) |
154
+ | `MOXT_HOST` | API hostname (default: `api.moxt.ai`) |
155
+ | `MOXT_TELEMETRY_DISABLED` | Set to `1` to disable anonymous usage telemetry |
156
+ | `DO_NOT_TRACK` | Set to `1` to disable anonymous usage telemetry (community standard) |
157
+
158
+ ## Telemetry
159
+
160
+ Moxt CLI collects **anonymous usage data** by default to help us understand how the tool
161
+ is used, prioritize features, and catch regressions. Telemetry is easy to turn off.
162
+
163
+ ### What we collect
164
+
165
+ Every invocation of a Moxt CLI command may record:
166
+
167
+ | Field | Example | Purpose |
168
+ |-------|---------|---------|
169
+ | `command` / `subcommand` | `workspace` / `list` | Which command was invoked |
170
+ | `cli_version` | `1.2.3` | Distribution of CLI versions in use |
171
+ | `node_version` | `20.11.0` | Minimum-supported runtime planning |
172
+ | `os` | `darwin` / `linux` / `win32` | OS support prioritization |
173
+ | `arch` | `arm64` / `x64` | Architecture support prioritization |
174
+ | `status` | `success` / `error` | Success and error rates |
175
+ | `error_code` | `uncaught_exception` | Error classification (best-effort; may be dropped on crash) |
176
+ | `is_ci` | `true` / `false` | Separate CI traffic from human usage |
177
+ | Duration | `0.42` seconds | Performance tracking |
178
+
179
+ User identification: telemetry is only sent while you are authenticated with a Moxt API
180
+ key. Your **user ID is attached server-side** so that product decisions reflect real
181
+ usage patterns.
182
+
183
+ ### What we do NOT collect
184
+
185
+ - Command argument values (file paths, workspace IDs, emails, etc.)
186
+ - File contents, directory names, or any data from your workspace
187
+ - Environment variables
188
+ - Standard output, standard error, or error messages
189
+
190
+ ### How to opt out
191
+
192
+ Any one of the following disables all telemetry:
193
+
194
+ ```bash
195
+ # Environment variable (recommended for CI)
196
+ export MOXT_TELEMETRY_DISABLED=1
197
+
198
+ # Or the community-standard variable
199
+ export DO_NOT_TRACK=1
200
+
201
+ # Or persist the choice
202
+ moxt telemetry disable
203
+ ```
204
+
205
+ Check current status with `moxt telemetry status`. Re-enable with `moxt telemetry enable`.
206
+
207
+ ### Where the data is sent
208
+
209
+ Metrics are sent to `POST /openapi/v1/cli-metrics` on Moxt's API endpoint, authenticated
210
+ with your API key. They are stored in Datadog and used to produce aggregated dashboards
211
+ and reliability monitors.
155
212
 
156
213
  ## License
157
214
 
package/dist/index.js CHANGED
@@ -46,10 +46,10 @@ function resolveSpaceSelector(options) {
46
46
  }
47
47
  return {};
48
48
  }
49
- function buildFileQueryString(path, spaceParams) {
49
+ function buildFileQueryString(path2, spaceParams) {
50
50
  const params = new URLSearchParams();
51
- if (path != null && path !== "") {
52
- params.set("path", path);
51
+ if (path2 != null && path2 !== "") {
52
+ params.set("path", path2);
53
53
  }
54
54
  if (spaceParams.space) {
55
55
  params.set("space", spaceParams.space);
@@ -63,10 +63,10 @@ function buildFileQueryString(path, spaceParams) {
63
63
  const qs = params.toString();
64
64
  return qs ? `?${qs}` : "";
65
65
  }
66
- function isBinaryContent(buffer) {
67
- const sampleSize = Math.min(buffer.length, 8192);
66
+ function isBinaryContent(buffer2) {
67
+ const sampleSize = Math.min(buffer2.length, 8192);
68
68
  for (let i = 0; i < sampleSize; i++) {
69
- const byte = buffer[i];
69
+ const byte = buffer2[i];
70
70
  if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {
71
71
  return true;
72
72
  }
@@ -141,14 +141,17 @@ function getApiKey() {
141
141
  }
142
142
  return apiKey;
143
143
  }
144
+ function getApiKeyOrUndefined() {
145
+ return process.env.MOXT_API_KEY;
146
+ }
144
147
 
145
148
  // src/utils/http.ts
146
149
  function getUserAgent() {
147
- return `moxt-cli/${"0.2.1"} (${platform()}/${arch()}) node/${process.versions.node}`;
150
+ return `moxt-cli/${"0.3.1"} (${platform()}/${arch()}) node/${process.versions.node}`;
148
151
  }
149
- async function request(method, path, body) {
152
+ async function fetchApi(method, path2, body) {
150
153
  const apiKey = getApiKey();
151
- const url = `${getApiBaseUrl()}${path}`;
154
+ const url = `${getApiBaseUrl()}${path2}`;
152
155
  const response = await fetch(url, {
153
156
  method,
154
157
  headers: {
@@ -158,35 +161,43 @@ async function request(method, path, body) {
158
161
  },
159
162
  body: body ? JSON.stringify(body) : void 0
160
163
  });
161
- let data;
162
- const contentType = response.headers.get("content-type");
163
- if (contentType?.includes("application/json")) {
164
- data = await response.json();
165
- } else {
166
- data = await response.text();
167
- }
168
164
  if (response.status === 401) {
169
165
  console.error("Authentication failed. Check your MOXT_API_KEY.");
170
166
  console.error("Get a new key at: https://moxt.ai");
171
167
  process.exit(1);
172
168
  }
169
+ return response;
170
+ }
171
+ async function request(method, path2, body) {
172
+ const response = await fetchApi(method, path2, body);
173
+ const contentType = response.headers.get("content-type");
174
+ const data = contentType?.includes("application/json") ? await response.json() : await response.text();
173
175
  return {
174
176
  ok: response.ok,
175
177
  status: response.status,
176
178
  data
177
179
  };
178
180
  }
179
- async function httpGet(path) {
180
- return request("GET", path);
181
+ async function httpGet(path2) {
182
+ return request("GET", path2);
181
183
  }
182
- async function httpPut(path, body) {
183
- return request("PUT", path, body);
184
+ async function httpPut(path2, body) {
185
+ return request("PUT", path2, body);
184
186
  }
185
- async function httpPost(path, body) {
186
- return request("POST", path, body);
187
+ async function httpPost(path2, body) {
188
+ return request("POST", path2, body);
187
189
  }
188
- async function httpDelete(path, body) {
189
- return request("DELETE", path, body);
190
+ async function httpDelete(path2, body) {
191
+ return request("DELETE", path2, body);
192
+ }
193
+ async function httpRaw(method, path2, body) {
194
+ const response = await fetchApi(method, path2, body);
195
+ return {
196
+ ok: response.ok,
197
+ status: response.status,
198
+ text: await response.text(),
199
+ contentType: response.headers.get("content-type")
200
+ };
190
201
  }
191
202
 
192
203
  // src/utils/output.ts
@@ -286,12 +297,12 @@ function registerFileCommand(program2) {
286
297
  }
287
298
  process.exit(1);
288
299
  }
289
- const { path, entries } = response.data;
300
+ const { path: path2, entries } = response.data;
290
301
  if (!entries || entries.length === 0) {
291
- stopSpinner(true, `${path}: empty directory`);
302
+ stopSpinner(true, `${path2}: empty directory`);
292
303
  return;
293
304
  }
294
- stopSpinner(true, path);
305
+ stopSpinner(true, path2);
295
306
  for (const entry of entries) {
296
307
  if (entry.type === "directory") {
297
308
  print(`${colors.blue}${entry.name}/${colors.reset}`);
@@ -353,12 +364,12 @@ function registerFileCommand(program2) {
353
364
  print(`${colors.red}\u2620 File too large (max 10MB): ${options.localPath}${colors.reset}`);
354
365
  process.exit(1);
355
366
  }
356
- const buffer = fs.readFileSync(options.localPath);
357
- if (isBinaryContent(buffer)) {
367
+ const buffer2 = fs.readFileSync(options.localPath);
368
+ if (isBinaryContent(buffer2)) {
358
369
  print(`${colors.red}\u2620 Binary files are not allowed. Only text files can be uploaded.${colors.reset}`);
359
370
  process.exit(1);
360
371
  }
361
- const content = buffer.toString("utf8");
372
+ const content = buffer2.toString("utf8");
362
373
  startSpinner("Uploading...");
363
374
  let response;
364
375
  let displayPath;
@@ -458,6 +469,231 @@ function registerFileCommand(program2) {
458
469
  );
459
470
  }
460
471
 
472
+ // src/utils/miniapp-db.ts
473
+ var MiniappDbOptionsError = class extends Error {
474
+ constructor(message) {
475
+ super(message);
476
+ this.name = "MiniappDbOptionsError";
477
+ }
478
+ };
479
+ var NON_FILTER_QUERY_PARAMS = /* @__PURE__ */ new Set([
480
+ "select",
481
+ "order",
482
+ "limit",
483
+ "offset",
484
+ "range",
485
+ "range-unit"
486
+ ]);
487
+ var ALLOWED_MINIAPP_DB_EMAIL_DOMAINS = ["@paraflow.com", "@moxt.ai", "@kanyun.com"];
488
+ function normalizePostgrestPath(path2) {
489
+ const trimmed = path2.trim();
490
+ if (!trimmed) {
491
+ throw new MiniappDbOptionsError("Error: PostgREST path is required.");
492
+ }
493
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
494
+ }
495
+ function buildMiniappDbDataPath(workspaceId, appId, postgrestPath) {
496
+ return `/workspaces/${encodeURIComponent(workspaceId)}/miniapps/${encodeURIComponent(appId)}/db/data${normalizePostgrestPath(postgrestPath)}`;
497
+ }
498
+ function buildMiniappDbSchemaPath(workspaceId, appId) {
499
+ return `/workspaces/${encodeURIComponent(workspaceId)}/miniapps/${encodeURIComponent(appId)}/db/schema`;
500
+ }
501
+ function parseJsonBody(raw) {
502
+ let parsed;
503
+ try {
504
+ parsed = JSON.parse(raw);
505
+ } catch (error) {
506
+ const detail = error instanceof Error ? error.message : String(error);
507
+ throw new MiniappDbOptionsError(`Error: --body must be valid JSON. ${detail}`);
508
+ }
509
+ if (parsed === null || typeof parsed !== "object" && !Array.isArray(parsed)) {
510
+ throw new MiniappDbOptionsError("Error: --body must be a JSON object or array.");
511
+ }
512
+ return parsed;
513
+ }
514
+ function hasPostgrestFilter(postgrestPath) {
515
+ const normalizedPath = normalizePostgrestPath(postgrestPath);
516
+ const parsed = new URL(normalizedPath, "https://postgrest.local");
517
+ for (const [name] of parsed.searchParams.entries()) {
518
+ if (!NON_FILTER_QUERY_PARAMS.has(name.toLowerCase())) {
519
+ return true;
520
+ }
521
+ }
522
+ return false;
523
+ }
524
+ function assertPostgrestFilter(postgrestPath, method) {
525
+ if (!hasPostgrestFilter(postgrestPath)) {
526
+ throw new MiniappDbOptionsError(
527
+ `Error: ${method.toLowerCase()} requires at least one PostgREST filter query parameter.`
528
+ );
529
+ }
530
+ }
531
+ function formatRawResponse(text, pretty) {
532
+ if (!pretty || !text) {
533
+ return text;
534
+ }
535
+ try {
536
+ return JSON.stringify(JSON.parse(text), null, 2);
537
+ } catch {
538
+ return text;
539
+ }
540
+ }
541
+ function isAllowedMiniappDbUserEmail(email) {
542
+ const normalized = email.trim().toLowerCase();
543
+ return ALLOWED_MINIAPP_DB_EMAIL_DOMAINS.some((domain) => normalized.endsWith(domain));
544
+ }
545
+
546
+ // src/commands/miniapp.ts
547
+ function runOrExit2(fn) {
548
+ try {
549
+ return fn();
550
+ } catch (err) {
551
+ if (err instanceof MiniappDbOptionsError) {
552
+ printError(err.message);
553
+ process.exit(1);
554
+ }
555
+ throw err;
556
+ }
557
+ }
558
+ function addMiniappDbTargetOptions(command) {
559
+ return command.requiredOption("-w, --workspace <workspaceId>", "Workspace ID").requiredOption("--app-id <appId>", "Miniapp app ID");
560
+ }
561
+ function handleRawResponse(response, pretty) {
562
+ if (!response.ok) {
563
+ printError(`Error [${response.status}]: ${response.text}`);
564
+ process.exit(1);
565
+ }
566
+ print(formatRawResponse(response.text, pretty));
567
+ }
568
+ async function ensureAllowedMiniappDbUser() {
569
+ const response = await httpGet("/users/whoami");
570
+ if (!response.ok) {
571
+ printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
572
+ process.exit(1);
573
+ }
574
+ if (!isAllowedMiniappDbUserEmail(response.data.email)) {
575
+ printError("Error: miniapp db commands are only available to @paraflow.com, @moxt.ai, or @kanyun.com users.");
576
+ process.exit(1);
577
+ }
578
+ }
579
+ async function requestDataApi(method, postgrestPath, options, body) {
580
+ await ensureAllowedMiniappDbUser();
581
+ const path2 = buildMiniappDbDataPath(options.workspace, options.appId, postgrestPath);
582
+ const response = await httpRaw(method, path2, body);
583
+ handleRawResponse(response, options.pretty);
584
+ }
585
+ function registerMiniappCommand(program2) {
586
+ const miniapp = program2.command("miniapp", { hidden: true }).description("Miniapp operations");
587
+ const db = miniapp.command("db").description("Miniapp database operations");
588
+ addMiniappDbTargetOptions(
589
+ db.command("schema").description("Print the miniapp database schema SQL")
590
+ ).action(async (options) => {
591
+ await ensureAllowedMiniappDbUser();
592
+ const response = await httpGet(buildMiniappDbSchemaPath(options.workspace, options.appId));
593
+ if (!response.ok) {
594
+ printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
595
+ process.exit(1);
596
+ }
597
+ print(response.data.sql);
598
+ });
599
+ addMiniappDbTargetOptions(
600
+ db.command("get").description("Read miniapp data through PostgREST").argument("<path>", "PostgREST path, for example /todos?select=*").option("--pretty", "Pretty-print JSON responses")
601
+ ).action(async (postgrestPath, options) => {
602
+ await requestDataApi("GET", postgrestPath, options);
603
+ });
604
+ addMiniappDbTargetOptions(
605
+ db.command("post").description("Create miniapp data through PostgREST").argument("<path>", "PostgREST path, for example /todos").requiredOption("--body <json>", "JSON object or array request body").option("--pretty", "Pretty-print JSON responses")
606
+ ).action(async (postgrestPath, options) => {
607
+ const body = runOrExit2(() => parseJsonBody(options.body ?? ""));
608
+ await requestDataApi("POST", postgrestPath, options, body);
609
+ });
610
+ addMiniappDbTargetOptions(
611
+ db.command("patch").description("Update miniapp data through PostgREST").argument("<path>", "PostgREST path with a filter, for example /todos?id=eq.1").requiredOption("--body <json>", "JSON object or array request body").option("--pretty", "Pretty-print JSON responses")
612
+ ).action(async (postgrestPath, options) => {
613
+ runOrExit2(() => assertPostgrestFilter(postgrestPath, "PATCH"));
614
+ const body = runOrExit2(() => parseJsonBody(options.body ?? ""));
615
+ await requestDataApi("PATCH", postgrestPath, options, body);
616
+ });
617
+ addMiniappDbTargetOptions(
618
+ db.command("delete").description("Delete miniapp data through PostgREST").argument("<path>", "PostgREST path with a filter, for example /todos?id=eq.1").option("--yes", "Confirm the delete operation").option("--pretty", "Pretty-print JSON responses")
619
+ ).action(async (postgrestPath, options) => {
620
+ if (options.yes !== true) {
621
+ printError("Error: delete requires --yes.");
622
+ process.exit(1);
623
+ }
624
+ runOrExit2(() => assertPostgrestFilter(postgrestPath, "DELETE"));
625
+ await requestDataApi("DELETE", postgrestPath, options);
626
+ });
627
+ }
628
+
629
+ // src/telemetry/config.ts
630
+ import * as fs2 from "fs";
631
+ import * as os from "os";
632
+ import * as path from "path";
633
+ function getConfigPath() {
634
+ return path.join(os.homedir(), ".moxt", "config.json");
635
+ }
636
+ function readTelemetryConfig() {
637
+ try {
638
+ const raw = fs2.readFileSync(getConfigPath(), "utf8");
639
+ const parsed = JSON.parse(raw);
640
+ return parsed.telemetry ?? {};
641
+ } catch {
642
+ return {};
643
+ }
644
+ }
645
+ function writeTelemetryConfig(update) {
646
+ const configPath = getConfigPath();
647
+ let existing = {};
648
+ try {
649
+ existing = JSON.parse(fs2.readFileSync(configPath, "utf8"));
650
+ } catch {
651
+ existing = {};
652
+ }
653
+ const currentTelemetry = existing.telemetry ?? {};
654
+ const next = { ...existing, telemetry: { ...currentTelemetry, ...update } };
655
+ fs2.mkdirSync(path.dirname(configPath), { recursive: true });
656
+ fs2.writeFileSync(configPath, JSON.stringify(next, null, 2));
657
+ }
658
+
659
+ // src/telemetry/opt-out.ts
660
+ function isCiEnvironment() {
661
+ return process.env.CI === "true" || process.env.CI === "1";
662
+ }
663
+ function isTelemetryDisabled() {
664
+ if (process.env.MOXT_TELEMETRY_DISABLED === "1" || process.env.MOXT_TELEMETRY_DISABLED === "true") {
665
+ return true;
666
+ }
667
+ if (process.env.DO_NOT_TRACK === "1" || process.env.DO_NOT_TRACK === "true") {
668
+ return true;
669
+ }
670
+ return readTelemetryConfig().disabled === true;
671
+ }
672
+
673
+ // src/commands/telemetry.ts
674
+ function registerTelemetryCommand(program2) {
675
+ const telemetry = program2.command("telemetry").description("Manage Moxt CLI telemetry");
676
+ telemetry.command("status").description("Show telemetry status").action(() => {
677
+ const cfg = readTelemetryConfig();
678
+ const envOverride = process.env.MOXT_TELEMETRY_DISABLED === "1" || process.env.MOXT_TELEMETRY_DISABLED === "true" || process.env.DO_NOT_TRACK === "1" || process.env.DO_NOT_TRACK === "true";
679
+ const state = isTelemetryDisabled() ? "disabled" : "enabled";
680
+ print(`telemetry: ${state}`);
681
+ if (envOverride) {
682
+ print("(disabled via environment variable)");
683
+ } else if (cfg.disabled) {
684
+ print("(disabled via config file)");
685
+ }
686
+ });
687
+ telemetry.command("enable").description("Enable telemetry").action(() => {
688
+ writeTelemetryConfig({ disabled: false });
689
+ print("telemetry: enabled");
690
+ });
691
+ telemetry.command("disable").description("Disable telemetry").action(() => {
692
+ writeTelemetryConfig({ disabled: true });
693
+ print("telemetry: disabled");
694
+ });
695
+ }
696
+
461
697
  // src/commands/whoami.ts
462
698
  function registerWhoamiCommand(program2) {
463
699
  program2.command("whoami").description("Show current user information").action(async () => {
@@ -587,19 +823,218 @@ function registerWorkspaceCommand(program2) {
587
823
  });
588
824
  }
589
825
 
826
+ // src/telemetry/client.ts
827
+ import { arch as arch2, platform as platform2 } from "os";
828
+ var buffer = [];
829
+ var FLUSH_TIMEOUT_MS = 3e3;
830
+ var MAX_BATCH_SIZE = 100;
831
+ function commonLabels() {
832
+ return {
833
+ cli_version: "0.3.1",
834
+ node_version: process.versions.node,
835
+ os: platform2(),
836
+ arch: arch2(),
837
+ is_ci: isCiEnvironment() ? "true" : "false"
838
+ };
839
+ }
840
+ function record(metric) {
841
+ if (isTelemetryDisabled()) {
842
+ debugLog(`record: disabled, dropping ${metric.metric_id}`);
843
+ return;
844
+ }
845
+ if (!getApiKeyOrUndefined()) {
846
+ debugLog(`record: no API key, dropping ${metric.metric_id}`);
847
+ return;
848
+ }
849
+ buffer.push({
850
+ ...metric,
851
+ extra_label_name_2_value: {
852
+ ...commonLabels(),
853
+ ...metric.extra_label_name_2_value ?? {}
854
+ }
855
+ });
856
+ debugLog(`record: buffered ${metric.metric_id} (buffer=${buffer.length})`);
857
+ }
858
+ function isDebug() {
859
+ return process.env.MOXT_TELEMETRY_DEBUG === "1" || process.env.MOXT_TELEMETRY_DEBUG === "true";
860
+ }
861
+ function debugLog(msg, detail) {
862
+ if (!isDebug()) return;
863
+ process.stderr.write(`[telemetry] ${msg}${detail !== void 0 ? ` ${JSON.stringify(detail)}` : ""}
864
+ `);
865
+ }
866
+ async function flush() {
867
+ if (buffer.length === 0) {
868
+ debugLog("flush: buffer empty, skipping");
869
+ return;
870
+ }
871
+ const apiKey = getApiKeyOrUndefined();
872
+ if (!apiKey) {
873
+ debugLog("flush: no API key, dropping buffer");
874
+ buffer.length = 0;
875
+ return;
876
+ }
877
+ const batch = buffer.splice(0, MAX_BATCH_SIZE);
878
+ const payload = {
879
+ release_id: "0.3.1",
880
+ client_type: "cli",
881
+ metric_data_list: batch.map((m) => ({
882
+ profile: "cli",
883
+ metric_id: m.metric_id,
884
+ metric_type: m.metric_type,
885
+ value: m.value,
886
+ extra_label_name_2_value: m.extra_label_name_2_value
887
+ }))
888
+ };
889
+ const url = `${getApiBaseUrl()}/cli-metrics`;
890
+ debugLog(`flush: POST ${url} with ${batch.length} metrics`, payload);
891
+ try {
892
+ const controller = new AbortController();
893
+ const timeout = setTimeout(() => {
894
+ controller.abort();
895
+ }, FLUSH_TIMEOUT_MS);
896
+ try {
897
+ const res = await fetch(url, {
898
+ method: "POST",
899
+ headers: {
900
+ "Content-Type": "application/json",
901
+ Authorization: `Bearer ${apiKey}`
902
+ },
903
+ body: JSON.stringify(payload),
904
+ signal: controller.signal
905
+ });
906
+ debugLog(`flush: response status=${res.status}`);
907
+ } finally {
908
+ clearTimeout(timeout);
909
+ }
910
+ } catch (err) {
911
+ debugLog("flush: failed", err instanceof Error ? err.message : String(err));
912
+ }
913
+ }
914
+
915
+ // src/telemetry/notice.ts
916
+ var NOTICE = [
917
+ "",
918
+ "Attention: Moxt CLI now collects anonymous telemetry regarding usage.",
919
+ "This information is used to shape Moxt CLI's roadmap and prioritize features.",
920
+ "",
921
+ "You may opt out by setting MOXT_TELEMETRY_DISABLED=1 in your env",
922
+ "or by running `moxt telemetry disable`.",
923
+ "Details: https://www.npmjs.com/package/@moxt-ai/cli#telemetry",
924
+ ""
925
+ ];
926
+ function maybeShowTelemetryNotice() {
927
+ if (isTelemetryDisabled()) return;
928
+ if (isCiEnvironment()) return;
929
+ if (readTelemetryConfig().noticeShown) return;
930
+ for (const line of NOTICE) {
931
+ process.stderr.write(`${line}
932
+ `);
933
+ }
934
+ try {
935
+ writeTelemetryConfig({ noticeShown: true });
936
+ } catch {
937
+ }
938
+ }
939
+
940
+ // src/telemetry/instrument.ts
941
+ var current = null;
942
+ function commandPath(cmd) {
943
+ const names = [];
944
+ let node = cmd;
945
+ while (node && node.parent) {
946
+ names.unshift(node.name());
947
+ node = node.parent;
948
+ }
949
+ if (names.length === 0) return { command: "unknown" };
950
+ if (names.length === 1) return { command: names[0] };
951
+ return { command: names[0], subcommand: names.slice(1).join(" ") };
952
+ }
953
+ function instrumentProgram(program2) {
954
+ program2.hook("preAction", (_thisCommand, actionCommand) => {
955
+ const { command, subcommand } = commandPath(actionCommand);
956
+ if (command !== "telemetry") {
957
+ maybeShowTelemetryNotice();
958
+ }
959
+ current = { name: command, subcommand, startedAt: Date.now() };
960
+ record({
961
+ metric_id: "client.cli.command_invocation.count",
962
+ metric_type: "counter",
963
+ value: 1,
964
+ extra_label_name_2_value: {
965
+ command,
966
+ ...subcommand ? { subcommand } : {},
967
+ status: "started"
968
+ }
969
+ });
970
+ });
971
+ program2.hook("postAction", async () => {
972
+ await reportOutcome("success");
973
+ });
974
+ }
975
+ async function reportOutcome(status, errorCode) {
976
+ if (!current) return;
977
+ const { name, subcommand, startedAt } = current;
978
+ const durationSeconds = (Date.now() - startedAt) / 1e3;
979
+ record({
980
+ metric_id: "client.cli.command_duration_seconds",
981
+ metric_type: "histogram",
982
+ value: durationSeconds,
983
+ extra_label_name_2_value: {
984
+ command: name,
985
+ ...subcommand ? { subcommand } : {},
986
+ status
987
+ }
988
+ });
989
+ if (status === "error") {
990
+ record({
991
+ metric_id: "client.cli.command_error.count",
992
+ metric_type: "counter",
993
+ value: 1,
994
+ extra_label_name_2_value: {
995
+ command: name,
996
+ ...subcommand ? { subcommand } : {},
997
+ ...errorCode ? { error_code: errorCode } : {}
998
+ }
999
+ });
1000
+ }
1001
+ current = null;
1002
+ await flush();
1003
+ }
1004
+ function installExitHandler() {
1005
+ const handleError = (errorCode) => {
1006
+ void reportOutcome("error", errorCode);
1007
+ };
1008
+ process.on("uncaughtException", () => {
1009
+ handleError("uncaught_exception");
1010
+ process.exit(1);
1011
+ });
1012
+ process.on("unhandledRejection", () => {
1013
+ handleError("unhandled_rejection");
1014
+ process.exit(1);
1015
+ });
1016
+ }
1017
+
590
1018
  // src/index.ts
591
1019
  updateNotifier({
592
- pkg: { name: "@moxt-ai/cli", version: "0.2.1" }
1020
+ pkg: { name: "@moxt-ai/cli", version: "0.3.1" }
593
1021
  }).notify();
594
1022
  var program = new Command();
595
- program.name("moxt").description("Moxt CLI - AI Workspace").version("0.2.1").action(() => {
1023
+ program.name("moxt").description("Moxt CLI - AI Workspace").version("0.3.1").action(() => {
596
1024
  program.help();
597
1025
  });
1026
+ instrumentProgram(program);
1027
+ installExitHandler();
598
1028
  registerWhoamiCommand(program);
599
1029
  registerWorkspaceCommand(program);
600
1030
  registerFileCommand(program);
601
- program.parseAsync(process.argv).catch((err) => {
1031
+ registerMiniappCommand(program);
1032
+ registerTelemetryCommand(program);
1033
+ program.parseAsync(process.argv).then(async () => {
1034
+ await flush();
1035
+ }).catch(async (err) => {
602
1036
  console.error("CLI Error:", err);
1037
+ await flush();
603
1038
  process.exit(1);
604
1039
  });
605
1040
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/commands/file.ts","../src/utils/file-selector.ts","../src/utils/http.ts","../src/utils/config.ts","../src/utils/output.ts","../src/utils/spinner.ts","../src/commands/whoami.ts","../src/commands/workspace.ts"],"sourcesContent":["import { Command } from 'commander'\nimport updateNotifier from 'update-notifier'\nimport { registerFileCommand } from './commands/file.js'\nimport { registerWhoamiCommand } from './commands/whoami.js'\nimport { registerWorkspaceCommand } from './commands/workspace.js'\n\ndeclare const __CLI_VERSION__: string\n\nupdateNotifier({\n pkg: { name: '@moxt-ai/cli', version: __CLI_VERSION__ },\n}).notify()\n\nconst program = new Command()\n\nprogram\n .name('moxt')\n .description('Moxt CLI - AI Workspace')\n .version(__CLI_VERSION__)\n .action(() => {\n program.help()\n })\n\nregisterWhoamiCommand(program)\nregisterWorkspaceCommand(program)\nregisterFileCommand(program)\n\nprogram.parseAsync(process.argv).catch((err: unknown) => {\n console.error('CLI Error:', err)\n process.exit(1)\n})\n","import * as fs from 'node:fs'\nimport { Command } from 'commander'\nimport {\n buildFileQueryString,\n isBinaryContent,\n resolveReadMode,\n resolveSpaceSelector,\n resolveWriteMode,\n SpaceOptions,\n SpaceOptionsError,\n} from '../utils/file-selector.js'\nimport { httpDelete, httpGet, httpPost, httpPut } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\n/**\n * Call a pure resolver that may throw SpaceOptionsError; on error, print the\n * message and exit(1). This keeps the CLI's user-facing contract (stderr +\n * exit code 1) identical to the previous inlined implementation, while the\n * resolver itself stays pure and unit-testable.\n */\nfunction runOrExit<T>(fn: () => T): T {\n try {\n return fn()\n } catch (err) {\n if (err instanceof SpaceOptionsError) {\n printError(err.message)\n process.exit(1)\n }\n throw err\n }\n}\n\ninterface FileEntry {\n name: string\n type: 'file' | 'directory'\n size: number | null\n}\n\ninterface FileReadResponse {\n path: string\n type: 'file' | 'directory'\n entries: FileEntry[] | null\n content: string | null\n}\n\ninterface FileWriteResponse {\n path: string\n created: boolean\n}\n\ninterface MkdirResponse {\n path: string\n created: boolean\n}\n\ninterface DeleteResponse {\n path: string\n}\n\ninterface FileUrlResponse {\n path: string\n url: string\n}\n\nfunction addSpaceOptions(cmd: Command): Command {\n return cmd\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('-s, --space <name>', 'Space name (personal or teamspace name)')\n .option('--personal', 'Use personal space (default)')\n .option('--team-space-id <teamSpaceId>', 'Team space ID')\n .option('--teammate-id <teammateId>', 'Teammate ID (teammate space)')\n}\n\nexport function registerFileCommand(program: Command): void {\n const file = program.command('file').description('File operations')\n\n addSpaceOptions(\n file.command('get-url')\n .description('Resolve the shareable browser URL for a file')\n .requiredOption('-p, --path <path>', 'File path'),\n ).action(async (options: SpaceOptions & { path: string }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n const qs = buildFileQueryString(options.path, spaceParams)\n\n startSpinner('Resolving URL...')\n const response = await httpGet<FileUrlResponse>(\n `/workspaces/${options.workspace}/files/url${qs}`,\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ ${options.path} does not exist${colors.reset}`)\n } else if (response.status === 400) {\n printError(`Error: ${JSON.stringify(response.data)}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n stopSpinner(true, response.data.path)\n print(`${colors.cyan}${response.data.url}${colors.reset}`)\n })\n\n addSpaceOptions(\n file.command('list')\n .description('List directory contents')\n .option('-p, --path <path>', 'Directory path', '/'),\n ).action(async (options: SpaceOptions & { path: string }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n const qs = buildFileQueryString(options.path, spaceParams)\n\n startSpinner('Listing files...')\n const response = await httpGet<FileReadResponse>(\n `/workspaces/${options.workspace}/files/list${qs}`,\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ ${options.path} does not exist${colors.reset}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const { path, entries } = response.data\n\n if (!entries || entries.length === 0) {\n stopSpinner(true, `${path}: empty directory`)\n return\n }\n\n stopSpinner(true, path)\n for (const entry of entries) {\n if (entry.type === 'directory') {\n print(`${colors.blue}${entry.name}/${colors.reset}`)\n } else {\n print(entry.name)\n }\n }\n })\n\n file.command('read')\n .description('Read file content')\n .option('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('-s, --space <name>', 'Space name (personal or teamspace name)')\n .option('--personal', 'Use personal space (default)')\n .option('--team-space-id <teamSpaceId>', 'Team space ID')\n .option('--teammate-id <teammateId>', 'Teammate ID (teammate space)')\n .option('-p, --path <path>', 'File path')\n .option('-u, --url <url>', 'Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})')\n .action(async (options: Partial<SpaceOptions> & { path?: string; url?: string }) => {\n const mode = runOrExit(() => resolveReadMode(options))\n\n startSpinner('Reading file...')\n\n let response: { ok: boolean; status: number; data: FileReadResponse }\n let displayPath: string\n\n if (mode.kind === 'by-url') {\n displayPath = mode.url\n response = await httpGet<FileReadResponse>(\n `/files/read-by-url?url=${encodeURIComponent(mode.url)}`,\n )\n } else {\n displayPath = mode.path\n const spaceParams = runOrExit(() => resolveSpaceSelector(options as SpaceOptions))\n const qs = buildFileQueryString(mode.path, spaceParams)\n response = await httpGet<FileReadResponse>(\n `/workspaces/${mode.workspace}/files/read${qs}`,\n )\n }\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ ${displayPath} does not exist${colors.reset}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const { type, content } = response.data\n\n if (type === 'directory') {\n stopSpinner(false, 'Failed')\n print(`${colors.red}☠ ${displayPath} is a directory${colors.reset}`)\n process.exit(1)\n }\n\n stopSpinner(true, 'Done')\n print(content ?? '')\n })\n\n file.command('put')\n .description('Upload a file')\n .option('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('-s, --space <name>', 'Space name (personal or teamspace name)')\n .option('--personal', 'Use personal space (default)')\n .option('--team-space-id <teamSpaceId>', 'Team space ID')\n .option('--teammate-id <teammateId>', 'Teammate ID (teammate space)')\n .option('-p, --path <path>', 'Remote file path')\n .option('-u, --url <url>', 'Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})')\n .requiredOption('-l, --local-path <localPath>', 'Local file path')\n .option('-r, --recursive', 'Create parent directories if needed')\n .action(\n async (options: Partial<SpaceOptions> & {\n path?: string\n url?: string\n localPath: string\n recursive?: boolean\n }) => {\n const mode = runOrExit(() => resolveWriteMode(options))\n\n // check local file exists\n if (!fs.existsSync(options.localPath)) {\n print(`${colors.red}☠ Local file not found: ${options.localPath}${colors.reset}`)\n process.exit(1)\n }\n\n // check it is a file, not a directory\n const stats = fs.statSync(options.localPath)\n if (!stats.isFile()) {\n print(`${colors.red}☠ Not a file: ${options.localPath}${colors.reset}`)\n process.exit(1)\n }\n\n // check file size (10MB limit)\n const maxSize = 10 * 1024 * 1024\n if (stats.size > maxSize) {\n print(`${colors.red}☠ File too large (max 10MB): ${options.localPath}${colors.reset}`)\n process.exit(1)\n }\n\n // read file and check for binary content\n const buffer = fs.readFileSync(options.localPath)\n if (isBinaryContent(buffer)) {\n print(`${colors.red}☠ Binary files are not allowed. Only text files can be uploaded.${colors.reset}`)\n process.exit(1)\n }\n\n const content = buffer.toString('utf8')\n\n startSpinner('Uploading...')\n\n let response: { ok: boolean; status: number; data: FileWriteResponse }\n let displayPath: string\n\n if (mode.kind === 'by-url') {\n displayPath = mode.url\n response = await httpPut<FileWriteResponse>('/files/write-by-url', {\n url: mode.url,\n content,\n })\n } else {\n displayPath = mode.path\n const spaceParams = runOrExit(() => resolveSpaceSelector(options as SpaceOptions))\n response = await httpPut<FileWriteResponse>(\n `/workspaces/${mode.workspace}/files/write`,\n {\n path: mode.path,\n content,\n recursive: options.recursive ?? false,\n ...spaceParams,\n },\n )\n }\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n if (mode.kind === 'by-url') {\n print(`${colors.red}☠ ${displayPath} does not exist${colors.reset}`)\n } else {\n print(`${colors.red}☠ Parent directory does not exist${colors.reset}`)\n }\n } else if (response.status === 400) {\n printError(`Error: ${JSON.stringify(response.data)}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const action = response.data.created ? 'Created' : 'Updated'\n stopSpinner(true, `${action}: ${response.data.path}`)\n },\n )\n\n addSpaceOptions(\n file.command('mkdir')\n .description('Create a directory')\n .requiredOption('-p, --path <path>', 'Directory path')\n .option('-r, --recursive', 'Create parent directories if needed'),\n ).action(\n async (options: SpaceOptions & {\n path: string\n recursive?: boolean\n }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n\n startSpinner('Creating directory...')\n const response = await httpPost<MkdirResponse>(\n `/workspaces/${options.workspace}/files/mkdir`,\n {\n path: options.path,\n recursive: options.recursive ?? false,\n ...spaceParams,\n },\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ Parent directory does not exist${colors.reset}`)\n } else if (response.status === 400) {\n printError(`Error: ${JSON.stringify(response.data)}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const action = response.data.created ? 'Created' : 'Already exists'\n stopSpinner(true, `${action}: ${response.data.path}`)\n },\n )\n\n addSpaceOptions(\n file.command('del')\n .description('Delete a file or empty directory')\n .requiredOption('-p, --path <path>', 'File or directory path'),\n ).action(\n async (options: SpaceOptions & {\n path: string\n }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n\n startSpinner('Deleting...')\n const response = await httpDelete<DeleteResponse>(\n `/workspaces/${options.workspace}/files/delete`,\n {\n path: options.path,\n ...spaceParams,\n },\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ Path not found: ${options.path}${colors.reset}`)\n } else if (response.status === 400) {\n print(`${colors.red}☠ Cannot delete non-empty directory${colors.reset}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n stopSpinner(true, `Deleted: ${response.data.path}`)\n },\n )\n}\n","/**\n * Pure logic for resolving file-command space selectors and building request URLs.\n *\n * These functions are extracted from commands/file.ts so they can be unit tested\n * without spawning the CLI or mocking process.exit. All error conditions are\n * surfaced as thrown Errors; action handlers are responsible for turning them\n * into user-facing output and exit codes.\n */\n\nexport interface SpaceOptions {\n workspace: string\n space?: string\n personal?: boolean\n teamSpaceId?: string\n teammateId?: string\n}\n\nexport interface SpaceParams {\n space?: string\n teamSpaceId?: string\n agentId?: number\n}\n\n/**\n * Error thrown when selector options violate a contract (mutually exclusive,\n * wrong format, etc). Action handlers catch this and print the message before\n * exiting with code 1.\n */\nexport class SpaceOptionsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SpaceOptionsError'\n }\n}\n\n/**\n * Resolve mutually-exclusive space selector flags into normalized request params.\n *\n * Priority (only one must be set): --team-space-id > --teammate-id > --personal > -s <name>.\n * When none is set, returns empty params (server treats this as personal space).\n */\nexport function resolveSpaceSelector(options: SpaceOptions): SpaceParams {\n // Destructure first so TypeScript's control-flow analysis can narrow each\n // field through the subsequent non-null / non-empty checks without having\n // to re-read options.* at the point of use (which would lose narrowing).\n const { space, teamSpaceId, teammateId } = options\n const personalIsSet = options.personal === true\n\n // Count \"user-set\" selectors explicitly so the mutual-exclusion check\n // reflects intent (\"which flags did the user pass?\") rather than a\n // generic truthiness filter. This keeps the mutual-exclusion check\n // cleanly separated from the downstream format validation (e.g.\n // `parsed <= 0` for teammateId).\n const spaceIsSet = space != null && space !== ''\n const teamSpaceIdIsSet = teamSpaceId != null && teamSpaceId !== ''\n const teammateIdIsSet = teammateId != null && teammateId !== ''\n const selectorCount =\n (spaceIsSet ? 1 : 0) + (personalIsSet ? 1 : 0) + (teamSpaceIdIsSet ? 1 : 0) + (teammateIdIsSet ? 1 : 0)\n if (selectorCount > 1) {\n throw new SpaceOptionsError(\n 'Error: -s, --personal, --team-space-id, and --teammate-id are mutually exclusive.',\n )\n }\n\n // Dispatch via the underlying field checks (not `*IsSet`) so TypeScript\n // narrows each local to `string`, letting us return without `!`.\n if (teamSpaceId != null && teamSpaceId !== '') {\n return { teamSpaceId }\n }\n if (teammateId != null && teammateId !== '') {\n const parsed = Number.parseInt(teammateId, 10)\n if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== teammateId) {\n throw new SpaceOptionsError(\n `Error: --teammate-id must be a positive integer, got \"${teammateId}\".`,\n )\n }\n return { agentId: parsed }\n }\n if (personalIsSet) {\n return { space: 'personal' }\n }\n if (space != null && space !== '') {\n return { space }\n }\n return {}\n}\n\n/**\n * Build the `?path=...&space=...` query string for file endpoints.\n * Returns empty string when no params are set (caller should not append `?`).\n * Values are URL-encoded via URLSearchParams.\n *\n * An empty-string `path` is treated as \"not provided\" and omitted from the query;\n * callers should pass `undefined` rather than `\"\"` when no path is intended.\n */\nexport function buildFileQueryString(path: string | undefined, spaceParams: SpaceParams): string {\n const params = new URLSearchParams()\n if (path != null && path !== '') {\n params.set('path', path)\n }\n if (spaceParams.space) {\n params.set('space', spaceParams.space)\n }\n if (spaceParams.teamSpaceId) {\n params.set('teamSpaceId', spaceParams.teamSpaceId)\n }\n if (spaceParams.agentId != null) {\n params.set('agentId', String(spaceParams.agentId))\n }\n const qs = params.toString()\n return qs ? `?${qs}` : ''\n}\n\n/**\n * Detect if a Buffer contains binary content by sampling the first 8192 bytes.\n * Control characters other than tab (9), LF (10), and CR (13) are treated as binary.\n */\nexport function isBinaryContent(buffer: Buffer): boolean {\n const sampleSize = Math.min(buffer.length, 8192)\n\n for (let i = 0; i < sampleSize; i++) {\n const byte = buffer[i]\n if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Validate `file read` command's top-level mutually-exclusive options (-u vs -w/-p).\n * Returns the resolved mode ('by-url' or 'by-path'). Throws SpaceOptionsError on conflict.\n *\n * Empty strings are treated as \"not provided\" (commander never passes empty strings\n * for optional flags, but callers outside the CLI context should pass undefined instead\n * of \"\" to avoid unexpected branch behaviour).\n */\nexport type ReadMode = { kind: 'by-url'; url: string } | { kind: 'by-path'; workspace: string; path: string }\n\nexport function resolveReadMode(options: {\n url?: string\n workspace?: string\n path?: string\n}): ReadMode {\n if (options.url && options.workspace) {\n throw new SpaceOptionsError('Error: --url cannot be used with --workspace')\n }\n if (options.url && options.path) {\n throw new SpaceOptionsError('Error: --url cannot be used with --path')\n }\n if (!options.url && !options.workspace) {\n throw new SpaceOptionsError('Error: Either --url or --workspace is required')\n }\n if (!options.url && !options.path) {\n throw new SpaceOptionsError('Error: --path is required when not using --url')\n }\n\n if (options.url) {\n return { kind: 'by-url', url: options.url }\n }\n // At this point both workspace and path are guaranteed non-empty by the guards\n // above. Use explicit checks so TypeScript narrows the types without needing `!`.\n if (!options.workspace) {\n throw new SpaceOptionsError('Error: Either --url or --workspace is required')\n }\n if (!options.path) {\n throw new SpaceOptionsError('Error: --path is required when not using --url')\n }\n return { kind: 'by-path', workspace: options.workspace, path: options.path }\n}\n\n/**\n * Validate `file put` command's top-level mutually-exclusive options (-u vs -w/-p).\n *\n * By-URL puts overwrite an existing file (the URL already identifies it), so\n * `--recursive` is meaningless in that mode and is rejected outright to keep the\n * user's intent unambiguous.\n */\nexport type WriteMode =\n | { kind: 'by-url'; url: string }\n | { kind: 'by-path'; workspace: string; path: string }\n\nexport function resolveWriteMode(options: {\n url?: string\n workspace?: string\n path?: string\n recursive?: boolean\n}): WriteMode {\n if (options.url && options.workspace) {\n throw new SpaceOptionsError('Error: --url cannot be used with --workspace')\n }\n if (options.url && options.path) {\n throw new SpaceOptionsError('Error: --url cannot be used with --path')\n }\n if (options.url && options.recursive) {\n throw new SpaceOptionsError('Error: --recursive cannot be used with --url (the file must already exist)')\n }\n if (!options.url && !options.workspace) {\n throw new SpaceOptionsError('Error: Either --url or --workspace is required')\n }\n if (!options.url && !options.path) {\n throw new SpaceOptionsError('Error: --path is required when not using --url')\n }\n\n if (options.url) {\n return { kind: 'by-url', url: options.url }\n }\n return { kind: 'by-path', workspace: options.workspace!, path: options.path! }\n}\n","import { arch, platform } from 'os'\nimport { getApiBaseUrl, getApiKey } from './config.js'\n\ndeclare const __CLI_VERSION__: string\n\nexport interface ApiResponse<T> {\n ok: boolean\n status: number\n data: T\n}\n\nfunction getUserAgent(): string {\n return `moxt-cli/${__CLI_VERSION__} (${platform()}/${arch()}) node/${process.versions.node}`\n}\n\nasync function request<T>(method: string, path: string, body?: unknown): Promise<ApiResponse<T>> {\n const apiKey = getApiKey()\n const url = `${getApiBaseUrl()}${path}`\n\n const response = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n 'User-Agent': getUserAgent(),\n },\n body: body ? JSON.stringify(body) : undefined,\n })\n\n let data: T\n const contentType = response.headers.get('content-type')\n if (contentType?.includes('application/json')) {\n data = (await response.json()) as T\n } else {\n data = (await response.text()) as T\n }\n\n if (response.status === 401) {\n console.error('Authentication failed. Check your MOXT_API_KEY.')\n console.error('Get a new key at: https://moxt.ai')\n process.exit(1)\n }\n\n return {\n ok: response.ok,\n status: response.status,\n data,\n }\n}\n\nexport async function httpGet<T>(path: string): Promise<ApiResponse<T>> {\n return request<T>('GET', path)\n}\n\nexport async function httpPut<T>(path: string, body: unknown): Promise<ApiResponse<T>> {\n return request<T>('PUT', path, body)\n}\n\nexport async function httpPost<T>(path: string, body: unknown): Promise<ApiResponse<T>> {\n return request<T>('POST', path, body)\n}\n\nexport async function httpDelete<T>(path: string, body?: unknown): Promise<ApiResponse<T>> {\n return request<T>('DELETE', path, body)\n}\n","const DEFAULT_HOST = 'api.moxt.ai'\n\nexport function getApiBaseUrl(): string {\n const host = process.env.MOXT_HOST ?? DEFAULT_HOST\n return `https://${host}/openapi/v1`\n}\n\nexport function getApiKey(): string {\n const apiKey = process.env.MOXT_API_KEY\n\n if (!apiKey) {\n console.error('MOXT_API_KEY environment variable is not set.')\n console.error('')\n console.error('Get your API key at: https://moxt.ai')\n console.error('')\n console.error('Then set it:')\n console.error(' export MOXT_API_KEY=moxt_...')\n process.exit(1)\n }\n\n return apiKey\n}\n","// ANSI colors\nexport const colors = {\n bold: '\\x1b[1m',\n blue: '\\x1b[1;34m',\n green: '\\x1b[32m',\n red: '\\x1b[31m',\n cyan: '\\x1b[36m',\n dim: '\\x1b[2m',\n reset: '\\x1b[0m',\n}\n\nexport function print(message: string): void {\n console.log(message)\n}\n\nexport function printError(message: string): void {\n console.error(`${colors.red}${message}${colors.reset}`)\n}\n","const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']\n\nlet intervalId: ReturnType<typeof setInterval> | null = null\nlet frameIndex = 0\n\nexport function startSpinner(message: string): void {\n frameIndex = 0\n process.stdout.write(`${frames[frameIndex]} ${message}`)\n\n intervalId = setInterval(() => {\n frameIndex = (frameIndex + 1) % frames.length\n process.stdout.write(`\\r${frames[frameIndex]} ${message}`)\n }, 80)\n}\n\nexport function stopSpinner(success: boolean, message?: string): void {\n if (intervalId) {\n clearInterval(intervalId)\n intervalId = null\n }\n\n const symbol = success ? '\\x1b[32m✓\\x1b[0m' : '\\x1b[31m✗\\x1b[0m'\n // \\x1b[2K 清除整行,\\r 回到行首\n process.stdout.write(`\\x1b[2K\\r${symbol} ${message ?? ''}\\n`)\n}\n","import { Command } from 'commander'\nimport { httpGet } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\ninterface WhoamiResponse {\n nickname: string\n email: string\n}\n\nexport function registerWhoamiCommand(program: Command): void {\n program\n .command('whoami')\n .description('Show current user information')\n .action(async () => {\n startSpinner('Fetching user info...')\n const response = await httpGet<WhoamiResponse>('/users/whoami')\n\n if (response.ok) {\n stopSpinner(true, 'Done')\n print(`${colors.bold}Nickname${colors.reset}: ${response.data.nickname}`)\n print(`${colors.bold}Email${colors.reset}: ${response.data.email}`)\n } else {\n stopSpinner(false, 'Failed')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n })\n}\n","import { Command } from 'commander'\nimport { httpGet, httpDelete } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\ninterface WorkspaceItem {\n workspaceId: string\n name: string\n}\n\ninterface WorkspaceListResponse {\n workspaces: WorkspaceItem[]\n}\n\ninterface MemberItem {\n userId: number\n email: string\n displayName: string | null\n role: string\n}\n\ninterface MembersResponse {\n members: MemberItem[]\n}\n\ninterface SpaceItem {\n type: 'personal' | 'team' | 'teammate'\n name: string\n teamSpaceId: string | null\n agentId: number | null\n}\n\n// Email regex (same as web/src/utils/email.ts)\nconst emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/\n\nfunction isValidEmail(email: string): boolean {\n return emailRegex.test(email)\n}\n\nexport function registerWorkspaceCommand(program: Command): void {\n const workspace = program.command('workspace').description('Workspace management')\n\n workspace\n .command('list')\n .description('List all workspaces you belong to')\n .action(async () => {\n startSpinner('Fetching workspaces...')\n const response = await httpGet<WorkspaceListResponse>('/workspaces')\n\n if (response.ok) {\n const { workspaces } = response.data\n if (workspaces.length === 0) {\n stopSpinner(true, 'No workspaces found.')\n return\n }\n\n stopSpinner(true, `Found ${workspaces.length} workspace(s)`)\n\n for (const ws of workspaces) {\n print(`${colors.bold}${ws.workspaceId}${colors.reset}\\t${ws.name}`)\n }\n } else {\n stopSpinner(false, 'Failed')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n })\n\n const members = program.command('members').description('Manage workspace members')\n\n members\n .command('list')\n .description('List all members in a workspace')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .action(async (options: { workspace: string }) => {\n const { workspace: workspaceId } = options\n\n startSpinner('Fetching workspace members...')\n const response = await httpGet<MembersResponse>(`/workspaces/${workspaceId}/members`)\n\n if (!response.ok) {\n stopSpinner(false, 'Failed to fetch members')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n const { members } = response.data\n if (members.length === 0) {\n stopSpinner(true, 'No members found.')\n return\n }\n\n stopSpinner(true, `Found ${members.length} member(s)`)\n\n for (const member of members) {\n const name = member.displayName || '-'\n print(`${colors.bold}${member.email}${colors.reset}\\t${name}\\t${member.role}`)\n }\n })\n\n members\n .command('remove')\n .description('Remove members from a workspace')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .argument('<emails>', 'Emails to remove (comma-separated)')\n .action(async (emailsArg: string, options: { workspace: string }) => {\n const { workspace: workspaceId } = options\n\n const emails = emailsArg.split(',').map((e) => e.trim()).filter(Boolean)\n if (emails.length === 0) {\n printError('No valid emails provided')\n process.exit(1)\n }\n\n // Validate email format\n const invalidEmails = emails.filter((e) => !isValidEmail(e))\n if (invalidEmails.length > 0) {\n for (const email of invalidEmails) {\n printError(`Invalid email format: ${email}`)\n }\n process.exit(1)\n }\n\n // Fetch members to get userId by email\n startSpinner('Fetching workspace members...')\n const membersResponse = await httpGet<MembersResponse>(`/workspaces/${workspaceId}/members`)\n\n if (!membersResponse.ok) {\n stopSpinner(false, 'Failed to fetch members')\n printError(`Error [${membersResponse.status}]: ${JSON.stringify(membersResponse.data)}`)\n process.exit(1)\n }\n\n stopSpinner(true, 'Members fetched')\n\n const { members } = membersResponse.data\n const emailToMember = new Map(members.map((m) => [m.email.toLowerCase(), m]))\n\n // Remove each member\n for (const email of emails) {\n const member = emailToMember.get(email.toLowerCase())\n if (!member) {\n print(`${colors.red}✗${colors.reset} ${email} - not found in workspace`)\n continue\n }\n\n const deleteResponse = await httpDelete(`/workspaces/${workspaceId}/members/${member.userId}`)\n\n if (deleteResponse.ok) {\n print(`${colors.green}✓${colors.reset} ${email} - removed`)\n } else {\n print(`${colors.red}✗${colors.reset} ${email} - failed: ${JSON.stringify(deleteResponse.data)}`)\n }\n }\n })\n\n const space = program.command('space').description('Manage spaces')\n\n space\n .command('list')\n .description('List accessible spaces in a workspace')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .action(async (options: { workspace: string }) => {\n const { workspace: workspaceId } = options\n\n startSpinner('Fetching spaces...')\n const response = await httpGet<{ spaces: SpaceItem[] }>(`/workspaces/${workspaceId}/spaces`)\n\n if (!response.ok) {\n stopSpinner(false, 'Failed to fetch spaces')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n const { spaces } = response.data\n if (spaces.length === 0) {\n stopSpinner(true, 'No spaces found.')\n return\n }\n\n stopSpinner(true, `Found ${spaces.length} space(s)`)\n\n print(\n `${colors.bold}TYPE${colors.reset}\\t${colors.bold}TEAM_SPACE_ID${colors.reset}\\t${colors.bold}TEAMMATE_ID${colors.reset}\\t${colors.bold}NAME${colors.reset}`,\n )\n for (const s of spaces) {\n const teamSpaceId = s.teamSpaceId ?? ''\n const teammateId = s.agentId != null ? String(s.agentId) : ''\n print(`${s.type}\\t${teamSpaceId}\\t${teammateId}\\t${s.name}`)\n }\n })\n\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,OAAO,oBAAoB;;;ACD3B,YAAY,QAAQ;;;AC4Bb,IAAM,oBAAN,cAAgC,MAAM;AAAA,EACzC,YAAY,SAAiB;AACzB,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EAChB;AACJ;AAQO,SAAS,qBAAqB,SAAoC;AAIrE,QAAM,EAAE,OAAO,aAAa,WAAW,IAAI;AAC3C,QAAM,gBAAgB,QAAQ,aAAa;AAO3C,QAAM,aAAa,SAAS,QAAQ,UAAU;AAC9C,QAAM,mBAAmB,eAAe,QAAQ,gBAAgB;AAChE,QAAM,kBAAkB,cAAc,QAAQ,eAAe;AAC7D,QAAM,iBACD,aAAa,IAAI,MAAM,gBAAgB,IAAI,MAAM,mBAAmB,IAAI,MAAM,kBAAkB,IAAI;AACzG,MAAI,gBAAgB,GAAG;AACnB,UAAM,IAAI;AAAA,MACN;AAAA,IACJ;AAAA,EACJ;AAIA,MAAI,eAAe,QAAQ,gBAAgB,IAAI;AAC3C,WAAO,EAAE,YAAY;AAAA,EACzB;AACA,MAAI,cAAc,QAAQ,eAAe,IAAI;AACzC,UAAM,SAAS,OAAO,SAAS,YAAY,EAAE;AAC7C,QAAI,CAAC,OAAO,UAAU,MAAM,KAAK,UAAU,KAAK,OAAO,MAAM,MAAM,YAAY;AAC3E,YAAM,IAAI;AA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AACrD,UAAQ,MAAM,cAAc,GAAG;AAC/B,UAAQ,KAAK,CAAC;AAClB,CAAC;","names":["program","program","program","members"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/commands/file.ts","../src/utils/file-selector.ts","../src/utils/http.ts","../src/utils/config.ts","../src/utils/output.ts","../src/utils/spinner.ts","../src/utils/miniapp-db.ts","../src/commands/miniapp.ts","../src/telemetry/config.ts","../src/telemetry/opt-out.ts","../src/commands/telemetry.ts","../src/commands/whoami.ts","../src/commands/workspace.ts","../src/telemetry/client.ts","../src/telemetry/notice.ts","../src/telemetry/instrument.ts"],"sourcesContent":["import { Command } from 'commander'\nimport updateNotifier from 'update-notifier'\nimport { registerFileCommand } from './commands/file.js'\nimport { registerMiniappCommand } from './commands/miniapp.js'\nimport { registerTelemetryCommand } from './commands/telemetry.js'\nimport { registerWhoamiCommand } from './commands/whoami.js'\nimport { registerWorkspaceCommand } from './commands/workspace.js'\nimport { flush } from './telemetry/client.js'\nimport { installExitHandler, instrumentProgram } from './telemetry/instrument.js'\n\ndeclare const __CLI_VERSION__: string\n\nupdateNotifier({\n pkg: { name: '@moxt-ai/cli', version: __CLI_VERSION__ },\n}).notify()\n\nconst program = new Command()\n\nprogram\n .name('moxt')\n .description('Moxt CLI - AI Workspace')\n .version(__CLI_VERSION__)\n .action(() => {\n program.help()\n })\n\ninstrumentProgram(program)\ninstallExitHandler()\n\nregisterWhoamiCommand(program)\nregisterWorkspaceCommand(program)\nregisterFileCommand(program)\nregisterMiniappCommand(program)\nregisterTelemetryCommand(program)\n\nprogram\n .parseAsync(process.argv)\n .then(async () => {\n await flush()\n })\n .catch(async (err: unknown) => {\n console.error('CLI Error:', err)\n await flush()\n process.exit(1)\n })\n","import * as fs from 'node:fs'\nimport { Command } from 'commander'\nimport {\n buildFileQueryString,\n isBinaryContent,\n resolveReadMode,\n resolveSpaceSelector,\n resolveWriteMode,\n SpaceOptions,\n SpaceOptionsError,\n} from '../utils/file-selector.js'\nimport { httpDelete, httpGet, httpPost, httpPut } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\n/**\n * Call a pure resolver that may throw SpaceOptionsError; on error, print the\n * message and exit(1). This keeps the CLI's user-facing contract (stderr +\n * exit code 1) identical to the previous inlined implementation, while the\n * resolver itself stays pure and unit-testable.\n */\nfunction runOrExit<T>(fn: () => T): T {\n try {\n return fn()\n } catch (err) {\n if (err instanceof SpaceOptionsError) {\n printError(err.message)\n process.exit(1)\n }\n throw err\n }\n}\n\ninterface FileEntry {\n name: string\n type: 'file' | 'directory'\n size: number | null\n}\n\ninterface FileReadResponse {\n path: string\n type: 'file' | 'directory'\n entries: FileEntry[] | null\n content: string | null\n}\n\ninterface FileWriteResponse {\n path: string\n created: boolean\n}\n\ninterface MkdirResponse {\n path: string\n created: boolean\n}\n\ninterface DeleteResponse {\n path: string\n}\n\ninterface FileUrlResponse {\n path: string\n url: string\n}\n\nfunction addSpaceOptions(cmd: Command): Command {\n return cmd\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('-s, --space <name>', 'Space name (personal or teamspace name)')\n .option('--personal', 'Use personal space (default)')\n .option('--team-space-id <teamSpaceId>', 'Team space ID')\n .option('--teammate-id <teammateId>', 'Teammate ID (teammate space)')\n}\n\nexport function registerFileCommand(program: Command): void {\n const file = program.command('file').description('File operations')\n\n addSpaceOptions(\n file.command('get-url')\n .description('Resolve the shareable browser URL for a file')\n .requiredOption('-p, --path <path>', 'File path'),\n ).action(async (options: SpaceOptions & { path: string }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n const qs = buildFileQueryString(options.path, spaceParams)\n\n startSpinner('Resolving URL...')\n const response = await httpGet<FileUrlResponse>(\n `/workspaces/${options.workspace}/files/url${qs}`,\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ ${options.path} does not exist${colors.reset}`)\n } else if (response.status === 400) {\n printError(`Error: ${JSON.stringify(response.data)}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n stopSpinner(true, response.data.path)\n print(`${colors.cyan}${response.data.url}${colors.reset}`)\n })\n\n addSpaceOptions(\n file.command('list')\n .description('List directory contents')\n .option('-p, --path <path>', 'Directory path', '/'),\n ).action(async (options: SpaceOptions & { path: string }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n const qs = buildFileQueryString(options.path, spaceParams)\n\n startSpinner('Listing files...')\n const response = await httpGet<FileReadResponse>(\n `/workspaces/${options.workspace}/files/list${qs}`,\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ ${options.path} does not exist${colors.reset}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const { path, entries } = response.data\n\n if (!entries || entries.length === 0) {\n stopSpinner(true, `${path}: empty directory`)\n return\n }\n\n stopSpinner(true, path)\n for (const entry of entries) {\n if (entry.type === 'directory') {\n print(`${colors.blue}${entry.name}/${colors.reset}`)\n } else {\n print(entry.name)\n }\n }\n })\n\n file.command('read')\n .description('Read file content')\n .option('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('-s, --space <name>', 'Space name (personal or teamspace name)')\n .option('--personal', 'Use personal space (default)')\n .option('--team-space-id <teamSpaceId>', 'Team space ID')\n .option('--teammate-id <teammateId>', 'Teammate ID (teammate space)')\n .option('-p, --path <path>', 'File path')\n .option('-u, --url <url>', 'Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})')\n .action(async (options: Partial<SpaceOptions> & { path?: string; url?: string }) => {\n const mode = runOrExit(() => resolveReadMode(options))\n\n startSpinner('Reading file...')\n\n let response: { ok: boolean; status: number; data: FileReadResponse }\n let displayPath: string\n\n if (mode.kind === 'by-url') {\n displayPath = mode.url\n response = await httpGet<FileReadResponse>(\n `/files/read-by-url?url=${encodeURIComponent(mode.url)}`,\n )\n } else {\n displayPath = mode.path\n const spaceParams = runOrExit(() => resolveSpaceSelector(options as SpaceOptions))\n const qs = buildFileQueryString(mode.path, spaceParams)\n response = await httpGet<FileReadResponse>(\n `/workspaces/${mode.workspace}/files/read${qs}`,\n )\n }\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ ${displayPath} does not exist${colors.reset}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const { type, content } = response.data\n\n if (type === 'directory') {\n stopSpinner(false, 'Failed')\n print(`${colors.red}☠ ${displayPath} is a directory${colors.reset}`)\n process.exit(1)\n }\n\n stopSpinner(true, 'Done')\n print(content ?? '')\n })\n\n file.command('put')\n .description('Upload a file')\n .option('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('-s, --space <name>', 'Space name (personal or teamspace name)')\n .option('--personal', 'Use personal space (default)')\n .option('--team-space-id <teamSpaceId>', 'Team space ID')\n .option('--teammate-id <teammateId>', 'Teammate ID (teammate space)')\n .option('-p, --path <path>', 'Remote file path')\n .option('-u, --url <url>', 'Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})')\n .requiredOption('-l, --local-path <localPath>', 'Local file path')\n .option('-r, --recursive', 'Create parent directories if needed')\n .action(\n async (options: Partial<SpaceOptions> & {\n path?: string\n url?: string\n localPath: string\n recursive?: boolean\n }) => {\n const mode = runOrExit(() => resolveWriteMode(options))\n\n // check local file exists\n if (!fs.existsSync(options.localPath)) {\n print(`${colors.red}☠ Local file not found: ${options.localPath}${colors.reset}`)\n process.exit(1)\n }\n\n // check it is a file, not a directory\n const stats = fs.statSync(options.localPath)\n if (!stats.isFile()) {\n print(`${colors.red}☠ Not a file: ${options.localPath}${colors.reset}`)\n process.exit(1)\n }\n\n // check file size (10MB limit)\n const maxSize = 10 * 1024 * 1024\n if (stats.size > maxSize) {\n print(`${colors.red}☠ File too large (max 10MB): ${options.localPath}${colors.reset}`)\n process.exit(1)\n }\n\n // read file and check for binary content\n const buffer = fs.readFileSync(options.localPath)\n if (isBinaryContent(buffer)) {\n print(`${colors.red}☠ Binary files are not allowed. Only text files can be uploaded.${colors.reset}`)\n process.exit(1)\n }\n\n const content = buffer.toString('utf8')\n\n startSpinner('Uploading...')\n\n let response: { ok: boolean; status: number; data: FileWriteResponse }\n let displayPath: string\n\n if (mode.kind === 'by-url') {\n displayPath = mode.url\n response = await httpPut<FileWriteResponse>('/files/write-by-url', {\n url: mode.url,\n content,\n })\n } else {\n displayPath = mode.path\n const spaceParams = runOrExit(() => resolveSpaceSelector(options as SpaceOptions))\n response = await httpPut<FileWriteResponse>(\n `/workspaces/${mode.workspace}/files/write`,\n {\n path: mode.path,\n content,\n recursive: options.recursive ?? false,\n ...spaceParams,\n },\n )\n }\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n if (mode.kind === 'by-url') {\n print(`${colors.red}☠ ${displayPath} does not exist${colors.reset}`)\n } else {\n print(`${colors.red}☠ Parent directory does not exist${colors.reset}`)\n }\n } else if (response.status === 400) {\n printError(`Error: ${JSON.stringify(response.data)}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const action = response.data.created ? 'Created' : 'Updated'\n stopSpinner(true, `${action}: ${response.data.path}`)\n },\n )\n\n addSpaceOptions(\n file.command('mkdir')\n .description('Create a directory')\n .requiredOption('-p, --path <path>', 'Directory path')\n .option('-r, --recursive', 'Create parent directories if needed'),\n ).action(\n async (options: SpaceOptions & {\n path: string\n recursive?: boolean\n }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n\n startSpinner('Creating directory...')\n const response = await httpPost<MkdirResponse>(\n `/workspaces/${options.workspace}/files/mkdir`,\n {\n path: options.path,\n recursive: options.recursive ?? false,\n ...spaceParams,\n },\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ Parent directory does not exist${colors.reset}`)\n } else if (response.status === 400) {\n printError(`Error: ${JSON.stringify(response.data)}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const action = response.data.created ? 'Created' : 'Already exists'\n stopSpinner(true, `${action}: ${response.data.path}`)\n },\n )\n\n addSpaceOptions(\n file.command('del')\n .description('Delete a file or empty directory')\n .requiredOption('-p, --path <path>', 'File or directory path'),\n ).action(\n async (options: SpaceOptions & {\n path: string\n }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n\n startSpinner('Deleting...')\n const response = await httpDelete<DeleteResponse>(\n `/workspaces/${options.workspace}/files/delete`,\n {\n path: options.path,\n ...spaceParams,\n },\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ Path not found: ${options.path}${colors.reset}`)\n } else if (response.status === 400) {\n print(`${colors.red}☠ Cannot delete non-empty directory${colors.reset}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n stopSpinner(true, `Deleted: ${response.data.path}`)\n },\n )\n}\n","/**\n * Pure logic for resolving file-command space selectors and building request URLs.\n *\n * These functions are extracted from commands/file.ts so they can be unit tested\n * without spawning the CLI or mocking process.exit. All error conditions are\n * surfaced as thrown Errors; action handlers are responsible for turning them\n * into user-facing output and exit codes.\n */\n\nexport interface SpaceOptions {\n workspace: string\n space?: string\n personal?: boolean\n teamSpaceId?: string\n teammateId?: string\n}\n\nexport interface SpaceParams {\n space?: string\n teamSpaceId?: string\n agentId?: number\n}\n\n/**\n * Error thrown when selector options violate a contract (mutually exclusive,\n * wrong format, etc). Action handlers catch this and print the message before\n * exiting with code 1.\n */\nexport class SpaceOptionsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SpaceOptionsError'\n }\n}\n\n/**\n * Resolve mutually-exclusive space selector flags into normalized request params.\n *\n * Priority (only one must be set): --team-space-id > --teammate-id > --personal > -s <name>.\n * When none is set, returns empty params (server treats this as personal space).\n */\nexport function resolveSpaceSelector(options: SpaceOptions): SpaceParams {\n // Destructure first so TypeScript's control-flow analysis can narrow each\n // field through the subsequent non-null / non-empty checks without having\n // to re-read options.* at the point of use (which would lose narrowing).\n const { space, teamSpaceId, teammateId } = options\n const personalIsSet = options.personal === true\n\n // Count \"user-set\" selectors explicitly so the mutual-exclusion check\n // reflects intent (\"which flags did the user pass?\") rather than a\n // generic truthiness filter. This keeps the mutual-exclusion check\n // cleanly separated from the downstream format validation (e.g.\n // `parsed <= 0` for teammateId).\n const spaceIsSet = space != null && space !== ''\n const teamSpaceIdIsSet = teamSpaceId != null && teamSpaceId !== ''\n const teammateIdIsSet = teammateId != null && teammateId !== ''\n const selectorCount =\n (spaceIsSet ? 1 : 0) + (personalIsSet ? 1 : 0) + (teamSpaceIdIsSet ? 1 : 0) + (teammateIdIsSet ? 1 : 0)\n if (selectorCount > 1) {\n throw new SpaceOptionsError(\n 'Error: -s, --personal, --team-space-id, and --teammate-id are mutually exclusive.',\n )\n }\n\n // Dispatch via the underlying field checks (not `*IsSet`) so TypeScript\n // narrows each local to `string`, letting us return without `!`.\n if (teamSpaceId != null && teamSpaceId !== '') {\n return { teamSpaceId }\n }\n if (teammateId != null && teammateId !== '') {\n const parsed = Number.parseInt(teammateId, 10)\n if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== teammateId) {\n throw new SpaceOptionsError(\n `Error: --teammate-id must be a positive integer, got \"${teammateId}\".`,\n )\n }\n return { agentId: parsed }\n }\n if (personalIsSet) {\n return { space: 'personal' }\n }\n if (space != null && space !== '') {\n return { space }\n }\n return {}\n}\n\n/**\n * Build the `?path=...&space=...` query string for file endpoints.\n * Returns empty string when no params are set (caller should not append `?`).\n * Values are URL-encoded via URLSearchParams.\n *\n * An empty-string `path` is treated as \"not provided\" and omitted from the query;\n * callers should pass `undefined` rather than `\"\"` when no path is intended.\n */\nexport function buildFileQueryString(path: string | undefined, spaceParams: SpaceParams): string {\n const params = new URLSearchParams()\n if (path != null && path !== '') {\n params.set('path', path)\n }\n if (spaceParams.space) {\n params.set('space', spaceParams.space)\n }\n if (spaceParams.teamSpaceId) {\n params.set('teamSpaceId', spaceParams.teamSpaceId)\n }\n if (spaceParams.agentId != null) {\n params.set('agentId', String(spaceParams.agentId))\n }\n const qs = params.toString()\n return qs ? `?${qs}` : ''\n}\n\n/**\n * Detect if a Buffer contains binary content by sampling the first 8192 bytes.\n * Control characters other than tab (9), LF (10), and CR (13) are treated as binary.\n */\nexport function isBinaryContent(buffer: Buffer): boolean {\n const sampleSize = Math.min(buffer.length, 8192)\n\n for (let i = 0; i < sampleSize; i++) {\n const byte = buffer[i]\n if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Validate `file read` command's top-level mutually-exclusive options (-u vs -w/-p).\n * Returns the resolved mode ('by-url' or 'by-path'). Throws SpaceOptionsError on conflict.\n *\n * Empty strings are treated as \"not provided\" (commander never passes empty strings\n * for optional flags, but callers outside the CLI context should pass undefined instead\n * of \"\" to avoid unexpected branch behaviour).\n */\nexport type ReadMode = { kind: 'by-url'; url: string } | { kind: 'by-path'; workspace: string; path: string }\n\nexport function resolveReadMode(options: {\n url?: string\n workspace?: string\n path?: string\n}): ReadMode {\n if (options.url && options.workspace) {\n throw new SpaceOptionsError('Error: --url cannot be used with --workspace')\n }\n if (options.url && options.path) {\n throw new SpaceOptionsError('Error: --url cannot be used with --path')\n }\n if (!options.url && !options.workspace) {\n throw new SpaceOptionsError('Error: Either --url or --workspace is required')\n }\n if (!options.url && !options.path) {\n throw new SpaceOptionsError('Error: --path is required when not using --url')\n }\n\n if (options.url) {\n return { kind: 'by-url', url: options.url }\n }\n // At this point both workspace and path are guaranteed non-empty by the guards\n // above. Use explicit checks so TypeScript narrows the types without needing `!`.\n if (!options.workspace) {\n throw new SpaceOptionsError('Error: Either --url or --workspace is required')\n }\n if (!options.path) {\n throw new SpaceOptionsError('Error: --path is required when not using --url')\n }\n return { kind: 'by-path', workspace: options.workspace, path: options.path }\n}\n\n/**\n * Validate `file put` command's top-level mutually-exclusive options (-u vs -w/-p).\n *\n * By-URL puts overwrite an existing file (the URL already identifies it), so\n * `--recursive` is meaningless in that mode and is rejected outright to keep the\n * user's intent unambiguous.\n */\nexport type WriteMode =\n | { kind: 'by-url'; url: string }\n | { kind: 'by-path'; workspace: string; path: string }\n\nexport function resolveWriteMode(options: {\n url?: string\n workspace?: string\n path?: string\n recursive?: boolean\n}): WriteMode {\n if (options.url && options.workspace) {\n throw new SpaceOptionsError('Error: --url cannot be used with --workspace')\n }\n if (options.url && options.path) {\n throw new SpaceOptionsError('Error: --url cannot be used with --path')\n }\n if (options.url && options.recursive) {\n throw new SpaceOptionsError('Error: --recursive cannot be used with --url (the file must already exist)')\n }\n if (!options.url && !options.workspace) {\n throw new SpaceOptionsError('Error: Either --url or --workspace is required')\n }\n if (!options.url && !options.path) {\n throw new SpaceOptionsError('Error: --path is required when not using --url')\n }\n\n if (options.url) {\n return { kind: 'by-url', url: options.url }\n }\n return { kind: 'by-path', workspace: options.workspace!, path: options.path! }\n}\n","import { arch, platform } from 'os'\nimport { getApiBaseUrl, getApiKey } from './config.js'\n\ndeclare const __CLI_VERSION__: string\n\nexport interface ApiResponse<T> {\n ok: boolean\n status: number\n data: T\n}\n\nexport interface RawApiResponse {\n ok: boolean\n status: number\n text: string\n contentType: string | null\n}\n\nfunction getUserAgent(): string {\n return `moxt-cli/${__CLI_VERSION__} (${platform()}/${arch()}) node/${process.versions.node}`\n}\n\nasync function fetchApi(method: string, path: string, body?: unknown): Promise<Response> {\n const apiKey = getApiKey()\n const url = `${getApiBaseUrl()}${path}`\n\n const response = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n 'User-Agent': getUserAgent(),\n },\n body: body ? JSON.stringify(body) : undefined,\n })\n\n if (response.status === 401) {\n console.error('Authentication failed. Check your MOXT_API_KEY.')\n console.error('Get a new key at: https://moxt.ai')\n process.exit(1)\n }\n\n return response\n}\n\nasync function request<T>(method: string, path: string, body?: unknown): Promise<ApiResponse<T>> {\n const response = await fetchApi(method, path, body)\n const contentType = response.headers.get('content-type')\n const data = contentType?.includes('application/json') ? ((await response.json()) as T) : ((await response.text()) as T)\n\n return {\n ok: response.ok,\n status: response.status,\n data,\n }\n}\n\nexport async function httpGet<T>(path: string): Promise<ApiResponse<T>> {\n return request<T>('GET', path)\n}\n\nexport async function httpPut<T>(path: string, body: unknown): Promise<ApiResponse<T>> {\n return request<T>('PUT', path, body)\n}\n\nexport async function httpPost<T>(path: string, body: unknown): Promise<ApiResponse<T>> {\n return request<T>('POST', path, body)\n}\n\nexport async function httpDelete<T>(path: string, body?: unknown): Promise<ApiResponse<T>> {\n return request<T>('DELETE', path, body)\n}\n\nexport async function httpRaw(method: 'GET' | 'POST' | 'PATCH' | 'DELETE', path: string, body?: unknown): Promise<RawApiResponse> {\n const response = await fetchApi(method, path, body)\n return {\n ok: response.ok,\n status: response.status,\n text: await response.text(),\n contentType: response.headers.get('content-type'),\n }\n}\n","const DEFAULT_HOST = 'api.moxt.ai'\n\nexport function getApiBaseUrl(): string {\n const host = process.env.MOXT_HOST ?? DEFAULT_HOST\n return `https://${host}/openapi/v1`\n}\n\nexport function getApiKey(): string {\n const apiKey = process.env.MOXT_API_KEY\n\n if (!apiKey) {\n console.error('MOXT_API_KEY environment variable is not set.')\n console.error('')\n console.error('Get your API key at: https://moxt.ai')\n console.error('')\n console.error('Then set it:')\n console.error(' export MOXT_API_KEY=moxt_...')\n process.exit(1)\n }\n\n return apiKey\n}\n\nexport function getApiKeyOrUndefined(): string | undefined {\n return process.env.MOXT_API_KEY\n}\n","// ANSI colors\nexport const colors = {\n bold: '\\x1b[1m',\n blue: '\\x1b[1;34m',\n green: '\\x1b[32m',\n red: '\\x1b[31m',\n cyan: '\\x1b[36m',\n dim: '\\x1b[2m',\n reset: '\\x1b[0m',\n}\n\nexport function print(message: string): void {\n console.log(message)\n}\n\nexport function printError(message: string): void {\n console.error(`${colors.red}${message}${colors.reset}`)\n}\n","const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']\n\nlet intervalId: ReturnType<typeof setInterval> | null = null\nlet frameIndex = 0\n\nexport function startSpinner(message: string): void {\n frameIndex = 0\n process.stdout.write(`${frames[frameIndex]} ${message}`)\n\n intervalId = setInterval(() => {\n frameIndex = (frameIndex + 1) % frames.length\n process.stdout.write(`\\r${frames[frameIndex]} ${message}`)\n }, 80)\n}\n\nexport function stopSpinner(success: boolean, message?: string): void {\n if (intervalId) {\n clearInterval(intervalId)\n intervalId = null\n }\n\n const symbol = success ? '\\x1b[32m✓\\x1b[0m' : '\\x1b[31m✗\\x1b[0m'\n // \\x1b[2K 清除整行,\\r 回到行首\n process.stdout.write(`\\x1b[2K\\r${symbol} ${message ?? ''}\\n`)\n}\n","export class MiniappDbOptionsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'MiniappDbOptionsError'\n }\n}\n\nconst NON_FILTER_QUERY_PARAMS = new Set([\n 'select',\n 'order',\n 'limit',\n 'offset',\n 'range',\n 'range-unit',\n])\n\nconst ALLOWED_MINIAPP_DB_EMAIL_DOMAINS = ['@paraflow.com', '@moxt.ai', '@kanyun.com']\n\nexport function normalizePostgrestPath(path: string): string {\n const trimmed = path.trim()\n if (!trimmed) {\n throw new MiniappDbOptionsError('Error: PostgREST path is required.')\n }\n return trimmed.startsWith('/') ? trimmed : `/${trimmed}`\n}\n\nexport function buildMiniappDbDataPath(workspaceId: string, appId: string, postgrestPath: string): string {\n return `/workspaces/${encodeURIComponent(workspaceId)}/miniapps/${encodeURIComponent(appId)}/db/data${normalizePostgrestPath(postgrestPath)}`\n}\n\nexport function buildMiniappDbSchemaPath(workspaceId: string, appId: string): string {\n return `/workspaces/${encodeURIComponent(workspaceId)}/miniapps/${encodeURIComponent(appId)}/db/schema`\n}\n\nexport function parseJsonBody(raw: string): unknown {\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error)\n throw new MiniappDbOptionsError(`Error: --body must be valid JSON. ${detail}`)\n }\n\n if (parsed === null || (typeof parsed !== 'object' && !Array.isArray(parsed))) {\n throw new MiniappDbOptionsError('Error: --body must be a JSON object or array.')\n }\n return parsed\n}\n\nexport function hasPostgrestFilter(postgrestPath: string): boolean {\n const normalizedPath = normalizePostgrestPath(postgrestPath)\n const parsed = new URL(normalizedPath, 'https://postgrest.local')\n for (const [name] of parsed.searchParams.entries()) {\n if (!NON_FILTER_QUERY_PARAMS.has(name.toLowerCase())) {\n return true\n }\n }\n return false\n}\n\nexport function assertPostgrestFilter(postgrestPath: string, method: 'PATCH' | 'DELETE'): void {\n if (!hasPostgrestFilter(postgrestPath)) {\n throw new MiniappDbOptionsError(\n `Error: ${method.toLowerCase()} requires at least one PostgREST filter query parameter.`,\n )\n }\n}\n\nexport function formatRawResponse(text: string, pretty?: boolean): string {\n if (!pretty || !text) {\n return text\n }\n try {\n return JSON.stringify(JSON.parse(text), null, 2)\n } catch {\n return text\n }\n}\n\nexport function isAllowedMiniappDbUserEmail(email: string): boolean {\n const normalized = email.trim().toLowerCase()\n return ALLOWED_MINIAPP_DB_EMAIL_DOMAINS.some((domain) => normalized.endsWith(domain))\n}\n","import { Command } from 'commander'\nimport {\n assertPostgrestFilter,\n buildMiniappDbDataPath,\n buildMiniappDbSchemaPath,\n formatRawResponse,\n isAllowedMiniappDbUserEmail,\n MiniappDbOptionsError,\n parseJsonBody,\n} from '../utils/miniapp-db.js'\nimport { httpGet, httpRaw } from '../utils/http.js'\nimport { print, printError } from '../utils/output.js'\n\ninterface MiniappDbOptions {\n workspace: string\n appId: string\n pretty?: boolean\n body?: string\n yes?: boolean\n}\n\ninterface MiniappDbSchemaResponse {\n sql: string\n}\n\ninterface WhoamiResponse {\n email: string\n}\n\nfunction runOrExit<T>(fn: () => T): T {\n try {\n return fn()\n } catch (err) {\n if (err instanceof MiniappDbOptionsError) {\n printError(err.message)\n process.exit(1)\n }\n throw err\n }\n}\n\nfunction addMiniappDbTargetOptions(command: Command): Command {\n return command\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .requiredOption('--app-id <appId>', 'Miniapp app ID')\n}\n\nfunction handleRawResponse(response: Awaited<ReturnType<typeof httpRaw>>, pretty?: boolean): void {\n if (!response.ok) {\n printError(`Error [${response.status}]: ${response.text}`)\n process.exit(1)\n }\n print(formatRawResponse(response.text, pretty))\n}\n\nasync function ensureAllowedMiniappDbUser(): Promise<void> {\n const response = await httpGet<WhoamiResponse>('/users/whoami')\n if (!response.ok) {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n if (!isAllowedMiniappDbUserEmail(response.data.email)) {\n printError('Error: miniapp db commands are only available to @paraflow.com, @moxt.ai, or @kanyun.com users.')\n process.exit(1)\n }\n}\n\nasync function requestDataApi(\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n postgrestPath: string,\n options: MiniappDbOptions,\n body?: unknown,\n): Promise<void> {\n await ensureAllowedMiniappDbUser()\n const path = buildMiniappDbDataPath(options.workspace, options.appId, postgrestPath)\n const response = await httpRaw(method, path, body)\n handleRawResponse(response, options.pretty)\n}\n\nexport function registerMiniappCommand(program: Command): void {\n const miniapp = program.command('miniapp', { hidden: true }).description('Miniapp operations')\n const db = miniapp.command('db').description('Miniapp database operations')\n\n addMiniappDbTargetOptions(\n db.command('schema').description('Print the miniapp database schema SQL'),\n ).action(async (options: MiniappDbOptions) => {\n await ensureAllowedMiniappDbUser()\n const response = await httpGet<MiniappDbSchemaResponse>(buildMiniappDbSchemaPath(options.workspace, options.appId))\n\n if (!response.ok) {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n print(response.data.sql)\n })\n\n addMiniappDbTargetOptions(\n db.command('get')\n .description('Read miniapp data through PostgREST')\n .argument('<path>', 'PostgREST path, for example /todos?select=*')\n .option('--pretty', 'Pretty-print JSON responses'),\n ).action(async (postgrestPath: string, options: MiniappDbOptions) => {\n await requestDataApi('GET', postgrestPath, options)\n })\n\n addMiniappDbTargetOptions(\n db.command('post')\n .description('Create miniapp data through PostgREST')\n .argument('<path>', 'PostgREST path, for example /todos')\n .requiredOption('--body <json>', 'JSON object or array request body')\n .option('--pretty', 'Pretty-print JSON responses'),\n ).action(async (postgrestPath: string, options: MiniappDbOptions) => {\n const body = runOrExit(() => parseJsonBody(options.body ?? ''))\n await requestDataApi('POST', postgrestPath, options, body)\n })\n\n addMiniappDbTargetOptions(\n db.command('patch')\n .description('Update miniapp data through PostgREST')\n .argument('<path>', 'PostgREST path with a filter, for example /todos?id=eq.1')\n .requiredOption('--body <json>', 'JSON object or array request body')\n .option('--pretty', 'Pretty-print JSON responses'),\n ).action(async (postgrestPath: string, options: MiniappDbOptions) => {\n runOrExit(() => assertPostgrestFilter(postgrestPath, 'PATCH'))\n const body = runOrExit(() => parseJsonBody(options.body ?? ''))\n await requestDataApi('PATCH', postgrestPath, options, body)\n })\n\n addMiniappDbTargetOptions(\n db.command('delete')\n .description('Delete miniapp data through PostgREST')\n .argument('<path>', 'PostgREST path with a filter, for example /todos?id=eq.1')\n .option('--yes', 'Confirm the delete operation')\n .option('--pretty', 'Pretty-print JSON responses'),\n ).action(async (postgrestPath: string, options: MiniappDbOptions) => {\n if (options.yes !== true) {\n printError('Error: delete requires --yes.')\n process.exit(1)\n }\n runOrExit(() => assertPostgrestFilter(postgrestPath, 'DELETE'))\n await requestDataApi('DELETE', postgrestPath, options)\n })\n}\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\n\nexport interface TelemetryConfig {\n disabled?: boolean\n noticeShown?: boolean\n}\n\nfunction getConfigPath(): string {\n return path.join(os.homedir(), '.moxt', 'config.json')\n}\n\nexport function readTelemetryConfig(): TelemetryConfig {\n try {\n const raw = fs.readFileSync(getConfigPath(), 'utf8')\n const parsed = JSON.parse(raw) as { telemetry?: TelemetryConfig }\n return parsed.telemetry ?? {}\n } catch {\n return {}\n }\n}\n\nexport function writeTelemetryConfig(update: Partial<TelemetryConfig>): void {\n const configPath = getConfigPath()\n let existing: Record<string, unknown> = {}\n try {\n existing = JSON.parse(fs.readFileSync(configPath, 'utf8')) as Record<string, unknown>\n } catch {\n existing = {}\n }\n const currentTelemetry = (existing.telemetry as TelemetryConfig | undefined) ?? {}\n const next = { ...existing, telemetry: { ...currentTelemetry, ...update } }\n fs.mkdirSync(path.dirname(configPath), { recursive: true })\n fs.writeFileSync(configPath, JSON.stringify(next, null, 2))\n}\n","import { readTelemetryConfig } from './config.js'\n\nexport function isCiEnvironment(): boolean {\n return process.env.CI === 'true' || process.env.CI === '1'\n}\n\nexport function isTelemetryDisabled(): boolean {\n if (process.env.MOXT_TELEMETRY_DISABLED === '1' || process.env.MOXT_TELEMETRY_DISABLED === 'true') {\n return true\n }\n if (process.env.DO_NOT_TRACK === '1' || process.env.DO_NOT_TRACK === 'true') {\n return true\n }\n return readTelemetryConfig().disabled === true\n}\n","import { Command } from 'commander'\nimport { readTelemetryConfig, writeTelemetryConfig } from '../telemetry/config.js'\nimport { isTelemetryDisabled } from '../telemetry/opt-out.js'\nimport { print } from '../utils/output.js'\n\nexport function registerTelemetryCommand(program: Command): void {\n const telemetry = program.command('telemetry').description('Manage Moxt CLI telemetry')\n\n telemetry\n .command('status')\n .description('Show telemetry status')\n .action(() => {\n const cfg = readTelemetryConfig()\n const envOverride =\n process.env.MOXT_TELEMETRY_DISABLED === '1' ||\n process.env.MOXT_TELEMETRY_DISABLED === 'true' ||\n process.env.DO_NOT_TRACK === '1' ||\n process.env.DO_NOT_TRACK === 'true'\n\n const state = isTelemetryDisabled() ? 'disabled' : 'enabled'\n print(`telemetry: ${state}`)\n if (envOverride) {\n print('(disabled via environment variable)')\n } else if (cfg.disabled) {\n print('(disabled via config file)')\n }\n })\n\n telemetry\n .command('enable')\n .description('Enable telemetry')\n .action(() => {\n writeTelemetryConfig({ disabled: false })\n print('telemetry: enabled')\n })\n\n telemetry\n .command('disable')\n .description('Disable telemetry')\n .action(() => {\n writeTelemetryConfig({ disabled: true })\n print('telemetry: disabled')\n })\n}\n","import { Command } from 'commander'\nimport { httpGet } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\ninterface WhoamiResponse {\n nickname: string\n email: string\n}\n\nexport function registerWhoamiCommand(program: Command): void {\n program\n .command('whoami')\n .description('Show current user information')\n .action(async () => {\n startSpinner('Fetching user info...')\n const response = await httpGet<WhoamiResponse>('/users/whoami')\n\n if (response.ok) {\n stopSpinner(true, 'Done')\n print(`${colors.bold}Nickname${colors.reset}: ${response.data.nickname}`)\n print(`${colors.bold}Email${colors.reset}: ${response.data.email}`)\n } else {\n stopSpinner(false, 'Failed')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n })\n}\n","import { Command } from 'commander'\nimport { httpGet, httpDelete } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\ninterface WorkspaceItem {\n workspaceId: string\n name: string\n}\n\ninterface WorkspaceListResponse {\n workspaces: WorkspaceItem[]\n}\n\ninterface MemberItem {\n userId: number\n email: string\n displayName: string | null\n role: string\n}\n\ninterface MembersResponse {\n members: MemberItem[]\n}\n\ninterface SpaceItem {\n type: 'personal' | 'team' | 'teammate'\n name: string\n teamSpaceId: string | null\n agentId: number | null\n}\n\n// Email regex (same as web/src/utils/email.ts)\nconst emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/\n\nfunction isValidEmail(email: string): boolean {\n return emailRegex.test(email)\n}\n\nexport function registerWorkspaceCommand(program: Command): void {\n const workspace = program.command('workspace').description('Workspace management')\n\n workspace\n .command('list')\n .description('List all workspaces you belong to')\n .action(async () => {\n startSpinner('Fetching workspaces...')\n const response = await httpGet<WorkspaceListResponse>('/workspaces')\n\n if (response.ok) {\n const { workspaces } = response.data\n if (workspaces.length === 0) {\n stopSpinner(true, 'No workspaces found.')\n return\n }\n\n stopSpinner(true, `Found ${workspaces.length} workspace(s)`)\n\n for (const ws of workspaces) {\n print(`${colors.bold}${ws.workspaceId}${colors.reset}\\t${ws.name}`)\n }\n } else {\n stopSpinner(false, 'Failed')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n })\n\n const members = program.command('members').description('Manage workspace members')\n\n members\n .command('list')\n .description('List all members in a workspace')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .action(async (options: { workspace: string }) => {\n const { workspace: workspaceId } = options\n\n startSpinner('Fetching workspace members...')\n const response = await httpGet<MembersResponse>(`/workspaces/${workspaceId}/members`)\n\n if (!response.ok) {\n stopSpinner(false, 'Failed to fetch members')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n const { members } = response.data\n if (members.length === 0) {\n stopSpinner(true, 'No members found.')\n return\n }\n\n stopSpinner(true, `Found ${members.length} member(s)`)\n\n for (const member of members) {\n const name = member.displayName || '-'\n print(`${colors.bold}${member.email}${colors.reset}\\t${name}\\t${member.role}`)\n }\n })\n\n members\n .command('remove')\n .description('Remove members from a workspace')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .argument('<emails>', 'Emails to remove (comma-separated)')\n .action(async (emailsArg: string, options: { workspace: string }) => {\n const { workspace: workspaceId } = options\n\n const emails = emailsArg.split(',').map((e) => e.trim()).filter(Boolean)\n if (emails.length === 0) {\n printError('No valid emails provided')\n process.exit(1)\n }\n\n // Validate email format\n const invalidEmails = emails.filter((e) => !isValidEmail(e))\n if (invalidEmails.length > 0) {\n for (const email of invalidEmails) {\n printError(`Invalid email format: ${email}`)\n }\n process.exit(1)\n }\n\n // Fetch members to get userId by email\n startSpinner('Fetching workspace members...')\n const membersResponse = await httpGet<MembersResponse>(`/workspaces/${workspaceId}/members`)\n\n if (!membersResponse.ok) {\n stopSpinner(false, 'Failed to fetch members')\n printError(`Error [${membersResponse.status}]: ${JSON.stringify(membersResponse.data)}`)\n process.exit(1)\n }\n\n stopSpinner(true, 'Members fetched')\n\n const { members } = membersResponse.data\n const emailToMember = new Map(members.map((m) => [m.email.toLowerCase(), m]))\n\n // Remove each member\n for (const email of emails) {\n const member = emailToMember.get(email.toLowerCase())\n if (!member) {\n print(`${colors.red}✗${colors.reset} ${email} - not found in workspace`)\n continue\n }\n\n const deleteResponse = await httpDelete(`/workspaces/${workspaceId}/members/${member.userId}`)\n\n if (deleteResponse.ok) {\n print(`${colors.green}✓${colors.reset} ${email} - removed`)\n } else {\n print(`${colors.red}✗${colors.reset} ${email} - failed: ${JSON.stringify(deleteResponse.data)}`)\n }\n }\n })\n\n const space = program.command('space').description('Manage spaces')\n\n space\n .command('list')\n .description('List accessible spaces in a workspace')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .action(async (options: { workspace: string }) => {\n const { workspace: workspaceId } = options\n\n startSpinner('Fetching spaces...')\n const response = await httpGet<{ spaces: SpaceItem[] }>(`/workspaces/${workspaceId}/spaces`)\n\n if (!response.ok) {\n stopSpinner(false, 'Failed to fetch spaces')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n const { spaces } = response.data\n if (spaces.length === 0) {\n stopSpinner(true, 'No spaces found.')\n return\n }\n\n stopSpinner(true, `Found ${spaces.length} space(s)`)\n\n print(\n `${colors.bold}TYPE${colors.reset}\\t${colors.bold}TEAM_SPACE_ID${colors.reset}\\t${colors.bold}TEAMMATE_ID${colors.reset}\\t${colors.bold}NAME${colors.reset}`,\n )\n for (const s of spaces) {\n const teamSpaceId = s.teamSpaceId ?? ''\n const teammateId = s.agentId != null ? String(s.agentId) : ''\n print(`${s.type}\\t${teamSpaceId}\\t${teammateId}\\t${s.name}`)\n }\n })\n\n}\n","import { arch, platform } from 'node:os'\nimport { getApiBaseUrl, getApiKeyOrUndefined } from '../utils/config.js'\nimport { isCiEnvironment, isTelemetryDisabled } from './opt-out.js'\n\ndeclare const __CLI_VERSION__: string\n\nexport type MetricType = 'counter' | 'gauge' | 'histogram'\n\nexport interface MetricRecord {\n metric_id: string\n metric_type: MetricType\n value: number\n extra_label_name_2_value?: Record<string, string>\n}\n\nconst buffer: MetricRecord[] = []\nconst FLUSH_TIMEOUT_MS = 3000\nconst MAX_BATCH_SIZE = 100\n\nfunction commonLabels(): Record<string, string> {\n return {\n cli_version: __CLI_VERSION__,\n node_version: process.versions.node,\n os: platform(),\n arch: arch(),\n is_ci: isCiEnvironment() ? 'true' : 'false',\n }\n}\n\nexport function record(metric: MetricRecord): void {\n if (isTelemetryDisabled()) {\n debugLog(`record: disabled, dropping ${metric.metric_id}`)\n return\n }\n if (!getApiKeyOrUndefined()) {\n debugLog(`record: no API key, dropping ${metric.metric_id}`)\n return\n }\n buffer.push({\n ...metric,\n extra_label_name_2_value: {\n ...commonLabels(),\n ...(metric.extra_label_name_2_value ?? {}),\n },\n })\n debugLog(`record: buffered ${metric.metric_id} (buffer=${buffer.length})`)\n}\n\nfunction isDebug(): boolean {\n return process.env.MOXT_TELEMETRY_DEBUG === '1' || process.env.MOXT_TELEMETRY_DEBUG === 'true'\n}\n\nfunction debugLog(msg: string, detail?: unknown): void {\n if (!isDebug()) return\n process.stderr.write(`[telemetry] ${msg}${detail !== undefined ? ` ${JSON.stringify(detail)}` : ''}\\n`)\n}\n\nexport async function flush(): Promise<void> {\n if (buffer.length === 0) {\n debugLog('flush: buffer empty, skipping')\n return\n }\n const apiKey = getApiKeyOrUndefined()\n if (!apiKey) {\n debugLog('flush: no API key, dropping buffer')\n buffer.length = 0\n return\n }\n\n const batch = buffer.splice(0, MAX_BATCH_SIZE)\n const payload = {\n release_id: __CLI_VERSION__,\n client_type: 'cli',\n metric_data_list: batch.map((m) => ({\n profile: 'cli',\n metric_id: m.metric_id,\n metric_type: m.metric_type,\n value: m.value,\n extra_label_name_2_value: m.extra_label_name_2_value,\n })),\n }\n\n const url = `${getApiBaseUrl()}/cli-metrics`\n debugLog(`flush: POST ${url} with ${batch.length} metrics`, payload)\n\n try {\n const controller = new AbortController()\n const timeout = setTimeout(() => {\n controller.abort()\n }, FLUSH_TIMEOUT_MS)\n try {\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n signal: controller.signal,\n })\n debugLog(`flush: response status=${res.status}`)\n } finally {\n clearTimeout(timeout)\n }\n } catch (err) {\n debugLog('flush: failed', err instanceof Error ? err.message : String(err))\n // fire-and-forget — never surface telemetry failures to the user\n }\n}\n","import { readTelemetryConfig, writeTelemetryConfig } from './config.js'\nimport { isCiEnvironment, isTelemetryDisabled } from './opt-out.js'\n\nconst NOTICE = [\n '',\n 'Attention: Moxt CLI now collects anonymous telemetry regarding usage.',\n \"This information is used to shape Moxt CLI's roadmap and prioritize features.\",\n '',\n 'You may opt out by setting MOXT_TELEMETRY_DISABLED=1 in your env',\n 'or by running `moxt telemetry disable`.',\n 'Details: https://www.npmjs.com/package/@moxt-ai/cli#telemetry',\n '',\n]\n\nexport function maybeShowTelemetryNotice(): void {\n if (isTelemetryDisabled()) return\n if (isCiEnvironment()) return\n if (readTelemetryConfig().noticeShown) return\n\n for (const line of NOTICE) {\n process.stderr.write(`${line}\\n`)\n }\n\n try {\n writeTelemetryConfig({ noticeShown: true })\n } catch {\n // persistence failure is not user-visible — we'll just show the notice again next run\n }\n}\n","import type { Command } from 'commander'\nimport { flush, record } from './client.js'\nimport { maybeShowTelemetryNotice } from './notice.js'\n\ninterface RunningCommand {\n name: string\n subcommand?: string\n startedAt: number\n}\n\nlet current: RunningCommand | null = null\n\nfunction commandPath(cmd: Command): { command: string; subcommand?: string } {\n const names: string[] = []\n let node: Command | null = cmd\n while (node && node.parent) {\n names.unshift(node.name())\n node = node.parent\n }\n if (names.length === 0) return { command: 'unknown' }\n if (names.length === 1) return { command: names[0] }\n return { command: names[0], subcommand: names.slice(1).join(' ') }\n}\n\nexport function instrumentProgram(program: Command): void {\n program.hook('preAction', (_thisCommand, actionCommand) => {\n const { command, subcommand } = commandPath(actionCommand)\n if (command !== 'telemetry') {\n maybeShowTelemetryNotice()\n }\n current = { name: command, subcommand, startedAt: Date.now() }\n record({\n metric_id: 'client.cli.command_invocation.count',\n metric_type: 'counter',\n value: 1,\n extra_label_name_2_value: {\n command,\n ...(subcommand ? { subcommand } : {}),\n status: 'started',\n },\n })\n })\n\n program.hook('postAction', async () => {\n await reportOutcome('success')\n })\n}\n\nasync function reportOutcome(status: 'success' | 'error', errorCode?: string): Promise<void> {\n if (!current) return\n const { name, subcommand, startedAt } = current\n const durationSeconds = (Date.now() - startedAt) / 1000\n\n record({\n metric_id: 'client.cli.command_duration_seconds',\n metric_type: 'histogram',\n value: durationSeconds,\n extra_label_name_2_value: {\n command: name,\n ...(subcommand ? { subcommand } : {}),\n status,\n },\n })\n\n if (status === 'error') {\n record({\n metric_id: 'client.cli.command_error.count',\n metric_type: 'counter',\n value: 1,\n extra_label_name_2_value: {\n command: name,\n ...(subcommand ? { subcommand } : {}),\n ...(errorCode ? { error_code: errorCode } : {}),\n },\n })\n }\n\n current = null\n await flush()\n}\n\n/**\n * Wire a final error/exit hook. Call before program.parseAsync so we can capture\n * failures routed through process.exit or unhandled rejections.\n *\n * Best-effort only: `reportOutcome` is fire-and-forget, and the subsequent\n * `process.exit(1)` terminates the process before `flush()` can complete — so\n * the error metric recorded here will typically be dropped. Reliable crash\n * reporting belongs to Sentry/APM, not this telemetry path.\n */\nexport function installExitHandler(): void {\n const handleError = (errorCode: string): void => {\n void reportOutcome('error', errorCode)\n }\n\n process.on('uncaughtException', () => {\n handleError('uncaught_exception')\n process.exit(1)\n })\n process.on('unhandledRejection', () => {\n handleError('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Q,MAAM,cAAc,GAAG;AAC/B,QAAM,MAAM;AACZ,UAAQ,KAAK,CAAC;AAClB,CAAC;","names":["path","buffer","path","program","path","buffer","path","runOrExit","path","program","fs","program","program","program","members","arch","platform","platform","arch","program"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moxt-ai/cli",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "Moxt - The Agent-Native Workspace",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -28,6 +28,11 @@
28
28
  "author": "Moxt",
29
29
  "license": "MIT",
30
30
  "homepage": "https://moxt.ai",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/paraflow-hq/moxt.git",
34
+ "directory": "moxt-cli"
35
+ },
31
36
  "engines": {
32
37
  "node": ">=18"
33
38
  },
@@ -40,7 +45,8 @@
40
45
  "@types/update-notifier": "^6.0.8",
41
46
  "tsup": "^8.5.0",
42
47
  "tsx": "^4.0.0",
43
- "typescript": "^5.8.0",
44
- "vitest": "^3.2.0"
48
+ "typescript": "^6.0.3",
49
+ "vite": "^8.0.12",
50
+ "vitest": "^4.1.6"
45
51
  }
46
52
  }