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.
@@ -0,0 +1,451 @@
1
+ """``fm whatsapp`` - platform-admin WhatsApp device management, over
2
+ ``/admin/whatsapp/devices*``.
3
+
4
+ Region-local, like `fm alerts` / `fm messages`. A ``whatsapp_device`` row is
5
+ regional: each region's instance manages the devices that live in its own
6
+ database, exactly like ``/admin/alerts``. So ``--env ae`` reads the AE
7
+ region's own devices; ``--host evane`` reads Global's, which is a different,
8
+ usually-empty set. There is no single "the" list across regions, only
9
+ per-region ones.
10
+
11
+ Writes. Every mutating subject here (``add``, ``pair``, ``start``,
12
+ ``stop``, ``logout``, ``mark-account-deleted``, ``delete``) takes effect
13
+ immediately, none has a server-side dry run, so ``--env`` never inherits from
14
+ ``fm use`` on a write, the same rule as every other write in this CLI.
15
+
16
+ ``delete`` is irreversible and the server itself refuses it while
17
+ ``account_deleted_at`` is unset, but this command adds its own gate on top:
18
+ it fetches the device, prints its phone number, and asks the operator to
19
+ type it back before sending the delete, unless ``--yes`` is given. A device
20
+ id is 36 characters nobody reads by eye; the phone number is the thing an
21
+ operator actually recognises, so that is what has to be typed, the same
22
+ reasoning `fm spaces delete`'s ``--confirm`` exists for, one step further
23
+ because there is no dry run to show first.
24
+
25
+ ``pair`` POSTs ``{"method": "qr"|"code"}`` to ``.../pair``, then polls
26
+ ``GET .../pairing`` every few seconds until the device reports ``connected`` or
27
+ ``--timeout`` (default 300s) elapses. A QR is rendered as a scannable terminal
28
+ code via the optional third-party ``qrcode`` package, imported lazily and
29
+ only here, since `fm` is stdlib-only at module import time, so a missing
30
+ ``qrcode`` prints the raw QR string instead of failing the command;
31
+ ``--code`` sidesteps the whole question by asking the server for a phone
32
+ code instead.
33
+
34
+ ``fm whatsapp runner start|stop|status`` is the armed switch, over
35
+ ``/admin/whatsapp/runner*``. This is process-wide, independent of any one
36
+ device's own ``start``/``stop`` above: a dev box can set autostart off so a
37
+ reload never reconnects on its own, and this is the manual step that
38
+ (re)connects it. ``status`` (the default with no action given) is a read;
39
+ ``start``/``stop`` are writes, so ``--env`` never inherits from ``fm use``
40
+ for any of the three, the same as every other write in this file.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import argparse
46
+ import json
47
+ import re
48
+ import time
49
+
50
+ from formist_cli import api, context
51
+ from formist_cli.cli_support import PLATFORM_ADMIN_GATE_NOTE, add_admin_flag
52
+ from formist_cli.cli_support import as_dict as _shared_as_dict
53
+ from formist_cli.cli_support import build_standalone_parser as _build_standalone_parser
54
+
55
+ SUBJECTS = (
56
+ "devices", "add", "show", "pair",
57
+ "start", "stop", "logout", "mark-account-deleted", "delete", "groups",
58
+ "runner",
59
+ )
60
+ DEFAULT_SUBJECT = "devices"
61
+
62
+ #: Write subjects, resolved with ``for_write=True`` (never inherits ``--env``
63
+ #: from ``fm use``), same convention as every other mutating command in this
64
+ #: CLI. ``runner`` covers all three of its own actions
65
+ #: (``start``/``stop``/``status``) even though ``status`` is a read, see
66
+ #: the module docstring.
67
+ _WHATSAPP_WRITE_SUBJECTS = frozenset({
68
+ "add", "pair", "start", "stop", "logout",
69
+ "mark-account-deleted", "delete", "runner",
70
+ })
71
+
72
+ DEVICES_PATH = "/admin/whatsapp/devices"
73
+ RUNNER_PATH = "/admin/whatsapp/runner"
74
+ RUNNER_ACTIONS = ("status", "start", "stop")
75
+ DEFAULT_RUNNER_ACTION = "status"
76
+
77
+ #: Poll cadence for `pair`: every 2-3 seconds, since the QR rotates roughly
78
+ #: every 20 seconds.
79
+ PAIR_POLL_INTERVAL_SECONDS = 3
80
+ DEFAULT_PAIR_TIMEOUT_SECONDS = 300
81
+
82
+ _E164_RE = re.compile(r"^\+[1-9]\d{6,14}$")
83
+
84
+ #: The device response's own field order, used to render `show`/`add`/every
85
+ #: write that returns a device: one table, so a field added to the server
86
+ #: response and forgotten here is a visible gap, not a silently-dropped
87
+ #: column (``.get`` returns ``None`` and the row still prints, labelled).
88
+ _DEVICE_FIELDS = (
89
+ "id", "phone_e164", "display_name", "region", "status", "enabled",
90
+ "jid", "push_name", "platform",
91
+ "account_deleted_at",
92
+ "last_connected_at", "last_seen_at", "last_error",
93
+ "groups_cached_at", "history_synced_at",
94
+ "registration_recordings",
95
+ "created_at", "updated_at",
96
+ )
97
+
98
+
99
+ class WhatsAppError(Exception):
100
+ """A refusal about the WhatsApp device surface, written for an operator."""
101
+
102
+
103
+ def canonical_subject(subject: str | None) -> str:
104
+ if subject is None:
105
+ return DEFAULT_SUBJECT
106
+ value = subject.strip().lower()
107
+ if value not in SUBJECTS:
108
+ raise WhatsAppError(
109
+ f"unknown subcommand {subject!r}. Valid: {', '.join(SUBJECTS)}.\n"
110
+ " devices every device in this region (default)\n"
111
+ " add <+E164> register a new device (status: registering)\n"
112
+ " show <id> one device\n"
113
+ " pair <id> pair by QR (or --code); polls until connected\n"
114
+ " start|stop <id> enable/disable the runner for this device\n"
115
+ " logout <id> unlink from the primary phone (WhatsApp-side)\n"
116
+ " mark-account-deleted <id> attest the WhatsApp account was deleted\n"
117
+ " delete <id> soft-delete the row (typed phone confirmation)\n"
118
+ " groups <id> this device's joined groups\n"
119
+ " runner [start|stop|status] arm/disarm the runner PROCESS (default: status)"
120
+ )
121
+ return value
122
+
123
+
124
+ def device_path(device_id: str) -> str:
125
+ return f"{DEVICES_PATH}/{device_id}"
126
+
127
+
128
+ # ===========================================================================
129
+ # Rendering
130
+ # ===========================================================================
131
+ def render_devices(items: list[dict]) -> str:
132
+ if not items:
133
+ return "(no WhatsApp devices in this region)"
134
+ lines = [
135
+ f"{'phone':<16} {'status':<13} {'en':<3} {'region':<7} {'display_name':<24} id",
136
+ f"{'-' * 16} {'-' * 13} {'-' * 3} {'-' * 7} {'-' * 24} {'-' * 8}",
137
+ ]
138
+ for row in items:
139
+ lines.append(
140
+ f"{str(row.get('phone_e164') or '-'):<16} "
141
+ f"{str(row.get('status') or '-'):<13} "
142
+ f"{'y' if row.get('enabled') else 'n':<3} "
143
+ f"{str(row.get('region') or '-'):<7} "
144
+ f"{str(row.get('display_name') or '-'):<24.24} "
145
+ f"{row.get('id')}"
146
+ )
147
+ return "\n".join(lines)
148
+
149
+
150
+ def render_device(device: dict) -> str:
151
+ lines = []
152
+ for field in _DEVICE_FIELDS:
153
+ value = device.get(field)
154
+ if field == "registration_recordings":
155
+ value = f"{len(value)} recording(s)" if value else "(none)"
156
+ lines.append(f" {field:<28} {value}")
157
+ return "\n".join(lines)
158
+
159
+
160
+ def render_runner(payload: dict) -> str:
161
+ lines = [f"armed={payload.get('armed')}"]
162
+ if "autostart" in payload:
163
+ lines.append(f"autostart={payload.get('autostart')}")
164
+ if "started" in payload:
165
+ lines.append(f"started={payload.get('started')}")
166
+ sessions = payload.get("sessions")
167
+ if sessions is not None:
168
+ if not sessions:
169
+ lines.append("(no live sessions)")
170
+ else:
171
+ lines.append("")
172
+ lines.append(f"{'device_id':<38} {'status':<13} connected")
173
+ lines.append(f"{'-' * 38} {'-' * 13} {'-' * 9}")
174
+ for row in sessions:
175
+ lines.append(
176
+ f"{str(row.get('device_id')):<38} "
177
+ f"{str(row.get('status') or '-'):<13} "
178
+ f"{'y' if row.get('connected') else 'n'}"
179
+ )
180
+ return "\n".join(lines)
181
+
182
+
183
+ def render_groups(payload: dict) -> str:
184
+ items = payload.get("items") or []
185
+ lines = [f"cached_at={payload.get('cached_at') or '?'}", ""]
186
+ if not items:
187
+ lines.append("(no groups cached for this device, connect it, or GET again later)")
188
+ return "\n".join(lines)
189
+ lines.append(f"{'participants':<12} {'eph':<6} {'announce':<9} {'name':<28} jid")
190
+ lines.append(f"{'-' * 12} {'-' * 6} {'-' * 9} {'-' * 28} {'-' * 8}")
191
+ for row in items:
192
+ lines.append(
193
+ f"{row.get('participants', '?'):<12} "
194
+ f"{row.get('ephemeral_seconds', 0):<6} "
195
+ f"{'y' if row.get('announce_only') else 'n':<9} "
196
+ f"{str(row.get('group_name') or '-'):<28.28} "
197
+ f"{row.get('jid')}"
198
+ )
199
+ return "\n".join(lines)
200
+
201
+
202
+ def _render_qr(qr: str) -> None:
203
+ """Render ``qr`` as a scannable terminal code, or fall back to the raw string.
204
+
205
+ ``qrcode`` is a third-party package and `fm` must add no runtime
206
+ dependency, so it is imported lazily, here, only when a QR actually
207
+ needs rendering, and only ever inside this try/except. A missing
208
+ package is not a command failure: the raw string still pairs a device,
209
+ and ``--code`` is the documented way around needing this at all.
210
+ """
211
+ try:
212
+ import qrcode
213
+ except ImportError:
214
+ print(f"QR (install the `qrcode` package to render this in the terminal): {qr}")
215
+ print(" -> or re-run with --code to pair by phone code instead.")
216
+ return
217
+ code = qrcode.QRCode()
218
+ code.add_data(qr)
219
+ code.make(fit=True)
220
+ code.print_ascii(invert=True)
221
+
222
+
223
+ def _show_pairing(state: dict, last_qr: str | None) -> str | None:
224
+ """Print whatever ``state`` currently offers; return the QR string just
225
+ shown so the caller can skip re-rendering an unchanged one. The QR
226
+ rotates roughly every 20 seconds, so an unchanged value between polls
227
+ is the common case, not the exception."""
228
+ qr = state.get("qr")
229
+ pair_code = state.get("pair_code")
230
+ if qr and qr != last_qr:
231
+ _render_qr(qr)
232
+ last_qr = qr
233
+ if pair_code:
234
+ print(f"pair code: {pair_code}")
235
+ if not qr and not pair_code:
236
+ print(f"status={state.get('status')}, waiting for the device to issue a code/QR...")
237
+ return last_qr
238
+
239
+
240
+ # ===========================================================================
241
+ # CLI
242
+ # ===========================================================================
243
+ _HELP = "platform-admin WhatsApp devices: register, pair, start/stop, retire (admin)"
244
+
245
+ _DESCRIPTION = """WhatsApp linked-device management, region-local, like `fm alerts`.
246
+
247
+ fm whatsapp --env ae every device in AE (default subject)
248
+ fm whatsapp add +97150... --name 'Event bot' --env ae
249
+ fm whatsapp pair <id> --env ae QR in the terminal; --code for a phone code
250
+ fm whatsapp start|stop|logout|mark-account-deleted <id> --env ae
251
+ fm whatsapp delete <id> --env ae types the phone number back, or --yes
252
+ fm whatsapp groups <id> --env ae
253
+ fm whatsapp runner start|stop|status --env ae arm/disarm the runner process (default: status)
254
+
255
+ `delete` is irreversible server-side once `account_deleted_at` is set, and this
256
+ command asks you to type the device's phone number back first (skip with --yes).
257
+ """
258
+
259
+
260
+ def _add_arguments(parser: argparse.ArgumentParser) -> None:
261
+ parser.add_argument(
262
+ "subject", nargs="?",
263
+ help=f"one of: {', '.join(SUBJECTS)} (default: {DEFAULT_SUBJECT})",
264
+ )
265
+ parser.add_argument(
266
+ "record", nargs="?",
267
+ help="device UUID for most subjects (`add`: the +E164 phone number; "
268
+ "`runner`: one of start|stop|status, default status)",
269
+ )
270
+ parser.add_argument(
271
+ "--host",
272
+ default=argparse.SUPPRESS,
273
+ metavar="HOST",
274
+ help="deployment name or API origin (default: formist, or `fm use` for reads); "
275
+ "a write never inherits it",
276
+ )
277
+ parser.add_argument("--name", dest="display_name", default=None, help="`add`: a human label")
278
+ parser.add_argument(
279
+ "--code", action="store_true", help="`pair`: pair by phone code instead of QR",
280
+ )
281
+ parser.add_argument(
282
+ "--timeout", type=int, default=None,
283
+ help=f"`pair`: seconds to poll before giving up (default: {DEFAULT_PAIR_TIMEOUT_SECONDS})",
284
+ )
285
+ parser.add_argument(
286
+ "--yes", action="store_true",
287
+ help="`delete`: skip the typed phone-number confirmation",
288
+ )
289
+ parser.add_argument("--json", action="store_true", help="raw JSON instead of a report")
290
+
291
+
292
+ def add_parser(subparsers) -> argparse.ArgumentParser:
293
+ parser = subparsers.add_parser(
294
+ "whatsapp", help=_HELP, description=_DESCRIPTION, epilog=PLATFORM_ADMIN_GATE_NOTE,
295
+ formatter_class=argparse.RawDescriptionHelpFormatter,
296
+ )
297
+ _add_arguments(parser)
298
+ add_admin_flag(parser)
299
+ return parser
300
+
301
+
302
+ def build_standalone_parser() -> argparse.ArgumentParser:
303
+ return _build_standalone_parser(add_parser)
304
+
305
+
306
+ def _require_record(args, subject: str) -> str:
307
+ value = getattr(args, "record", None)
308
+ if not value or not value.strip():
309
+ if subject == "add":
310
+ raise WhatsAppError(
311
+ "`fm whatsapp add` needs a phone number (E.164, e.g. +97150...) as "
312
+ "the second argument."
313
+ )
314
+ raise WhatsAppError(
315
+ f"`fm whatsapp {subject}` needs a device id as the second argument.\n"
316
+ "-> `fm whatsapp devices` lists them (id is the last column)."
317
+ )
318
+ return value.strip()
319
+
320
+
321
+ def _validate_phone(value: str) -> str:
322
+ if not _E164_RE.match(value):
323
+ raise WhatsAppError(
324
+ f"`fm whatsapp add` needs an E.164 phone number like +97150XXXXXXX, got {value!r}."
325
+ )
326
+ return value
327
+
328
+
329
+ def run(args) -> int:
330
+ subject = canonical_subject(getattr(args, "subject", None))
331
+ ctx = context.resolve(args, for_write=subject in _WHATSAPP_WRITE_SUBJECTS, need_token=True)
332
+
333
+ if subject == "devices":
334
+ payload = _payload(api.admin_get(ctx.target, DEVICES_PATH, token=ctx.token))
335
+ items = payload.get("items") or []
336
+ print(json.dumps(payload, indent=2, ensure_ascii=False) if args.json
337
+ else render_devices(items))
338
+ return 0
339
+
340
+ if subject == "runner":
341
+ return _run_runner(ctx, args)
342
+
343
+ if subject == "add":
344
+ phone = _validate_phone(_require_record(args, subject))
345
+ body: dict = {"phone_e164": phone}
346
+ if getattr(args, "display_name", None):
347
+ body["display_name"] = args.display_name
348
+ payload = _payload(api.admin_post(ctx.target, DEVICES_PATH, body, token=ctx.token))
349
+ print(json.dumps(payload, indent=2, ensure_ascii=False) if args.json
350
+ else render_device(payload))
351
+ return 0
352
+
353
+ device_id = _require_record(args, subject)
354
+
355
+ if subject == "show":
356
+ payload = _payload(api.admin_get(ctx.target, device_path(device_id), token=ctx.token))
357
+ print(json.dumps(payload, indent=2, ensure_ascii=False) if args.json
358
+ else render_device(payload))
359
+ return 0
360
+
361
+ if subject == "pair":
362
+ return _run_pair(ctx, device_id, args)
363
+
364
+ if subject in ("start", "stop", "logout", "mark-account-deleted"):
365
+ payload = _payload(
366
+ api.admin_post(ctx.target, f"{device_path(device_id)}/{subject}", {}, token=ctx.token)
367
+ )
368
+ print(json.dumps(payload, indent=2, ensure_ascii=False) if args.json
369
+ else render_device(payload))
370
+ return 0
371
+
372
+ if subject == "delete":
373
+ return _run_delete(ctx, device_id, args)
374
+
375
+ # groups
376
+ payload = _payload(api.admin_get(ctx.target, f"{device_path(device_id)}/groups", token=ctx.token))
377
+ print(json.dumps(payload, indent=2, ensure_ascii=False) if args.json else render_groups(payload))
378
+ return 0
379
+
380
+
381
+ def _run_runner(ctx, args) -> int:
382
+ """`fm whatsapp runner [start|stop|status]`, the armed switch (module
383
+ docstring). `record` carries the action here, the same slot `add` uses for
384
+ a phone number and `show`/`pair`/etc. use for a device id: this file's
385
+ existing per-subject overload of that one positional, not a new shape."""
386
+ action = (getattr(args, "record", None) or DEFAULT_RUNNER_ACTION).strip().lower()
387
+ if action not in RUNNER_ACTIONS:
388
+ raise WhatsAppError(
389
+ f"`fm whatsapp runner` action must be one of {'|'.join(RUNNER_ACTIONS)}, got {action!r}."
390
+ )
391
+ if action == "status":
392
+ payload = _payload(api.admin_get(ctx.target, RUNNER_PATH, token=ctx.token))
393
+ else:
394
+ payload = _payload(api.admin_post(ctx.target, f"{RUNNER_PATH}/{action}", {}, token=ctx.token))
395
+ print(json.dumps(payload, indent=2, ensure_ascii=False) if args.json else render_runner(payload))
396
+ return 0
397
+
398
+
399
+ def _run_pair(ctx, device_id: str, args) -> int:
400
+ method = "code" if getattr(args, "code", False) else "qr"
401
+ timeout = getattr(args, "timeout", None) or DEFAULT_PAIR_TIMEOUT_SECONDS
402
+
403
+ state = _payload(
404
+ api.admin_post(ctx.target, f"{device_path(device_id)}/pair", {"method": method}, token=ctx.token)
405
+ )
406
+ last_qr = _show_pairing(state, None)
407
+
408
+ deadline = time.monotonic() + timeout
409
+ while state.get("status") != "connected":
410
+ if time.monotonic() >= deadline:
411
+ raise WhatsAppError(
412
+ f"timed out after {timeout}s waiting for device {device_id} to report "
413
+ f"connected (last status: {state.get('status')!r}).\n"
414
+ f"-> `fm whatsapp pair {device_id}` to keep waiting, or "
415
+ f"`fm whatsapp show {device_id}` to see what the device reports now."
416
+ )
417
+ time.sleep(PAIR_POLL_INTERVAL_SECONDS)
418
+ state = _payload(
419
+ api.admin_get(ctx.target, f"{device_path(device_id)}/pairing", token=ctx.token)
420
+ )
421
+ last_qr = _show_pairing(state, last_qr)
422
+
423
+ print(f"connected. device={device_id}")
424
+ if args.json:
425
+ print(json.dumps(state, indent=2, ensure_ascii=False))
426
+ return 0
427
+
428
+
429
+ def _run_delete(ctx, device_id: str, args) -> int:
430
+ device = _payload(api.admin_get(ctx.target, device_path(device_id), token=ctx.token))
431
+ phone = device.get("phone_e164") or device_id
432
+
433
+ if not getattr(args, "yes", False):
434
+ typed = input(
435
+ f"This PERMANENTLY deletes WhatsApp device {device_id} ({phone}). "
436
+ f"Type the phone number to confirm: "
437
+ ).strip()
438
+ if typed != phone:
439
+ raise WhatsAppError(
440
+ f"typed {typed!r} does not match {phone!r}, refusing.\n"
441
+ "-> Re-run and type the exact phone number, or pass --yes to skip this prompt."
442
+ )
443
+
444
+ payload = _payload(api.admin_delete(ctx.target, device_path(device_id), token=ctx.token))
445
+ print(json.dumps(payload, indent=2, ensure_ascii=False) if args.json
446
+ else f"deleted device {device_id} ({phone}): ok={payload.get('ok')}")
447
+ return 0
448
+
449
+
450
+ def _payload(payload: object) -> dict:
451
+ return _shared_as_dict(payload, what="/admin/whatsapp", error=WhatsAppError)
@@ -0,0 +1,176 @@
1
+ Metadata-Version: 2.5
2
+ Name: formist-cli
3
+ Version: 0.1.0
4
+ Summary: Command-line client for Formist and Evane deployments
5
+ Project-URL: Homepage, https://formist.ai
6
+ Project-URL: Repository, https://github.com/WeCarbon/formist-cli
7
+ Author: WeCarbon
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: cli,formist
11
+ Classifier: Environment :: Console
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+
18
+ **English** · [简体中文](README.zh-CN.md) · [Français](README.fr.md) · [العربية](README.ar.md)
19
+
20
+ # formist-cli
21
+
22
+ **`fm` is a terminal client for [Formist](https://formist.ai) and [Evane](https://evane.ai)
23
+ deployments, over the exact same API and login the web app uses.**
24
+
25
+ ![A terminal running fm health, fm spaces and fm kb search against a Formist deployment](docs/screenshot.png)
26
+
27
+ <sub>Mock data, rendered by the real `fm` code with `python3 scripts/render_screenshot.py`.</sub>
28
+
29
+ ---
30
+
31
+ ## The problem
32
+
33
+ Keeping a Formist or Evane deployment running means asking it small, urgent questions all day:
34
+ is this region healthy, is a connector stuck, did yesterday's migration apply everywhere, which
35
+ of many spaces is this customer's. Each one normally means opening the web app and clicking
36
+ through an admin page, or writing a one-off script against the API and hand-rolling the login.
37
+ Neither is scriptable, and both are slow exactly when speed matters.
38
+
39
+ ## The idea
40
+
41
+ `fm` signs in the same way the web app does, so it can only ever do what your own account is
42
+ allowed to do there, nothing more. Every command prints the deployment, space and credential it
43
+ resolved, before it runs, so what is on screen is the full picture, not a guess. A command that
44
+ changes data always shows what it would do first; committing is a separate, explicit step.
45
+
46
+ - **One client, every deployment.** `--host` switches between Formist, Evane, Evane UAE, Formist
47
+ China, or any custom origin, such as a local dev server, same binary, same commands.
48
+ - **Provenance before action.** Every command announces which deployment and space it resolved,
49
+ and where each came from, a flag, a remembered default, or nothing, so a wrong target is caught
50
+ by reading the screen, not by its effect.
51
+ - **Dry run by default.** A command that changes data prints what it would do and waits for
52
+ `--apply`. `fm update`, which applies a batch of changes at once, re-checks the plan still
53
+ matches before committing, so a stale read can't turn into a wrong write.
54
+ - **A credential per deployment.** `fm login` stores an OAuth credential at `0600`, one file per
55
+ host, so signing in to a staging deployment never touches production. `FORMIST_TOKEN` supplies
56
+ one for CI: used as-is, never written to disk, never refreshed.
57
+ - **No surprise dependencies.** Standard library only, Python 3.10+, installs in a second.
58
+
59
+ ## Install
60
+
61
+ ```sh
62
+ pipx install formist-cli
63
+ ```
64
+
65
+ Python 3.10 or newer. No third-party dependencies.
66
+
67
+ ## Usage
68
+
69
+ ### Sign in
70
+
71
+ ```sh
72
+ fm login # opens a browser; the credential is stored at 0600
73
+ fm whoami
74
+ fm logout
75
+ ```
76
+
77
+ On a machine without a browser, use `fm login --no-browser` and paste the code the page shows.
78
+ For CI, export `FORMIST_TOKEN` with the `token` field of the file `fm login` writes; it is used
79
+ as-is and never written to disk.
80
+
81
+ Credentials live in `~/.config/formist/` (override with `FORMIST_CONFIG_DIR`), one file per host,
82
+ so signing in to one deployment never replaces another.
83
+
84
+ Platform-administration actions need an extra grant: `fm login --admin` requests it, and the
85
+ server only honours the request if your account already has it. Without that flag, a platform
86
+ admin's own token still runs as an ordinary user.
87
+
88
+ ### Choosing a deployment
89
+
90
+ `fm` talks to `https://api.formist.ai` by default. `--host` picks another one:
91
+
92
+ | `--host` | API |
93
+ |--------------|---------------------------------------|
94
+ | `formist` | `https://api.formist.ai` (default) |
95
+ | `evane` | `https://api.evane.ai` |
96
+ | `evane-ae` | `https://ae.api.evane.ai` |
97
+ | `formist-cn` | `https://formist-api.we-carbon.com` |
98
+
99
+ Anything else is taken as an API origin, for example `fm --host 127.0.0.1:8160 spaces` for a
100
+ local server. `--host` works before or after the command: `fm --host evane spaces` and
101
+ `fm spaces --host evane` are the same.
102
+
103
+ ### Spaces
104
+
105
+ A space is always addressed by its id, never by its name, since names are not unique:
106
+
107
+ ```sh
108
+ fm spaces # your own spaces
109
+ fm use --space <space-id> # remember a default space
110
+ fm kb search "venue contract" --space <space-id>
111
+ ```
112
+
113
+ `fm use` can also remember a host, for reads only. A command that writes never inherits a
114
+ remembered host: name it with `--host`, or the default (`formist`) is used.
115
+
116
+ ### Writes
117
+
118
+ Most commands that change data run as a dry run first and print what they would do; add
119
+ `--apply` to commit. `fm update`, which applies a batch of changes transactionally, is slightly
120
+ different: the dry run prints a plan token, and `--apply <token>` re-runs the dry run to confirm
121
+ the plan still matches before committing. A handful of actions with no undo, such as `fm spaces
122
+ --admin delete`, have no dry run at all and say so in their own `--help`.
123
+
124
+ ### Commands
125
+
126
+ Run `fm --help` for the full list and `fm <command> --help` for each one. Every command works
127
+ with your own account's permissions, the same as the web app, and the server re-checks every
128
+ permission on every call: `fm spaces` lists the spaces you belong to, `fm health` is public and
129
+ needs no login, `fm doctor` rolls health up across every deployment, and the rest, `chats`,
130
+ `chat`, `kb`, `get`, `export`, `import`, `diff`, `upload`, `skill-attach`, `entity-fields`,
131
+ `skill-library-install`, `meeting`, `project`, `connector`, `skills-add`, `skills-update`,
132
+ `proposals`, `audit-log`, `connectors`, `files`, read or write your own space the same way.
133
+
134
+ ## FAQ
135
+
136
+ **Do I need platform-admin access to use this?**
137
+ No. Every command works with your own account's permissions by default, the same as the web app
138
+ would for that account: `fm spaces`, for example, lists the spaces you belong to. A few
139
+ commands also accept `--admin`, for a platform administrator account; without it, or without
140
+ the matching grant, they refuse locally before any request is sent, and the server still has
141
+ the final say either way.
142
+
143
+ **Can I point it at a local dev server?**
144
+ Yes: `--host` accepts any API origin, not only the four named deployments, for example
145
+ `fm --host 127.0.0.1:8160 health`.
146
+
147
+ **Can I use it in CI, without a browser?**
148
+ Yes: export `FORMIST_TOKEN` with the `token` field from the file `fm login` writes. It is read
149
+ fresh on every invocation, used as-is, and `fm` never writes it to disk or refreshes it.
150
+
151
+ **What stops a write from landing on the wrong deployment?**
152
+ `fm use` only remembers a host for reads; a write always resolves `--host` from the command
153
+ line, defaulting to `formist` if it is not given. There is no "current environment" for a write
154
+ to silently inherit.
155
+
156
+ **Will `fm` ever do something my account couldn't do in the web app?**
157
+ No. It calls the same API with the same credential, and the server enforces every permission on
158
+ every call; `fm` is a different front end for it, not a different set of rights.
159
+
160
+ ## Development
161
+
162
+ ```sh
163
+ uv sync
164
+ uv run pytest
165
+ ```
166
+
167
+ `docs/screenshot.png` is generated from real `fm` output against a local mock server, never
168
+ handwritten:
169
+
170
+ ```sh
171
+ python3 scripts/render_screenshot.py
172
+ ```
173
+
174
+ ## License
175
+
176
+ [MIT](LICENSE) © 2026 WeCarbon
@@ -0,0 +1,44 @@
1
+ formist_cli/__init__.py,sha256=SSy4e4MZ09Oe1oRWR1SeDN3oRTMsfcBQm6IqYGzBsoQ,44
2
+ formist_cli/__main__.py,sha256=v-b5Uwhit1vnG-HYpIGYLHx8XmMQAbaRJzB_0d-V4Ns,59
3
+ formist_cli/airtable.py,sha256=2bPmGS6Vs_ET7ZxgXMqIUG7h1QKTkpAvcdmh55tW_DE,9335
4
+ formist_cli/alerts.py,sha256=QhteprZikx_9mWJC5Rohpu7IAFUyEczsfyGuAEIeEzI,8261
5
+ formist_cli/api.py,sha256=r6dJXOwcGiv2pjjNZig_HfE_VYqR2Lg4ekfIzoiBC8I,39282
6
+ formist_cli/chat.py,sha256=q_V8G_kPRX7H5ugY_u4d2AS5LadH5C-p9dK0QggH74w,24930
7
+ formist_cli/chats.py,sha256=IVE1YGxivhKfQb5tvJHlT6-utSs8tFFV0FwP4n96680,20305
8
+ formist_cli/cli.py,sha256=ziPJet0hRZ13jCqsaPTsxTliWgULM95ubC29UdC8ZJI,54874
9
+ formist_cli/cli_support.py,sha256=5BDQiqadPtpY14W50cxnVzyNNZDqDiRW-E05YqbGV9A,9633
10
+ formist_cli/connectors.py,sha256=iI4Ti8fl6jXGwc8O0z2kt2sOcDWrTJgOScmNKRo-rUc,15313
11
+ formist_cli/context.py,sha256=JDMz05_Ka5SCcgmTxjNXHbxVYXex6rU2aM-LzC4ZJw8,6010
12
+ formist_cli/diff.py,sha256=Vk_WK8DXan9wKphV6hhMa_wVGzBoa8FX2-CO2BmeSTQ,40976
13
+ formist_cli/doctor.py,sha256=XG3bNB27S0sFoC3D7wpjD8CYffPKN4AJZGg_C2MHAlI,4174
14
+ formist_cli/export.py,sha256=4KoU7loF_1slLQNMx5AdhS_9vqpbPKe0Pghp0e9Fdyw,18011
15
+ formist_cli/files.py,sha256=wFsPjPHhT4HK86SyMGbKBK6Ph6nUNHcXrvX7jTfdCjM,27955
16
+ formist_cli/importer.py,sha256=7ZU5jlAmE3xaEi-wqxKTEbkFWuj0t566WsZglSWTmIk,17790
17
+ formist_cli/kb.py,sha256=ItOPq9Lf0Lszbh93GKLt_1PQ6Pa4DRp2AXbVd1n1oEo,7065
18
+ formist_cli/login.py,sha256=VeCVxIgtYapHuwK56mxJAf6PcmQcBaLHh28kkTtAEgc,25517
19
+ formist_cli/logs.py,sha256=9o5XtNNYMaE55xvwys7vSFh5A0605V0WBavezXH9az4,30161
20
+ formist_cli/meetings.py,sha256=9HA4qPkANHucHMEf7eZ8tzus3ykxBl28k13CACcLFj0,7969
21
+ formist_cli/messages.py,sha256=NjpFVjl6jl0Q5bVS-I7-yX3HaTahS2zruhW4CNLSsBM,18030
22
+ formist_cli/participants.py,sha256=-zlW7SVGxKpN-CnI0czYhlsB7dY_Uzj8hke4pK-kRow,16685
23
+ formist_cli/prefs.py,sha256=3ufFp_4ym1FfrUWO3p7vK2rvObDLt9W2DCgOnsEmClg,11334
24
+ formist_cli/privileges.py,sha256=bjboeWoRg5lR-l11_00sgcyDtD-TVozLs1qeOXDKmkw,16788
25
+ formist_cli/projects.py,sha256=IJlCqOds-KQ2gNuXYovmRFm2iEzjR5D60iERBJBU1_k,4299
26
+ formist_cli/resolve.py,sha256=VXxqFsOJgu7x61-lzp_Y7YdcoUM6zrtVITk_fi-NqBs,18179
27
+ formist_cli/settings.py,sha256=ZWJ56WmwLvwaXYnULQLaZoNYWxPc8aT2xNrLo0rmC4g,7565
28
+ formist_cli/skill_library.py,sha256=bp8W04BiJqyOq7Y3g_DI2lQvB8KF0PEQVg3htPJcK9o,10476
29
+ formist_cli/skills.py,sha256=_IrKlSYFB9rqFqngQAxn9PU9xX9Cpq68mlBKsbwUWeQ,12578
30
+ formist_cli/space_plan.py,sha256=n-JMdYassg6_ppg9kQcRbn152ZTuF-y8HwrHVONCuDc,17209
31
+ formist_cli/spaces.py,sha256=7W6mtOr9OrIC6UbrTy5qPDIKyMWlpKIUkI7ZqZ7Yeb4,29391
32
+ formist_cli/targets.py,sha256=o0wzKWgDWI6J4l5HgkP3c01f1oGOmMsTZlftrUoQXu0,4833
33
+ formist_cli/textnorm.py,sha256=E7GV41Jy3518sdHXVunvpuI4xCslhQmP06fu-xmuhis,1195
34
+ formist_cli/tokens.py,sha256=YFyRKG00Xuf1B63HBWZJM88LSF1Gg0mHVrwDt-OyImM,13131
35
+ formist_cli/update.py,sha256=sEOB5jINvwbYond_vnHoOG2FlhA9lYsY1SAinEXPmOk,17120
36
+ formist_cli/uploads.py,sha256=nlkEupiu4SUuVCMsYXj4qkPywBzsx_gaLHEWzD4Xcnk,36806
37
+ formist_cli/usage_tokens.py,sha256=Dsar8VHm7VBlOorZhlUQsuMopRG22KJQXeBl1dEGrFA,6437
38
+ formist_cli/users.py,sha256=LTA-2I2g6Sk2Xx0a1xabU_oHTG2v_7k2r7PvrSZF0GI,15493
39
+ formist_cli/whatsapp.py,sha256=yn5endLD5E-d-EL9jE-Eblw7JpttlQMPbjHHa4yYSRc,18733
40
+ formist_cli-0.1.0.dist-info/METADATA,sha256=n-m4Nt-j6dwdt1BOPHtQslwIk1uLBkNOR6kvQmtavXI,7642
41
+ formist_cli-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
42
+ formist_cli-0.1.0.dist-info/entry_points.txt,sha256=2GbYSSF5nElS4peAA8JPAV6VZtQUCgXbuq2mVyEUjnY,44
43
+ formist_cli-0.1.0.dist-info/licenses/LICENSE,sha256=Ysun_FMaE6Z-nDYzIxUUIuyR-WAakqwD2EqM-aSnIgY,1065
44
+ formist_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ fm = formist_cli.cli:main