driverkit 0.0.0-stage → 0.0.1

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.
Files changed (160) hide show
  1. package/CONTROLS.md +578 -0
  2. package/REACT.md +477 -0
  3. package/README.md +104 -2
  4. package/dist/agent/backend.d.ts +69 -0
  5. package/dist/agent/backend.d.ts.map +1 -0
  6. package/dist/agent/backend.js +130 -0
  7. package/dist/agent/backend.js.map +1 -0
  8. package/dist/agent/control.d.ts +148 -0
  9. package/dist/agent/control.d.ts.map +1 -0
  10. package/dist/agent/control.js +342 -0
  11. package/dist/agent/control.js.map +1 -0
  12. package/dist/agent/index.d.ts +9 -0
  13. package/dist/agent/index.d.ts.map +1 -0
  14. package/dist/agent/index.js +6 -0
  15. package/dist/agent/index.js.map +1 -0
  16. package/dist/agent/loop.d.ts +136 -0
  17. package/dist/agent/loop.d.ts.map +1 -0
  18. package/dist/agent/loop.js +824 -0
  19. package/dist/agent/loop.js.map +1 -0
  20. package/dist/agent/render.d.ts +173 -0
  21. package/dist/agent/render.d.ts.map +1 -0
  22. package/dist/agent/render.js +425 -0
  23. package/dist/agent/render.js.map +1 -0
  24. package/dist/agent/tools.d.ts +138 -0
  25. package/dist/agent/tools.d.ts.map +1 -0
  26. package/dist/agent/tools.js +622 -0
  27. package/dist/agent/tools.js.map +1 -0
  28. package/dist/agent/types.d.ts +566 -0
  29. package/dist/agent/types.d.ts.map +1 -0
  30. package/dist/agent/types.js +32 -0
  31. package/dist/agent/types.js.map +1 -0
  32. package/dist/browser/budget.d.ts +92 -0
  33. package/dist/browser/budget.d.ts.map +1 -0
  34. package/dist/browser/budget.js +151 -0
  35. package/dist/browser/budget.js.map +1 -0
  36. package/dist/browser/connect.d.ts +368 -0
  37. package/dist/browser/connect.d.ts.map +1 -0
  38. package/dist/browser/connect.js +1038 -0
  39. package/dist/browser/connect.js.map +1 -0
  40. package/dist/browser/elsewhere.d.ts +89 -0
  41. package/dist/browser/elsewhere.d.ts.map +1 -0
  42. package/dist/browser/elsewhere.js +91 -0
  43. package/dist/browser/elsewhere.js.map +1 -0
  44. package/dist/browser/frames.d.ts +85 -0
  45. package/dist/browser/frames.d.ts.map +1 -0
  46. package/dist/browser/frames.js +11 -0
  47. package/dist/browser/frames.js.map +1 -0
  48. package/dist/browser/index.d.ts +8 -0
  49. package/dist/browser/index.d.ts.map +1 -0
  50. package/dist/browser/index.js +9 -0
  51. package/dist/browser/index.js.map +1 -0
  52. package/dist/check/check.d.ts +171 -0
  53. package/dist/check/check.d.ts.map +1 -0
  54. package/dist/check/check.js +666 -0
  55. package/dist/check/check.js.map +1 -0
  56. package/dist/check/index.d.ts +3 -0
  57. package/dist/check/index.d.ts.map +1 -0
  58. package/dist/check/index.js +2 -0
  59. package/dist/check/index.js.map +1 -0
  60. package/dist/check/types.d.ts +149 -0
  61. package/dist/check/types.d.ts.map +1 -0
  62. package/dist/check/types.js +29 -0
  63. package/dist/check/types.js.map +1 -0
  64. package/dist/controls/controls.d.ts +198 -0
  65. package/dist/controls/controls.d.ts.map +1 -0
  66. package/dist/controls/controls.js +742 -0
  67. package/dist/controls/controls.js.map +1 -0
  68. package/dist/controls/dom.d.ts +108 -0
  69. package/dist/controls/dom.d.ts.map +1 -0
  70. package/dist/controls/dom.js +56 -0
  71. package/dist/controls/dom.js.map +1 -0
  72. package/dist/controls/index.d.ts +26 -0
  73. package/dist/controls/index.d.ts.map +1 -0
  74. package/dist/controls/index.js +23 -0
  75. package/dist/controls/index.js.map +1 -0
  76. package/dist/controls/rows.d.ts +66 -0
  77. package/dist/controls/rows.d.ts.map +1 -0
  78. package/dist/controls/rows.js +127 -0
  79. package/dist/controls/rows.js.map +1 -0
  80. package/dist/core/index.d.ts +3 -0
  81. package/dist/core/index.d.ts.map +1 -0
  82. package/dist/core/index.js +15 -0
  83. package/dist/core/index.js.map +1 -0
  84. package/dist/core/registry.d.ts +192 -0
  85. package/dist/core/registry.d.ts.map +1 -0
  86. package/dist/core/registry.js +2799 -0
  87. package/dist/core/registry.js.map +1 -0
  88. package/dist/core/types.d.ts +2468 -0
  89. package/dist/core/types.d.ts.map +1 -0
  90. package/dist/core/types.js +19 -0
  91. package/dist/core/types.js.map +1 -0
  92. package/dist/otel/index.d.ts +122 -0
  93. package/dist/otel/index.d.ts.map +1 -0
  94. package/dist/otel/index.js +157 -0
  95. package/dist/otel/index.js.map +1 -0
  96. package/dist/react/index.d.ts +191 -0
  97. package/dist/react/index.d.ts.map +1 -0
  98. package/dist/react/index.js +547 -0
  99. package/dist/react/index.js.map +1 -0
  100. package/dist/react/runtime.d.ts +95 -0
  101. package/dist/react/runtime.d.ts.map +1 -0
  102. package/dist/react/runtime.js +54 -0
  103. package/dist/react/runtime.js.map +1 -0
  104. package/dist/react/store.d.ts +333 -0
  105. package/dist/react/store.d.ts.map +1 -0
  106. package/dist/react/store.js +695 -0
  107. package/dist/react/store.js.map +1 -0
  108. package/dist/relay/auth.d.ts +244 -0
  109. package/dist/relay/auth.d.ts.map +1 -0
  110. package/dist/relay/auth.js +391 -0
  111. package/dist/relay/auth.js.map +1 -0
  112. package/dist/relay/frames.d.ts +141 -0
  113. package/dist/relay/frames.d.ts.map +1 -0
  114. package/dist/relay/frames.js +20 -0
  115. package/dist/relay/frames.js.map +1 -0
  116. package/dist/relay/index.d.ts +8 -0
  117. package/dist/relay/index.d.ts.map +1 -0
  118. package/dist/relay/index.js +4 -0
  119. package/dist/relay/index.js.map +1 -0
  120. package/dist/relay/relay.d.ts +277 -0
  121. package/dist/relay/relay.d.ts.map +1 -0
  122. package/dist/relay/relay.js +1026 -0
  123. package/dist/relay/relay.js.map +1 -0
  124. package/dist/relay/serve.d.ts +33 -0
  125. package/dist/relay/serve.d.ts.map +1 -0
  126. package/dist/relay/serve.js +86 -0
  127. package/dist/relay/serve.js.map +1 -0
  128. package/dist/widget/chat.d.ts +290 -0
  129. package/dist/widget/chat.d.ts.map +1 -0
  130. package/dist/widget/chat.js +486 -0
  131. package/dist/widget/chat.js.map +1 -0
  132. package/dist/widget/css.d.ts +49 -0
  133. package/dist/widget/css.d.ts.map +1 -0
  134. package/dist/widget/css.js +532 -0
  135. package/dist/widget/css.js.map +1 -0
  136. package/dist/widget/dom.d.ts +143 -0
  137. package/dist/widget/dom.d.ts.map +1 -0
  138. package/dist/widget/dom.js +27 -0
  139. package/dist/widget/dom.js.map +1 -0
  140. package/dist/widget/highlight.d.ts +64 -0
  141. package/dist/widget/highlight.d.ts.map +1 -0
  142. package/dist/widget/highlight.js +136 -0
  143. package/dist/widget/highlight.js.map +1 -0
  144. package/dist/widget/index.d.ts +9 -0
  145. package/dist/widget/index.d.ts.map +1 -0
  146. package/dist/widget/index.js +20 -0
  147. package/dist/widget/index.js.map +1 -0
  148. package/dist/widget/position.d.ts +166 -0
  149. package/dist/widget/position.d.ts.map +1 -0
  150. package/dist/widget/position.js +497 -0
  151. package/dist/widget/position.js.map +1 -0
  152. package/dist/widget/settings.d.ts +116 -0
  153. package/dist/widget/settings.d.ts.map +1 -0
  154. package/dist/widget/settings.js +117 -0
  155. package/dist/widget/settings.js.map +1 -0
  156. package/dist/widget/widget.d.ts +442 -0
  157. package/dist/widget/widget.d.ts.map +1 -0
  158. package/dist/widget/widget.js +2005 -0
  159. package/dist/widget/widget.js.map +1 -0
  160. package/package.json +144 -4
@@ -0,0 +1,824 @@
1
+ /**
2
+ * driverkit/agent — the loop.
3
+ *
4
+ * This is the other case the library is for. The relay and the MCP server
5
+ * carry verbs to an agent in another process; this one has no transport at
6
+ * all, because the page already holds the driver. The person types "find the
7
+ * Acme contacts and accept the top thousand" into a panel in the corner, and
8
+ * `drive` turns that into model turns and `driver.call()`s until the model
9
+ * answers in prose.
10
+ *
11
+ * Which makes this a loop and not a protocol. There are no frames, no ids, no
12
+ * deadline and no `WireResult`: every call lands, every call returns a
13
+ * `Result`, and every `Result` carries a snapshot. What is left to get right
14
+ * is the shape of the conversation, and there are four decisions in it that
15
+ * matter more than the code:
16
+ *
17
+ * **1. The static half is computed once, above the loop.** `system` and
18
+ * `tools` are derived from `driver.manifest()` before the first turn and never
19
+ * touched again, so they are byte-identical on every call to `think` and a
20
+ * caller can have their provider cache them. One per-turn string in there — a
21
+ * clock, a step counter, the current screen — re-prices the entire prefix on
22
+ * every turn, and the prefix is the big half. Making them `const`s outside the
23
+ * loop is the only version of this rule that cannot be broken by accident.
24
+ *
25
+ * **2. The screen goes in the newest message, never in the system prompt.** It
26
+ * is the dynamic half by definition. It enters the conversation exactly twice:
27
+ * on the person's own turn, and riding on each tool result. And it LEAVES
28
+ * again: one copy survives, the newest, and every older turn keeps its words
29
+ * or its outcome and gives up its screen. Each copy is small and ten of them
30
+ * are not, and they land in the half nothing caches — see `pruneScreens`,
31
+ * which is where the rest of that argument is.
32
+ *
33
+ * **3. One round trip per step, not two.** `Result` already carries the
34
+ * snapshot after the call, so the tool result the model reads is the outcome
35
+ * *and* the new screen. The loop never follows a verb with a read. With ten
36
+ * steps that is ten saved model turns, each of which would otherwise have
37
+ * re-read the whole prefix — and the round trips, not the manifest, are what
38
+ * actually cost money.
39
+ *
40
+ * **4. A refusal is information, not a failure.** It is fed back and the model
41
+ * is expected to adapt. The one thing that must not happen is adapting
42
+ * forever: the same verb refused the same way three times is a model that has
43
+ * stopped learning, and continuing costs the person money to watch nothing
44
+ * happen.
45
+ *
46
+ * **5. The run is watchable and interruptible, and that is a property of the
47
+ * loop rather than of a UI.** The agent is moving the screen a person is
48
+ * looking at, so going as fast as the model answers is the wrong speed: what
49
+ * the person needs is to see each step coming and have somewhere to put their
50
+ * hand. Pacing (`pace`) puts a cancellable wait before each call, run controls
51
+ * (`controls`) hold the run between calls, and the events are detailed enough
52
+ * that a step list can show a row before the call it describes has happened.
53
+ * None of it reaches the model — it is runtime state, and decision 1 is still
54
+ * the rule: nothing per-turn goes anywhere near `system` or `tools`.
55
+ */
56
+ import { paceWait, realClock } from "./control.js";
57
+ import { SLOW_MS, renderDuration, renderOutcome, renderSnapshot } from "./render.js";
58
+ import { READ_SCREEN, systemPrompt, toolsFor } from "./tools.js";
59
+ /**
60
+ * The refusal slug a vetoed commit comes back as.
61
+ *
62
+ * A new name rather than one of the core's. PROTOCOL.md reserves `stale`,
63
+ * `unknown-verb`, `bad-argument`, `unmounted`, `threw`, `no-such-tab`,
64
+ * `tab-went-away` and `timeout`; this is reserved on the same grounds and for
65
+ * the same reason. A model that cannot tell "the person said no" from "your
66
+ * arguments were wrong" will retry with different arguments, which is the one
67
+ * response that is certainly wrong — the arguments were fine and the answer
68
+ * was no.
69
+ *
70
+ * An app must not name one of its own verb refusals this.
71
+ */
72
+ export const DECLINED = "declined-by-user";
73
+ /**
74
+ * The core's cost-ceiling slug, spelled here because this file has to
75
+ * recognise it. The same arrangement as `DECLINED` above: the string is
76
+ * PROTOCOL.md's rather than either file's, and the core exports the whole
77
+ * reserved list rather than a constant per slug.
78
+ *
79
+ * Recognised and never emitted. The loop cannot run out of somebody else's
80
+ * budget on its own — only `call()` can say this — so a match here is always
81
+ * the driver talking.
82
+ */
83
+ const BUDGET_SPENT = "budget-spent";
84
+ const DECLINED_HINT = "The person was asked to confirm this and declined. Do not retry it, and do not try " +
85
+ "another verb that does the same thing. Tell them what you were about to do and ask " +
86
+ "what they would like instead.";
87
+ /**
88
+ * How a screen is introduced, and the seam pruning cuts at.
89
+ *
90
+ * A marker rather than a guess at where the rest of the turn ends. Pruning has
91
+ * to remove exactly what this file added and nothing anybody typed, and looking
92
+ * for a line this file wrote is the only way to be sure of that.
93
+ *
94
+ * Written on both kinds of turn that carry a screen — the person's own, and
95
+ * every tool result — so there is one seam and not two. A tool turn whose text
96
+ * were nothing but a screen would have no seam in it at all, which is why even
97
+ * `read_screen`, whose whole answer is the screen, gets an outcome line above
98
+ * this marker. One shape, one cut; see `pruneScreens`.
99
+ */
100
+ const SCREEN_MARK = "\n\nOn screen now:\n";
101
+ /**
102
+ * What an older turn's screen is replaced with.
103
+ *
104
+ * Replaced, not deleted. A turn that simply has no screen reads as a turn where
105
+ * the screen was empty, and "there were no contacts a moment ago" is a worse
106
+ * thing for a model to believe than "there was a screen there and you are not
107
+ * being shown it any more". On a tool result the empty reading would be worse
108
+ * still: a verb whose result showed no rows looks like a verb that emptied the
109
+ * table.
110
+ *
111
+ * One sentence for both kinds of turn, and it is deliberately short. Unlike the
112
+ * user-turn case, which happens once or twice in a conversation, this is paid
113
+ * once per pruned tool turn — so it is the one piece of boilerplate in here
114
+ * that is itself O(steps), and the only honest answer to that is to keep it to
115
+ * a line. It buys back four fifths of a screen each time it is written.
116
+ */
117
+ const STALE_NOTE = "\n\n(screen no longer shown; only the newest screen in this conversation is current)";
118
+ /**
119
+ * A tool result for a call the loop decided not to run.
120
+ *
121
+ * **Why this is not optional.** `DriveOutcome.messages` is documented as
122
+ * something a caller hands back as the next run's `history`, and every tool-use
123
+ * API — Anthropic's included — rejects a conversation in which a `tool_use`
124
+ * block has no matching result. A 3-call assistant turn that stops after the
125
+ * first call therefore does not merely lose two results: it poisons the
126
+ * widget's own conversation permanently, and the person's next question comes
127
+ * back as a 400 from then on, forever, with nothing on screen to explain it.
128
+ * One missing tool turn is a dead panel.
129
+ *
130
+ * So the answer is written for the model rather than for the protocol. It says
131
+ * plainly that the verb did not run and why, because the honest alternative — a
132
+ * blank or an "ok" — would have the model believe a commit happened and build
133
+ * its next step on it. What it must never say is anything that reads as a
134
+ * failure to retry: `stopped` and `aborted` are decisions, not errors.
135
+ */
136
+ function abandoned(call, why) {
137
+ const text = why === "aborted"
138
+ ? "not run: the person stopped this run before this call was made. Nothing happened " +
139
+ "here and nothing changed. This is not an error and must not be retried by itself."
140
+ : "not run: the run stopped at an earlier call in this same turn. Nothing happened " +
141
+ "here and nothing changed. This is not an error and must not be retried by itself.";
142
+ return { role: "tool", callId: call.id, name: call.name, text };
143
+ }
144
+ /**
145
+ * Keep exactly one screen in the conversation: the newest one, wherever it is.
146
+ *
147
+ * The rule the core states on `Snapshot` and this function exists to hold:
148
+ *
149
+ * "an agent is never shown more than the person at the keyboard. Same
150
+ * filters, same sort, same page. That is what keeps the cost flat as the
151
+ * data grows — a hundred rows on screen is a hundred rows in the prompt
152
+ * whether the table holds a hundred or a million"
153
+ *
154
+ * Flat as the data grows, and the cost of a step is what the person could see
155
+ * when it ran. A conversation holding one copy of the screen per step honours
156
+ * neither: the person at the keyboard is looking at one screen, and the prompt
157
+ * carried ten. Each copy is small, which is exactly why this went unnoticed for
158
+ * as long as it did — the leak is in the COUNT, not in the size, and it lands
159
+ * in the uncached half where every byte is paid for on every remaining turn.
160
+ *
161
+ * Both kinds of turn carry one. A user turn carries the screen as it was when
162
+ * the person spoke; a tool turn carries the screen the call left behind, which
163
+ * is the authoritative one at the moment it arrives. Each is right at the time
164
+ * and wrong a few turns later, for the same two reasons, and the second is the
165
+ * one that matters: old blocks are bytes in the uncached half paid for forever,
166
+ * and a model that reads a screen from four messages ago as current will act on
167
+ * rows that have moved. The second is a correctness problem wearing a cost
168
+ * problem's clothes — and the cure is written into `DriveOutcome.messages`
169
+ * already: a model is never shown two screens and left to work out which one is
170
+ * now true.
171
+ *
172
+ * **What survives on an older tool turn, and what a model loses.** The outcome
173
+ * line stays: `ok`, the count and its warning, `refused: <slug>` and its hint.
174
+ * That is what an old tool turn is actually consulted for — "what did my third
175
+ * call do" — and it is the half that never goes stale. What is gone is the
176
+ * table as it stood between two of the model's own calls. A model that wants it
177
+ * can call `read_screen`, which costs one round trip against ten turns of
178
+ * carrying it, and the newest screen is always in front of it untouched.
179
+ *
180
+ * **Why the newest and not the newest few.** A window of N would still grow
181
+ * with N, would need a number nobody can justify, and would put two or three
182
+ * screens of the same table in the tail with nothing but position to say which
183
+ * is live — reintroducing the misreading above at a constant factor. Keeping
184
+ * the last screen per `Snapshot.screen` id was the other candidate, and it
185
+ * fails on the same count: an app with six screens keeps six, the total grows
186
+ * with navigation rather than with steps, and `screen` is optional — so the
187
+ * bill would depend on whether an app happens to name its screens.
188
+ */
189
+ export function pruneScreens(messages) {
190
+ // The newest turn that carries a screen, of either kind. Found by looking for
191
+ // the marker rather than by role: after a call, the newest screen is on a
192
+ // tool turn and the person's own turn is as stale as any other.
193
+ let newest = -1;
194
+ for (let i = messages.length - 1; i >= 0; i--) {
195
+ const turn = messages[i];
196
+ if (turn.role === "assistant")
197
+ continue;
198
+ if (turn.text.includes(SCREEN_MARK)) {
199
+ newest = i;
200
+ break;
201
+ }
202
+ }
203
+ return messages.map((turn, i) => {
204
+ if (turn.role === "assistant" || i === newest)
205
+ return turn;
206
+ const at = turn.text.indexOf(SCREEN_MARK);
207
+ if (at === -1)
208
+ return turn;
209
+ // Everything before the marker is kept verbatim, which on a tool turn is
210
+ // the outcome line and on a user turn is what the person typed. Spread
211
+ // rather than rebuilt, so a tool turn keeps the `callId` its `tool_use`
212
+ // is answering: pruning rewrites text and never removes or re-pairs a
213
+ // turn, which is what makes it safe to do to something a caller will hand
214
+ // back as `history`. See `abandoned`.
215
+ return { ...turn, text: turn.text.slice(0, at) + STALE_NOTE };
216
+ });
217
+ }
218
+ /**
219
+ * Run the loop until the model answers, or a bound stops it.
220
+ *
221
+ * ```ts
222
+ * const out = await drive(driver, {
223
+ * // No model client in this package. The browser cannot hold a key, so the
224
+ * // realistic shape is a call to your own backend, which already knows who
225
+ * // the person is.
226
+ * think: backendThink("/api/chat"),
227
+ * task: "find the Acme contacts and accept the top thousand",
228
+ * // Opt-in here; mountWidget turns it on by default. See onBeforeCommit.
229
+ * onBeforeCommit: ({ verb, snapshot }) =>
230
+ * confirm(`${verb.describe}\n\n${snapshot.selected?.length ?? 0} selected. Go ahead?`),
231
+ * });
232
+ * out.stop; // "answered" | "max-steps" | "aborted" | "stuck" | "over-budget" | "silent"
233
+ * ```
234
+ */
235
+ export async function drive(driver, options) {
236
+ const manifest = driver.manifest();
237
+ // The static half. Computed here, used unchanged on every turn below. See
238
+ // decision 1 in the file comment, and `the system prompt is byte-identical
239
+ // across turns` in the tests, which asserts it rather than trusting it.
240
+ const timing = options.timing ?? "off";
241
+ // The note about what a `took:` line means goes in the CACHED half, once,
242
+ // and the per-call line is then four words. The alternative -- a sentence of
243
+ // guidance beside every duration, the way `count` carries `COUNT_NOTE` --
244
+ // would be the one piece of boilerplate in a turn that is O(calls), for a
245
+ // number that needs explaining once. `systemPrompt` stays a pure function of
246
+ // its arguments and therefore still byte-identical across every turn of the
247
+ // run, which is the property the prefix cache is built on.
248
+ const system = systemPrompt(manifest, options.instructions, timing);
249
+ const tools = toolsFor(manifest);
250
+ const verbs = new Map(manifest.verbs.map((v) => [v.name, v]));
251
+ const maxSteps = options.maxSteps ?? 12;
252
+ const refusalLimit = options.refusalLimit ?? 3;
253
+ const signal = options.signal;
254
+ const controls = options.controls;
255
+ const clock = options.clock ?? realClock;
256
+ // The run's `pace` option is the initial value and the controls own it from
257
+ // then on, which is what makes `controls.pace()` live. Seeded only when the
258
+ // option was actually given, so a caller who set the pace on the controls and
259
+ // left the option out keeps theirs instead of being reset to 0.
260
+ if (controls && options.pace !== undefined)
261
+ controls.pace(options.pace);
262
+ // Read fresh before every wait when there are controls — the whole point —
263
+ // and fixed for the run when there are none. 0 by default, so a headless
264
+ // `drive` is not slowed down by a feature that exists for somebody watching;
265
+ // `mountWidget` passes `WATCHABLE_PACE`. See `pace`.
266
+ const pace = controls ? () => controls.paceMs : (options.pace ?? 0);
267
+ // Named once rather than written inline, so the wait and the loop cannot come
268
+ // to disagree about whether a pace change is being listened for.
269
+ const watchPace = controls ? (listener) => controls.subscribe(listener) : undefined;
270
+ let messages = [...(options.history ?? [])];
271
+ // How many times each (verb, refusal slug) pair has come back. The loop
272
+ // detector; see decision 4.
273
+ const refusals = new Map();
274
+ if (options.task !== undefined) {
275
+ // The person's words and the screen they are looking at, in one turn.
276
+ //
277
+ // Together on purpose: this is the newest message at the moment it is
278
+ // sent, which is where the dynamic half belongs, and it saves the model
279
+ // spending its first step on a `read_screen` whose answer we already have
280
+ // in hand. "Accept the top thousand" is also not interpretable without
281
+ // knowing what is on screen — the screen is half of what was said.
282
+ messages.push({
283
+ role: "user",
284
+ text: `${options.task}${SCREEN_MARK}${renderSnapshot(driver.snapshot())}`,
285
+ });
286
+ }
287
+ // Lossy on purpose, and worth stating: a caller that wanted a verbatim
288
+ // transcript of what the model was shown does not get one from here. The
289
+ // alternative is paying for every screen the conversation ever had, on every
290
+ // turn, so that nothing is lost — and nobody reads those bytes.
291
+ //
292
+ // Called below, before every `think` and once on the way out, rather than
293
+ // once here. Once here was enough while only user turns carried screens,
294
+ // because a run adds at most one of those; tool turns are added by the loop
295
+ // itself, one per call, so the newest screen moves on every step and the
296
+ // pruning has to move with it. Running it before each turn also keeps the
297
+ // `messages` handed back already pruned, so a conversation carried across
298
+ // many runs does not re-accumulate what this just removed.
299
+ let steps = 0;
300
+ let text;
301
+ let stop = "max-steps";
302
+ // Mirrored here rather than read off `controls` when wanted, because the
303
+ // event is about *transitions* and because `awaiting-approval` is a state
304
+ // only this loop knows it is in. Reported, never consulted: nothing below
305
+ // branches on it, so a bug in here can make a UI say the wrong word and
306
+ // cannot make the run do the wrong thing.
307
+ let state = controls?.state ?? "running";
308
+ const mark = (next) => {
309
+ if (next === state)
310
+ return;
311
+ state = next;
312
+ options.onControl?.({ step: steps, state: next });
313
+ };
314
+ // Fired unconditionally, including for a run with no controls, so a UI has a
315
+ // defined starting state instead of having to assume one. `step: 0` — no
316
+ // model turn has been spent yet.
317
+ options.onControl?.({ step: 0, state });
318
+ /** Hold if the controls say to, announcing the hold so a UI can show it.
319
+ *
320
+ * Asking `controls.state` first rather than timing the `gate` call: a UI
321
+ * that flashed "paused" for every call of an unpaused run would be noise,
322
+ * and the condition for actually holding is knowable up front. */
323
+ const hold = async (what) => {
324
+ if (!controls)
325
+ return;
326
+ if (controls.state === "paused" && controls.permits === 0)
327
+ mark("paused");
328
+ await controls.gate(what, signal);
329
+ // Before `mark("running")`, so a run stopped while held is not reported as
330
+ // having resumed on its way out. The caller breaks on the abort next.
331
+ if (signal?.aborted)
332
+ return;
333
+ mark("running");
334
+ };
335
+ for (;;) {
336
+ if (signal?.aborted) {
337
+ stop = "aborted";
338
+ break;
339
+ }
340
+ if (steps >= maxSteps) {
341
+ stop = "max-steps";
342
+ break;
343
+ }
344
+ // Before `steps++` and before `onStep`, which is the honest order: a held
345
+ // run has not started a step, and a model round trip is the expensive
346
+ // thing a pause is most worth having in front of.
347
+ await hold("think");
348
+ if (signal?.aborted) {
349
+ stop = "aborted";
350
+ break;
351
+ }
352
+ steps++;
353
+ options.onStep?.({ step: steps });
354
+ // Here, not after the pushes below: this is the last moment before the
355
+ // tail is handed to the model, so "the newest screen" means the newest at
356
+ // the instant it is read. Idempotent, so running it on every turn costs a
357
+ // scan of a short array and cannot double-cut anything.
358
+ messages = pruneScreens(messages);
359
+ // `messages.slice()` and not `messages`. A `think` that is a fetch will
360
+ // serialise this and forget it, but one that is a scripted fake, a
361
+ // recorder or a middleware will keep the array, and handing out the live
362
+ // one means a later push mutates something a caller believes it owns.
363
+ const thought = await options.think({
364
+ system,
365
+ tools,
366
+ messages: messages.slice(),
367
+ // Spread rather than passed as `signal: undefined`. `ThinkInput.signal`
368
+ // is optional, and under `exactOptionalPropertyTypes` an explicit
369
+ // `undefined` is a different thing from an absent field — a `think` that
370
+ // checks `"signal" in input` would see one that is not there.
371
+ ...(signal ? { signal } : {}),
372
+ });
373
+ const calls = thought.calls ?? [];
374
+ messages.push({
375
+ role: "assistant",
376
+ ...(thought.text ? { text: thought.text } : {}),
377
+ ...(calls.length ? { calls } : {}),
378
+ });
379
+ if (thought.text) {
380
+ text = thought.text;
381
+ options.onSay?.({ step: steps, text: thought.text });
382
+ }
383
+ if (calls.length === 0) {
384
+ // The only ending the model chooses. Prose with no call is an answer;
385
+ // nothing at all is a broken adapter, and is worth distinguishing so
386
+ // that whoever wrote `think` is told which of the two happened.
387
+ stop = thought.text ? "answered" : "silent";
388
+ break;
389
+ }
390
+ // Checked after `think` as well as before it, because `think` is the slow
391
+ // part of a step and is exactly where a person clicks the stop button. The
392
+ // model's calls are abandoned unrun: an abort that still commits is not an
393
+ // abort.
394
+ if (signal?.aborted) {
395
+ // Every one of the model's calls is abandoned, and every one of them
396
+ // still gets an answer: see `abandoned`. The assistant turn carrying them
397
+ // is already in `messages`, and a `tool_use` with no result makes the
398
+ // whole conversation unusable.
399
+ for (const call of calls)
400
+ messages.push(abandoned(call, "aborted"));
401
+ stop = "aborted";
402
+ break;
403
+ }
404
+ let stuck = false;
405
+ let aborted = false;
406
+ /** Set by the first `budget-spent`. Separate from `stuck` because the two
407
+ * say different things to the person watching; see `StopReason`. */
408
+ let spent = false;
409
+ /** Calls the loop decided not to run. Each one still owes the model a
410
+ * result; see `abandoned`. */
411
+ let unrun = [];
412
+ for (let i = 0; i < calls.length; i++) {
413
+ const call = calls[i];
414
+ // Re-checked inside the fan-out. A model may emit several calls in one
415
+ // turn, and if the person stops the run halfway through them the rest
416
+ // must not run — the second of three verbs is the worst place to be
417
+ // interrupted and the only way to be sure is to look before each one.
418
+ if (signal?.aborted) {
419
+ aborted = true;
420
+ unrun = calls.slice(i);
421
+ break;
422
+ }
423
+ const verb = verbs.get(call.name);
424
+ const kind = verb?.kind;
425
+ // `at` rides along with `kind`, from the manifest, untouched. Nothing in
426
+ // this loop reads it and nothing ever should: it is a hint for whoever is
427
+ // drawing the run, and driverkit resolving a selector would be the one
428
+ // thing the library promises not to do. See `Verb.at` in the core.
429
+ const event = {
430
+ step: steps,
431
+ call,
432
+ ...(kind === undefined ? {} : { kind }),
433
+ ...(verb?.at === undefined ? {} : { at: verb.at }),
434
+ index: i,
435
+ of: calls.length,
436
+ };
437
+ // Before the pacing and before any hold, so the row for this call can be
438
+ // on screen and glowing while the person still has time to stop it. The
439
+ // ordering is the whole point of the event; see `onBeforeCall`.
440
+ //
441
+ // A copy per listener, like `messages.slice()` above: three events
442
+ // describe one call, and one of them mutating the object would quietly
443
+ // rewrite what the other two were told.
444
+ options.onBeforeCall?.({ ...event });
445
+ // Then the pace, then the gate, in that order. Pacing first so that a
446
+ // person who pauses and then resumes gets the next call immediately
447
+ // instead of sitting through a wait whose job — giving them time to
448
+ // react — they have already done by hand.
449
+ await paceWait({
450
+ ms: pace,
451
+ clock,
452
+ ...(signal ? { signal } : {}),
453
+ ...(watchPace ? { watch: watchPace } : {}),
454
+ });
455
+ if (signal?.aborted) {
456
+ aborted = true;
457
+ unrun = calls.slice(i);
458
+ break;
459
+ }
460
+ await hold("call");
461
+ // The abort wins over the hold. A paused run that could not be stopped
462
+ // would be the worst version of this feature: the person presses stop and
463
+ // the loop is parked on a promise nobody is going to resolve.
464
+ if (signal?.aborted) {
465
+ aborted = true;
466
+ unrun = calls.slice(i);
467
+ break;
468
+ }
469
+ options.onCall?.({ ...event });
470
+ const outcome = await runOne(driver, call, verb, options, mark, timing, clock);
471
+ // The two halves, joined with the pruning seam between them. A call that
472
+ // reached no screen at all — an unknown tool name — gets no marker and
473
+ // no screen, which is the one honest shape for it: a marker followed by
474
+ // nothing would say the screen was empty.
475
+ const screened = (head) => outcome.screen === undefined ? head : head + SCREEN_MARK + outcome.screen;
476
+ options.onResult?.({
477
+ ...event,
478
+ result: outcome.result,
479
+ text: screened(outcome.head),
480
+ });
481
+ // The outcome line only. The screen is appended last, below, so that
482
+ // anything else this loop has to say about the call sits ABOVE the seam
483
+ // and survives pruning — the refusal-limit note in particular, which is
484
+ // written for a caller resuming this conversation later and would be the
485
+ // first thing cut if it were appended after the screen.
486
+ let body = outcome.head;
487
+ if (outcome.result && !outcome.result.ok && outcome.result.refused === BUDGET_SPENT) {
488
+ // Before the refusal counter and not through it. `refusalLimit` exists
489
+ // to notice a model repeating a mistake, and this is not a mistake the
490
+ // model made or can fix — the ceiling was set by whoever mounted the
491
+ // app. Letting it accumulate would spend two more model round trips to
492
+ // reach a conclusion the first refusal already stated, and spend them
493
+ // against the budget that has just run out.
494
+ //
495
+ // The app's own hint is already in the tool turn, which matters for a
496
+ // caller who resumes this conversation later: the transcript says which
497
+ // ceiling and that it does not refill.
498
+ body +=
499
+ `\n\n(stopped: this app's spend ceiling is reached. It does not refill, and no ` +
500
+ `other verb will run either. Say what got through and what is left.)`;
501
+ spent = true;
502
+ }
503
+ else if (outcome.result && !outcome.result.ok) {
504
+ const key = `${call.name}:${outcome.result.refused}`;
505
+ const seen = (refusals.get(key) ?? 0) + 1;
506
+ refusals.set(key, seen);
507
+ if (seen >= refusalLimit) {
508
+ // The note is appended to the tool result rather than replacing it,
509
+ // so the transcript a caller keeps reads as what actually happened.
510
+ // The model never gets a chance to act on it — that is the point —
511
+ // but a caller resuming this conversation later hands the model a
512
+ // history in which the reason for the gap is written down.
513
+ body +=
514
+ `\n\n(stopped: \`${call.name}\` has now been refused \`${outcome.result.refused}\` ` +
515
+ `${seen} times. Repeating it will not work. Say what is in the way.)`;
516
+ stuck = true;
517
+ }
518
+ }
519
+ messages.push({ role: "tool", callId: call.id, name: call.name, text: screened(body) });
520
+ if (stuck || spent) {
521
+ unrun = calls.slice(i + 1);
522
+ break;
523
+ }
524
+ }
525
+ // The fan-out is never left half-answered. See `abandoned`: this is the
526
+ // difference between a conversation a caller can hand back as `history`
527
+ // and one that makes every later `ask()` fail with a 400.
528
+ for (const call of unrun)
529
+ messages.push(abandoned(call, aborted ? "aborted" : "stopped"));
530
+ if (aborted) {
531
+ stop = "aborted";
532
+ break;
533
+ }
534
+ // Before `stuck`, which it cannot be at the same time -- the two are set in
535
+ // exclusive branches -- and first anyway, because a budget is the wider
536
+ // fact: `stuck` is about one verb and this is about the whole app.
537
+ if (spent) {
538
+ stop = "over-budget";
539
+ break;
540
+ }
541
+ if (stuck) {
542
+ stop = "stuck";
543
+ break;
544
+ }
545
+ }
546
+ // Again on the way out, because the last thing a run does is often to push
547
+ // tool turns nobody will `think` about — a fan-out's results, or the
548
+ // `abandoned` answers after a stop. Without this the array handed back would
549
+ // carry every screen from that final turn, and a caller passing it as
550
+ // `history` would be billed for them until the next run's first prune.
551
+ messages = pruneScreens(messages);
552
+ options.onStop?.({ stop, steps, ...(text === undefined ? {} : { text }) });
553
+ return { stop, steps, messages, ...(text === undefined ? {} : { text }) };
554
+ }
555
+ /** The sentinel `readRev` returns for a `rev` that was sent and cannot be
556
+ * honoured. A distinct value because `undefined` already means something
557
+ * load-bearing here — "no rev was sent, so do not check staleness" — and
558
+ * collapsing the two is exactly the bug. */
559
+ const BAD_REV = Symbol("bad-rev");
560
+ /**
561
+ * The `rev` a model sent, as a number, or `BAD_REV`.
562
+ *
563
+ * A model answering `{"rev": "9"}` is not a model making a mistake: tool
564
+ * arguments arrive as JSON generated by a language model, and a string where a
565
+ * number was asked for is ordinary behaviour from every vendor. A clean
566
+ * integer-valued string is the same claim as the integer, so it is honoured.
567
+ *
568
+ * Everything else is refused rather than coerced. `"3.7"`, `"abc"`, `""` and
569
+ * `true` are not claims about a rev, they are evidence the model did not read
570
+ * one off the screen — and `Number("")` being `0` and `Number(true)` being `1`
571
+ * is precisely how a permissive coercion turns that into a confident claim
572
+ * about a screen that never existed.
573
+ *
574
+ * `null` is treated as absent, matching `checkArg`: a vendor serialising an
575
+ * omitted optional field as `null` has said nothing, not something wrong.
576
+ */
577
+ function readRev(raw) {
578
+ if (raw === undefined || raw === null)
579
+ return undefined;
580
+ if (typeof raw === "number")
581
+ return Number.isInteger(raw) ? raw : BAD_REV;
582
+ if (typeof raw === "boolean")
583
+ return BAD_REV;
584
+ const text = raw.trim();
585
+ if (!/^[+-]?\d+$/.test(text))
586
+ return BAD_REV;
587
+ const n = Number(text);
588
+ return Number.isSafeInteger(n) ? n : BAD_REV;
589
+ }
590
+ /**
591
+ * The `screen` a model sent, as a string, or `BAD_REV`.
592
+ *
593
+ * The same shape as `readRev`, and for the same reason: a safety check that
594
+ * silently disables itself when its argument arrives in the wrong type is worse
595
+ * than no check, because the transcript then reads `ok` for a call made against
596
+ * a screen the model never saw. A number or a boolean is not a screen id, it is
597
+ * evidence the model did not read one off a screen, so it is refused rather
598
+ * than dropped. An empty string is refused too: `""` is not the same claim as
599
+ * leaving the field out, which is "I make none".
600
+ *
601
+ * `null` is absent, matching `checkArg` and `readRev`: a vendor serialising an
602
+ * omitted optional field as `null` has said nothing, not something wrong.
603
+ */
604
+ function readScreen(raw) {
605
+ if (raw === undefined || raw === null)
606
+ return undefined;
607
+ if (typeof raw !== "string")
608
+ return BAD_REV;
609
+ const text = raw.trim();
610
+ return text ? text : BAD_REV;
611
+ }
612
+ /**
613
+ * One tool call: resolve it, maybe gate it, run it, render it.
614
+ *
615
+ * `result` is null when nothing was called on the driver — `read_screen`, or a
616
+ * name the manifest does not have. A caller's `onResult` uses that to tell "a
617
+ * verb ran" from "the model looked" when drawing its trace.
618
+ *
619
+ * The rendering comes back in two pieces rather than one string, and the
620
+ * caller joins them. `head` is the outcome and keeps its meaning forever;
621
+ * `screen` is the block that is current for one turn and is dropped from the
622
+ * turn after. Joining them here would mean the loop had to find the seam again
623
+ * by searching the text it just built. `screen` is absent only for a call that
624
+ * reached no screen at all.
625
+ */
626
+ async function runOne(driver, call, verb, options,
627
+ /** Report the run's state. Used for exactly one thing: saying that the run is
628
+ * parked in front of a person's confirmation, which is a wait the run
629
+ * controls do not own and a panel showing "running" would misdescribe. */
630
+ mark,
631
+ /** `DriveOptions.timing`, already defaulted by the caller. */
632
+ timing,
633
+ /** The run's clock, so a suite that pins `now` gets a byte-exact transcript
634
+ * out of a timed run. See `renderDuration` on why buckets are for
635
+ * production and an injected clock is for determinism. */
636
+ clock) {
637
+ if (call.name === READ_SCREEN && verb === undefined) {
638
+ // `verb === undefined` so an app that genuinely declares a verb by this
639
+ // name keeps it. The app's meaning wins over ours, the same way it does
640
+ // for the hoisted `rev`.
641
+ // `ok` above the screen, where a verb's outcome goes. The screen is the
642
+ // whole answer here and the line says nothing a model did not know — it is
643
+ // there so that this turn has the same two-part shape as every other turn
644
+ // carrying a screen, and therefore a seam to cut at when it goes stale. A
645
+ // tool turn that was nothing but a screen was the one kind pruning could
646
+ // not touch, and `read_screen` is the call whose turn is pure screen.
647
+ return { result: null, head: "ok", screen: renderSnapshot(driver.snapshot()) };
648
+ }
649
+ if (verb === undefined) {
650
+ // Named, not counted. A model asked for a tool that does not exist, and
651
+ // listing the real names is how the fix happens on the next turn rather
652
+ // than after another read — the same reason the core lists them on
653
+ // `unknown-verb`.
654
+ const known = [...driver.manifest().verbs.map((v) => v.name), READ_SCREEN].sort().join(", ");
655
+ // No screen: nothing was called, so there is no post-call screen to show,
656
+ // and the newest one is already in the conversation a turn above.
657
+ return { result: null, head: `no such tool \`${call.name}\`. available: ${known}` };
658
+ }
659
+ // `rev` is ours unless the verb claimed the name, in which case it is an
660
+ // ordinary argument and goes through untouched. Mirrors the MCP server.
661
+ const args = { ...call.args };
662
+ // NEITHER CLAIM IS OFFERED ON AN `ask`, AND NEITHER IS HONOURED HERE.
663
+ //
664
+ // `verbTool` leaves both properties off a question's schema -- a question
665
+ // acts on no screen, so there is nothing for it to be stale about -- and this
666
+ // is the other half of that. A model volunteering a `rev` it was told to
667
+ // quote would otherwise have its question refused `stale` because the person
668
+ // clicked a row while it was being composed, which is the likeliest thing in
669
+ // the world when they are sitting right there, and a question refused for a
670
+ // reason that has nothing to do with the question teaches a model not to ask.
671
+ // So the keys are dropped: not hoisted into a claim, and not left behind to
672
+ // become an argument the core has never heard of. Mirrors the MCP server.
673
+ const asking = verb.kind === "ask";
674
+ if (asking) {
675
+ delete args.rev;
676
+ delete args.screen;
677
+ }
678
+ let rev;
679
+ if (!asking && !(verb.args && "rev" in verb.args)) {
680
+ const raw = args.rev;
681
+ delete args.rev;
682
+ const hoisted = readRev(raw);
683
+ if (hoisted === BAD_REV) {
684
+ // Refused, never dropped. This is the whole bug: `rev` undefined is read
685
+ // by the core as "opt out of the staleness check", so a model answering
686
+ // `{"rev": "9"}` — ordinary behaviour from every vendor — used to turn
687
+ // the check off instead of using it. A safety check that silently
688
+ // disables itself on a type coercion is worse than no check, because the
689
+ // transcript then shows `ok` for a call that acted on a screen the model
690
+ // never saw.
691
+ //
692
+ // `bad-argument` and not `stale`: nothing is known about the screen here,
693
+ // only about the call. It is shaped as a real `Result` so the renderer,
694
+ // `onResult` and the loop detector treat it like any other refusal —
695
+ // a model that keeps sending junk revs hits the refusal limit.
696
+ const snapshot = driver.snapshot();
697
+ const result = {
698
+ ok: false,
699
+ refused: "bad-argument",
700
+ hint: `\`rev\` must be the whole number printed on the screen you are acting on, like ` +
701
+ `${snapshot.rev}. Got ${JSON.stringify(raw)}. Read the screen and quote its rev, or ` +
702
+ `leave \`rev\` out entirely.`,
703
+ snapshot,
704
+ };
705
+ return { result, head: renderOutcome(result), screen: renderSnapshot(result.snapshot) };
706
+ }
707
+ rev = hoisted;
708
+ }
709
+ // `screen` is hoisted exactly like `rev`, down to the app keeping the name if
710
+ // it declared one: `go(screen)` is a real verb in a real app, and the app's
711
+ // meaning wins over ours.
712
+ let screen;
713
+ if (!asking && !(verb.args && "screen" in verb.args)) {
714
+ const raw = args.screen;
715
+ delete args.screen;
716
+ const hoisted = readScreen(raw);
717
+ if (hoisted === BAD_REV) {
718
+ const snapshot = driver.snapshot();
719
+ const result = {
720
+ ok: false,
721
+ refused: "bad-argument",
722
+ hint: "`screen` must be the id printed on the `screen` line of the screen you are " +
723
+ `acting on${snapshot.screen ? `, like \`${snapshot.screen}\`` : ""}. Got ` +
724
+ `${JSON.stringify(raw)}. Read the screen and quote it, or leave \`screen\` out ` +
725
+ "entirely.",
726
+ snapshot,
727
+ };
728
+ return { result, head: renderOutcome(result), screen: renderSnapshot(result.snapshot) };
729
+ }
730
+ screen = hoisted;
731
+ }
732
+ // `plan` is hoisted on the same terms as `rev` and `screen` — the app keeps
733
+ // the name if it declared an argument by it — with one difference: it is
734
+ // taken off the args only for a verb that declares `consumes`, because that
735
+ // is the only verb the tool schema offered it on, so on any other verb a
736
+ // `plan` key is an argument the app named or a mistake the core should see.
737
+ //
738
+ // Not coerced and not refused on a bad type, which is where this parts
739
+ // company with `readRev` and `readScreen`. Those two refuse a wrong type
740
+ // because `undefined` means "skip the check" and a silent drop would turn a
741
+ // safety claim off. Here the opposite is true: the check is mandatory, so a
742
+ // token that is missing, blank or not a string all arrive at the core and all
743
+ // come back as `stale-plan` — which is the refusal that explains the pairing.
744
+ // Inventing a `bad-argument` here would answer a smaller question with a
745
+ // worse hint.
746
+ let plan;
747
+ if (verb.consumes === "plan" && !(verb.args && "plan" in verb.args)) {
748
+ const raw = args.plan;
749
+ delete args.plan;
750
+ if (typeof raw === "string" && raw.trim())
751
+ plan = raw.trim();
752
+ }
753
+ if (verb.kind === "commit" && options.onBeforeCommit) {
754
+ const snapshot = driver.snapshot();
755
+ let decision;
756
+ mark("awaiting-approval");
757
+ try {
758
+ decision = await options.onBeforeCommit({ name: verb.name, args, verb, snapshot });
759
+ }
760
+ catch (err) {
761
+ // A host's confirmation UI throwing must not take the run down, and it
762
+ // must not be read as consent either. A failed ask is a no.
763
+ decision = `the confirmation could not be shown (${err instanceof Error ? err.message : String(err)})`;
764
+ }
765
+ finally {
766
+ // In a `finally` so a confirmation UI that throws cannot leave a panel
767
+ // claiming forever that it is waiting for an answer nobody is being
768
+ // asked for. The run carries on either way — a failed ask is a no.
769
+ mark("running");
770
+ }
771
+ if (decision === false || typeof decision === "string") {
772
+ // Shaped as a real `Result`, so the renderer, `onResult` and the loop
773
+ // detector all treat it like any other refusal. The veto reaches the
774
+ // model as a refusal rather than a crash, which is the difference
775
+ // between "you declined that, shall I narrow it first?" and a panel
776
+ // that stops responding.
777
+ const result = {
778
+ ok: false,
779
+ refused: DECLINED,
780
+ hint: typeof decision === "string" ? decision : DECLINED_HINT,
781
+ snapshot,
782
+ };
783
+ return { result, head: renderOutcome(result), screen: renderSnapshot(result.snapshot) };
784
+ }
785
+ }
786
+ // The clock brackets `driver.call()` and nothing else. Everything this loop
787
+ // does before this point -- the pace wait, a `controls` hold, the
788
+ // `onBeforeCommit` dialog above -- is already outside it, which is why the
789
+ // honest figure falls out of WHERE the measurement is taken rather than out
790
+ // of arithmetic afterwards. Read only when a duration is going to be
791
+ // rendered: an untimed run reads no clock, exactly as it did before.
792
+ // `clock.now?.()` and never a detached `clock.now ?? Date.now`. A `Clock` is
793
+ // an interface and an implementation is free to be a class -- the test suite's
794
+ // own fake is one, reading a `#private` field -- so a method pulled off the
795
+ // object and called bare loses its receiver and throws. `paceWait` calls it
796
+ // the same way for the same reason.
797
+ const now = () => clock.now?.() ?? Date.now();
798
+ const started = timing === "off" ? 0 : now();
799
+ // The person-wait counter before, and again after, so a gate that lives
800
+ // INSIDE `driver.call()` is subtracted. See `DriveOptions.waited`.
801
+ const waitedBefore = timing === "off" ? 0 : (options.waited?.() ?? 0);
802
+ const result = await driver.call(verb.name, args, {
803
+ ...(rev === undefined ? {} : { rev }),
804
+ ...(screen === undefined ? {} : { screen }),
805
+ ...(plan === undefined ? {} : { plan }),
806
+ });
807
+ let head = renderOutcome(result);
808
+ if (timing !== "off") {
809
+ // `Math.max(0, ...)` because `waited` is reported by a host and a host that
810
+ // reports more wait than the call took is a host with a bug -- in which
811
+ // case the floor is zero and the line is simply omitted rather than a
812
+ // negative duration being put in front of a model.
813
+ const waited = Math.max(0, (options.waited?.() ?? 0) - waitedBefore);
814
+ const line = renderDuration(Math.max(0, now() - started - waited), timing === "slow" ? SLOW_MS : 0);
815
+ // Appended to the OUTCOME half, above the screen seam, so it survives
816
+ // `pruneScreens`. That is the right half on its merits and not only for
817
+ // thrift: "how long did my third call take" is a question whose answer
818
+ // stays true forever, like `ok` and like the count, and unlike the table.
819
+ if (line)
820
+ head += `\n${line}`;
821
+ }
822
+ return { result, head, screen: renderSnapshot(result.snapshot) };
823
+ }
824
+ //# sourceMappingURL=loop.js.map