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