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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,2400 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/index.ts
4
- import updateNotifier from "update-notifier";
5
-
6
- // src/program.ts
7
- import { Command } from "commander";
8
-
9
- // src/commands/file.ts
10
- import * as fs2 from "fs";
11
-
12
- // src/commands/file-comment.ts
13
- import * as fs from "fs";
14
- import { TextDecoder } from "util";
15
-
16
- // src/utils/file-selector.ts
17
- var SpaceOptionsError = class extends Error {
18
- constructor(message) {
19
- super(message);
20
- this.name = "SpaceOptionsError";
21
- }
22
- };
23
- function resolveSpaceSelector(options) {
24
- const { space, teamSpaceId, teammateId } = options;
25
- const personalIsSet = options.personal === true;
26
- const spaceIsSet = space != null && space !== "";
27
- const teamSpaceIdIsSet = teamSpaceId != null && teamSpaceId !== "";
28
- const teammateIdIsSet = teammateId != null && teammateId !== "";
29
- const selectorCount = (spaceIsSet ? 1 : 0) + (personalIsSet ? 1 : 0) + (teamSpaceIdIsSet ? 1 : 0) + (teammateIdIsSet ? 1 : 0);
30
- if (selectorCount > 1) {
31
- throw new SpaceOptionsError(
32
- "Error: -s, --personal, --team-space-id, and --teammate-id are mutually exclusive."
33
- );
34
- }
35
- if (teamSpaceId != null && teamSpaceId !== "") {
36
- return { teamSpaceId };
37
- }
38
- if (teammateId != null && teammateId !== "") {
39
- const parsed = Number.parseInt(teammateId, 10);
40
- if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== teammateId) {
41
- throw new SpaceOptionsError(
42
- `Error: --teammate-id must be a positive integer, got "${teammateId}".`
43
- );
44
- }
45
- return { agentId: parsed };
46
- }
47
- if (personalIsSet) {
48
- return { space: "personal" };
49
- }
50
- if (space != null && space !== "") {
51
- return { space };
52
- }
53
- return {};
54
- }
55
- function buildFileQueryString(path2, spaceParams) {
56
- const params = new URLSearchParams();
57
- if (path2 != null && path2 !== "") {
58
- params.set("path", path2);
59
- }
60
- if (spaceParams.space) {
61
- params.set("space", spaceParams.space);
62
- }
63
- if (spaceParams.teamSpaceId) {
64
- params.set("teamSpaceId", spaceParams.teamSpaceId);
65
- }
66
- if (spaceParams.agentId != null) {
67
- params.set("agentId", String(spaceParams.agentId));
68
- }
69
- const qs = params.toString();
70
- return qs ? `?${qs}` : "";
71
- }
72
- function isBinaryContent(buffer2) {
73
- const sampleSize = Math.min(buffer2.length, 8192);
74
- for (let i = 0; i < sampleSize; i++) {
75
- const byte = buffer2[i];
76
- if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {
77
- return true;
78
- }
79
- }
80
- return false;
81
- }
82
- function resolveReadMode(options) {
83
- if (options.url && options.workspace) {
84
- throw new SpaceOptionsError("Error: --url cannot be used with --workspace");
85
- }
86
- if (options.url && options.path) {
87
- throw new SpaceOptionsError("Error: --url cannot be used with --path");
88
- }
89
- if (!options.url && !options.workspace) {
90
- throw new SpaceOptionsError("Error: Either --url or --workspace is required");
91
- }
92
- if (!options.url && !options.path) {
93
- throw new SpaceOptionsError("Error: --path is required when not using --url");
94
- }
95
- if (options.url) {
96
- return { kind: "by-url", url: options.url };
97
- }
98
- if (!options.workspace) {
99
- throw new SpaceOptionsError("Error: Either --url or --workspace is required");
100
- }
101
- if (!options.path) {
102
- throw new SpaceOptionsError("Error: --path is required when not using --url");
103
- }
104
- return { kind: "by-path", workspace: options.workspace, path: options.path };
105
- }
106
- function resolveWriteMode(options) {
107
- if (options.url && options.workspace) {
108
- throw new SpaceOptionsError("Error: --url cannot be used with --workspace");
109
- }
110
- if (options.url && options.path) {
111
- throw new SpaceOptionsError("Error: --url cannot be used with --path");
112
- }
113
- if (options.url && options.recursive) {
114
- throw new SpaceOptionsError("Error: --recursive cannot be used with --url (the file must already exist)");
115
- }
116
- if (!options.url && !options.workspace) {
117
- throw new SpaceOptionsError("Error: Either --url or --workspace is required");
118
- }
119
- if (!options.url && !options.path) {
120
- throw new SpaceOptionsError("Error: --path is required when not using --url");
121
- }
122
- if (options.url) {
123
- return { kind: "by-url", url: options.url };
124
- }
125
- return { kind: "by-path", workspace: options.workspace, path: options.path };
126
- }
127
-
128
- // src/utils/http.ts
129
- import { arch, platform } from "os";
130
-
131
- // src/utils/config.ts
132
- var DEFAULT_HOST = "api.moxt.ai";
133
- function getApiBaseUrl() {
134
- const host = process.env.MOXT_HOST ?? DEFAULT_HOST;
135
- return `https://${host}/openapi/v1`;
136
- }
137
- function getApiKey() {
138
- const apiKey = process.env.MOXT_API_KEY;
139
- if (!apiKey) {
140
- console.error("MOXT_API_KEY environment variable is not set.");
141
- console.error("");
142
- console.error("Get your API key at: https://moxt.ai");
143
- console.error("");
144
- console.error("Then set it:");
145
- console.error(" export MOXT_API_KEY=moxt_...");
146
- process.exit(1);
147
- }
148
- return apiKey;
149
- }
150
- function getApiKeyOrUndefined() {
151
- return process.env.MOXT_API_KEY;
152
- }
153
-
154
- // src/utils/http.ts
155
- function getUserAgent() {
156
- return `moxt-cli/${"0.7.2"} (${platform()}/${arch()}) node/${process.versions.node}`;
157
- }
158
- async function fetchApi(method, path2, body) {
159
- const apiKey = getApiKey();
160
- const url = `${getApiBaseUrl()}${path2}`;
161
- const response = await fetch(url, {
162
- method,
163
- headers: {
164
- "Content-Type": "application/json",
165
- Authorization: `Bearer ${apiKey}`,
166
- "User-Agent": getUserAgent()
167
- },
168
- body: body ? JSON.stringify(body) : void 0
169
- });
170
- if (response.status === 401) {
171
- console.error("Authentication failed. Check your MOXT_API_KEY.");
172
- console.error("Get a new key at: https://moxt.ai");
173
- process.exit(1);
174
- }
175
- return response;
176
- }
177
- async function request(method, path2, body) {
178
- const response = await fetchApi(method, path2, body);
179
- const contentType = response.headers.get("content-type");
180
- const data = contentType?.includes("application/json") ? await response.json() : await response.text();
181
- return {
182
- ok: response.ok,
183
- status: response.status,
184
- data
185
- };
186
- }
187
- async function httpGet(path2) {
188
- return request("GET", path2);
189
- }
190
- async function httpPut(path2, body) {
191
- return request("PUT", path2, body);
192
- }
193
- async function httpPost(path2, body) {
194
- return request("POST", path2, body);
195
- }
196
- async function httpPatch(path2, body) {
197
- return request("PATCH", path2, body);
198
- }
199
- async function httpDelete(path2, body) {
200
- return request("DELETE", path2, body);
201
- }
202
- async function httpRaw(method, path2, body) {
203
- const response = await fetchApi(method, path2, body);
204
- return {
205
- ok: response.ok,
206
- status: response.status,
207
- text: await response.text(),
208
- contentType: response.headers.get("content-type")
209
- };
210
- }
211
-
212
- // src/utils/output.ts
213
- var colors = {
214
- bold: "\x1B[1m",
215
- blue: "\x1B[1;34m",
216
- green: "\x1B[32m",
217
- red: "\x1B[31m",
218
- cyan: "\x1B[36m",
219
- dim: "\x1B[2m",
220
- reset: "\x1B[0m"
221
- };
222
- function print(message) {
223
- console.log(message);
224
- }
225
- function printError(message) {
226
- console.error(`${colors.red}${message}${colors.reset}`);
227
- }
228
-
229
- // src/utils/spinner.ts
230
- var frames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
231
- var intervalId = null;
232
- var frameIndex = 0;
233
- function startSpinner(message) {
234
- frameIndex = 0;
235
- process.stdout.write(`${frames[frameIndex]} ${message}`);
236
- intervalId = setInterval(() => {
237
- frameIndex = (frameIndex + 1) % frames.length;
238
- process.stdout.write(`\r${frames[frameIndex]} ${message}`);
239
- }, 80);
240
- }
241
- function stopSpinner(success, message) {
242
- if (intervalId) {
243
- clearInterval(intervalId);
244
- intervalId = null;
245
- }
246
- const symbol = success ? "\x1B[32m\u2713\x1B[0m" : "\x1B[31m\u2717\x1B[0m";
247
- process.stdout.write(`\x1B[2K\r${symbol} ${message ?? ""}
248
- `);
249
- }
250
-
251
- // src/commands/file-comment.ts
252
- var FILE_ID_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
253
- var URL_FORMAT_HINT = "Error: invalid Moxt URL format. Expected https://moxt.ai/w/{workspaceId}/{fileId} or https://moxt.ai/w/{workspaceId}/c/{agentId}[/{sessionId}]?file={fileId}";
254
- var FileCommentOptionsError = class extends Error {
255
- constructor(message) {
256
- super(message);
257
- this.name = "FileCommentOptionsError";
258
- }
259
- };
260
- function runOrExit(fn) {
261
- try {
262
- return fn();
263
- } catch (err) {
264
- if (err instanceof FileCommentOptionsError || err instanceof SpaceOptionsError) {
265
- printError(err.message);
266
- process.exit(1);
267
- }
268
- throw err;
269
- }
270
- }
271
- function parseMoxtFileUrl(url) {
272
- let parsed;
273
- try {
274
- parsed = new URL(url);
275
- } catch {
276
- throw new FileCommentOptionsError(URL_FORMAT_HINT);
277
- }
278
- const segments = parsed.pathname.split("/").filter(Boolean);
279
- if (segments.length < 3 || segments[0] !== "w") {
280
- throw new FileCommentOptionsError(URL_FORMAT_HINT);
281
- }
282
- const workspaceId = segments[1];
283
- let fileId;
284
- if (segments[2] === "c") {
285
- fileId = parsed.searchParams.get("file") ?? void 0;
286
- } else if (segments.length === 3) {
287
- fileId = segments[2];
288
- }
289
- if (!fileId || !FILE_ID_UUID_RE.test(fileId)) {
290
- throw new FileCommentOptionsError(URL_FORMAT_HINT);
291
- }
292
- return { workspaceId, fileId };
293
- }
294
- async function resolveFileTarget(options) {
295
- const mode = runOrExit(() => resolveReadMode(options));
296
- if (mode.kind === "by-url") {
297
- return runOrExit(() => parseMoxtFileUrl(mode.url));
298
- }
299
- const spaceParams = runOrExit(() => resolveSpaceSelector(options));
300
- const qs = buildFileQueryString(mode.path, spaceParams);
301
- startSpinner("Resolving file...");
302
- const response = await httpGet(`/workspaces/${mode.workspace}/files/url${qs}`);
303
- if (!response.ok) {
304
- stopSpinner(false, "Failed");
305
- if (response.status === 404) {
306
- print(`${colors.red}\u2620 ${mode.path} does not exist${colors.reset}`);
307
- } else if (response.status === 400) {
308
- printError(`Error: ${JSON.stringify(response.data)}`);
309
- } else {
310
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
311
- }
312
- process.exit(1);
313
- }
314
- stopSpinner(true, response.data.path);
315
- return runOrExit(() => parseMoxtFileUrl(response.data.url));
316
- }
317
- function readCommentContentFile(path2) {
318
- if (!fs.existsSync(path2)) {
319
- throw new FileCommentOptionsError(`Error: comment content file not found: ${path2}`);
320
- }
321
- const stat = fs.statSync(path2);
322
- if (!stat.isFile()) {
323
- throw new FileCommentOptionsError(`Error: comment content path is not a file: ${path2}`);
324
- }
325
- const buffer2 = fs.readFileSync(path2);
326
- if (buffer2.includes(0)) {
327
- throw new FileCommentOptionsError("Error: comment content file must not contain NUL bytes.");
328
- }
329
- let content;
330
- try {
331
- content = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer2);
332
- } catch {
333
- throw new FileCommentOptionsError("Error: comment content file must contain valid UTF-8 text.");
334
- }
335
- if (content.length === 0) {
336
- throw new FileCommentOptionsError("Error: comment content file must not be empty.");
337
- }
338
- return content;
339
- }
340
- function parseResolveState(state) {
341
- if (state === "resolved") return true;
342
- if (state === "open") return false;
343
- throw new FileCommentOptionsError('Error: --state must be "resolved" or "open".');
344
- }
345
- function indentation(size) {
346
- return " ".repeat(size);
347
- }
348
- function escapeTerminalControlCharacters(value) {
349
- return value.replace(/\r\n/g, "\n").replace(
350
- /[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,
351
- (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
352
- );
353
- }
354
- function formatDetailScalar(value) {
355
- if (value === null) return "null";
356
- if (typeof value === "string") {
357
- const escaped = escapeTerminalControlCharacters(value);
358
- if (escaped === "") return '""';
359
- if (/\n/.test(escaped)) return JSON.stringify(escaped);
360
- return escaped;
361
- }
362
- return String(value);
363
- }
364
- function printDetailField(name, value, indent = 0) {
365
- print(`${indentation(indent)}${name}: ${formatDetailScalar(value)}`);
366
- }
367
- function printDetailTextField(name, value, indent = 0) {
368
- if (value === null || value === "") {
369
- printDetailField(name, value, indent);
370
- return;
371
- }
372
- const escaped = escapeTerminalControlCharacters(value);
373
- print(`${indentation(indent)}${name}:`);
374
- for (const line of escaped.split("\n")) {
375
- print(`${indentation(indent + 2)}${line}`);
376
- }
377
- }
378
- function printAuthorFields(author, indent) {
379
- printDetailField("humanId", author.humanId, indent);
380
- printDetailField("assistantId", author.assistantId, indent);
381
- printDetailField("teammateId", author.teammateId, indent);
382
- printDetailField("authorName", author.authorName, indent);
383
- printDetailField("authorAvatarUrl", author.authorAvatarUrl, indent);
384
- }
385
- function printCommentItem(item, indent = 0) {
386
- print(`${indentation(indent)}${colors.bold}Comment${colors.reset}`);
387
- printDetailField("id", item.id, indent + 2);
388
- printDetailField("threadId", item.threadId, indent + 2);
389
- printAuthorFields(item, indent + 2);
390
- printDetailTextField("content", item.content, indent + 2);
391
- printDetailField("createdAt", item.createdAt, indent + 2);
392
- printDetailField("editedAt", item.editedAt, indent + 2);
393
- }
394
- function printThread(thread) {
395
- print(`${colors.bold}Thread${colors.reset}`);
396
- printDetailField("threadId", thread.threadId, 2);
397
- printDetailField("fileId", thread.fileId, 2);
398
- printDetailTextField("quotedText", thread.quotedText, 2);
399
- printDetailField("resolvedAt", thread.resolvedAt, 2);
400
- print(`${indentation(2)}createdBy:`);
401
- printAuthorFields(thread.createdBy, 4);
402
- printDetailField("createdAt", thread.createdAt, 2);
403
- print(`${indentation(2)}comments:`);
404
- thread.items.forEach((item) => printCommentItem(item, 4));
405
- }
406
- function addFileSelectorOptions(cmd) {
407
- return cmd.option("-w, --workspace <workspaceId>", "Workspace ID").option("-s, --space <name>", "Space name (personal or teamspace name)").option("--personal", "Use personal space (default)").option("--team-space-id <teamSpaceId>", "Team space ID").option("--teammate-id <teammateId>", "Teammate ID (teammate space)").option("-p, --path <path>", "File path").option("-u, --url <url>", "Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})");
408
- }
409
- function registerFileCommentCommands(file) {
410
- const comment = file.command("comment").description("File comment operations");
411
- addFileSelectorOptions(
412
- comment.command("list").description("List comment threads on a file")
413
- ).action(async (options) => {
414
- const target = await resolveFileTarget(options);
415
- startSpinner("Fetching comments...");
416
- const response = await httpGet(
417
- `/workspaces/${target.workspaceId}/files/${target.fileId}/comment-threads`
418
- );
419
- if (!response.ok) {
420
- stopSpinner(false, "Failed");
421
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
422
- process.exit(1);
423
- }
424
- if (response.data.items.length === 0) {
425
- stopSpinner(true, "No comments found.");
426
- return;
427
- }
428
- stopSpinner(true, `Found ${response.data.items.length} thread(s)`);
429
- response.data.items.forEach((thread, index) => {
430
- if (index > 0) print("");
431
- printThread(thread);
432
- });
433
- });
434
- addFileSelectorOptions(
435
- comment.command("update").description("Update a comment you created").argument("<commentId>").requiredOption("--content-path <localPath>", "Local UTF-8 text file for comment content")
436
- ).action(async (commentId, options) => {
437
- const content = runOrExit(() => readCommentContentFile(options.contentPath));
438
- const target = await resolveFileTarget(options);
439
- startSpinner("Updating comment...");
440
- const response = await httpPatch(
441
- `/workspaces/${target.workspaceId}/files/${target.fileId}/comments/${commentId}`,
442
- { content }
443
- );
444
- if (!response.ok) {
445
- stopSpinner(false, "Failed");
446
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
447
- process.exit(1);
448
- }
449
- stopSpinner(true, "Comment updated");
450
- printCommentItem(response.data);
451
- });
452
- addFileSelectorOptions(
453
- comment.command("resolve").description("Resolve or reopen a comment thread").argument("<threadId>").requiredOption("--state <state>", "Thread state: resolved or open")
454
- ).action(async (threadId, options) => {
455
- const resolved = runOrExit(() => parseResolveState(options.state));
456
- const target = await resolveFileTarget(options);
457
- startSpinner(resolved ? "Resolving thread..." : "Reopening thread...");
458
- const response = await httpPatch(
459
- `/workspaces/${target.workspaceId}/files/${target.fileId}/comment-threads/${threadId}/resolve`,
460
- { resolved }
461
- );
462
- if (!response.ok) {
463
- stopSpinner(false, "Failed");
464
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
465
- process.exit(1);
466
- }
467
- stopSpinner(true, resolved ? `Resolved: ${threadId}` : `Reopened: ${threadId}`);
468
- });
469
- }
470
-
471
- // src/utils/search-options.ts
472
- var SearchOptionsError = class extends Error {
473
- constructor(message) {
474
- super(message);
475
- this.name = "SearchOptionsError";
476
- }
477
- };
478
- function parseSearchLimit(raw, defaultValue, max) {
479
- if (raw == null || raw === "") {
480
- return defaultValue;
481
- }
482
- const parsed = Number.parseInt(raw, 10);
483
- if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== raw) {
484
- throw new SearchOptionsError(`Error: --limit must be a positive integer, got "${raw}".`);
485
- }
486
- if (parsed > max) {
487
- throw new SearchOptionsError(`Error: --limit must be less than or equal to ${max}.`);
488
- }
489
- return parsed;
490
- }
491
- function parseSearchMode(raw) {
492
- if (raw == null || raw === "") {
493
- return "any";
494
- }
495
- if (raw === "all" || raw === "any") {
496
- return raw;
497
- }
498
- throw new SearchOptionsError(`Error: --mode must be "any" or "all", got "${raw}".`);
499
- }
500
- function parseTeammateId(raw) {
501
- if (raw == null || raw === "") {
502
- return void 0;
503
- }
504
- const parsed = Number.parseInt(raw, 10);
505
- if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== raw) {
506
- throw new SearchOptionsError(`Error: --teammate-id must be a positive integer, got "${raw}".`);
507
- }
508
- return parsed;
509
- }
510
-
511
- // src/utils/run-or-exit.ts
512
- function runOrExit2(fn) {
513
- try {
514
- return fn();
515
- } catch (err) {
516
- if (err instanceof SpaceOptionsError || err instanceof SearchOptionsError) {
517
- printError(err.message);
518
- process.exit(1);
519
- }
520
- throw err;
521
- }
522
- }
523
-
524
- // src/commands/file.ts
525
- function addSpaceOptions(cmd) {
526
- return cmd.requiredOption("-w, --workspace <workspaceId>", "Workspace ID").option("-s, --space <name>", "Space name (personal or teamspace name)").option("--personal", "Use personal space (default)").option("--team-space-id <teamSpaceId>", "Team space ID").option("--teammate-id <teammateId>", "Teammate ID (teammate space)");
527
- }
528
- function registerFileCommand(program2) {
529
- const file = program2.command("file").description("File operations");
530
- registerFileCommentCommands(file);
531
- addSpaceOptions(
532
- file.command("search").description("Search files in accessible spaces").argument("<query>", "Search query").option("-l, --limit <limit>", "Maximum number of files to return", "30").option("--mode <mode>", "Keyword matching mode: any or all", "any")
533
- ).action(async (query, options) => {
534
- const spaceParams = runOrExit2(() => resolveSpaceSelector(options));
535
- const limit = runOrExit2(() => parseSearchLimit(options.limit, 30, 80));
536
- const mode = runOrExit2(() => parseSearchMode(options.mode));
537
- startSpinner("Searching files...");
538
- const response = await httpPost(
539
- `/workspaces/${options.workspace}/files/search`,
540
- {
541
- query,
542
- limit,
543
- mode,
544
- ...spaceParams
545
- }
546
- );
547
- if (!response.ok) {
548
- stopSpinner(false, "Failed");
549
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
550
- process.exit(1);
551
- }
552
- const { items } = response.data;
553
- if (items.length === 0) {
554
- stopSpinner(true, "No files found.");
555
- return;
556
- }
557
- stopSpinner(true, `Found ${items.length} file(s)`);
558
- for (const item of items) {
559
- print(`${colors.bold}${item.rank}. ${item.filePath}${colors.reset}`);
560
- print(`${colors.dim}repo=${item.repoId} file=${item.fileId}${colors.reset}`);
561
- const snippet = item.contentHighlight?.text ?? item.semanticSnippets[0]?.content;
562
- if (snippet) {
563
- print(snippet);
564
- }
565
- print("");
566
- }
567
- });
568
- addSpaceOptions(
569
- file.command("get-url").description("Resolve the shareable browser URL for a file").requiredOption("-p, --path <path>", "File path")
570
- ).action(async (options) => {
571
- const spaceParams = runOrExit2(() => resolveSpaceSelector(options));
572
- const qs = buildFileQueryString(options.path, spaceParams);
573
- startSpinner("Resolving URL...");
574
- const response = await httpGet(
575
- `/workspaces/${options.workspace}/files/url${qs}`
576
- );
577
- if (!response.ok) {
578
- stopSpinner(false, "Failed");
579
- if (response.status === 404) {
580
- print(`${colors.red}\u2620 ${options.path} does not exist${colors.reset}`);
581
- } else if (response.status === 400) {
582
- printError(`Error: ${JSON.stringify(response.data)}`);
583
- } else {
584
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
585
- }
586
- process.exit(1);
587
- }
588
- stopSpinner(true, response.data.path);
589
- print(`${colors.cyan}${response.data.url}${colors.reset}`);
590
- });
591
- addSpaceOptions(
592
- file.command("list").description("List directory contents").option("-p, --path <path>", "Directory path", "/")
593
- ).action(async (options) => {
594
- const spaceParams = runOrExit2(() => resolveSpaceSelector(options));
595
- const qs = buildFileQueryString(options.path, spaceParams);
596
- startSpinner("Listing files...");
597
- const response = await httpGet(
598
- `/workspaces/${options.workspace}/files/list${qs}`
599
- );
600
- if (!response.ok) {
601
- stopSpinner(false, "Failed");
602
- if (response.status === 404) {
603
- print(`${colors.red}\u2620 ${options.path} does not exist${colors.reset}`);
604
- } else {
605
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
606
- }
607
- process.exit(1);
608
- }
609
- const { path: path2, entries } = response.data;
610
- if (!entries || entries.length === 0) {
611
- stopSpinner(true, `${path2}: empty directory`);
612
- return;
613
- }
614
- stopSpinner(true, path2);
615
- for (const entry of entries) {
616
- if (entry.type === "directory") {
617
- print(`${colors.blue}${entry.name}/${colors.reset}`);
618
- } else {
619
- print(entry.name);
620
- }
621
- }
622
- });
623
- file.command("read").description("Read file content").option("-w, --workspace <workspaceId>", "Workspace ID").option("-s, --space <name>", "Space name (personal or teamspace name)").option("--personal", "Use personal space (default)").option("--team-space-id <teamSpaceId>", "Team space ID").option("--teammate-id <teammateId>", "Teammate ID (teammate space)").option("-p, --path <path>", "File path").option("-u, --url <url>", "Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})").action(async (options) => {
624
- const mode = runOrExit2(() => resolveReadMode(options));
625
- startSpinner("Reading file...");
626
- let response;
627
- let displayPath;
628
- if (mode.kind === "by-url") {
629
- displayPath = mode.url;
630
- response = await httpGet(
631
- `/files/read-by-url?url=${encodeURIComponent(mode.url)}`
632
- );
633
- } else {
634
- displayPath = mode.path;
635
- const spaceParams = runOrExit2(() => resolveSpaceSelector(options));
636
- const qs = buildFileQueryString(mode.path, spaceParams);
637
- response = await httpGet(
638
- `/workspaces/${mode.workspace}/files/read${qs}`
639
- );
640
- }
641
- if (!response.ok) {
642
- stopSpinner(false, "Failed");
643
- if (response.status === 404) {
644
- print(`${colors.red}\u2620 ${displayPath} does not exist${colors.reset}`);
645
- } else {
646
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
647
- }
648
- process.exit(1);
649
- }
650
- const { type, content } = response.data;
651
- if (type === "directory") {
652
- stopSpinner(false, "Failed");
653
- print(`${colors.red}\u2620 ${displayPath} is a directory${colors.reset}`);
654
- process.exit(1);
655
- }
656
- stopSpinner(true, "Done");
657
- print(content ?? "");
658
- });
659
- file.command("put").description("Upload a file").option("-w, --workspace <workspaceId>", "Workspace ID").option("-s, --space <name>", "Space name (personal or teamspace name)").option("--personal", "Use personal space (default)").option("--team-space-id <teamSpaceId>", "Team space ID").option("--teammate-id <teammateId>", "Teammate ID (teammate space)").option("-p, --path <path>", "Remote file path").option("-u, --url <url>", "Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})").requiredOption("-l, --local-path <localPath>", "Local file path").option("-r, --recursive", "Create parent directories if needed").action(
660
- async (options) => {
661
- const mode = runOrExit2(() => resolveWriteMode(options));
662
- if (!fs2.existsSync(options.localPath)) {
663
- print(`${colors.red}\u2620 Local file not found: ${options.localPath}${colors.reset}`);
664
- process.exit(1);
665
- }
666
- const stats = fs2.statSync(options.localPath);
667
- if (!stats.isFile()) {
668
- print(`${colors.red}\u2620 Not a file: ${options.localPath}${colors.reset}`);
669
- process.exit(1);
670
- }
671
- const maxSize = 10 * 1024 * 1024;
672
- if (stats.size > maxSize) {
673
- print(`${colors.red}\u2620 File too large (max 10MB): ${options.localPath}${colors.reset}`);
674
- process.exit(1);
675
- }
676
- const buffer2 = fs2.readFileSync(options.localPath);
677
- if (isBinaryContent(buffer2)) {
678
- print(`${colors.red}\u2620 Binary files are not allowed. Only text files can be uploaded.${colors.reset}`);
679
- process.exit(1);
680
- }
681
- const content = buffer2.toString("utf8");
682
- startSpinner("Uploading...");
683
- let response;
684
- let displayPath;
685
- if (mode.kind === "by-url") {
686
- displayPath = mode.url;
687
- response = await httpPut("/files/write-by-url", {
688
- url: mode.url,
689
- content
690
- });
691
- } else {
692
- displayPath = mode.path;
693
- const spaceParams = runOrExit2(() => resolveSpaceSelector(options));
694
- response = await httpPut(
695
- `/workspaces/${mode.workspace}/files/write`,
696
- {
697
- path: mode.path,
698
- content,
699
- recursive: options.recursive ?? false,
700
- ...spaceParams
701
- }
702
- );
703
- }
704
- if (!response.ok) {
705
- stopSpinner(false, "Failed");
706
- if (response.status === 404) {
707
- if (mode.kind === "by-url") {
708
- print(`${colors.red}\u2620 ${displayPath} does not exist${colors.reset}`);
709
- } else {
710
- print(`${colors.red}\u2620 Parent directory does not exist${colors.reset}`);
711
- }
712
- } else if (response.status === 400) {
713
- printError(`Error: ${JSON.stringify(response.data)}`);
714
- } else {
715
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
716
- }
717
- process.exit(1);
718
- }
719
- const action = response.data.created ? "Created" : "Updated";
720
- stopSpinner(true, `${action}: ${response.data.path}`);
721
- }
722
- );
723
- addSpaceOptions(
724
- file.command("mkdir").description("Create a directory").requiredOption("-p, --path <path>", "Directory path").option("-r, --recursive", "Create parent directories if needed")
725
- ).action(
726
- async (options) => {
727
- const spaceParams = runOrExit2(() => resolveSpaceSelector(options));
728
- startSpinner("Creating directory...");
729
- const response = await httpPost(
730
- `/workspaces/${options.workspace}/files/mkdir`,
731
- {
732
- path: options.path,
733
- recursive: options.recursive ?? false,
734
- ...spaceParams
735
- }
736
- );
737
- if (!response.ok) {
738
- stopSpinner(false, "Failed");
739
- if (response.status === 404) {
740
- print(`${colors.red}\u2620 Parent directory does not exist${colors.reset}`);
741
- } else if (response.status === 400) {
742
- printError(`Error: ${JSON.stringify(response.data)}`);
743
- } else {
744
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
745
- }
746
- process.exit(1);
747
- }
748
- const action = response.data.created ? "Created" : "Already exists";
749
- stopSpinner(true, `${action}: ${response.data.path}`);
750
- }
751
- );
752
- addSpaceOptions(
753
- file.command("del").description("Delete a file or empty directory").requiredOption("-p, --path <path>", "File or directory path")
754
- ).action(
755
- async (options) => {
756
- const spaceParams = runOrExit2(() => resolveSpaceSelector(options));
757
- startSpinner("Deleting...");
758
- const response = await httpDelete(
759
- `/workspaces/${options.workspace}/files/delete`,
760
- {
761
- path: options.path,
762
- ...spaceParams
763
- }
764
- );
765
- if (!response.ok) {
766
- stopSpinner(false, "Failed");
767
- if (response.status === 404) {
768
- print(`${colors.red}\u2620 Path not found: ${options.path}${colors.reset}`);
769
- } else if (response.status === 400) {
770
- print(`${colors.red}\u2620 Cannot delete non-empty directory${colors.reset}`);
771
- } else {
772
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
773
- }
774
- process.exit(1);
775
- }
776
- stopSpinner(true, `Deleted: ${response.data.path}`);
777
- }
778
- );
779
- }
780
-
781
- // src/commands/memory.ts
782
- function registerMemoryCommand(program2) {
783
- const memory = program2.command("memory").description("Memory operations");
784
- memory.command("search").description("Search archived agent memory").requiredOption("-w, --workspace <workspaceId>", "Workspace ID").option("--teammate-id <teammateId>", "Search a managed AI teammate memory").option("-l, --limit <limit>", "Maximum number of memory chunks to return", "5").argument("<query>", "Search query").action(
785
- async (query, options) => {
786
- const limit = runOrExit2(() => parseSearchLimit(options.limit, 5, 10));
787
- const teammateId = runOrExit2(() => parseTeammateId(options.teammateId));
788
- startSpinner("Searching memory...");
789
- const response = await httpPost(
790
- `/workspaces/${options.workspace}/memory/search`,
791
- {
792
- query,
793
- limit,
794
- ...teammateId !== void 0 ? { agentId: teammateId } : {}
795
- }
796
- );
797
- if (!response.ok) {
798
- stopSpinner(false, "Failed");
799
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
800
- process.exit(1);
801
- }
802
- const { items } = response.data;
803
- if (items.length === 0) {
804
- stopSpinner(true, "No memory found.");
805
- return;
806
- }
807
- stopSpinner(true, `Found ${items.length} memory chunk(s)`);
808
- for (const item of items) {
809
- print(`${colors.bold}${item.rank}. pipeline=${item.pipelineId} chunk=${item.chunkIndex}${colors.reset}`);
810
- print(`${colors.dim}chunkId=${item.chunkId}${item.contentTruncated ? " truncated=true" : ""}${colors.reset}`);
811
- print(item.content);
812
- print("");
813
- }
814
- }
815
- );
816
- }
817
-
818
- // src/utils/miniapp-db.ts
819
- var MiniappDbOptionsError = class extends Error {
820
- constructor(message) {
821
- super(message);
822
- this.name = "MiniappDbOptionsError";
823
- }
824
- };
825
- var NON_FILTER_QUERY_PARAMS = /* @__PURE__ */ new Set([
826
- "select",
827
- "order",
828
- "limit",
829
- "offset",
830
- "range",
831
- "range-unit"
832
- ]);
833
- var ALLOWED_MINIAPP_DB_EMAIL_DOMAINS = ["@paraflow.com", "@moxt.ai", "@kanyun.com"];
834
- function normalizePostgrestPath(path2) {
835
- const trimmed = path2.trim();
836
- if (!trimmed) {
837
- throw new MiniappDbOptionsError("Error: PostgREST path is required.");
838
- }
839
- return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
840
- }
841
- function buildMiniappDbDataPath(workspaceId, appId, postgrestPath) {
842
- return `/workspaces/${encodeURIComponent(workspaceId)}/miniapps/${encodeURIComponent(appId)}/db/data${normalizePostgrestPath(postgrestPath)}`;
843
- }
844
- function buildMiniappDbSchemaPath(workspaceId, appId) {
845
- return `/workspaces/${encodeURIComponent(workspaceId)}/miniapps/${encodeURIComponent(appId)}/db/schema`;
846
- }
847
- function parseJsonBody(raw) {
848
- let parsed;
849
- try {
850
- parsed = JSON.parse(raw);
851
- } catch (error) {
852
- const detail = error instanceof Error ? error.message : String(error);
853
- throw new MiniappDbOptionsError(`Error: --body must be valid JSON. ${detail}`);
854
- }
855
- if (parsed === null || typeof parsed !== "object" && !Array.isArray(parsed)) {
856
- throw new MiniappDbOptionsError("Error: --body must be a JSON object or array.");
857
- }
858
- return parsed;
859
- }
860
- function hasPostgrestFilter(postgrestPath) {
861
- const normalizedPath = normalizePostgrestPath(postgrestPath);
862
- const parsed = new URL(normalizedPath, "https://postgrest.local");
863
- for (const [name] of parsed.searchParams.entries()) {
864
- if (!NON_FILTER_QUERY_PARAMS.has(name.toLowerCase())) {
865
- return true;
866
- }
867
- }
868
- return false;
869
- }
870
- function assertPostgrestFilter(postgrestPath, method) {
871
- if (!hasPostgrestFilter(postgrestPath)) {
872
- throw new MiniappDbOptionsError(
873
- `Error: ${method.toLowerCase()} requires at least one PostgREST filter query parameter.`
874
- );
875
- }
876
- }
877
- function formatRawResponse(text, pretty) {
878
- if (!pretty || !text) {
879
- return text;
880
- }
881
- try {
882
- return JSON.stringify(JSON.parse(text), null, 2);
883
- } catch {
884
- return text;
885
- }
886
- }
887
- function isAllowedMiniappDbUserEmail(email) {
888
- const normalized = email.trim().toLowerCase();
889
- return ALLOWED_MINIAPP_DB_EMAIL_DOMAINS.some((domain) => normalized.endsWith(domain));
890
- }
891
-
892
- // src/commands/miniapp.ts
893
- function runOrExit3(fn) {
894
- try {
895
- return fn();
896
- } catch (err) {
897
- if (err instanceof MiniappDbOptionsError) {
898
- printError(err.message);
899
- process.exit(1);
900
- }
901
- throw err;
902
- }
903
- }
904
- function addMiniappDbTargetOptions(command) {
905
- return command.requiredOption("-w, --workspace <workspaceId>", "Workspace ID").requiredOption("--app-id <appId>", "Miniapp app ID");
906
- }
907
- function handleRawResponse(response, pretty) {
908
- if (!response.ok) {
909
- printError(`Error [${response.status}]: ${response.text}`);
910
- process.exit(1);
911
- }
912
- print(formatRawResponse(response.text, pretty));
913
- }
914
- async function ensureAllowedMiniappDbUser() {
915
- const response = await httpGet("/users/whoami");
916
- if (!response.ok) {
917
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
918
- process.exit(1);
919
- }
920
- if (!isAllowedMiniappDbUserEmail(response.data.email)) {
921
- printError("Error: miniapp db commands are only available to @paraflow.com, @moxt.ai, or @kanyun.com users.");
922
- process.exit(1);
923
- }
924
- }
925
- async function requestDataApi(method, postgrestPath, options, body) {
926
- await ensureAllowedMiniappDbUser();
927
- const path2 = buildMiniappDbDataPath(options.workspace, options.appId, postgrestPath);
928
- const response = await httpRaw(method, path2, body);
929
- handleRawResponse(response, options.pretty);
930
- }
931
- function registerMiniappCommand(program2) {
932
- const miniapp = program2.command("miniapp", { hidden: true }).description("Miniapp operations");
933
- const db = miniapp.command("db").description("Miniapp database operations");
934
- addMiniappDbTargetOptions(
935
- db.command("schema").description("Print the miniapp database schema SQL")
936
- ).action(async (options) => {
937
- await ensureAllowedMiniappDbUser();
938
- const response = await httpGet(buildMiniappDbSchemaPath(options.workspace, options.appId));
939
- if (!response.ok) {
940
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
941
- process.exit(1);
942
- }
943
- print(response.data.sql);
944
- });
945
- addMiniappDbTargetOptions(
946
- db.command("get").description("Read miniapp data through PostgREST").argument("<path>", "PostgREST path, for example /todos?select=*").option("--pretty", "Pretty-print JSON responses")
947
- ).action(async (postgrestPath, options) => {
948
- await requestDataApi("GET", postgrestPath, options);
949
- });
950
- addMiniappDbTargetOptions(
951
- 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")
952
- ).action(async (postgrestPath, options) => {
953
- const body = runOrExit3(() => parseJsonBody(options.body ?? ""));
954
- await requestDataApi("POST", postgrestPath, options, body);
955
- });
956
- addMiniappDbTargetOptions(
957
- 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")
958
- ).action(async (postgrestPath, options) => {
959
- runOrExit3(() => assertPostgrestFilter(postgrestPath, "PATCH"));
960
- const body = runOrExit3(() => parseJsonBody(options.body ?? ""));
961
- await requestDataApi("PATCH", postgrestPath, options, body);
962
- });
963
- addMiniappDbTargetOptions(
964
- 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")
965
- ).action(async (postgrestPath, options) => {
966
- if (options.yes !== true) {
967
- printError("Error: delete requires --yes.");
968
- process.exit(1);
969
- }
970
- runOrExit3(() => assertPostgrestFilter(postgrestPath, "DELETE"));
971
- await requestDataApi("DELETE", postgrestPath, options);
972
- });
973
- }
974
-
975
- // src/telemetry/config.ts
976
- import * as fs3 from "fs";
977
- import * as os from "os";
978
- import * as path from "path";
979
- function getConfigPath() {
980
- return path.join(os.homedir(), ".moxt", "config.json");
981
- }
982
- function readTelemetryConfig() {
983
- try {
984
- const raw = fs3.readFileSync(getConfigPath(), "utf8");
985
- const parsed = JSON.parse(raw);
986
- return parsed.telemetry ?? {};
987
- } catch {
988
- return {};
989
- }
990
- }
991
- function writeTelemetryConfig(update) {
992
- const configPath = getConfigPath();
993
- let existing = {};
994
- try {
995
- existing = JSON.parse(fs3.readFileSync(configPath, "utf8"));
996
- } catch {
997
- existing = {};
998
- }
999
- const currentTelemetry = existing.telemetry ?? {};
1000
- const next = { ...existing, telemetry: { ...currentTelemetry, ...update } };
1001
- fs3.mkdirSync(path.dirname(configPath), { recursive: true });
1002
- fs3.writeFileSync(configPath, JSON.stringify(next, null, 2));
1003
- }
1004
-
1005
- // src/telemetry/opt-out.ts
1006
- function isCiEnvironment() {
1007
- return process.env.CI === "true" || process.env.CI === "1";
1008
- }
1009
- function isTelemetryDisabled() {
1010
- if (process.env.MOXT_TELEMETRY_DISABLED === "1" || process.env.MOXT_TELEMETRY_DISABLED === "true") {
1011
- return true;
1012
- }
1013
- if (process.env.DO_NOT_TRACK === "1" || process.env.DO_NOT_TRACK === "true") {
1014
- return true;
1015
- }
1016
- return readTelemetryConfig().disabled === true;
1017
- }
1018
-
1019
- // src/commands/telemetry.ts
1020
- function registerTelemetryCommand(program2) {
1021
- const telemetry = program2.command("telemetry").description("Manage Moxt CLI telemetry");
1022
- telemetry.command("status").description("Show telemetry status").action(() => {
1023
- const cfg = readTelemetryConfig();
1024
- 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";
1025
- const state = isTelemetryDisabled() ? "disabled" : "enabled";
1026
- print(`telemetry: ${state}`);
1027
- if (envOverride) {
1028
- print("(disabled via environment variable)");
1029
- } else if (cfg.disabled) {
1030
- print("(disabled via config file)");
1031
- }
1032
- });
1033
- telemetry.command("enable").description("Enable telemetry").action(() => {
1034
- writeTelemetryConfig({ disabled: false });
1035
- print("telemetry: enabled");
1036
- });
1037
- telemetry.command("disable").description("Disable telemetry").action(() => {
1038
- writeTelemetryConfig({ disabled: true });
1039
- print("telemetry: disabled");
1040
- });
1041
- }
1042
-
1043
- // src/commands/whoami.ts
1044
- function registerWhoamiCommand(program2) {
1045
- program2.command("whoami").description("Show current user information").action(async () => {
1046
- startSpinner("Fetching user info...");
1047
- const response = await httpGet("/users/whoami");
1048
- if (response.ok) {
1049
- stopSpinner(true, "Done");
1050
- print(`${colors.bold}Nickname${colors.reset}: ${response.data.nickname}`);
1051
- print(`${colors.bold}Email${colors.reset}: ${response.data.email}`);
1052
- } else {
1053
- stopSpinner(false, "Failed");
1054
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
1055
- process.exit(1);
1056
- }
1057
- });
1058
- }
1059
-
1060
- // src/commands/workspace.ts
1061
- var emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
1062
- function isValidEmail(email) {
1063
- return emailRegex.test(email);
1064
- }
1065
- function registerWorkspaceCommand(program2) {
1066
- const workspace = program2.command("workspace").description("Workspace management");
1067
- workspace.command("list").description("List all workspaces you belong to").action(async () => {
1068
- startSpinner("Fetching workspaces...");
1069
- const response = await httpGet("/workspaces");
1070
- if (response.ok) {
1071
- const { workspaces } = response.data;
1072
- if (workspaces.length === 0) {
1073
- stopSpinner(true, "No workspaces found.");
1074
- return;
1075
- }
1076
- stopSpinner(true, `Found ${workspaces.length} workspace(s)`);
1077
- for (const ws of workspaces) {
1078
- print(`${colors.bold}${ws.workspaceId}${colors.reset} ${ws.name}`);
1079
- }
1080
- } else {
1081
- stopSpinner(false, "Failed");
1082
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
1083
- process.exit(1);
1084
- }
1085
- });
1086
- const members = program2.command("members").description("Manage workspace members");
1087
- members.command("list").description("List all members in a workspace").requiredOption("-w, --workspace <workspaceId>", "Workspace ID").action(async (options) => {
1088
- const { workspace: workspaceId } = options;
1089
- startSpinner("Fetching workspace members...");
1090
- const response = await httpGet(`/workspaces/${workspaceId}/members`);
1091
- if (!response.ok) {
1092
- stopSpinner(false, "Failed to fetch members");
1093
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
1094
- process.exit(1);
1095
- }
1096
- const { members: members2 } = response.data;
1097
- if (members2.length === 0) {
1098
- stopSpinner(true, "No members found.");
1099
- return;
1100
- }
1101
- stopSpinner(true, `Found ${members2.length} member(s)`);
1102
- for (const member of members2) {
1103
- const name = member.displayName || "-";
1104
- print(`${colors.bold}${member.email}${colors.reset} ${name} ${member.role}`);
1105
- }
1106
- });
1107
- members.command("remove").description("Remove members from a workspace").requiredOption("-w, --workspace <workspaceId>", "Workspace ID").argument("<emails>", "Emails to remove (comma-separated)").action(async (emailsArg, options) => {
1108
- const { workspace: workspaceId } = options;
1109
- const emails = emailsArg.split(",").map((e) => e.trim()).filter(Boolean);
1110
- if (emails.length === 0) {
1111
- printError("No valid emails provided");
1112
- process.exit(1);
1113
- }
1114
- const invalidEmails = emails.filter((e) => !isValidEmail(e));
1115
- if (invalidEmails.length > 0) {
1116
- for (const email of invalidEmails) {
1117
- printError(`Invalid email format: ${email}`);
1118
- }
1119
- process.exit(1);
1120
- }
1121
- startSpinner("Fetching workspace members...");
1122
- const membersResponse = await httpGet(`/workspaces/${workspaceId}/members`);
1123
- if (!membersResponse.ok) {
1124
- stopSpinner(false, "Failed to fetch members");
1125
- printError(`Error [${membersResponse.status}]: ${JSON.stringify(membersResponse.data)}`);
1126
- process.exit(1);
1127
- }
1128
- stopSpinner(true, "Members fetched");
1129
- const { members: members2 } = membersResponse.data;
1130
- const emailToMember = new Map(members2.map((m) => [m.email.toLowerCase(), m]));
1131
- for (const email of emails) {
1132
- const member = emailToMember.get(email.toLowerCase());
1133
- if (!member) {
1134
- print(`${colors.red}\u2717${colors.reset} ${email} - not found in workspace`);
1135
- continue;
1136
- }
1137
- const deleteResponse = await httpDelete(`/workspaces/${workspaceId}/members/${member.userId}`);
1138
- if (deleteResponse.ok) {
1139
- print(`${colors.green}\u2713${colors.reset} ${email} - removed`);
1140
- } else {
1141
- print(`${colors.red}\u2717${colors.reset} ${email} - failed: ${JSON.stringify(deleteResponse.data)}`);
1142
- }
1143
- }
1144
- });
1145
- const space = program2.command("space").description("Manage spaces");
1146
- space.command("list").description("List accessible spaces in a workspace").requiredOption("-w, --workspace <workspaceId>", "Workspace ID").action(async (options) => {
1147
- const { workspace: workspaceId } = options;
1148
- startSpinner("Fetching spaces...");
1149
- const response = await httpGet(`/workspaces/${workspaceId}/spaces`);
1150
- if (!response.ok) {
1151
- stopSpinner(false, "Failed to fetch spaces");
1152
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
1153
- process.exit(1);
1154
- }
1155
- const { spaces } = response.data;
1156
- if (spaces.length === 0) {
1157
- stopSpinner(true, "No spaces found.");
1158
- return;
1159
- }
1160
- stopSpinner(true, `Found ${spaces.length} space(s)`);
1161
- print(
1162
- `${colors.bold}TYPE${colors.reset} ${colors.bold}TEAM_SPACE_ID${colors.reset} ${colors.bold}TEAMMATE_ID${colors.reset} ${colors.bold}NAME${colors.reset}`
1163
- );
1164
- for (const s of spaces) {
1165
- const teamSpaceId = s.teamSpaceId ?? "";
1166
- const teammateId = s.agentId != null ? String(s.agentId) : "";
1167
- print(`${s.type} ${teamSpaceId} ${teammateId} ${s.name}`);
1168
- }
1169
- });
1170
- }
1171
-
1172
- // src/commands/workflow.ts
1173
- import * as fs4 from "fs";
1174
- import { TextDecoder as TextDecoder2 } from "util";
1175
- var MAX_DESC_LENGTH = 5e3;
1176
- var MAX_COMMENT_CONTENT_LENGTH = 5e3;
1177
- var MAX_COMMENT_CONTENT_BYTES = MAX_COMMENT_CONTENT_LENGTH * 4;
1178
- var WorkflowOptionsError = class extends Error {
1179
- constructor(message) {
1180
- super(message);
1181
- this.name = "WorkflowOptionsError";
1182
- }
1183
- };
1184
- function runOrExit4(fn) {
1185
- try {
1186
- return fn();
1187
- } catch (err) {
1188
- if (err instanceof WorkflowOptionsError || err instanceof SpaceOptionsError || err instanceof SearchOptionsError) {
1189
- printError(err.message);
1190
- process.exit(1);
1191
- }
1192
- throw err;
1193
- }
1194
- }
1195
- function addWorkspaceOption(command) {
1196
- return command.requiredOption("-w, --workspace <workspaceId>", "Workspace ID");
1197
- }
1198
- function addSpaceOptions2(command) {
1199
- return addWorkspaceOption(command).option("-s, --space <name>", "Space name (personal or teamspace name)").option("--personal", "Use personal space (default)").option("--team-space-id <teamSpaceId>", "Team space ID").option("--teammate-id <teammateId>", "Teammate ID (teammate space)");
1200
- }
1201
- function addAssigneeOptions(command) {
1202
- return command.option("--human-id <humanId>", "Human assignee ID").option("--assistant-id <assistantId>", "AI assistant assignee ID").option("--teammate-id <teammateId>", "AI teammate assignee ID");
1203
- }
1204
- function addPreferredAssigneeOptions(command) {
1205
- return command.option("--preferred-human-id <humanId>", "Preferred human assignee ID").option("--preferred-assistant-id <assistantId>", "Preferred AI assistant assignee ID").option("--preferred-teammate-id <teammateId>", "Preferred AI teammate assignee ID");
1206
- }
1207
- function parsePositiveInteger(raw, label) {
1208
- const parsed = Number.parseInt(raw, 10);
1209
- if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== raw) {
1210
- throw new WorkflowOptionsError(`Error: ${label} must be a positive integer, got "${raw}".`);
1211
- }
1212
- return parsed;
1213
- }
1214
- function parseOptionalPositiveInteger(raw, label) {
1215
- if (raw == null || raw === "") return void 0;
1216
- return parsePositiveInteger(raw, label);
1217
- }
1218
- function parseStatusType(raw) {
1219
- if (raw == null || raw === "") return void 0;
1220
- const parsed = Number.parseInt(raw, 10);
1221
- if ((parsed === 1 || parsed === 2 || parsed === 3) && String(parsed) === raw) return parsed;
1222
- throw new WorkflowOptionsError("Error: --type must be one of 1 (todo), 2 (in-progress), or 3 (done).");
1223
- }
1224
- function parseRequiredStatusType(raw) {
1225
- const value = parseStatusType(raw);
1226
- if (value === void 0) {
1227
- throw new WorkflowOptionsError("Error: --type is required.");
1228
- }
1229
- return value;
1230
- }
1231
- function parsePriority(raw) {
1232
- if (raw == null || raw === "") return void 0;
1233
- if (raw === "urgent") return 0;
1234
- if (raw === "high") return 1;
1235
- if (raw === "medium") return 2;
1236
- if (raw === "low") return 3;
1237
- throw new WorkflowOptionsError('Error: --priority must be "urgent", "high", "medium", or "low".');
1238
- }
1239
- function parseRequiredPriority(raw) {
1240
- return parsePriority(raw ?? "medium") ?? 2;
1241
- }
1242
- function parseWorkflowScope(raw) {
1243
- if (raw == null || raw === "") return "all";
1244
- if (raw === "all" || raw === "owner_is_me") return raw;
1245
- throw new WorkflowOptionsError('Error: --scope must be "all" or "owner_is_me".');
1246
- }
1247
- function parseTaskScope(raw) {
1248
- if (raw == null || raw === "") return "all";
1249
- if (raw === "all" || raw === "assigned_to_me" || raw === "subscribed_by_me" || raw === "owner_is_me") {
1250
- return raw;
1251
- }
1252
- throw new WorkflowOptionsError(
1253
- 'Error: --scope must be "all", "assigned_to_me", "subscribed_by_me", or "owner_is_me".'
1254
- );
1255
- }
1256
- function parseFileIds(raw, label = "--file-ids") {
1257
- if (raw == null || raw === "") return void 0;
1258
- const ids = raw.split(",").map((item) => item.trim()).filter(Boolean);
1259
- if (ids.length === 0) {
1260
- throw new WorkflowOptionsError(`Error: ${label} must include at least one file ID.`);
1261
- }
1262
- return ids;
1263
- }
1264
- function readDescFile(path2) {
1265
- if (path2 == null || path2 === "") return void 0;
1266
- if (!fs4.existsSync(path2)) {
1267
- throw new WorkflowOptionsError(`Error: desc file not found: ${path2}`);
1268
- }
1269
- const stat = fs4.statSync(path2);
1270
- if (!stat.isFile()) {
1271
- throw new WorkflowOptionsError(`Error: desc file is not a file: ${path2}`);
1272
- }
1273
- const buffer2 = fs4.readFileSync(path2);
1274
- if (isBinaryContent(buffer2)) {
1275
- throw new WorkflowOptionsError("Error: desc file must be UTF-8 text, not binary content.");
1276
- }
1277
- const content = buffer2.toString("utf8");
1278
- if (content.length > MAX_DESC_LENGTH) {
1279
- throw new WorkflowOptionsError(`Error: desc file must be at most ${MAX_DESC_LENGTH} characters.`);
1280
- }
1281
- return content;
1282
- }
1283
- function readCommentContentFile2(path2) {
1284
- if (!fs4.existsSync(path2)) {
1285
- throw new WorkflowOptionsError(`Error: comment content file not found: ${path2}`);
1286
- }
1287
- const stat = fs4.statSync(path2);
1288
- if (!stat.isFile()) {
1289
- throw new WorkflowOptionsError(`Error: comment content path is not a file: ${path2}`);
1290
- }
1291
- if (stat.size > MAX_COMMENT_CONTENT_BYTES) {
1292
- throw new WorkflowOptionsError(
1293
- `Error: comment content file must be at most ${MAX_COMMENT_CONTENT_LENGTH} characters.`
1294
- );
1295
- }
1296
- const buffer2 = fs4.readFileSync(path2);
1297
- if (buffer2.includes(0)) {
1298
- throw new WorkflowOptionsError("Error: comment content file must not contain NUL bytes.");
1299
- }
1300
- if (isBinaryContent(buffer2)) {
1301
- throw new WorkflowOptionsError("Error: comment content file must be UTF-8 text, not binary content.");
1302
- }
1303
- let content;
1304
- try {
1305
- content = new TextDecoder2("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer2);
1306
- } catch {
1307
- throw new WorkflowOptionsError("Error: comment content file must contain valid UTF-8 text.");
1308
- }
1309
- if (content.length === 0) {
1310
- throw new WorkflowOptionsError("Error: comment content file must not be empty.");
1311
- }
1312
- if (content.length > MAX_COMMENT_CONTENT_LENGTH) {
1313
- throw new WorkflowOptionsError(
1314
- `Error: comment content file must be at most ${MAX_COMMENT_CONTENT_LENGTH} characters.`
1315
- );
1316
- }
1317
- return content;
1318
- }
1319
- function parseAssigneeBody(options, allowClear) {
1320
- const hasClear = options.clear === true;
1321
- const humanId = parseOptionalPositiveInteger(options.humanId, "--human-id");
1322
- const assistantId = parseOptionalPositiveInteger(options.assistantId, "--assistant-id");
1323
- const teammateId = parseOptionalPositiveInteger(options.teammateId, "--teammate-id");
1324
- const count = (humanId !== void 0 ? 1 : 0) + (assistantId !== void 0 ? 1 : 0) + (teammateId !== void 0 ? 1 : 0);
1325
- if (hasClear && !allowClear) {
1326
- throw new WorkflowOptionsError("Error: --clear is not supported here.");
1327
- }
1328
- if (hasClear && count > 0) {
1329
- throw new WorkflowOptionsError("Error: --clear cannot be used with assignee ID options.");
1330
- }
1331
- if (count > 1) {
1332
- throw new WorkflowOptionsError("Error: assignee ID options are mutually exclusive.");
1333
- }
1334
- if (hasClear) return {};
1335
- if (humanId !== void 0) return { assigneeHumanId: humanId };
1336
- if (assistantId !== void 0) return { assigneeAiAssistantId: assistantId };
1337
- if (teammateId !== void 0) return { assigneeAiTeammateId: teammateId };
1338
- return {};
1339
- }
1340
- function parsePreferredAssigneeBody(options) {
1341
- const hasClear = options.clearPreferredAssignee === true;
1342
- const humanId = parseOptionalPositiveInteger(options.preferredHumanId, "--preferred-human-id");
1343
- const assistantId = parseOptionalPositiveInteger(options.preferredAssistantId, "--preferred-assistant-id");
1344
- const teammateId = parseOptionalPositiveInteger(options.preferredTeammateId, "--preferred-teammate-id");
1345
- const count = (humanId !== void 0 ? 1 : 0) + (assistantId !== void 0 ? 1 : 0) + (teammateId !== void 0 ? 1 : 0);
1346
- if (hasClear && count > 0) {
1347
- throw new WorkflowOptionsError("Error: --clear-preferred-assignee cannot be used with preferred assignee ID options.");
1348
- }
1349
- if (count > 1) {
1350
- throw new WorkflowOptionsError("Error: preferred assignee ID options are mutually exclusive.");
1351
- }
1352
- if (hasClear) return { preferredAssigneeHumanId: null };
1353
- if (humanId !== void 0) return { preferredAssigneeHumanId: humanId };
1354
- if (assistantId !== void 0) return { preferredAssigneeAiAssistantId: assistantId };
1355
- if (teammateId !== void 0) return { preferredAssigneeAiTeammateId: teammateId };
1356
- return {};
1357
- }
1358
- function assertNonEmptyBody(body) {
1359
- if (Object.keys(body).length === 0) {
1360
- throw new WorkflowOptionsError("Error: at least one update option must be provided.");
1361
- }
1362
- }
1363
- function buildQuery(params) {
1364
- const query = new URLSearchParams();
1365
- for (const [key, value] of Object.entries(params)) {
1366
- if (value !== void 0) {
1367
- query.set(key, String(value));
1368
- }
1369
- }
1370
- const text = query.toString();
1371
- return text ? `?${text}` : "";
1372
- }
1373
- function failResponse(response) {
1374
- printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`);
1375
- process.exit(1);
1376
- }
1377
- function priorityLabel(value) {
1378
- switch (value) {
1379
- case 0:
1380
- return "urgent";
1381
- case 1:
1382
- return "high";
1383
- case 2:
1384
- return "medium";
1385
- case 3:
1386
- return "low";
1387
- default: {
1388
- const unsupportedValue = value;
1389
- throw new Error(`Unsupported workflow task priority: ${String(unsupportedValue)}`);
1390
- }
1391
- }
1392
- }
1393
- function statusTypeLabel(value) {
1394
- switch (value) {
1395
- case 1:
1396
- return "todo";
1397
- case 2:
1398
- return "in-progress";
1399
- case 3:
1400
- return "done";
1401
- default: {
1402
- const unsupportedValue = value;
1403
- throw new Error(`Unsupported workflow status type: ${String(unsupportedValue)}`);
1404
- }
1405
- }
1406
- }
1407
- function formatAssignee(assignee) {
1408
- if (!assignee) return "-";
1409
- if (assignee.type === "human") return assignee.displayName ?? `human:${assignee.humanId}`;
1410
- if (assignee.type === "assistant") return assignee.displayName ?? `assistant:${assignee.aiAssistantId}`;
1411
- if (assignee.type === "teammate") return assignee.displayName ?? `teammate:${assignee.aiTeammateId}`;
1412
- return "unknown";
1413
- }
1414
- function printWorkflow(item) {
1415
- print(`${colors.bold}${item.fileId}${colors.reset} owner=${item.ownerHumanId ?? "-"} desc=${item.desc ?? "-"}`);
1416
- }
1417
- function indentation2(size) {
1418
- return " ".repeat(size);
1419
- }
1420
- function escapeTerminalControlCharacters2(value) {
1421
- return value.replace(/\r\n/g, "\n").replace(
1422
- /[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,
1423
- (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
1424
- );
1425
- }
1426
- function formatDetailScalar2(value) {
1427
- if (value === null) return "null";
1428
- if (typeof value === "string") {
1429
- const escaped = escapeTerminalControlCharacters2(value);
1430
- if (escaped === "") return '""';
1431
- if (/\n/.test(escaped)) return JSON.stringify(escaped);
1432
- return escaped;
1433
- }
1434
- return String(value);
1435
- }
1436
- function printDetailField2(name, value, indent = 0) {
1437
- print(`${indentation2(indent)}${name}: ${formatDetailScalar2(value)}`);
1438
- }
1439
- function printDetailTextField2(name, value, indent = 0) {
1440
- if (value === null || value === "") {
1441
- printDetailField2(name, value, indent);
1442
- return;
1443
- }
1444
- const escaped = escapeTerminalControlCharacters2(value);
1445
- print(`${indentation2(indent)}${name}:`);
1446
- for (const line of escaped.split("\n")) {
1447
- print(`${indentation2(indent + 2)}${line}`);
1448
- }
1449
- }
1450
- function printAssigneeDetail(name, assignee, indent = 0) {
1451
- if (assignee === null) {
1452
- printDetailField2(name, null, indent);
1453
- return;
1454
- }
1455
- print(`${indentation2(indent)}${name}:`);
1456
- printDetailField2("type", assignee.type, indent + 2);
1457
- switch (assignee.type) {
1458
- case "human":
1459
- printDetailField2("humanId", assignee.humanId, indent + 2);
1460
- printDetailField2("displayName", assignee.displayName, indent + 2);
1461
- printDetailField2("avatarUrl", assignee.avatarUrl, indent + 2);
1462
- return;
1463
- case "assistant":
1464
- printDetailField2("aiAssistantId", assignee.aiAssistantId, indent + 2);
1465
- printDetailField2("displayName", assignee.displayName, indent + 2);
1466
- printDetailField2("avatarUrl", assignee.avatarUrl, indent + 2);
1467
- return;
1468
- case "teammate":
1469
- printDetailField2("aiTeammateId", assignee.aiTeammateId, indent + 2);
1470
- printDetailField2("displayName", assignee.displayName, indent + 2);
1471
- printDetailField2("avatarUrl", assignee.avatarUrl, indent + 2);
1472
- return;
1473
- case "unknown":
1474
- printDetailField2("humanId", assignee.humanId, indent + 2);
1475
- printDetailField2("aiAssistantId", assignee.aiAssistantId, indent + 2);
1476
- printDetailField2("aiTeammateId", assignee.aiTeammateId, indent + 2);
1477
- }
1478
- }
1479
- function printStatusRemainingFields(item, indent) {
1480
- printDetailField2("name", item.name, indent);
1481
- printDetailTextField2("desc", item.desc, indent);
1482
- printDetailField2("type", `${item.type} (${statusTypeLabel(item.type)})`, indent);
1483
- printAssigneeDetail("preferredAssignee", item.preferredAssignee, indent);
1484
- printDetailField2("order", item.order, indent);
1485
- }
1486
- function printStatusDetail(item) {
1487
- print(`${colors.bold}Status${colors.reset}`);
1488
- printDetailField2("scopedId", item.scopedId);
1489
- printStatusRemainingFields(item, 0);
1490
- }
1491
- function printWorkflowDetail(item) {
1492
- print(`${colors.bold}Workflow${colors.reset}`);
1493
- printDetailField2("fileId", item.fileId);
1494
- printDetailField2("ownerHumanId", item.ownerHumanId);
1495
- printDetailTextField2("desc", item.desc);
1496
- if (item.statusList.length === 0) {
1497
- print("statusList: []");
1498
- } else {
1499
- print("statusList:");
1500
- for (const status of item.statusList) {
1501
- print(` - scopedId: ${status.scopedId}`);
1502
- printStatusRemainingFields(status, 4);
1503
- }
1504
- }
1505
- if (item.transitions.length === 0) {
1506
- print("transitions: []");
1507
- } else {
1508
- print("transitions:");
1509
- for (const transition of item.transitions) {
1510
- print(` - statusFromScopedId: ${transition.statusFromScopedId}`);
1511
- printDetailField2("statusToScopedId", transition.statusToScopedId, 4);
1512
- }
1513
- }
1514
- }
1515
- function printTaskSummary(item) {
1516
- const runIds = item.runningAgentRuns.map((run) => run.pipelineId).join(",") || "-";
1517
- print(
1518
- `${colors.bold}#${item.scopedId}${colors.reset} ${item.title} status=${item.statusScopedId} priority=${priorityLabel(item.priority)} assignee=${formatAssignee(item.assignee)} runs=${runIds}`
1519
- );
1520
- }
1521
- function printTaskDetail(item) {
1522
- print(`${colors.bold}Task${colors.reset}`);
1523
- printDetailField2("scopedId", item.scopedId);
1524
- printDetailField2("workflowFileId", item.workflowFileId);
1525
- printDetailField2("ownerHumanId", item.ownerHumanId);
1526
- printDetailField2("title", item.title);
1527
- printDetailTextField2("desc", item.desc);
1528
- printDetailField2("statusScopedId", item.statusScopedId);
1529
- printDetailField2("priority", `${item.priority} (${priorityLabel(item.priority)})`);
1530
- printAssigneeDetail("assignee", item.assignee);
1531
- if (item.linkedFileIds.length === 0) {
1532
- print("linkedFileIds: []");
1533
- } else {
1534
- print("linkedFileIds:");
1535
- for (const fileId of item.linkedFileIds) print(` - ${fileId}`);
1536
- }
1537
- printDetailField2("subscribed", item.subscribed);
1538
- if (item.runningAgentRuns.length === 0) {
1539
- print("runningAgentRuns: []");
1540
- } else {
1541
- print("runningAgentRuns:");
1542
- for (const run of item.runningAgentRuns) {
1543
- print(` - pipelineId: ${run.pipelineId}`);
1544
- printAssigneeDetail("executor", run.executor, 4);
1545
- }
1546
- }
1547
- printDetailField2("createdAt", item.createdAt);
1548
- printDetailField2("latestActAt", item.latestActAt);
1549
- }
1550
- function printCommentDetail(item) {
1551
- print(`${colors.bold}Comment${colors.reset}`);
1552
- printDetailField2("id", item.id);
1553
- printDetailField2("workflowFileId", item.workflowFileId);
1554
- printDetailField2("workflowTaskScopedId", item.workflowTaskScopedId);
1555
- printDetailTextField2("content", item.content);
1556
- printAssigneeDetail("createdBy", item.createdBy);
1557
- printDetailField2("createdAt", item.createdAt);
1558
- printDetailField2("updatedAt", item.updatedAt);
1559
- }
1560
- function registerWorkflowCommand(program2) {
1561
- const workflow = program2.command("workflow").description("Workflow operations");
1562
- addWorkspaceOption(
1563
- workflow.command("list").description("List accessible workflows").option("--scope <scope>", "Workflow scope: all or owner_is_me", "all")
1564
- ).action(async (options) => {
1565
- const scope = runOrExit4(() => parseWorkflowScope(options.scope));
1566
- startSpinner("Fetching workflows...");
1567
- const response = await httpGet(
1568
- `/workspaces/${options.workspace}/workflows${buildQuery({ scope })}`
1569
- );
1570
- if (!response.ok) {
1571
- stopSpinner(false, "Failed");
1572
- failResponse(response);
1573
- }
1574
- if (response.data.workflows.length === 0) {
1575
- stopSpinner(true, "No workflows found.");
1576
- return;
1577
- }
1578
- stopSpinner(true, `Found ${response.data.workflows.length} workflow(s)`);
1579
- for (const item of response.data.workflows) printWorkflow(item);
1580
- });
1581
- addSpaceOptions2(
1582
- workflow.command("create").description("Create a blank workflow").requiredOption("-p, --path <path>", "Target .workflow path").option("--desc-file <localPath>", "Local UTF-8 text file for workflow description").option("--owner-human-id <humanId>", "Workflow owner human ID")
1583
- ).action(async (options) => {
1584
- const body = runOrExit4(() => {
1585
- const next = {
1586
- path: options.path,
1587
- ...resolveSpaceSelector(options)
1588
- };
1589
- const desc = readDescFile(options.descFile);
1590
- if (desc !== void 0) next.desc = desc;
1591
- const ownerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
1592
- if (ownerHumanId !== void 0) next.ownerHumanId = ownerHumanId;
1593
- return next;
1594
- });
1595
- startSpinner("Creating workflow...");
1596
- const response = await httpPost(`/workspaces/${options.workspace}/workflows`, body);
1597
- if (!response.ok) {
1598
- stopSpinner(false, "Failed");
1599
- failResponse(response);
1600
- }
1601
- stopSpinner(true, "Workflow created");
1602
- printWorkflow(response.data);
1603
- });
1604
- addWorkspaceOption(workflow.command("get").description("Get a workflow").argument("<workflowFileId>")).action(
1605
- async (workflowFileId, options) => {
1606
- startSpinner("Fetching workflow...");
1607
- const response = await httpGet(
1608
- `/workspaces/${options.workspace}/workflows/${workflowFileId}`
1609
- );
1610
- if (!response.ok) {
1611
- stopSpinner(false, "Failed");
1612
- failResponse(response);
1613
- }
1614
- stopSpinner(true, "Workflow fetched");
1615
- printWorkflowDetail(response.data);
1616
- }
1617
- );
1618
- addWorkspaceOption(
1619
- workflow.command("update").description("Update workflow metadata").argument("<workflowFileId>").option("--desc-file <localPath>", "Local UTF-8 text file for workflow description").option("--owner-human-id <humanId>", "Workflow owner human ID")
1620
- ).action(async (workflowFileId, options) => {
1621
- const body = runOrExit4(() => {
1622
- const next = {};
1623
- const desc = readDescFile(options.descFile);
1624
- if (desc !== void 0) next.desc = desc;
1625
- const ownerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
1626
- if (ownerHumanId !== void 0) next.ownerHumanId = ownerHumanId;
1627
- assertNonEmptyBody(next);
1628
- return next;
1629
- });
1630
- startSpinner("Updating workflow...");
1631
- const response = await httpPatch(`/workspaces/${options.workspace}/workflows/${workflowFileId}`, body);
1632
- if (!response.ok) {
1633
- stopSpinner(false, "Failed");
1634
- failResponse(response);
1635
- }
1636
- stopSpinner(true, "Workflow updated");
1637
- printWorkflow(response.data);
1638
- });
1639
- addWorkspaceOption(
1640
- workflow.command("delete").description("Delete a workflow").argument("<workflowFileId>").option("--message <message>", "Commit message")
1641
- ).action(async (workflowFileId, options) => {
1642
- startSpinner("Deleting workflow...");
1643
- const response = await httpDelete(
1644
- `/workspaces/${options.workspace}/workflows/${workflowFileId}`,
1645
- options.message ? { message: options.message } : {}
1646
- );
1647
- if (!response.ok) {
1648
- stopSpinner(false, "Failed");
1649
- failResponse(response);
1650
- }
1651
- stopSpinner(true, `Deleted: ${response.data.fileId}`);
1652
- });
1653
- addWorkspaceOption(workflow.command("duplicate").description("Duplicate a workflow").argument("<workflowFileId>")).action(
1654
- async (workflowFileId, options) => {
1655
- startSpinner("Duplicating workflow...");
1656
- const response = await httpPost(
1657
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/duplicate`,
1658
- {}
1659
- );
1660
- if (!response.ok) {
1661
- stopSpinner(false, "Failed");
1662
- failResponse(response);
1663
- }
1664
- stopSpinner(true, "Workflow duplicated");
1665
- printWorkflow(response.data);
1666
- }
1667
- );
1668
- registerStatusCommands(workflow);
1669
- registerTransitionCommands(workflow);
1670
- registerTaskCommands(workflow);
1671
- registerCommentCommands(workflow);
1672
- registerRunCommands(workflow);
1673
- }
1674
- function registerStatusCommands(workflow) {
1675
- const status = workflow.command("status").description("Workflow status operations");
1676
- addPreferredAssigneeOptions(
1677
- addWorkspaceOption(
1678
- status.command("create").description("Create a workflow status").argument("<workflowFileId>").requiredOption("--name <name>", "Status name").requiredOption("--type <type>", "Status type value: 1=todo, 2=in-progress, 3=done").option("--desc-file <localPath>", "Local UTF-8 text file for status description")
1679
- )
1680
- ).action(
1681
- async (workflowFileId, options) => {
1682
- const body = runOrExit4(() => {
1683
- const next = {
1684
- name: options.name,
1685
- type: parseRequiredStatusType(options.type)
1686
- };
1687
- const desc = readDescFile(options.descFile);
1688
- if (desc !== void 0) next.desc = desc;
1689
- Object.assign(next, parsePreferredAssigneeBody(options));
1690
- return next;
1691
- });
1692
- startSpinner("Creating status...");
1693
- const response = await httpPost(
1694
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/statuses`,
1695
- body
1696
- );
1697
- if (!response.ok) {
1698
- stopSpinner(false, "Failed");
1699
- failResponse(response);
1700
- }
1701
- stopSpinner(true, "Status created");
1702
- printStatusDetail(response.data);
1703
- }
1704
- );
1705
- addPreferredAssigneeOptions(
1706
- addWorkspaceOption(
1707
- status.command("update").description("Update a workflow status").argument("<workflowFileId>").argument("<statusScopedId>").option("--name <name>", "Status name").option("--type <type>", "Status type value: 1=todo, 2=in-progress, 3=done").option("--desc-file <localPath>", "Local UTF-8 text file for status description").option("--clear-desc", "Clear status description").option("--clear-preferred-assignee", "Clear preferred assignee")
1708
- )
1709
- ).action(
1710
- async (workflowFileId, statusScopedId, options) => {
1711
- const body = runOrExit4(() => {
1712
- if (options.descFile && options.clearDesc) {
1713
- throw new WorkflowOptionsError("Error: --desc-file cannot be used with --clear-desc.");
1714
- }
1715
- const next = {};
1716
- if (options.name) next.name = options.name;
1717
- const type = parseStatusType(options.type);
1718
- if (type !== void 0) next.type = type;
1719
- const desc = readDescFile(options.descFile);
1720
- if (desc !== void 0) next.desc = desc;
1721
- if (options.clearDesc) next.desc = null;
1722
- Object.assign(next, parsePreferredAssigneeBody(options));
1723
- assertNonEmptyBody(next);
1724
- return next;
1725
- });
1726
- const id = runOrExit4(() => parsePositiveInteger(statusScopedId, "statusScopedId"));
1727
- startSpinner("Updating status...");
1728
- const response = await httpPatch(
1729
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/statuses/${id}`,
1730
- body
1731
- );
1732
- if (!response.ok) {
1733
- stopSpinner(false, "Failed");
1734
- failResponse(response);
1735
- }
1736
- stopSpinner(true, "Status updated");
1737
- printStatusDetail(response.data);
1738
- }
1739
- );
1740
- addWorkspaceOption(
1741
- status.command("move-after").description("Move a workflow status after another status").argument("<workflowFileId>").argument("<statusScopedId>").option("--after <statusScopedId>", "Anchor status scoped ID").option("--first", "Move to first position")
1742
- ).action(
1743
- async (workflowFileId, statusScopedId, options) => {
1744
- const { id, anchoredStatusScopedId } = runOrExit4(() => {
1745
- if (options.after && options.first) {
1746
- throw new WorkflowOptionsError("Error: --after cannot be used with --first.");
1747
- }
1748
- if (!options.after && !options.first) {
1749
- throw new WorkflowOptionsError("Error: either --after or --first is required.");
1750
- }
1751
- return {
1752
- id: parsePositiveInteger(statusScopedId, "statusScopedId"),
1753
- anchoredStatusScopedId: options.first ? null : parsePositiveInteger(options.after, "--after")
1754
- };
1755
- });
1756
- startSpinner("Moving status...");
1757
- const response = await httpPost(
1758
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/statuses/${id}/move-after`,
1759
- { anchoredStatusScopedId }
1760
- );
1761
- if (!response.ok) {
1762
- stopSpinner(false, "Failed");
1763
- failResponse(response);
1764
- }
1765
- stopSpinner(true, "Status moved");
1766
- }
1767
- );
1768
- addWorkspaceOption(
1769
- status.command("delete").description("Delete a workflow status").argument("<workflowFileId>").argument("<statusScopedId>")
1770
- ).action(async (workflowFileId, statusScopedId, options) => {
1771
- const id = runOrExit4(() => parsePositiveInteger(statusScopedId, "statusScopedId"));
1772
- startSpinner("Deleting status...");
1773
- const response = await httpDelete(
1774
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/statuses/${id}`
1775
- );
1776
- if (!response.ok) {
1777
- stopSpinner(false, "Failed");
1778
- failResponse(response);
1779
- }
1780
- stopSpinner(true, `Deleted: ${response.data.scopedId}`);
1781
- });
1782
- }
1783
- function registerTransitionCommands(workflow) {
1784
- const transition = workflow.command("transition").description("Workflow transition operations");
1785
- for (const action of ["create", "delete"]) {
1786
- addWorkspaceOption(
1787
- transition.command(action).description(`${action === "create" ? "Create" : "Delete"} a workflow transition`).argument("<workflowFileId>").requiredOption("--from <statusScopedId>", "Source status scoped ID").requiredOption("--to <statusScopedId>", "Target status scoped ID")
1788
- ).action(async (workflowFileId, options) => {
1789
- const body = runOrExit4(() => ({
1790
- statusFromScopedId: parsePositiveInteger(options.from, "--from"),
1791
- statusToScopedId: parsePositiveInteger(options.to, "--to")
1792
- }));
1793
- startSpinner(`${action === "create" ? "Creating" : "Deleting"} transition...`);
1794
- const response = action === "create" ? await httpPost(
1795
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/transitions`,
1796
- body
1797
- ) : await httpDelete(
1798
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/transitions`,
1799
- body
1800
- );
1801
- if (!response.ok) {
1802
- stopSpinner(false, "Failed");
1803
- failResponse(response);
1804
- }
1805
- stopSpinner(true, action === "create" ? "Transition created" : "Transition deleted");
1806
- print(`${response.data.statusFromScopedId} -> ${response.data.statusToScopedId}`);
1807
- });
1808
- }
1809
- }
1810
- function registerTaskCommands(workflow) {
1811
- const task = workflow.command("task").description("Workflow task operations");
1812
- addWorkspaceOption(
1813
- task.command("list").description("List workflow tasks").option("--workflow-file-id <workflowFileId>", "Filter by workflow file ID").option("--scope <scope>", "Task scope", "all").option("-l, --limit <limit>", "Maximum number of tasks to return", "20").option("--cursor <cursor>", "Pagination cursor")
1814
- ).action(
1815
- async (options) => {
1816
- const query = runOrExit4(() => buildQuery({
1817
- scope: parseTaskScope(options.scope),
1818
- limit: parseSearchLimit(options.limit, 20, 100),
1819
- cursor: options.cursor,
1820
- workflowFileId: options.workflowFileId
1821
- }));
1822
- startSpinner("Fetching workflow tasks...");
1823
- const response = await httpGet(`/workspaces/${options.workspace}/workflow-tasks-v2${query}`);
1824
- if (!response.ok) {
1825
- stopSpinner(false, "Failed");
1826
- failResponse(response);
1827
- }
1828
- if (response.data.tasks.length === 0) {
1829
- stopSpinner(true, "No workflow tasks found.");
1830
- return;
1831
- }
1832
- stopSpinner(true, `Found ${response.data.tasks.length} task(s)`);
1833
- for (const item of response.data.tasks) printTaskSummary(item);
1834
- if (response.data.nextCursor) print(`${colors.dim}nextCursor=${response.data.nextCursor}${colors.reset}`);
1835
- }
1836
- );
1837
- addWorkspaceOption(
1838
- task.command("get").description("Get a workflow task").argument("<workflowFileId>").argument("<taskScopedId>")
1839
- ).action(async (workflowFileId, taskScopedId, options) => {
1840
- const id = runOrExit4(() => parsePositiveInteger(taskScopedId, "taskScopedId"));
1841
- startSpinner("Fetching task...");
1842
- const response = await getWorkflowTask(options.workspace, workflowFileId, id);
1843
- if (!response.ok) {
1844
- stopSpinner(false, "Failed");
1845
- failResponse(response);
1846
- }
1847
- stopSpinner(true, "Task fetched");
1848
- printTaskDetail(response.data);
1849
- });
1850
- addAssigneeOptions(
1851
- addWorkspaceOption(
1852
- task.command("create").description("Create a workflow task").argument("<workflowFileId>").requiredOption("--title <title>", "Task title").requiredOption("--status <statusScopedId>", "Status scoped ID").option("--priority <priority>", "Priority: urgent, high, medium, or low", "medium").option("--desc-file <localPath>", "Local UTF-8 text file for task description").option("--owner-human-id <humanId>", "Task owner human ID")
1853
- )
1854
- ).action(
1855
- async (workflowFileId, options) => {
1856
- const body = runOrExit4(() => {
1857
- const next = {
1858
- title: options.title,
1859
- statusScopedId: parsePositiveInteger(options.status, "--status"),
1860
- priority: parseRequiredPriority(options.priority)
1861
- };
1862
- const desc = readDescFile(options.descFile);
1863
- if (desc !== void 0) next.desc = desc;
1864
- const ownerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
1865
- if (ownerHumanId !== void 0) next.ownerHumanId = ownerHumanId;
1866
- Object.assign(next, parseAssigneeBody(options, false));
1867
- return next;
1868
- });
1869
- startSpinner("Creating task...");
1870
- const createResponse = await httpPost(
1871
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2`,
1872
- body
1873
- );
1874
- if (!createResponse.ok) {
1875
- stopSpinner(false, "Failed");
1876
- failResponse(createResponse);
1877
- }
1878
- const response = await getWorkflowTask(
1879
- options.workspace,
1880
- workflowFileId,
1881
- createResponse.data.taskScopedId
1882
- );
1883
- if (!response.ok) {
1884
- stopSpinner(false, "Failed");
1885
- failResponse(response);
1886
- }
1887
- stopSpinner(true, "Task created");
1888
- printTaskDetail(response.data);
1889
- }
1890
- );
1891
- addWorkspaceOption(
1892
- task.command("update").description("Update workflow task metadata").argument("<workflowFileId>").argument("<taskScopedId>").option("--title <title>", "Task title").option("--priority <priority>", "Priority: urgent, high, medium, or low").option("--desc-file <localPath>", "Local UTF-8 text file for task description").option("--clear-desc", "Clear task description").option("--owner-human-id <humanId>", "Task owner human ID")
1893
- ).action(
1894
- async (workflowFileId, taskScopedId, options) => {
1895
- const body = runOrExit4(() => {
1896
- if (options.descFile && options.clearDesc) {
1897
- throw new WorkflowOptionsError("Error: --desc-file cannot be used with --clear-desc.");
1898
- }
1899
- const next = {};
1900
- if (options.title) next.title = options.title;
1901
- const priority = parsePriority(options.priority);
1902
- if (priority !== void 0) next.priority = priority;
1903
- const desc = readDescFile(options.descFile);
1904
- if (desc !== void 0) next.desc = desc;
1905
- if (options.clearDesc) next.desc = null;
1906
- const ownerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
1907
- if (ownerHumanId !== void 0) next.ownerHumanId = ownerHumanId;
1908
- assertNonEmptyBody(next);
1909
- return next;
1910
- });
1911
- const id = runOrExit4(() => parsePositiveInteger(taskScopedId, "taskScopedId"));
1912
- startSpinner("Updating task...");
1913
- const updateResponse = await httpPatch(
1914
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/metadata`,
1915
- body
1916
- );
1917
- if (!updateResponse.ok) {
1918
- stopSpinner(false, "Failed");
1919
- failResponse(updateResponse);
1920
- }
1921
- const response = await getWorkflowTask(options.workspace, workflowFileId, id);
1922
- if (!response.ok) {
1923
- stopSpinner(false, "Failed");
1924
- failResponse(response);
1925
- }
1926
- stopSpinner(true, "Task updated");
1927
- printTaskDetail(response.data);
1928
- }
1929
- );
1930
- for (const action of ["add-linked-files", "remove-linked-files"]) {
1931
- addWorkspaceOption(
1932
- task.command(action).description(`${action === "add-linked-files" ? "Add" : "Remove"} linked files on a workflow task`).argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--file-ids <ids>", "Comma-separated file IDs")
1933
- ).action(
1934
- async (workflowFileId, taskScopedId, options) => {
1935
- const { id, fileIds } = runOrExit4(() => ({
1936
- id: parsePositiveInteger(taskScopedId, "taskScopedId"),
1937
- fileIds: parseFileIds(options.fileIds, "--file-ids")
1938
- }));
1939
- startSpinner(action === "add-linked-files" ? "Adding linked files..." : "Removing linked files...");
1940
- const path2 = `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/linked-files`;
1941
- const updateResponse = action === "add-linked-files" ? await httpPost(path2, { fileIds }) : await httpDelete(path2, { fileIds });
1942
- if (!updateResponse.ok) {
1943
- stopSpinner(false, "Failed");
1944
- failResponse(updateResponse);
1945
- }
1946
- const response = await getWorkflowTask(options.workspace, workflowFileId, id);
1947
- if (!response.ok) {
1948
- stopSpinner(false, "Failed");
1949
- failResponse(response);
1950
- }
1951
- stopSpinner(true, action === "add-linked-files" ? "Linked files added" : "Linked files removed");
1952
- printTaskDetail(response.data);
1953
- }
1954
- );
1955
- }
1956
- addWorkspaceOption(
1957
- task.command("move").description("Move a workflow task to another status").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--status <statusScopedId>", "Target status scoped ID")
1958
- ).action(
1959
- async (workflowFileId, taskScopedId, options) => {
1960
- const { id, statusScopedId } = runOrExit4(() => ({
1961
- id: parsePositiveInteger(taskScopedId, "taskScopedId"),
1962
- statusScopedId: parsePositiveInteger(options.status, "--status")
1963
- }));
1964
- startSpinner("Moving task...");
1965
- const updateResponse = await httpPatch(
1966
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/status`,
1967
- { statusScopedId }
1968
- );
1969
- if (!updateResponse.ok) {
1970
- stopSpinner(false, "Failed");
1971
- failResponse(updateResponse);
1972
- }
1973
- const response = await getWorkflowTask(options.workspace, workflowFileId, id);
1974
- if (!response.ok) {
1975
- stopSpinner(false, "Failed");
1976
- failResponse(response);
1977
- }
1978
- stopSpinner(true, "Task moved");
1979
- printTaskDetail(response.data);
1980
- }
1981
- );
1982
- addWorkspaceOption(
1983
- task.command("move-after").description("Move a workflow task after an anchor task within a Board column").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--status <statusScopedId>", "Target status scoped ID").option("--after <taskScopedId>", "Anchor task scoped ID").option("--first", "Move to the top of the column")
1984
- ).action(
1985
- async (workflowFileId, taskScopedId, options) => {
1986
- const { id, statusScopedId, anchorTaskScopedId } = runOrExit4(() => {
1987
- if (options.after && options.first) {
1988
- throw new WorkflowOptionsError("Error: --after cannot be used with --first.");
1989
- }
1990
- if (!options.after && !options.first) {
1991
- throw new WorkflowOptionsError("Error: either --after or --first is required.");
1992
- }
1993
- return {
1994
- id: parsePositiveInteger(taskScopedId, "taskScopedId"),
1995
- statusScopedId: parsePositiveInteger(options.status, "--status"),
1996
- anchorTaskScopedId: options.first ? null : parsePositiveInteger(options.after, "--after")
1997
- };
1998
- });
1999
- startSpinner("Moving task...");
2000
- const updateResponse = await httpPost(
2001
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/move-after`,
2002
- { statusScopedId, anchorTaskScopedId }
2003
- );
2004
- if (!updateResponse.ok) {
2005
- stopSpinner(false, "Failed");
2006
- failResponse(updateResponse);
2007
- }
2008
- const response = await getWorkflowTask(options.workspace, workflowFileId, id);
2009
- if (!response.ok) {
2010
- stopSpinner(false, "Failed");
2011
- failResponse(response);
2012
- }
2013
- stopSpinner(true, "Task moved");
2014
- printTaskDetail(response.data);
2015
- }
2016
- );
2017
- addAssigneeOptions(
2018
- addWorkspaceOption(
2019
- task.command("assign").description("Update workflow task assignee").argument("<workflowFileId>").argument("<taskScopedId>").option("--clear", "Clear assignee")
2020
- )
2021
- ).action(
2022
- async (workflowFileId, taskScopedId, options) => {
2023
- const body = runOrExit4(() => {
2024
- const next = parseAssigneeBody(options, true);
2025
- if (Object.keys(next).length === 0 && options.clear !== true) assertNonEmptyBody(next);
2026
- return next;
2027
- });
2028
- const id = runOrExit4(() => parsePositiveInteger(taskScopedId, "taskScopedId"));
2029
- startSpinner("Updating task assignee...");
2030
- const updateResponse = await httpPatch(
2031
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/assignee`,
2032
- body
2033
- );
2034
- if (!updateResponse.ok) {
2035
- stopSpinner(false, "Failed");
2036
- failResponse(updateResponse);
2037
- }
2038
- const response = await getWorkflowTask(options.workspace, workflowFileId, id);
2039
- if (!response.ok) {
2040
- stopSpinner(false, "Failed");
2041
- failResponse(response);
2042
- }
2043
- stopSpinner(true, "Task assignee updated");
2044
- printTaskDetail(response.data);
2045
- }
2046
- );
2047
- addWorkspaceOption(
2048
- task.command("delete").description("Delete a workflow task").argument("<workflowFileId>").argument("<taskScopedId>")
2049
- ).action(async (workflowFileId, taskScopedId, options) => {
2050
- const id = runOrExit4(() => parsePositiveInteger(taskScopedId, "taskScopedId"));
2051
- startSpinner("Deleting task...");
2052
- const response = await httpDelete(
2053
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${id}`
2054
- );
2055
- if (!response.ok) {
2056
- stopSpinner(false, "Failed");
2057
- failResponse(response);
2058
- }
2059
- stopSpinner(true, `Deleted: ${response.data.scopedId}`);
2060
- });
2061
- }
2062
- function getWorkflowTask(workspaceId, workflowFileId, taskScopedId) {
2063
- return httpGet(
2064
- `/workspaces/${workspaceId}/workflows/${workflowFileId}/tasks-v2/${taskScopedId}`
2065
- );
2066
- }
2067
- function registerCommentCommands(workflow) {
2068
- const comment = workflow.command("comment").description("Workflow task comment operations");
2069
- addWorkspaceOption(
2070
- comment.command("create").description("Create a workflow task comment").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--content-path <localPath>", "Local UTF-8 text file for comment content")
2071
- ).action(
2072
- async (workflowFileId, taskScopedId, options) => {
2073
- const { id, content } = runOrExit4(() => ({
2074
- id: parsePositiveInteger(taskScopedId, "taskScopedId"),
2075
- content: readCommentContentFile2(options.contentPath)
2076
- }));
2077
- startSpinner("Creating comment...");
2078
- const response = await httpPost(
2079
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${id}/comments`,
2080
- { content }
2081
- );
2082
- if (!response.ok) {
2083
- stopSpinner(false, "Failed");
2084
- failResponse(response);
2085
- }
2086
- stopSpinner(true, "Comment created");
2087
- printCommentDetail(response.data);
2088
- }
2089
- );
2090
- addWorkspaceOption(
2091
- comment.command("list").description("List workflow task comments").argument("<workflowFileId>").argument("<taskScopedId>").option("-l, --limit <limit>", "Maximum number of comments to return", "30").option("--cursor <cursor>", "Pagination cursor")
2092
- ).action(async (workflowFileId, taskScopedId, options) => {
2093
- const { id, limit } = runOrExit4(() => ({
2094
- id: parsePositiveInteger(taskScopedId, "taskScopedId"),
2095
- limit: parseSearchLimit(options.limit, 30, 100)
2096
- }));
2097
- startSpinner("Fetching comments...");
2098
- const response = await httpGet(
2099
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${id}/comments-v2${buildQuery({
2100
- limit,
2101
- cursor: options.cursor
2102
- })}`
2103
- );
2104
- if (!response.ok) {
2105
- stopSpinner(false, "Failed");
2106
- failResponse(response);
2107
- }
2108
- if (response.data.items.length === 0) {
2109
- stopSpinner(true, "No comments found.");
2110
- return;
2111
- }
2112
- stopSpinner(true, `Found ${response.data.items.length} comment(s)`);
2113
- response.data.items.forEach((item, index) => {
2114
- if (index > 0) print("");
2115
- printCommentDetail(item);
2116
- });
2117
- if (response.data.nextCursor) print(`${colors.dim}nextCursor=${response.data.nextCursor}${colors.reset}`);
2118
- });
2119
- addWorkspaceOption(
2120
- comment.command("update").description("Edit a workflow task comment authored by the current user").argument("<workflowFileId>").argument("<taskScopedId>").argument("<commentId>").requiredOption("--content-path <localPath>", "Local UTF-8 text file for comment content")
2121
- ).action(
2122
- async (workflowFileId, taskScopedId, commentId, options) => {
2123
- const { task, comment: commentIdValue, content } = runOrExit4(() => ({
2124
- task: parsePositiveInteger(taskScopedId, "taskScopedId"),
2125
- comment: parsePositiveInteger(commentId, "commentId"),
2126
- content: readCommentContentFile2(options.contentPath)
2127
- }));
2128
- startSpinner("Updating comment...");
2129
- const response = await httpPatch(
2130
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${task}/comments/${commentIdValue}`,
2131
- { content }
2132
- );
2133
- if (!response.ok) {
2134
- stopSpinner(false, "Failed");
2135
- failResponse(response);
2136
- }
2137
- stopSpinner(true, `Updated: ${response.data.id}`);
2138
- }
2139
- );
2140
- addWorkspaceOption(
2141
- comment.command("delete").description("Delete a workflow task comment").argument("<workflowFileId>").argument("<taskScopedId>").argument("<commentId>")
2142
- ).action(
2143
- async (workflowFileId, taskScopedId, commentId, options) => {
2144
- const ids = runOrExit4(() => ({
2145
- task: parsePositiveInteger(taskScopedId, "taskScopedId"),
2146
- comment: parsePositiveInteger(commentId, "commentId")
2147
- }));
2148
- startSpinner("Deleting comment...");
2149
- const response = await httpDelete(
2150
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${ids.task}/comments/${ids.comment}`
2151
- );
2152
- if (!response.ok) {
2153
- stopSpinner(false, "Failed");
2154
- failResponse(response);
2155
- }
2156
- stopSpinner(true, `Deleted: ${response.data.id}`);
2157
- }
2158
- );
2159
- }
2160
- function registerRunCommands(workflow) {
2161
- const run = workflow.command("run").description("Workflow agent run operations");
2162
- addWorkspaceOption(
2163
- run.command("abort").description("Abort a workflow agent run").argument("<workflowFileId>").argument("<pipelineId>")
2164
- ).action(async (workflowFileId, pipelineId, options) => {
2165
- startSpinner("Aborting run...");
2166
- const response = await httpPost(
2167
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/pipeline/${pipelineId}/abort`,
2168
- {}
2169
- );
2170
- if (!response.ok) {
2171
- stopSpinner(false, "Failed");
2172
- failResponse(response);
2173
- }
2174
- stopSpinner(true, `Abort accepted: ${pipelineId}`);
2175
- });
2176
- }
2177
-
2178
- // src/program.ts
2179
- function createProgram(version) {
2180
- const program2 = new Command();
2181
- program2.name("moxt").description("Moxt CLI - AI Workspace").version(version).action(() => {
2182
- program2.help();
2183
- });
2184
- registerWhoamiCommand(program2);
2185
- registerWorkspaceCommand(program2);
2186
- registerFileCommand(program2);
2187
- registerMemoryCommand(program2);
2188
- registerWorkflowCommand(program2);
2189
- registerMiniappCommand(program2);
2190
- registerTelemetryCommand(program2);
2191
- return program2;
2192
- }
2193
-
2194
- // src/telemetry/client.ts
2195
- import { arch as arch2, platform as platform2 } from "os";
2196
- var buffer = [];
2197
- var FLUSH_TIMEOUT_MS = 3e3;
2198
- var MAX_BATCH_SIZE = 100;
2199
- function commonLabels() {
2200
- return {
2201
- cli_version: "0.7.2",
2202
- node_version: process.versions.node,
2203
- os: platform2(),
2204
- arch: arch2(),
2205
- is_ci: isCiEnvironment() ? "true" : "false"
2206
- };
2207
- }
2208
- function record(metric) {
2209
- if (isTelemetryDisabled()) {
2210
- debugLog(`record: disabled, dropping ${metric.metric_id}`);
2211
- return;
2212
- }
2213
- if (!getApiKeyOrUndefined()) {
2214
- debugLog(`record: no API key, dropping ${metric.metric_id}`);
2215
- return;
2216
- }
2217
- buffer.push({
2218
- ...metric,
2219
- extra_label_name_2_value: {
2220
- ...commonLabels(),
2221
- ...metric.extra_label_name_2_value ?? {}
2222
- }
2223
- });
2224
- debugLog(`record: buffered ${metric.metric_id} (buffer=${buffer.length})`);
2225
- }
2226
- function isDebug() {
2227
- return process.env.MOXT_TELEMETRY_DEBUG === "1" || process.env.MOXT_TELEMETRY_DEBUG === "true";
2228
- }
2229
- function debugLog(msg, detail) {
2230
- if (!isDebug()) return;
2231
- process.stderr.write(`[telemetry] ${msg}${detail !== void 0 ? ` ${JSON.stringify(detail)}` : ""}
2232
- `);
2233
- }
2234
- async function flush() {
2235
- if (buffer.length === 0) {
2236
- debugLog("flush: buffer empty, skipping");
2237
- return;
2238
- }
2239
- const apiKey = getApiKeyOrUndefined();
2240
- if (!apiKey) {
2241
- debugLog("flush: no API key, dropping buffer");
2242
- buffer.length = 0;
2243
- return;
2244
- }
2245
- const batch = buffer.splice(0, MAX_BATCH_SIZE);
2246
- const payload = {
2247
- release_id: "0.7.2",
2248
- client_type: "cli",
2249
- metric_data_list: batch.map((m) => ({
2250
- profile: "cli",
2251
- metric_id: m.metric_id,
2252
- metric_type: m.metric_type,
2253
- value: m.value,
2254
- extra_label_name_2_value: m.extra_label_name_2_value
2255
- }))
2256
- };
2257
- const url = `${getApiBaseUrl()}/cli-metrics`;
2258
- debugLog(`flush: POST ${url} with ${batch.length} metrics`, payload);
2259
- try {
2260
- const controller = new AbortController();
2261
- const timeout = setTimeout(() => {
2262
- controller.abort();
2263
- }, FLUSH_TIMEOUT_MS);
2264
- try {
2265
- const res = await fetch(url, {
2266
- method: "POST",
2267
- headers: {
2268
- "Content-Type": "application/json",
2269
- Authorization: `Bearer ${apiKey}`
2270
- },
2271
- body: JSON.stringify(payload),
2272
- signal: controller.signal
2273
- });
2274
- debugLog(`flush: response status=${res.status}`);
2275
- } finally {
2276
- clearTimeout(timeout);
2277
- }
2278
- } catch (err) {
2279
- debugLog("flush: failed", err instanceof Error ? err.message : String(err));
2280
- }
2281
- }
2282
-
2283
- // src/telemetry/notice.ts
2284
- var NOTICE = [
2285
- "",
2286
- "Attention: Moxt CLI now collects anonymous telemetry regarding usage.",
2287
- "This information is used to shape Moxt CLI's roadmap and prioritize features.",
2288
- "",
2289
- "You may opt out by setting MOXT_TELEMETRY_DISABLED=1 in your env",
2290
- "or by running `moxt telemetry disable`.",
2291
- "Details: https://www.npmjs.com/package/@moxt-ai/cli#telemetry",
2292
- ""
2293
- ];
2294
- function maybeShowTelemetryNotice() {
2295
- if (isTelemetryDisabled()) return;
2296
- if (isCiEnvironment()) return;
2297
- if (readTelemetryConfig().noticeShown) return;
2298
- for (const line of NOTICE) {
2299
- process.stderr.write(`${line}
2300
- `);
2301
- }
2302
- try {
2303
- writeTelemetryConfig({ noticeShown: true });
2304
- } catch {
2305
- }
2306
- }
2307
-
2308
- // src/telemetry/instrument.ts
2309
- var current = null;
2310
- function commandPath(cmd) {
2311
- const names = [];
2312
- let node = cmd;
2313
- while (node && node.parent) {
2314
- names.unshift(node.name());
2315
- node = node.parent;
2316
- }
2317
- if (names.length === 0) return { command: "unknown" };
2318
- if (names.length === 1) return { command: names[0] };
2319
- return { command: names[0], subcommand: names.slice(1).join(" ") };
2320
- }
2321
- function instrumentProgram(program2) {
2322
- program2.hook("preAction", (_thisCommand, actionCommand) => {
2323
- const { command, subcommand } = commandPath(actionCommand);
2324
- if (command !== "telemetry") {
2325
- maybeShowTelemetryNotice();
2326
- }
2327
- current = { name: command, subcommand, startedAt: Date.now() };
2328
- record({
2329
- metric_id: "client.cli.command_invocation.count",
2330
- metric_type: "counter",
2331
- value: 1,
2332
- extra_label_name_2_value: {
2333
- command,
2334
- ...subcommand ? { subcommand } : {},
2335
- status: "started"
2336
- }
2337
- });
2338
- });
2339
- program2.hook("postAction", async () => {
2340
- await reportOutcome("success");
2341
- });
2342
- }
2343
- async function reportOutcome(status, errorCode) {
2344
- if (!current) return;
2345
- const { name, subcommand, startedAt } = current;
2346
- const durationSeconds = (Date.now() - startedAt) / 1e3;
2347
- record({
2348
- metric_id: "client.cli.command_duration_seconds",
2349
- metric_type: "histogram",
2350
- value: durationSeconds,
2351
- extra_label_name_2_value: {
2352
- command: name,
2353
- ...subcommand ? { subcommand } : {},
2354
- status
2355
- }
2356
- });
2357
- if (status === "error") {
2358
- record({
2359
- metric_id: "client.cli.command_error.count",
2360
- metric_type: "counter",
2361
- value: 1,
2362
- extra_label_name_2_value: {
2363
- command: name,
2364
- ...subcommand ? { subcommand } : {},
2365
- ...errorCode ? { error_code: errorCode } : {}
2366
- }
2367
- });
2368
- }
2369
- current = null;
2370
- await flush();
2371
- }
2372
- function installExitHandler() {
2373
- const handleError = (errorCode) => {
2374
- void reportOutcome("error", errorCode);
2375
- };
2376
- process.on("uncaughtException", () => {
2377
- handleError("uncaught_exception");
2378
- process.exit(1);
2379
- });
2380
- process.on("unhandledRejection", () => {
2381
- handleError("unhandled_rejection");
2382
- process.exit(1);
2383
- });
2384
- }
2385
-
2386
- // src/index.ts
2387
- updateNotifier({
2388
- pkg: { name: "@moxt-ai/cli", version: "0.7.2" }
2389
- }).notify();
2390
- var program = createProgram("0.7.2");
2391
- instrumentProgram(program);
2392
- installExitHandler();
2393
- program.parseAsync(process.argv).then(async () => {
2394
- await flush();
2395
- }).catch(async (err) => {
2396
- console.error("CLI Error:", err);
2397
- await flush();
2398
- process.exit(1);
2399
- });
2400
- //# sourceMappingURL=index.js.map