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/mcp_core.py ADDED
@@ -0,0 +1,988 @@
1
+ """
2
+ driverkit — the manifest→tools translation, shared by both MCP servers.
3
+
4
+ Two MCP servers ship in this package and they must expose the same tools. One
5
+ is the hand-rolled JSON-RPC-over-stdio server in :mod:`driverkit.mcp_server`,
6
+ which has no dependencies and is the path that runs today; the other is
7
+ :mod:`driverkit.fastmcp_server`, which needs ``fastmcp`` and exists because
8
+ FastMCP owns the authentication story an agent-facing server should not
9
+ hand-roll. A tool list written twice is two tool lists, and the second one is
10
+ wrong the first time somebody adds a verb kind — so it is written here once and
11
+ both servers are transports over :class:`TabTools`.
12
+
13
+ What lives here is everything that is not transport: the schema translation,
14
+ the two fixed reads, the instructions a client is given, and the dispatch from
15
+ a tool name to the text a model sees. What lives in each server is JSON-RPC
16
+ framing, or FastMCP's decorators, and nothing else.
17
+
18
+ THE POINT OF ALL OF IT, worth repeating where the generator is: **the tool list
19
+ is generated from the tab's manifest.** Nothing here knows the name of a single
20
+ verb. Each verb becomes one MCP tool, its ``args`` become the tool's
21
+ ``inputSchema``, and its ``refuses`` go into the description so a model can
22
+ decline a call that was always going to be declined.
23
+
24
+ The alternative — hand-writing an MCP tool per app feature — is the thing this
25
+ replaces. It means every app ships a second, drifting copy of its own
26
+ capability list, and the copy is wrong the first time somebody adds an
27
+ argument.
28
+
29
+ Two tools are not verbs and are added by hand: ``read_screen`` and
30
+ ``list_tabs``. They are not app features, they are the protocol's own two
31
+ reads, and no app should have to declare them. (Verb names are kebab-case by
32
+ the core's contract and these are snake_case, so they cannot collide; the
33
+ generator checks anyway rather than silently shadowing a verb.)
34
+
35
+ Stdlib only, like everything that must run.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ from dataclasses import dataclass
41
+ from typing import Any, Mapping, Sequence
42
+
43
+ from .client import Driverkit
44
+ from .render import SLOW_MS, render_duration, render_result, render_snapshot
45
+ from .types import ArgSpec, FlowSpec, Manifest, Result, ScreenSpec, Tab, VerbSpec
46
+
47
+ __all__ = [
48
+ "READ_SCREEN",
49
+ "LIST_TABS",
50
+ "ToolOutcome",
51
+ "TabTools",
52
+ "arg_schema",
53
+ "verb_tool",
54
+ "tools_for",
55
+ "render_tabs",
56
+ "pick_tab",
57
+ "FOCUS_WORDS",
58
+ "instructions_for",
59
+ "TIMING",
60
+ ]
61
+
62
+ READ_SCREEN = "read_screen"
63
+ LIST_TABS = "list_tabs"
64
+
65
+ #: ``ArgSpec.type`` is already a JSON Schema type name for all three cases, but
66
+ #: the mapping is written out rather than passed through: the core's three
67
+ #: accepted types are a closed set, and an unknown one should be loud here
68
+ #: instead of producing a schema no client will validate.
69
+ _JSON_TYPES = {"string": "string", "number": "number", "boolean": "boolean"}
70
+
71
+ _RESULT_NOTE = (
72
+ "Returns the screen as it is AFTER this runs, so you do not need to read it again."
73
+ )
74
+ _REFUSAL_NOTE = (
75
+ "A refusal is a normal answer, not an error: read the reason and change what you do, "
76
+ "rather than repeating the same call."
77
+ )
78
+
79
+ #: ``kind`` folded into the description, because it is the difference between a
80
+ #: call that is free to try and one that is irreversible, and nothing else in
81
+ #: the tool definition can express that. Asked to "select the top 1000 and bulk
82
+ #: accept", a model that cannot tell `select` from `accept` finds out by doing
83
+ #: it, and the finding out costs a thousand accepted rows.
84
+ #:
85
+ #: ``read`` says "changes no data and reports no count" and no longer says
86
+ #: "changes nothing", because `go`, `open-contact` and `back` are reads and they
87
+ #: move the person's screen out from under them. The two things the sentence
88
+ #: must get right are the ones that decide whether the next call is safe; "the
89
+ #: person will see it" is said as well, because they will. Verbatim from the TS
90
+ #: half.
91
+ _KIND_NOTE = {
92
+ "read": (
93
+ "READ-ONLY: this changes no data and reports no count. Free to call, free to get "
94
+ "wrong. It may still move what the person is looking at \u2014 navigating is a read "
95
+ "\u2014 so they will see you do it."
96
+ ),
97
+ "describe": (
98
+ "DESCRIBE: this changes what is SELECTED and changes no data. "
99
+ "Safe to call \u2014 the worst outcome is the wrong rows highlighted. It reports a "
100
+ "`count` of what it matched; read that count before you commit to anything."
101
+ ),
102
+ "commit": (
103
+ "*** COMMIT: THIS CHANGES DATA AND MAY BE IRREVERSIBLE. ***\n"
104
+ "Do not call it to find out what it does. If it acts on a selection, use the "
105
+ "app's `describe` verb first, check the `count` it reports is the number you "
106
+ "expect, and only then commit."
107
+ ),
108
+ # The fourth kind, and the only one whose cost is paid by somebody who is
109
+ # not the app. ``read`` is "free to call, free to get wrong" and that
110
+ # sentence is false here, so this one says what asking actually costs: a
111
+ # person's attention, a capped allowance, and every other call blocked while
112
+ # the question is open. The last sentence is the one the whole mechanism
113
+ # stands on -- an answer is not an approval -- and it is in the cached half
114
+ # because a model that learns it from a refusal has already asked somebody
115
+ # for permission it was never going to get. Verbatim from the TS half.
116
+ "ask": (
117
+ "ASK: this puts a question to the person and their answer comes back as the result. "
118
+ "It changes no data and reports no count, and it is NOT free: it costs their "
119
+ "attention, the app may cap how many questions you get, and nothing else runs while "
120
+ "one is open. Ask when you cannot act without guessing, ask once, and ask the "
121
+ "narrowest question that unblocks you.\n"
122
+ "An answer is not permission: a commit still goes to whoever approves commits here, "
123
+ "whatever they said to you."
124
+ ),
125
+ }
126
+
127
+ #: The commit banner for a commit the app says it can undo.
128
+ #:
129
+ #: A separate string rather than a sentence appended to the shouted one, and the
130
+ #: difference is the point. ``set-setting("dense-rows", "true")`` and accepting
131
+ #: 3,412 contacts were both getting THIS CHANGES DATA AND MAY BE IRREVERSIBLE,
132
+ #: and a banner that appears on a page-size change is a banner a model learns to
133
+ #: read past — the same way a person learns to click Yes without reading. So
134
+ #: the reversible one is not shouted, and the irreversible one keeps its
135
+ #: asterisks and goes on meaning something.
136
+ #:
137
+ #: It still says the data changes, because it does. ``reversible`` is a claim
138
+ #: that there is a way back, not that nobody minds. Verbatim from the TS half.
139
+ #: ``consumes: "plan"`` folded into the description.
140
+ #:
141
+ #: In the cached half for exactly the reason ``refuses`` and ``screen`` are: the
142
+ #: point is that the bare call is never made. A model that learns the pairing
143
+ #: here runs the ``describe`` first and keeps the token; a model that learns it
144
+ #: from a refusal has already spent a round trip, and on a commit it has spent
145
+ #: it in front of a person waiting for an answer.
146
+ #:
147
+ #: It says what the token is FOR and not merely that it is required, because
148
+ #: "pass the plan" reads as ceremony and gets dropped, while "the number you
149
+ #: read is the number that moves" is the reason it exists. Verbatim from the TS
150
+ #: half.
151
+ _PLAN_NOTE = (
152
+ "REQUIRES A PLAN. This acts on the selection, so it may only be called with the `plan` "
153
+ "token that the app's `describe` verb returned beside its `count`. Run that describe, read "
154
+ "the count, check it is the number the person asked for, and pass the `plan` straight back "
155
+ "here. If anything has moved the selection in between — the person ticked a row, data "
156
+ "arrived — this is refused as `stale-plan` and the refusal names both counts. Reading and "
157
+ "navigating do not move the selection and do not spend the plan, so go and confirm "
158
+ "whatever you are unsure of first. That is the point of the token: the number you read is "
159
+ "the number that moves."
160
+ )
161
+
162
+ _COMMIT_REVERSIBLE_NOTE = (
163
+ "COMMIT (reversible): this changes data, and the app says the change can be undone. "
164
+ "Still a change the person will see, so do not call it to find out what it does; if it "
165
+ "acts on a selection, read the `count` from the app's `describe` verb first."
166
+ )
167
+
168
+
169
+ #: The MCP path's default for whether a call's elapsed time reaches the model.
170
+ #:
171
+ #: ``"slow"``, which is ``mountWidget``'s default and not ``drive``'s — and the
172
+ #: split is worth the paragraph, because this is the one place the two halves
173
+ #: could have disagreed about what an outside agent is.
174
+ #:
175
+ #: ``drive`` defaults to ``"off"`` because it is a LIBRARY PRIMITIVE: a widget,
176
+ #: a backend job, a test and a CLI all drive it, and a caller that opted into
177
+ #: nothing must get the transcript it got before timing existed, byte for byte,
178
+ #: or every cached eval prompt moves on upgrade. Nothing about this server is
179
+ #: that. It is one process pointed at one live tab for one agent, with its own
180
+ #: instructions text, and it has no transcript anybody has cached.
181
+ #:
182
+ #: And the case for the line is STRONGER here than in the panel, which is what
183
+ #: settles it. ``mountWidget`` turns it on because "that verb took twenty
184
+ #: seconds" is a fact about the app worth a line to somebody watching — but
185
+ #: that somebody can see the spinner. An agent arriving over MCP cannot see
186
+ #: anything: it has one number available to it, its own round trip, and that
187
+ #: number is the network plus the tab's work plus any question the page put to
188
+ #: a person. The whole reason ``tookMs`` is on the wire is that this reader
189
+ #: could not otherwise tell a slow app from a slow network from somebody taking
190
+ #: thirty seconds over an Approve button. Defaulting the one honest figure to
191
+ #: silence would have left it unable to tell them apart anyway.
192
+ #:
193
+ #: The cost argument is satisfied the same way it is in the panel: nothing is
194
+ #: rendered below a second, and nothing at all is rendered for a tab that
195
+ #: reports no figure, so a snappy app and an older tab both pay zero bytes.
196
+ TIMING = "slow"
197
+
198
+ #: How to read a ``took:`` line, said once in the instructions rather than
199
+ #: beside every duration.
200
+ #:
201
+ #: NOT the TS half's wording, and the difference is the one sentence that
202
+ #: matters. ``systemPrompt`` can say "a result with NO ``took:`` line took under
203
+ #: a second — that is the only reason the line is missing", because in the page
204
+ #: the clock is in the same process as the verb and silence can only mean fast.
205
+ #: Over the relay silence has a second cause: PROTOCOL.md makes an absent
206
+ #: ``tookMs`` mean UNKNOWN — an older tab, a hand-written loop, or a call the
207
+ #: tab could not time honestly because a person was inside it — and a model
208
+ #: told that silence means fast would report an unmeasured app as a quick one.
209
+ #: So this says both, and says which one is which, because "I cannot tell" is
210
+ #: an answer a model can give and "it was fast" asserted on no evidence is not.
211
+ _TIMING_NOTE = {
212
+ "slow": (
213
+ "Some results carry a `took:` line, which is roughly how long that verb took in the "
214
+ "app itself. It is rounded, so treat `~2s` and `~3s` as about the same and do not "
215
+ "report differences smaller than the rounding. It counts only the app's own work: the "
216
+ "network between you and the tab is not in it, and neither is time somebody spent "
217
+ "reading a confirmation. A result with NO `took:` line is one of two things — the "
218
+ "call took under a second, or this tab does not report its own timing — and you "
219
+ "cannot tell which from here, so do not say a call with no line was fast. If you are "
220
+ "asked which of two things is slower, answer from the lines you have, say they are "
221
+ "approximate, and say so when a call you were asked about carried none."
222
+ ),
223
+ "always": (
224
+ "Every result that can carry one carries a `took:` line: roughly how long that verb "
225
+ "took in the app itself, rounded, so treat `~0.4s` and `~0.5s` as about the same. It "
226
+ "counts only the app's own work — not the network between you and the tab, and not "
227
+ "time somebody spent reading a confirmation. A result with no line at all is one this "
228
+ "tab did not time, which is not a claim that it was fast. If you are asked which of "
229
+ "two things is slower, answer from these lines and say they are approximate."
230
+ ),
231
+ }
232
+
233
+
234
+ def _floor_ms(timing: str) -> float | None:
235
+ """The ``render_duration`` threshold for a mode, or None to render nothing.
236
+
237
+ One mapping rather than three ``if`` branches at the two call sites, which
238
+ is also where the modes are documented as a closed set: an unknown word
239
+ renders nothing, because a server configured with a typo should go on
240
+ working and should not start printing durations nobody asked for.
241
+ """
242
+ if timing == "slow":
243
+ return SLOW_MS
244
+ if timing == "always":
245
+ return 0
246
+ return None
247
+
248
+
249
+ def _screen_note(screen: str | Sequence[str]) -> str:
250
+ """``screen`` folded into the description.
251
+
252
+ The tool list is the same on every screen — a verb list that changed
253
+ with the screen would bust the prompt prefix on every navigation, which is
254
+ the cost argument — so this sentence is how a model learns, in the
255
+ cached half, that a verb it can see will not work where it is standing.
256
+ Exactly the argument for putting ``refuses`` in here: the point is that the
257
+ call is never made.
258
+
259
+ A verb on several screens names them all, because naming one of three is
260
+ worse than naming none: a model told ``next-page`` is "ONLY ON THE
261
+ `contacts` SCREEN" will navigate away from the company list it was already
262
+ standing on to do something it could have done where it was. The one-screen
263
+ wording is byte-for-byte what it was before this could be a list, so no
264
+ app's cached prefix moved for a feature it does not use. Verbatim from the
265
+ TS half.
266
+ """
267
+ # A string is one screen and anything else is a sequence of them. Tested
268
+ # that way round rather than with `isinstance(..., list)`, because a string
269
+ # IS a sequence of characters and a tuple is what ``VerbSpec`` holds — the
270
+ # list check passes a tuple straight through and prints it.
271
+ screens = [screen] if isinstance(screen, str) else list(screen)
272
+ quoted = [f"`{s}`" for s in screens]
273
+ if len(quoted) > 1:
274
+ where = f"ONLY ON THE {', '.join(quoted[:-1])} AND {quoted[-1]} SCREENS."
275
+ else:
276
+ where = f"ONLY ON THE {quoted[0]} SCREEN."
277
+ return (
278
+ f"{where} The screen you are on is the `screen` line of "
279
+ "every screen you read. Called from anywhere else this is refused as `wrong-screen`, "
280
+ "and the refusal names where you are and where the verb lives."
281
+ )
282
+
283
+
284
+ # ---- manifest → tools ----------------------------------------------------
285
+
286
+
287
+ def arg_schema(spec: ArgSpec) -> dict[str, Any]:
288
+ """One ``ArgSpec`` as one JSON Schema property.
289
+
290
+ ``oneOf`` becomes ``enum`` and not a JSON Schema ``oneOf``. The names look
291
+ alike and the meanings diverge: the core's ``oneOf`` is a list of permitted
292
+ scalar values, which is ``enum``, while JSON Schema's ``oneOf`` is a list of
293
+ subschemas. Emitting the latter would produce a schema that validates
294
+ anything.
295
+ """
296
+ if spec.type not in _JSON_TYPES:
297
+ raise ValueError(f"driverkit: unknown arg type {spec.type!r}")
298
+ schema: dict[str, Any] = {"type": _JSON_TYPES[spec.type], "description": spec.describe}
299
+ if spec.one_of is not None:
300
+ schema["enum"] = list(spec.one_of)
301
+ return schema
302
+
303
+
304
+ def verb_tool(verb: VerbSpec) -> dict[str, Any]:
305
+ """One manifest verb as one MCP tool.
306
+
307
+ ``optional`` is expressed by omission from ``required``, which is how JSON
308
+ Schema says it; an ``"optional": true`` key would be ignored by every
309
+ validator and the argument would silently become mandatory.
310
+
311
+ ``rev`` is added as an extra optional property on every verb. It is not an
312
+ app argument — it is the staleness claim from PROTOCOL.md's ``call`` frame,
313
+ hoisted into the schema because a model has nowhere else to put it. Passing
314
+ the ``rev`` it last read is what turns "act on a row somebody already
315
+ moved" into a clean ``stale`` refusal. A verb that declares its own ``rev``
316
+ argument keeps it and does not get the hoisted one, because the app's
317
+ meaning wins over ours.
318
+ """
319
+ properties = {name: arg_schema(spec) for name, spec in verb.args.items()}
320
+ required = [name for name, spec in verb.args.items() if spec.required]
321
+
322
+ # NOT on an ``ask``, which is the one exception to hoisting them onto
323
+ # everything: a question acts on no screen, so there is nothing for it to be
324
+ # stale about, and a model that volunteered the ``rev`` it was told to quote
325
+ # would have its question refused ``stale`` because the person clicked a row
326
+ # while it was being composed. See the TS half, which says it at length.
327
+ asking = verb.kind == "ask"
328
+
329
+ if not asking and "rev" not in properties:
330
+ properties["rev"] = {
331
+ "type": "integer",
332
+ "description": (
333
+ "Optional. The `rev` from the last screen you read. If the screen has "
334
+ "moved since, the call is refused as `stale` instead of acting on "
335
+ "something you did not see. Omit it to skip that check."
336
+ ),
337
+ }
338
+
339
+ # Hoisted exactly as `rev` is, and for a failure `rev` does not catch: a
340
+ # paging call sent with no rev once landed on a screen the agent had never
341
+ # seen, paged a different company's list and answered `ok`. "You are
342
+ # somewhere else" and "the number moved" are different mistakes with
343
+ # different fixes, so they are different claims and different refusals. A
344
+ # verb with its own `screen` argument keeps it, because the app's meaning
345
+ # wins over ours — the same rule as `rev`.
346
+ if not asking and "screen" not in properties:
347
+ properties["screen"] = {
348
+ "type": "string",
349
+ "description": (
350
+ "Optional. The `screen` from the last screen you read. If the app is on "
351
+ "another screen now, the call is refused as `wrong-screen` instead of "
352
+ "acting on a screen you never saw. Omit it to skip that check."
353
+ ),
354
+ }
355
+
356
+ # Hoisted like `rev` and `screen`, with one difference: ONLY onto a verb
357
+ # that declares `consumes`. Those two are claims any verb can make, so they
358
+ # go on everything; a plan token means nothing to a verb that does not
359
+ # consume one, and adding the property to every tool in every app would move
360
+ # every cached prompt prefix in the world for a feature those apps do not
361
+ # use. That prefix is the cost argument the library is built on.
362
+ #
363
+ # NOT in `required`, although the core refuses the call without it, and that
364
+ # is deliberate. `required` moves the failure into the client's validator,
365
+ # where the refusal's hint — which names both counts and spells out the
366
+ # pairing — never reaches the model. The schema stays permissive and the
367
+ # core is strict; the description says it is required.
368
+ if verb.consumes == "plan" and "plan" not in properties:
369
+ properties["plan"] = {
370
+ "type": "string",
371
+ "description": (
372
+ "Required. The `plan` token from the `describe` verb that counted this "
373
+ "selection, passed back exactly as it was given. Without it the call is "
374
+ "refused as `stale-plan`, and so is a token taken before the selection moved."
375
+ ),
376
+ }
377
+
378
+ description = [verb.describe]
379
+ if verb.kind == "commit" and verb.reversible:
380
+ # Checked before the table, so a reversible commit reads differently
381
+ # from an irreversible one. `reversible` is read only here, on a
382
+ # `commit`: on a `read` or a `describe` it is a claim about nothing,
383
+ # since the app has already said no data moves.
384
+ description.append(_COMMIT_REVERSIBLE_NOTE)
385
+ elif verb.kind in _KIND_NOTE:
386
+ # Second, straight after what the verb does and ahead of the mechanical
387
+ # notes, so a model skimming the first two lines of a description
388
+ # cannot miss that a verb commits. An unknown or absent kind adds
389
+ # nothing: this server does not manufacture a safety claim the app did
390
+ # not make, in either direction.
391
+ description.append(_KIND_NOTE[verb.kind])
392
+ # Third, above `screen`, because HOW a verb may be called outranks WHERE: a
393
+ # model that goes to the right screen and calls the commit bare has still
394
+ # lost the turn, and this is the sentence that stops it. Both still outrank
395
+ # the mechanics.
396
+ if verb.consumes == "plan":
397
+ description.append(_PLAN_NOTE)
398
+ if verb.screen:
399
+ description.append(_screen_note(verb.screen))
400
+ description.append(_RESULT_NOTE)
401
+ if verb.refuses:
402
+ # In the description rather than only in the error path, because this is
403
+ # the half that gets cached in the prompt prefix: the point of
404
+ # `refuses` is that a well-briefed agent never makes the call.
405
+ description.append("May refuse: " + ", ".join(verb.refuses) + ". " + _REFUSAL_NOTE)
406
+
407
+ return {
408
+ "name": verb.name,
409
+ "description": "\n\n".join(description),
410
+ "inputSchema": {
411
+ "type": "object",
412
+ "properties": properties,
413
+ "required": required,
414
+ # The app named its own arguments; an extra one is a mistake worth
415
+ # catching at the client rather than sending to a verb that will
416
+ # ignore it.
417
+ "additionalProperties": False,
418
+ },
419
+ }
420
+
421
+
422
+ def tools_for(manifest: Manifest) -> list[dict[str, Any]]:
423
+ """The whole tool list: every verb, then the two fixed reads."""
424
+ tools = [verb_tool(v) for v in manifest.verbs]
425
+ taken = {t["name"] for t in tools}
426
+
427
+ if READ_SCREEN not in taken:
428
+ tools.append(
429
+ {
430
+ "name": READ_SCREEN,
431
+ "description": (
432
+ f"Read what is on screen in the {manifest.app or 'app'} right now: where "
433
+ "the user is, the rows visible to them, what they have selected, and the "
434
+ "`rev` to quote back when you act.\n\n"
435
+ "You see exactly what the person at the keyboard sees — same filters, same "
436
+ "page — and nothing more. If a record you expect is missing, it is probably "
437
+ "off screen rather than absent.\n\n"
438
+ "Read it again after anything unexpected: it is the cheapest tool here and "
439
+ "the only way to settle what actually happened."
440
+ ),
441
+ "inputSchema": {"type": "object", "properties": {}, "required": []},
442
+ }
443
+ )
444
+
445
+ if LIST_TABS not in taken:
446
+ tools.append(
447
+ {
448
+ "name": LIST_TABS,
449
+ "description": (
450
+ "List the app tabs connected to this relay, with their titles, URLs and "
451
+ "whether the person is looking at each one. Use it to tell two open tabs "
452
+ "apart when a person has to be asked which one they mean. This server "
453
+ "drives one fixed tab; the others are informational."
454
+ ),
455
+ "inputSchema": {"type": "object", "properties": {}, "required": []},
456
+ }
457
+ )
458
+
459
+ return tools
460
+
461
+
462
+ #: How each :attr:`driverkit.types.Tab.focus` value reads to a person being
463
+ #: asked "which tab?".
464
+ #:
465
+ #: Spelled here rather than at each use because this listing is read in two
466
+ #: places — the ``list_tabs`` tool and the message ``driverkit-mcp`` prints
467
+ #: when it refuses to guess — and two copies is how the two come to describe
468
+ #: the same tab differently to the model and to the human.
469
+ #:
470
+ #: A value this mapping does not know is printed as it arrived rather than
471
+ #: dropped: PROTOCOL.md promises a field may gain a value without a version
472
+ #: bump, and a client that silently showed nothing for a state it had not heard
473
+ #: of would be hiding the one thing the person is choosing on.
474
+ FOCUS_WORDS = {
475
+ "focused": "you are looking at this one",
476
+ "visible": "on screen, but this window is not frontmost",
477
+ "hidden": "a background tab",
478
+ }
479
+
480
+
481
+ def render_tabs(tabs: list[Tab], current: str) -> str:
482
+ if not tabs:
483
+ return "(no tabs connected to this relay)"
484
+ lines = []
485
+ for tab in tabs:
486
+ mark = " <- this server drives this one" if tab.id == current else ""
487
+ focus = FOCUS_WORDS.get(tab.focus, tab.focus) if tab.focus else ""
488
+ bits = [b for b in (tab.app, tab.title, tab.url, focus) if b]
489
+ lines.append(f"{tab.id} {' | '.join(bits)}{mark}")
490
+ return "\n".join(lines)
491
+
492
+
493
+ def pick_tab(tabs: Sequence[Tab]) -> Tab | None:
494
+ """The tab a person means by "the one I am looking at", or ``None`` to ask.
495
+
496
+ ``--tab <id>`` works and "omit it when exactly one tab is connected" stops
497
+ working at two, and until the page started reporting
498
+ :attr:`driverkit.types.Tab.focus` there was nothing in the protocol that
499
+ could express the thing a person actually means. This is where that field
500
+ is turned into a decision, and it is in the CLIENT rather than in either
501
+ relay on purpose: a relay carries the string and has no opinion about it,
502
+ so the two implementations stay behaviourally identical by not implementing
503
+ this at all.
504
+
505
+ The rules, in order, and the last one is the important one:
506
+
507
+ 1. **One tab connected** — that one. The behaviour this had before focus
508
+ existed, kept exactly, including for a tab that reports no focus.
509
+ 2. **Exactly one tab says ``focused``** — that one. It is claiming the
510
+ person is looking at it, which beats a tab that says nothing.
511
+ 3. **Nobody says ``focused`` and exactly one says ``visible``** — that one.
512
+ This is the person being in another application entirely, and it is
513
+ still an unambiguous answer: with one window, exactly one tab of an app
514
+ is on screen and the rest are ``hidden``. "The one I was last in" is
515
+ what they will mean when they come back.
516
+ 4. **Anything else — ``None``, and the caller asks.** Two windows each with
517
+ a focused tab, two tabs reporting nothing, a relay from before this
518
+ field: in all of them the honest answer is a question. A wrong answer
519
+ confidently given drives somebody's other screen, and the cost of
520
+ asking is one sentence.
521
+
522
+ Note what rule 4 does NOT do: it does not fall back to the first tab, the
523
+ newest tab or the one that happens to sort first. Each of those would make
524
+ the ambiguous case *look* handled, and the failure would be a commit landing
525
+ in a window nobody was watching.
526
+ """
527
+ if len(tabs) == 1:
528
+ return tabs[0]
529
+ focused = [t for t in tabs if t.focus == "focused"]
530
+ if len(focused) == 1:
531
+ return focused[0]
532
+ if not focused:
533
+ visible = [t for t in tabs if t.focus == "visible"]
534
+ if len(visible) == 1:
535
+ return visible[0]
536
+ return None
537
+
538
+
539
+
540
+ def _screens_note(screens: Sequence[ScreenSpec]) -> str:
541
+ """The app's map, rendered for the model.
542
+
543
+ ``Manifest.screens`` is the static list of every screen the app has, so
544
+ this belongs in the instructions a client prepends once rather than in any
545
+ turn's tail. What an agent could not do before the field existed is learn
546
+ that a screen *exists* without standing on it: ``Snapshot.screen`` says
547
+ where it is and ``Verb.screen`` says where a verb works, and between them
548
+ there was still no way to find out that a companies list is in there
549
+ somewhere. The worked example closed that gap by pasting a prose screen-map
550
+ into ``instructions`` — the same map the app's own route table already had,
551
+ written a second time in English with nothing checking that the two agree.
552
+
553
+ The sentence about it being the same for every user is not padding. It is
554
+ the one thing a model cannot tell by looking: a list that might have been
555
+ filtered for this person is a list whose absences mean nothing. See
556
+ ``ScreenSpec``, which forbids filtering it. Verbatim from the TS half.
557
+ """
558
+ lines = [
559
+ "THE SCREENS THIS APP HAS. The same screens for every user, always \u2014 a screen listed "
560
+ "here exists whether or not you have been to it. Only which one is LIVE changes, and "
561
+ "that is the `screen` line of every screen you read. If you cannot get to one of "
562
+ "these, the app will tell you why when you try; it is never missing from this list."
563
+ ]
564
+ for screen in screens:
565
+ needs = list(screen.args.keys())
566
+ line = f"- `{screen.id}`: {screen.describe}"
567
+ if screen.url:
568
+ line += f" Address: `{screen.url}`."
569
+ if needs:
570
+ line += " Needs: " + ", ".join(f"`{n}`" for n in needs) + "."
571
+ lines.append(line)
572
+ return "\n".join(lines)
573
+
574
+
575
+ def _render_flow(flow: FlowSpec, verbs: Sequence[VerbSpec] = ()) -> str:
576
+ """One flow, rendered as the recipe it is.
577
+
578
+ The id first and the ``describe`` on the same line, because the
579
+ ``describe`` is what a model picks a flow on — Microsoft's finding on
580
+ selection across tool groups is that the choice is made "based on the
581
+ plugin's description, not on any of the individual functions" — and the
582
+ steps are what it follows once it has picked. A ``section`` is printed once
583
+ where it changes rather than on every step.
584
+
585
+ TWO MARKS GO IN PARENTHESES AFTER THE VERB, so that a model skimming five
586
+ numbered lines sees the shape of the recipe without reading every hint:
587
+ OPTIONAL for a step with a ``skip_when``, because which steps carry the job
588
+ is structural and used to be a clause buried mid-hint; and the plan
589
+ handoff, naming the numbered step whose ``describe`` mints the token. The
590
+ second is DERIVED from ``kind`` and ``consumes``, which the manifest
591
+ already carries -- nothing for an author to keep in step, and it is the one
592
+ value that crosses two steps in this library. Verbatim from the TS half.
593
+ """
594
+ lines = [f"`{flow.id}` \u2014 {flow.describe}"]
595
+ section: str | None = None
596
+ by_name = {v.name: v for v in verbs}
597
+ # The numbered step whose `describe` verb last minted a plan token, so the
598
+ # mark can name it. Updated AFTER the current step is rendered: a describe
599
+ # does not consume its own plan.
600
+ minted: int | None = None
601
+ for i, step in enumerate(flow.steps):
602
+ if step.section and step.section != section:
603
+ lines.append(f" ({step.section})")
604
+ section = step.section
605
+ verb = by_name.get(step.verb)
606
+ marks: list[str] = []
607
+ if step.skip_when:
608
+ marks.append(f"OPTIONAL \u2014 skip it when {step.skip_when}")
609
+ if verb is not None and verb.consumes == "plan" and minted is not None:
610
+ marks.append(f"takes the `plan` token step {minted} returned")
611
+ mark = f" ({'; '.join(marks)})" if marks else ""
612
+ lines.append(f" {i + 1}. `{step.verb}`{mark} \u2014 {step.hint}")
613
+ if verb is not None and verb.kind == "describe":
614
+ minted = i + 1
615
+ return "\n".join(lines)
616
+
617
+
618
+ def _flows_note(flows: Sequence[FlowSpec], verbs: Sequence[VerbSpec] = ()) -> str:
619
+ """The app's flows, rendered for the model.
620
+
621
+ THE SENTENCE THAT MATTERS is the one saying there is no tool that runs a
622
+ flow. A model handed a list of numbered steps will look for the button, and
623
+ not finding one it may well decide the flow is unavailable; being told that
624
+ following the steps IS the mechanism, and why, is what turns a list into an
625
+ instruction. The why is honest and is the design: a flow that executed
626
+ internally could not adapt when step three found the record already
627
+ accepted, and the agent would get back an ``ok`` that told it nothing.
628
+ Apple's app skills say the same thing about themselves — "Skills don't
629
+ enforce deterministic behavior, and Siri doesn't run the listed intents in
630
+ sequence." Verbatim from the TS half.
631
+ """
632
+ return (
633
+ "THE JOBS THIS APP SAYS ITS VERBS ARE USUALLY COMBINED INTO. Each one is a recipe for "
634
+ "YOU to carry out with the verbs you already have. **There is no tool that runs a "
635
+ "flow**, and that is deliberate: following the steps yourself means you see what each "
636
+ "one actually returned and can change course, which something running them for you "
637
+ "could not. Take the steps in order, read what each verb reports before the next, and "
638
+ "depart from the recipe when the screen says something it did not expect \u2014 then say so."
639
+ # The sentence about OPTIONAL steps is added only when some step
640
+ # actually is one. Everything in here rides in the cached prefix of
641
+ # every session of every user, and a paragraph about a construct the app
642
+ # does not use is the kind of cost that is real, paid once, and
643
+ # invisible -- which is the exact cost the size budgets exist to make
644
+ # somebody weigh. An app whose flows mark nothing optional gets the note
645
+ # it got before the field existed.
646
+ + (
647
+ " A step marked OPTIONAL may be skipped when the condition beside it holds, and "
648
+ "that condition is a sentence for you to judge, not a rule something checks: when "
649
+ "it is not clearly true, take the step."
650
+ if any(s.skip_when for f in flows for s in f.steps)
651
+ else ""
652
+ )
653
+ + "\n\n"
654
+ + "\n\n".join(_render_flow(f, verbs) for f in flows)
655
+ )
656
+
657
+
658
+ def instructions_for(manifest: Manifest, timing: str = "off") -> str:
659
+ """The server instructions an MCP client prepends to its system prompt.
660
+
661
+ Shared because this text is half the safety story: it is where a model is
662
+ told to read the screen before acting, to quote the ``rev`` back, and that
663
+ COMMIT verbs change data. Two servers with two copies of it would be two
664
+ different safety stories, and the one that drifts is the one nobody is
665
+ reading when it matters.
666
+
667
+ ``timing`` adds the note about what a ``took:`` line means, once, in the
668
+ text a client prepends once — the same placement ``systemPrompt`` gives it
669
+ in the TS half, and for the same reason: a sentence of guidance beside
670
+ every duration is the one piece of boilerplate in a turn that is
671
+ O(calls), for a number that needs explaining once.
672
+
673
+ It defaults to ``"off"`` HERE while :data:`TIMING` is ``"slow"``, which is
674
+ not a contradiction. This function is called directly by both servers and
675
+ by tests, and a default of off is what keeps a caller that says nothing
676
+ getting the bytes it got before this existed. :class:`TabTools` is the
677
+ thing an agent actually talks to, and it is the thing that has an opinion.
678
+ """
679
+ parts = [
680
+ f"You are driving a live {manifest.app} tab that a person has open. "
681
+ f"Call {READ_SCREEN} before acting so you know what they are looking at, "
682
+ "then quote that screen's `rev` back when you act. Every verb returns the "
683
+ "screen after it ran, so acting and looking are one step. You can do exactly "
684
+ "what that person could do, and nothing more.",
685
+ "Every verb says what it does to the world: READ-ONLY changes no data and reports "
686
+ "no count \u2014 moving to another screen is a read, and the person watching will "
687
+ "see it \u2014 DESCRIBE changes what is selected and reports a count, COMMIT "
688
+ "changes data and may be irreversible. Never commit on a selection whose count you "
689
+ "have not read.",
690
+ # The other half of "never commit on a count you have not read", which
691
+ # that sentence could only ever ask for. A count read and then acted on
692
+ # a moment later is not a count of the rows that moved: the person can
693
+ # tick a row between the two calls. A commit that says `consumes:
694
+ # "plan"` is one the core will not let that happen to, and this is where
695
+ # an agent arriving over MCP learns the pairing rather than meeting it
696
+ # as a refusal.
697
+ "A COMMIT whose description says REQUIRES A PLAN takes the `plan` token that the "
698
+ "`describe` verb returned beside its `count`. Pass it straight back, do not reuse one "
699
+ "and do not keep one for later: a plan is good for one commit and only while nothing "
700
+ "has moved the selection. Looking is free: reading a screen or navigating to another "
701
+ "one leaves the plan good, so go back and confirm anything you are unsure of before an "
702
+ "irreversible commit. `stale-plan` means the rows changed under you and names both "
703
+ "counts — the one you were shown and the one there is now — so run the "
704
+ "describe again, read the new number and say it before committing to it.",
705
+ # The consent half of the safety story, which used to be missing from
706
+ # this text because it was missing from this path: the confirmation
707
+ # lived in the in-page loop, so a person watching the widget was asked
708
+ # and an agent arriving here was not. It is in the core's `call()` now,
709
+ # so every one of these three answers is reachable from here — and the
710
+ # last sentence is the one that matters. An agent that is refused a
711
+ # commit and then presses the page's own Approve button has not been
712
+ # approved by anybody; see webmachinelearning/webmcp#288, where exactly
713
+ # that happened and the receipt said "approved by you".
714
+ "A COMMIT may be put to the person first. `declined-by-user` means they said no: do "
715
+ "not retry it, do not try another verb or control that does the same thing, and do "
716
+ "not press an approve or confirm control \u2014 pressing it yourself is not consent and "
717
+ "is refused anyway. `approval-pending` means somebody is being asked right now and "
718
+ "nothing ran; wait. `approval-timeout` means nobody answered and the verb DID NOT "
719
+ "RUN, which is not the same as the transport `timeout`, where the call was accepted "
720
+ "and the outcome is unknown.",
721
+ ]
722
+ # The paragraph about asking, and only for an app that CAN ask.
723
+ #
724
+ # Conditional for the reason the map and the recipes below are: this text is
725
+ # prepended once per session and a paragraph about a tool the app has not
726
+ # got is a cost that is real, paid per person, and invisible. It is also
727
+ # worse than wasteful -- a model told to ask rather than guess, in an app
728
+ # with no way to ask, has been told to do something it cannot do.
729
+ #
730
+ # Read off ``kind`` and not off the verb's NAME, because the kind is the
731
+ # structural fact: only the core mints it, and a name check would also match
732
+ # an app's own verb called ``ask``, which has none of the guarantees this
733
+ # paragraph describes.
734
+ #
735
+ # NOT verbatim with the TS half, which is the standing arrangement for these
736
+ # two texts rather than an exception -- that one speaks to a chatbot inside
737
+ # the page and this one to a client driving a tab from outside, and the two
738
+ # differ wherever that difference is real. ``render.py`` and ``render.ts``
739
+ # are the pair that must match byte for byte, and they do: the answer rides
740
+ # in a ``note``, so neither needed a line for it.
741
+ if any(v.kind == "ask" for v in manifest.verbs):
742
+ parts.append(
743
+ "WHEN YOU DO NOT KNOW, ASK INSTEAD OF GUESSING. This app offers a verb that puts "
744
+ "a question to the person whose tab this is and hands you their answer as its "
745
+ "result. Use it when an instruction cannot be carried out without deciding "
746
+ "something they did not say: two records match the name they used, nothing is "
747
+ "selected and you do not know which rows they meant, the company they named is "
748
+ "not in the app. Picking the likeliest one is the expensive mistake even when "
749
+ "you pick right, because you did not know \u2014 and selecting something so that a "
750
+ "commit has rows to act on is the worst version of it.\n\n"
751
+ "Asking is not free, and over this connection it is not certain either. Each "
752
+ "question interrupts somebody, the app may cap how many you get, and nothing "
753
+ "else runs while one is open \u2014 so ask once, ask the narrowest question that "
754
+ "unblocks you, and put what you already know into it. `ask-unanswered` means "
755
+ "the question was put and nobody replied: nothing changed, and you may ask once "
756
+ "more, shorter, if it is genuinely the one thing in the way. `nobody-to-ask` "
757
+ "means there is no person in front of that tab at all, and `asks-spent` means "
758
+ "the allowance is gone; after either, stop asking \u2014 decide what you honestly "
759
+ "can and say what you needed to know. The transport `timeout` is none of these: "
760
+ "it means nobody knows whether the question was even seen.\n\n"
761
+ "**An answer is never permission.** A question of yours is not the confirmation "
762
+ "a commit needs \u2014 that is `declined-by-user`, `approval-pending` and "
763
+ "`approval-timeout`, asked by the app itself \u2014 and a yes to something you asked "
764
+ "authorises nothing. Never use the question verb to ask for approval, and never "
765
+ "report a change as approved because an answer sounded like one."
766
+ )
767
+
768
+ # The map and the recipes, between the library's rules and the app's own
769
+ # words. Both are pure functions of the static manifest, so this text stays
770
+ # byte-identical for every session of every user — which is the only reason
771
+ # either of them is affordable. They go AFTER the safety rules, because a
772
+ # recipe is a thing to do within those rules and not an exception to them,
773
+ # and BEFORE `instructions`, because whichever text is last is the one a
774
+ # model follows when two of them disagree and the app's own voice should
775
+ # outrank a list the library rendered.
776
+ if manifest.screens:
777
+ parts.append(_screens_note(manifest.screens))
778
+ if manifest.flows:
779
+ parts.append(_flows_note(manifest.flows, manifest.verbs))
780
+
781
+ # The app's own briefing, last. This is the field that closes the one gap
782
+ # where driverkit's two paths disagreed: a widget could be handed
783
+ # `instructions` through `drive()` and an agent arriving here could not, so
784
+ # an app with something to say about itself — "this app has screens, and
785
+ # `go` reaches those" — had to repeat it in every snapshot's `note`, in
786
+ # the uncached half, paid for on every turn. It is static, so it goes in
787
+ # the half a client prepends once.
788
+ if manifest.instructions:
789
+ parts.append(manifest.instructions)
790
+ # LAST, after the app's own words, and this one is deliberately not in the
791
+ # "whichever text is last wins" argument above: it is not a rule about what
792
+ # to do, it is how to read one line of the answer, and an app has no opinion
793
+ # about that. Added only in a mode that can produce the line, so a server
794
+ # with timing off pays not one byte for it.
795
+ if timing in _TIMING_NOTE:
796
+ parts.append(_TIMING_NOTE[timing])
797
+ return "\n\n".join(parts)
798
+
799
+
800
+ @dataclass(frozen=True)
801
+ class ToolOutcome:
802
+ """What a tool call produced: text for the model, and whether it ran.
803
+
804
+ ``is_error`` is MCP's ``isError`` and means "the tool could not run". It is
805
+ deliberately False for an app refusal — see :meth:`TabTools.call`.
806
+ """
807
+
808
+ text: str
809
+ is_error: bool = False
810
+
811
+
812
+ class TabTools:
813
+ """MCP tools over one driverkit tab, with no transport attached.
814
+
815
+ The manifest is fetched once and kept. That is not a performance tweak, it
816
+ is the shape of the protocol: the manifest is the static half and is
817
+ guaranteed not to vary between two calls, while the snapshot is read fresh
818
+ every time and never cached. Getting that backwards is the whole cost
819
+ argument reversed.
820
+
821
+ ``client`` carries whatever credential the agent was given, so everything
822
+ this class can reach is already scoped to one principal by the relay. It
823
+ cannot see another person's tabs even in ``list_tabs``, because the relay
824
+ does not list them — which is why there is no filtering here and must not
825
+ be: a second place that decides what an agent may see is a second set of
826
+ rules, and the relay's is the one that is enforced.
827
+ """
828
+
829
+ def __init__(self, client: Driverkit, tab: str, timing: str = TIMING) -> None:
830
+ self.client = client
831
+ self.tab = tab
832
+ #: ``"slow"``, ``"always"`` or ``"off"`` — whether a call's elapsed time
833
+ #: reaches the model, and when. See :data:`TIMING` for why the default
834
+ #: is the panel's and not ``drive``'s.
835
+ self.timing = timing
836
+ self._manifest: Manifest | None = None
837
+
838
+ def manifest(self) -> Manifest:
839
+ if self._manifest is None:
840
+ self._manifest = self.client.manifest(self.tab)
841
+ return self._manifest
842
+
843
+ def tools(self) -> list[dict[str, Any]]:
844
+ return tools_for(self.manifest())
845
+
846
+ def instructions(self) -> str:
847
+ return instructions_for(self.manifest(), self.timing)
848
+
849
+ def call(self, name: str, arguments: Mapping[str, Any] | None = None) -> ToolOutcome:
850
+ """Run one tool and render the answer for a model.
851
+
852
+ ``isError`` is False for an app refusal. MCP's ``isError`` means the
853
+ tool could not run; a refusal means it ran and the answer was no, which
854
+ is information the model is supposed to act on. Flagging it as an error
855
+ invites a client to hide it or a model to retry unchanged.
856
+
857
+ It is True only when the call provably never landed — ``no-such-tab``,
858
+ ``tab-went-away`` — where there is nothing to reason about and the next
859
+ move is to list the tabs.
860
+
861
+ ``timeout`` is deliberately NOT an error, and this is the subtle one.
862
+ The outcome is unknown: the tab may have run the verb and died before
863
+ answering. Clients commonly render an ``isError`` result as a failed
864
+ step for the model to retry, and retrying an unknown commit is how a
865
+ bulk accept happens twice. So it comes back as an ordinary result whose
866
+ text says the outcome is unknown and, for a commit, to read the screen
867
+ before deciding anything.
868
+ """
869
+ args = dict(arguments or {})
870
+
871
+ if name == READ_SCREEN:
872
+ return ToolOutcome(render_snapshot(self.client.snapshot(self.tab)))
873
+
874
+ if name == LIST_TABS:
875
+ return ToolOutcome(render_tabs(self.client.tabs(), self.tab))
876
+
877
+ manifest = self.manifest()
878
+ verb = manifest.verb(str(name))
879
+ if verb is None:
880
+ known = ", ".join([v.name for v in manifest.verbs] + [READ_SCREEN, LIST_TABS])
881
+ # isError, because this one never reached the app: the model asked
882
+ # for a tool that does not exist. The known names are listed for the
883
+ # same reason the core lists them — so the fix needs no extra round
884
+ # trip.
885
+ return ToolOutcome(f"no such tool `{name}`. available: {known}", is_error=True)
886
+
887
+ # NEITHER CLAIM IS OFFERED ON AN ``ask``, AND NEITHER IS HONOURED HERE.
888
+ #
889
+ # ``verb_tool`` leaves both properties off a question's schema -- a
890
+ # question acts on no screen, so there is nothing for it to be stale
891
+ # about -- and this is the other half of that. A model volunteering a
892
+ # ``rev`` it was told to quote would otherwise have its question refused
893
+ # ``stale`` because the person clicked a row while it was being
894
+ # composed, which is the likeliest thing in the world when they are
895
+ # sitting right there. So the keys are dropped: not turned into a claim,
896
+ # and not left behind to become an argument the core has never heard of.
897
+ # Verbatim in behaviour with the in-page loop.
898
+ asking = verb.kind == "ask"
899
+ if asking:
900
+ args.pop("rev", None)
901
+ args.pop("screen", None)
902
+
903
+ # `rev` is ours unless the verb claimed the name, in which case it is an
904
+ # ordinary argument and goes through untouched.
905
+ rev = None
906
+ if not asking and "rev" not in verb.args:
907
+ raw_rev = args.pop("rev", None)
908
+ if isinstance(raw_rev, bool) or raw_rev is None:
909
+ rev = None
910
+ elif isinstance(raw_rev, (int, float)):
911
+ rev = int(raw_rev)
912
+
913
+ # And so is `screen`, by the same rule: the app keeps the name if it
914
+ # declared one, because `go(screen)` is a real verb in a real app.
915
+ # Anything that is not a non-empty string is dropped rather than sent;
916
+ # a number is not a screen id, and the relay would refuse the frame
917
+ # anyway. The in-page loop refuses it instead of dropping it, and the
918
+ # difference is that it has the screen in hand to quote back.
919
+ screen = None
920
+ if not asking and "screen" not in verb.args:
921
+ raw_screen = args.pop("screen", None)
922
+ if isinstance(raw_screen, str) and raw_screen.strip():
923
+ screen = raw_screen.strip()
924
+
925
+ # And so is `plan`, by the same rule, and only on a verb that consumes
926
+ # one — that is the only verb whose tool schema offered it, so a `plan`
927
+ # key on any other is either an argument the app named or a mistake the
928
+ # core should be allowed to see.
929
+ #
930
+ # Anything that is not a non-empty string is dropped rather than sent,
931
+ # as with `screen`. The core then refuses as `stale-plan` with the
932
+ # pairing spelled out, which is a better answer than a `bad-argument`
933
+ # about the shape of a field the model should not have invented.
934
+ plan = None
935
+ if verb.consumes == "plan" and "plan" not in verb.args:
936
+ raw_plan = args.pop("plan", None)
937
+ if isinstance(raw_plan, str) and raw_plan.strip():
938
+ plan = raw_plan.strip()
939
+
940
+ result = self.client.call(
941
+ self.tab, verb.name, args, rev=rev, screen=screen, plan=plan
942
+ )
943
+ return ToolOutcome(
944
+ self._timed(render_result(result, verb.kind), result), is_error=not result.landed
945
+ )
946
+
947
+ def _timed(self, text: str, result: Result) -> str:
948
+ """``render_result``'s text with the duration line in the outcome half.
949
+
950
+ WHY THE FIGURE IS THE TAB'S AND NOT THIS PROCESS'S. The only duration
951
+ this side can measure is the whole round trip — the network out, the
952
+ tab's work, any approval the page asked a person for, and the network
953
+ back — and three of those four are not the app's speed. Rendering it
954
+ would be exactly the lie ``DriveOptions.waited`` exists to prevent in
955
+ the in-page loop: "this call took 40 seconds" when 38 of them were
956
+ somebody reading a confirmation sends a model looking for a faster route
957
+ around a verb that is not slow. So the figure rendered here is the one
958
+ the TAB measured around its own call into the driver, carried in the
959
+ ``result`` frame, with the person's time already taken out of it by the
960
+ one party that could see them. See PROTOCOL.md and
961
+ :attr:`driverkit.types.Result.took_ms`.
962
+
963
+ ABOVE THE SCREEN, like the in-page loop puts it: "how long did my third
964
+ call take" is a question whose answer stays true forever, like ``ok``
965
+ and like the count, and unlike the table. The seam is the blank line
966
+ ``render_result`` puts between the outcome and the screen; a text with
967
+ no such seam — a refusal with no snapshot — gets the line appended,
968
+ where it is still in the outcome half because that is all there is.
969
+
970
+ NOTHING IS RENDERED FOR A RELAY REFUSAL, even if a figure somehow
971
+ arrived with one. There is no tab answer behind it: ``no-such-tab``
972
+ never reached anybody, and ``timeout`` and ``tab-went-away`` leave the
973
+ outcome unknown, where ``render_duration``'s own rule is that a deadline
974
+ that fired is not a duration.
975
+ """
976
+ floor = _floor_ms(self.timing)
977
+ if floor is None or result.took_ms is None or result.relay_refusal is not None:
978
+ return text
979
+ # `render_duration` and not a format string of our own: the two halves
980
+ # of this library say the same words about the same number, and a
981
+ # prompt that worked through the widget and reads differently here is a
982
+ # bug with no stack trace. `test/cross-impl.test.ts` is what holds the
983
+ # two renderers to it.
984
+ line = render_duration(result.took_ms, floor)
985
+ if not line:
986
+ return text
987
+ head, seam, screen = text.partition("\n\n")
988
+ return head + "\n" + line + seam + screen