driverkit 0.0.0-stage → 0.1.0

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 (159) hide show
  1. package/CONTROLS.md +578 -0
  2. package/README.md +104 -2
  3. package/dist/agent/backend.d.ts +69 -0
  4. package/dist/agent/backend.d.ts.map +1 -0
  5. package/dist/agent/backend.js +130 -0
  6. package/dist/agent/backend.js.map +1 -0
  7. package/dist/agent/control.d.ts +148 -0
  8. package/dist/agent/control.d.ts.map +1 -0
  9. package/dist/agent/control.js +342 -0
  10. package/dist/agent/control.js.map +1 -0
  11. package/dist/agent/index.d.ts +9 -0
  12. package/dist/agent/index.d.ts.map +1 -0
  13. package/dist/agent/index.js +6 -0
  14. package/dist/agent/index.js.map +1 -0
  15. package/dist/agent/loop.d.ts +136 -0
  16. package/dist/agent/loop.d.ts.map +1 -0
  17. package/dist/agent/loop.js +824 -0
  18. package/dist/agent/loop.js.map +1 -0
  19. package/dist/agent/render.d.ts +173 -0
  20. package/dist/agent/render.d.ts.map +1 -0
  21. package/dist/agent/render.js +425 -0
  22. package/dist/agent/render.js.map +1 -0
  23. package/dist/agent/tools.d.ts +138 -0
  24. package/dist/agent/tools.d.ts.map +1 -0
  25. package/dist/agent/tools.js +622 -0
  26. package/dist/agent/tools.js.map +1 -0
  27. package/dist/agent/types.d.ts +566 -0
  28. package/dist/agent/types.d.ts.map +1 -0
  29. package/dist/agent/types.js +32 -0
  30. package/dist/agent/types.js.map +1 -0
  31. package/dist/browser/budget.d.ts +92 -0
  32. package/dist/browser/budget.d.ts.map +1 -0
  33. package/dist/browser/budget.js +151 -0
  34. package/dist/browser/budget.js.map +1 -0
  35. package/dist/browser/connect.d.ts +368 -0
  36. package/dist/browser/connect.d.ts.map +1 -0
  37. package/dist/browser/connect.js +1038 -0
  38. package/dist/browser/connect.js.map +1 -0
  39. package/dist/browser/elsewhere.d.ts +89 -0
  40. package/dist/browser/elsewhere.d.ts.map +1 -0
  41. package/dist/browser/elsewhere.js +91 -0
  42. package/dist/browser/elsewhere.js.map +1 -0
  43. package/dist/browser/frames.d.ts +85 -0
  44. package/dist/browser/frames.d.ts.map +1 -0
  45. package/dist/browser/frames.js +11 -0
  46. package/dist/browser/frames.js.map +1 -0
  47. package/dist/browser/index.d.ts +8 -0
  48. package/dist/browser/index.d.ts.map +1 -0
  49. package/dist/browser/index.js +9 -0
  50. package/dist/browser/index.js.map +1 -0
  51. package/dist/check/check.d.ts +171 -0
  52. package/dist/check/check.d.ts.map +1 -0
  53. package/dist/check/check.js +666 -0
  54. package/dist/check/check.js.map +1 -0
  55. package/dist/check/index.d.ts +3 -0
  56. package/dist/check/index.d.ts.map +1 -0
  57. package/dist/check/index.js +2 -0
  58. package/dist/check/index.js.map +1 -0
  59. package/dist/check/types.d.ts +149 -0
  60. package/dist/check/types.d.ts.map +1 -0
  61. package/dist/check/types.js +29 -0
  62. package/dist/check/types.js.map +1 -0
  63. package/dist/controls/controls.d.ts +198 -0
  64. package/dist/controls/controls.d.ts.map +1 -0
  65. package/dist/controls/controls.js +742 -0
  66. package/dist/controls/controls.js.map +1 -0
  67. package/dist/controls/dom.d.ts +108 -0
  68. package/dist/controls/dom.d.ts.map +1 -0
  69. package/dist/controls/dom.js +56 -0
  70. package/dist/controls/dom.js.map +1 -0
  71. package/dist/controls/index.d.ts +26 -0
  72. package/dist/controls/index.d.ts.map +1 -0
  73. package/dist/controls/index.js +23 -0
  74. package/dist/controls/index.js.map +1 -0
  75. package/dist/controls/rows.d.ts +66 -0
  76. package/dist/controls/rows.d.ts.map +1 -0
  77. package/dist/controls/rows.js +127 -0
  78. package/dist/controls/rows.js.map +1 -0
  79. package/dist/core/index.d.ts +3 -0
  80. package/dist/core/index.d.ts.map +1 -0
  81. package/dist/core/index.js +15 -0
  82. package/dist/core/index.js.map +1 -0
  83. package/dist/core/registry.d.ts +192 -0
  84. package/dist/core/registry.d.ts.map +1 -0
  85. package/dist/core/registry.js +2799 -0
  86. package/dist/core/registry.js.map +1 -0
  87. package/dist/core/types.d.ts +2468 -0
  88. package/dist/core/types.d.ts.map +1 -0
  89. package/dist/core/types.js +19 -0
  90. package/dist/core/types.js.map +1 -0
  91. package/dist/otel/index.d.ts +122 -0
  92. package/dist/otel/index.d.ts.map +1 -0
  93. package/dist/otel/index.js +157 -0
  94. package/dist/otel/index.js.map +1 -0
  95. package/dist/react/index.d.ts +191 -0
  96. package/dist/react/index.d.ts.map +1 -0
  97. package/dist/react/index.js +547 -0
  98. package/dist/react/index.js.map +1 -0
  99. package/dist/react/runtime.d.ts +95 -0
  100. package/dist/react/runtime.d.ts.map +1 -0
  101. package/dist/react/runtime.js +54 -0
  102. package/dist/react/runtime.js.map +1 -0
  103. package/dist/react/store.d.ts +333 -0
  104. package/dist/react/store.d.ts.map +1 -0
  105. package/dist/react/store.js +695 -0
  106. package/dist/react/store.js.map +1 -0
  107. package/dist/relay/auth.d.ts +244 -0
  108. package/dist/relay/auth.d.ts.map +1 -0
  109. package/dist/relay/auth.js +391 -0
  110. package/dist/relay/auth.js.map +1 -0
  111. package/dist/relay/frames.d.ts +141 -0
  112. package/dist/relay/frames.d.ts.map +1 -0
  113. package/dist/relay/frames.js +20 -0
  114. package/dist/relay/frames.js.map +1 -0
  115. package/dist/relay/index.d.ts +8 -0
  116. package/dist/relay/index.d.ts.map +1 -0
  117. package/dist/relay/index.js +4 -0
  118. package/dist/relay/index.js.map +1 -0
  119. package/dist/relay/relay.d.ts +277 -0
  120. package/dist/relay/relay.d.ts.map +1 -0
  121. package/dist/relay/relay.js +1026 -0
  122. package/dist/relay/relay.js.map +1 -0
  123. package/dist/relay/serve.d.ts +33 -0
  124. package/dist/relay/serve.d.ts.map +1 -0
  125. package/dist/relay/serve.js +86 -0
  126. package/dist/relay/serve.js.map +1 -0
  127. package/dist/widget/chat.d.ts +290 -0
  128. package/dist/widget/chat.d.ts.map +1 -0
  129. package/dist/widget/chat.js +486 -0
  130. package/dist/widget/chat.js.map +1 -0
  131. package/dist/widget/css.d.ts +49 -0
  132. package/dist/widget/css.d.ts.map +1 -0
  133. package/dist/widget/css.js +532 -0
  134. package/dist/widget/css.js.map +1 -0
  135. package/dist/widget/dom.d.ts +143 -0
  136. package/dist/widget/dom.d.ts.map +1 -0
  137. package/dist/widget/dom.js +27 -0
  138. package/dist/widget/dom.js.map +1 -0
  139. package/dist/widget/highlight.d.ts +64 -0
  140. package/dist/widget/highlight.d.ts.map +1 -0
  141. package/dist/widget/highlight.js +136 -0
  142. package/dist/widget/highlight.js.map +1 -0
  143. package/dist/widget/index.d.ts +9 -0
  144. package/dist/widget/index.d.ts.map +1 -0
  145. package/dist/widget/index.js +20 -0
  146. package/dist/widget/index.js.map +1 -0
  147. package/dist/widget/position.d.ts +166 -0
  148. package/dist/widget/position.d.ts.map +1 -0
  149. package/dist/widget/position.js +497 -0
  150. package/dist/widget/position.js.map +1 -0
  151. package/dist/widget/settings.d.ts +116 -0
  152. package/dist/widget/settings.d.ts.map +1 -0
  153. package/dist/widget/settings.js +117 -0
  154. package/dist/widget/settings.js.map +1 -0
  155. package/dist/widget/widget.d.ts +442 -0
  156. package/dist/widget/widget.d.ts.map +1 -0
  157. package/dist/widget/widget.js +2005 -0
  158. package/dist/widget/widget.js.map +1 -0
  159. package/package.json +153 -4
@@ -0,0 +1,2005 @@
1
+ /**
2
+ * driverkit/widget — the corner panel.
3
+ *
4
+ * Plain DOM. No React, no framework, no dependencies, because the whole point
5
+ * is that it drops into an app somebody else built with tools nobody here
6
+ * chose. A React widget is unusable in a Vue app and a Vue widget is unusable
7
+ * in a Rails app, and either way the host now owns a version of a framework it
8
+ * did not pick.
9
+ *
10
+ * It is also the file people will read to decide whether to trust the library,
11
+ * so it is kept short and literal: one function, one tree of elements built by
12
+ * hand, and every decision that is not obvious written down beside it.
13
+ *
14
+ * **What it adds over `drive` alone is visibility.** The loop is headless and
15
+ * correct and would happily move a person's screen without saying a word. A
16
+ * person watching their own app change under them needs to see what changed
17
+ * it; silent mutation is alarming even when it is right, and it is the
18
+ * difference between "the agent accepted two hundred rows" and "something
19
+ * accepted two hundred rows". So every verb that runs appears in the
20
+ * transcript, labelled with what it did to the world and what it answered.
21
+ *
22
+ * **And what it adds over visibility is time.** Seeing a verb after it ran is
23
+ * not the same as being able to stop it. So the panel renders the run as a
24
+ * step list — one row per call, appearing while the call is still pending —
25
+ * paces the run slowly enough to follow, and puts Pause, Step and Stop beside
26
+ * it. The pace, the step-every-call mode, the outlining of the element a call
27
+ * is about, and the commit confirmation are all the person's to change in a
28
+ * settings view under the ⚙, remembered per viewer. Everything about that
29
+ * surface is one judgement: the person watching their own screen move is the
30
+ * one who should be deciding how fast it moves.
31
+ *
32
+ * **What it does not do is hold a key.** `think` is the host app's function,
33
+ * exactly as in `driverkit/agent`; see that area's `types.ts` for why, and
34
+ * `backendThink` for the thirty lines that make the realistic deployment work.
35
+ */
36
+ import { ASK } from "../core/index.js";
37
+ // A value import, and the only one that crosses an entry point's boundary:
38
+ // everything else between areas is `import type`, which
39
+ // `verbatimModuleSyntax` erases outright. It used to be the one line that
40
+ // forced an import map on every page loading the widget from a static host,
41
+ // because a bare `@driverkit/agent` is not something a browser can resolve.
42
+ // One package, one relative path, and that problem is gone -- see the
43
+ // packaging test, which pins that the emitted JavaScript names no bare
44
+ // specifier at all.
45
+ import { commas, drive, runControls } from "../agent/index.js";
46
+ import { CSS } from "./css.js";
47
+ import { closeDangling, defaultSession, forgetChat, loadChat, replayLines, restoredLines, saveChat, scrubTurns, trimTurns, } from "./chat.js";
48
+ import { spotlight } from "./highlight.js";
49
+ import { defaultStorage, positioner } from "./position.js";
50
+ import { SPEEDS, defaults as defaultSettings, load as loadSettings, nearestSpeed, pace as clampPace, save as saveSettings, } from "./settings.js";
51
+ /**
52
+ * The selection size at which a commit is confirmed even though the app said
53
+ * it could be undone. A commit acting on MORE than this many rows is asked
54
+ * about; `commitAskAbove` overrides it.
55
+ *
56
+ * **This number is a judgement and not a fact**, so here is the judgement. Two
57
+ * lines could have been drawn and they are drawn in different places:
58
+ *
59
+ * - Where can a person still check the claim themselves? A screenful. This
60
+ * library's premise is that an agent sees exactly what the person sees, and
61
+ * its own demo puts twenty rows on a screen; past a screenful the person
62
+ * cannot look at what is about to change, so "the app can undo it" is a
63
+ * promise they have no way to weigh.
64
+ * - Where does an app's undo stop being credible? Much higher — somewhere in
65
+ * the thousands, where a batch half-applies, a buffer sized for one row
66
+ * runs out, or a server gives up at row 1,800.
67
+ *
68
+ * The lower line is taken, and 25 rather than 20 because the first is the point
69
+ * where the gate stops being able to help and the second is a page size that
70
+ * differs per app: a selection a few rows past one screenful is an ordinary
71
+ * thing a person was probably looking at, and tripping the dialog on it would
72
+ * put us back to asking about the trivial. Anything that cannot be seen at once
73
+ * is asked about, which is the side of the line to err on — the cost of a
74
+ * needless question here is one click, and the cost of a missed one is an
75
+ * "undo" that turns out to be partial.
76
+ *
77
+ * It is one number for every app and therefore wrong for some of them, which is
78
+ * exactly why it is an option.
79
+ */
80
+ export const COMMIT_ASK_ABOVE = 25;
81
+ /**
82
+ * The word in the panel header when the host has not supplied one.
83
+ *
84
+ * It used to be the app's own name, and the app's own name is the one thing
85
+ * that must not size this strip. "Northwind CRM" is a header full before the
86
+ * three controls beside it get a place; "Mail" leaves it two thirds empty; and
87
+ * neither of them tells the person anything they do not already know, because
88
+ * the app they are looking at is the whole screen behind the panel. A chat
89
+ * panel's title is only there to say what the panel IS.
90
+ *
91
+ * "Assistant" and not "Ask", which is the launcher's word, because the two are
92
+ * different parts of speech doing different jobs: a button says what pressing
93
+ * it does, and a title names the thing it is on top of. "Ask" as a header
94
+ * would read as an instruction with nothing to instruct. It is also already
95
+ * the word in the panel's `aria-label` — `"<app> assistant"` — so the visible
96
+ * title and the announced one now agree instead of being two different names
97
+ * for one surface.
98
+ *
99
+ * The app's name is NOT gone: it is in that `aria-label`, in the launcher's
100
+ * and the input's accessible names, in the input's placeholder, in the
101
+ * greeting, and on the title's own `title` tooltip. Those are the places where
102
+ * naming the app answers a question somebody actually has — "what is this
103
+ * thing reading my screen" — and none of them is a box whose width the name
104
+ * gets to decide.
105
+ */
106
+ export const PANEL_TITLE = "Assistant";
107
+ const STOP_NOTE = {
108
+ // Nothing to add: the model's own prose is already in the transcript.
109
+ answered: null,
110
+ silent: "The model replied with nothing. That is usually a bug in `think`.",
111
+ // Named in the transcript rather than logged, because the person is the one
112
+ // who has to decide whether to ask again. A run that quietly stops looks
113
+ // like a run that is still thinking.
114
+ "max-steps": "Stopped: this took more steps than allowed. Ask again, more specifically.",
115
+ stuck: "Stopped: the same call kept being refused, so going on would not have helped.",
116
+ // The one stop reason that is about the APP and not about the run, which is
117
+ // why it names the limit rather than suggesting the person rephrase. A panel
118
+ // that said "ask again, more specifically" here would be sending somebody to
119
+ // reword a request against an app that will refuse the next one too — and a
120
+ // panel that said nothing would be the silent mid-job stop that
121
+ // `MountOptions.budget` is written to avoid. The settings view shows the
122
+ // numbers; this says which thing happened.
123
+ "over-budget": "Stopped: this app's limit on what one session may spend is reached. Asking again will " +
124
+ "not help — the limit is set by the app, not by the panel.",
125
+ aborted: "Stopped.",
126
+ };
127
+ /**
128
+ * Put a chat panel in the corner of the app and let it drive the app.
129
+ *
130
+ * ```ts
131
+ * const panel = mountWidget(driver, { think: backendThink("/api/chat") });
132
+ * // later
133
+ * panel.unmount();
134
+ * ```
135
+ *
136
+ * A `commit` verb the app cannot undo is confirmed with the person by default,
137
+ * in the panel, with the count the preceding `describe` reported. One that
138
+ * declares `Verb.reversible` runs without a question unless it acts on a large
139
+ * selection. See `confirmCommits`, `commitAskAbove` and `confirmEveryCommit`.
140
+ */
141
+ export function mountWidget(driver, options) {
142
+ const doc = options.document ?? globalThis.document;
143
+ if (!doc)
144
+ throw new Error("driverkit: no document; pass one");
145
+ const Abort = options.AbortController ??
146
+ globalThis.AbortController;
147
+ const manifest = driver.manifest();
148
+ const app = options.title ?? manifest.app;
149
+ // The launcher's accessible name, and the one place the app's name is still
150
+ // read out loud about that button. A screen reader reads a name in
151
+ // isolation, with none of the context a sighted person gets from the app
152
+ // behind it, so the visible word can be one word and this cannot.
153
+ const ASK_LABEL = `Ask ${app} to do something`;
154
+ // The same name with the state the dot shows, in words. A dot is not a thing
155
+ // a screen reader can read, and "there is a conversation in here" is exactly
156
+ // the fact somebody who cannot see the dot is missing.
157
+ const WAITING_LABEL = `${ASK_LABEL}. Your conversation is still here.`;
158
+ // One place, shared with positioning, because two storage mechanisms would
159
+ // be two places to get the try/catch wrong. `persist: false` means neither
160
+ // the position nor the settings are remembered.
161
+ const storage = options.persist === false ? undefined : (options.storage ?? defaultStorage());
162
+ // The person's choices beat the host's options, because the host's options
163
+ // are an author's default and these are what this particular viewer, looking
164
+ // at their own screen, decided.
165
+ const settings = loadSettings(storage, app, {
166
+ ...defaultSettings(options.confirmCommits !== false),
167
+ ...(options.pace === undefined ? {} : { pace: clampPace(options.pace) }),
168
+ });
169
+ // Not a `Settings` field, deliberately: the three settings and the commit
170
+ // switch are the viewer's to change because they are about how fast this
171
+ // person reads and how much they trust this run, and "how many rows is too
172
+ // many to take an app's undo on faith for" is not that — it is a property of
173
+ // the app's own undo, which the author knows and the viewer does not. So it
174
+ // is a mount option and nothing else, and it is not remembered.
175
+ const askAbove = options.commitAskAbove === undefined ? COMMIT_ASK_ABOVE : options.commitAskAbove;
176
+ const host = doc.createElement("div");
177
+ // A class on the host element, in the light DOM, because the positioning
178
+ // state has to be visible to `:host(...)` selectors inside the shadow tree
179
+ // and that is the only place a shadow tree can read anything from.
180
+ host.className = "dk-host";
181
+ // A shadow root if there is one, the host element itself if not. The
182
+ // fallback is honest rather than ideal: without a shadow tree the host app's
183
+ // CSS can reach these elements, so the panel may look wrong. Refusing to
184
+ // mount would be worse — a chat panel is not worth failing an app's boot
185
+ // over — and the class names are all prefixed so nothing collides.
186
+ const root = host.attachShadow
187
+ ? host.attachShadow({ mode: "open" })
188
+ : host;
189
+ const style = doc.createElement("style");
190
+ style.textContent = CSS;
191
+ root.appendChild(style);
192
+ // One wrapper inside the shadow root, because the open/busy state is a class
193
+ // and a shadow root cannot carry one.
194
+ const wrap = el("div", "dk-wrap");
195
+ root.appendChild(wrap);
196
+ // In the document BEFORE the rest is built, which positioning depends on:
197
+ // `getBoundingClientRect` on an element that is not in the document answers
198
+ // zero for everything, and a clamp that believes the panel is 0x0 will
199
+ // happily leave it half off the screen. Everything below is appended into a
200
+ // live tree, which costs one synchronous reflow and buys a measurable box.
201
+ (options.container ?? doc.body).appendChild(host);
202
+ const launcher = el("button", "dk-launcher");
203
+ // ONE WORD, and the app's name is deliberately not in it. `Ask Northwind
204
+ // CRM` grew with the app, so the button was a different size in every app
205
+ // that used it, and it reads as an instruction to the person rather than as
206
+ // a label on a control — a button says what it is, not what you should do
207
+ // with it. The app's name belongs in the panel header, where there is room
208
+ // for it and where it is still the first thing read on opening, and it is
209
+ // still in the accessible name here. `title` overrides this for a host that
210
+ // wants its own word; a long one is ellipsised rather than allowed to
211
+ // stretch the pill.
212
+ launcher.textContent = options.title ?? "Ask";
213
+ launcher.setAttribute("type", "button");
214
+ // The app's name survives for anybody who cannot see the panel behind the
215
+ // button. A screen reader reads a name in isolation, with none of the
216
+ // context a sighted person gets from the app around it, so "Ask" alone would
217
+ // be a button that could be about anything; a visual label has the whole
218
+ // screen for context and needs no more than a word. Same reasoning as the
219
+ // input's `aria-label`, which is why they read the same.
220
+ launcher.setAttribute("aria-label", ASK_LABEL);
221
+ // And on hover, for the case the visible word was clipped.
222
+ launcher.setAttribute("title", ASK_LABEL);
223
+ launcher.setAttribute("aria-haspopup", "dialog");
224
+ launcher.setAttribute("aria-expanded", "false");
225
+ /**
226
+ * The "there is a conversation behind this" dot.
227
+ *
228
+ * Minimising keeps the transcript, which is the whole point of change one —
229
+ * but a person who minimised mid-run then has a pill that looks exactly like
230
+ * a pill they have never pressed, and no way to tell that the agent is still
231
+ * working or that what they asked is still in there. So the pill carries a
232
+ * dot, which pulses while a run is in flight.
233
+ *
234
+ * INSIDE the pill, absolutely positioned, and with its own class so its
235
+ * rules never mention `.dk-launcher`: the launcher's box is 96x40 and
236
+ * nothing is allowed to change it — a badge hanging off the corner would
237
+ * grow the element, and the remembered position is a fraction of the
238
+ * viewport less the element's own width, so a launcher that grew would also
239
+ * have moved itself. See the launcher's rule in `css.ts`.
240
+ *
241
+ * Appended AFTER the label is written, because `textContent =` replaces
242
+ * every child and would throw the dot away. `aria-hidden`, because the state
243
+ * it shows is said in words in the launcher's own accessible name — a
244
+ * screen reader hearing "dot" has learnt nothing.
245
+ */
246
+ const dot = el("span", "dk-dot");
247
+ dot.setAttribute("aria-hidden", "true");
248
+ launcher.appendChild(dot);
249
+ wrap.appendChild(launcher);
250
+ const panel = el("section", "dk-panel");
251
+ // Not `aria-modal`: the person is meant to keep using the app while this is
252
+ // open, and claiming modality would tell a screen reader to hide the rest of
253
+ // the page — the opposite of what a panel that drives that page wants.
254
+ panel.setAttribute("role", "dialog");
255
+ panel.setAttribute("aria-label", `${app} assistant`);
256
+ wrap.appendChild(panel);
257
+ const head = el("div", "dk-head");
258
+ /**
259
+ * The grip: the drag handle, and the only drag surface on the panel.
260
+ *
261
+ * A glyph and not the word "Move", because what a drag handle has to do is
262
+ * LOOK like one. Six dots is the one thing on a screen people already read
263
+ * as "pick this up", and the word "Move" read as a button that teleports the
264
+ * panel somewhere \u2014 which is only half of what it does.
265
+ *
266
+ * It is a real `<button>`, and that is deliberate: it is the grab affordance
267
+ * AND the keyboard control. A drag handle with no focusable element in it is
268
+ * a feature that exists only for people with a mouse, and a shortcut nobody
269
+ * can see is a shortcut nobody uses. One control answers both.
270
+ *
271
+ * First in the strip, at the far end from the gear and the minimise button.
272
+ * The whole complaint this change answers is that an imprecise press near a
273
+ * button started a drag; putting the thing that drags as far as the strip
274
+ * allows from the things that do not is the cheap half of the fix.
275
+ */
276
+ const grip = el("button", "dk-move");
277
+ grip.textContent = "\u283f";
278
+ grip.setAttribute("type", "button");
279
+ grip.setAttribute("aria-label", "Move panel: arrow keys to nudge, Enter for the next corner");
280
+ grip.setAttribute("title", "Drag to move. Arrow keys to nudge, Enter for the next corner, Alt (Option) and an arrow from anywhere.");
281
+ const title = el("div", "dk-title");
282
+ // A short word, not the app's name. See `PANEL_TITLE`.
283
+ title.textContent = options.title ?? PANEL_TITLE;
284
+ // And the app's name on hover, so a generic title is still answerable for
285
+ // what it is attached to without being sized by it.
286
+ title.setAttribute("title", `${app} assistant`);
287
+ // A glyph, not the word "Settings". The header is a 380px strip with a title
288
+ // and three controls in it, and three words would not fit; it is still a
289
+ // real button with a real label.
290
+ const gear = el("button", "dk-gear");
291
+ gear.textContent = "\u2699";
292
+ gear.setAttribute("type", "button");
293
+ gear.setAttribute("aria-label", "Settings");
294
+ gear.setAttribute("title", "Settings: speed, highlighting, step mode, confirmations, clear");
295
+ // `aria-expanded` and not `aria-pressed`: this discloses a panel section
296
+ // rather than turning something on, and claiming both would be two
297
+ // different promises about one button.
298
+ gear.setAttribute("aria-expanded", "false");
299
+ /**
300
+ * Minimise, which is what this button always did and is now what it says.
301
+ *
302
+ * It hid the panel and kept the conversation, and it was labelled "Close" \u2014
303
+ * so people read it as "throw this conversation away" and stopped pressing
304
+ * it. That is a real failure even though the behaviour was right: a control
305
+ * whose label overstates what it does is a control people avoid, and the
306
+ * person who avoids this one is left with a panel sitting on top of the rows
307
+ * they asked about. The behaviour is untouched; the word and the glyph are
308
+ * the fix.
309
+ *
310
+ * A minus and not a chevron, because a chevron points somewhere and this
311
+ * panel can be in any of four corners, so "down" is wrong a quarter to three
312
+ * quarters of the time. The destructive option people were looking for when
313
+ * they read "Close" is now in the settings view, where destructive things
314
+ * belong, and it says what it does.
315
+ */
316
+ const minimise = el("button", "dk-min");
317
+ minimise.textContent = "\u2212";
318
+ minimise.setAttribute("type", "button");
319
+ minimise.setAttribute("aria-label", "Minimise the panel. The conversation is kept.");
320
+ minimise.setAttribute("title", "Minimise. Your conversation is kept \u2014 reopen to carry on.");
321
+ head.appendChild(grip);
322
+ head.appendChild(title);
323
+ head.appendChild(gear);
324
+ head.appendChild(minimise);
325
+ panel.appendChild(head);
326
+ // The run controls, directly above the step list they act on, and only while
327
+ // a run is in flight.
328
+ const bar = el("div", "dk-run");
329
+ bar.setAttribute("role", "group");
330
+ bar.setAttribute("aria-label", "Run controls");
331
+ const pause = el("button", "dk-pause");
332
+ pause.textContent = "Pause";
333
+ pause.setAttribute("type", "button");
334
+ const once = el("button", "dk-once");
335
+ once.textContent = "Step";
336
+ once.setAttribute("type", "button");
337
+ once.setAttribute("title", "Run one more call, then wait");
338
+ const note = el("div", "dk-run-note");
339
+ bar.appendChild(pause);
340
+ bar.appendChild(once);
341
+ bar.appendChild(note);
342
+ panel.appendChild(bar);
343
+ // Outside the panel on purpose: a live region inside a `display: none` panel
344
+ // is not announced at all, and moving the COLLAPSED widget is exactly the
345
+ // case that needs announcing.
346
+ const status = el("div", "dk-status");
347
+ status.setAttribute("role", "status");
348
+ status.setAttribute("aria-live", "polite");
349
+ wrap.appendChild(status);
350
+ const log = el("div", "dk-log");
351
+ // `log`, not `alert`: entries are announced as they arrive and do not
352
+ // interrupt. `polite` for the same reason — the person may be typing.
353
+ log.setAttribute("role", "log");
354
+ log.setAttribute("aria-live", "polite");
355
+ panel.appendChild(log);
356
+ // ---- the settings view -------------------------------------------------
357
+ //
358
+ // In the panel and not a window of its own: it is four preferences, and the
359
+ // person is already looking here. It replaces the transcript rather than
360
+ // covering it, so nothing is half-readable behind it, and the header stays
361
+ // put so the panel can still be dragged out of the way while it is open.
362
+ const settingsView = el("div", "dk-settings");
363
+ settingsView.setAttribute("role", "group");
364
+ settingsView.setAttribute("aria-label", "Settings");
365
+ panel.appendChild(settingsView);
366
+ const speedRow = setRow("Speed", "How long the agent waits between steps, so you can see each one before the next.");
367
+ const speeds = el("div", "dk-speeds");
368
+ speeds.setAttribute("role", "radiogroup");
369
+ speeds.setAttribute("aria-label", "Speed");
370
+ const speedButtons = SPEEDS.map((speed) => {
371
+ const button = el("button", "dk-speed");
372
+ button.textContent = speed.label;
373
+ button.setAttribute("type", "button");
374
+ button.setAttribute("role", "radio");
375
+ button.setAttribute("title", `${speed.ms} ms between steps`);
376
+ button.addEventListener("click", () => setPace(speed.ms));
377
+ speeds.appendChild(button);
378
+ return { speed, button };
379
+ });
380
+ speedRow.appendChild(speeds);
381
+ settingsView.appendChild(speedRow);
382
+ const highlightRow = setRow("Highlight", "Outline the thing on screen a step is about to touch, when the app named one. Many verbs name nothing, and those are simply not outlined.");
383
+ highlightRow.appendChild(toggle("dk-t-highlight", "Outline what a step will touch", () => settings.highlight, (on) => {
384
+ settings.highlight = on;
385
+ // Immediately, not at the next step: somebody switching this off is
386
+ // looking at an outline they want gone.
387
+ if (!on)
388
+ spot.hide();
389
+ }));
390
+ settingsView.appendChild(highlightRow);
391
+ const stepRow = setRow("Step mode", "Wait for you before every single call, not just after a pause. Slow, and the right setting the first time you watch this drive something that matters.");
392
+ stepRow.appendChild(toggle("dk-t-stepmode", "Ask before every call", () => settings.stepMode, (on) => {
393
+ settings.stepMode = on;
394
+ // Step mode is not a mode the controls have: it IS "paused, and stepped
395
+ // one call at a time", which is why turning it on mid-run holds the run
396
+ // and turning it off lets it go. The next run starts in the right state
397
+ // because `runControls` is built with it.
398
+ if (on)
399
+ active?.pause();
400
+ else
401
+ active?.resume();
402
+ }));
403
+ settingsView.appendChild(stepRow);
404
+ // Hidden when the host supplied its own confirmation: that option overrides
405
+ // this one outright, so a switch here would be a switch that does nothing.
406
+ if (!options.onBeforeCommit) {
407
+ const commitRow = setRow("Confirm commits", options.confirmEveryCommit
408
+ ? "Ask before any step that changes data. One question per call, not per row — a commit acts on the whole selection."
409
+ : "Ask before a step that changes data the app cannot undo, and before any step that changes a lot of rows. One question per call, not per row — a commit acts on the whole selection.");
410
+ commitRow.appendChild(toggle("dk-t-commits", "Ask before changing data", () => settings.confirmCommits, (on) => {
411
+ settings.confirmCommits = on;
412
+ }));
413
+ settingsView.appendChild(commitRow);
414
+ }
415
+ // Hidden unless the APP opted in, because a switch for a thing that cannot
416
+ // happen is a switch that teaches somebody the wrong thing about where their
417
+ // conversation goes. The app's `false` is the harder of the two keys; see
418
+ // `WidgetOptions.rememberChat`.
419
+ if (options.rememberChat === true) {
420
+ const rememberRow = setRow("Remember this conversation", "Bring the conversation back if this page reloads. It is kept in this tab only, and it goes when you close the tab. Turning this off forgets what is already stored. Nothing is resumed either way — a run does not restart by itself.");
421
+ rememberRow.appendChild(toggle("dk-t-remember", "Remember this conversation", () => settings.rememberChat, (on) => {
422
+ settings.rememberChat = on;
423
+ // Acted on at once, in both directions. Switching it off is a request
424
+ // about what is on the disk right now and not only about what happens
425
+ // next: somebody turning this off on a shared machine means "and get
426
+ // rid of it", and a panel that waited until the next write to honour
427
+ // that would have kept the transcript through the one moment they
428
+ // asked for it to be gone. `rememberNow` does the forgetting itself
429
+ // when the switch is off, which keeps the two directions in one place.
430
+ rememberNow();
431
+ }));
432
+ settingsView.appendChild(rememberRow);
433
+ }
434
+ /**
435
+ * Clear the conversation: the destructive option, in the one place a person
436
+ * goes looking for one.
437
+ *
438
+ * It is here and not in the header for the same reason the header button is
439
+ * now a minus. There were two controls and one of them was lying: minimise
440
+ * read as "destroy the conversation" and nothing actually destroyed it. Now
441
+ * the header is where you put the panel away and the settings view is where
442
+ * you throw things away — and this is the LAST row of it, below four
443
+ * preferences, which is where a destructive action is least likely to be hit
444
+ * by somebody reaching for something else.
445
+ *
446
+ * **No confirmation**, deliberately. A confirmation is worth a click when
447
+ * the thing behind it cannot be undone and cost somebody something: a
448
+ * commit, which is why this panel has a dialog for those. A lost chat costs
449
+ * one retyped sentence, and the panel's own doctrine is that a dialog on the
450
+ * cheap thing is how people learn to click through the dialog on the
451
+ * expensive one. The transcript is not a record of anything but itself — the
452
+ * app's data is untouched by this, and the steps that ran stay run.
453
+ *
454
+ * **It stops a run in flight**, through the run's own `AbortController` and
455
+ * not a second stop path, because that controller is already the one thing
456
+ * that stops a run and a second one could disagree with it. The alternative
457
+ * was letting the loop go on holding `messages` the panel has just thrown
458
+ * away, which is a panel and a model disagreeing about what has been said —
459
+ * and the model would win, so the next answer would refer to a conversation
460
+ * the person is looking at the absence of.
461
+ */
462
+ /**
463
+ * What this session has spent, and against what ceiling — SHOWN, never
464
+ * offered.
465
+ *
466
+ * This row is the whole reason `Driver.budget` exists. `MountOptions.budget`
467
+ * is declared by whoever mounted the app and a viewer must not be able to
468
+ * raise their own ceiling, so this is the only thing in the settings view
469
+ * with no control beside it: everything above it is a comfort (speed, step
470
+ * mode, confirmations) and this is somebody else's money.
471
+ *
472
+ * It is here rather than in the header for the reason the ceiling exists at
473
+ * all. A run that stops mid-job and does not say why is read as a broken
474
+ * app, and `STOP_NOTE["over-budget"]` says which thing happened — but that
475
+ * only appears AFTER the ceiling is hit. This is where a person who is
476
+ * wondering whether they are close can look before they are.
477
+ *
478
+ * Absent when the app declared no ceiling. A row reading "no limit" would be
479
+ * one more thing to read in a view of four, and the counter is still on
480
+ * `Driver.budget` for anybody debugging.
481
+ */
482
+ const spend = driver.budget?.();
483
+ const budgetRow = spend &&
484
+ (spend.calls.limit !== undefined ||
485
+ spend.commits.limit !== undefined ||
486
+ // The question ceiling belongs in this row and not in a switch of its
487
+ // own, which is the whole of why it is here: it is the app's number and
488
+ // not a viewer's comfort setting. A person who could raise their own
489
+ // allowance of questions does not have one -- and the number IS worth
490
+ // showing, because "it has asked me four of its five" is what makes the
491
+ // fifth question read as the last one rather than as an app going quiet.
492
+ spend.asks.limit !== undefined)
493
+ ? setRow("This session's limit", "Set by the app, not by this panel, so it cannot be changed from here. It counts " +
494
+ "steps for the whole time this page has been open and does not refill.")
495
+ : undefined;
496
+ const budgetText = budgetRow ? el("div", "dk-set-budget") : undefined;
497
+ if (budgetRow && budgetText) {
498
+ budgetRow.appendChild(budgetText);
499
+ settingsView.appendChild(budgetRow);
500
+ }
501
+ /** Repaint the spend numbers. Read on every open rather than subscribed to:
502
+ * the numbers only matter while somebody is looking at them, and a listener
503
+ * on every call would be work done for a view that is usually closed. */
504
+ const paintBudget = () => {
505
+ if (!budgetText)
506
+ return;
507
+ const now = driver.budget?.();
508
+ if (!now)
509
+ return;
510
+ const parts = [];
511
+ if (now.calls.limit !== undefined) {
512
+ parts.push(`${now.calls.used} of ${now.calls.limit} steps used`);
513
+ }
514
+ if (now.commits.limit !== undefined) {
515
+ parts.push(`${now.commits.used} of ${now.commits.limit} changes to data used`);
516
+ }
517
+ if (now.asks.limit !== undefined) {
518
+ parts.push(`${now.asks.used} of ${now.asks.limit} questions asked`);
519
+ }
520
+ budgetText.textContent = parts.join(" · ");
521
+ };
522
+ paintBudget();
523
+ const clearRow = setRow("Clear conversation", "Throw away everything in this panel and start over. Nothing in the app changes and steps that already ran stay run. A run in flight is stopped, because a transcript the model still remembers and the panel does not is worse than no transcript.");
524
+ const clear = el("button", "dk-clear");
525
+ clear.textContent = "Clear conversation";
526
+ clear.setAttribute("type", "button");
527
+ clear.addEventListener("click", () => clearConversation());
528
+ clearRow.appendChild(clear);
529
+ settingsView.appendChild(clearRow);
530
+ const done = el("button", "dk-done");
531
+ done.textContent = "Done";
532
+ done.setAttribute("type", "button");
533
+ done.addEventListener("click", () => setSettingsOpen(false));
534
+ settingsView.appendChild(done);
535
+ const form = el("form", "dk-form");
536
+ const input = el("input", "dk-input");
537
+ input.setAttribute("type", "text");
538
+ input.setAttribute("autocomplete", "off");
539
+ input.setAttribute("aria-label", `Ask ${app} to do something`);
540
+ input.setAttribute("placeholder", options.placeholder ?? `Ask ${app} to do something…`);
541
+ const send = el("button", "dk-send");
542
+ send.textContent = "Send";
543
+ send.setAttribute("type", "submit");
544
+ const stop = el("button", "dk-stop");
545
+ stop.textContent = "Stop";
546
+ stop.setAttribute("type", "button");
547
+ form.appendChild(input);
548
+ form.appendChild(send);
549
+ form.appendChild(stop);
550
+ panel.appendChild(form);
551
+ /**
552
+ * Every element in the transcript, in the order it was added.
553
+ *
554
+ * Kept because clearing has to be able to empty the log, and there is no way
555
+ * to do that through `ElementLike` — `innerHTML` is not in `dom.ts` and
556
+ * putting it there to clear a container would be adding the one DOM property
557
+ * whose whole reputation is for being misused. Each line can remove itself,
558
+ * which is a method the fake and every browser already have, so the list of
559
+ * what to remove is the only missing piece. Declared above the greeting
560
+ * because the greeting is the first thing to go in it.
561
+ */
562
+ const lines = [];
563
+ // Kept rather than inlined, because clearing the conversation puts it back:
564
+ // an empty panel with no greeting looks broken, and a fresh panel is what
565
+ // clearing promises.
566
+ const greeting = options.greeting ?? `Ask me to do things in ${app}. I use the app the way you do.`;
567
+ say("dk-note", greeting);
568
+ // The conversation lives here, not in `drive`: the loop is stateless between
569
+ // runs, so a widget is simply the thing that remembers.
570
+ let messages = [];
571
+ let running = null;
572
+ let live = true;
573
+ /** The control surface for the run in flight, or null between runs.
574
+ * "Paused" has no meaning between runs, which is why this is per run. */
575
+ let active = null;
576
+ /** What the loop last said it was doing. Never inferred from the panel's own
577
+ * buttons: `drive` moves this too — a spent step permit leaves the run
578
+ * paused again, and the commit gate parks it in `awaiting-approval` — and a
579
+ * panel that tracked its own presses would be wrong in exactly those
580
+ * cases. */
581
+ let runState = "running";
582
+ /**
583
+ * The last count a `describe` reported in the run in flight, or undefined.
584
+ *
585
+ * Lifted out of `ask()` when the dialog became the core's approver, and the
586
+ * lift is the point rather than a tidy-up: the question used to be asked
587
+ * from inside the run, where this was in scope, and is now asked from inside
588
+ * `driver.call()`, where nothing of the run is. Without it every in-page
589
+ * commit would have gone back to asking "accept the current selection?"
590
+ * instead of "accept 1,000 contacts?" -- which is the number the whole
591
+ * dialog exists to put in front of somebody.
592
+ *
593
+ * Cleared when a run starts and when one ends, so a count from a finished
594
+ * run can never be read as the size of a commit that arrived afterwards over
595
+ * the relay. Cleared when a question is ASKED, because at that moment the
596
+ * number has been put in front of somebody and is spoken for.
597
+ */
598
+ let lastCount;
599
+ /**
600
+ * Every question on screen with no answer yet, as the function that answers
601
+ * it.
602
+ *
603
+ * Only ever non-empty while somebody is being asked something. It exists for
604
+ * `unmount`: a question asked through the core's gate has no run behind it
605
+ * when it came over the relay, so there is no abort signal to answer it, and
606
+ * a panel that is torn down with one open would leave `driver.call()` waiting
607
+ * on a promise nobody can resolve -- forever, since `approvalTimeout` is
608
+ * absent by default. That is a dead app, caused by closing a chat panel.
609
+ */
610
+ const openQuestions = new Set();
611
+ // The wrapper's classes, as flags. Written in one place and in one order,
612
+ // because three separate string edits to `className` is three chances for
613
+ // one of them to drop another's class.
614
+ let isOpen = false;
615
+ let isBusy = false;
616
+ let isSettings = false;
617
+ /** Whether anything has been asked since the panel was last cleared. What
618
+ * the launcher's dot is about: "there is a conversation in here", which is
619
+ * not the same question as "is a run in flight". */
620
+ let conversed = false;
621
+ /**
622
+ * Which conversation the panel is on. Bumped by clearing.
623
+ *
624
+ * A run that was in flight when the person cleared is aborted, but an abort
625
+ * is not instant: the loop resolves at its next await, and everything it
626
+ * does on the way out — the stop note, the `messages` it hands back, the
627
+ * sweep that marks abandoned steps — is about a conversation that no longer
628
+ * exists. Checking a counter is how those writes know not to land in the
629
+ * fresh transcript. A boolean would not do: clear twice during one run and
630
+ * the second clear has to invalidate the run too.
631
+ */
632
+ let era = 0;
633
+ /**
634
+ * Where a remembered conversation goes, or undefined when none is kept.
635
+ *
636
+ * Resolved once, at mount, and `undefined` whenever the app did not opt in —
637
+ * so an app that passed no `rememberChat` never reaches storage at all, not
638
+ * even to read it. The viewer's switch is checked at each write rather than
639
+ * here, because they can turn it off halfway through a conversation and the
640
+ * point of the switch is that doing so forgets what is already stored.
641
+ */
642
+ const session = options.rememberChat === true ? (options.session ?? defaultSession()) : undefined;
643
+ /**
644
+ * What the panel believes is happening to the app right now, for the record.
645
+ *
646
+ * The whole of "a reload mid-commit comes back saying so". Set when a call is
647
+ * announced and when a question goes on screen, cleared when either settles,
648
+ * and written into storage as it stands — so a page that dies between the
649
+ * two is a page whose stored record says which verb was open and in what
650
+ * state. See `ChatInFlight` for why `asked` and `sent` are different facts.
651
+ */
652
+ let inFlight;
653
+ /**
654
+ * The conversation as the run in flight is building it, or null between runs.
655
+ *
656
+ * **Why this exists at all, when `drive` hands back `messages` already.** It
657
+ * hands them back when the run ENDS, and the whole case this feature is
658
+ * shaped by is a page that dies five steps in. Without this, a reload
659
+ * mid-commit came back with the notice about the in-flight verb and an empty
660
+ * conversation — it had the alarming half and not the useful half, and the
661
+ * person's own question, the one they would have to retype, was the first
662
+ * thing lost.
663
+ *
664
+ * So the three per-call events are used to rebuild exactly what the loop is
665
+ * pushing: `onSay` is an assistant turn, `onBeforeCall` adds that turn's
666
+ * calls, and `onResult` carries the rendered tool turn verbatim as `text`. It
667
+ * is a mirror and never a second source of truth — `out.messages` replaces it
668
+ * outright when the run ends, and that is the pruned, authoritative version.
669
+ * Nothing reads this but `rememberNow`. Named for the turns and not `live`,
670
+ * which is already this file's "is the panel mounted" flag.
671
+ */
672
+ let liveTurns = null;
673
+ /**
674
+ * Milliseconds this panel has spent waiting on a PERSON, cumulative.
675
+ *
676
+ * Handed to `drive` as `waited` so the duration a MODEL is shown is the
677
+ * app's own work and not somebody reading a dialog. Cumulative and
678
+ * monotonic rather than per call, because the loop diffs it either side of
679
+ * `driver.call()` and a counter cannot be got wrong by a dialog that opens
680
+ * twice. See `DriveOptions.waited`.
681
+ *
682
+ * It has to be counted here, and this is the reason: the panel's dialog is
683
+ * installed as the CORE's approver — see `adoptDialog` — so the wait happens
684
+ * inside `driver.call()`, where the loop can see only that the call took a
685
+ * long time. Every path to a question goes through `askPerson`, which is the
686
+ * one place this is incremented.
687
+ */
688
+ let waitedMs = 0;
689
+ // ---- wiring ------------------------------------------------------------
690
+ // Positioning. Built before the wiring because the launcher's click handler
691
+ // has to ask it whether that click is really the tail of a drag.
692
+ const place = positioner({
693
+ host,
694
+ app,
695
+ ...(options.position === undefined ? {} : { position: options.position }),
696
+ ...(options.window === undefined ? {} : { window: options.window }),
697
+ ...(options.storage === undefined ? {} : { storage: options.storage }),
698
+ ...(options.persist === undefined ? {} : { persist: options.persist }),
699
+ ...(options.draggable === undefined ? {} : { draggable: options.draggable }),
700
+ ...(options.snapThreshold === undefined ? {} : { snapThreshold: options.snapThreshold }),
701
+ ...(options.gap === undefined ? {} : { gap: options.gap }),
702
+ announce: (text) => {
703
+ status.textContent = text;
704
+ },
705
+ });
706
+ // The outline over the element a step is about to touch. Its own host
707
+ // element, because the panel's is translated and a transformed ancestor
708
+ // becomes the containing block for `position: fixed` children; see
709
+ // `highlight.ts`. Nothing is written to the host app's own elements.
710
+ const spot = spotlight({
711
+ document: doc,
712
+ container: options.container ?? doc.body,
713
+ ...(options.window === undefined ? {} : { window: options.window }),
714
+ });
715
+ /**
716
+ * The grip is the handle, and the header is NOT one any more.
717
+ *
718
+ * The header used to be the drag surface, which is why `position.ts` has a
719
+ * `controls: "ignore"` mode at all: a press that landed on a button inside
720
+ * the handle had to be rescued from the drag it would otherwise have
721
+ * started. That guard works, and it is still the wrong shape for this
722
+ * header. "Ignore the controls" is a rule about the pixels a button covers,
723
+ * and a header is also the 4px between two of them, the strip above them,
724
+ * and the few pixels of padding a pointer lands on when somebody aims at the
725
+ * gear and misses by two — all of which drag, and none of which the person
726
+ * meant to drag.
727
+ *
728
+ * So the handle is now exactly the thing that looks like a handle, and the
729
+ * header is inert. The cost is forgiveness: somebody who grabs the title
730
+ * text and pulls gets nothing, where before they got a moving panel. That is
731
+ * the trade taken deliberately, and in this direction, for three reasons.
732
+ * The grip is visible and the header's grabbability never was — it was a
733
+ * `cursor: grab` and no more, so nobody who had not already discovered it
734
+ * ever would. Predictability is worth more than reach HERE because there is
735
+ * no reach to lose: the keyboard path still moves the panel from anywhere in
736
+ * the widget with Alt and an arrow, and the grip's own bare arrows and Enter
737
+ * still work. And a surface that is not a handle cannot grow a new header
738
+ * button that is accidentally draggable, which is this bug's shape and the
739
+ * shape it would come back in.
740
+ *
741
+ * `"ignore"` stays in `position.ts` with no caller here on purpose: it is
742
+ * the right answer for any container handle, and the next person who makes
743
+ * one should find it rather than rediscover the bug.
744
+ */
745
+ const movedGrip = place.handle(grip);
746
+ // And the launcher, because a collapsed widget is over the app just as much
747
+ // as an open one.
748
+ const movedLauncher = place.handle(launcher);
749
+ launcher.addEventListener("click", () => {
750
+ // A drag is not a click. Without this, shoving the collapsed launcher off
751
+ // the rows somebody wants to read opens the panel back over them.
752
+ if (movedLauncher())
753
+ return;
754
+ setOpen(true);
755
+ });
756
+ minimise.addEventListener("click", () => setOpen(false));
757
+ gear.addEventListener("click", () => setSettingsOpen(!isSettings));
758
+ pause.addEventListener("click", () => {
759
+ if (runState === "paused")
760
+ active?.resume();
761
+ else
762
+ active?.pause();
763
+ // Not painted here. The loop answers through `onControl`, and it is the
764
+ // only thing that knows — including in the case where a run ended between
765
+ // the person deciding to press this and pressing it.
766
+ });
767
+ once.addEventListener("click", () => active?.step());
768
+ grip.addEventListener("click", () => {
769
+ if (movedGrip())
770
+ return;
771
+ place.cycle();
772
+ });
773
+ // Bare arrows, and only here, where the panel's own control has focus. Alt
774
+ // is left to the wrapper's handler so the two do not both act on one press.
775
+ grip.addEventListener("keydown", (e) => {
776
+ if (e.altKey === true)
777
+ return;
778
+ place.key(e, true);
779
+ });
780
+ form.addEventListener("submit", (e) => {
781
+ e.preventDefault?.();
782
+ const text = (input.value ?? "").trim();
783
+ if (!text)
784
+ return;
785
+ input.value = "";
786
+ void ask(text);
787
+ });
788
+ // Stop is the abort signal and nothing else, which is also why it is not on
789
+ // `RunControls`: an abort outranks a pause, so a held run is still stoppable
790
+ // and never wedged.
791
+ stop.addEventListener("click", () => running?.abort());
792
+ // On the wrapper and not on the input, so Escape closes the panel from
793
+ // anywhere inside it — the transcript, the buttons, the input. Keydown
794
+ // bubbles, and a handler per focusable element would be three handlers that
795
+ // drift apart.
796
+ wrap.addEventListener("keydown", (e) => {
797
+ if (e.key === "Escape") {
798
+ e.preventDefault?.();
799
+ setOpen(false);
800
+ return;
801
+ }
802
+ // Alt+arrow, from anywhere in the widget including the collapsed launcher
803
+ // and including the text input mid-sentence. Dragging is pointer-only and
804
+ // a panel that can only be moved with a mouse cannot be moved at all by
805
+ // the people most likely to be stuck behind it.
806
+ place.key(e);
807
+ });
808
+ paintSpeeds();
809
+ show("running");
810
+ // Before `options.open`, so a panel told to start open starts open with its
811
+ // conversation already in it rather than appearing empty and then filling.
812
+ // A no-op unless the app opted in; see `restoreConversation`.
813
+ restoreConversation();
814
+ if (options.open)
815
+ setOpen(true);
816
+ /**
817
+ * Hand this panel's dialog to the core, and hold the release.
818
+ *
819
+ * WHY THIS IS HERE AND NOT IN THE RUN. Until this, the panel gated OUTSIDE
820
+ * `driver.call()`: hold the core's lock, ask the person, then let the loop
821
+ * make the call. The core therefore never saw the question, and an app that
822
+ * mounted this panel and wired `onAudit` recorded
823
+ * `approval: "not-asked", policy: "none"` for a commit somebody had just
824
+ * clicked Approve on. The record read as complete and said the opposite of
825
+ * what happened. Correlating the two afterwards was the alternative and it
826
+ * cannot be made sound: between the dialog's answer and the call that
827
+ * follows, another agent on the relay can call the same verb, and an audit
828
+ * trail that is usually right is not an audit trail. So the dialog becomes
829
+ * the approver, and the answer is written down by the thing that asked.
830
+ *
831
+ * `null` back means somebody else is the gate: the app's own `approve`, or
832
+ * a panel that mounted first. Then this panel keeps its in-page gate or
833
+ * drops it according to `coreAsks`, and nothing about the arrangement is
834
+ * silent — the core warns about a second panel, and the `unattended` case is
835
+ * warned about below.
836
+ */
837
+ const release = adoptDialog();
838
+ function adoptDialog() {
839
+ // A host that supplied its own confirmation has said HOW it wants to ask,
840
+ // and `onBeforeCommit` is documented as replacing this panel's dialog
841
+ // rather than stacking with it. Adopting anyway would stack them: the
842
+ // host's dialog out here and this panel's inside `driver.call()`, two
843
+ // questions about one commit, which is the thing that teaches people to
844
+ // click Yes without reading.
845
+ //
846
+ // The cost is that such a gate is still outside the core, so its answer is
847
+ // not in the audit record -- `onBeforeCommit`'s own documentation already
848
+ // says it gates the in-page run only and that the gate covering every path
849
+ // is `MountOptions.approve`. Unchanged by this, deliberately: a host that
850
+ // wants its dialog in the record passes it as `approve`.
851
+ if (options.onBeforeCommit)
852
+ return null;
853
+ const adopt = driver.approval?.adopt;
854
+ // A driver from before adoption existed — hand-written, or an older
855
+ // build. Nothing to install and nothing to say: the panel's in-page gate
856
+ // is what it has always been, and it still works.
857
+ if (!adopt)
858
+ return null;
859
+ const won = adopt(approveRequest);
860
+ if (won)
861
+ return won;
862
+ // Refused because the app declared `unattended`, which `adopt` will not
863
+ // overrule. The panel goes on asking in-page, which is right — somebody
864
+ // is plainly sitting there — but the core is not asked, so those
865
+ // confirmations do not appear in `onAudit` and the records say
866
+ // `not-asked, unattended` for commits a person clicked Approve on. That is
867
+ // the bug this change fixes, in the one configuration where it cannot be
868
+ // fixed without overruling the app, so it is said out loud instead.
869
+ if (driver.approval?.declared === "unattended") {
870
+ warn(`\`${app}\` was mounted with \`approve: "unattended"\` and also mounts this panel, ` +
871
+ `which asks before a commit. The panel's question is NOT in the audit record: ` +
872
+ `\`onAudit\` will report \`approval: "not-asked", policy: "unattended"\` for commits ` +
873
+ `somebody confirmed here, because the core was never asked. Wire the panel up as the ` +
874
+ `gate — \`approve: (req) => panel.approve(req)\` — if those confirmations should be ` +
875
+ `in the record, or drop this panel if the run really is unattended.`);
876
+ }
877
+ return null;
878
+ }
879
+ // ---- the run -----------------------------------------------------------
880
+ async function ask(text) {
881
+ if (!live || running)
882
+ return;
883
+ say("dk-you", text);
884
+ conversed = true;
885
+ // The person's words go into the mirror before anything can go wrong, so a
886
+ // page that dies on the very first call still comes back with the question
887
+ // they asked. `drive` appends the screen to its own copy of this turn; the
888
+ // mirror carries the words alone, which is what a restored transcript and a
889
+ // resumed conversation both want.
890
+ liveTurns = [...messages, { role: "user", text }];
891
+ // Which conversation this run belongs to. Clearing bumps it, and
892
+ // everything below that would write into the transcript checks it first.
893
+ const mine = era;
894
+ const controller = Abort ? new Abort() : null;
895
+ running = controller;
896
+ busy(true);
897
+ // One control surface per run, started paused if step mode is on — which
898
+ // is all step mode is, and deliberately so: a separate flag beside the
899
+ // state would be a second source of truth able to disagree with it.
900
+ const control = (options.controls ?? runControls)({
901
+ pace: settings.pace,
902
+ stepMode: settings.stepMode,
903
+ });
904
+ active = control;
905
+ show("running");
906
+ // One step per call, keyed by the model's call id so a turn with several
907
+ // calls does not cross its wires.
908
+ const steps = new Map();
909
+ // Nothing of the last run's selection survives into this one. The field
910
+ // itself is at the top of the panel, because the dialog that reads it is
911
+ // now called from inside `driver.call()` rather than from inside the loop.
912
+ lastCount = undefined;
913
+ // Always installed when the host has not replaced it AND the core is not
914
+ // already gating, and the SETTING is read inside — so turning
915
+ // confirmations off, or back on, in the middle of a run takes effect on
916
+ // the next commit rather than the next run. That is what somebody who has
917
+ // just watched a commit go past expects of the switch they reached for.
918
+ //
919
+ // Nothing is installed when the core already has an approver — the app's
920
+ // own `approve` hook, or this panel's dialog, which `mountWidget` adopted
921
+ // at the bottom of this file. That approver is called inside
922
+ // `driver.call()` for every path, this one included, so installing the
923
+ // panel's gate as well would be two questions about one commit — which is
924
+ // the thing this panel's own documentation says teaches people to click Yes
925
+ // without reading.
926
+ //
927
+ // Read per run, not once at mount, because the answer moves: a second
928
+ // panel on the same driver does not get the gate, and a panel whose
929
+ // adoption was refused because the app declared `approve: "unattended"`
930
+ // keeps its own in-page gate and always did. See `coreAsks`.
931
+ const gate = options.onBeforeCommit ?? (coreAsks() ? undefined : confirmCommit);
932
+ /** The built-in gate, per run: find the count, then ask. */
933
+ function confirmCommit(req) {
934
+ // `lastCount` first, because it is the number the MODEL just put on the
935
+ // screen in this run. The two fallbacks and their order are
936
+ // `countFor`'s, which the out-of-run path shares.
937
+ const count = lastCount ?? countFor(req.snapshot);
938
+ if (!shouldAsk(req, count))
939
+ return Promise.resolve(true);
940
+ // Cleared when a question is ASKED, because that is when the number has
941
+ // been put in front of somebody and spoken for. A commit that ran
942
+ // without asking has not used it up, and the next commit — which may
943
+ // well be the irreversible one — still needs it to be answerable.
944
+ lastCount = undefined;
945
+ return withLock(req.name, async () => (await askPerson(req, count, controller?.signal, CLOSED_VETO)));
946
+ }
947
+ const paced = {
948
+ think: options.think,
949
+ task: text,
950
+ history: messages,
951
+ ...(options.instructions === undefined ? {} : { instructions: options.instructions }),
952
+ ...(options.maxSteps === undefined ? {} : { maxSteps: options.maxSteps }),
953
+ ...(options.refusalLimit === undefined ? {} : { refusalLimit: options.refusalLimit }),
954
+ ...(gate ? { onBeforeCommit: gate } : {}),
955
+ ...(controller ? { signal: controller.signal } : {}),
956
+ controls: control,
957
+ // The person's remembered speed, which `setPace` then changes live on the
958
+ // controls. Passed here as well because `drive`'s own option is what a run
959
+ // starts from, and a panel that only set it afterwards would pace its
960
+ // first call differently from its second.
961
+ pace: settings.pace,
962
+ ...(options.clock === undefined ? {} : { clock: options.clock }),
963
+ // A step appears HERE: `onBeforeCall` fires before the pace wait and
964
+ // before any hold, which is the only way "you can see it coming and stop
965
+ // it" is true rather than aspirational. `onCall` is then the moment the
966
+ // app is actually touched, and `onResult` the outcome — the three states
967
+ // of one row.
968
+ onBeforeCall: (e) => {
969
+ // Nothing from a cleared conversation reaches the one that replaced
970
+ // it. An abort stops the loop at its next await, so a call it had
971
+ // already announced can still arrive here afterwards, and a step row
972
+ // about it would appear in a transcript the person has just emptied.
973
+ if (era !== mine)
974
+ return;
975
+ mark(step(steps, e), "pending");
976
+ aim(e);
977
+ },
978
+ onCall: (e) => {
979
+ if (era !== mine)
980
+ return;
981
+ mark(step(steps, e), "running");
982
+ aim(e);
983
+ // `onCall` and not `onBeforeCall`, and the distinction is the whole
984
+ // honesty of the restored notice. `onBeforeCall` fires before the pace
985
+ // wait and before any hold, so a page dying there is a page that died
986
+ // while a call was QUEUED -- nothing was sent, nothing can have
987
+ // landed. `onCall` is the moment the app is actually touched. Recording
988
+ // `sent` from the earlier event would have the panel come back telling
989
+ // somebody to go and check a verb that was never called.
990
+ inFlight = { verb: e.call.name, phase: "sent" };
991
+ // The assistant turn the loop pushed, rebuilt. `index === 0` starts it,
992
+ // and a fan-out's later calls join the same turn rather than making one
993
+ // each -- which matters because a `tool_use` must be answered within
994
+ // the turn that made it.
995
+ if (liveTurns) {
996
+ const last = liveTurns[liveTurns.length - 1];
997
+ if (e.index === 0 && last?.role === "assistant" && last.calls === undefined) {
998
+ liveTurns[liveTurns.length - 1] = { ...last, calls: [e.call] };
999
+ }
1000
+ else if (e.index > 0 && last?.role === "assistant" && last.calls) {
1001
+ last.calls.push(e.call);
1002
+ }
1003
+ else {
1004
+ liveTurns.push({ role: "assistant", calls: [e.call] });
1005
+ }
1006
+ }
1007
+ rememberNow(mine);
1008
+ },
1009
+ onControl: ({ state }) => show(state),
1010
+ onResult: ({ call, kind, result, text: answered }) => {
1011
+ if (era !== mine)
1012
+ return;
1013
+ // Settled, so nothing is in flight any more. Before the early returns
1014
+ // below -- a call whose step row has gone missing has still finished,
1015
+ // and leaving the flag set would have the panel come back after a
1016
+ // reload claiming a verb was interrupted when it had answered.
1017
+ if (inFlight?.verb === call.name && inFlight.phase === "sent")
1018
+ inFlight = undefined;
1019
+ // The tool turn, verbatim as the loop renders it, screen and all. Taken
1020
+ // from the event rather than rebuilt here, so the stored conversation
1021
+ // and the one the model is reading cannot come to differ by a word.
1022
+ liveTurns?.push({ role: "tool", callId: call.id, name: call.name, text: answered });
1023
+ if (kind === "describe" && result?.ok)
1024
+ lastCount = result.count;
1025
+ // The step stops being highlighted the moment it is over, whatever
1026
+ // the outcome. An outline left behind is an outline about nothing.
1027
+ spot.hide();
1028
+ const entry = steps.get(call.id);
1029
+ if (!entry)
1030
+ return;
1031
+ if (result === null) {
1032
+ outcome(entry, " · looked", "done");
1033
+ return;
1034
+ }
1035
+ if (result.ok) {
1036
+ // The count is repeated here on purpose. It is the number the
1037
+ // commit decision turns on, and the person watching should be able
1038
+ // to see "1,000 matched" without reading the model's summary of
1039
+ // it.
1040
+ outcome(entry, " · ok" + (result.count === undefined ? "" : ` · ${commas(result.count)} matched`), "done");
1041
+ }
1042
+ else {
1043
+ // A refusal is an OUTCOME and not an error. The app said no, on
1044
+ // purpose, in its own vocabulary, and the model is about to adapt
1045
+ // to it; rendering it as a failure would teach the person to read
1046
+ // a working app as a broken one.
1047
+ outcome(entry, ` · refused: ${result.refused}`, "refused");
1048
+ }
1049
+ rememberNow(mine);
1050
+ },
1051
+ onSay: ({ text: prose }) => {
1052
+ if (era !== mine)
1053
+ return;
1054
+ say("dk-me", prose);
1055
+ liveTurns?.push({ role: "assistant", text: prose });
1056
+ // The model's own words are the half of a transcript a person would
1057
+ // most miss, and a run can be many steps away from its next write.
1058
+ rememberNow(mine);
1059
+ },
1060
+ // The duration a MODEL is shown, and the human wait kept out of it. See
1061
+ // `waitedMs`: the panel's dialog is the core's approver, so the wait
1062
+ // happens inside `driver.call()` and the loop can only subtract what it
1063
+ // is told.
1064
+ timing: options.timing ?? "slow",
1065
+ waited: () => waitedMs,
1066
+ };
1067
+ try {
1068
+ const out = await drive(driver, paced);
1069
+ // The conversation this run was part of was cleared while it was
1070
+ // running. Its history is exactly what clearing threw away and its stop
1071
+ // note is about a transcript nobody can see, so neither is kept: `drive`
1072
+ // has already stopped, the panel already said so, and the person is
1073
+ // looking at a fresh panel.
1074
+ if (era !== mine)
1075
+ return;
1076
+ messages = out.messages;
1077
+ // The mirror is discarded the moment the real thing arrives.
1078
+ // `out.messages` is pruned -- one screen, not one per step -- so it is
1079
+ // both the authoritative version and the smaller one.
1080
+ liveTurns = null;
1081
+ const note = STOP_NOTE[out.stop];
1082
+ if (note)
1083
+ say("dk-note", note);
1084
+ // The authoritative write of the run. `out.messages` is the pruned
1085
+ // conversation `drive` hands back -- one screen, not one per step -- so
1086
+ // this is both the most complete and the smallest version of it, and it
1087
+ // is what a reload should come back to.
1088
+ rememberNow(mine);
1089
+ }
1090
+ catch (err) {
1091
+ // A `think` that throws — a 500 from the app's own backend, usually. Said
1092
+ // in the transcript as well as handed to `onError`, because the person is
1093
+ // sitting in front of a panel that just went quiet and the console is
1094
+ // not where they are looking.
1095
+ // Handed to `onError` whichever conversation it belonged to — a host
1096
+ // logging its own backend's 500 wants it either way — and said in the
1097
+ // transcript only if that transcript is still the one it is about.
1098
+ options.onError?.(err);
1099
+ if (era === mine) {
1100
+ say("dk-note", `Something went wrong talking to the model: ${message(err)}`);
1101
+ }
1102
+ }
1103
+ finally {
1104
+ running = null;
1105
+ active = null;
1106
+ // Also here, for the paths that never reach the assignment above: a
1107
+ // `think` that threw, and a run whose conversation was cleared while it
1108
+ // was in flight. A mirror left behind would be persisted on the next
1109
+ // write as though a run were still going.
1110
+ liveTurns = null;
1111
+ // The run's last count dies with the run. A commit arriving afterwards
1112
+ // from somewhere else is about the selection on screen now, and labelling
1113
+ // its question with a number this run happened to report would be the
1114
+ // dialog making up the one fact it exists to show.
1115
+ lastCount = undefined;
1116
+ show("running");
1117
+ spot.hide();
1118
+ // Pending rows for calls that never ran. A stop during a pace wait or a
1119
+ // hold abandons them unrun and no `onResult` is coming, so leaving them
1120
+ // mid-flight would be a panel saying something is about to happen when
1121
+ // the run is already over.
1122
+ if (era === mine) {
1123
+ for (const entry of steps.values()) {
1124
+ if (entry.line.className.includes("dk-step-pending")) {
1125
+ outcome(entry, " · not run", "skipped");
1126
+ }
1127
+ }
1128
+ }
1129
+ busy(false);
1130
+ // Not after a clear: `clearConversation` has already put focus where a
1131
+ // fresh panel starts, and it may well have been in the settings view
1132
+ // that the person pressed the button.
1133
+ if (live && era === mine)
1134
+ input.focus?.();
1135
+ }
1136
+ }
1137
+ // ---- the gate ----------------------------------------------------------
1138
+ //
1139
+ // Two answers for one event, and the difference between them is the whole
1140
+ // argument of this file's half of the audit trail. The panel is unmounted
1141
+ // with a question on screen:
1142
+ //
1143
+ // from the in-page run, the run is being torn down with it, so the commit
1144
+ // is vetoed and the model is told why. `unmount` aborts the run first, so
1145
+ // in practice the abort usually answers before this does; this is the
1146
+ // backstop for a gate reached without one.
1147
+ //
1148
+ // from the core's approver, somebody is waiting on an approval that will
1149
+ // now never be answered. That is `{ timedOut: true }` and not a denial:
1150
+ // `timed-out` says the verb did not run and nobody decided, `declined`
1151
+ // says a person refused, and a record that cannot tell those apart is the
1152
+ // record this change exists to stop writing.
1153
+ const CLOSED_VETO = "the panel was closed before this was approved";
1154
+ const CLOSED_LAPSE = {
1155
+ timedOut: true,
1156
+ hint: "the approval panel was closed while this was waiting to be approved, so nobody " +
1157
+ "answered. **The verb did not run and nothing changed.** Ask the person to reopen the " +
1158
+ "assistant, then call it again.",
1159
+ };
1160
+ //
1161
+ // Lifted out of `ask()` so that the panel's dialog is an IMPLEMENTATION of
1162
+ // `MountOptions.approve` rather than the only gate in the system. The same
1163
+ // three functions serve both callers: the in-page loop's `onBeforeCommit`,
1164
+ // which has a run and a `lastCount` and an abort signal, and `approve()`
1165
+ // below, which has none of those because the call it is about arrived over
1166
+ // the relay. One dialog, one set of rules, two paths — which is the whole
1167
+ // point of the gate moving into the core.
1168
+ /**
1169
+ * How many rows the question is about, from the screen alone.
1170
+ *
1171
+ * `Snapshot.selectedCount` first, because a commit verb takes no predicate
1172
+ * and acts on the current selection, so the size of that selection is the
1173
+ * number this question is about whether or not a `describe` verb happened to
1174
+ * report one. `selected.length` last and only as a floor: that field carries
1175
+ * just the ids that are ON SCREEN, so it is the true size exactly when the
1176
+ * whole selection is in front of the person and an undercount otherwise. An
1177
+ * app that fills `selectedCount` is believed over it.
1178
+ */
1179
+ function countFor(snapshot) {
1180
+ return snapshot.selectedCount ?? snapshot.selected?.length;
1181
+ }
1182
+ /** Whether this commit gets a question. The three options' whole meaning. */
1183
+ function shouldAsk(req, count) {
1184
+ if (!settings.confirmCommits)
1185
+ return false;
1186
+ // Absent means the app made no claim, which is gated: a commit that has
1187
+ // not said there is a way back is treated as one that has not got one.
1188
+ const reversible = req.verb.reversible === true;
1189
+ // A size check beside the flag rather than folded into it, because they
1190
+ // answer different questions. `reversible` is a claim about the kind of
1191
+ // change; this is about how much of it there is, and an undo over
1192
+ // thousands of rows is a promise an app may not be able to keep at that
1193
+ // size whatever it declared. Strictly greater than, so the option reads as
1194
+ // "ask above this many". See `COMMIT_ASK_ABOVE`.
1195
+ const large = count !== undefined && count > askAbove;
1196
+ return !reversible || options.confirmEveryCommit === true || large;
1197
+ }
1198
+ /**
1199
+ * Hold the core's no-other-calls lock while this dialog is open.
1200
+ *
1201
+ * This is the panel's share of the webmcp#288 defence. The agent being asked
1202
+ * is not the only agent that can reach this driver: a second one over the
1203
+ * relay can call `press("approve")` while the question sits in the
1204
+ * transcript, and in-page nothing was stopping it. With the lock held, every
1205
+ * `call()` on this driver is refused `approval-pending` until the person
1206
+ * answers — including a press of this panel's own Yes, if a host ever put an
1207
+ * approval control in the light DOM.
1208
+ *
1209
+ * Via the driver rather than by the panel keeping a flag of its own, because
1210
+ * the thing that has to refuse the call is the thing that runs it. An older
1211
+ * hand-written driver with no `approval` simply asks without the lock, which
1212
+ * is what it did before this existed.
1213
+ */
1214
+ function withLock(verb, ask) {
1215
+ const hold = driver.approval?.hold;
1216
+ return hold ? hold(verb, ask) : ask();
1217
+ }
1218
+ /**
1219
+ * Whether `driver.call()` already asks about commits, so this panel must not.
1220
+ *
1221
+ * `hook` is the app's own `approve`. `adopted` is a dialog installed through
1222
+ * `DriverApproval.adopt` — this panel's, in the ordinary case, or the first
1223
+ * panel's when a page mounted two. Either way the question is asked inside
1224
+ * the call, on every path, and a second gate out here would be a second
1225
+ * dialog about one commit.
1226
+ *
1227
+ * `none` and `unattended` both mean the core asks nothing, and the panel's
1228
+ * own in-page gate stands exactly as it did: `none` is a driver this
1229
+ * mechanism could not reach — hand-written, or an adoption somebody else
1230
+ * won and then released — and `unattended` is an app that said commits here
1231
+ * run with nobody in front of them, which `adopt` refuses to overrule.
1232
+ */
1233
+ function coreAsks() {
1234
+ const policy = driver.approval?.policy;
1235
+ return policy === "hook" || policy === "adopted";
1236
+ }
1237
+ /**
1238
+ * This panel's dialog, in the shape of `MountOptions.approve`.
1239
+ *
1240
+ * One function behind two callers: `Widget.approve`, for an app that wires it
1241
+ * up itself, and the hook this panel adopts at mount. Both are the same
1242
+ * question with the same rules, which is the whole reason the gate moved into
1243
+ * the core.
1244
+ */
1245
+ async function approveRequest(req) {
1246
+ // `lastCount` only while a run is in flight, and then first, because it is
1247
+ // the number the model just put on the screen. A commit that arrived from
1248
+ // somewhere else between runs has no run to have counted anything, and
1249
+ // `countFor` reads the selection the commit is about to act on.
1250
+ const count = (running ? lastCount : undefined) ?? countFor(req.snapshot);
1251
+ // Not `true`. A gate that let this through without asking must not be
1252
+ // recorded as a person saying yes — see `Approval`'s `{ asked: false }`,
1253
+ // which is in the core's vocabulary for exactly this answer.
1254
+ if (!shouldAsk(req, count))
1255
+ return { asked: false };
1256
+ // Spoken for, as in the in-page path: the number is now in front of
1257
+ // somebody, so the next commit cannot borrow it.
1258
+ lastCount = undefined;
1259
+ // The run, when there is one, says "waiting for you" rather than
1260
+ // "running". `drive` marks that state itself when the gate is its own
1261
+ // `onBeforeCommit`; asked from inside `driver.call()` the loop has no idea
1262
+ // a question is open, so the panel says so. Restored to whatever the run
1263
+ // was doing before — which may be `paused` — rather than to `running`.
1264
+ const was = runState;
1265
+ if (active)
1266
+ show("awaiting-approval");
1267
+ try {
1268
+ // No `withLock`: the core takes its lock before it calls an approver,
1269
+ // and a second take would assert a thing that is already true.
1270
+ //
1271
+ // The run's signal when there is one, so stopping a run also answers a
1272
+ // question asked during it. A commit that arrived over the relay has no
1273
+ // run and no signal: that question stays open until somebody answers it,
1274
+ // `MountOptions.approvalTimeout` lapses, or this panel is unmounted.
1275
+ return await askPerson(req, count, running?.signal, CLOSED_LAPSE);
1276
+ }
1277
+ finally {
1278
+ if (active)
1279
+ show(was);
1280
+ }
1281
+ }
1282
+ /**
1283
+ * Put the agent's question to the person, in the shape of
1284
+ * `MountOptions.ask`.
1285
+ *
1286
+ * The twin of `approveRequest` and deliberately shorter, because almost
1287
+ * everything that makes a question safe is the core's: the lock, the
1288
+ * deadline, the allowance, the record, and the fact that nothing keeps the
1289
+ * answer. What is left for a panel is the box and the honest teardown.
1290
+ *
1291
+ * THERE IS NO `shouldAsk` HERE, AND THAT IS THE DIFFERENCE WORTH NAMING. The
1292
+ * approval dialog has thresholds — a small reversible commit goes through
1293
+ * unasked — because it is a gate and a gate that stops you over a page-size
1294
+ * change is one you learn to click through. A question is not a gate. The
1295
+ * agent asked because it could not act without guessing, so a panel that
1296
+ * answered on its behalf would be inventing the answer, which is the one
1297
+ * thing neither this panel nor the core will do. Every question reaches the
1298
+ * person; what bounds them is `Budget.asks`, which is the app's to set and
1299
+ * not a viewer's comfort setting.
1300
+ */
1301
+ async function questionFor(q) {
1302
+ // The run, when there is one, says "waiting for you" rather than
1303
+ // "running" -- the same borrowing of `awaiting-approval` that
1304
+ // `approveRequest` does, and for the same reason: the loop asked for a
1305
+ // verb and has no idea a person is now being typed at. The state is named
1306
+ // for approval and means "parked in front of somebody", which is true
1307
+ // here; a fifth `RunState` for it would be a word a panel renders
1308
+ // identically.
1309
+ const was = runState;
1310
+ if (active)
1311
+ show("awaiting-approval");
1312
+ try {
1313
+ // No `withLock`: the core takes its lock before it calls the ask hook,
1314
+ // exactly as it does before an approver, and a second take would assert
1315
+ // a thing that is already true.
1316
+ //
1317
+ // The run's signal when there is one, so stopping a run also closes a
1318
+ // question asked during it. A question that arrived over the relay has no
1319
+ // run and no signal: it stays open until somebody answers, the core's
1320
+ // `askTimeout` lapses -- 45 seconds by default, unlike the approval,
1321
+ // which waits forever -- or this panel is unmounted.
1322
+ return await askAnswer(q, running?.signal);
1323
+ }
1324
+ finally {
1325
+ if (active)
1326
+ show(was);
1327
+ }
1328
+ }
1329
+ /**
1330
+ * Render the question and a box, and wait for what they type.
1331
+ *
1332
+ * EVERY EXIT THAT IS NOT SOMEBODY TYPING IS `{ answered: false }`, and there
1333
+ * is deliberately no other answer in here. A stopped run, a torn-down panel,
1334
+ * a person who presses "Not now": none of them is a person speaking, and the
1335
+ * core keeps "asked and ignored" apart from "asked and answered" on the
1336
+ * strength of that. A panel that answered "" or "no" on teardown would be
1337
+ * putting a word in somebody's mouth and letting a model act on it.
1338
+ *
1339
+ * It also never answers `{ nobody: true }`. A mounted panel is a place a
1340
+ * question can be seen, even if nobody is looking at it this minute; "there
1341
+ * is nobody on this run" is a claim about the deployment and is the app's to
1342
+ * make, from its own hook. See `AskAnswer`.
1343
+ */
1344
+ function askAnswer(q, signal) {
1345
+ // A question nobody can see is not a question -- the same first two lines
1346
+ // as the approval dialog, and the same reason: they may have hit Escape
1347
+ // while the model was thinking, or be reading the settings view.
1348
+ setOpen(true);
1349
+ setSettingsOpen(false);
1350
+ // From here until somebody answers, the stored record says a question was
1351
+ // open. `asked`, like the approval, and for a stronger version of the same
1352
+ // reason: a question runs no verb at all, so a page that dies now provably
1353
+ // changed nothing.
1354
+ inFlight = { verb: ASK, phase: "asked" };
1355
+ rememberNow();
1356
+ // The clock on the human wait starts here and stops in `answer` below,
1357
+ // whichever way it ends. The core times its own side for the audit record;
1358
+ // this is the figure the MODEL's durations are measured against, so that a
1359
+ // call that waited 30 seconds on a person is not reported to it as a slow
1360
+ // app. See `waitedMs` and `DriveOptions.waited`.
1361
+ const askedAt = Date.now();
1362
+ const row = el("div", "dk-ask dk-q");
1363
+ const question = el("div", "dk-ask-q");
1364
+ // The agent's own words, verbatim. The core does not rewrite a question
1365
+ // and neither does this: a question the panel paraphrased is a question the
1366
+ // person answers and the model did not ask.
1367
+ question.textContent = q.question;
1368
+ const why = el("div", "dk-ask-why");
1369
+ why.textContent =
1370
+ `${app} is asking you, because it cannot do what you asked without guessing. ` +
1371
+ "Whatever you type goes back to it as the answer. Nothing has changed yet, and " +
1372
+ "answering is not approving: anything that changes data is still confirmed " +
1373
+ "separately.";
1374
+ const box = el("input", "dk-ask-box");
1375
+ box.setAttribute("type", "text");
1376
+ box.setAttribute("autocomplete", "off");
1377
+ box.setAttribute("aria-label", q.question);
1378
+ box.setAttribute("placeholder", "Your answer…");
1379
+ const reply = el("button", "dk-yes");
1380
+ reply.textContent = "Answer";
1381
+ reply.setAttribute("type", "button");
1382
+ const skip = el("button", "dk-no");
1383
+ skip.textContent = "Not now";
1384
+ skip.setAttribute("type", "button");
1385
+ row.appendChild(question);
1386
+ row.appendChild(why);
1387
+ row.appendChild(box);
1388
+ row.appendChild(skip);
1389
+ row.appendChild(reply);
1390
+ post(row);
1391
+ // The BOX is focused and not the safe button, which is the opposite of the
1392
+ // approval dialog, and the asymmetry is the point. There, Enter on a dialog
1393
+ // that appeared while somebody was typing must not accept a thousand rows,
1394
+ // so the safe answer has the focus. Here the only thing Enter can do is
1395
+ // send what they typed, and an empty box sends nothing -- so focusing it
1396
+ // costs nothing and saves a click on the one interaction in this panel
1397
+ // where the person has to type.
1398
+ box.focus?.();
1399
+ return new Promise((resolve) => {
1400
+ let answered = false;
1401
+ const answer = (decision, said) => {
1402
+ if (answered)
1403
+ return;
1404
+ answered = true;
1405
+ // Counted on EVERY exit, like the approval dialog's: a model told that
1406
+ // a question "took 40 seconds" has learnt a false thing about the app's
1407
+ // speed whether or not anybody answered it.
1408
+ waitedMs += Math.max(0, Date.now() - askedAt);
1409
+ if (inFlight?.phase === "asked" && inFlight.verb === ASK)
1410
+ inFlight = undefined;
1411
+ openQuestions.delete(onTeardown);
1412
+ // The controls go and the answer stays. Scrolling back and finding a
1413
+ // live box beside a question that was answered twenty turns ago is
1414
+ // worse than no record at all.
1415
+ box.remove();
1416
+ reply.remove();
1417
+ skip.remove();
1418
+ const outcome = el("div", "dk-ask-said");
1419
+ outcome.textContent = said;
1420
+ row.appendChild(outcome);
1421
+ scroll();
1422
+ rememberNow();
1423
+ resolve(decision);
1424
+ };
1425
+ const send = () => {
1426
+ const typed = String(box.value ?? "").trim();
1427
+ // An empty box is not an answer and must not be sent as one. Nothing
1428
+ // happens, the box keeps the focus, and the question stays open --
1429
+ // which is the honest behaviour: they have not answered yet. "Not now"
1430
+ // is how somebody declines to answer, and it says so.
1431
+ if (typed === "") {
1432
+ box.focus?.();
1433
+ return;
1434
+ }
1435
+ answer(typed, `You answered: ${typed}`);
1436
+ };
1437
+ reply.addEventListener("click", send);
1438
+ box.addEventListener("keydown", (event) => {
1439
+ const key = event.key;
1440
+ if (key !== "Enter")
1441
+ return;
1442
+ event.preventDefault?.();
1443
+ send();
1444
+ });
1445
+ skip.addEventListener("click", () => answer({ answered: false }, "You did not answer this."));
1446
+ signal?.addEventListener?.("abort", () => answer({ answered: false }, "Stopped before this was answered."));
1447
+ // Registered last, so the set only ever holds questions that are
1448
+ // genuinely open.
1449
+ openQuestions.add(onTeardown);
1450
+ function onTeardown() {
1451
+ answer({ answered: false }, "The panel was closed before this was answered.");
1452
+ }
1453
+ });
1454
+ }
1455
+ /**
1456
+ * Render the question in the transcript and wait for an answer.
1457
+ *
1458
+ * `signal` is the run's abort, when there is a run. Without it a stop or an
1459
+ * unmount would leave the loop waiting on a promise nobody will ever resolve
1460
+ * and the panel stuck busy forever — so the abort answers the question, and
1461
+ * the only safe answer is no. A call that arrived over the relay has no run
1462
+ * and therefore no signal: that question stays open until somebody answers
1463
+ * it, `MountOptions.approvalTimeout` lapses, or this panel is unmounted.
1464
+ *
1465
+ * `teardown` is that last one: the answer to give if the panel is unmounted
1466
+ * with the question still on screen. It is a parameter rather than a
1467
+ * constant because the two callers are owed different answers. The in-page
1468
+ * run is being stopped, so a veto is the truth and the model is told. A
1469
+ * question asked from inside `driver.call()` has somebody waiting on an
1470
+ * approval, and "the panel went away" is nobody answering rather than
1471
+ * somebody refusing — `{ timedOut: true }`, which the record keeps apart
1472
+ * from `declined`. Confusing those two is the thing this whole mechanism
1473
+ * exists to stop doing.
1474
+ */
1475
+ function askPerson(req, count, signal, teardown) {
1476
+ // A question nobody can see is not a question. The person may have hit
1477
+ // Escape while the model was thinking, or be reading the settings view.
1478
+ setOpen(true);
1479
+ setSettingsOpen(false);
1480
+ // From here until somebody answers, the stored record says a question was
1481
+ // open on this verb. `asked` and not `sent`: the core asks BEFORE it runs,
1482
+ // so if the page dies now the verb provably did not run, and the restored
1483
+ // panel can say that flatly instead of hedging. Written down at once rather
1484
+ // than at the next transcript change, because the event this is for is a
1485
+ // page that goes away without warning.
1486
+ inFlight = { verb: req.verb.name, phase: "asked" };
1487
+ rememberNow();
1488
+ // The clock on the human wait starts here and stops in the `finally`
1489
+ // below, whichever way the question is answered -- yes, no, a timeout, the
1490
+ // panel being torn down. See `waitedMs`.
1491
+ const askedAt = Date.now();
1492
+ const reversible = req.verb.reversible === true;
1493
+ const large = count !== undefined && count > askAbove;
1494
+ const row = el("div", "dk-ask");
1495
+ const question = el("div", "dk-ask-q");
1496
+ question.textContent =
1497
+ count === undefined
1498
+ ? `${req.verb.describe}?`
1499
+ : `${req.verb.describe} — ${commas(count)} rows?`;
1500
+ const why = el("div", "dk-ask-why");
1501
+ // The two dialogs must not read alike. Two questions with the same words
1502
+ // are one question as far as a person's attention is concerned, and the
1503
+ // person who stops reading the reversible one has stopped reading the
1504
+ // other one too — which is the failure this whole change exists to avoid,
1505
+ // reintroduced one level down. So a reversible commit says there is a way
1506
+ // back, and says why it is being asked about at all when the only reason
1507
+ // is the size.
1508
+ why.textContent =
1509
+ (reversible
1510
+ ? "This changes data, but the app says this can be undone." +
1511
+ (large
1512
+ ? " You are being asked because of how many rows it affects: an undo over" +
1513
+ " this many is a promise an app may not be able to keep."
1514
+ : "")
1515
+ : "This changes data and may be irreversible.") +
1516
+ (count === undefined
1517
+ ? " No count was reported, so nobody can tell you how many rows it affects."
1518
+ : "") +
1519
+ argSummary(req.args);
1520
+ const yes = el("button", "dk-yes");
1521
+ yes.textContent = "Yes, do it";
1522
+ yes.setAttribute("type", "button");
1523
+ const no = el("button", "dk-no");
1524
+ no.textContent = "No";
1525
+ no.setAttribute("type", "button");
1526
+ row.appendChild(question);
1527
+ row.appendChild(why);
1528
+ row.appendChild(no);
1529
+ row.appendChild(yes);
1530
+ post(row);
1531
+ // Focus the safe answer, not the destructive one. A person pressing Enter
1532
+ // on a dialog that appeared while they were typing should not thereby
1533
+ // accept a thousand rows; reaching "Yes" takes one deliberate key.
1534
+ no.focus?.();
1535
+ return new Promise((resolve) => {
1536
+ let answered = false;
1537
+ const answer = (decision, said) => {
1538
+ if (answered)
1539
+ return;
1540
+ answered = true;
1541
+ // The human wait is over, however it ended. Counted on EVERY exit --
1542
+ // yes, no, a stopped run, the panel being torn down -- because a model
1543
+ // told a declined commit "took 40 seconds" has learnt the same false
1544
+ // thing about the app's speed as one told it about an approved commit.
1545
+ waitedMs += Math.max(0, Date.now() - askedAt);
1546
+ // The question is no longer open. Whether the verb then RUNS is the
1547
+ // core's business and the call path's; `onCall` sets `sent` a moment
1548
+ // later for an approved commit, and for a declined one nothing runs and
1549
+ // the record correctly says nothing was in flight.
1550
+ if (inFlight?.phase === "asked" && inFlight.verb === req.verb.name) {
1551
+ inFlight = undefined;
1552
+ }
1553
+ openQuestions.delete(onTeardown);
1554
+ // The buttons go and the answer stays. Scrolling back through a
1555
+ // transcript and finding a live "Yes, do it" button beside something
1556
+ // that already happened is worse than no record at all.
1557
+ yes.remove();
1558
+ no.remove();
1559
+ const outcome = el("div", "dk-ask-said");
1560
+ outcome.textContent = said;
1561
+ row.appendChild(outcome);
1562
+ scroll();
1563
+ resolve(decision);
1564
+ };
1565
+ yes.addEventListener("click", () => answer(true, "You allowed this."));
1566
+ no.addEventListener("click", () => answer(false, "You said no."));
1567
+ signal?.addEventListener?.("abort", () => answer("the run was stopped before this ran", "Stopped before this ran."));
1568
+ // Registered last, so the set only ever holds questions that are
1569
+ // genuinely open — a signal that had already fired answered above and
1570
+ // deleted this before it was ever added.
1571
+ openQuestions.add(onTeardown);
1572
+ function onTeardown() {
1573
+ answer(teardown, "The panel was closed before this was answered.");
1574
+ }
1575
+ });
1576
+ }
1577
+ // ---- bits --------------------------------------------------------------
1578
+ function el(tag, className) {
1579
+ const node = doc.createElement(tag);
1580
+ node.className = className;
1581
+ return node;
1582
+ }
1583
+ function say(className, text) {
1584
+ const line = el("div", className);
1585
+ line.textContent = text;
1586
+ return post(line);
1587
+ }
1588
+ /** Put one element in the transcript, and remember that it is in there.
1589
+ * Everything that appends to the log goes through here, because a line that
1590
+ * skipped it would be a line "clear conversation" could not clear — which
1591
+ * is a transcript that is half gone, the one outcome worse than either
1592
+ * keeping it or dropping it. */
1593
+ function post(node) {
1594
+ lines.push(node);
1595
+ log.appendChild(node);
1596
+ scroll();
1597
+ return node;
1598
+ }
1599
+ /**
1600
+ * Write the conversation down as it stands.
1601
+ *
1602
+ * Called after every event that changes what a restored panel would show: a
1603
+ * question going up or coming down, a call being announced or settling, the
1604
+ * model saying something, a run ending. Not debounced and not deferred to
1605
+ * `beforeunload`. The event this whole feature exists for is a page that goes
1606
+ * away WITHOUT warning — a crash, a navigation the agent itself caused — so a
1607
+ * scheme that batches is a scheme that loses exactly the moment it was built
1608
+ * to remember. Each write is a `JSON.stringify` of an already-pruned
1609
+ * conversation and one `setItem`, which is cheaper than the model round trip
1610
+ * on either side of it.
1611
+ *
1612
+ * `at` is the caller's `era`, where the caller is inside a run. A write from a
1613
+ * run the person has cleared must not land, for the reason `era` exists at
1614
+ * all: an abort resolves at the loop's next await, so a run can still be
1615
+ * speaking after its conversation has been thrown away — and here that write
1616
+ * would go to DISK, where a reload brings it back. The clear itself forgets
1617
+ * the key, so the only way a cleared conversation could return is a stray
1618
+ * write afterwards, and this is what stops it.
1619
+ *
1620
+ * Three things make this a no-op, in order of how often they happen: the app
1621
+ * did not opt in, the viewer switched it off, or there is nothing to store. On
1622
+ * the viewer's switch it also FORGETS — turning the setting off is a request
1623
+ * about what is on the disk, not just about what happens next.
1624
+ */
1625
+ function rememberNow(at) {
1626
+ if (session === undefined)
1627
+ return;
1628
+ if (at !== undefined && at !== era)
1629
+ return;
1630
+ if (!settings.rememberChat) {
1631
+ forgetChat(session, app);
1632
+ return;
1633
+ }
1634
+ // The run in flight, when there is one, because a conversation stored
1635
+ // halfway through a run is the entire point. See `live`.
1636
+ const conversation = liveTurns ?? messages;
1637
+ if (conversation.length === 0 && inFlight === undefined) {
1638
+ // Nothing worth coming back to. Written as a forget rather than as an
1639
+ // empty record so that a fresh panel in a reloaded tab is a fresh panel,
1640
+ // not one announcing that it restored nothing.
1641
+ forgetChat(session, app);
1642
+ return;
1643
+ }
1644
+ // Scrub, then trim, in that order and not the other way round. Scrubbing
1645
+ // replaces a value with a shorter marker, so doing it first can only make
1646
+ // the record smaller -- and trimming first would decide what to keep on the
1647
+ // strength of bytes that are about to be thrown away anyway. Both at this
1648
+ // one boundary: see `scrubTurns` on why the redaction is here and not at
1649
+ // the call sites that build turns.
1650
+ const scrubbed = scrubTurns(conversation, driver.manifest());
1651
+ const { messages: kept, trimmed } = trimTurns(scrubbed);
1652
+ saveChat(session, app, {
1653
+ at: Date.now(),
1654
+ messages: kept,
1655
+ conversed,
1656
+ ...(inFlight === undefined ? {} : { inFlight }),
1657
+ ...(trimmed ? { trimmed } : {}),
1658
+ });
1659
+ }
1660
+ /**
1661
+ * Bring back whatever the last page load left, and resume nothing.
1662
+ *
1663
+ * Run once, at mount, after the greeting. What comes back is the
1664
+ * conversation: the model turns go into `messages`, so the person's next
1665
+ * message carries on from where they were, and a readable line per turn goes
1666
+ * into the transcript so the panel does not look empty while secretly
1667
+ * remembering everything.
1668
+ *
1669
+ * **What is deliberately NOT restored, and why none of it is an oversight.**
1670
+ * No run is restarted and no verb is called — see `chat.ts` on "restore
1671
+ * everything, resume nothing". The step list's live states are not redrawn,
1672
+ * because a marker that says "running" about a run which ended at a reload is
1673
+ * a panel lying about the present. The screen blocks in the stored turns are
1674
+ * not displayed, though the newest is still handed to the model, because a
1675
+ * wall of table is not what somebody wants to see first.
1676
+ *
1677
+ * The notice goes LAST, under the restored history, because that is where the
1678
+ * panel scrolls to and where the eye lands — and the first of its lines is
1679
+ * the one about what may have happened to the data.
1680
+ */
1681
+ function restoreConversation() {
1682
+ if (session === undefined || !settings.rememberChat)
1683
+ return;
1684
+ const found = loadChat(session, app);
1685
+ if (!found)
1686
+ return;
1687
+ // Every dangling `tool_use` gets an answer before this history can ever
1688
+ // reach a provider. Not optional and not cosmetic: a `tool_use` with no
1689
+ // result is a 400 on the person's next message and on every message after
1690
+ // it, with a transcript on screen that looks fine. See `closeDangling`.
1691
+ messages = closeDangling(found.messages, found.inFlight);
1692
+ conversed = found.conversed;
1693
+ for (const line of replayLines(found))
1694
+ say(line.className, line.text);
1695
+ for (const line of restoredLines(found))
1696
+ say("dk-note", line);
1697
+ // Rewritten at once, with the dangling calls now answered and `inFlight`
1698
+ // cleared. Otherwise a second reload would re-announce a call that is two
1699
+ // reloads old as though it had just been interrupted, and the person would
1700
+ // be sent to check the same verb again.
1701
+ inFlight = undefined;
1702
+ rememberNow();
1703
+ }
1704
+ /**
1705
+ * Drop the transcript, the step list and the history, and stop whatever is
1706
+ * running. See the settings row for why this is where it lives and why it
1707
+ * asks nothing first.
1708
+ */
1709
+ function clearConversation() {
1710
+ // First, and through the run's own controller: the loop must not be left
1711
+ // holding `messages` the panel has just thrown away. `era` is what keeps
1712
+ // that run's dying words — its stop note, its abandoned steps, the history
1713
+ // it hands back — out of the conversation that replaces it.
1714
+ era++;
1715
+ running?.abort();
1716
+ messages = [];
1717
+ // Before anything else that could write, and unconditional. `era` already
1718
+ // stops a dying run's words landing in the fresh transcript, and a stored
1719
+ // record is the same hazard with a longer fuse: clear the panel, reload,
1720
+ // and a cleared conversation comes back off disk. The destructive option
1721
+ // has to be destructive all the way down -- and `rememberNow` below is
1722
+ // era-guarded, so the aborted run cannot write the old transcript back
1723
+ // after this.
1724
+ inFlight = undefined;
1725
+ forgetChat(session, app);
1726
+ for (const line of lines)
1727
+ line.remove();
1728
+ lines.length = 0;
1729
+ conversed = false;
1730
+ say("dk-note", greeting);
1731
+ // Out of the settings view, because the thing the person just acted on is
1732
+ // the conversation and that is not the view they are looking at. This also
1733
+ // puts focus in the input, which is where a fresh panel starts.
1734
+ setSettingsOpen(false);
1735
+ // Said out loud as well, because the panel going empty is a change
1736
+ // somebody who cannot see it has no other way to notice.
1737
+ status.textContent = "Conversation cleared";
1738
+ }
1739
+ /** One row of the step list, created the first time a call is mentioned and
1740
+ * returned every time after, so the plan and the call and the result are
1741
+ * three states of ONE row rather than three rows about one call. */
1742
+ function step(steps, e) {
1743
+ const { call, kind } = e;
1744
+ const found = steps.get(call.id);
1745
+ if (found)
1746
+ return found;
1747
+ const entry = {
1748
+ line: el("div", "dk-step"),
1749
+ // `commit` is marked for the person as well as in the prompt for the
1750
+ // model. Those are not the same thing, and this is the row somebody
1751
+ // scrolls back to when they want to know what changed their data.
1752
+ commit: kind === "commit",
1753
+ text: `${call.name}${kind ? ` (${kind})` : ""}${argSummary(call.args)}`,
1754
+ };
1755
+ entry.line.textContent = entry.text;
1756
+ if (entry.commit) {
1757
+ entry.line.setAttribute("title", "Changes data, and may be irreversible.");
1758
+ }
1759
+ steps.set(call.id, entry);
1760
+ post(entry.line);
1761
+ return entry;
1762
+ }
1763
+ /** The state, as classes. Never as text: the row's text is the record of the
1764
+ * call and should read the same whether somebody looked at it while it was
1765
+ * pending or a minute afterwards. The marker is a `::before` in `css.ts`. */
1766
+ function mark(entry, state) {
1767
+ entry.line.className = `dk-step dk-step-${state}${entry.commit ? " dk-step-commit" : ""}`;
1768
+ }
1769
+ function outcome(entry, said, state) {
1770
+ entry.text += said;
1771
+ entry.line.textContent = entry.text;
1772
+ mark(entry, state);
1773
+ scroll();
1774
+ }
1775
+ /**
1776
+ * Outline whatever this call's `at` names, if it names anything.
1777
+ *
1778
+ * `at` is PRESENTATIONAL and this is the only thing done with it. It is
1779
+ * never used to find something to call, never clicked, never read for a
1780
+ * value, and its absence never changes what runs — which is most calls,
1781
+ * since most verbs declare no `at` at all. A selector anywhere in the
1782
+ * execution path is the failure mode this library exists to avoid; see
1783
+ * `highlight.ts`.
1784
+ */
1785
+ function aim(e) {
1786
+ if (!settings.highlight)
1787
+ return;
1788
+ spot.show(e.at);
1789
+ }
1790
+ /** A labelled block in the settings view: what it is, and why anybody would
1791
+ * touch it. A settings view that only names its switches is a settings view
1792
+ * people change at random. */
1793
+ function setRow(label, why) {
1794
+ const row = el("div", "dk-set-row");
1795
+ const name = el("div", "dk-set-label");
1796
+ name.textContent = label;
1797
+ const reason = el("div", "dk-set-why");
1798
+ reason.textContent = why;
1799
+ row.appendChild(name);
1800
+ row.appendChild(reason);
1801
+ return row;
1802
+ }
1803
+ /** A real `<button role="switch">`, so it is reachable by keyboard and
1804
+ * announced as on or off, rather than a styled div with a click handler. */
1805
+ function toggle(className, label, get, set) {
1806
+ const button = el("button", `dk-toggle ${className}`);
1807
+ button.textContent = label;
1808
+ button.setAttribute("type", "button");
1809
+ button.setAttribute("role", "switch");
1810
+ const paint = () => button.setAttribute("aria-checked", get() ? "true" : "false");
1811
+ paint();
1812
+ button.addEventListener("click", () => {
1813
+ set(!get());
1814
+ paint();
1815
+ remember();
1816
+ });
1817
+ return button;
1818
+ }
1819
+ function setPace(ms) {
1820
+ settings.pace = clampPace(ms);
1821
+ paintSpeeds();
1822
+ show(runState);
1823
+ remember();
1824
+ // Live, and that is the whole reason the controls have a setter: the
1825
+ // moment somebody wants the agent slowed down is while it is going. A
1826
+ // slider that quietly applied next run would be worse than no slider —
1827
+ // they move it, nothing happens, and they conclude it is broken.
1828
+ active?.pace(settings.pace);
1829
+ }
1830
+ function paintSpeeds() {
1831
+ const now = nearestSpeed(settings.pace);
1832
+ for (const { speed, button } of speedButtons) {
1833
+ button.setAttribute("aria-checked", speed.id === now.id ? "true" : "false");
1834
+ }
1835
+ }
1836
+ /** What the run is doing, in the one place that says it. */
1837
+ function show(state) {
1838
+ const was = runState;
1839
+ runState = state;
1840
+ const held = state === "paused";
1841
+ pause.textContent = held ? "Resume" : "Pause";
1842
+ pause.setAttribute("aria-label", held ? "Resume the run" : "Pause the run");
1843
+ const speed = nearestSpeed(settings.pace);
1844
+ note.textContent =
1845
+ state === "paused"
1846
+ ? "Paused"
1847
+ : // Not "running": the run is waiting for the person, and a panel that
1848
+ // said "running" there would be telling them to wait for the thing
1849
+ // that is waiting for them.
1850
+ state === "awaiting-approval"
1851
+ ? "Waiting for you"
1852
+ : `${speed.label} · ${settings.pace} ms a step`;
1853
+ // Announced on a change and only while a run is in flight. A pause is a
1854
+ // change to what the app is about to do next, and the panel is not
1855
+ // necessarily where the person is looking.
1856
+ if (isBusy && state !== was) {
1857
+ status.textContent = held ? "Run paused" : state === "awaiting-approval" ? "Waiting for you" : "Run continuing";
1858
+ }
1859
+ }
1860
+ function setSettingsOpen(next) {
1861
+ isSettings = next;
1862
+ // Before the paint, so the numbers a person reads are the numbers as of the
1863
+ // moment they opened the view and not as of whenever the panel was built.
1864
+ if (next)
1865
+ paintBudget();
1866
+ gear.setAttribute("aria-expanded", next ? "true" : "false");
1867
+ paintWrap();
1868
+ // Focus follows, in both directions, and lands on the first thing worth
1869
+ // changing rather than on the container.
1870
+ (next ? speedButtons[0]?.button ?? done : input).focus?.();
1871
+ }
1872
+ function remember() {
1873
+ saveSettings(storage, app, settings);
1874
+ }
1875
+ function scroll() {
1876
+ // Both guarded: `scrollHeight` does not exist on a fake and `scrollTop` is
1877
+ // a courtesy, not part of the contract.
1878
+ if (typeof log.scrollTop === "number" && typeof log.scrollHeight === "number") {
1879
+ log.scrollTop = log.scrollHeight;
1880
+ }
1881
+ }
1882
+ function paintWrap() {
1883
+ wrap.className = `dk-wrap${isOpen ? " dk-open" : ""}${isBusy ? " dk-busy" : ""}${isSettings ? " dk-set-open" : ""}`;
1884
+ paintLauncher();
1885
+ }
1886
+ /**
1887
+ * The dot in the launcher, and the launcher's accessible name with it.
1888
+ *
1889
+ * On when the panel is minimised AND there is something behind it: a
1890
+ * conversation, or a run still going. Both, because they are different
1891
+ * reasons to look: the run is the urgent one and the transcript is the one
1892
+ * that is still true an hour later. Not on while the panel is open, where
1893
+ * the transcript is the thing the person is looking at and a dot would be
1894
+ * saying so to somebody already reading it.
1895
+ */
1896
+ function paintLauncher() {
1897
+ const waiting = !isOpen && (conversed || isBusy);
1898
+ dot.className = waiting ? "dk-dot dk-dot-on" : "dk-dot";
1899
+ launcher.setAttribute("aria-label", waiting ? WAITING_LABEL : ASK_LABEL);
1900
+ launcher.setAttribute("title", waiting ? WAITING_LABEL : ASK_LABEL);
1901
+ }
1902
+ function setOpen(next) {
1903
+ isOpen = next;
1904
+ // A closed panel is not a panel with a settings view open inside it. The
1905
+ // alternative is that reopening lands somebody in the settings instead of
1906
+ // the conversation they were having.
1907
+ if (!next) {
1908
+ isSettings = false;
1909
+ gear.setAttribute("aria-expanded", "false");
1910
+ }
1911
+ paintWrap();
1912
+ launcher.setAttribute("aria-expanded", next ? "true" : "false");
1913
+ // Focus follows the panel in both directions. A keyboard user who opens a
1914
+ // panel and is left on the launcher has to tab back through the whole app
1915
+ // to reach it, and one who closes it and is left nowhere has lost their
1916
+ // place entirely.
1917
+ (next ? input : launcher).focus?.();
1918
+ }
1919
+ function busy(on) {
1920
+ isBusy = on;
1921
+ paintWrap();
1922
+ if (on)
1923
+ send.setAttribute("disabled", "disabled");
1924
+ else
1925
+ send.removeAttribute("disabled");
1926
+ }
1927
+ return {
1928
+ open: () => setOpen(true),
1929
+ close: () => setOpen(false),
1930
+ ask,
1931
+ // The same function the panel adopts as the core's approver, so an app
1932
+ // that wires this up by hand and an app that wires up nothing get the
1933
+ // identical dialog, the identical rules and the identical record.
1934
+ approve: approveRequest,
1935
+ question: questionFor,
1936
+ moveTo: place.moveTo,
1937
+ position: place.chosen,
1938
+ unmount: () => {
1939
+ // Idempotent, and it aborts a run in flight. Unmounting while a commit
1940
+ // is pending is the case worth thinking about: the abort stops the loop
1941
+ // before the next verb, but a verb already inside `driver.call()` runs
1942
+ // to completion. That is the right behaviour — tearing down a panel must
1943
+ // not leave a half-applied bulk edit — but it means `unmount` is not a
1944
+ // promise that nothing further will change.
1945
+ live = false;
1946
+ running?.abort();
1947
+ running = null;
1948
+ // The gate goes back to whatever the app declared, BEFORE the questions
1949
+ // are drained: a commit arriving in between must not be sent to a dialog
1950
+ // that is already being torn down. After this the core's policy is
1951
+ // `declared` again — `none` for a widget-only app — so a later commit is
1952
+ // ungated and records `not-asked, none`, which is then the truth.
1953
+ release?.();
1954
+ // Nobody is going to answer these. An unmount with a question open is
1955
+ // ordinary — the person closes the app's tab, the host swaps a route —
1956
+ // and `driver.call()` is sitting on a promise that only this panel can
1957
+ // resolve, with no `approvalTimeout` by default. Left alone that is a
1958
+ // driver that refuses every later call `approval-pending` until the page
1959
+ // is reloaded: a dead app, caused by closing a chat panel.
1960
+ for (const answer of [...openQuestions])
1961
+ answer();
1962
+ openQuestions.clear();
1963
+ // Before the element goes, because the resize listener is on the window
1964
+ // and would otherwise outlive the panel it was clamping.
1965
+ place.dispose();
1966
+ // The outline has its own host element and its own window listeners, and
1967
+ // both would otherwise outlive the panel that drew them.
1968
+ spot.dispose();
1969
+ host.remove();
1970
+ },
1971
+ };
1972
+ }
1973
+ /** A short, safe rendering of a call's arguments for a step row.
1974
+ *
1975
+ * Truncated, because an argument can be a predicate and a predicate can be
1976
+ * long, and a trace line that wraps to four lines stops being skimmable —
1977
+ * which is the only thing the trace is for. */
1978
+ function argSummary(args) {
1979
+ const parts = Object.entries(args).map(([k, v]) => `${k}=${String(v)}`);
1980
+ if (!parts.length)
1981
+ return "";
1982
+ const text = parts.join(" ");
1983
+ return ` ${text.length > 60 ? text.slice(0, 57) + "…" : text}`;
1984
+ }
1985
+ function message(err) {
1986
+ return err instanceof Error ? err.message : String(err);
1987
+ }
1988
+ /**
1989
+ * Said once, for an arrangement the author has to fix in their own source.
1990
+ *
1991
+ * The core's shape, deliberately copied rather than imported: `registry.ts`
1992
+ * keeps its `warn` private, and a panel that printed the same sentence on every
1993
+ * commit would be a panel people learn to mute. Deduped per message, so a run
1994
+ * that confirms forty commits says this once.
1995
+ */
1996
+ const warned = new Set();
1997
+ function warn(text) {
1998
+ if (warned.has(text))
1999
+ return;
2000
+ warned.add(text);
2001
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
2002
+ console.warn(`driverkit: ${text}`);
2003
+ }
2004
+ }
2005
+ //# sourceMappingURL=widget.js.map