@ant0/cli 0.0.0-stage → 0.3.22-beta.3

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.
Files changed (67) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +97 -2
  3. package/dist/api/generated/schema.d.ts +11600 -0
  4. package/dist/api/generated/schema.js +6 -0
  5. package/dist/api/index.d.ts +219 -0
  6. package/dist/api/index.js +342 -0
  7. package/dist/bin.d.ts +3 -0
  8. package/dist/bin.js +12 -0
  9. package/dist/bulk.d.ts +38 -0
  10. package/dist/bulk.js +66 -0
  11. package/dist/commands/account.d.ts +48 -0
  12. package/dist/commands/account.js +337 -0
  13. package/dist/commands/api-keys.d.ts +5 -0
  14. package/dist/commands/api-keys.js +310 -0
  15. package/dist/commands/browsers.d.ts +4 -0
  16. package/dist/commands/browsers.js +165 -0
  17. package/dist/commands/daemon.d.ts +15 -0
  18. package/dist/commands/daemon.js +202 -0
  19. package/dist/commands/events.d.ts +8 -0
  20. package/dist/commands/events.js +81 -0
  21. package/dist/commands/extensions.d.ts +4 -0
  22. package/dist/commands/extensions.js +74 -0
  23. package/dist/commands/profiles.d.ts +36 -0
  24. package/dist/commands/profiles.js +552 -0
  25. package/dist/commands/proxies.d.ts +23 -0
  26. package/dist/commands/proxies.js +170 -0
  27. package/dist/commands/sync.d.ts +4 -0
  28. package/dist/commands/sync.js +435 -0
  29. package/dist/commands/team.d.ts +7 -0
  30. package/dist/commands/team.js +403 -0
  31. package/dist/commands/trash.d.ts +10 -0
  32. package/dist/commands/trash.js +54 -0
  33. package/dist/commands/workspace.d.ts +10 -0
  34. package/dist/commands/workspace.js +56 -0
  35. package/dist/context.d.ts +111 -0
  36. package/dist/context.js +300 -0
  37. package/dist/errors.d.ts +27 -0
  38. package/dist/errors.js +96 -0
  39. package/dist/format.d.ts +23 -0
  40. package/dist/format.js +85 -0
  41. package/dist/index.d.ts +19 -0
  42. package/dist/index.js +35 -0
  43. package/dist/inventory.d.ts +50 -0
  44. package/dist/inventory.js +202 -0
  45. package/dist/management-transport.d.ts +3 -0
  46. package/dist/management-transport.js +90 -0
  47. package/dist/native-terminal.d.ts +50 -0
  48. package/dist/native-terminal.js +228 -0
  49. package/dist/program.d.ts +10 -0
  50. package/dist/program.js +185 -0
  51. package/dist/runtime-types.d.ts +20 -0
  52. package/dist/runtime-types.js +2 -0
  53. package/dist/set.d.ts +15 -0
  54. package/dist/set.js +87 -0
  55. package/dist/shared/parse-error.d.ts +6 -0
  56. package/dist/shared/parse-error.js +8 -0
  57. package/dist/shared/proxy-parse.d.ts +42 -0
  58. package/dist/shared/proxy-parse.js +238 -0
  59. package/dist/shared/proxy-types.d.ts +21 -0
  60. package/dist/shared/proxy-types.js +2 -0
  61. package/dist/shared/recovery-code.d.ts +7 -0
  62. package/dist/shared/recovery-code.js +53 -0
  63. package/dist/version.d.ts +8 -0
  64. package/dist/version.js +18 -0
  65. package/licenses/README.md +5 -0
  66. package/licenses/THIRD_PARTY_NOTICES +96 -0
  67. package/package.json +63 -4
@@ -0,0 +1,403 @@
1
+ /** Team administration commands over the daemon's authenticated loopback API. */
2
+ import { isAnt0ApiError, unwrap } from "../api/index.js";
3
+ import { InvalidArgumentError } from "commander";
4
+ import { createHash } from "node:crypto";
5
+ import { UsageError } from "../errors.js";
6
+ import { keyValues, table } from "../format.js";
7
+ import { validateEmail } from "./account.js";
8
+ import { printActiveWorkspace } from "./workspace.js";
9
+ const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;
10
+ const OWNERSHIP_IDEMPOTENCY_DOMAIN = "ant0/cli/ownership-acceptance/idempotency/v1\0";
11
+ const HEADLESS_VAULT_WARNING = "Warning: standalone/headless sync protects its vault key with a mode-0600 file, not the OS keychain.";
12
+ function collect(value, previous) {
13
+ return [...previous, value];
14
+ }
15
+ function parseRole(value) {
16
+ if (value === "manager" || value === "operator" || value === "starter")
17
+ return value;
18
+ throw new InvalidArgumentError("expected manager, operator or starter");
19
+ }
20
+ function parsePositiveInteger(value) {
21
+ const parsed = Number(value);
22
+ if (!Number.isSafeInteger(parsed) || parsed < 1) {
23
+ throw new InvalidArgumentError("expected a positive integer");
24
+ }
25
+ return parsed;
26
+ }
27
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
28
+ export function parseIdempotencyKey(value) {
29
+ if (!UUID_RE.test(value)) {
30
+ throw new UsageError("idempotency key must be a lowercase canonical UUID");
31
+ }
32
+ return value;
33
+ }
34
+ function mutation(command) {
35
+ return command.requiredOption("--idempotency-key <uuid>", "stable UUID to reuse when retrying this mutation", parseIdempotencyKey);
36
+ }
37
+ function headers(opts) {
38
+ return { "idempotency-key": opts.idempotencyKey };
39
+ }
40
+ function withCursor(text, cursor) {
41
+ return cursor === null ? text : `${text}\nnext cursor: ${cursor}`;
42
+ }
43
+ function ensureFolders(folder) {
44
+ const unique = [...new Set(folder)];
45
+ if (unique.length !== folder.length)
46
+ throw new UsageError("--folder values must be unique");
47
+ return unique;
48
+ }
49
+ function rejectSecretArgv(command) {
50
+ if (command.args.length > 0) {
51
+ throw new UsageError("secret values cannot be supplied on argv; use the hidden terminal prompt");
52
+ }
53
+ }
54
+ /** Stable UUID with the same RFC 4122 version/variant normalization as daemon operation IDs. */
55
+ export function deriveOwnershipAcceptanceIdempotencyKey(token) {
56
+ const digest = createHash("sha256").update(OWNERSHIP_IDEMPOTENCY_DOMAIN).update(token).digest();
57
+ const bytes = Buffer.from(digest.subarray(0, 16));
58
+ digest.fill(0);
59
+ try {
60
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
61
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
62
+ const hex = bytes.toString("hex");
63
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
64
+ }
65
+ finally {
66
+ bytes.fill(0);
67
+ }
68
+ }
69
+ async function withToken(terminal, question, action) {
70
+ const input = await terminal.readSecret(question);
71
+ try {
72
+ const token = input.toString("ascii");
73
+ if (!TOKEN_RE.test(token))
74
+ throw new UsageError("token must be 43 base64url characters");
75
+ return await action(input);
76
+ }
77
+ finally {
78
+ input.fill(0);
79
+ }
80
+ }
81
+ async function acceptedOwnership(ctx, operationKey) {
82
+ try {
83
+ return unwrap(await ctx.client().GET("/v1/team/ownership-transfers/accept", {
84
+ params: { header: { "idempotency-key": operationKey } },
85
+ }));
86
+ }
87
+ catch (error) {
88
+ if (isAnt0ApiError(error) &&
89
+ (error.status === 404 || (error.status === 409 && error.code === "ownership.conflict"))) {
90
+ return undefined;
91
+ }
92
+ throw error;
93
+ }
94
+ }
95
+ function writeOwnershipRecovery(terminal, result) {
96
+ const recovery = Buffer.from(result.recovery_code, "ascii");
97
+ try {
98
+ terminal.writeLine("Store this replacement recovery code securely before acknowledging it.");
99
+ terminal.writeSecret("Recovery code: ", recovery);
100
+ }
101
+ finally {
102
+ recovery.fill(0);
103
+ }
104
+ return { workspace_id: result.workspace_id, owner_user_id: result.owner_user_id };
105
+ }
106
+ export function registerTeam(program, ctx) {
107
+ const team = program.command("team").description("Folders, members and invitations");
108
+ team.hook("preAction", async () => printActiveWorkspace(ctx));
109
+ const folders = team.command("folders").description("Team profile folders");
110
+ folders
111
+ .command("list")
112
+ .alias("ls")
113
+ .description("List visible team folders")
114
+ .option("--cursor <cursor>", "continue an earlier listing")
115
+ .action(async (opts) => {
116
+ const result = unwrap(await ctx.client().GET("/v1/team/folders", {
117
+ params: { query: opts.cursor === undefined ? {} : { cursor: opts.cursor } },
118
+ }));
119
+ ctx.emit(result, () => withCursor(table(["id", "name", "version", "updated"], result.items.map((folder) => [
120
+ folder.id,
121
+ folder.name,
122
+ folder.metadata_version,
123
+ folder.updated_at,
124
+ ])), result.next_cursor));
125
+ });
126
+ mutation(folders.command("create <name>").description("Create a team folder")).action(async (name, opts) => {
127
+ const result = unwrap(await ctx.client().POST("/v1/team/folders", {
128
+ params: { header: headers(opts) },
129
+ body: { name },
130
+ }));
131
+ ctx.emit(result, () => keyValues([
132
+ ["folder", result.folder.id],
133
+ ["name", result.folder.name],
134
+ ["version", result.folder.metadata_version],
135
+ ]));
136
+ });
137
+ mutation(folders
138
+ .command("update <id> <name>")
139
+ .description("Rename a team folder with metadata CAS")
140
+ .requiredOption("--metadata-version <n>", "expected metadata version", parsePositiveInteger)).action(async (id, name, opts) => {
141
+ const result = unwrap(await ctx.client().PATCH("/v1/team/folders/{id}", {
142
+ params: { path: { id }, header: headers(opts) },
143
+ body: { expected_metadata_version: opts.metadataVersion, name },
144
+ }));
145
+ ctx.emit(result, () => keyValues([
146
+ ["folder", result.folder.id],
147
+ ["name", result.folder.name],
148
+ ["version", result.folder.metadata_version],
149
+ ]));
150
+ });
151
+ mutation(folders
152
+ .command("remove <id>")
153
+ .description("Delete a folder and optionally move its profiles")
154
+ .requiredOption("--metadata-version <n>", "expected metadata version", parsePositiveInteger)
155
+ .option("--move-profiles-to <id>", "destination folder UUID (default: unfiled)")
156
+ .option("-y, --yes", "do not ask for confirmation")).action(async (id, opts) => {
157
+ await ctx.confirm(`remove team folder ${id}?`, opts.yes);
158
+ unwrap(await ctx.client().DELETE("/v1/team/folders/{id}", {
159
+ params: { path: { id }, header: headers(opts) },
160
+ body: {
161
+ expected_metadata_version: opts.metadataVersion,
162
+ move_profiles_to: opts.moveProfilesTo ?? null,
163
+ },
164
+ }));
165
+ ctx.emit(undefined, () => `removed folder ${id}`);
166
+ });
167
+ const members = team.command("members").description("Accepted workspace members");
168
+ members
169
+ .command("list")
170
+ .alias("ls")
171
+ .description("List team members")
172
+ .option("--cursor <cursor>", "continue an earlier listing")
173
+ .action(async (opts) => {
174
+ const result = unwrap(await ctx.client().GET("/v1/team/members", {
175
+ params: { query: opts.cursor === undefined ? {} : { cursor: opts.cursor } },
176
+ }));
177
+ ctx.emit(result, () => withCursor(table(["id", "email", "role", "state", "key", "folders"], result.items.map((member) => [
178
+ member.user_id,
179
+ member.email,
180
+ member.role,
181
+ member.state,
182
+ member.key_state,
183
+ member.folder_ids.length ? member.folder_ids.join(",") : null,
184
+ ])), result.next_cursor));
185
+ });
186
+ mutation(members
187
+ .command("update <id>")
188
+ .description("Change a member role and folder grants")
189
+ .requiredOption("--role <role>", "manager, operator or starter", parseRole)
190
+ .option("--folder <id>", "granted folder UUID (repeatable)", collect, [])).action(async (id, opts) => {
191
+ const result = unwrap(await ctx.client().PATCH("/v1/team/members/{id}", {
192
+ params: { path: { id }, header: headers(opts) },
193
+ body: { role: opts.role, folder_ids: ensureFolders(opts.folder) },
194
+ }));
195
+ ctx.emit(result, () => keyValues([
196
+ ["member", result.member.user_id],
197
+ ["email", result.member.email],
198
+ ["role", result.member.role],
199
+ ["key state", result.member.key_state],
200
+ ["folders", result.member.folder_ids.length ? result.member.folder_ids.join(",") : null],
201
+ ]));
202
+ });
203
+ mutation(members
204
+ .command("remove <id>")
205
+ .description("Remove a member and immediately revoke new access")
206
+ .option("-y, --yes", "do not ask for confirmation")).action(async (id, opts) => {
207
+ await ctx.confirm(`remove team member ${id}?`, opts.yes);
208
+ unwrap(await ctx.client().DELETE("/v1/team/members/{id}", {
209
+ params: { path: { id }, header: headers(opts) },
210
+ }));
211
+ ctx.emit(undefined, () => `removed member ${id}`);
212
+ });
213
+ const invites = team.command("invites").description("Workspace invitations");
214
+ invites
215
+ .command("list")
216
+ .alias("ls")
217
+ .description("List invitations (tokens are never returned)")
218
+ .option("--cursor <cursor>", "continue an earlier listing")
219
+ .action(async (opts) => {
220
+ const result = unwrap(await ctx.client().GET("/v1/team/invites", {
221
+ params: { query: opts.cursor === undefined ? {} : { cursor: opts.cursor } },
222
+ }));
223
+ ctx.emit(result, () => withCursor(table(["id", "email", "role", "state", "folders", "expires"], result.items.map((invite) => [
224
+ invite.id,
225
+ invite.email,
226
+ invite.role,
227
+ invite.state,
228
+ invite.folder_ids.length ? invite.folder_ids.join(",") : null,
229
+ invite.expires_at,
230
+ ])), result.next_cursor));
231
+ });
232
+ mutation(invites
233
+ .command("create <email>")
234
+ .description("Invite a verified account to the workspace")
235
+ .requiredOption("--role <role>", "manager, operator or starter", parseRole)
236
+ .option("--folder <id>", "granted folder UUID (repeatable)", collect, [])).action(async (email, opts) => {
237
+ const result = unwrap(await ctx.client().POST("/v1/team/invites", {
238
+ params: { header: headers(opts) },
239
+ body: {
240
+ email: validateEmail(email),
241
+ role: opts.role,
242
+ folder_ids: ensureFolders(opts.folder),
243
+ },
244
+ }));
245
+ ctx.emit(result, () => keyValues([
246
+ ["invite", result.invite.id],
247
+ ["email", result.invite.email],
248
+ ["role", result.invite.role],
249
+ ["state", result.invite.state],
250
+ ["expires", result.invite.expires_at],
251
+ ]));
252
+ });
253
+ mutation(invites.command("revoke <id>").description("Revoke a pending invitation")).action(async (id, opts) => {
254
+ unwrap(await ctx.client().POST("/v1/team/invites/{id}/revoke", {
255
+ params: { path: { id }, header: headers(opts) },
256
+ body: {},
257
+ }));
258
+ ctx.emit(undefined, () => `revoked invite ${id}`);
259
+ });
260
+ mutation(invites
261
+ .command("accept")
262
+ .description("Accept an invitation; reads its token without echo from an interactive terminal")
263
+ // Absorb unexpected values so Commander never reflects a token-looking `--value` in errors.
264
+ .allowUnknownOption()
265
+ .allowExcessArguments()).action(async (opts, command) => {
266
+ rejectSecretArgv(command);
267
+ const result = await ctx.withNativeTerminal("invitation acceptance", async (terminal) => {
268
+ return withToken(terminal, "Invitation token: ", async (token) => unwrap(await ctx.client().POST("/v1/team/invites/accept", {
269
+ params: { header: headers(opts) },
270
+ body: { token: token.toString("ascii") },
271
+ })));
272
+ });
273
+ ctx.emit(result, () => `${keyValues([
274
+ ["workspace", result.workspace_id],
275
+ ["member", result.member.user_id],
276
+ ["role", result.member.role],
277
+ ["key state", result.key_state],
278
+ ])}\nRun \`ant0 workspace switch ${result.workspace_id}\` to use the accepted workspace.`);
279
+ });
280
+ const ownership = team.command("ownership").description("Workspace ownership transfer");
281
+ for (const direction of ["outgoing", "incoming"]) {
282
+ ownership
283
+ .command(direction)
284
+ .description(`List ${direction} ownership transfers`)
285
+ .option("--cursor <cursor>", "continue an earlier listing")
286
+ .action(async (opts) => {
287
+ const path = `/v1/team/ownership-transfers/${direction}`;
288
+ const result = unwrap(await ctx.client().GET(path, {
289
+ params: { query: opts.cursor === undefined ? {} : { cursor: opts.cursor } },
290
+ }));
291
+ ctx.emit(result, () => withCursor(table(["id", "workspace", "name", "from", "to", "state", "expires"], result.items.map((item) => [
292
+ item.transfer_id,
293
+ item.workspace_id,
294
+ item.workspace_name,
295
+ item.from_user_id,
296
+ item.to_user_id,
297
+ item.state,
298
+ item.expires_at,
299
+ ])), result.next_cursor));
300
+ });
301
+ }
302
+ mutation(ownership
303
+ .command("start <user>")
304
+ .description("Offer workspace ownership to an accepted key-ready member")).action(async (user, opts) => {
305
+ const result = unwrap(await ctx.client().POST("/v1/team/ownership-transfers", {
306
+ params: { header: headers(opts) },
307
+ body: { target_user_id: user },
308
+ }));
309
+ ctx.emit(result, () => keyValues([
310
+ ["transfer", result.transfer_id],
311
+ ["expires", result.expires_at],
312
+ ]));
313
+ });
314
+ ownership
315
+ .command("accept")
316
+ .description("Accept ownership and show its recovery code on the controlling terminal")
317
+ // Absorb unexpected values so Commander never reflects a token-looking `--value` in errors.
318
+ .allowUnknownOption()
319
+ .allowExcessArguments()
320
+ .action(async (_opts, command) => {
321
+ rejectSecretArgv(command);
322
+ const publicResult = await ctx.withNativeTerminal("ownership acceptance", async (terminal) => {
323
+ terminal.writeLine(HEADLESS_VAULT_WARNING);
324
+ return withToken(terminal, "Ownership transfer token: ", async (token) => {
325
+ const operationKey = deriveOwnershipAcceptanceIdempotencyKey(token);
326
+ const recovered = await acceptedOwnership(ctx, operationKey);
327
+ let result = recovered;
328
+ if (!result) {
329
+ const workspaces = unwrap(await ctx.client().GET("/v1/workspaces"));
330
+ if (workspaces.current_workspace_id === null) {
331
+ throw new UsageError("ownership acceptance requires a current workspace");
332
+ }
333
+ result = unwrap(await ctx.client().POST("/v1/team/ownership-transfers/accept", {
334
+ params: { header: { "idempotency-key": operationKey } },
335
+ body: {
336
+ token: token.toString("ascii"),
337
+ expected_workspace_id: workspaces.current_workspace_id,
338
+ },
339
+ }));
340
+ }
341
+ return writeOwnershipRecovery(terminal, result);
342
+ });
343
+ });
344
+ ctx.emit(publicResult, () => keyValues([
345
+ ["workspace", publicResult.workspace_id],
346
+ ["owner", publicResult.owner_user_id],
347
+ ]));
348
+ });
349
+ ownership
350
+ .command("status")
351
+ .description("Retrieve a retained recovery code using the emailed token")
352
+ // Absorb unexpected values so Commander never reflects a token-looking `--value` in errors.
353
+ .allowUnknownOption()
354
+ .allowExcessArguments()
355
+ .action(async (_opts, command) => {
356
+ rejectSecretArgv(command);
357
+ const publicResult = await ctx.withNativeTerminal("ownership recovery retrieval", async (terminal) => {
358
+ terminal.writeLine(HEADLESS_VAULT_WARNING);
359
+ return withToken(terminal, "Ownership transfer token: ", async (token) => {
360
+ const result = unwrap(await ctx.client().GET("/v1/team/ownership-transfers/accept", {
361
+ params: {
362
+ header: {
363
+ "idempotency-key": deriveOwnershipAcceptanceIdempotencyKey(token),
364
+ },
365
+ },
366
+ }));
367
+ return writeOwnershipRecovery(terminal, result);
368
+ });
369
+ });
370
+ ctx.emit(publicResult, () => keyValues([
371
+ ["workspace", publicResult.workspace_id],
372
+ ["owner", publicResult.owner_user_id],
373
+ ]));
374
+ });
375
+ ownership
376
+ .command("acknowledge")
377
+ .description("Clear a retained recovery code after storing it safely")
378
+ .option("-y, --yes", "do not ask for confirmation")
379
+ // Absorb unexpected values so Commander never reflects a token-looking `--value` in errors.
380
+ .allowUnknownOption()
381
+ .allowExcessArguments()
382
+ .action(async (opts, command) => {
383
+ rejectSecretArgv(command);
384
+ const operationKey = await ctx.withNativeTerminal("ownership recovery acknowledgement", async (terminal) => withToken(terminal, "Ownership transfer token: ", async (token) => deriveOwnershipAcceptanceIdempotencyKey(token)));
385
+ await ctx.confirm("clear the retained ownership recovery code?", opts.yes);
386
+ unwrap(await ctx.client().DELETE("/v1/team/ownership-transfers/accept", {
387
+ params: { header: { "idempotency-key": operationKey } },
388
+ }));
389
+ ctx.emit(undefined, () => "ownership recovery code acknowledged and cleared");
390
+ });
391
+ mutation(ownership
392
+ .command("cancel <id>")
393
+ .description("Cancel a pending ownership transfer")
394
+ .option("-y, --yes", "do not ask for confirmation")).action(async (id, opts) => {
395
+ await ctx.confirm(`cancel ownership transfer ${id}?`, opts.yes);
396
+ unwrap(await ctx.client().POST("/v1/team/ownership-transfers/{id}/cancel", {
397
+ params: { path: { id }, header: headers(opts) },
398
+ body: {},
399
+ }));
400
+ ctx.emit(undefined, () => `cancelled ownership transfer ${id}`);
401
+ });
402
+ }
403
+ //# sourceMappingURL=team.js.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `ant0 trash ls [-q --group --tag --limit --offset] | empty [--yes]`.
3
+ *
4
+ * Trashed profiles keep everything (`GET /trash` lists them with `purge_at`); the daemon's sweeper
5
+ * purges them after `trash_retention_days`. `empty` purges them all now, running ones excepted.
6
+ */
7
+ import type { Command } from "commander";
8
+ import type { Context } from "../context.js";
9
+ export declare function registerTrash(program: Command, ctx: Context): void;
10
+ //# sourceMappingURL=trash.d.ts.map
@@ -0,0 +1,54 @@
1
+ import { unwrap } from "../api/index.js";
2
+ import { UsageError } from "../errors.js";
3
+ import { table } from "../format.js";
4
+ import { SUMMARY_HEADERS, summaryRows } from "./profiles.js";
5
+ function positiveInt(flag) {
6
+ return (value) => {
7
+ const n = Number(value);
8
+ if (!Number.isInteger(n) || n < 0)
9
+ throw new UsageError(`${flag} expects a non-negative integer`);
10
+ return n;
11
+ };
12
+ }
13
+ export function registerTrash(program, ctx) {
14
+ const trash = program
15
+ .command("trash")
16
+ .description("Profiles waiting in the trash (restore with `ant0 profiles restore`)");
17
+ trash
18
+ .command("ls")
19
+ .description("List trashed profiles and when each will be purged")
20
+ .option("-q, --query <text>", "filter by name substring")
21
+ .option("--group <name>", "filter by group")
22
+ .option("--tag <tag>", "filter by tag")
23
+ .option("--limit <n>", "page size", positiveInt("--limit"))
24
+ .option("--offset <n>", "page offset", positiveInt("--offset"))
25
+ .action(async (opts) => {
26
+ const data = unwrap(await ctx.client().GET("/v1/trash", {
27
+ params: {
28
+ query: {
29
+ ...(opts.query !== undefined ? { q: opts.query } : {}),
30
+ ...(opts.group !== undefined ? { group: opts.group } : {}),
31
+ ...(opts.tag !== undefined ? { tag: opts.tag } : {}),
32
+ ...(opts.limit !== undefined ? { limit: opts.limit } : {}),
33
+ ...(opts.offset !== undefined ? { offset: opts.offset } : {}),
34
+ },
35
+ },
36
+ }));
37
+ ctx.emit(data, () => {
38
+ const body = table([...SUMMARY_HEADERS, "deleted", "purge at"], data.items.map((p) => [...summaryRows([p])[0], p.deleted_at, p.purge_at]));
39
+ return data.items.length === 0
40
+ ? body
41
+ : `${body}\n(${data.total} trashed; kept ${data.trash_retention_days} day(s) after deletion)`;
42
+ });
43
+ });
44
+ trash
45
+ .command("empty")
46
+ .description("Permanently delete every trashed profile now (running ones are skipped)")
47
+ .option("-y, --yes", "do not ask for confirmation")
48
+ .action(async (opts) => {
49
+ await ctx.confirm("permanently delete every profile in the trash?", opts.yes);
50
+ const result = unwrap(await ctx.client().DELETE("/v1/trash"));
51
+ ctx.emit(result, () => `purged ${result.purged} profile(s)`);
52
+ });
53
+ }
54
+ //# sourceMappingURL=trash.js.map
@@ -0,0 +1,10 @@
1
+ /** Account workspace selection over the daemon's persisted cloud session. */
2
+ import { type components } from "../api/index.js";
3
+ import { type Command } from "commander";
4
+ import type { Context } from "../context.js";
5
+ type LicenceState = components["schemas"]["LicenceState"];
6
+ export declare function activeWorkspaceLine(workspace: LicenceState["workspace"]): string;
7
+ export declare function printActiveWorkspace(ctx: Context): Promise<void>;
8
+ export declare function registerWorkspace(program: Command, ctx: Context): void;
9
+ export {};
10
+ //# sourceMappingURL=workspace.d.ts.map
@@ -0,0 +1,56 @@
1
+ /** Account workspace selection over the daemon's persisted cloud session. */
2
+ import { unwrap } from "../api/index.js";
3
+ import { InvalidArgumentError } from "commander";
4
+ import { keyValues, table } from "../format.js";
5
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
6
+ function workspaceId(value) {
7
+ if (!UUID_RE.test(value))
8
+ throw new InvalidArgumentError("expected a lowercase canonical UUID");
9
+ return value;
10
+ }
11
+ export function activeWorkspaceLine(workspace) {
12
+ return workspace === null
13
+ ? "active workspace unavailable (run `ant0 workspace list`)"
14
+ : `active workspace ${workspace.name ?? "-"} (${workspace.id})`;
15
+ }
16
+ export async function printActiveWorkspace(ctx) {
17
+ const licence = unwrap(await ctx.client().GET("/v1/licence"));
18
+ if (!ctx.json)
19
+ ctx.out(activeWorkspaceLine(licence.workspace));
20
+ }
21
+ function workspaceRows(result) {
22
+ return result.workspaces.map((workspace) => [
23
+ workspace.id === result.current_workspace_id ? "*" : "",
24
+ workspace.id,
25
+ workspace.name,
26
+ workspace.role,
27
+ workspace.status,
28
+ workspace.usability,
29
+ workspace.plan.id,
30
+ workspace.plan.profiles,
31
+ workspace.seats,
32
+ ]);
33
+ }
34
+ export function registerWorkspace(program, ctx) {
35
+ const workspace = program.command("workspace").description("List and select account workspaces");
36
+ workspace
37
+ .command("list")
38
+ .alias("ls")
39
+ .description("List workspaces available to the signed-in account")
40
+ .action(async () => {
41
+ const result = unwrap(await ctx.client().GET("/v1/workspaces"));
42
+ ctx.emit(result, () => `${keyValues([
43
+ ["account", `${result.account.email} (${result.account.id})`],
44
+ ["current workspace", result.current_workspace_id],
45
+ ])}\n\n${table(["current", "id", "name", "role", "status", "usability", "plan", "profiles", "seats"], workspaceRows(result))}`);
46
+ });
47
+ workspace
48
+ .command("switch")
49
+ .description("Switch this daemon session to another usable workspace")
50
+ .argument("<id>", "workspace UUID", workspaceId)
51
+ .action(async (id) => {
52
+ const result = unwrap(await ctx.client().POST("/v1/workspaces/current", { body: { workspace_id: id } }));
53
+ ctx.emit(result, () => activeWorkspaceLine(result.workspace));
54
+ });
55
+ }
56
+ //# sourceMappingURL=workspace.js.map
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Per-invocation state shared by every command: the streams, the environment, the global flags
3
+ * (`--home`, `--port`, `--json`) and a lazily created API client.
4
+ */
5
+ import { type Ant0Client, type DiscoveredDaemon } from "./api/index.js";
6
+ import { type NativeTerminal } from "./native-terminal.js";
7
+ import { type CredentialFile, type KeyGrant } from "@ant0/mcp/credentials";
8
+ import type { RuntimeCommands } from "./runtime-types.js";
9
+ export interface Writer {
10
+ write(chunk: string): unknown;
11
+ }
12
+ /**
13
+ * What prompting commands need from stdin: a TTY check, a line reader when interactive, and raw
14
+ * mode for the password prompt (`login`), which a real `tty.ReadStream` provides.
15
+ */
16
+ export interface Reader extends NodeJS.ReadableStream {
17
+ isTTY?: boolean;
18
+ isRaw?: boolean;
19
+ setRawMode?(mode: boolean): unknown;
20
+ }
21
+ export interface RunIo {
22
+ stdout: Writer;
23
+ stderr: Writer;
24
+ env: Record<string, string | undefined>;
25
+ /** Injected fetch (tests). Default: `globalThis.fetch`. */
26
+ fetch?: typeof fetch;
27
+ /** Aborting stops long-running commands (`events`); default is SIGINT. */
28
+ signal?: AbortSignal;
29
+ /**
30
+ * Confirmation prompts (`rm --permanent`, `trash empty`), `login`'s prompts and
31
+ * `--password-stdin`. Default: `process.stdin`.
32
+ */
33
+ stdin?: Reader;
34
+ /** Injected direct controlling terminal (tests/embedding). `null` means unavailable. */
35
+ nativeTerminal?: NativeTerminal | null;
36
+ /** OS browser opening and wait seams; tests never launch a real browser. */
37
+ openBrowser?: (url: string) => Promise<void>;
38
+ wait?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
39
+ }
40
+ export interface GlobalOptions {
41
+ credentialFile?: string;
42
+ apiKeyStdin?: boolean;
43
+ home?: string;
44
+ port?: number;
45
+ json?: boolean;
46
+ }
47
+ export declare class Context {
48
+ readonly io: RunIo;
49
+ readonly runtime?: RuntimeCommands | undefined;
50
+ private globalsFn;
51
+ private cached;
52
+ private cachedKey;
53
+ private delegated;
54
+ private secret;
55
+ private grant;
56
+ credential: CredentialFile | undefined;
57
+ apiKey: string | undefined;
58
+ constructor(io: RunIo, runtime?: RuntimeCommands | undefined);
59
+ /** Installed by the program builder once the root command exists. */
60
+ bindGlobals(fn: () => GlobalOptions): void;
61
+ get globals(): GlobalOptions;
62
+ get json(): boolean;
63
+ /** Where the daemon should be, according to flags, pid file and environment. */
64
+ connection(): DiscoveredDaemon;
65
+ /**
66
+ * `connection()` for a command that sends the token: a token file that is not private is
67
+ * refused here (or warned about with ANT0_ALLOW_SHARED_TOKEN_FILE=1), not during discovery, so
68
+ * daemon start/stop/status and health checks keep working.
69
+ */
70
+ authenticatedConnection(): DiscoveredDaemon;
71
+ keyMode(): boolean;
72
+ /** Authenticated client; throws `DaemonNotRunningError` when there is no token to send. */
73
+ client(): Ant0Client;
74
+ /** Scopes come from the private file, or from the key's own status in env/stdin mode. */
75
+ keyGrant(): Promise<KeyGrant | undefined>;
76
+ /** Provisioning's credential-file is an output/recovery record, never its authentication. */
77
+ managementClient(): Ant0Client;
78
+ /** Unauthenticated client (health checks). */
79
+ openClient(): Ant0Client;
80
+ private clientFor;
81
+ openBrowser(url: string): Promise<void>;
82
+ wait(milliseconds: number): Promise<void>;
83
+ fetch(): typeof fetch;
84
+ out(text: string): void;
85
+ err(text: string): void;
86
+ /**
87
+ * Gate an irreversible action. `--yes` skips the question; on a terminal the user is asked on
88
+ * stderr; without a terminal the command refuses (exit 2) so scripts never hang or destroy data
89
+ * by accident.
90
+ */
91
+ /** `refusal` replaces the generic "pass --yes" message when there is no terminal to ask on. */
92
+ confirm(question: string, yes: boolean | undefined, refusal?: string): Promise<void>;
93
+ private get stdin();
94
+ /** Whether prompts are possible (stdin is a terminal). */
95
+ interactive(): boolean;
96
+ /** Ask one line on the terminal (echoed); refuses without one (exit 2). */
97
+ prompt(question: string): Promise<string>;
98
+ /**
99
+ * Ask a secret on the terminal without echo (raw mode, Backspace edits, Ctrl-C aborts with exit
100
+ * 2). Without a terminal the command must take `--password-stdin` instead.
101
+ */
102
+ promptSecret(question: string): Promise<string>;
103
+ /** Run a native-secret operation on the controlling terminal, never stdin/stdout/stderr. */
104
+ withNativeTerminal<T>(operation: string, action: (terminal: NativeTerminal) => Promise<T>): Promise<T>;
105
+ private readSecret;
106
+ /** The first line of stdin (`--password-stdin`): everything up to the first newline or EOF. */
107
+ readStdinLine(): Promise<string>;
108
+ /** `--json`: the payload verbatim (nothing for a 204); otherwise the human rendering. */
109
+ emit(payload: unknown, human: () => string | undefined): void;
110
+ }
111
+ //# sourceMappingURL=context.d.ts.map