Repository navigation
Expand file tree
/
Copy pathprogram.ts
More file actions
484 lines (460 loc) · 18.4 KB
/
Copy pathprogram.ts
File metadata and controls
484 lines (460 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// SPDX-License-Identifier: MIT
/**
* The CLI itself: the commander program and the `main()` that runs it.
*
* Kept out of `index.ts` on purpose. `index.ts` is both the `synchain` binary and the package
* entry (`exports["."]`), and whatever it exports is public API that has to stay stable. This
* module is not reachable through the `exports` map, so tests can import `buildProgram` /
* `main` without them becoming part of the package surface.
*/
import { Command, CommanderError, Help, Option } from "commander";
import { createRequire } from "node:module";
import { EXIT_CODES, reportError, wantsStructuredOutput } from "./api.js";
import { DEFAULT_BASE_URL, isFirstRun, markWelcomeSeen } from "./config.js";
import { DRY_RUN_DESC } from "./dry-run.js";
import { AUTH_HELP_TEXT } from "./help-auth.js";
import { buildHelpJson } from "./help-json.js";
import { argvWantsJsonOutput, OUTPUT_FORMATS, resolveOutputFormat } from "./output-format.js";
import { printWelcomeBanner } from "./commands/welcome.js";
import { runLogin } from "./commands/login.js";
import { runLogout } from "./commands/logout.js";
import { runWhoami } from "./commands/whoami.js";
import { runProjectLs, runProjectUse } from "./commands/project.js";
import {
runFilesDownload,
runFilesLs,
runFilesMv,
runFilesRename,
runFilesRm,
runFilesUpload,
} from "./commands/files.js";
import {
runFoldersLs,
runFoldersMkdir,
runFoldersRename,
runFoldersRm,
} from "./commands/folders.js";
import {
runCalendarAdd,
runCalendarEdit,
runCalendarLs,
runCalendarRm,
} from "./commands/calendar.js";
import {
runDiscussionLs,
runDiscussionPost,
runDiscussionRead,
runDiscussionReply,
} from "./commands/discussion.js";
import { runNotificationsLs, runNotificationsRead } from "./commands/notifications.js";
import { runMembersLs } from "./commands/members.js";
import { runHelp } from "./commands/help.js";
import { runDoctor } from "./commands/doctor.js";
import { DOCS_AGENTS, DOCS_README } from "./constants.js";
const require = createRequire(import.meta.url);
const pkg = require("../package.json") as { version: string };
const DOCS_HELP_TEXT =
"\nAI agents: install + usage guide at\n" +
` ${DOCS_AGENTS}\n` +
"Humans: full reference at\n" +
` ${DOCS_README}\n`;
/**
* What the root's text `--help` prints after commander's own: how to authenticate, the
* environment it reads and a few examples first (src/help-auth.ts), then where the docs are.
* Logging in is the first thing anyone has to do, so it should not take a second command to
* find out how.
*/
const ROOT_HELP_TEXT = `\n${AUTH_HELP_TEXT}${DOCS_HELP_TEXT}`;
/**
* @param argv the command line about to be parsed. It only decides how a parse error is written
* (see below); parsing itself still happens in `parseAsync`.
*/
export function buildProgram(argv: readonly string[] = process.argv): Command {
const program = new Command();
// Parse errors (unknown command or option, a missing value, `--format yaml`) are commander's
// own and never reach a command's catch block. Throw them instead of exiting, so main() can
// report them like any other failure; and in structured mode keep commander from printing its
// prose line, since main() writes the envelope in its place.
// Must come before any .command(): a subcommand copies both settings when it is created.
program.exitOverride();
program.configureOutput({
outputError: (str, write) => {
if (!wantsStructuredOutput(undefined, argv)) write(str);
},
});
// `--help --format json`: swap the help *renderer* rather than scanning argv for `-h`/`--help`.
// By the time commander prints help it has parsed the root's `--format`, so the value can be
// read off the parent chain; and an option *value* that happens to be `-h`
// (`discussion post --title -h`) never reaches this code at all. An argv pre-scan cannot tell
// the two apart, and would skip the write while still exiting 0.
// Must come before any .command(): a subcommand copies the help configuration when created.
program.configureHelp({
formatHelp: (cmd, helper) =>
resolveOutputFormat(cmd) === "json"
? `${JSON.stringify(buildHelpJson(cmd), null, 2)}\n`
: // Not `helper.formatHelp`: on this helper that is the function being defined here.
Help.prototype.formatHelp.call(helper, cmd, helper),
});
program
.name("synchain")
.description("CLI for the Synchain platform")
.version(pkg.version)
.addOption(
// The choices go in the description too: the JSON command tree carries flags and
// description only, and an agent reading it should not have to guess the legal values.
new Option(
"--format <fmt>",
"Output format: text | json (json turns on each command's --json)"
)
.choices(OUTPUT_FORMATS)
.default("text")
)
// Empty in JSON mode: text after the JSON document would make stdout unparseable. The JSON
// tree carries the same authentication data as its root `auth` / `environment`.
.addHelpText("after", ({ command }) =>
resolveOutputFormat(command) === "json" ? "" : ROOT_HELP_TEXT
);
// `--format json` means `--json` for every command that declares `--json`. Only for those:
// injecting a synthetic `--json` into argv would fail `files download`, `project use` and the
// other commands without JSON output as an unknown option.
program.hook("preAction", (_thisCommand, actionCommand) => {
if (resolveOutputFormat(actionCommand) !== "json") return;
if (actionCommand.options.some((option) => option.long === "--json")) {
actionCommand.setOptionValue("json", true);
}
});
// -- auth
program
.command("login")
.description("Authenticate the CLI against a Synchain instance")
.option(
"--base-url <url>",
// Not "a self-hosted instance": the server cannot be self-hosted (README).
`Override the API host (default ${DEFAULT_BASE_URL}; only needed for testing against another deployment)`
)
.action(async (opts) => {
// The key is never accepted via argv (it would leak into shell history and
// /proc/<pid>/cmdline). Use SYNCHAIN_TOKEN in CI, or the interactive prompt.
await runLogin({ baseUrl: opts.baseUrl });
});
program
.command("logout")
.description("Clear stored credentials (local only; does not revoke the CLI key server-side)")
.option("--yes", "Skip the confirmation prompt (required in non-TTY/CI environments)")
.action(async (opts) => {
await runLogout(opts);
});
program
.command("whoami")
.description("Print current user and project memberships")
.option("--json", "Output JSON")
.action(async (opts) => {
await runWhoami({ json: Boolean(opts.json) });
});
// -- project
const project = program.command("project").description("List or switch the active project");
project
.command("ls")
.description("List accessible projects")
.option("--json", "Output JSON")
.action(async (opts) => {
await runProjectLs({ json: Boolean(opts.json) });
});
project
.command("use <id>")
.description("Set the active project for subsequent commands")
.action(async (id: string) => {
await runProjectUse(id);
});
// -- files
const files = program.command("files").description("Manage project files");
files
.command("ls")
.description("List files in the active project (root or a folder)")
.option("--folder <id>", "Folder id or 8-char prefix (root if omitted)")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.action(async (opts) => {
await runFilesLs(opts);
});
files
.command("upload <localPath>")
.description("Upload a local file (defaults to project root)")
.option("--folder <id>", "Destination folder id or 8-char prefix (root if omitted)")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (localPath: string, opts) => {
await runFilesUpload(localPath, opts);
});
files
.command("download <fileId>")
.description("Download a file by id/prefix (use --out - to stream to stdout)")
.option("--out <path>", "Output path, or `-` for stdout")
.option("--project <p>", "Project id")
.action(async (fileId: string, opts) => {
await runFilesDownload(fileId, opts);
});
files
.command("mv <fileId>")
.description("Move a file to a folder (or `root`)")
.requiredOption("--to <folderId|root>", "Destination folder id/prefix or `root`")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (fileId: string, opts) => {
await runFilesMv(fileId, opts);
});
files
.command("rm <fileId>")
.description("Delete a file (confirms first; --yes to skip)")
.option("--yes", "Skip the confirmation prompt (required when stdin is not a terminal)")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (fileId: string, opts) => {
await runFilesRm(fileId, opts);
});
files
.command("rename <fileId> <newName>")
.description("Rename a file (extension must stay the same)")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (fileId: string, newName: string, opts) => {
await runFilesRename(fileId, newName, opts);
});
// -- folders
const folders = program.command("folders").description("Manage folders");
folders
.command("ls [folderId]")
.description("List the folder tree, or files inside a specific folder")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.action(async (folderId: string | undefined, opts) => {
await runFoldersLs(folderId, opts);
});
folders
.command("mkdir <name>")
.description("Create a folder")
.option("--parent <id>", "Parent folder id or 8-char prefix (root if omitted)")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (name: string, opts) => {
await runFoldersMkdir(name, opts);
});
folders
.command("rm <folderId>")
.description("Delete an empty folder (409 if not empty)")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (folderId: string, opts) => {
await runFoldersRm(folderId, opts);
});
folders
.command("rename <folderId> <newName>")
.description("Rename a folder")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (folderId: string, newName: string, opts) => {
await runFoldersRename(folderId, newName, opts);
});
// -- calendar
const calendar = program.command("calendar").description("Manage project calendar events");
calendar
.command("add")
.description("Create a calendar event")
.requiredOption("--title <t>", "Event title")
.requiredOption("--start <date>", "ISO 8601 or local `YYYY-MM-DD HH:mm`")
.requiredOption("--end <date>", "ISO 8601 or local `YYYY-MM-DD HH:mm`")
.option("--desc <d>", "Event description")
.option(
"--tag <tag>",
"meeting | mix | master | vocal | review | release | arrange | harmony | custom",
"meeting"
)
.option("--custom-tag <c>", "Free-text label (required when --tag custom)")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (opts) => {
await runCalendarAdd(opts);
});
calendar
.command("ls")
.description("List events in a date range (default: next 30 days)")
.option("--from <date>", "Window start (ISO or local `YYYY-MM-DD HH:mm`)")
.option("--to <date>", "Window end (ISO or local `YYYY-MM-DD HH:mm`)")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.action(async (opts) => {
await runCalendarLs(opts);
});
calendar
.command("edit <eventId>")
.description("Edit an existing event (creator or admin only)")
.option("--title <t>", "New title")
.option("--start <date>", "New start (ISO or local)")
.option("--end <date>", "New end (ISO or local)")
.option("--desc <d>", "New description")
.option("--tag <tag>", "New tag (see `calendar add`)")
.option("--custom-tag <c>", "New free-text label (with --tag custom)")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (eventId: string, opts) => {
await runCalendarEdit(eventId, opts);
});
calendar
.command("rm <eventId>")
.description("Delete a calendar event (creator or admin only)")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (eventId: string, opts) => {
await runCalendarRm(eventId, opts);
});
// -- discussion
const discussion = program
.command("discussion")
.description("Browse + post to project discussion threads");
discussion
.command("ls")
.description("List discussion threads (paginated: root threads + reply counts)")
.option("--limit <n>", "Threads per page (default 50, max 100)")
.option("--offset <n>", "Skip the first N threads")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.action(async (opts) => {
await runDiscussionLs(opts);
});
discussion
.command("read <postId>")
.description("Print a thread (root or a reply id) as a tree")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.action(async (postId: string, opts) => {
await runDiscussionRead(postId, opts);
});
discussion
.command("post")
.description("Start a new discussion thread")
.requiredOption("--title <t>", "Thread title")
.requiredOption("--content <c>", "Thread body (use `-` to read from stdin)")
.option("--category <c>", "mix | master | art | release | vocal | general", "general")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (opts) => {
await runDiscussionPost(opts);
});
discussion
.command("reply <postId>")
.description("Reply to an existing thread or post")
.requiredOption("--content <c>", "Reply body (use `-` to read from stdin)")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (postId: string, opts) => {
await runDiscussionReply(postId, opts);
});
// -- members (read-only project roster)
const members = program.command("members").description("List project members (read-only)");
members
.command("ls")
.description("List the members of the active project")
.option("--project <p>", "Project id")
.option("--json", "Output JSON")
.action(async (opts) => {
await runMembersLs(opts);
});
// -- notifications (your own; user-level, not project-scoped)
const notifications = program
.command("notifications")
.alias("notif")
.description("Your notifications (list / mark read)");
notifications
.command("ls")
.description("List your notifications (unread only by default)")
.option("--all", "Include already-read notifications")
.option("--limit <n>", "Max items to fetch (default 30, max 100)")
.option("--json", "Output JSON")
.action(async (opts) => {
await runNotificationsLs(opts);
});
notifications
.command("read [id]")
.description("Mark one notification read, or --all to clear them")
.option("--all", "Mark all notifications read")
.option("--json", "Output JSON")
.option("--dry-run", DRY_RUN_DESC)
.action(async (id: string | undefined, opts) => {
await runNotificationsRead(id, opts);
});
// -- doctor (offline: never makes a request)
program
.command("doctor")
.description(
"Check the local setup offline: config file, stored key shape, base URL, active project"
)
.option("--json", "Output JSON")
.action(async (opts) => {
await runDoctor({ json: Boolean(opts.json) });
});
// -- help
program
.command("help [topic]")
.description(
"Rich help per topic (login, project, files, folders, calendar, discussion, members, " +
"notifications, doctor, safety)"
)
.action((topic: string | undefined) => {
runHelp(topic);
});
return program;
}
export async function main(argv: string[] = process.argv): Promise<void> {
// First-run welcome banner —— 仅在【交互式且非 JSON 输出】时打印,且只在真正打印后才落 sentinel。
// banner 走 stderr(见 welcome.ts),据 stderr 是否为终端判定:--json/管道/重定向时完全不打印、
// 也不消费 first-run(让人类首次交互运行仍能看到 banner,同时绝不污染 stdout/--json)。
// `--format json` / `--format=json` 与 `--json` 同等对待:这一步发生在 commander 解析之前。
const wantsJson = argvWantsJsonOutput(argv);
if (isFirstRun() && process.stderr.isTTY === true && !wantsJson) {
printWelcomeBanner();
try {
await markWelcomeSeen();
} catch {
// Non-fatal — worst case, the banner shows again next run.
}
}
const program = buildProgram(argv);
try {
await program.parseAsync(argv);
} catch (err) {
if (!(err instanceof CommanderError)) throw err;
// --help and --version arrive here as exit-code-0 CommanderErrors under exitOverride().
if (err.exitCode === 0) return;
// A bare `synchain`, or a command group without a subcommand (`synchain files`), has already
// printed its help as the error report; an envelope on top would be a second record of it.
if (err.code !== "commander.help" && wantsStructuredOutput(undefined, argv)) {
reportError(new Error(err.message.replace(/^error: /, "")), {
json: true,
code: commanderCode(err.code),
});
}
process.exitCode = EXIT_CODES.usage;
}
}
/**
* commander's error code as an envelope code: `commander.unknownOption` -> `unknown_option`.
* Derived rather than tabled, so a parse error commander adds later still gets a stable name.
*/
function commanderCode(code: string): string {
return code
.replace(/^commander\./, "")
.replace(/([A-Z])/g, "_$1")
.toLowerCase();
}