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/__init__.py +1 -0
- formist_cli/__main__.py +3 -0
- formist_cli/airtable.py +238 -0
- formist_cli/alerts.py +207 -0
- formist_cli/api.py +1027 -0
- formist_cli/chat.py +618 -0
- formist_cli/chats.py +517 -0
- formist_cli/cli.py +1367 -0
- formist_cli/cli_support.py +221 -0
- formist_cli/connectors.py +358 -0
- formist_cli/context.py +164 -0
- formist_cli/diff.py +943 -0
- formist_cli/doctor.py +128 -0
- formist_cli/export.py +427 -0
- formist_cli/files.py +670 -0
- formist_cli/importer.py +425 -0
- formist_cli/kb.py +185 -0
- formist_cli/login.py +615 -0
- formist_cli/logs.py +781 -0
- formist_cli/meetings.py +200 -0
- formist_cli/messages.py +414 -0
- formist_cli/participants.py +402 -0
- formist_cli/prefs.py +328 -0
- formist_cli/privileges.py +375 -0
- formist_cli/projects.py +127 -0
- formist_cli/resolve.py +443 -0
- formist_cli/settings.py +199 -0
- formist_cli/skill_library.py +246 -0
- formist_cli/skills.py +308 -0
- formist_cli/space_plan.py +411 -0
- formist_cli/spaces.py +693 -0
- formist_cli/targets.py +153 -0
- formist_cli/textnorm.py +26 -0
- formist_cli/tokens.py +339 -0
- formist_cli/update.py +433 -0
- formist_cli/uploads.py +928 -0
- formist_cli/usage_tokens.py +152 -0
- formist_cli/users.py +384 -0
- formist_cli/whatsapp.py +451 -0
- formist_cli-0.1.0.dist-info/METADATA +176 -0
- formist_cli-0.1.0.dist-info/RECORD +44 -0
- formist_cli-0.1.0.dist-info/WHEEL +4 -0
- formist_cli-0.1.0.dist-info/entry_points.txt +2 -0
- formist_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
formist_cli/cli.py
ADDED
|
@@ -0,0 +1,1367 @@
|
|
|
1
|
+
"""``fm``: the Formist/Evane operator CLI.
|
|
2
|
+
|
|
3
|
+
Design rules, all of which are safety properties rather than preferences:
|
|
4
|
+
|
|
5
|
+
- **Local by default, prod named explicitly.** ``--env`` defaults to
|
|
6
|
+
``local``. There is no state file and no "current environment",
|
|
7
|
+
because a remembered target is one somebody forgets they set.
|
|
8
|
+
- **Hosts are allow-listed** (``formist_cli.targets``): an unknown
|
|
9
|
+
host is refused rather than tried.
|
|
10
|
+
- **Spaces are addressed by UUID, never by name**, since names are
|
|
11
|
+
not guaranteed unique.
|
|
12
|
+
- **Every ``/admin`` mutation is exposed, and every one is audited, by
|
|
13
|
+
two different mechanisms, and that is fine.** ``fm update`` posts to
|
|
14
|
+
``/projects/{id}/admin/data-changes``, where every op lands in the
|
|
15
|
+
project-scoped ``AuditLog``. The rest of the platform-admin surface
|
|
16
|
+
(``fm users create/set/add-space/remove-space``, ``fm spaces
|
|
17
|
+
rename/delete/transfer-ownership/delete-conversation/delete-skill/
|
|
18
|
+
delete-invitation``) writes to a separate ``PlatformAuditLog``
|
|
19
|
+
instead, because ``AuditLog.project_id`` is a non-nullable FK and a
|
|
20
|
+
platform action (create a user, delete a space) often has no project
|
|
21
|
+
at all.
|
|
22
|
+
- **A write never inherits its environment.** ``fm use`` remembers a
|
|
23
|
+
space and, for reads, an environment. A write resolves ``--env``
|
|
24
|
+
from the command line only. A space is 36 characters nobody
|
|
25
|
+
verifies by eye; an environment is one word and decides whether
|
|
26
|
+
this is production.
|
|
27
|
+
|
|
28
|
+
Stdlib only: the production image builds without dev dependencies, so
|
|
29
|
+
this tool must not add a runtime dependency.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import argparse
|
|
35
|
+
import json
|
|
36
|
+
import sys
|
|
37
|
+
from dataclasses import replace
|
|
38
|
+
|
|
39
|
+
from formist_cli import airtable as airtable_mod
|
|
40
|
+
from formist_cli import alerts as alerts_mod
|
|
41
|
+
from formist_cli import api, context, logs, prefs, privileges, skill_library, skills, space_plan, tokens, users
|
|
42
|
+
from formist_cli import chat as chat_mod
|
|
43
|
+
from formist_cli import chats as chats_mod
|
|
44
|
+
from formist_cli import connectors as connectors_mod
|
|
45
|
+
from formist_cli import diff as diff_mod
|
|
46
|
+
from formist_cli import doctor as doctor_mod
|
|
47
|
+
from formist_cli import export as export_mod
|
|
48
|
+
from formist_cli import files as files_mod
|
|
49
|
+
from formist_cli import importer as importer_mod
|
|
50
|
+
from formist_cli import kb as kb_mod
|
|
51
|
+
from formist_cli import login as login_mod
|
|
52
|
+
from formist_cli import meetings as meetings_mod
|
|
53
|
+
from formist_cli import messages as messages_mod
|
|
54
|
+
from formist_cli import participants as participants_mod
|
|
55
|
+
from formist_cli import projects as projects_mod
|
|
56
|
+
from formist_cli import resolve as resolve_mod
|
|
57
|
+
from formist_cli import settings as settings_mod
|
|
58
|
+
from formist_cli import spaces as spaces_mod
|
|
59
|
+
from formist_cli import update as update_mod
|
|
60
|
+
from formist_cli import uploads as uploads_mod
|
|
61
|
+
from formist_cli import usage_tokens as usage_tokens_mod
|
|
62
|
+
from formist_cli import whatsapp as whatsapp_mod
|
|
63
|
+
from formist_cli.airtable import AirtableError
|
|
64
|
+
from formist_cli.alerts import AlertsError
|
|
65
|
+
from formist_cli.chats import ChatsError
|
|
66
|
+
from formist_cli import cli_support
|
|
67
|
+
from formist_cli.cli_support import as_dict
|
|
68
|
+
from formist_cli.diff import DiffError
|
|
69
|
+
from formist_cli.export import ExportError
|
|
70
|
+
from formist_cli.files import FilesError
|
|
71
|
+
from formist_cli.importer import ImportRefused
|
|
72
|
+
from formist_cli.kb import KbError
|
|
73
|
+
from formist_cli.meetings import MeetingsError
|
|
74
|
+
from formist_cli.participants import ParticipantsError
|
|
75
|
+
from formist_cli.prefs import PrefsError
|
|
76
|
+
from formist_cli.projects import ProjectsError
|
|
77
|
+
from formist_cli.resolve import ResolutionError
|
|
78
|
+
from formist_cli.spaces import SpacesError
|
|
79
|
+
from formist_cli.targets import (
|
|
80
|
+
DEFAULT_HOST,
|
|
81
|
+
HOSTS,
|
|
82
|
+
TargetError,
|
|
83
|
+
is_admin_env,
|
|
84
|
+
require_space_id,
|
|
85
|
+
resolve,
|
|
86
|
+
)
|
|
87
|
+
from formist_cli.update import UpdateError
|
|
88
|
+
from formist_cli.uploads import UploadError
|
|
89
|
+
from formist_cli.usage_tokens import UsageTokensError
|
|
90
|
+
from formist_cli.whatsapp import WhatsAppError
|
|
91
|
+
|
|
92
|
+
_HOST_HELP = (
|
|
93
|
+
f"deployment: {', '.join(HOSTS)}, or an API origin such as "
|
|
94
|
+
f"https://api.example.com or 127.0.0.1:8160 (default: {DEFAULT_HOST})"
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _add_env(parser: argparse.ArgumentParser, *, for_write: bool = False) -> None:
|
|
99
|
+
"""Add ``--host`` to a subcommand.
|
|
100
|
+
|
|
101
|
+
The root parser carries ``--host`` too, so both ``fm --host X cmd`` and
|
|
102
|
+
``fm cmd --host X`` work. A write never inherits a host remembered by
|
|
103
|
+
``fm use``; see :mod:`formist_cli.prefs`.
|
|
104
|
+
"""
|
|
105
|
+
parser.add_argument(
|
|
106
|
+
"--host",
|
|
107
|
+
default=argparse.SUPPRESS,
|
|
108
|
+
metavar="HOST",
|
|
109
|
+
help=_HOST_HELP + ("; a write never inherits it from `fm use`" if for_write else ""),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _add_space(parser: argparse.ArgumentParser) -> None:
|
|
114
|
+
parser.add_argument(
|
|
115
|
+
"--space", help="space UUID (never a name; default from `fm use`)"
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _effective(
|
|
120
|
+
args, *, for_write: bool = False, need_space: bool = True, need_token: bool = False
|
|
121
|
+
):
|
|
122
|
+
"""Resolve the effective target and print its provenance before anything runs.
|
|
123
|
+
|
|
124
|
+
The banner goes to stderr on every command, reads included: the
|
|
125
|
+
target alone tells the operator little, while where each half
|
|
126
|
+
came from, and how stale a remembered one is, is what catches a
|
|
127
|
+
wrong assumption.
|
|
128
|
+
"""
|
|
129
|
+
return context.resolve(
|
|
130
|
+
args, for_write=for_write, need_space=need_space, need_token=need_token
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _token_for(eff):
|
|
135
|
+
"""The stored token for this target, announcing a cross-region borrow.
|
|
136
|
+
|
|
137
|
+
A credential silently sourced from another file is exactly the invisible state
|
|
138
|
+
this tool otherwise refuses, so the borrow is printed.
|
|
139
|
+
"""
|
|
140
|
+
# Already resolved and already announced by context.resolve; kept as a named
|
|
141
|
+
# accessor so ten call sites read the same as before.
|
|
142
|
+
return eff.token
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
146
|
+
parser = argparse.ArgumentParser(
|
|
147
|
+
prog="fm",
|
|
148
|
+
description="Command-line client for Formist (and Evane) deployments.",
|
|
149
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
150
|
+
epilog=(
|
|
151
|
+
f"Named hosts: {', '.join(f'{n} ({h.api_base})' for n, h in HOSTS.items())}.\n"
|
|
152
|
+
"Writes run as a dry run first; pass --apply to commit.\n"
|
|
153
|
+
),
|
|
154
|
+
)
|
|
155
|
+
parser.add_argument("--host", default=None, metavar="HOST", help=_HOST_HELP)
|
|
156
|
+
# ``default=False`` here, not SUPPRESS, so every command always has an
|
|
157
|
+
# `admin` attribute to read with a plain `getattr`/truth test. A subcommand's
|
|
158
|
+
# own `--admin` (added with `cli_support.add_admin_flag`, SUPPRESS'd) never
|
|
159
|
+
# overwrites this back to False when omitted, the same duality `--host` uses.
|
|
160
|
+
parser.add_argument(
|
|
161
|
+
"--admin", action="store_true", default=False, help=cli_support.ADMIN_FLAG_HELP,
|
|
162
|
+
)
|
|
163
|
+
parser.add_argument("--version", action="version", version=f"fm {login_mod.cli_version()}")
|
|
164
|
+
sub = parser.add_subparsers(
|
|
165
|
+
dest="command", required=True, parser_class=cli_support.SubcommandParser
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
p = sub.add_parser(
|
|
169
|
+
"login",
|
|
170
|
+
help="sign in through the browser and store a CLI credential (0600)",
|
|
171
|
+
description=(
|
|
172
|
+
"Signs in through the same OAuth 2.1 flow the MCP connector uses, "
|
|
173
|
+
"one authorization server for both. `fm` registers itself as a "
|
|
174
|
+
"public client, opens the authorization page in a browser where "
|
|
175
|
+
"you sign in with your normal login and approve, and exchanges a "
|
|
176
|
+
"one-time code (PKCE S256) for a credential that is scoped to "
|
|
177
|
+
"you, expires, and is revocable on its own from Settings > "
|
|
178
|
+
"Security > Connected apps, beside your other connected apps. "
|
|
179
|
+
"It replaces pasting a browser session JWT, which was the whole "
|
|
180
|
+
"account and could only be killed by signing out everywhere. "
|
|
181
|
+
"There is no --token flag. For CI / an unattended machine, export "
|
|
182
|
+
"FORMIST_TOKEN with the 'token' field of the file this command "
|
|
183
|
+
"writes (0600, printed below); `fm` uses it for that invocation "
|
|
184
|
+
"only, never writes it to disk, and never refreshes it; run "
|
|
185
|
+
"`fm whoami` to confirm which source is in use. "
|
|
186
|
+
"A --host evane or --host evane-ae login runs against the Global "
|
|
187
|
+
"region and the credential works at both of those hosts; "
|
|
188
|
+
"--host formist signs in against its own deployment."
|
|
189
|
+
),
|
|
190
|
+
)
|
|
191
|
+
_add_env(p)
|
|
192
|
+
p.add_argument(
|
|
193
|
+
"--no-browser",
|
|
194
|
+
action="store_true",
|
|
195
|
+
help="do not open a browser or listen on 127.0.0.1; print the URL and "
|
|
196
|
+
"prompt for the code the page displays (headless boxes, SSH)",
|
|
197
|
+
)
|
|
198
|
+
p.add_argument(
|
|
199
|
+
"--admin",
|
|
200
|
+
action="store_true",
|
|
201
|
+
default=argparse.SUPPRESS,
|
|
202
|
+
help="also request the platform-administration scope. Only granted if your "
|
|
203
|
+
"account already has it; needed for any other command's own --admin",
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
p = sub.add_parser(
|
|
207
|
+
"logout",
|
|
208
|
+
help="revoke the stored credential server-side and delete the file",
|
|
209
|
+
)
|
|
210
|
+
_add_env(p)
|
|
211
|
+
p.add_argument("--all", action="store_true", help="remove every environment's token")
|
|
212
|
+
p.add_argument(
|
|
213
|
+
"--local-only",
|
|
214
|
+
action="store_true",
|
|
215
|
+
help="delete the file without calling the server (offline)",
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
p = sub.add_parser("whoami", help="describe the stored token (never prints it)")
|
|
219
|
+
_add_env(p)
|
|
220
|
+
p.add_argument(
|
|
221
|
+
"--remote",
|
|
222
|
+
action="store_true",
|
|
223
|
+
help="also list this account's connected apps as the SERVER sees them "
|
|
224
|
+
"(MCP connectors and CLI devices together)",
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
p = sub.add_parser("health", help="health checks for a region (public, no auth)")
|
|
228
|
+
_add_env(p)
|
|
229
|
+
p.add_argument(
|
|
230
|
+
"--admin", action="store_true", default=argparse.SUPPRESS,
|
|
231
|
+
help="GET /admin/health instead: this region's checks plus the other "
|
|
232
|
+
"region's, in one call (" + cli_support.ADMIN_FLAG_HELP + ")",
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
p = sub.add_parser("instance", help="build + migration identity (Tier 1 endpoint)")
|
|
236
|
+
_add_env(p)
|
|
237
|
+
cli_support.add_admin_flag(p)
|
|
238
|
+
|
|
239
|
+
spaces_mod.add_parser(sub)
|
|
240
|
+
|
|
241
|
+
p = sub.add_parser(
|
|
242
|
+
"proposals",
|
|
243
|
+
help=(
|
|
244
|
+
"list a space's AI proposals (member), or unstick the "
|
|
245
|
+
"pre-atomic-approve ones (--admin)"
|
|
246
|
+
),
|
|
247
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
248
|
+
)
|
|
249
|
+
_add_env(p)
|
|
250
|
+
_add_space(p)
|
|
251
|
+
cli_support.add_admin_flag(p)
|
|
252
|
+
# Positional, defaulted, and NOT a second subparser level: `fm proposals` with
|
|
253
|
+
# no subject has meant "list them" for months and every runbook says so.
|
|
254
|
+
p.add_argument(
|
|
255
|
+
"subject",
|
|
256
|
+
nargs="?",
|
|
257
|
+
default="list",
|
|
258
|
+
choices=PROPOSAL_SUBJECTS,
|
|
259
|
+
help="list (default, member) | unstick (always needs --admin)",
|
|
260
|
+
)
|
|
261
|
+
p.add_argument("--status", help="list: e.g. PENDING")
|
|
262
|
+
p.add_argument("--target-kind", dest="target_kind")
|
|
263
|
+
p.add_argument("--limit", default="50")
|
|
264
|
+
p.add_argument(
|
|
265
|
+
"--id",
|
|
266
|
+
dest="proposal_ids",
|
|
267
|
+
action="append",
|
|
268
|
+
help="unstick: repair only this proposal id (repeatable). "
|
|
269
|
+
"Default is every stranded proposal in the space.",
|
|
270
|
+
)
|
|
271
|
+
p.add_argument(
|
|
272
|
+
"--apply",
|
|
273
|
+
action="store_true",
|
|
274
|
+
help="unstick: commit the write. Without it nothing is written.",
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
p = sub.add_parser("audit-log", help="a space's audit log (member; --admin for a space you are not a member of)")
|
|
278
|
+
_add_env(p)
|
|
279
|
+
_add_space(p)
|
|
280
|
+
cli_support.add_admin_flag(p)
|
|
281
|
+
p.add_argument("--limit", default="50")
|
|
282
|
+
|
|
283
|
+
p = sub.add_parser(
|
|
284
|
+
"connectors",
|
|
285
|
+
help="a space's connectors (member); `grants` always needs --admin",
|
|
286
|
+
description=connectors_mod.COMMAND_DESCRIPTION,
|
|
287
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
288
|
+
)
|
|
289
|
+
_add_env(p)
|
|
290
|
+
_add_space(p)
|
|
291
|
+
cli_support.add_admin_flag(p)
|
|
292
|
+
# Optional and default-preserving: `fm connectors` alone must keep
|
|
293
|
+
# printing the plain list it always printed, since a positional
|
|
294
|
+
# that changed the default behaviour would silently redefine an
|
|
295
|
+
# existing operator command.
|
|
296
|
+
p.add_argument(
|
|
297
|
+
"subject", nargs="?", default=None,
|
|
298
|
+
help=f"one of: {', '.join(connectors_mod.SUBJECTS)} (default: list)",
|
|
299
|
+
)
|
|
300
|
+
p.add_argument(
|
|
301
|
+
"space_id", nargs="?", default=None,
|
|
302
|
+
help="space UUID (an alternative to --space)",
|
|
303
|
+
)
|
|
304
|
+
p.add_argument("--json", action="store_true", help="raw JSON instead of a table")
|
|
305
|
+
|
|
306
|
+
p = sub.add_parser(
|
|
307
|
+
"entity-fields",
|
|
308
|
+
help="a space's custom-field schemas (the read whose absence forced a write)",
|
|
309
|
+
)
|
|
310
|
+
_add_env(p)
|
|
311
|
+
_add_space(p)
|
|
312
|
+
|
|
313
|
+
# Parser and body live in logs.py: cli.py gets an import and a dispatch
|
|
314
|
+
# entry and nothing else.
|
|
315
|
+
logs.add_parser(sub)
|
|
316
|
+
users.add_parser(sub)
|
|
317
|
+
space_plan.add_parser(sub)
|
|
318
|
+
skill_library.add_install_parser(sub)
|
|
319
|
+
skills.add_parser(sub)
|
|
320
|
+
|
|
321
|
+
p = sub.add_parser(
|
|
322
|
+
"doctor",
|
|
323
|
+
help="readable health rollup across environments",
|
|
324
|
+
description=(
|
|
325
|
+
"Health, migration identity and credential status for every "
|
|
326
|
+
"environment, in one place. Distinguishes 'could not reach it' from "
|
|
327
|
+
"'reached it and it is unhealthy', different facts, different next "
|
|
328
|
+
"actions, and reports every environment even when one is down."
|
|
329
|
+
),
|
|
330
|
+
)
|
|
331
|
+
p.add_argument(
|
|
332
|
+
"--host",
|
|
333
|
+
default=argparse.SUPPRESS,
|
|
334
|
+
metavar="HOST",
|
|
335
|
+
help="check only this deployment (default: every named, live one)",
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
p = sub.add_parser(
|
|
339
|
+
"use",
|
|
340
|
+
help="remember a default space (and, for reads, a host)",
|
|
341
|
+
description=(
|
|
342
|
+
"Remembers defaults so a space UUID need not be retyped. The space is "
|
|
343
|
+
"remembered for everything; the host is remembered for READS "
|
|
344
|
+
"ONLY. A write never inherits it: with one remembered the write is "
|
|
345
|
+
"REFUSED until you pass --host, and with nothing remembered a write "
|
|
346
|
+
"targets the default host (formist). A remembered host is one "
|
|
347
|
+
"somebody forgets they set and the cost of forgetting is a write to "
|
|
348
|
+
"the wrong database. Every command prints "
|
|
349
|
+
"the effective target and where each half came from."
|
|
350
|
+
),
|
|
351
|
+
)
|
|
352
|
+
_add_env(p)
|
|
353
|
+
_add_space(p)
|
|
354
|
+
p.add_argument("--show", action="store_true", help="print the current defaults")
|
|
355
|
+
p.add_argument("--clear", action="store_true", help="forget everything")
|
|
356
|
+
|
|
357
|
+
p = sub.add_parser(
|
|
358
|
+
"get",
|
|
359
|
+
help="find rows by name, and the ids they resolve to",
|
|
360
|
+
description=(
|
|
361
|
+
"The resolver that means a UUID is never transcribed. Prints the id for "
|
|
362
|
+
"a name so it can be checked, and is the same lookup `fm update` does "
|
|
363
|
+
"for $name. Listing shows every candidate; resolving requires exactly "
|
|
364
|
+
"one match and refuses otherwise."
|
|
365
|
+
),
|
|
366
|
+
)
|
|
367
|
+
_add_env(p)
|
|
368
|
+
_add_space(p)
|
|
369
|
+
p.add_argument(
|
|
370
|
+
"kind",
|
|
371
|
+
help=f"one of: {resolve_mod.kind_names()} (case-insensitive; - and _ alike)",
|
|
372
|
+
)
|
|
373
|
+
p.add_argument("--name", help="exact name; omit to list the kind")
|
|
374
|
+
p.add_argument("--json", action="store_true", help="machine-readable output")
|
|
375
|
+
|
|
376
|
+
p = sub.add_parser(
|
|
377
|
+
"update",
|
|
378
|
+
help="bulk data change: dry-run always, apply with the plan token",
|
|
379
|
+
description=(
|
|
380
|
+
"Applies a batch of data changes transactionally, or reports what would "
|
|
381
|
+
"happen. A dry run ALWAYS runs first and prints a plan token; --apply "
|
|
382
|
+
"takes that token and re-runs the dry run to check it still matches "
|
|
383
|
+
"before committing.\n\n"
|
|
384
|
+
"Payload ops use the endpoint's own vocabulary ($action, $kind, $id, "
|
|
385
|
+
"$set, $expect, $ref, $replace_data, $hard) plus one fm-side addition: "
|
|
386
|
+
"$name, resolved to an id here, seconds before the write, against the "
|
|
387
|
+
"environment being written. The name is copied into $expect so the "
|
|
388
|
+
"server re-checks the resolution against the row itself.\n\n"
|
|
389
|
+
"A $set naming `data` (STAKEHOLDER / CUSTOM's free-form blob) MERGES "
|
|
390
|
+
"into the row's existing value by default -- {'country': 'AE'} changes "
|
|
391
|
+
"only `country`. Add \"$replace_data\": true to an op to replace the "
|
|
392
|
+
"whole blob instead; that is the only way to remove a key.\n\n"
|
|
393
|
+
"$action \"delete\" is SOFT -- restorable from the space's Trash, "
|
|
394
|
+
"like the UI. $hard is refused for a kind with a Trash entry (purge "
|
|
395
|
+
"from there instead) and required for the two that have none "
|
|
396
|
+
"(FILE_LINK, SESSION_PARTICIPANT).\n\n"
|
|
397
|
+
+ update_mod.NOT_DEPLOYED_NOTE
|
|
398
|
+
),
|
|
399
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
400
|
+
)
|
|
401
|
+
_add_env(p, for_write=True)
|
|
402
|
+
_add_space(p)
|
|
403
|
+
cli_support.add_admin_flag(p)
|
|
404
|
+
p.add_argument("payload", help="path to a JSON file of ops")
|
|
405
|
+
p.add_argument(
|
|
406
|
+
"--apply",
|
|
407
|
+
metavar="PLAN_TOKEN",
|
|
408
|
+
help="commit, if this token still matches a fresh dry run of this plan",
|
|
409
|
+
)
|
|
410
|
+
p.add_argument("--json", action="store_true", help="machine-readable output")
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
chats_mod.add_parser(sub)
|
|
414
|
+
|
|
415
|
+
chat_mod.add_parser(sub)
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
export_mod.add_parser(sub)
|
|
419
|
+
importer_mod.add_parser(sub)
|
|
420
|
+
|
|
421
|
+
diff_mod.add_parser(sub)
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
airtable_mod.add_parser(sub)
|
|
425
|
+
participants_mod.add_parser(sub)
|
|
426
|
+
|
|
427
|
+
usage_tokens_mod.add_parser(sub)
|
|
428
|
+
|
|
429
|
+
alerts_mod.add_parser(sub)
|
|
430
|
+
settings_mod.add_parser(sub)
|
|
431
|
+
|
|
432
|
+
messages_mod.add_parser(sub)
|
|
433
|
+
whatsapp_mod.add_parser(sub)
|
|
434
|
+
|
|
435
|
+
uploads_mod.add_parser(sub)
|
|
436
|
+
|
|
437
|
+
kb_mod.add_parser(sub)
|
|
438
|
+
meetings_mod.add_parser(sub)
|
|
439
|
+
files_mod.add_parser(sub)
|
|
440
|
+
projects_mod.add_parser(sub)
|
|
441
|
+
connectors_mod.add_connector_parser(sub)
|
|
442
|
+
|
|
443
|
+
return parser
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
# --- commands -----------------------------------------------------------------
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def cmd_login(args) -> int:
|
|
450
|
+
"""Browser-confirmed OAuth authorization.
|
|
451
|
+
|
|
452
|
+
Deliberately `resolve`, not `_effective`: the credential commands
|
|
453
|
+
bind to the environment named on the command line, never to a
|
|
454
|
+
remembered one. `fm login` picks which file a token lands in, and
|
|
455
|
+
inheriting that from `fm use` is how a prod token ends up in the
|
|
456
|
+
local slot (or the reverse). Same for logout/whoami.
|
|
457
|
+
"""
|
|
458
|
+
target = resolve(args.host)
|
|
459
|
+
payload = login_mod.perform_login(
|
|
460
|
+
target,
|
|
461
|
+
no_browser=bool(getattr(args, "no_browser", False)),
|
|
462
|
+
admin=bool(getattr(args, "admin", False)),
|
|
463
|
+
)
|
|
464
|
+
login_mod.store_payload(
|
|
465
|
+
target.name, payload,
|
|
466
|
+
client_id=str(payload["client_id"]),
|
|
467
|
+
client_name=str(payload.get("client_name") or ""),
|
|
468
|
+
)
|
|
469
|
+
meta = tokens.load_meta(target.name)
|
|
470
|
+
|
|
471
|
+
who = _describe_account(target, payload)
|
|
472
|
+
print(f"Connected as {who} ({target.name})")
|
|
473
|
+
print(f" credential stored at {tokens.token_path(target.name)} (0600)")
|
|
474
|
+
print(f" scopes: {', '.join(meta.get('scopes') or []) or '(none granted)'}")
|
|
475
|
+
if privileges.SCOPE_ADMIN not in (meta.get("scopes") or []):
|
|
476
|
+
# Said out loud rather than discovered at the first 403. The whole point of
|
|
477
|
+
# the default is that it is narrow; a narrow default nobody was told about
|
|
478
|
+
# reads as a bug.
|
|
479
|
+
print(
|
|
480
|
+
" platform-admin actions are NOT granted to this credential "
|
|
481
|
+
"(`fm login --admin` requests them; only a platform admin is granted them)"
|
|
482
|
+
)
|
|
483
|
+
print(" revoke it from Settings > Security > Connected apps, or `fm logout`")
|
|
484
|
+
return 0
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _describe_account(target, payload: dict) -> str:
|
|
488
|
+
"""Who the new credential belongs to, asked of the server.
|
|
489
|
+
|
|
490
|
+
The OAuth token response says nothing about the user, it is opaque
|
|
491
|
+
by design, so "Connected as <who>" has to be a question, not a
|
|
492
|
+
claim read off the token. Falls back to the client name when
|
|
493
|
+
/auth/me cannot be reached: printing a wrong identity would be
|
|
494
|
+
worse than printing none.
|
|
495
|
+
"""
|
|
496
|
+
try:
|
|
497
|
+
me = api.get(login_mod.auth_target(target), "/auth/me",
|
|
498
|
+
token=str(payload["access_token"]))
|
|
499
|
+
except (api.ApiError, TargetError, OSError):
|
|
500
|
+
return str(payload.get("client_name") or "this account")
|
|
501
|
+
if isinstance(me, dict):
|
|
502
|
+
return str(me.get("email") or me.get("id") or "this account")
|
|
503
|
+
return "this account"
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def cmd_logout(args) -> int:
|
|
507
|
+
"""Revoke the grant server-side, then delete the file.
|
|
508
|
+
|
|
509
|
+
In that order, and both halves matter. Deleting only the file
|
|
510
|
+
leaves a live credential in the world that nobody can see any
|
|
511
|
+
more; revoking only on the server leaves a dead file that `fm`
|
|
512
|
+
will keep presenting. The local delete happens even when the
|
|
513
|
+
revoke fails (an offline laptop must still be able to forget its
|
|
514
|
+
credential), and the failure is printed, since "logged out" while
|
|
515
|
+
the credential is still live would be a quiet wrong answer.
|
|
516
|
+
"""
|
|
517
|
+
if args.all:
|
|
518
|
+
removed = tokens.clear_all()
|
|
519
|
+
print(f"removed: {', '.join(removed)}" if removed else "no stored tokens")
|
|
520
|
+
if removed:
|
|
521
|
+
print(
|
|
522
|
+
" note: --all deletes the local files only. Revoke the grants "
|
|
523
|
+
"themselves from Settings > Security > Connected apps."
|
|
524
|
+
)
|
|
525
|
+
return 0
|
|
526
|
+
|
|
527
|
+
target = resolve(args.host)
|
|
528
|
+
token = tokens.load(target.name)
|
|
529
|
+
if not token:
|
|
530
|
+
print(f"no stored token for {target.name}")
|
|
531
|
+
return 0
|
|
532
|
+
|
|
533
|
+
revoked = False
|
|
534
|
+
if not getattr(args, "local_only", False):
|
|
535
|
+
revoked = login_mod.revoke(target, token, _own_grant_id(target, token))
|
|
536
|
+
tokens.clear(target.name)
|
|
537
|
+
if revoked:
|
|
538
|
+
print(f"revoked the {target.name} grant server-side and removed the file")
|
|
539
|
+
return 0
|
|
540
|
+
if getattr(args, "local_only", False):
|
|
541
|
+
print(f"removed the {target.name} token file (--local-only: NOT revoked)")
|
|
542
|
+
return 0
|
|
543
|
+
print(
|
|
544
|
+
f"removed the {target.name} token file, but the server did NOT confirm the "
|
|
545
|
+
"revocation; the grant may still be live. Revoke it from "
|
|
546
|
+
"Settings > Security > Connected apps.",
|
|
547
|
+
file=sys.stderr,
|
|
548
|
+
)
|
|
549
|
+
return 1
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _own_grant_id(target, token: str) -> str | None:
|
|
553
|
+
"""The grant id of the credential we are holding, asked of the server.
|
|
554
|
+
|
|
555
|
+
An OAuth access token is opaque: there is nothing in it to read a
|
|
556
|
+
grant id out of, which is the property that makes it revocable in
|
|
557
|
+
the first place. So `fm logout` asks: `GET /auth/apps` returns
|
|
558
|
+
this user's grants and the CLI matches the one whose client_id it
|
|
559
|
+
stored. A stored grant id would be the alternative and it would go
|
|
560
|
+
stale on the first refresh.
|
|
561
|
+
"""
|
|
562
|
+
client_id = tokens.load_meta(target.name).get("client_id")
|
|
563
|
+
if not client_id:
|
|
564
|
+
return None
|
|
565
|
+
try:
|
|
566
|
+
apps = login_mod.list_apps(target, token)
|
|
567
|
+
except (api.ApiError, TargetError, OSError):
|
|
568
|
+
return None
|
|
569
|
+
for app in apps:
|
|
570
|
+
if app.get("client_id") == client_id and not app.get("revoked"):
|
|
571
|
+
return str(app.get("grant_id") or "") or None
|
|
572
|
+
return None
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def cmd_whoami(args) -> int:
|
|
576
|
+
target = resolve(args.host)
|
|
577
|
+
token, origin = tokens.load_for(target.name)
|
|
578
|
+
if not token:
|
|
579
|
+
print(f"no stored token for {target.name}. Run fm login --host {target.name}")
|
|
580
|
+
return 1
|
|
581
|
+
|
|
582
|
+
if origin == tokens.ENV_TOKEN_ORIGIN:
|
|
583
|
+
print(f"{target.name}: token source = environment ({tokens.ENV_TOKEN_VAR})")
|
|
584
|
+
print(
|
|
585
|
+
" not written to disk and not auto-refreshed by `fm`; scopes and "
|
|
586
|
+
"expiry are whatever the issuer granted; the server decides on every "
|
|
587
|
+
"call"
|
|
588
|
+
)
|
|
589
|
+
else:
|
|
590
|
+
meta = tokens.load_meta(target.name)
|
|
591
|
+
print(f"{target.name}: {meta.get('client_name') or 'fm'}")
|
|
592
|
+
print(f" token source: {tokens.token_path(target.name)}")
|
|
593
|
+
if meta.get("scopes"):
|
|
594
|
+
print(f" scopes: {', '.join(meta['scopes'])}")
|
|
595
|
+
if meta.get("expires_at"):
|
|
596
|
+
print(f" access token expires: {meta['expires_at']} (refreshed automatically)")
|
|
597
|
+
print(" the token is OPAQUE: `fm` cannot read anything out of it; the server decides")
|
|
598
|
+
|
|
599
|
+
if getattr(args, "remote", False):
|
|
600
|
+
for app in login_mod.list_apps(target, token):
|
|
601
|
+
state = (
|
|
602
|
+
"revoked" if app.get("revoked")
|
|
603
|
+
else "expired" if app.get("expired")
|
|
604
|
+
else "active"
|
|
605
|
+
)
|
|
606
|
+
mark = "*" if app.get("client_id") == meta.get("client_id") else " "
|
|
607
|
+
kind = "cli" if app.get("is_cli") else "app"
|
|
608
|
+
admin = " [ADMIN]" if app.get("grants_admin") else ""
|
|
609
|
+
print(
|
|
610
|
+
f" {mark} [{kind}] {app.get('client_name')} {state} "
|
|
611
|
+
f"last used {app.get('last_used_at') or 'never'}{admin}"
|
|
612
|
+
)
|
|
613
|
+
return 0
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _print_health_block(label: str, payload: dict) -> bool:
|
|
617
|
+
"""One region's health block. Returns True iff a FATAL check failed."""
|
|
618
|
+
print(f"{label}: {payload.get('status')} ({payload.get('checked_at', '')})")
|
|
619
|
+
for check in payload.get("checks", []):
|
|
620
|
+
flag = "!" if check.get("status") != "ok" else " "
|
|
621
|
+
fatal = " [fatal]" if check.get("fatal") else ""
|
|
622
|
+
print(f" {flag} {check.get('name'):<22} {check.get('status'):<6}"
|
|
623
|
+
f" {check.get('detail', '')}{fatal}")
|
|
624
|
+
bad = [c for c in payload.get("checks", []) if c.get("status") != "ok"]
|
|
625
|
+
return any(c.get("fatal") for c in bad)
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def cmd_health(args) -> int:
|
|
629
|
+
if getattr(args, "admin", False):
|
|
630
|
+
# /admin/health is a DIFFERENT endpoint from the public /health above: it
|
|
631
|
+
# is platform-admin-gated and reports THIS region PLUS a best-effort read
|
|
632
|
+
# of the OTHER region's public /health, in one call.
|
|
633
|
+
eff = _effective(args, need_space=False, need_token=True)
|
|
634
|
+
payload = api.admin_get(eff.target, "/admin/health", token=_token_for(eff))
|
|
635
|
+
if not isinstance(payload, dict):
|
|
636
|
+
print(payload)
|
|
637
|
+
return 0
|
|
638
|
+
regions = payload.get("regions") or {}
|
|
639
|
+
worst = False
|
|
640
|
+
for name, data in regions.items():
|
|
641
|
+
worst = _print_health_block(name, data if isinstance(data, dict) else {}) or worst
|
|
642
|
+
return 1 if worst else 0
|
|
643
|
+
|
|
644
|
+
eff = _effective(args, need_space=False)
|
|
645
|
+
target = eff.target
|
|
646
|
+
payload = api.get(target, "/health")
|
|
647
|
+
if not isinstance(payload, dict):
|
|
648
|
+
print(payload)
|
|
649
|
+
return 0
|
|
650
|
+
return 1 if _print_health_block(target.name, payload) else 0
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def cmd_instance(args) -> int:
|
|
654
|
+
eff = _effective(args, need_space=False)
|
|
655
|
+
target = eff.target
|
|
656
|
+
payload = api.admin_get(target, "/admin/instance", token=_token_for(eff))
|
|
657
|
+
if not isinstance(payload, dict):
|
|
658
|
+
print(payload)
|
|
659
|
+
return 0
|
|
660
|
+
worst = 0
|
|
661
|
+
for name, data in (payload.get("regions") or {}).items():
|
|
662
|
+
alembic = data.get("alembic") or {}
|
|
663
|
+
print(f"[{name}] scope={data.get('scope')}")
|
|
664
|
+
if data.get("scope") == "process":
|
|
665
|
+
print(f" db_role={data.get('db_role')} scheduler={data.get('scheduler')}"
|
|
666
|
+
f" build_marker={data.get('build_marker')}")
|
|
667
|
+
print(f" alembic db_head={alembic.get('db_head')}")
|
|
668
|
+
if "code_heads" in alembic:
|
|
669
|
+
print(f" alembic code_heads={alembic.get('code_heads')}")
|
|
670
|
+
if alembic.get("in_sync") is False:
|
|
671
|
+
print(" db_head != code_heads: a migration is pending or failed.")
|
|
672
|
+
worst = 1
|
|
673
|
+
return worst
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
#: `fm proposals <subject>`.
|
|
677
|
+
PROPOSAL_SUBJECTS = ("list", "unstick")
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def cmd_proposals(args) -> int:
|
|
681
|
+
subject = getattr(args, "subject", None) or "list"
|
|
682
|
+
admin = bool(getattr(args, "admin", False))
|
|
683
|
+
if subject == "unstick":
|
|
684
|
+
privileges.require_admin_flag("fm proposals unstick", admin)
|
|
685
|
+
return _proposals_unstick(args)
|
|
686
|
+
eff = _effective(args)
|
|
687
|
+
target, space = eff.target, eff.space
|
|
688
|
+
params = {"limit": args.limit, "status": args.status, "target_kind": args.target_kind}
|
|
689
|
+
# Same shared list contract on both sides (PROPOSAL_SPEC): the admin route
|
|
690
|
+
# reads any space cross-region, platform-admin only; the member route reads
|
|
691
|
+
# the caller's own space only, and needs no flag.
|
|
692
|
+
path = (
|
|
693
|
+
f"/admin/spaces/{space}/proposals" if admin else f"/projects/{space}/proposals"
|
|
694
|
+
)
|
|
695
|
+
fetch = api.admin_get if admin else api.get
|
|
696
|
+
payload = fetch(target, path, token=_token_for(eff), params=params)
|
|
697
|
+
for item in _items(payload):
|
|
698
|
+
print(f"{item.get('id')} {item.get('status'):<10} {item.get('target_kind'):<14}"
|
|
699
|
+
f" {item.get('created_at', '')}")
|
|
700
|
+
return 0
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
def _proposals_unstick(args) -> int:
|
|
704
|
+
"""Survey (and with --apply, repair) proposals an earlier approve stranded.
|
|
705
|
+
|
|
706
|
+
The dry run always runs, including under --apply, and it is
|
|
707
|
+
printed before anything is written. The whole value of this
|
|
708
|
+
command is that the operator reads which proposals are
|
|
709
|
+
half-applied before deciding; a repair whose scope is only visible
|
|
710
|
+
afterwards is a repair nobody reviewed.
|
|
711
|
+
|
|
712
|
+
Half-applied proposals are called out separately from merely-failed ones
|
|
713
|
+
because only the first needs a decision: its applied items cannot be undone,
|
|
714
|
+
so approving finishes the job and rejecting leaves those rows changed. The
|
|
715
|
+
command does not choose between those; a person does.
|
|
716
|
+
"""
|
|
717
|
+
eff = _effective(args)
|
|
718
|
+
target, space = eff.target, eff.space
|
|
719
|
+
path = f"/admin/spaces/{space}/proposals/unstick"
|
|
720
|
+
body: dict = {"dry_run": True}
|
|
721
|
+
if getattr(args, "proposal_ids", None):
|
|
722
|
+
body["proposal_ids"] = list(args.proposal_ids)
|
|
723
|
+
|
|
724
|
+
dry = as_dict(
|
|
725
|
+
api.admin_post(target, path, body, token=_token_for(eff)),
|
|
726
|
+
what="unstick survey",
|
|
727
|
+
error=TargetError,
|
|
728
|
+
)
|
|
729
|
+
_render_unstick(dry)
|
|
730
|
+
if not dry.get("total"):
|
|
731
|
+
return 0
|
|
732
|
+
if not args.apply:
|
|
733
|
+
ids = "".join(f" --id {i}" for i in (body.get("proposal_ids") or []))
|
|
734
|
+
print()
|
|
735
|
+
print("NOTHING WAS WRITTEN. To apply exactly this:")
|
|
736
|
+
print(f" fm proposals unstick --space {space}{ids} --apply")
|
|
737
|
+
return 0
|
|
738
|
+
|
|
739
|
+
applied = as_dict(
|
|
740
|
+
api.admin_post(target, path, {**body, "dry_run": False}, token=_token_for(eff)),
|
|
741
|
+
what="unstick result",
|
|
742
|
+
error=TargetError,
|
|
743
|
+
)
|
|
744
|
+
_render_unstick(applied)
|
|
745
|
+
print()
|
|
746
|
+
print(
|
|
747
|
+
f"APPLIED: reopened {applied.get('reopened_targets')} failed item(s) "
|
|
748
|
+
f"across {applied.get('watermarks_written')} proposal(s). "
|
|
749
|
+
"Approve or reject them from the space as usual."
|
|
750
|
+
)
|
|
751
|
+
return 0
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def _render_unstick(payload: dict) -> None:
|
|
755
|
+
rows = payload.get("proposals") or []
|
|
756
|
+
mode = "DRY RUN" if payload.get("dry_run") else "APPLIED"
|
|
757
|
+
print(
|
|
758
|
+
f"{mode}: {payload.get('total', 0)} stranded proposal(s), "
|
|
759
|
+
f"{payload.get('half_applied', 0)} of them HALF-APPLIED"
|
|
760
|
+
)
|
|
761
|
+
for row in rows:
|
|
762
|
+
flag = "HALF-APPLIED" if row.get("half_applied") else "failed-items"
|
|
763
|
+
print(
|
|
764
|
+
f" {row.get('id')} {row.get('status'):<9} {flag:<12} "
|
|
765
|
+
f"applied={row.get('applied')}/{row.get('target_count')} "
|
|
766
|
+
f"failed={row.get('failed')} reopen={row.get('reopened_targets')}"
|
|
767
|
+
)
|
|
768
|
+
for actor in row.get("blocked_actors") or []:
|
|
769
|
+
print(f" blocked: {actor} (can neither approve nor reject)")
|
|
770
|
+
for reason in row.get("failure_reasons") or []:
|
|
771
|
+
print(f" why: {reason}")
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
#: The route's default sort is `created_at` ascending, so a space with
|
|
775
|
+
#: more rows than `--limit` would otherwise show its oldest page and
|
|
776
|
+
#: nothing else, which is a page nobody asked for: "what changed
|
|
777
|
+
#: recently" is the only question this command is ever asked.
|
|
778
|
+
_AUDIT_LOG_SORT = "-created_at"
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def cmd_audit_log(args) -> int:
|
|
782
|
+
"""A space's audit log, newest first, saying so when it did not show all of it.
|
|
783
|
+
|
|
784
|
+
Both halves are load-bearing and neither is decoration:
|
|
785
|
+
|
|
786
|
+
* The sort, because ascending order answers a question nobody has.
|
|
787
|
+
* The count line, because the server caps `--limit`, so asking for
|
|
788
|
+
more than the cap and receiving fewer rows is not an error and
|
|
789
|
+
prints no warning of its own. A listing that shows a page while
|
|
790
|
+
looking like it showed the whole set would be true about what it
|
|
791
|
+
fetched and false about what exists.
|
|
792
|
+
"""
|
|
793
|
+
admin = bool(getattr(args, "admin", False))
|
|
794
|
+
eff = _effective(args)
|
|
795
|
+
target, space = eff.target, eff.space
|
|
796
|
+
# Same shared list contract (AUDIT_LOG_SPEC) either way: the member route
|
|
797
|
+
# reads only the caller's own space and needs no flag; --admin reads a
|
|
798
|
+
# space this credential is not a member of, platform-admin only.
|
|
799
|
+
path = (
|
|
800
|
+
f"/admin/spaces/{space}/audit-log" if admin else f"/projects/{space}/audit-log"
|
|
801
|
+
)
|
|
802
|
+
fetch = api.admin_get if admin else api.get
|
|
803
|
+
payload = fetch(
|
|
804
|
+
target, path,
|
|
805
|
+
token=_token_for(eff),
|
|
806
|
+
params={"limit": args.limit, "sort": _AUDIT_LOG_SORT},
|
|
807
|
+
)
|
|
808
|
+
items = _items(payload)
|
|
809
|
+
for item in items:
|
|
810
|
+
print(f"{item.get('created_at', '')} {item.get('actor_type', ''):<6}"
|
|
811
|
+
f" {item.get('action', ''):<8} {item.get('target_kind', '')}")
|
|
812
|
+
total = payload.get("total") if isinstance(payload, dict) else None
|
|
813
|
+
shown = len(items)
|
|
814
|
+
if total is None:
|
|
815
|
+
# The route always sends `total`; if it ever stops, say so rather than
|
|
816
|
+
# printing a count that looks authoritative.
|
|
817
|
+
print(f"\n{shown} shown (newest first), total UNKNOWN "
|
|
818
|
+
f"(the server sent no `total`)")
|
|
819
|
+
elif shown < int(total):
|
|
820
|
+
print(f"\n{shown} of {total} shown, NEWEST FIRST, {int(total) - shown} "
|
|
821
|
+
f"older rows not listed. Raise --limit to reach further back.")
|
|
822
|
+
else:
|
|
823
|
+
print(f"\n{shown} of {total} (newest first)")
|
|
824
|
+
return 0
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def cmd_connectors(args) -> int:
|
|
828
|
+
"""A space's connectors, what each one's last sync run actually did, or
|
|
829
|
+
`grants` for what they may do.
|
|
830
|
+
|
|
831
|
+
The default subject is the original listing, unchanged: adding a
|
|
832
|
+
subject that displaced it would break every existing invocation,
|
|
833
|
+
and the breakage would look like a connector problem rather than a
|
|
834
|
+
CLI change.
|
|
835
|
+
|
|
836
|
+
The second line per connector is the whole point of the command
|
|
837
|
+
for an operator diagnosing cadence: `trigger` separates the two
|
|
838
|
+
clocks a connector runs on (`scheduler` means the periodic poll
|
|
839
|
+
produced this run, `push` means a provider change notification
|
|
840
|
+
did), and `dur` is how long the run held the tick. The tick is
|
|
841
|
+
strictly serial, so a large number here on one connector explains
|
|
842
|
+
every other connector running late.
|
|
843
|
+
"""
|
|
844
|
+
subject = (getattr(args, "subject", None) or connectors_mod.DEFAULT_SUBJECT).strip().lower()
|
|
845
|
+
if subject not in connectors_mod.SUBJECTS:
|
|
846
|
+
raise connectors_mod.subject_error(getattr(args, "subject", None))
|
|
847
|
+
if getattr(args, "space_id", None) and not getattr(args, "space", None):
|
|
848
|
+
args.space = args.space_id
|
|
849
|
+
admin = bool(getattr(args, "admin", False))
|
|
850
|
+
if subject == "grants":
|
|
851
|
+
# No member-level equivalent: the grant view (consented scopes, auth
|
|
852
|
+
# status, expiry) is platform-admin only, always.
|
|
853
|
+
privileges.require_admin_flag("fm connectors grants", admin)
|
|
854
|
+
return connectors_mod.run_grants(args, _effective(args))
|
|
855
|
+
eff = _effective(args)
|
|
856
|
+
target, space = eff.target, eff.space
|
|
857
|
+
# Same card shape either way (`_connection_dict`): the member route reads
|
|
858
|
+
# only the caller's own space's connections; --admin reads any space.
|
|
859
|
+
path = (
|
|
860
|
+
f"/admin/spaces/{space}/connectors" if admin else f"/projects/{space}/connections"
|
|
861
|
+
)
|
|
862
|
+
fetch = api.admin_get if admin else api.get
|
|
863
|
+
payload = fetch(target, path, token=_token_for(eff))
|
|
864
|
+
for item in _items(payload):
|
|
865
|
+
# `type`, not `kind`: the payload has never had a `kind` key, so an
|
|
866
|
+
# operator could not otherwise tell one connector type from another in
|
|
867
|
+
# the output of the command whose whole job is telling them apart.
|
|
868
|
+
# `label` is the registry's human name for the same thing.
|
|
869
|
+
kind = item.get("type") or item.get("kind") or "?"
|
|
870
|
+
print(f"{item.get('id')} {str(kind).lower():<16} {item.get('status', '?')}")
|
|
871
|
+
print(
|
|
872
|
+
f" last_synced={item.get('last_synced_at') or '-'}"
|
|
873
|
+
f" next_sync={item.get('next_sync_at') or '-'}"
|
|
874
|
+
f" every={item.get('sync_interval_seconds', '?')}s"
|
|
875
|
+
)
|
|
876
|
+
run = item.get("sync_run")
|
|
877
|
+
if not isinstance(run, dict):
|
|
878
|
+
# Distinguished from a run that failed: this connector has never run at
|
|
879
|
+
# all, which for a linked connector is itself the finding.
|
|
880
|
+
print(" last run: (never)")
|
|
881
|
+
continue
|
|
882
|
+
dur = run.get("duration_seconds")
|
|
883
|
+
# A live run has no finished_at, so its duration is elapsed-so-far; saying
|
|
884
|
+
# which it is costs one character and stops "202s" being read as final.
|
|
885
|
+
elapsed = "-" if dur is None else (
|
|
886
|
+
f"{dur}s" if run.get("finished_at") else f"{dur}s so far"
|
|
887
|
+
)
|
|
888
|
+
print(
|
|
889
|
+
f" last run: {run.get('state', '?'):<10} trigger={run.get('trigger', '?'):<9}"
|
|
890
|
+
f" dur={elapsed}"
|
|
891
|
+
f" items={run.get('items_processed', '?')}/{run.get('items_seen', '?')}"
|
|
892
|
+
f" failed={run.get('items_failed', '?')}"
|
|
893
|
+
)
|
|
894
|
+
if run.get("error"):
|
|
895
|
+
print(f" error: {run['error']}")
|
|
896
|
+
return 0
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
def cmd_entity_fields(args) -> int:
|
|
900
|
+
"""A space's custom-field schemas.
|
|
901
|
+
|
|
902
|
+
This is a project route, not an admin one (``GET
|
|
903
|
+
/projects/{id}/entity-fields``): being able to inspect the field
|
|
904
|
+
shape directly means an operator never has to write to
|
|
905
|
+
``project.settings`` by hand to work around not seeing it.
|
|
906
|
+
|
|
907
|
+
The gate is membership, not platform-admin, so this needs a
|
|
908
|
+
session belonging to a member of the space. That is the normal
|
|
909
|
+
case for the operator and is why no admin-scoped endpoint was
|
|
910
|
+
added for it.
|
|
911
|
+
"""
|
|
912
|
+
eff = _effective(args)
|
|
913
|
+
target, space = eff.target, eff.space
|
|
914
|
+
payload = api.get(
|
|
915
|
+
target,
|
|
916
|
+
f"/projects/{space}/entity-fields",
|
|
917
|
+
token=_token_for(eff),
|
|
918
|
+
)
|
|
919
|
+
items = payload.get("items") if isinstance(payload, dict) else None
|
|
920
|
+
if not isinstance(items, dict) or not items:
|
|
921
|
+
print("(no custom entity fields configured for this space)")
|
|
922
|
+
return 0
|
|
923
|
+
for kind, fields in sorted(items.items()):
|
|
924
|
+
print(f"{kind} ({len(fields)} field{'s' if len(fields) != 1 else ''})")
|
|
925
|
+
for field in fields:
|
|
926
|
+
if isinstance(field, dict):
|
|
927
|
+
print(f" {field.get('name', '?'):<24} {field.get('type', '?')}")
|
|
928
|
+
return 0
|
|
929
|
+
|
|
930
|
+
|
|
931
|
+
def cmd_doctor(args) -> int:
|
|
932
|
+
"""Health across environments, reported honestly.
|
|
933
|
+
|
|
934
|
+
Never aborts on the first failure: one region being unreachable is exactly when
|
|
935
|
+
the state of the others matters most. The exit code is the WORST status seen,
|
|
936
|
+
not the first.
|
|
937
|
+
"""
|
|
938
|
+
host = getattr(args, "host", None)
|
|
939
|
+
envs = [prefs.canonical_env(host)] if host else list(HOSTS)
|
|
940
|
+
|
|
941
|
+
reports = []
|
|
942
|
+
for env in envs:
|
|
943
|
+
try:
|
|
944
|
+
target = resolve(env)
|
|
945
|
+
except TargetError as exc:
|
|
946
|
+
reports.append(doctor_mod.EnvReport.unreachable(str(env), str(exc)))
|
|
947
|
+
continue
|
|
948
|
+
|
|
949
|
+
try:
|
|
950
|
+
report = doctor_mod.EnvReport.from_health(
|
|
951
|
+
env, api.get(target, "/health", timeout=10)
|
|
952
|
+
)
|
|
953
|
+
except api.ApiError as exc:
|
|
954
|
+
# One line, because a rollup with a five-line paragraph in it is not a
|
|
955
|
+
# rollup. The per-env command still gives the full explanation.
|
|
956
|
+
reports.append(
|
|
957
|
+
doctor_mod.EnvReport.unreachable(
|
|
958
|
+
str(env), str(exc).splitlines()[0]
|
|
959
|
+
)
|
|
960
|
+
)
|
|
961
|
+
continue
|
|
962
|
+
|
|
963
|
+
report = _with_credential(report, target.name)
|
|
964
|
+
reports.append(_with_migrations(report, target, target.env))
|
|
965
|
+
|
|
966
|
+
print(f"fm doctor: {len(reports)} deployment(s)")
|
|
967
|
+
print(doctor_mod.rollup(reports))
|
|
968
|
+
worst = doctor_mod.Status.worst([r.status for r in reports])
|
|
969
|
+
if worst is not doctor_mod.Status.OK:
|
|
970
|
+
print(f"\nworst: {worst.name}", file=sys.stderr)
|
|
971
|
+
return 0 if worst is doctor_mod.Status.OK else 1
|
|
972
|
+
|
|
973
|
+
|
|
974
|
+
def _with_credential(report, env: str):
|
|
975
|
+
"""Annotate with the stored credential's state, described, never revealed.
|
|
976
|
+
|
|
977
|
+
Never decodes the token: an ``fm login`` access token is opaque,
|
|
978
|
+
so the only place left to read expiry from is the metadata
|
|
979
|
+
``fm login``/refresh wrote beside it (:func:`tokens.load_meta`,
|
|
980
|
+
:func:`tokens.describe_meta`), the same source ``fm whoami``
|
|
981
|
+
already uses.
|
|
982
|
+
"""
|
|
983
|
+
try:
|
|
984
|
+
token, origin = tokens.load_for(env)
|
|
985
|
+
except tokens.TokenError as exc:
|
|
986
|
+
return replace(report, credential=f"unusable: {exc}")
|
|
987
|
+
if not token:
|
|
988
|
+
return replace(report, credential=f"none stored (fm login --host {env})")
|
|
989
|
+
if origin == tokens.ENV_TOKEN_ORIGIN:
|
|
990
|
+
return replace(report, credential=f"environment ({tokens.ENV_TOKEN_VAR})")
|
|
991
|
+
info = tokens.describe_meta(tokens.load_meta(origin))
|
|
992
|
+
borrowed = "" if origin == env else f" (using the {origin} token)"
|
|
993
|
+
return replace(report, credential=f"{info.describe_expiry()}{borrowed}")
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
def _with_migrations(report, target, env: str):
|
|
997
|
+
"""Annotate with alembic identity when /admin/instance is available.
|
|
998
|
+
|
|
999
|
+
Absence is not a failure: the endpoint is admin-gated (Global, or
|
|
1000
|
+
Formist as its own single-region deployment), so a local or
|
|
1001
|
+
unauthenticated run against any other region legitimately has
|
|
1002
|
+
nothing to say here. Reporting "unknown" would be inventing a
|
|
1003
|
+
problem.
|
|
1004
|
+
"""
|
|
1005
|
+
if target.is_prod and not is_admin_env(env):
|
|
1006
|
+
return report
|
|
1007
|
+
try:
|
|
1008
|
+
token, _ = tokens.load_for(target.name)
|
|
1009
|
+
payload = api.admin_get(target, "/admin/instance", token=token)
|
|
1010
|
+
except (api.ApiError, tokens.TokenError):
|
|
1011
|
+
return report
|
|
1012
|
+
if not isinstance(payload, dict):
|
|
1013
|
+
return report
|
|
1014
|
+
for name, data in (payload.get("regions") or {}).items():
|
|
1015
|
+
alembic = (data or {}).get("alembic") or {}
|
|
1016
|
+
if alembic.get("in_sync") is False:
|
|
1017
|
+
return replace(
|
|
1018
|
+
report,
|
|
1019
|
+
migrations=(
|
|
1020
|
+
f"{name}: db_head={alembic.get('db_head')} != "
|
|
1021
|
+
f"code_heads={alembic.get('code_heads')}; a migration is "
|
|
1022
|
+
"pending or failed"
|
|
1023
|
+
),
|
|
1024
|
+
)
|
|
1025
|
+
return replace(report, migrations="in sync")
|
|
1026
|
+
|
|
1027
|
+
|
|
1028
|
+
def cmd_use(args) -> int:
|
|
1029
|
+
"""Remember a default space, and, for reads only, a default environment.
|
|
1030
|
+
|
|
1031
|
+
Records the space's region as reported by the server, so a later
|
|
1032
|
+
write whose --env contradicts it is refused before a socket is
|
|
1033
|
+
opened. That is a cheap catch for a costly accident, and it costs
|
|
1034
|
+
one comparison.
|
|
1035
|
+
"""
|
|
1036
|
+
if args.clear:
|
|
1037
|
+
print("forgot the remembered defaults" if prefs.clear() else "nothing remembered")
|
|
1038
|
+
return 0
|
|
1039
|
+
|
|
1040
|
+
if not args.show and args.space is None and args.host is None:
|
|
1041
|
+
print("nothing to set. Usage: fm use --space <uuid> [--host <host>] | --show | --clear",
|
|
1042
|
+
file=sys.stderr)
|
|
1043
|
+
return 2
|
|
1044
|
+
|
|
1045
|
+
if args.space is not None or args.host is not None:
|
|
1046
|
+
region = prefs._UNSET
|
|
1047
|
+
if args.space is not None:
|
|
1048
|
+
space = require_space_id(args.space)
|
|
1049
|
+
# Read the region back from the SERVER rather than assuming the env
|
|
1050
|
+
# being set is the one that owns the space. The recorded value has to
|
|
1051
|
+
# come from the thing it describes, or it vouches for nothing.
|
|
1052
|
+
region = _lookup_region(space, args.host)
|
|
1053
|
+
prefs.store(
|
|
1054
|
+
space=args.space if args.space is not None else prefs._UNSET,
|
|
1055
|
+
env=args.host if args.host is not None else prefs._UNSET,
|
|
1056
|
+
space_region=region,
|
|
1057
|
+
)
|
|
1058
|
+
|
|
1059
|
+
current = prefs.load()
|
|
1060
|
+
print(f"space {current.space or '(none)'}")
|
|
1061
|
+
print(f"host {current.env or '(none)'} (reads only; a write always needs --host)")
|
|
1062
|
+
if current.space_region:
|
|
1063
|
+
print(f"region {current.space_region} (recorded from the server)")
|
|
1064
|
+
if current.set_at:
|
|
1065
|
+
print(f"set {current.age}")
|
|
1066
|
+
return 0
|
|
1067
|
+
|
|
1068
|
+
|
|
1069
|
+
def _lookup_region(space: str, env: str | None) -> object:
|
|
1070
|
+
"""The region /admin/spaces reports for ``space``, or ``_UNSET`` if unknown.
|
|
1071
|
+
|
|
1072
|
+
Never guessed from the env being set: an unknown region must stay
|
|
1073
|
+
unknown, so that `prefs.effective` treats it as absence of
|
|
1074
|
+
knowledge rather than as evidence. A lookup that fails is not a
|
|
1075
|
+
reason to refuse `fm use`, since the operator may legitimately be
|
|
1076
|
+
offline or not logged in.
|
|
1077
|
+
"""
|
|
1078
|
+
for candidate in (env or DEFAULT_HOST,):
|
|
1079
|
+
if candidate is None:
|
|
1080
|
+
continue
|
|
1081
|
+
try:
|
|
1082
|
+
target = resolve(prefs.canonical_env(candidate))
|
|
1083
|
+
except (TargetError, PrefsError):
|
|
1084
|
+
continue
|
|
1085
|
+
# Only a prod instance can make a residency claim. A local dev server
|
|
1086
|
+
# reports every space it holds as its own home region (`global`), which
|
|
1087
|
+
# is a fact about the server, not about the row.
|
|
1088
|
+
if not target.is_prod:
|
|
1089
|
+
continue
|
|
1090
|
+
try:
|
|
1091
|
+
token, _ = tokens.load_for(target.name)
|
|
1092
|
+
payload = api.admin_get(target, "/admin/spaces", token=token)
|
|
1093
|
+
except (api.ApiError, tokens.TokenError):
|
|
1094
|
+
continue
|
|
1095
|
+
for item in _items(payload):
|
|
1096
|
+
if str(item.get("id")) == space and item.get("region"):
|
|
1097
|
+
region = str(item["region"])
|
|
1098
|
+
print(f" server reports this space is resident in {region}",
|
|
1099
|
+
file=sys.stderr)
|
|
1100
|
+
return region
|
|
1101
|
+
print(
|
|
1102
|
+
" (no residency region recorded; only a prod instance can state one)",
|
|
1103
|
+
file=sys.stderr,
|
|
1104
|
+
)
|
|
1105
|
+
return prefs._UNSET
|
|
1106
|
+
|
|
1107
|
+
|
|
1108
|
+
def cmd_get(args) -> int:
|
|
1109
|
+
"""Find rows by name and print the ids they resolve to.
|
|
1110
|
+
|
|
1111
|
+
Listing and resolving are different acts: listing shows every candidate,
|
|
1112
|
+
resolving demands exactly one. `fm get --name X` therefore refuses on ambiguity
|
|
1113
|
+
where a bare `fm get` happily prints both rows.
|
|
1114
|
+
"""
|
|
1115
|
+
eff = _effective(args, need_token=True)
|
|
1116
|
+
token = eff.token
|
|
1117
|
+
kind = resolve_mod.require_kind(args.kind)
|
|
1118
|
+
|
|
1119
|
+
if args.name:
|
|
1120
|
+
match = resolve_mod.resolve_one(
|
|
1121
|
+
args.name, kind=kind, target=eff.target, space=eff.space, token=token
|
|
1122
|
+
)
|
|
1123
|
+
if args.json:
|
|
1124
|
+
print(json.dumps(
|
|
1125
|
+
{"id": match.id, "field": match.field, "value": match.value},
|
|
1126
|
+
indent=2, ensure_ascii=False, default=str,
|
|
1127
|
+
))
|
|
1128
|
+
else:
|
|
1129
|
+
print(f"{match.id} {match.label}")
|
|
1130
|
+
print(f" matched on {match.field} = "
|
|
1131
|
+
f"{json.dumps(match.value, ensure_ascii=False, default=str)}")
|
|
1132
|
+
return 0
|
|
1133
|
+
|
|
1134
|
+
matches = resolve_mod.find(
|
|
1135
|
+
None, kind=kind, target=eff.target, space=eff.space, token=token
|
|
1136
|
+
)
|
|
1137
|
+
if args.json:
|
|
1138
|
+
print(json.dumps(
|
|
1139
|
+
[{"id": m.id, "field": m.field, "value": m.value} for m in matches],
|
|
1140
|
+
indent=2, ensure_ascii=False, default=str,
|
|
1141
|
+
))
|
|
1142
|
+
return 0
|
|
1143
|
+
for match in matches:
|
|
1144
|
+
print(f"{match.id} {match.label}")
|
|
1145
|
+
if not matches:
|
|
1146
|
+
print(f"(no {kind} rows in this space)")
|
|
1147
|
+
return 0
|
|
1148
|
+
|
|
1149
|
+
|
|
1150
|
+
def cmd_update(args) -> int:
|
|
1151
|
+
"""Dry-run a bulk change, then apply it only against the token that dry run gave.
|
|
1152
|
+
|
|
1153
|
+
The dry run is not optional and not skippable. The server executes
|
|
1154
|
+
every op for real and rolls back, so what is printed is what would
|
|
1155
|
+
happen, including the ids the inserts actually produced.
|
|
1156
|
+
"""
|
|
1157
|
+
eff = _effective(args, for_write=True, need_token=True)
|
|
1158
|
+
token = eff.token
|
|
1159
|
+
|
|
1160
|
+
payload = update_mod.load_payload(args.payload)
|
|
1161
|
+
plan = update_mod.build_plan(
|
|
1162
|
+
payload, target=eff.target, space=eff.space, token=token
|
|
1163
|
+
)
|
|
1164
|
+
|
|
1165
|
+
if plan.resolutions:
|
|
1166
|
+
print("\nresolved by name:", file=sys.stderr)
|
|
1167
|
+
for resolution in plan.resolutions:
|
|
1168
|
+
print(f" {resolution.describe()}", file=sys.stderr)
|
|
1169
|
+
|
|
1170
|
+
if args.apply:
|
|
1171
|
+
report = update_mod.apply(
|
|
1172
|
+
plan, eff.target, token=token, supplied_token=args.apply
|
|
1173
|
+
)
|
|
1174
|
+
_print_report(report, applied=True, json_out=args.json)
|
|
1175
|
+
return 0
|
|
1176
|
+
|
|
1177
|
+
report = update_mod.dry_run(plan, eff.target, token=token)
|
|
1178
|
+
_print_report(report, applied=False, json_out=args.json)
|
|
1179
|
+
token_value = update_mod.plan_token(plan, report)
|
|
1180
|
+
print(
|
|
1181
|
+
f"\nDRY RUN: nothing was changed.\n"
|
|
1182
|
+
f"To apply this exact plan:\n"
|
|
1183
|
+
f" fm update --host {eff.target.name} --space {eff.space} "
|
|
1184
|
+
f"{args.payload} --apply {token_value}",
|
|
1185
|
+
file=sys.stderr,
|
|
1186
|
+
)
|
|
1187
|
+
return 0
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
def _print_report(report: object, *, applied: bool, json_out: bool) -> None:
|
|
1191
|
+
"""Print the server's report.
|
|
1192
|
+
|
|
1193
|
+
Every value here is read out of the response body. Nothing is
|
|
1194
|
+
echoed from the payload that was sent: a confirmation line that
|
|
1195
|
+
prints what it hoped to write would confirm whatever landed,
|
|
1196
|
+
whether or not it matched what was sent.
|
|
1197
|
+
"""
|
|
1198
|
+
if json_out:
|
|
1199
|
+
print(json.dumps(report, indent=2, ensure_ascii=False, default=str))
|
|
1200
|
+
return
|
|
1201
|
+
if not isinstance(report, dict):
|
|
1202
|
+
print(report)
|
|
1203
|
+
return
|
|
1204
|
+
|
|
1205
|
+
counts = report.get("counts") or {}
|
|
1206
|
+
print(f"mode={report.get('mode')} committed={report.get('committed')}")
|
|
1207
|
+
print(f" ops={counts.get('ops')} ok={counts.get('ok')} "
|
|
1208
|
+
f"refused={counts.get('refused')} applied={counts.get('applied')}")
|
|
1209
|
+
for result in report.get("results") or []:
|
|
1210
|
+
if not isinstance(result, dict):
|
|
1211
|
+
continue
|
|
1212
|
+
cascaded = result.get("cascaded")
|
|
1213
|
+
extra = f" cascade={cascaded}" if cascaded else ""
|
|
1214
|
+
print(f" [{result.get('index')}] {result.get('action')} "
|
|
1215
|
+
f"{result.get('kind')} {result.get('id')} "
|
|
1216
|
+
f"-> {result.get('outcome')}{extra}")
|
|
1217
|
+
for refusal in report.get("refusals") or []:
|
|
1218
|
+
if isinstance(refusal, dict):
|
|
1219
|
+
print(f" REFUSED [{refusal.get('index')}] {refusal.get('reason')}: "
|
|
1220
|
+
f"{refusal.get('message', '')}")
|
|
1221
|
+
|
|
1222
|
+
|
|
1223
|
+
def _items(payload: object) -> list[dict]:
|
|
1224
|
+
if isinstance(payload, dict):
|
|
1225
|
+
items = payload.get("items")
|
|
1226
|
+
if isinstance(items, list):
|
|
1227
|
+
return [i for i in items if isinstance(i, dict)]
|
|
1228
|
+
if isinstance(payload, list):
|
|
1229
|
+
return [i for i in payload if isinstance(i, dict)]
|
|
1230
|
+
print(json.dumps(payload, indent=2, default=str))
|
|
1231
|
+
return []
|
|
1232
|
+
|
|
1233
|
+
|
|
1234
|
+
_COMMANDS = {
|
|
1235
|
+
"login": cmd_login,
|
|
1236
|
+
"logout": cmd_logout,
|
|
1237
|
+
"whoami": cmd_whoami,
|
|
1238
|
+
"health": cmd_health,
|
|
1239
|
+
"instance": cmd_instance,
|
|
1240
|
+
"spaces": spaces_mod.run,
|
|
1241
|
+
"proposals": cmd_proposals,
|
|
1242
|
+
"audit-log": cmd_audit_log,
|
|
1243
|
+
"connectors": cmd_connectors,
|
|
1244
|
+
"entity-fields": cmd_entity_fields,
|
|
1245
|
+
"doctor": cmd_doctor,
|
|
1246
|
+
"use": cmd_use,
|
|
1247
|
+
"get": cmd_get,
|
|
1248
|
+
"chats": chats_mod.cmd_chats,
|
|
1249
|
+
"chat": chat_mod.cmd_chat,
|
|
1250
|
+
"export": export_mod.cmd_export,
|
|
1251
|
+
"import": importer_mod.cmd_import,
|
|
1252
|
+
"update": cmd_update,
|
|
1253
|
+
"logs": logs.run,
|
|
1254
|
+
"users": users.run,
|
|
1255
|
+
"space-plan": space_plan.run,
|
|
1256
|
+
"skill-library-install": skill_library.run_install,
|
|
1257
|
+
"skills-add": skills.cmd_skills_add,
|
|
1258
|
+
"skills-update": skills.cmd_skills_update,
|
|
1259
|
+
"diff": diff_mod.cmd_diff,
|
|
1260
|
+
"airtable": airtable_mod.cmd_airtable,
|
|
1261
|
+
"participants": participants_mod.cmd_participants,
|
|
1262
|
+
"upload": uploads_mod.cmd_upload,
|
|
1263
|
+
"skill-attach": uploads_mod.cmd_skill_attach,
|
|
1264
|
+
"usage-tokens": usage_tokens_mod.run,
|
|
1265
|
+
"alerts": alerts_mod.run,
|
|
1266
|
+
"settings": settings_mod.run,
|
|
1267
|
+
"kb": kb_mod.run,
|
|
1268
|
+
"meeting": meetings_mod.run,
|
|
1269
|
+
"files": files_mod.cmd_files,
|
|
1270
|
+
"project": projects_mod.run,
|
|
1271
|
+
"connector": connectors_mod.run_connector,
|
|
1272
|
+
"messages": messages_mod.run,
|
|
1273
|
+
"whatsapp": whatsapp_mod.run,
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
|
|
1277
|
+
def main(
|
|
1278
|
+
argv: list[str] | None = None,
|
|
1279
|
+
*,
|
|
1280
|
+
parser: argparse.ArgumentParser | None = None,
|
|
1281
|
+
commands: dict | None = None,
|
|
1282
|
+
extra_errors: tuple[type[BaseException], ...] = (),
|
|
1283
|
+
check_privileges=None,
|
|
1284
|
+
prepare=None,
|
|
1285
|
+
) -> int:
|
|
1286
|
+
"""Run one command. ``parser``/``commands``/``extra_errors`` let another
|
|
1287
|
+
front end (such as a repository's own developer tool) reuse this dispatch."""
|
|
1288
|
+
args = (parser or build_parser()).parse_args(argv)
|
|
1289
|
+
table = _COMMANDS if commands is None else commands
|
|
1290
|
+
try:
|
|
1291
|
+
if prepare is not None:
|
|
1292
|
+
prepare(args)
|
|
1293
|
+
# The --admin gate, for every command whose WHOLE surface is
|
|
1294
|
+
# platform-admin (LEVEL_ADMIN). It fires on the missing FLAG, before
|
|
1295
|
+
# any file is read or any request is built, regardless of what the
|
|
1296
|
+
# stored credential's scopes say; a MIXED command (e.g. `fm spaces`,
|
|
1297
|
+
# `fm files merge`) gates its own admin-only subject/subcommand
|
|
1298
|
+
# itself, since this table entry cannot see which one is about to run.
|
|
1299
|
+
if privileges.requires_admin(args.command) and not getattr(args, "admin", False):
|
|
1300
|
+
print(
|
|
1301
|
+
f"error: `fm {args.command}` needs --admin (platform administrators "
|
|
1302
|
+
"only).",
|
|
1303
|
+
file=sys.stderr,
|
|
1304
|
+
)
|
|
1305
|
+
return 2
|
|
1306
|
+
# The privilege pre-check, at the one point every command passes
|
|
1307
|
+
# through. It only ever refuses what the server would also refuse.
|
|
1308
|
+
# `resolve` here (not `_effective`) for the same reason cmd_login
|
|
1309
|
+
# uses it: which credential file is read must come from the command
|
|
1310
|
+
# line, never from a remembered target.
|
|
1311
|
+
(check_privileges or privileges.check)(
|
|
1312
|
+
args.command,
|
|
1313
|
+
tokens.local_scopes(resolve(getattr(args, "host", None)).name),
|
|
1314
|
+
)
|
|
1315
|
+
return table[args.command](args)
|
|
1316
|
+
except api.BulkRefused as exc:
|
|
1317
|
+
# The refusal report is the product: it names the offending op by index and
|
|
1318
|
+
# carries a machine-readable reason. Flattening it to a message would throw
|
|
1319
|
+
# away the only part a caller can act on.
|
|
1320
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
1321
|
+
_print_report(exc.payload, applied=False, json_out=False)
|
|
1322
|
+
return 2
|
|
1323
|
+
except USER_ERRORS + extra_errors as exc:
|
|
1324
|
+
# These carry operator-facing prose, so print the message rather than a
|
|
1325
|
+
# traceback: the message is the product.
|
|
1326
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
1327
|
+
return 2
|
|
1328
|
+
except KeyboardInterrupt:
|
|
1329
|
+
return 130
|
|
1330
|
+
|
|
1331
|
+
|
|
1332
|
+
#: Exceptions whose message is written for the user; printed, not a traceback.
|
|
1333
|
+
USER_ERRORS = (
|
|
1334
|
+
TargetError,
|
|
1335
|
+
PrefsError,
|
|
1336
|
+
DiffError,
|
|
1337
|
+
ResolutionError,
|
|
1338
|
+
ChatsError,
|
|
1339
|
+
AirtableError,
|
|
1340
|
+
ParticipantsError,
|
|
1341
|
+
FilesError,
|
|
1342
|
+
ExportError,
|
|
1343
|
+
ImportRefused,
|
|
1344
|
+
UpdateError,
|
|
1345
|
+
UploadError,
|
|
1346
|
+
api.ApiError,
|
|
1347
|
+
tokens.TokenError,
|
|
1348
|
+
logs.LogsError,
|
|
1349
|
+
users.UsersError,
|
|
1350
|
+
connectors_mod.ConnectorsError,
|
|
1351
|
+
space_plan.SpacePlanError,
|
|
1352
|
+
skill_library.SkillLibraryError,
|
|
1353
|
+
messages_mod.MessagesError,
|
|
1354
|
+
SpacesError,
|
|
1355
|
+
UsageTokensError,
|
|
1356
|
+
AlertsError,
|
|
1357
|
+
WhatsAppError,
|
|
1358
|
+
KbError,
|
|
1359
|
+
MeetingsError,
|
|
1360
|
+
ProjectsError,
|
|
1361
|
+
privileges.PrivilegeError,
|
|
1362
|
+
login_mod.LoginError,
|
|
1363
|
+
)
|
|
1364
|
+
|
|
1365
|
+
|
|
1366
|
+
if __name__ == "__main__":
|
|
1367
|
+
raise SystemExit(main())
|