@retainer/cli 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,678 @@
1
+ #!/usr/bin/env node
2
+ import { rm } from 'node:fs/promises';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { parseArgs } from 'node:util';
5
+ import { RetainerAccountClient, RetainerApiError, } from '@retainer/sdk';
6
+ import { pinnedMcpAddress } from '@retainer/shared';
7
+ import { interactiveChat, sendMessage, startFailure } from './agent-chat.js';
8
+ import { commandGroups } from './commands.js';
9
+ import { getTokens, KeyMode, LoginRequired, login, refreshWhileLocked, serverOrigin, } from './oauth.js';
10
+ import { credentials, locked, loginFile, readJson, updateCredentials } from './store.js';
11
+ const commands = commandGroups.flatMap(({ commands }) => commands);
12
+ const noArguments = new Set([
13
+ 'login',
14
+ 'logout',
15
+ 'whoami',
16
+ 'elevate',
17
+ 'workspaces',
18
+ 'members',
19
+ 'invitations',
20
+ 'keys',
21
+ 'connections',
22
+ 'review',
23
+ 'schema-changes',
24
+ 'extensions',
25
+ 'routines',
26
+ ]);
27
+ const twoArguments = new Set(['role', 'routine approve', 'routine reject']);
28
+ function validateArguments(command, args, options) {
29
+ const expected = noArguments.has(command) ? 0 : twoArguments.has(command) ? 2 : 1;
30
+ const optional = command === 'mcp-address' || command === 'agent chat';
31
+ if (args.length > expected || (args.length !== expected && !optional))
32
+ throw new Usage(`Check the arguments for retainer ${command} with retainer --help.`);
33
+ if (command === 'role' && !!options.org === !!options.workspace?.length)
34
+ throw new Usage('Choose either --org or --workspace for a role change.');
35
+ if (command === 'duplicates merge')
36
+ required(options.keep, '--keep');
37
+ if (command === 'key create' && !['read', 'write', 'schema'].includes(options.access ?? ''))
38
+ throw new Usage('Choose --access read, write or schema.');
39
+ }
40
+ function parse(argv) {
41
+ return parseArgs({
42
+ args: argv,
43
+ allowPositionals: true,
44
+ options: {
45
+ json: { type: 'boolean' },
46
+ help: { type: 'boolean', short: 'h' },
47
+ server: { type: 'string' },
48
+ org: { type: 'string' },
49
+ workspace: { type: 'string', multiple: true },
50
+ minutes: { type: 'string' },
51
+ reason: { type: 'string' },
52
+ end: { type: 'boolean' },
53
+ template: { type: 'string' },
54
+ 'org-role': { type: 'string' },
55
+ role: { type: 'string', multiple: true },
56
+ approval: { type: 'string' },
57
+ access: { type: 'string' },
58
+ keep: { type: 'string' },
59
+ message: { type: 'string' },
60
+ },
61
+ });
62
+ }
63
+ const waiting = (data) => ({ data, exit: 6 });
64
+ const done = (data) => ({ data });
65
+ class Usage extends Error {
66
+ }
67
+ function required(value, name) {
68
+ if (!value)
69
+ throw new Usage(`Give ${name}.`);
70
+ return value;
71
+ }
72
+ const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
73
+ const uuid = /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i;
74
+ class CommandContext {
75
+ server;
76
+ options;
77
+ savedWorkspace;
78
+ identity;
79
+ tokens;
80
+ target;
81
+ routineUrl;
82
+ constructor(server, options, savedWorkspace) {
83
+ this.server = server;
84
+ this.options = options;
85
+ this.savedWorkspace = savedWorkspace;
86
+ }
87
+ async client(workspace) {
88
+ this.tokens ??= getTokens(this.server);
89
+ return new RetainerAccountClient({
90
+ baseUrl: this.server,
91
+ accessToken: (await this.tokens).accessToken,
92
+ ...(workspace ? { workspace: workspace.id } : {}),
93
+ ...(this.options.approval ? { approval: this.options.approval } : {}),
94
+ fetch: (input, init) => fetch(input, { ...init, signal: AbortSignal.timeout(29_000), redirect: 'error' }),
95
+ });
96
+ }
97
+ account() {
98
+ this.identity ??= this.client().then((client) => client.account());
99
+ return this.identity;
100
+ }
101
+ explicitWorkspace() {
102
+ if ((this.options.workspace?.length ?? 0) > 1)
103
+ throw new Usage('Give one --workspace.');
104
+ return this.options.workspace?.[0];
105
+ }
106
+ async workspace(selector) {
107
+ const flag = this.explicitWorkspace();
108
+ const name = required(selector ?? flag ?? process.env.RETAINER_WORKSPACE ?? this.savedWorkspace, '--workspace <slug|id>');
109
+ const all = (await this.account()).organizations.flatMap(({ workspaces }) => workspaces);
110
+ const workspace = all.find((w) => w.id === name || w.slug === name);
111
+ if (!workspace)
112
+ throw new Usage(`Workspace "${name}" is not available. Run retainer workspaces.`);
113
+ if (flag && flag !== workspace.id && flag !== workspace.slug)
114
+ throw new Usage('The workspace argument and --workspace refer to different targets.');
115
+ this.target = { type: 'workspace', selector: workspace.slug };
116
+ return workspace;
117
+ }
118
+ async organization(allowWorkspaceOptions = false) {
119
+ if (!allowWorkspaceOptions && this.options.workspace?.length)
120
+ throw new Usage('Use --org for this organization command.');
121
+ const all = (await this.account()).organizations.filter(({ role }) => role !== 'member');
122
+ const name = this.options.org;
123
+ const matches = name
124
+ ? all.filter((org) => org.id === name ||
125
+ org.name.toLowerCase() === name.toLowerCase() ||
126
+ org.name
127
+ .toLowerCase()
128
+ .replace(/[^a-z0-9]+/g, '-')
129
+ .replace(/^-|-$/g, '') === name.toLowerCase())
130
+ : all;
131
+ if (matches.length !== 1 || !matches[0])
132
+ throw new Usage('Give --org <slug|id> for an organization you manage. Run retainer whoami.');
133
+ const org = matches[0];
134
+ this.target = { type: 'org', selector: org.id };
135
+ return org;
136
+ }
137
+ workspacePage(workspace, route) {
138
+ return `${this.server}/app/w/${encodeURIComponent(workspace.slug)}/${route}`;
139
+ }
140
+ }
141
+ async function waitFor(ctx, id) {
142
+ if (!uuid.test(id))
143
+ throw new Usage('Give the ID printed by login or an approval request.');
144
+ const file = await readJson(loginFile(id));
145
+ const deadline = Date.now() + 600_000;
146
+ if (file) {
147
+ for (;;) {
148
+ const status = await readJson(loginFile(id));
149
+ if (status?.status === 'done') {
150
+ await rm(loginFile(id), { force: true });
151
+ return done({ id, server: status.server, status: 'done' });
152
+ }
153
+ if (status?.status === 'denied')
154
+ return { data: { id, status: 'denied' }, exit: 7 };
155
+ if (status?.status === 'failed')
156
+ throw new Error('The browser could not complete login. Run retainer login again.');
157
+ if (status?.status === 'expired' || Date.now() >= Date.parse(file.expiresAt))
158
+ break;
159
+ await delay(250);
160
+ }
161
+ }
162
+ else {
163
+ const api = await ctx.client();
164
+ for (;;) {
165
+ const approval = await api.approval(id);
166
+ if (approval.status === 'approved' || approval.status === 'used')
167
+ return done(approval);
168
+ if (approval.status === 'denied' || approval.status === 'ended')
169
+ return { data: approval, exit: 7 };
170
+ if (approval.status === 'expired' || Date.now() >= deadline)
171
+ break;
172
+ await delay(600);
173
+ }
174
+ }
175
+ return { data: { id, status: 'expired' }, exit: 5 };
176
+ }
177
+ async function inboxPages(api) {
178
+ const inbox = await api.review({ limit: 100 });
179
+ let pending = inbox.nextCursors.pendingAssertions;
180
+ let merges = inbox.nextCursors.mergeSuggestions;
181
+ while (pending || merges) {
182
+ const page = await api.review({
183
+ limit: 100,
184
+ ...(pending ? { pendingAssertionsCursor: pending } : {}),
185
+ ...(merges ? { mergeSuggestionsCursor: merges } : {}),
186
+ });
187
+ if (pending) {
188
+ inbox.pendingAssertions.push(...page.pendingAssertions);
189
+ pending = page.nextCursors.pendingAssertions;
190
+ }
191
+ if (merges) {
192
+ inbox.mergeSuggestions.push(...page.mergeSuggestions);
193
+ merges = page.nextCursors.mergeSuggestions;
194
+ }
195
+ }
196
+ return inbox;
197
+ }
198
+ async function proposedChanges(api) {
199
+ const result = await api.schemaChanges({ status: 'proposed', limit: 100 });
200
+ while (result.nextCursor) {
201
+ const page = await api.schemaChanges({
202
+ status: 'proposed',
203
+ limit: 100,
204
+ cursor: result.nextCursor,
205
+ });
206
+ result.changes.push(...page.changes);
207
+ result.nextCursor = page.nextCursor;
208
+ }
209
+ return result;
210
+ }
211
+ async function getReview(ctx, id) {
212
+ const account = await ctx.account();
213
+ const workspaces = ctx.explicitWorkspace()
214
+ ? [await ctx.workspace()]
215
+ : account.organizations.flatMap((org) => org.workspaces);
216
+ for (const workspace of id ? workspaces : []) {
217
+ const api = await ctx.client(workspace);
218
+ const tryRead = async (fn) => {
219
+ try {
220
+ return await fn();
221
+ }
222
+ catch (error) {
223
+ if (!(error instanceof RetainerApiError) || error.status !== 404)
224
+ throw error;
225
+ }
226
+ };
227
+ const [assertion, schemaChange, routine, extension] = await Promise.all([
228
+ tryRead(() => api.assertion(id ?? '')),
229
+ tryRead(() => api.schemaChange(id ?? '')),
230
+ tryRead(() => api.routine(id ?? '')),
231
+ tryRead(() => api.extension(id ?? '')),
232
+ ]);
233
+ if (assertion)
234
+ return { workspace, assertion, record: await api.record(assertion.recordId) };
235
+ if (schemaChange || routine || extension)
236
+ return { workspace, schemaChange, routine, extension };
237
+ for (let cursor;;) {
238
+ const page = await api.review({
239
+ limit: 100,
240
+ ...(cursor ? { mergeSuggestionsCursor: cursor } : {}),
241
+ });
242
+ const suggestion = page.mergeSuggestions.find((entry) => entry.id === id);
243
+ if (suggestion)
244
+ return {
245
+ workspace,
246
+ suggestion,
247
+ records: await Promise.all(suggestion.recordIds.map((recordId) => api.record(recordId))),
248
+ };
249
+ cursor = page.nextCursors.mergeSuggestions ?? undefined;
250
+ if (!cursor)
251
+ break;
252
+ }
253
+ }
254
+ if (id)
255
+ throw new Usage('That review item was not found. Run retainer review.');
256
+ return {
257
+ workspaces: await Promise.all(workspaces.map(async (workspace) => {
258
+ const api = await ctx.client(workspace);
259
+ const [inbox, schemaChanges, routines, extensions] = await Promise.all([
260
+ inboxPages(api),
261
+ proposedChanges(api),
262
+ api.routines().catch((error) => {
263
+ if (error instanceof RetainerApiError && error.status === 404)
264
+ return { routines: [] };
265
+ throw error;
266
+ }),
267
+ api.extensions(),
268
+ ]);
269
+ return {
270
+ workspace,
271
+ inbox,
272
+ schemaChanges,
273
+ routines: routines.routines.filter((routine) => routine.proposals > 0),
274
+ extensions: extensions.installations,
275
+ };
276
+ })),
277
+ };
278
+ }
279
+ async function execute(ctx, command, args) {
280
+ const { options, server } = ctx;
281
+ const first = () => required(args[0], 'the command argument');
282
+ switch (command) {
283
+ case 'login':
284
+ return waiting(await login(server));
285
+ case 'wait':
286
+ return waitFor(ctx, first());
287
+ case 'logout': {
288
+ let warning;
289
+ await locked(server, async () => {
290
+ try {
291
+ const { accessToken } = await refreshWhileLocked(server);
292
+ const api = new RetainerAccountClient({
293
+ baseUrl: server,
294
+ accessToken,
295
+ fetch: (input, init) => fetch(input, { ...init, signal: AbortSignal.timeout(10_000), redirect: 'error' }),
296
+ });
297
+ await api.logout();
298
+ }
299
+ catch {
300
+ warning = 'Disconnect this CLI login from Connected apps in Your account.';
301
+ }
302
+ await updateCredentials((file) => {
303
+ delete file.servers[server];
304
+ if (file.lastServer === server) {
305
+ const replacement = Object.keys(file.servers).at(-1);
306
+ if (replacement)
307
+ file.lastServer = replacement;
308
+ else
309
+ delete file.lastServer;
310
+ }
311
+ });
312
+ });
313
+ return done({ server, signedOut: true, warning });
314
+ }
315
+ case 'whoami': {
316
+ const account = await ctx.account();
317
+ const selector = ctx.explicitWorkspace() ?? process.env.RETAINER_WORKSPACE ?? ctx.savedWorkspace;
318
+ const workspace = selector
319
+ ? account.organizations
320
+ .flatMap((o) => o.workspaces)
321
+ .find((w) => w.id === selector || w.slug === selector)
322
+ : undefined;
323
+ return done({
324
+ ...account,
325
+ server,
326
+ workspace: workspace ?? null,
327
+ elevations: (account.elevations ?? []).map((value) => ({
328
+ ...value,
329
+ secondsLeft: Math.max(0, Math.floor((Date.parse(value.expiresAt) - Date.now()) / 1000)),
330
+ })),
331
+ });
332
+ }
333
+ case 'workspaces':
334
+ return done({
335
+ workspaces: (await ctx.account()).organizations.flatMap((org) => org.workspaces),
336
+ });
337
+ case 'review':
338
+ return done(await getReview(ctx));
339
+ case 'review show':
340
+ return done(await getReview(ctx, first()));
341
+ case 'elevate': {
342
+ const organization = options.org ? await ctx.organization() : null;
343
+ const workspace = organization ? null : await ctx.workspace();
344
+ const target = organization
345
+ ? { organizationId: organization.id }
346
+ : { workspaceId: workspace?.id ?? '' };
347
+ const api = await ctx.client(workspace ?? undefined);
348
+ if (options.end) {
349
+ const approvals = ((await ctx.account()).elevations ?? []).filter((e) => 'organizationId' in target
350
+ ? e.organizationId === target.organizationId
351
+ : e.workspaceId === target.workspaceId);
352
+ await Promise.all(approvals.map((e) => api.endElevation(e.id)));
353
+ return done({ ...target, ended: approvals.map((e) => e.id) });
354
+ }
355
+ const minutes = options.minutes === undefined ? undefined : Number(options.minutes);
356
+ if (minutes !== undefined && (!Number.isInteger(minutes) || minutes < 1 || minutes > 60))
357
+ throw new Usage('--minutes must be an integer from 1 to 60.');
358
+ return waiting(await api.startElevation({
359
+ ...target,
360
+ ...(minutes ? { minutes } : {}),
361
+ ...(options.reason ? { reason: options.reason } : {}),
362
+ }));
363
+ }
364
+ case 'connections':
365
+ if (!ctx.explicitWorkspace())
366
+ return done(await (await ctx.client()).connections());
367
+ break;
368
+ case 'invite':
369
+ case 'invitations':
370
+ case 'invitation revoke':
371
+ case 'workspace create': {
372
+ const organization = await ctx.organization(command === 'invite');
373
+ const api = await ctx.client();
374
+ const named = { organization: { id: organization.id, name: organization.name } };
375
+ if (command === 'invitations')
376
+ return done({ ...named, ...(await api.invitations(organization.id)) });
377
+ if (command === 'invitation revoke') {
378
+ await api.revokeInvitation(organization.id, first());
379
+ return done({ ...named, revoked: first() });
380
+ }
381
+ if (command === 'workspace create')
382
+ return done({
383
+ ...named,
384
+ ...(await api.createWorkspace({
385
+ name: first(),
386
+ organizationId: organization.id,
387
+ ...(options.template ? { template: options.template } : {}),
388
+ })),
389
+ });
390
+ const workspaces = options.workspace ?? [];
391
+ const roles = options.role ?? [];
392
+ if (workspaces.length !== roles.length)
393
+ throw new Usage('Give one --role for each invited --workspace.');
394
+ const grants = workspaces.map((selector, index) => {
395
+ const workspace = organization.workspaces.find((w) => w.id === selector || w.slug === selector);
396
+ if (!workspace)
397
+ throw new Usage(`Workspace "${selector}" is outside this organization.`);
398
+ return { workspaceId: workspace.id, role: required(roles[index], '--role') };
399
+ });
400
+ return done({
401
+ ...named,
402
+ ...(await api.invite(organization.id, {
403
+ email: first(),
404
+ role: options['org-role'] ?? 'member',
405
+ workspaces: grants,
406
+ })),
407
+ });
408
+ }
409
+ case 'role':
410
+ case 'remove': {
411
+ const organization = options.org ? await ctx.organization() : undefined;
412
+ const workspace = organization ? undefined : await ctx.workspace();
413
+ const api = await ctx.client(workspace);
414
+ const listing = organization
415
+ ? await api.organization(organization.id)
416
+ : await api.members(workspace?.id ?? '');
417
+ const email = first().toLowerCase();
418
+ const candidates = 'candidates' in listing ? listing.candidates : [];
419
+ const member = [
420
+ ...listing.members,
421
+ ...(Array.isArray(candidates) ? candidates : []),
422
+ ].find((m) => m.email.toLowerCase() === email);
423
+ if (!member)
424
+ throw new Usage('That member was not found in this target.');
425
+ const target = organization
426
+ ? { organizationId: organization.id }
427
+ : { workspaceId: workspace?.id ?? '' };
428
+ if (command === 'role')
429
+ await api.setMemberRole(target, member.userId, required(args[1], 'the new role'));
430
+ else
431
+ await api.removeMember(target, member.userId);
432
+ return done({
433
+ ...target,
434
+ userId: member.userId,
435
+ email: member.email,
436
+ role: command === 'role' ? args[1] : null,
437
+ });
438
+ }
439
+ }
440
+ const workspace = await ctx.workspace(['workspace delete', 'mcp-address', 'use'].includes(command) ? args[0] : undefined);
441
+ const api = await ctx.client(workspace);
442
+ const wrap = (value) => done({ workspace, result: value });
443
+ const extensionPath = (suffix) => ctx.workspacePage(workspace, `extensions/${encodeURIComponent(first())}${suffix}`);
444
+ const routinePath = () => ctx.workspacePage(workspace, `routines/${encodeURIComponent(first())}`);
445
+ switch (command) {
446
+ case 'use':
447
+ first();
448
+ await locked(server, () => updateCredentials((file) => {
449
+ const saved = file.servers[server];
450
+ if (!saved)
451
+ throw new LoginRequired();
452
+ saved.workspace = workspace.id;
453
+ }));
454
+ return wrap({ selected: true });
455
+ case 'mcp-address':
456
+ return wrap({ url: pinnedMcpAddress(server, workspace.id) });
457
+ case 'agent chat': {
458
+ const json = options.json === true || !process.stdout.isTTY;
459
+ const chatId = args[0] ?? (await api.createAgentChat(undefined, 'cli')).id;
460
+ const io = {
461
+ write: (text) => process.stdout.write(text),
462
+ color: process.stdout.isTTY && !process.env.NO_COLOR,
463
+ ...(json && options.message
464
+ ? { json: (chunk) => console.log(JSON.stringify(chunk)) }
465
+ : {}),
466
+ };
467
+ if (options.message) {
468
+ const result = await sendMessage(api, chatId, options.message, io);
469
+ if (result.status === 'refused_to_start') {
470
+ return {
471
+ data: {
472
+ workspace,
473
+ chat: chatId,
474
+ error: result.code,
475
+ message: startFailure(result.code ?? ''),
476
+ },
477
+ exit: 1,
478
+ };
479
+ }
480
+ return json
481
+ ? {
482
+ data: { workspace, chat: chatId, status: result.status, code: result.code },
483
+ exit: result.status === 'completed' ? 0 : 1,
484
+ }
485
+ : { data: undefined, exit: result.status === 'completed' ? 0 : 1 };
486
+ }
487
+ if (!process.stdin.isTTY)
488
+ throw new Usage('Give --message <text>, or run agent chat in a terminal.');
489
+ return { data: undefined, exit: await interactiveChat(api, chatId, io) };
490
+ }
491
+ case 'workspace rename':
492
+ return wrap(await api.renameWorkspace(workspace.id, first()));
493
+ case 'workspace delete':
494
+ first();
495
+ return wrap(await api.deleteWorkspace(workspace.id, workspace.name));
496
+ case 'members':
497
+ return wrap(await api.members(workspace.id));
498
+ case 'keys':
499
+ return wrap(await api.keys(workspace.id));
500
+ case 'key create':
501
+ return wrap(await api.createKey(workspace.id, first(), required(options.access, '--access')));
502
+ case 'key revoke':
503
+ await api.revokeKey(workspace.id, first());
504
+ return wrap({ revoked: first() });
505
+ case 'connections':
506
+ return wrap(await api.connections(workspace.id));
507
+ case 'disconnect':
508
+ await api.disconnect(first(), workspace.id);
509
+ return wrap({ disconnected: first() });
510
+ case 'duplicates merge':
511
+ return wrap(await api.mergeSuggestion(first(), required(options.keep, '--keep')));
512
+ case 'duplicates dismiss':
513
+ return wrap(await api.dismissMergeSuggestion(first()));
514
+ case 'pending accept':
515
+ return wrap(await api.decideAssertion(first(), 'accept'));
516
+ case 'pending reject':
517
+ return wrap(await api.decideAssertion(first(), 'reject'));
518
+ case 'schema-changes':
519
+ return wrap(await api.schemaChanges());
520
+ case 'schema-changes approve':
521
+ case 'schema-changes reject': {
522
+ const result = await api.decideSchemaChange(first(), command.endsWith('approve') ? 'approve' : 'reject');
523
+ return { data: { workspace, result }, ...(result.status === 'failed' ? { exit: 1 } : {}) };
524
+ }
525
+ case 'extensions':
526
+ return wrap(await api.extensions());
527
+ case 'extension show':
528
+ return wrap(await api.extension(first()));
529
+ case 'extension disable':
530
+ return wrap(await api.disableExtension(first()));
531
+ case 'extension remove':
532
+ return wrap(await api.uninstallExtension(first()));
533
+ case 'extension install': {
534
+ const name = first();
535
+ const catalog = await api.extensionCatalog();
536
+ const release = catalog.releases.find(({ manifest }) => manifest.universalId === name || manifest.name.toLowerCase() === name.toLowerCase());
537
+ if (!release)
538
+ throw new Usage('This extension is not in the workspace catalog.');
539
+ return waiting({
540
+ url: ctx.workspacePage(workspace, `extensions/new/${encodeURIComponent(release.manifest.universalId)}`),
541
+ });
542
+ }
543
+ case 'extension configure': {
544
+ const extension = await api.extension(first());
545
+ return waiting({
546
+ url: extension.state === 'configuring'
547
+ ? ctx.workspacePage(workspace, `extensions/new/${encodeURIComponent(extension.registrationId)}`)
548
+ : extensionPath('/bindings'),
549
+ });
550
+ }
551
+ case 'extension upgrade':
552
+ return waiting({ url: extensionPath('/upgrade') });
553
+ case 'routines':
554
+ return wrap(await api.routines());
555
+ case 'routine approve': {
556
+ const version = required(args[1], 'the version');
557
+ return waiting({ url: `${routinePath()}?version=${encodeURIComponent(version)}` });
558
+ }
559
+ case 'routine reject': {
560
+ const requested = required(args[1], 'the version');
561
+ const version = /^\d+$/.test(requested)
562
+ ? (await api.routine(first())).versions.find((v) => v.number === Number(requested))?.id
563
+ : requested;
564
+ return wrap(await api.decideRoutineVersion(first(), required(version, 'a version available for review'), 'reject'));
565
+ }
566
+ case 'routine pause':
567
+ return wrap(await api.setRoutineState(first(), 'pause'));
568
+ case 'routine resume':
569
+ ctx.routineUrl = routinePath();
570
+ return wrap(await api.setRoutineState(first(), 'resume'));
571
+ default:
572
+ throw new Usage('Use retainer --help to choose a command.');
573
+ }
574
+ }
575
+ const help = () => ({
576
+ usage: 'retainer <command> [--server <url>] [--workspace <slug|id>] [--json]',
577
+ commands: commands.map(([command, args, target, example]) => ({
578
+ command,
579
+ args,
580
+ target,
581
+ example: `retainer ${example}`,
582
+ })),
583
+ });
584
+ function print(result, json) {
585
+ if (json)
586
+ console.log(JSON.stringify(result));
587
+ else if (result && typeof result === 'object' && 'usage' in result) {
588
+ const description = result;
589
+ console.log(description.usage);
590
+ for (const item of description.commands) {
591
+ console.log(`\n ${item.command} ${item.args}\n ${item.target}\n ${item.example}`);
592
+ }
593
+ }
594
+ else if (result && typeof result === 'object') {
595
+ console.table(Object.fromEntries(Object.entries(result).map(([key, value]) => [
596
+ key,
597
+ typeof value === 'object' ? JSON.stringify(value, null, 2) : value,
598
+ ])));
599
+ }
600
+ else
601
+ console.log(result);
602
+ }
603
+ async function main(argv) {
604
+ let json = !process.stdout.isTTY || argv.includes('--json');
605
+ let ctx;
606
+ let command = '';
607
+ try {
608
+ const parsed = parse(argv);
609
+ json ||= parsed.values.json === true;
610
+ if (parsed.values.help) {
611
+ print(help(), json);
612
+ return 0;
613
+ }
614
+ const [group, subcommand, ...tail] = parsed.positionals;
615
+ const twoWords = `${group} ${subcommand}`;
616
+ const pair = commands.some(([name]) => name === twoWords);
617
+ command = pair ? twoWords : (group ?? '');
618
+ if (!commands.some(([name]) => name === command))
619
+ throw new Usage('Choose a command with retainer --help.');
620
+ const file = await credentials();
621
+ const server = serverOrigin(parsed.values.server ??
622
+ process.env.RETAINER_URL ??
623
+ file.lastServer ??
624
+ 'https://retainer.tamloot.cc');
625
+ ctx = new CommandContext(server, parsed.values, file.servers[server]?.workspace);
626
+ const args = pair ? tail : parsed.positionals.slice(1);
627
+ validateArguments(command, args, parsed.values);
628
+ const result = await execute(ctx, command, args);
629
+ if (result.data !== undefined)
630
+ print(result.data, json);
631
+ return result.exit ?? 0;
632
+ }
633
+ catch (error) {
634
+ const message = error instanceof Error ? error.message : 'The command failed.';
635
+ if (error instanceof KeyMode) {
636
+ print({ error: 'key_mode', message, next: 'retainer-ops --help' }, json);
637
+ return 1;
638
+ }
639
+ if (error instanceof RetainerApiError &&
640
+ error.code === 'confirmation_required' &&
641
+ error.details) {
642
+ const { id, url, expiresAt } = error.details;
643
+ print({ id, url, expiresAt }, json);
644
+ return 6;
645
+ }
646
+ if (error instanceof RetainerApiError &&
647
+ error.code === 'approval_required' &&
648
+ ctx?.routineUrl) {
649
+ print({ url: ctx.routineUrl }, json);
650
+ return 6;
651
+ }
652
+ const loginNeeded = error instanceof LoginRequired || (error instanceof RetainerApiError && error.status === 401);
653
+ const usage = error instanceof Usage ||
654
+ (error instanceof Error &&
655
+ 'code' in error &&
656
+ String(error.code).startsWith('ERR_PARSE_ARGS'));
657
+ const elevation = error instanceof RetainerApiError && error.code === 'elevation_required';
658
+ const next = loginNeeded || command === 'login'
659
+ ? `retainer login${ctx ? ` --server ${quote(ctx.server)}` : ''}`
660
+ : elevation && ctx?.target
661
+ ? `retainer elevate --${ctx.target.type} ${quote(ctx.target.selector)} --reason ${quote(command)}`
662
+ : 'retainer --help';
663
+ print({
664
+ error: loginNeeded
665
+ ? 'not_logged_in'
666
+ : usage
667
+ ? 'invalid_usage'
668
+ : error instanceof RetainerApiError
669
+ ? error.code
670
+ : 'request_failed',
671
+ message,
672
+ next,
673
+ }, json);
674
+ return loginNeeded ? 3 : usage ? 2 : elevation ? 4 : 1;
675
+ }
676
+ }
677
+ process.exitCode = await main(process.argv.slice(2));
678
+ //# sourceMappingURL=index.js.map