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/chats.py ADDED
@@ -0,0 +1,517 @@
1
+ """Reading an agent run, and never overstating how much of it you read.
2
+
3
+ A background agent run persists as an ordinary chat, same tables and
4
+ transcript shape as an interactive conversation, just a different kind.
5
+ They are not uniformly space-wide: a scheduler- or webhook-initiated run is
6
+ workspace-scoped, while a run a person asked for is private to them. Both
7
+ are background agents, so "I can see it in the list" and "I can read its
8
+ transcript" are different questions with different answers, routinely, for
9
+ the same kind of row. A space-wide run is in turn readable only by project
10
+ admins and owners, not by every member, so a member session can see an
11
+ empty list in a space that plainly has agent runs, and nothing is wrong.
12
+ That is a third answer to "why did I see nothing", alongside "no runs
13
+ exist" and "they are someone else's private runs", and it is
14
+ indistinguishable from either without knowing your role.
15
+
16
+ This reads the member route rather than the admin one, because the admin
17
+ listing has no privacy predicate and returns metadata only, with no admin
18
+ route for chat messages at all; a listing from there could show a chat
19
+ whose transcript then 404s. The member route lists exactly what the
20
+ transcript route will serve. A 404 on another member's private chat is
21
+ deliberate (never a 403, so the API never reveals that the chat exists),
22
+ and `fm` does not route around it; what it adds is saying so, because a
23
+ 404 on an id you were just shown otherwise reads as a broken tool.
24
+
25
+ The other thing this module is built around: the message-listing endpoint
26
+ caps a page, and an agent run can exceed it in turns. A page that measured
27
+ itself must say so rather than let a capped page read as the whole
28
+ transcript. So completeness is treated as a claim, sourced from the
29
+ server's reported total and from nothing else. :attr:`Transcript.complete`
30
+ is False when that total is absent, because "I could not tell" and "it is
31
+ complete" are different facts, and the natural shorthand
32
+ (``len(messages) >= (total or 0)``) collapses them in the unsafe
33
+ direction, reporting complete for every truncated page it cannot measure.
34
+
35
+ Stdlib only: `fm` must add no runtime dependency.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import json
41
+ import sys
42
+ from collections.abc import Callable
43
+ from dataclasses import dataclass
44
+ from typing import Any
45
+
46
+ from formist_cli import context
47
+ from formist_cli.cli_support import default_fetch as _default_fetch
48
+ from formist_cli.targets import Target, require_space_id
49
+
50
+ #: What ``parse_pagination`` clamps a page to (``utils/list_query.py:60``). Asking
51
+ #: for more is silently reduced, so this is the real page size and paging is the
52
+ #: only way past it.
53
+ MESSAGE_PAGE = 200
54
+
55
+ #: Safety bound on the paging walk. A server that keeps claiming more rows than it
56
+ #: returns is a server bug; spinning forever in the client is a worse way to find
57
+ #: out than stopping and reporting the transcript as incomplete.
58
+ MAX_PAGES = 200
59
+
60
+ #: The command line speaks kebab-case, the API speaks the ``ChatKind`` enum.
61
+ _KIND_ALIASES = {
62
+ "background-agent": "BACKGROUND_AGENT",
63
+ "user-chat": "USER_CHAT",
64
+ }
65
+
66
+ VALID_KINDS = tuple(sorted(set(_KIND_ALIASES.values())))
67
+
68
+
69
+ class ChatsError(Exception):
70
+ """A refusal about chats, written for an operator.
71
+
72
+ Deliberately NOT an ``api.ApiError`` subclass: a caller distinguishing "the
73
+ server said something" from "fm decided something" must be able to, and a
74
+ privacy explanation is the second kind.
75
+ """
76
+
77
+
78
+ Fetcher = Callable[..., Any]
79
+
80
+
81
+ def canonical_kind(kind: str | None) -> str | None:
82
+ """Normalise a ``--kind`` value to the enum spelling. ``None`` stays ``None``.
83
+
84
+ Both spellings are accepted because both are things a person reasonably types;
85
+ an unrecognised one is refused rather than passed through, since the server
86
+ would answer 422 and the operator would be debugging the wrong layer.
87
+ """
88
+ if kind is None:
89
+ return None
90
+ raw = kind.strip()
91
+ mapped = _KIND_ALIASES.get(raw.lower())
92
+ if mapped:
93
+ return mapped
94
+ if raw.upper() in VALID_KINDS:
95
+ return raw.upper()
96
+ raise ChatsError(
97
+ f"unknown chat kind {kind!r}. Valid: "
98
+ f"{', '.join(sorted(_KIND_ALIASES))} (or the enum spellings "
99
+ f"{', '.join(VALID_KINDS)})."
100
+ )
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class Transcript:
105
+ """A chat's messages, and an honest account of whether that is all of them.
106
+
107
+ :attr:`total` is the server's count, or ``None`` when the envelope carried
108
+ none. It is never defaulted to a number: a default would make the completeness
109
+ test answerable in a case where nothing answered it.
110
+ """
111
+
112
+ messages: list[dict]
113
+ total: int | None
114
+
115
+ @property
116
+ def complete(self) -> bool:
117
+ """True only when the server stated a total and we hold all of it."""
118
+ if self.total is None:
119
+ return False
120
+ return len(self.messages) >= self.total
121
+
122
+ def render(self) -> str:
123
+ """The transcript, with its completeness stated rather than implied."""
124
+ lines = [
125
+ f"[{m.get('created_at', '')}] {str(m.get('role', '?')):<9} "
126
+ f"{m.get('content', '')}"
127
+ for m in self.messages
128
+ ]
129
+ lines.append("")
130
+ if self.total is None:
131
+ lines.append(
132
+ f"{len(self.messages)} turn(s) shown. The server reported no "
133
+ "total, so fm could not tell whether this is the whole "
134
+ "transcript.\n"
135
+ "-> `--all-messages` pages until the server stops adding rows."
136
+ )
137
+ elif not self.complete:
138
+ lines.append(
139
+ f"showing {len(self.messages)} of {self.total} turns: this "
140
+ f"transcript is INCOMPLETE. The list endpoint caps a page at "
141
+ f"{MESSAGE_PAGE}.\n"
142
+ "-> `--all-messages` to page through the rest."
143
+ )
144
+ else:
145
+ lines.append(f"{self.total} turn(s), the whole transcript.")
146
+ return "\n".join(lines)
147
+
148
+
149
+ def _envelope(payload: object, *, what: str) -> tuple[list[dict], int | None]:
150
+ """``(items, total)`` from a list envelope; ``total`` stays ``None`` if absent."""
151
+ if not isinstance(payload, dict):
152
+ raise ChatsError(
153
+ f"listing {what} returned {type(payload).__name__}, not a list envelope."
154
+ )
155
+ items = [i for i in (payload.get("items") or []) if isinstance(i, dict)]
156
+ total = payload.get("total")
157
+ return items, total if isinstance(total, int) else None
158
+
159
+
160
+ def list_chats(
161
+ target: Target,
162
+ space: str,
163
+ *,
164
+ token: str | None,
165
+ kind: str | None = None,
166
+ archived: bool = False,
167
+ limit: int = 50,
168
+ offset: int = 0,
169
+ fetch: Fetcher | None = None,
170
+ ) -> tuple[list[dict], int | None]:
171
+ """The chats this session may read in ``space``, newest first.
172
+
173
+ Filtered server-side. The ``?kind=`` filter is applied as a view filter
174
+ layered on the privacy predicate; it never widens what is visible.
175
+ Re-deriving that filter here would both measure the page and put a
176
+ second copy of a rule next to the one the server owns.
177
+ """
178
+ space = require_space_id(space)
179
+ fetch = fetch or _default_fetch
180
+
181
+ params = {"limit": str(limit), "offset": str(offset)}
182
+ canonical = canonical_kind(kind)
183
+ if canonical:
184
+ params["kind"] = canonical
185
+ if archived:
186
+ params["archived"] = "true"
187
+
188
+ payload = fetch(
189
+ target, f"/projects/{space}/chats", token=token, params=params
190
+ )
191
+ return _envelope(payload, what="chats")
192
+
193
+
194
+ def latest_chat(
195
+ target: Target,
196
+ space: str,
197
+ *,
198
+ token: str | None,
199
+ kind: str | None = None,
200
+ fetch: Fetcher | None = None,
201
+ ) -> dict:
202
+ """The most recently updated readable chat, or a refusal.
203
+
204
+ Exists to remove a transcription: the common question is "what did the
205
+ last run do", and answering it by copying a UUID off the line above is
206
+ the failure this is meant to end.
207
+
208
+ The ordering is the server's (``updated_at`` desc, then ``created_at``
209
+ desc, then ``id``), and this takes the first row rather than re-sorting
210
+ locally. A second ordering is a second answer, and when the two
211
+ disagree the operator is shown a different run than the one they asked
212
+ for, with nothing indicating it.
213
+ """
214
+ items, _total = list_chats(
215
+ target, space, token=token, kind=kind, limit=1, fetch=fetch
216
+ )
217
+ if not items:
218
+ described = f" of kind {kind!r}" if kind else ""
219
+ raise ChatsError(
220
+ f"no readable chat{described} in this space ({target.name}).\n"
221
+ "A background run triggered by another member is private to them and "
222
+ "is not listed here, see `fm chats --help`."
223
+ )
224
+ return items[0]
225
+
226
+
227
+ def get_chat(
228
+ target: Target,
229
+ space: str,
230
+ chat_id: str,
231
+ *,
232
+ token: str | None,
233
+ fetch: Fetcher | None = None,
234
+ ) -> dict:
235
+ """One chat's metadata, translating a 404 into the rule that caused it.
236
+
237
+ ``GET /chats/{id}`` returns an envelope, ``{"chat": {...}, "messages":
238
+ [...]}``, not a bare chat, unlike the list endpoint's items. This
239
+ refuses rather than falling back to ``.get("chat", payload)``, because
240
+ accepting both shapes would let a mismatch between the two render every
241
+ field as ``None`` instead of raising. The ``messages`` the envelope
242
+ carries are a capped recent tail with no ``total`` and are deliberately
243
+ ignored: a transcript comes from the paginated endpoint, which can say
244
+ how much of it you have.
245
+ """
246
+ space = require_space_id(space)
247
+ fetch = fetch or _default_fetch
248
+ try:
249
+ payload = fetch(
250
+ target, f"/projects/{space}/chats/{chat_id}", token=token
251
+ )
252
+ except Exception as exc: # narrowed immediately by _explain_404
253
+ _explain_404(exc, target, chat_id)
254
+ raise
255
+ if not isinstance(payload, dict):
256
+ raise ChatsError(f"chat {chat_id} returned {type(payload).__name__}.")
257
+ chat = payload.get("chat")
258
+ if not isinstance(chat, dict):
259
+ raise ChatsError(
260
+ f"chat {chat_id}: the response has no 'chat' object "
261
+ f"(keys: {sorted(payload)}).\n"
262
+ "GET /chats/{id} is expected to return {'chat': ..., 'messages': ...}. "
263
+ "Refusing rather than rendering every field as None."
264
+ )
265
+ return chat
266
+
267
+
268
+ def fetch_messages(
269
+ target: Target,
270
+ space: str,
271
+ chat_id: str,
272
+ *,
273
+ token: str | None,
274
+ all_pages: bool = False,
275
+ limit: int = MESSAGE_PAGE,
276
+ fetch: Fetcher | None = None,
277
+ ) -> Transcript:
278
+ """A chat's turns, and whether they are all of them.
279
+
280
+ One page by default. A transcript is the largest thing this tool prints
281
+ and the endpoint caps a page anyway, so paging is opt-in, but a partial
282
+ result is always marked partial, which is the part that is not optional.
283
+ """
284
+ space = require_space_id(space)
285
+ fetch = fetch or _default_fetch
286
+ path = f"/projects/{space}/chats/{chat_id}/messages"
287
+
288
+ messages: list[dict] = []
289
+ total: int | None = None
290
+ offset = 0
291
+
292
+ for _page in range(MAX_PAGES):
293
+ try:
294
+ payload = fetch(
295
+ target,
296
+ path,
297
+ token=token,
298
+ params={"limit": str(limit), "offset": str(offset)},
299
+ )
300
+ except Exception as exc:
301
+ _explain_404(exc, target, chat_id)
302
+ raise
303
+
304
+ items, total = _envelope(payload, what="messages")
305
+ messages.extend(items)
306
+
307
+ if not all_pages:
308
+ break
309
+ # Stop on a page that adds nothing, even if `total` still claims more.
310
+ # The alternative is trusting a count over the rows actually delivered,
311
+ # which spins forever against a server that is wrong about one of them.
312
+ if not items or total is None or len(messages) >= total:
313
+ break
314
+ offset += len(items)
315
+
316
+ return Transcript(messages=messages, total=total)
317
+
318
+
319
+ def _explain_404(exc: Exception, target: Target, chat_id: str) -> None:
320
+ """Re-raise a 404 as the access rule behind it. Anything else is left alone.
321
+
322
+ Only a 404 carries this meaning. Attaching the privacy explanation to
323
+ any other status would be a confident wrong answer, which costs more
324
+ than the bare status it replaced: the operator stops looking for the
325
+ real cause.
326
+ """
327
+ from formist_cli import api
328
+
329
+ if not isinstance(exc, api.ApiError) or getattr(exc, "status", None) != 404:
330
+ return
331
+ raise ChatsError(
332
+ f"404 from {target.name} for chat {chat_id}.\n"
333
+ "This is one of two things, and the server will not say which:\n"
334
+ " - no such chat in this space; or\n"
335
+ " - the chat is private to another member (owner_scope=USER, user_id "
336
+ "not you).\n"
337
+ "\n"
338
+ "The second is deliberate: the API answers 404 rather than 403 so it "
339
+ "never reveals that another member's private chat exists, and being a "
340
+ "platform-admin does not widen this.\n"
341
+ "\n"
342
+ "A background run is private when a person triggered it directly; "
343
+ "scheduler- and webhook-initiated runs are workspace-scoped instead. "
344
+ "Both are background-agent rows, so this 404 is an ordinary outcome, "
345
+ "not an edge case.\n"
346
+ "\n"
347
+ "A workspace-scoped background run is also 404 unless your session is "
348
+ "an admin or owner of the space. If `fm chats` shows you no runs at "
349
+ "all in a space that plainly has them, that is the likeliest reason.\n"
350
+ "-> `fm chats` lists what this session may actually read."
351
+ ) from None
352
+
353
+
354
+ # ===========================================================================
355
+ # The CLI surface. Per-module `add_parser` is the convention: it is the shape
356
+ # that survives a three-way merge, since adding a command then costs the
357
+ # top-level parser one line instead of a block two branches both land in.
358
+ # ===========================================================================
359
+ def add_parser(sub) -> None:
360
+ import argparse
361
+
362
+ from formist_cli.cli import _add_env, _add_space
363
+ p = sub.add_parser(
364
+ "chats",
365
+ help="list a space's chats / agent runs, or read one's transcript",
366
+ description=(
367
+ "Every agent run persists as a chat, so this reads both the "
368
+ "background agents list and an interactive conversation.\n\n"
369
+ "Omit the id to list; give one to show it. --messages adds the "
370
+ "transcript.\n\n"
371
+ "Scope: this reads the member route, so it shows exactly what your "
372
+ "session may read: your own chats plus every workspace-scoped one. A "
373
+ "background run someone else triggered is private to them and "
374
+ "answers 404, deliberately, so the API never reveals it exists. "
375
+ "Platform-admin does not bypass that; there is no admin route for "
376
+ "chat messages at all.\n\n"
377
+ "A transcript can be long and the list endpoint caps a page at 200. "
378
+ "A partial transcript is always marked partial; --all-messages "
379
+ "pages through the rest."
380
+ ),
381
+ formatter_class=argparse.RawDescriptionHelpFormatter,
382
+ )
383
+ _add_env(p)
384
+ _add_space(p)
385
+ p.add_argument(
386
+ "chat_id", nargs="?", help="chat UUID (from `fm chats`); omit to list"
387
+ )
388
+ p.add_argument("--kind", help="background-agent | user-chat (default: both)")
389
+ p.add_argument("--archived", action="store_true", help="list archived chats")
390
+ p.add_argument(
391
+ "--latest",
392
+ action="store_true",
393
+ help="address the newest matching chat instead of naming an id",
394
+ )
395
+ p.add_argument(
396
+ "--messages", action="store_true", help="also print the transcript (one page)"
397
+ )
398
+ p.add_argument(
399
+ "--all-messages",
400
+ dest="all_messages",
401
+ action="store_true",
402
+ help="page the WHOLE transcript, however long",
403
+ )
404
+ p.add_argument("--limit", type=int, default=50)
405
+ p.add_argument("--json", action="store_true", help="machine-readable output")
406
+
407
+
408
+ def cmd_chats(args) -> int:
409
+ """List the space's chats, or show one, and never overstate a transcript.
410
+
411
+ Listing and showing are one command because they are one question asked at two
412
+ zoom levels, and because the id that identifies a chat comes from the listing
413
+ directly above it. `--latest` removes even that transcription for the common
414
+ case ("what did the last run do"), and prints the id it resolved to so the
415
+ answer is checkable.
416
+
417
+ There is no resolve-by-title. Chat titles are auto-generated and
418
+ duplicate heavily, since every run of one connector sync shares a
419
+ title, so an exactly-one-or-refuse rule would correctly refuse almost
420
+ every time, which is a command that looks broken rather than one that
421
+ is careful.
422
+ """
423
+ # Lazy: `cli` imports this module, so a module-level import here would
424
+ # be a cycle.
425
+
426
+ eff = context.resolve(args, need_space=True, need_token=True)
427
+ token = eff.token
428
+ chat_id = args.chat_id
429
+
430
+ if args.latest:
431
+ if chat_id:
432
+ raise ChatsError(
433
+ "give a chat id or --latest, not both; they are two ways of "
434
+ "naming the same argument, and if they disagree there is no "
435
+ "sensible winner."
436
+ )
437
+ chat = latest_chat(
438
+ eff.target, eff.space, token=token, kind=args.kind
439
+ )
440
+ chat_id = str(chat.get("id"))
441
+ # To stderr, and printed before anything else: --latest resolved an
442
+ # argument the operator did not type, so the value it chose is part of
443
+ # the answer, not a detail.
444
+ print(f" --latest resolved to chat {chat_id}", file=sys.stderr)
445
+
446
+ if not chat_id:
447
+ return _list_chats(args, eff, token)
448
+
449
+ chat = get_chat(eff.target, eff.space, chat_id, token=token)
450
+ transcript = None
451
+ if args.messages or args.all_messages:
452
+ transcript = fetch_messages(
453
+ eff.target,
454
+ eff.space,
455
+ chat_id,
456
+ token=token,
457
+ all_pages=args.all_messages,
458
+ )
459
+
460
+ if args.json:
461
+ out = dict(chat)
462
+ if transcript is not None:
463
+ out["messages"] = transcript.messages
464
+ out["messages_total"] = transcript.total
465
+ # The completeness verdict travels WITH the data. A JSON consumer
466
+ # cannot see the warning line render() prints, and a truncated list
467
+ # with no flag beside it is the failure this command is built around.
468
+ out["messages_complete"] = transcript.complete
469
+ print(json.dumps(out, indent=2, ensure_ascii=False, default=str))
470
+ return 0
471
+
472
+ print(f"{chat.get('id')} {chat.get('kind', '?')}")
473
+ print(f" title {chat.get('title')}")
474
+ print(f" owner_scope {chat.get('owner_scope', '?')}"
475
+ f" user_id={chat.get('user_id')}")
476
+ if chat.get("kind") == "BACKGROUND_AGENT":
477
+ print(f" agent_status {chat.get('agent_status', '?')}")
478
+ print(f" triggered_by {chat.get('triggered_by_name') or chat.get('trigger_kind') or '?'}")
479
+ if chat.get("last_error"):
480
+ print(f" last_error {chat.get('last_error')}")
481
+ print(f" updated_at {chat.get('updated_at', '')}")
482
+
483
+ if transcript is not None:
484
+ print()
485
+ print(transcript.render())
486
+ return 0
487
+
488
+
489
+ def _list_chats(args, eff, token) -> int:
490
+ items, total = list_chats(
491
+ eff.target,
492
+ eff.space,
493
+ token=token,
494
+ kind=args.kind,
495
+ archived=args.archived,
496
+ limit=args.limit,
497
+ )
498
+ if args.json:
499
+ print(json.dumps(
500
+ {"items": items, "total": total}, indent=2, ensure_ascii=False, default=str
501
+ ))
502
+ return 0
503
+
504
+ for item in items:
505
+ status = item.get("agent_status") or ""
506
+ print(f"{item.get('id')} {str(item.get('kind', '?')):<16} {status:<10}"
507
+ f" {item.get('updated_at', ''):<28} {item.get('title') or ''}")
508
+ if not items:
509
+ print("(no readable chats in this space)")
510
+ # Say what was NOT shown. The same rule the transcript keeps: a page that
511
+ # measured itself must not read as the table.
512
+ if isinstance(total, int) and total > len(items):
513
+ print(
514
+ f"\nshowing {len(items)} of {total}, raise --limit to see more.",
515
+ file=sys.stderr,
516
+ )
517
+ return 0