formist-cli 0.1.0__py3-none-any.whl

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.
formist_cli/spaces.py ADDED
@@ -0,0 +1,693 @@
1
+ """``fm spaces`` - your own spaces by default, or (``--admin``) a platform-admin
2
+ view of every space across every region, plus operations on one space's
3
+ members, conversations, skills, invitations and plan usage.
4
+
5
+ ``list`` (the default, no subject needed) returns the spaces the signed-in
6
+ caller is a member of, needing no flag: ``GET /projects``, the same route the
7
+ web app's own space picker reads. ``list --admin`` instead returns every
8
+ space on the platform, with member counts: ``GET /admin/spaces``. Every other
9
+ subject requires a space id AND ``--admin``; none of them has a member-level
10
+ equivalent in this command.
11
+
12
+ ``list --admin``, ``conversations``, ``skills`` and ``invitations`` are all
13
+ server-paginated, so every listing reports shown and total together with the
14
+ flag that widens the view, the same contract ``fm users list`` and ``fm
15
+ audit-log --admin`` use. Plain ``list`` (no ``--admin``) is not paginated:
16
+ nobody is a member of enough spaces for a server-side cap to matter.
17
+
18
+ Writes (``rename``, ``delete``, ``transfer-ownership``, ``delete-conversation``,
19
+ ``delete-skill``, ``delete-invitation``, ``create``, ``add-member``) have no
20
+ server-side dry run: each takes effect immediately. ``--env`` never inherits
21
+ from `fm use` on a write. ``delete`` is irreversible (it permanently deletes
22
+ the space and every row/blob under it) and requires ``--confirm``, mirroring
23
+ the server's own confirmation requirement.
24
+
25
+ ``create`` differs from every other subject here: it calls ``POST /projects``
26
+ (the ordinary product route, not ``/admin``) with the caller's own token, and
27
+ the caller becomes the new space's owner, same as creating a workspace in the
28
+ app. It lives in this module because an operator thinks of it as one more
29
+ thing `fm spaces` does to a space.
30
+
31
+ ``add-member`` wraps the same route ``fm users add-space`` does
32
+ (``POST /admin/users/{user_id}/spaces``): a second door onto that route for an
33
+ operator who has an email rather than a user id, resolved by walking
34
+ ``GET /admin/users`` (which has no server-side email filter). It sends no
35
+ email and creates no invitation row; it is an immediate membership grant.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import argparse
41
+ import json
42
+
43
+ from formist_cli import api, context, privileges
44
+ from formist_cli.cli_support import add_admin_flag, pagination_footer
45
+ from formist_cli.cli_support import as_dict as _shared_space_payload
46
+ from formist_cli.cli_support import build_standalone_parser as _build_standalone_parser
47
+ from formist_cli.targets import require_space_id
48
+ from formist_cli.users import render_membership_change
49
+
50
+ SUBJECTS = (
51
+ "list", "members", "conversations", "delete-conversation",
52
+ "skills", "delete-skill", "invitations", "delete-invitation",
53
+ "usage", "rename", "delete", "transfer-ownership",
54
+ "create", "add-member",
55
+ )
56
+ DEFAULT_SUBJECT = "list"
57
+
58
+ #: Every project-role string the server accepts for ``--role``. Checked here
59
+ #: too so a typo'd ``--role`` is a readable local refusal instead of a 400
60
+ #: from the server.
61
+ _ROLES = ("OWNER", "ADMIN", "USER", "VIEWER")
62
+
63
+ #: Subjects resolved with ``for_write=True``, same rule as ``fm users``.
64
+ _MUTATING_SUBJECTS = frozenset({
65
+ "delete-conversation", "delete-skill", "delete-invitation",
66
+ "rename", "delete", "transfer-ownership", "create", "add-member",
67
+ })
68
+
69
+ #: (subject, server field name) for the three delete-a-child-object subjects,
70
+ #: shared so the argparse help, the dispatch and the error messages cannot list
71
+ #: three different names for the same id.
72
+ _CHILD_LABEL = {
73
+ "delete-conversation": "chat_id",
74
+ "delete-skill": "skill_id",
75
+ "delete-invitation": "invitation_id",
76
+ }
77
+
78
+
79
+ class SpacesError(Exception):
80
+ """A refusal about the space surface, written for an operator."""
81
+
82
+
83
+ def canonical_subject(subject: str | None) -> str:
84
+ if subject is None:
85
+ return DEFAULT_SUBJECT
86
+ value = subject.strip().lower()
87
+ if value not in SUBJECTS:
88
+ raise SpacesError(
89
+ f"unknown subcommand {subject!r}. Valid: {', '.join(SUBJECTS)}.\n"
90
+ " list your own spaces, the default (--admin: every "
91
+ "space, every region, paginated)\n"
92
+ " create create a new workspace; you become its OWNER\n"
93
+ " members a space's members and roles (--admin)\n"
94
+ " conversations a space's chat sessions, paginated (--admin)\n"
95
+ " delete-conversation delete one conversation + its messages (--admin)\n"
96
+ " skills a space's skills, paginated (--admin)\n"
97
+ " delete-skill delete (soft) one skill (--admin)\n"
98
+ " invitations a space's pending/decided invitations, "
99
+ "paginated (--admin)\n"
100
+ " delete-invitation revoke a still-PENDING invitation (--admin)\n"
101
+ " usage subscription + token usage for this space (--admin)\n"
102
+ " rename set the space's name (--admin)\n"
103
+ " delete PERMANENTLY delete the space and everything "
104
+ "under it (--admin)\n"
105
+ " transfer-ownership move OWNER to a different existing member (--admin)\n"
106
+ " add-member assign an existing platform user (by email) to "
107
+ "a space (--admin)"
108
+ )
109
+ return value
110
+
111
+
112
+ # ===========================================================================
113
+ # Rendering - reads
114
+ # ===========================================================================
115
+ def render_space_list(payload: dict) -> str:
116
+ """Every space, never overstating how much of the platform it saw."""
117
+ items = payload.get("items") or []
118
+ total = payload.get("total")
119
+ offset = int(payload.get("offset") or 0)
120
+
121
+ lines = [
122
+ f"{'region':<7} {'members':<8} {'name':<32} id",
123
+ f"{'-' * 7} {'-' * 8} {'-' * 32} {'-' * 8}",
124
+ ]
125
+ for row in items:
126
+ lines.append(
127
+ f"{str(row.get('region') or '?'):<7} "
128
+ f"{row.get('member_count', '?'):<8} "
129
+ f"{str(row.get('name') or '-'):<32.32} "
130
+ f"{row.get('id')}"
131
+ )
132
+
133
+ lines.append("\n" + pagination_footer(shown=len(items), total=total, offset=offset))
134
+ return "\n".join(lines)
135
+
136
+
137
+ def render_my_spaces(payload: dict) -> str:
138
+ """``GET /projects``: the spaces the signed-in caller is a member of.
139
+
140
+ No pagination and no ``member_count`` here: the route returns every
141
+ space the user belongs to in one response (nobody is a member of enough
142
+ spaces for a server-side cap to matter), and the admin aggregate
143
+ `member_count` is not something a non-admin member reads about their own
144
+ space. `role` takes that column instead: it is what the caller already
145
+ knows about each one.
146
+ """
147
+ items = payload.get("items") or []
148
+ if not items:
149
+ return "(you are not a member of any space)"
150
+ lines = [
151
+ f"{'region':<7} {'role':<6} {'name':<32} id",
152
+ f"{'-' * 7} {'-' * 6} {'-' * 32} {'-' * 8}",
153
+ ]
154
+ for row in items:
155
+ lines.append(
156
+ f"{str(row.get('region') or '?'):<7} "
157
+ f"{str(row.get('role') or '?'):<6} "
158
+ f"{str(row.get('name') or '-'):<32.32} "
159
+ f"{row.get('id')}"
160
+ )
161
+ return "\n".join(lines)
162
+
163
+
164
+ def render_members(payload: dict) -> str:
165
+ items = payload.get("items") or []
166
+ if not items:
167
+ return "(this space has no members)"
168
+ lines = [
169
+ f"{'email':<34} {'name':<20} {'role':<8} user_id",
170
+ f"{'-' * 34} {'-' * 20} {'-' * 8} {'-' * 8}",
171
+ ]
172
+ for row in items:
173
+ lines.append(
174
+ f"{str(row.get('email') or '-'):<34.34} "
175
+ f"{str(row.get('name') or '-'):<20.20} "
176
+ f"{str(row.get('role') or '-'):<8} "
177
+ f"{row.get('user_id')}"
178
+ )
179
+ return "\n".join(lines)
180
+
181
+
182
+ def _paginated(payload: dict, rows: list[str], *, header: list[str], noun: str) -> str:
183
+ """Shared body for the three paginated per-space listings, one place that
184
+ can misreport shown vs. total, not three."""
185
+ items = payload.get("items") or []
186
+ total = payload.get("total")
187
+ offset = int(payload.get("offset") or 0)
188
+ if not items:
189
+ return f"(this space has no {noun})"
190
+ lines = list(header) + rows
191
+ lines.append("\n" + pagination_footer(shown=len(items), total=total, offset=offset))
192
+ return "\n".join(lines)
193
+
194
+
195
+ def render_conversations(payload: dict) -> str:
196
+ items = payload.get("items") or []
197
+ rows = [
198
+ f"{str(c.get('title') or '(untitled)'):<40.40} "
199
+ f"{str(c.get('model') or '-'):<20} "
200
+ f"{('archived' if c.get('archived') else ''):<8} "
201
+ f"{c.get('id')}"
202
+ for c in items
203
+ ]
204
+ header = [
205
+ f"{'title':<40} {'model':<20} {'':<8} id",
206
+ f"{'-' * 40} {'-' * 20} {'-' * 8} {'-' * 8}",
207
+ ]
208
+ return _paginated(payload, rows, header=header, noun="conversations")
209
+
210
+
211
+ def render_skills(payload: dict) -> str:
212
+ items = payload.get("items") or []
213
+ rows = [
214
+ f"{str(s.get('name') or '-'):<30.30} "
215
+ f"{('enabled' if s.get('enabled') else 'disabled'):<8} "
216
+ f"{s.get('id')}"
217
+ for s in items
218
+ ]
219
+ header = [f"{'name':<30} {'':<8} id", f"{'-' * 30} {'-' * 8} {'-' * 8}"]
220
+ return _paginated(payload, rows, header=header, noun="skills")
221
+
222
+
223
+ def render_invitations(payload: dict) -> str:
224
+ items = payload.get("items") or []
225
+ rows = [
226
+ f"{str(i.get('email') or '-'):<34.34} "
227
+ f"{str(i.get('role') or '-'):<8} "
228
+ f"{str(i.get('status') or '-'):<10} "
229
+ f"{i.get('id')}"
230
+ for i in items
231
+ ]
232
+ header = [
233
+ f"{'email':<34} {'role':<8} {'status':<10} id",
234
+ f"{'-' * 34} {'-' * 8} {'-' * 10} {'-' * 8}",
235
+ ]
236
+ return _paginated(payload, rows, header=header, noun="invitations")
237
+
238
+
239
+ def render_usage(payload: dict) -> str:
240
+ """Subscription status plus token usage. ``tokens_used_this_period`` is
241
+ what gets invoiced; ``current_cycle`` is every LLM call this space made,
242
+ including calls outside an agent run, so the two numbers can differ."""
243
+ lines = [
244
+ f"plan {payload.get('plan') or '(none)'} status={payload.get('status')}",
245
+ f"seats {payload.get('seats')}",
246
+ f"period ends {payload.get('current_period_end') or '?'}",
247
+ f"invoiced {payload.get('tokens_used_this_period')} / "
248
+ f"{payload.get('included_tokens')} included tokens "
249
+ f"(overage {payload.get('overage_tokens')})",
250
+ ]
251
+ cycle = payload.get("current_cycle") or {}
252
+ if cycle:
253
+ lines.append("current_cycle (this space's own billing_reset_day, ALL LLM calls):")
254
+ for key in sorted(cycle):
255
+ lines.append(f" {key:<28} {cycle[key]}")
256
+ return "\n".join(lines)
257
+
258
+
259
+ # ===========================================================================
260
+ # Rendering - writes
261
+ # ===========================================================================
262
+ def render_rename(payload: dict) -> str:
263
+ return f"renamed {payload.get('id')} -> {payload.get('name')!r}"
264
+
265
+
266
+ def render_delete(payload: dict) -> str:
267
+ return (
268
+ f"DELETED {payload.get('deleted')}\n"
269
+ f" rows {payload.get('rows')}\n"
270
+ f" blobs {payload.get('blobs')}"
271
+ )
272
+
273
+
274
+ def render_transfer(payload: dict) -> str:
275
+ return (
276
+ f"transferred space={payload.get('space_id')}\n"
277
+ f" {payload.get('old_owner_user_id')} -> {payload.get('new_owner_user_id')} (OWNER)\n"
278
+ f" outgoing owner demoted to {payload.get('old_owner_demoted_to') or '(unchanged, no prior owner rel)'}"
279
+ )
280
+
281
+
282
+ def render_child_delete(payload: dict, *, noun: str) -> str:
283
+ return f"deleted {noun} {payload.get('deleted')}"
284
+
285
+
286
+ def render_created(payload: dict) -> str:
287
+ """``POST /projects``'s response, trimmed to what an operator needs next."""
288
+ return (
289
+ f"created {payload.get('id')}\n"
290
+ f" name {payload.get('name')!r}\n"
291
+ f" region {payload.get('region')}\n"
292
+ f" role {payload.get('role')} (you)"
293
+ )
294
+
295
+
296
+ # ===========================================================================
297
+ # CLI
298
+ # ===========================================================================
299
+ _HELP = "your own spaces, the default; --admin for every space and its members/usage/etc"
300
+
301
+ _DESCRIPTION = """Spaces: your own by default, or (--admin) a platform-admin view of any.
302
+
303
+ fm spaces your own spaces, the default
304
+ fm spaces create --name 'New Workspace' --country ae
305
+ fm spaces --admin every space, every region (paginated)
306
+ fm spaces --admin members <space-id>
307
+ fm spaces --admin conversations <space-id> [--limit --offset]
308
+ fm spaces --admin delete-conversation <space-id> <chat-id>
309
+ fm spaces --admin skills <space-id> [--limit --offset]
310
+ fm spaces --admin delete-skill <space-id> <skill-id>
311
+ fm spaces --admin invitations <space-id> [--limit --offset]
312
+ fm spaces --admin delete-invitation <space-id> <invitation-id>
313
+ fm spaces --admin usage <space-id>
314
+ fm spaces --admin rename <space-id> --name 'New Name'
315
+ fm spaces --admin delete <space-id> --confirm # IRREVERSIBLE
316
+ fm spaces --admin transfer-ownership <space-id> --new-owner <user-id>
317
+ fm spaces --admin add-member --space <space-id> --user <email> [--role USER]
318
+
319
+ `list` (no subject, the default) and `create` work for any signed-in user and
320
+ need no flag. `list` without --admin is the spaces you are a member of: no
321
+ server-side pagination, no search, just id/name/role/region. `create` calls
322
+ `POST /projects`, the ordinary product route, with your own token; you become
323
+ the new space's owner. `--country` is required: the server infers the
324
+ datacenter from it, and country is immutable once set. `--region` is optional
325
+ and only checked for agreement; it cannot pick a datacenter by itself.
326
+
327
+ Every other subject needs --admin (platform administrators only): it reads or
328
+ writes an arbitrary space, which is not something an ordinary member does to
329
+ their own space through this command. `fm spaces --admin` lists every space,
330
+ every region, paginated (same limit/offset contract as `fm users`; an empty
331
+ page means "not on this page", not "no such space"). `delete` is permanent:
332
+ every row and blob under the space, with no dry run and no undo, and requires
333
+ --confirm on top of the server's own confirmation check. `add-member`
334
+ resolves --user's email to a user id via `GET /admin/users` (no server-side
335
+ email filter, so this walks the platform's full user list) and then assigns
336
+ them with `POST /admin/users/{id}/spaces`, the same route `fm users add-space`
337
+ calls: a second door onto it, addressed by email because that is what an
338
+ operator has on hand. Sends no invitation email; the membership is immediate.
339
+ --role is OWNER/ADMIN/USER/VIEWER (default USER), case-insensitive.
340
+
341
+ `--host formist` is its own deployment, not a region of the default product.
342
+ Use it for every one of these commands against a workspace on that
343
+ deployment.
344
+ """
345
+
346
+
347
+ def _add_arguments(parser: argparse.ArgumentParser) -> None:
348
+ parser.add_argument(
349
+ "subject", nargs="?",
350
+ help=f"one of: {', '.join(SUBJECTS)} (default: {DEFAULT_SUBJECT})",
351
+ )
352
+ parser.add_argument("space_id", nargs="?", help="space UUID (never a name)")
353
+ parser.add_argument(
354
+ "child_id", nargs="?",
355
+ help="chat/skill/invitation UUID (for the three delete-* subjects)",
356
+ )
357
+ parser.add_argument(
358
+ "--host",
359
+ default=argparse.SUPPRESS,
360
+ metavar="HOST",
361
+ help="deployment name or API origin (default: formist, or `fm use` for reads); "
362
+ "a write never inherits it",
363
+ )
364
+ parser.add_argument("--limit", type=int, default=None, help="rows per page (server caps it)")
365
+ parser.add_argument("--offset", type=int, default=None, help="skip this many rows")
366
+ parser.add_argument("--json", action="store_true", help="raw JSON instead of a table")
367
+ parser.add_argument("--name", default=None, help="`rename`/`create`: the (new) name")
368
+ parser.add_argument(
369
+ "--country", default=None,
370
+ help="`create`: required, the ISO 3166-1 alpha-2 country/territory the "
371
+ "space is for (e.g. 'ae'). Decides the datacenter. Immutable once created",
372
+ )
373
+ parser.add_argument(
374
+ "--region", default=None,
375
+ help="`create`: optional, must agree with the datacenter --country "
376
+ "infers for this product, or the server refuses with "
377
+ "region-conflict. Cannot select a datacenter on its own",
378
+ )
379
+ parser.add_argument(
380
+ "--new-owner", dest="new_owner", default=None,
381
+ help="`transfer-ownership`: the new owner's user UUID (must already be a member)",
382
+ )
383
+ parser.add_argument(
384
+ "--confirm", action="store_true",
385
+ help="`delete`: required to actually delete, there is no dry run",
386
+ )
387
+ parser.add_argument(
388
+ "--space", default=None,
389
+ help="`add-member`: the space UUID (an alternative to the positional "
390
+ "space-id argument; never a name)",
391
+ )
392
+ parser.add_argument(
393
+ "--user", default=None,
394
+ help="`add-member`: the platform user's email (resolved to an id via "
395
+ "`GET /admin/users`, never pass a user id here)",
396
+ )
397
+ parser.add_argument(
398
+ "--role", default="USER",
399
+ help=f"`add-member`: one of {', '.join(_ROLES)} (default: USER), "
400
+ "case-insensitive",
401
+ )
402
+ add_admin_flag(parser)
403
+
404
+
405
+ def add_parser(subparsers) -> argparse.ArgumentParser:
406
+ parser = subparsers.add_parser(
407
+ "spaces", help=_HELP, description=_DESCRIPTION,
408
+ formatter_class=argparse.RawDescriptionHelpFormatter,
409
+ )
410
+ _add_arguments(parser)
411
+ return parser
412
+
413
+
414
+ def build_standalone_parser() -> argparse.ArgumentParser:
415
+ return _build_standalone_parser(add_parser)
416
+
417
+
418
+ def _require_space(args) -> str:
419
+ space_id = getattr(args, "space_id", None)
420
+ if not space_id:
421
+ raise SpacesError(
422
+ "this subcommand needs a space id.\n"
423
+ "-> `fm spaces` prints them (id is the last column)."
424
+ )
425
+ return require_space_id(space_id)
426
+
427
+
428
+ def run(args) -> int:
429
+ subject = canonical_subject(getattr(args, "subject", None))
430
+ admin = bool(getattr(args, "admin", False))
431
+ if subject in _MUTATING_SUBJECTS:
432
+ return _run_write(subject, args)
433
+
434
+ if subject != "list":
435
+ # Every read here other than `list` is a platform-admin view of a space
436
+ # the caller may not even be a member of (members/usage/conversations/
437
+ # skills/invitations of an arbitrary space id); none of them has a
438
+ # member-level equivalent in this command, so they all need --admin.
439
+ privileges.require_admin_flag(f"fm spaces {subject}", admin)
440
+
441
+ ctx = context.resolve(args, need_token=True)
442
+
443
+ if subject == "list":
444
+ if not admin:
445
+ # GET /projects: the caller's own spaces, no server-side pagination
446
+ # and no member_count (that is an admin-only aggregate).
447
+ payload = api.get(ctx.target, "/projects", token=ctx.token)
448
+ print(json.dumps(payload, indent=2) if args.json else
449
+ render_my_spaces(_space_payload(payload)))
450
+ return 0
451
+ params: dict[str, str] = {}
452
+ if getattr(args, "limit", None) is not None:
453
+ params["limit"] = str(args.limit)
454
+ if getattr(args, "offset", None) is not None:
455
+ params["offset"] = str(args.offset)
456
+ payload = api.admin_get(ctx.target, "/admin/spaces", token=ctx.token, params=params)
457
+ print(json.dumps(payload, indent=2) if args.json else render_space_list(_space_payload(payload)))
458
+ return 0
459
+
460
+ space = _require_space(args)
461
+
462
+ if subject == "members":
463
+ payload = api.admin_get(
464
+ ctx.target, f"/admin/spaces/{space}/members", token=ctx.token
465
+ )
466
+ print(json.dumps(payload, indent=2) if args.json else render_members(_space_payload(payload)))
467
+ return 0
468
+
469
+ if subject == "usage":
470
+ payload = api.admin_get(ctx.target, f"/admin/spaces/{space}/usage", token=ctx.token)
471
+ print(json.dumps(payload, indent=2) if args.json else render_usage(_space_payload(payload)))
472
+ return 0
473
+
474
+ params = {}
475
+ if getattr(args, "limit", None) is not None:
476
+ params["limit"] = str(args.limit)
477
+ if getattr(args, "offset", None) is not None:
478
+ params["offset"] = str(args.offset)
479
+
480
+ if subject == "conversations":
481
+ payload = api.admin_get(
482
+ ctx.target, f"/admin/spaces/{space}/conversations", token=ctx.token, params=params
483
+ )
484
+ print(json.dumps(payload, indent=2) if args.json else
485
+ render_conversations(_space_payload(payload)))
486
+ return 0
487
+
488
+ if subject == "skills":
489
+ payload = api.admin_get(
490
+ ctx.target, f"/admin/spaces/{space}/skills", token=ctx.token, params=params
491
+ )
492
+ print(json.dumps(payload, indent=2) if args.json else render_skills(_space_payload(payload)))
493
+ return 0
494
+
495
+ # invitations
496
+ payload = api.admin_get(
497
+ ctx.target, f"/admin/spaces/{space}/invitations", token=ctx.token, params=params
498
+ )
499
+ print(json.dumps(payload, indent=2) if args.json else render_invitations(_space_payload(payload)))
500
+ return 0
501
+
502
+
503
+ def _run_write(subject: str, args) -> int:
504
+ if subject != "create":
505
+ # `create` calls the ordinary product route with the caller's own
506
+ # token (see `_create_space`'s docstring) and needs no flag. Every
507
+ # other write here is platform-admin: renaming/deleting an arbitrary
508
+ # space, transferring its ownership, or assigning a member to it by
509
+ # email, none of which is something an ordinary member does to their
510
+ # own space through this command.
511
+ privileges.require_admin_flag(f"fm spaces {subject}", bool(getattr(args, "admin", False)))
512
+
513
+ ctx = context.resolve(args, for_write=True, need_token=True)
514
+
515
+ # `create` has no existing space to require: it makes one. `add-member`
516
+ # addresses its space via `--space` (an alternative to the positional
517
+ # `space_id` the other subjects use). Both are dispatched before the
518
+ # generic `_require_space` below, which every other mutating subject uses.
519
+ if subject == "create":
520
+ return _create_space(ctx, args)
521
+ if subject == "add-member":
522
+ return _add_member(ctx, args)
523
+
524
+ space = _require_space(args)
525
+
526
+ if subject == "rename":
527
+ name = (getattr(args, "name", None) or "").strip()
528
+ if not name:
529
+ raise SpacesError("`fm spaces rename` needs --name <text>")
530
+ payload = api.admin_patch(
531
+ ctx.target, f"/admin/spaces/{space}", {"name": name}, token=ctx.token
532
+ )
533
+ payload = _space_payload(payload)
534
+ print(json.dumps(payload, indent=2) if args.json else render_rename(payload))
535
+ return 0
536
+
537
+ if subject == "delete":
538
+ if not getattr(args, "confirm", False):
539
+ raise SpacesError(
540
+ "refusing: this permanently deletes the space and every row/blob "
541
+ "under it, with no dry run and no undo.\n"
542
+ "-> Re-run with --confirm once you are certain."
543
+ )
544
+ payload = api.admin_delete(
545
+ ctx.target, f"/admin/spaces/{space}", token=ctx.token,
546
+ params={"confirm": "true"},
547
+ )
548
+ payload = _space_payload(payload)
549
+ print(json.dumps(payload, indent=2) if args.json else render_delete(payload))
550
+ return 0
551
+
552
+ if subject == "transfer-ownership":
553
+ new_owner = getattr(args, "new_owner", None)
554
+ if not new_owner:
555
+ raise SpacesError(
556
+ "`fm spaces transfer-ownership` needs --new-owner <user-uuid>.\n"
557
+ "-> `fm spaces members <space-id>` lists candidates, the new owner "
558
+ "must already be a member."
559
+ )
560
+ payload = api.admin_post(
561
+ ctx.target, f"/admin/spaces/{space}/transfer-ownership",
562
+ {"new_owner_user_id": new_owner}, token=ctx.token,
563
+ )
564
+ payload = _space_payload(payload)
565
+ print(json.dumps(payload, indent=2) if args.json else render_transfer(payload))
566
+ return 0
567
+
568
+ # the three delete-<child> subjects
569
+ child_id = getattr(args, "child_id", None)
570
+ child_label = _CHILD_LABEL[subject]
571
+ if not child_id:
572
+ raise SpacesError(f"`fm spaces {subject}` needs a {child_label} as the third argument")
573
+ child_path = {
574
+ "delete-conversation": "conversations",
575
+ "delete-skill": "skills",
576
+ "delete-invitation": "invitations",
577
+ }[subject]
578
+ noun = {
579
+ "delete-conversation": "conversation",
580
+ "delete-skill": "skill",
581
+ "delete-invitation": "invitation",
582
+ }[subject]
583
+ payload = api.admin_delete(
584
+ ctx.target, f"/admin/spaces/{space}/{child_path}/{child_id}", token=ctx.token
585
+ )
586
+ payload = _space_payload(payload)
587
+ print(json.dumps(payload, indent=2) if args.json else
588
+ render_child_delete(payload, noun=noun))
589
+ return 0
590
+
591
+
592
+ def _create_space(ctx, args) -> int:
593
+ """``POST /projects``, the ordinary product route, with the caller's own
594
+ token, not ``/admin``. See the module docstring for why `create` lives
595
+ here rather than being `/admin`-gated like everything else in this file.
596
+
597
+ `--country` is required and refused client-side before any network call;
598
+ the server would reject it too, but a caller script should not need a
599
+ round trip to learn that."""
600
+ name = (getattr(args, "name", None) or "").strip()
601
+ if not name:
602
+ raise SpacesError("`fm spaces create` needs --name <text>")
603
+ country = (getattr(args, "country", None) or "").strip()
604
+ if not country:
605
+ raise SpacesError("`fm spaces create` needs --country <ISO alpha-2> (e.g. ae, us)")
606
+ body: dict = {"name": name, "country": country}
607
+ region = (getattr(args, "region", None) or "").strip()
608
+ if region:
609
+ body["region"] = region
610
+ payload = _space_payload(api.post(ctx.target, "/projects", body, token=ctx.token))
611
+ print(json.dumps(payload, indent=2) if args.json else render_created(payload))
612
+ return 0
613
+
614
+
615
+ def _add_member(ctx, args) -> int:
616
+ """Resolve ``--user``'s email to a user id, then call
617
+ ``POST /admin/users/{user_id}/spaces``, the same route ``fm users
618
+ add-space`` calls (see the module docstring for why this is a second
619
+ door onto it rather than a new one)."""
620
+ space = getattr(args, "space", None) or getattr(args, "space_id", None)
621
+ if not space:
622
+ raise SpacesError(
623
+ "`fm spaces add-member` needs a space id: --space <uuid>, or as the "
624
+ "second argument.\n"
625
+ "-> `fm spaces` prints them (id is the last column)."
626
+ )
627
+ space = require_space_id(space)
628
+
629
+ email = (getattr(args, "user", None) or "").strip()
630
+ if not email:
631
+ raise SpacesError("`fm spaces add-member` needs --user <email>")
632
+
633
+ role = (getattr(args, "role", None) or "USER").strip().upper()
634
+ if role not in _ROLES:
635
+ raise SpacesError(
636
+ f"unknown --role {getattr(args, 'role', None)!r}. Valid: {', '.join(_ROLES)}."
637
+ )
638
+
639
+ user_id = _find_user_id_by_email(ctx, email)
640
+ body = {"space_id": space, "role": role}
641
+ payload = _space_payload(
642
+ api.admin_post(ctx.target, f"/admin/users/{user_id}/spaces", body, token=ctx.token)
643
+ )
644
+ print(json.dumps(payload, indent=2) if args.json else
645
+ render_membership_change(payload, removed=False))
646
+ return 0
647
+
648
+
649
+ #: Rows per page while walking `GET /admin/users` looking for one email. Large
650
+ #: enough that a normal platform (tens to a few hundred users) resolves in one
651
+ #: or two requests; the server caps `limit` regardless, so this is a ceiling
652
+ #: this client asks for, not one it can force.
653
+ _USER_SEARCH_PAGE_SIZE = 200
654
+
655
+
656
+ def _find_user_id_by_email(ctx, email: str) -> str:
657
+ """Walk ``GET /admin/users`` for an exact, case-insensitive email match.
658
+
659
+ There is no server-side email filter, so resolving one email means
660
+ paging through all of them. Exact match only, never a substring: a
661
+ substring match risks assigning the wrong account to a space, which is
662
+ a worse failure than a slower, correct one.
663
+ """
664
+ target = email.strip().lower()
665
+ offset = 0
666
+ while True:
667
+ payload = _space_payload(
668
+ api.admin_get(
669
+ ctx.target, "/admin/users", token=ctx.token,
670
+ params={"limit": str(_USER_SEARCH_PAGE_SIZE), "offset": str(offset)},
671
+ )
672
+ )
673
+ items = payload.get("items") or []
674
+ for row in items:
675
+ if str(row.get("email") or "").strip().lower() == target:
676
+ return str(row.get("id"))
677
+ offset += len(items)
678
+ total = payload.get("total")
679
+ if not items or (total is not None and offset >= int(total)):
680
+ break
681
+ raise SpacesError(
682
+ f"no platform user with email {email!r} on {ctx.target.name}.\n"
683
+ f"-> `fm users create --email {email} --host {ctx.target.name}` first, then "
684
+ "re-run this command."
685
+ )
686
+
687
+
688
+ def _space_payload(payload: object) -> dict:
689
+ """:func:`formist_cli.cli_support.as_dict`, bound to this command's error
690
+ type. Deliberately not named the same as the equivalent binding in
691
+ ``users.py``, to keep two independent one-line bindings of the same
692
+ shared function from looking like a single shared one."""
693
+ return _shared_space_payload(payload, what="/admin/spaces", error=SpacesError)