driverkit 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.
driverkit/render.py ADDED
@@ -0,0 +1,486 @@
1
+ """
2
+ Rendering a Snapshot and a Result for a model to read.
3
+
4
+ Why this file exists at all, rather than ``json.dumps`` at the MCP boundary:
5
+ a tool result is prompt. The snapshot that comes back from every call is the
6
+ uncached half, so its bytes are paid for on every turn of the conversation,
7
+ and JSON spends a large share of them on punctuation and on repeating each
8
+ column name once per row. A two-column, ten-row table costs about 240 bytes of
9
+ braces and quotes as JSON and about none as text. The win is not elegance, it
10
+ is that the thing an agent re-reads most often is the thing we made smallest.
11
+
12
+ The second rule here is that the post-call snapshot is never dropped. The TS
13
+ ``Result`` carries it so that acting and observing are one round trip; a
14
+ renderer that returned "ok" and nothing else would hand that saving straight
15
+ back, because the model's next move would be to read the screen it was just
16
+ given.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from .types import Result, Snapshot
22
+
23
+ __all__ = ["render_snapshot", "render_result", "render_duration", "SLOW_MS"]
24
+
25
+ #: What an unanswered call means, per PROTOCOL.md: the call was accepted and no
26
+ #: answer came back, so the tab may well have run the verb. Only
27
+ #: ``no-such-tab`` proves otherwise. Each slug gets its own sentence, because
28
+ #: "it went quiet" and "its connection closed" lead to different next moves —
29
+ #: wait and re-read, versus check whether the tab is still there at all.
30
+ _UNKNOWN_WHY = {
31
+ "timeout": "The tab accepted this call and went quiet past the deadline.",
32
+ "tab-went-away": (
33
+ "The tab accepted this call and its connection then closed, so the answer died "
34
+ "with the stream."
35
+ ),
36
+ }
37
+ _UNKNOWN_OUTCOME = "The outcome is UNKNOWN: it may well have run."
38
+ #: Spelled out for a `commit` verb because that is the case where guessing
39
+ #: wrong is expensive. The natural reflex — treat a non-answer as a failed step
40
+ #: and retry it — is the one move that turns one bulk accept into two.
41
+ _UNKNOWN_COMMIT = (
42
+ "DO NOT retry this. It changes data, and it may already have taken effect. "
43
+ "Read the screen first and decide from what you see there."
44
+ )
45
+ _UNKNOWN_SAFE = "Reading the screen again is cheap and safe, and settles it."
46
+ _NEVER_LANDED = (
47
+ "The call was never forwarded, because there was nowhere to forward it: nothing ran "
48
+ "and nothing changed."
49
+ )
50
+
51
+
52
+ #: The shortest honest wait worth a line in a prompt.
53
+ #:
54
+ #: One second, and the number is the whole token argument. A duration on every
55
+ #: call is a line in every turn forever, for a capability most runs never use,
56
+ #: and the TS half's ``pruneScreens`` cut a ten-step run from 5,775 to 1,397
57
+ #: characters by refusing to pay exactly that kind of per-step rent. So the
58
+ #: default is that a call which took no time says nothing: a snappy app renders
59
+ #: not one byte more than it did before this existed, and the bytes get spent
60
+ #: only on the calls where elapsed time is a fact about the app rather than
61
+ #: noise.
62
+ #:
63
+ #: A second is also roughly where a wait stops being invisible to the person
64
+ #: watching. Below it, the model learning the number changes no decision it
65
+ #: could make; above it, "this verb is slow" is a real property of the app that
66
+ #: explains why the next step should not be another one of these.
67
+ SLOW_MS = 1000
68
+
69
+
70
+ def render_duration(ms: float, floor_ms: float = SLOW_MS) -> str:
71
+ """How long a call took, as one line for the outcome half of a tool turn.
72
+
73
+ ::
74
+
75
+ ok — 3,412 contacts accepted
76
+ took: ~2s
77
+
78
+ On screen now:
79
+ screen: contacts
80
+
81
+ **Why this is a function and not a field on ``Result``.** A ``Result`` is
82
+ what the APP returned; a duration is a fact about the call that wrapped it,
83
+ which the app never measured and cannot be asked to. Putting it on the wire
84
+ would invite an app to fill it in, and then the number a model reads would
85
+ be an app's claim about its own speed rather than an observation. The
86
+ caller measures, the caller renders, and this is the one place either half
87
+ of the library says it in words.
88
+
89
+ **Why it is bucketed rather than exact.** Every other byte of a rendered
90
+ turn is a function of app state, so two identical runs produce identical
91
+ transcripts — which is what eval caching, snapshot tests and anything that
92
+ diffs transcripts are built on. A wall-clock millisecond count breaks that
93
+ for every reader at once. Rounding to a coarse bucket gives it back for the
94
+ ordinary case: a verb that takes 2.1s one run and 2.3s the next renders
95
+ ``~2s`` both times, so the transcript is stable wherever the app's own
96
+ behaviour is. It does not make the output a pure function of state — a
97
+ bucket boundary is still a boundary, and a call that straddles one renders
98
+ two ways — and that is why the TS half's ``DriveOptions.clock`` is
99
+ injectable: a suite or an eval that needs a byte-exact transcript pins the
100
+ clock and gets one. Buckets are for production, the injected clock is for
101
+ determinism, and neither is asked to do the other's job.
102
+
103
+ ``~`` is on the number on purpose. A model shown ``took: 2.13s`` will
104
+ compare two of them to three figures and report a difference that is
105
+ scheduler noise; ``~2s`` cannot be over-read, and reads naturally in an
106
+ answer a person gets back.
107
+
108
+ **What this must never include.** The time a person spent deciding. ``ms``
109
+ in an audit record is approval-inclusive by design — a reader of the record
110
+ wants that gap back — but telling a MODEL that a call "took 40 seconds"
111
+ when 38 of them were somebody reading a confirmation dialog is a false
112
+ claim about the app's speed, and a model that believes it will go looking
113
+ for a faster route around a verb that is not slow. Over the relay there is
114
+ a second thing to keep out: this is the time the CALL took, and a deadline
115
+ that fired is not a duration — a ``timeout`` means the outcome is unknown,
116
+ so the only honest figure for it is none at all.
117
+
118
+ **NOT YET CALLED BY THIS HALF'S MCP SERVER, AND THAT IS DELIBERATE RATHER
119
+ THAN UNFINISHED.** The function is here because the two renderers are kept
120
+ string-for-string and ``test/cross-impl.test.ts`` crosses them — a half that
121
+ did not have it would drift the moment anybody touched the other. What it is
122
+ not yet wired to is ``mcp_core``, because the only duration the MCP path can
123
+ measure today is the whole relay round trip: the network hop out, the tab's
124
+ own work, any approval the page asked a person for, and the hop back. Three
125
+ of those four are not the app's speed, and there is no ``waited`` channel
126
+ over the wire to subtract the human one with — so wiring it would render
127
+ exactly the lie the TS half's ``DriveOptions.waited`` exists to prevent. The
128
+ honest fix is for the relay to carry the tab's own elapsed time in the
129
+ ``result`` frame, which is a PROTOCOL.md change and not a renderer change.
130
+
131
+ ``floor_ms`` is the "not interesting" threshold, and ``0`` renders every
132
+ call. Returns the EMPTY STRING rather than a sentinel when there is nothing
133
+ worth saying, so a caller appends it unconditionally and the fast path adds
134
+ no line at all.
135
+
136
+ Verbatim with ``render.ts``. Both halves say the same words about the same
137
+ number, which is the rule for everything in this file: a prompt that worked
138
+ through MCP and misbehaves in the widget is a bug with no stack trace.
139
+ """
140
+ # A negative or non-finite figure is a broken clock, not a fast call, and
141
+ # the honest rendering of a measurement that did not happen is silence. A
142
+ # monotonic clock cannot go backwards; an injected one can, and a test
143
+ # clock that does should not put `took: ~-1s` in a prompt.
144
+ if ms != ms or ms in (float("inf"), float("-inf")):
145
+ return ""
146
+ whole = int(ms // 1)
147
+ if whole < 0 or whole < floor_ms:
148
+ return ""
149
+ return f"took: {_bucket(whole)}"
150
+
151
+
152
+ def _bucket(ms: int) -> str:
153
+ """Whole milliseconds as a coarse, stable label.
154
+
155
+ Integer arithmetic only, and no locale and no float formatting anywhere:
156
+ ``toFixed`` and ``%.1f`` are the two things most likely to disagree between
157
+ the two implementations, and this function's entire job is to agree. Each
158
+ band floors rather than rounds, so the label never claims more time than
159
+ elapsed.
160
+
161
+ ============== ============== =========================================
162
+ under 100ms ``under 0.1s`` said in words, because ``~0.0s`` reads as
163
+ zero and ``~0.1s`` would overstate it
164
+ under 1s ``~0.4s`` tenths: the resolution a ``floor_ms=0``
165
+ caller asked for, and the one at which two
166
+ fetches are actually worth comparing
167
+ under 10s ``~2s`` whole seconds
168
+ under 1m ``~15s`` five-second steps. Tens were the first try
169
+ and understated badly at the top of the
170
+ band — 19 seconds rendering ``~10s`` is a
171
+ 47% lie, and "it took ten seconds" is the
172
+ sentence a model will repeat to somebody.
173
+ Five is still far coarser than any
174
+ scheduler noise, so the label is stable
175
+ where the app is
176
+ 1m and over ``~3m`` whole minutes
177
+ ============== ============== =========================================
178
+ """
179
+ if ms < 100:
180
+ return "under 0.1s"
181
+ if ms < 1000:
182
+ return f"~0.{ms // 100}s"
183
+ if ms < 10_000:
184
+ return f"~{ms // 1000}s"
185
+ if ms < 60_000:
186
+ return f"~{(ms // 5_000) * 5}s"
187
+ return f"~{ms // 60_000}m"
188
+
189
+
190
+ def render_snapshot(snapshot: Snapshot) -> str:
191
+ """The screen as a short text block.
192
+
193
+ ::
194
+
195
+ screen: contacts
196
+ where: contacts, filtered to Acme (rev 8)
197
+ selected: c-8821
198
+ rows 1-2 of 5
199
+ id company status
200
+ c-8820 Acme new
201
+ c-8821 Acme accepted
202
+
203
+ Field order is fixed so the same screen renders identically every time: a
204
+ model comparing two reads should see a diff only where the screen changed.
205
+
206
+ ``screen`` goes FIRST, above the prose, and is omitted by an app that does
207
+ not declare one. It is the one line on this block a model can compare for
208
+ equality: ``where`` carries the filter, the sort and a drill-down's record
209
+ description, so it moves for reasons that are not navigation, and two reads
210
+ either side of a ``go`` differ in a dozen ways. One short word that changes
211
+ if and only if the screen changed is worth a line of the uncached half.
212
+ Verbatim from the TS half, which this file is kept string-for-string with.
213
+ """
214
+ # ``getattr`` for the same reason ``selected_count`` below uses it: the
215
+ # field arrives from the wire, and an older ``Snapshot`` dataclass without
216
+ # it must keep rendering rather than raise.
217
+ screen = getattr(snapshot, "screen", None)
218
+ lines = [f"where: {snapshot.where} (rev {snapshot.rev})"]
219
+ if screen:
220
+ lines.insert(0, f"screen: {screen}")
221
+
222
+ # ``is None`` and not ``or ()``: an absent ``selected`` and an empty one
223
+ # are different claims, and the branch below has to tell them apart.
224
+ selected = snapshot.selected if snapshot.selected is not None else None
225
+ on_screen = selected or ()
226
+ if on_screen:
227
+ # Before the rows, because "this one" is usually the subject of the
228
+ # next verb and the model should not have to scan the table to find it.
229
+ lines.append("selected: " + ", ".join(on_screen))
230
+
231
+ # Read off the snapshot defensively because a relay may be newer or older
232
+ # than this client: the field arrives from the wire, and an older
233
+ # ``Snapshot`` dataclass without it must keep rendering rather than raise.
234
+ selected_count = getattr(snapshot, "selected_count", None)
235
+ if selected_count is not None and selected_count != len(on_screen):
236
+ # The ids and the size of a selection are different facts, and the size
237
+ # is the one a commit decision turns on. ``selected`` carries only what
238
+ # is on screen — ten thousand ids in the uncached half is the token
239
+ # budget gone — so a model holding three ids and about to commit has to
240
+ # be told in words that the list is a window onto the selection and not
241
+ # the selection. Verbatim from the TS half.
242
+ lines.append(
243
+ f"selected {selected_count:,} rows in all; "
244
+ + (
245
+ f"the {len(on_screen)} ids above are only the ones on screen"
246
+ if on_screen
247
+ else "none of them are on screen"
248
+ )
249
+ )
250
+ elif not on_screen:
251
+ # An absent value reads as a claim — the same defect already fixed on
252
+ # ``page`` and on ``rows``, in the one remaining place it was still
253
+ # live.
254
+ #
255
+ # This block used to be nothing at all: the selection was described
256
+ # only when it was non-empty, so a screen with nothing selected said
257
+ # NOTHING about selections, and silence cannot be told from "this
258
+ # screen does not report selections". The library's own rule is that a
259
+ # commit is never made on a count nobody read, so a model asked to
260
+ # accept the selection here obeyed the rule against a screen that told
261
+ # it nothing — and went navigating other screens hunting for the
262
+ # number. Observed in an eval run, not imagined.
263
+ #
264
+ # selectedCount: 0 the app counts, and the answer is none
265
+ # count absent, selected [] the app says which ids on screen are
266
+ # selected and none are, but does not
267
+ # count, so a row off screen may still
268
+ # be selected
269
+ # both absent the app does not report selections at
270
+ # all
271
+ #
272
+ # Three sentences because they are three different facts, and the whole
273
+ # bug was one of them being rendered as another. The middle one is the
274
+ # weakest claim and the one nobody thinks about; conflating it with the
275
+ # first would say "nothing is selected" on the strength of a window.
276
+ # Verbatim from the TS half.
277
+ if selected_count == 0:
278
+ lines.append("selected: none (0 rows; this screen counts the selection)")
279
+ elif selected is None:
280
+ lines.append("(this screen reports no selection)")
281
+ else:
282
+ lines.append(
283
+ "selected: none on screen; this screen does not count the selection, so rows "
284
+ "off screen may be selected"
285
+ )
286
+
287
+ if snapshot.note:
288
+ lines.append(f"note: {snapshot.note}")
289
+
290
+ rows = snapshot.rows
291
+ if rows is None:
292
+ # Absent rows and zero rows are different claims. An app with no table
293
+ # on screen reports no rows; a filter that matched nothing reports an
294
+ # empty list, and an agent told "no rows" in the first case would
295
+ # conclude the records do not exist.
296
+ lines.append("(this screen reports no rows)")
297
+ return "\n".join(lines)
298
+
299
+ page = snapshot.page
300
+ if page is not None:
301
+ first = page.index * page.size + 1 if rows else 0
302
+ seen = page.index * page.size + len(rows)
303
+ # ``total`` is optional in the TS `Snapshot`, and total-absent is the
304
+ # NORMAL case for anything reading a rendered DOM: an adapter cannot
305
+ # tell a virtualised grid from a short list, so it is the only honest
306
+ # thing it can say. ``getattr`` because this dataclass may still
307
+ # require it while a relay is already sending screens without it.
308
+ total = getattr(page, "total", None)
309
+
310
+ if total is None:
311
+ # Rendered as a claim rather than as a gap. "of at least 20" is
312
+ # true, which "of None" and "of 20" are not — the first is noise a
313
+ # model ignores or hallucinates around, the second tells it the
314
+ # table ends where the window ends and invites it to report that a
315
+ # record does not exist. The count a nobody-knows total would need
316
+ # is simply not said. Verbatim from the TS half.
317
+ lines.append(
318
+ f"rows {first}-{first + len(rows) - 1} of at least {seen} (total unknown)"
319
+ if rows
320
+ else f"rows 0 of at least {seen} (total unknown)"
321
+ )
322
+ lines.append(
323
+ "the total is not known, so more rows may exist off screen; use the app's own "
324
+ "paging verb to look further, and do not report that something is absent on "
325
+ "the strength of this window"
326
+ )
327
+ else:
328
+ lines.append(
329
+ f"rows {first}-{first + len(rows) - 1} of {total}" if rows else f"rows 0 of {total}"
330
+ )
331
+ if seen < total:
332
+ # Said in words, because `of 5` alone has repeatedly been read
333
+ # by models as "I have all five".
334
+ lines.append(
335
+ "more rows exist off screen; use the app's own paging verb to reach them"
336
+ )
337
+ else:
338
+ # No `page` is a claim that this is everything. Worth stating, since
339
+ # the alternative reading — "the relay forgot to tell me" — leads an
340
+ # agent to hunt for a paging verb that does not exist.
341
+ lines.append(f"rows {len(rows)} (all of them)")
342
+
343
+ if not rows:
344
+ lines.append("(no rows on screen)")
345
+ return "\n".join(lines)
346
+
347
+ lines.extend(_table(snapshot))
348
+ return "\n".join(lines)
349
+
350
+
351
+ def render_result(result: Result, kind: str | None = None) -> str:
352
+ """A Result as text: the outcome, then the screen it left behind.
353
+
354
+ ``kind`` is the verb's ``read``/``describe``/``commit`` and changes only
355
+ one thing: what a client is told to do when the outcome is unknown. It is
356
+ passed in rather than read off the result because the kind lives in the
357
+ cached half and the result does not carry it.
358
+
359
+ A refusal renders as an ordinary outcome and not as an error banner. The
360
+ refusal slug is the one the manifest already declared under ``refuses``, so
361
+ an agent that read the tool description recognises the word and generally
362
+ knows the fix; wrapping it in alarm language mostly teaches a model to
363
+ retry the same call.
364
+
365
+ A relay refusal is the exception, and is rendered loudly, because it is not
366
+ the app saying no — it is the call not landing, or nobody knowing.
367
+ """
368
+ relay = result.relay_refusal
369
+ if relay is not None:
370
+ return _render_relay_refusal(result, relay, kind)
371
+
372
+ if result.ok:
373
+ head = "ok" + (f" — {result.note}" if result.note else "")
374
+ if result.count is not None:
375
+ # On its own line, high up, with thousands separators. This is the
376
+ # number a person would have to see before pressing a bulk button,
377
+ # and the reason `describe` and `commit` are separate verbs; a
378
+ # renderer that folds it into prose further down has given back the
379
+ # safety the split was bought with. 1000 and 10000 also look alike
380
+ # at a glance, which is the mistake that costs the most.
381
+ head += (
382
+ f"\ncount: {result.count:,} matched"
383
+ "\nThis is what a commit verb acting on the current selection would affect. "
384
+ "Check it is the number you expect before committing."
385
+ )
386
+ if result.plan is not None:
387
+ # Rendered directly under the count, because it is the count's
388
+ # receipt and means nothing apart from it. Without this line the
389
+ # token exists in the Result and the model never sees it, so every
390
+ # commit that requires one is refused -- the field would be plumbing
391
+ # that reaches everywhere except the one reader that has to use it.
392
+ #
393
+ # Verbatim with the TS half. The two renderers say the same words to
394
+ # the same model, and a difference between them is a difference in
395
+ # what an agent is told depending on how it connected.
396
+ head += (
397
+ f"\nplan: {result.plan}"
398
+ "\nPass this `plan` back to the commit verb that acts on this selection. It is "
399
+ "the receipt for the count above: if anything moves the selection first the "
400
+ "commit is refused as `stale-plan` rather than acting on rows nobody counted. "
401
+ "One commit per plan. Reading and navigating do not move the selection and do "
402
+ "not spend this plan, so go and check whatever you need to before you commit."
403
+ )
404
+ else:
405
+ head = f"refused: {result.refused}"
406
+ if result.hint:
407
+ head += f"\nhint: {result.hint}"
408
+
409
+ if result.snapshot is None:
410
+ # Shape says app refusal, but there is no screen. Not a case a
411
+ # conforming relay produces; saying so beats rendering a blank screen,
412
+ # which would read as "the app is empty".
413
+ return head + "\n(no snapshot was returned)"
414
+
415
+ return head + "\n\n" + render_snapshot(result.snapshot)
416
+
417
+
418
+ def _render_relay_refusal(result: Result, relay: str, kind: str | None) -> str:
419
+ """A refusal from the relay about a call that never reached a tab.
420
+
421
+ Kept visibly distinct from an app's own refusal. An agent that reads
422
+ ``no-such-tab`` as a business rule will rephrase its arguments and try
423
+ again forever, when what it needs to do is list the tabs; and an agent that
424
+ reads ``timeout`` as a failure may repeat a commit that already happened.
425
+ """
426
+ lines = [f"the call did not complete: {relay}"]
427
+ if result.hint:
428
+ lines.append(f"hint: {result.hint}")
429
+
430
+ if result.outcome_unknown:
431
+ lines.append(_UNKNOWN_WHY.get(relay, "") + " " + _UNKNOWN_OUTCOME)
432
+ lines.append(_UNKNOWN_COMMIT if kind == "commit" else _UNKNOWN_SAFE)
433
+ elif relay == "no-such-tab":
434
+ lines.append(_NEVER_LANDED + " List the tabs: the id may be wrong, or that tab has closed.")
435
+ else:
436
+ lines.append(_NEVER_LANDED)
437
+
438
+ # Never an invented empty screen. Its absence is the signal, and a blank
439
+ # table would tell an agent the app has no rows.
440
+ #
441
+ # Worded by case: "nothing ran" is only true of `no-such-tab`, and putting
442
+ # it under an unknown outcome would contradict the line above it — the one
443
+ # saying the verb may well have run. A model reading both believes the
444
+ # reassuring one.
445
+ lines.append(
446
+ "(no snapshot: nobody read the screen, so this says nothing about what the app now holds)"
447
+ if result.outcome_unknown
448
+ else "(no snapshot: nothing ran and nobody looked)"
449
+ )
450
+ return "\n".join(lines)
451
+
452
+
453
+ def _table(snapshot: Snapshot) -> list[str]:
454
+ """Rows as a padded text table.
455
+
456
+ Columns are the union of every row's keys, not the first row's: rows are
457
+ not required to agree, and silently dropping a column that only some rows
458
+ carry would hide exactly the outlier a person is usually asking about.
459
+ """
460
+ columns = snapshot.columns()
461
+ rows = snapshot.rows or ()
462
+ cells = [[_cell(row.get(c)) for c in columns] for row in rows]
463
+
464
+ widths = [len(c) for c in columns]
465
+ for row_cells in cells:
466
+ for i, text in enumerate(row_cells):
467
+ widths[i] = max(widths[i], len(text))
468
+
469
+ def line(values: list[str]) -> str:
470
+ # The last column is not padded: trailing spaces are tokens that carry
471
+ # nothing.
472
+ return " ".join(
473
+ v.ljust(widths[i]) if i < len(values) - 1 else v for i, v in enumerate(values)
474
+ ).rstrip()
475
+
476
+ return [line(columns), *(line(c) for c in cells)]
477
+
478
+
479
+ def _cell(value: object) -> str:
480
+ if value is None:
481
+ return "-"
482
+ if value is True:
483
+ return "true"
484
+ if value is False:
485
+ return "false"
486
+ return str(value)