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,695 @@
1
+ /**
2
+ * The React panel's state, with no React in it.
3
+ *
4
+ * WHY THE STATE IS NOT IN REACT. Everything the panel knows — the transcript,
5
+ * the step list, the run's control state, the approval state machine — lives in
6
+ * a plain object with `subscribe`/`getSnapshot`, and the React layer is a
7
+ * `useSyncExternalStore` call over it. Three reasons, in the order they
8
+ * mattered while writing it:
9
+ *
10
+ * 1. **It is the half that has to be tested, and this repository has no
11
+ * React.** The published package depends on nothing and there is no
12
+ * network install here, so a state machine expressed as `useReducer`
13
+ * plus eight `useEffect`s would be a state machine nothing in the suite
14
+ * could drive. The approval receipt — the one behaviour this area exists
15
+ * to get right — is asserted in `test/react.test.ts` against this file,
16
+ * with no renderer involved.
17
+ *
18
+ * 2. **`drive` is not a React citizen.** It is an async loop that fires
19
+ * callbacks from inside awaits, and callbacks that land after an unmount
20
+ * or after a Clear are the normal case rather than the exception. A store
21
+ * can be written once to be correct about that — see `era` — where a
22
+ * component tree would have to be correct about it at every subscription
23
+ * point.
24
+ *
25
+ * 3. **It is what makes the components replaceable.** A host with a design
26
+ * system wants our behaviour and its own markup. If the behaviour is in
27
+ * the components, "restyle it" means "fork it". Here a host can take
28
+ * `useDriver()` and render none of our components at all, and nothing
29
+ * about the gate, the pacing or the receipt changes.
30
+ *
31
+ * The parts of the vanilla widget's reasoning that still apply are applied
32
+ * here and marked; the ones that do not are listed in `REACT.md` with why.
33
+ */
34
+ import { commas, drive, runControls } from "../agent/index.js";
35
+ /**
36
+ * The selection size past which a commit is confirmed even though the app
37
+ * called it reversible.
38
+ *
39
+ * **Deliberately the same number as `COMMIT_ASK_ABOVE` in
40
+ * `src/widget/widget.ts`, and deliberately not imported from it.** Importing it
41
+ * would make this area's module graph include the vanilla widget's, and
42
+ * therefore its hand-written DOM, its stylesheet, its drag positioner and its
43
+ * `localStorage` access — in a React app's bundle, to read one integer. The
44
+ * whole promise of this entry point is that the two panels are independent, and
45
+ * a constant is not worth breaking it for.
46
+ *
47
+ * Two copies of a number drift, so the drift is a test failure rather than a
48
+ * hope: `test/react.test.ts` pins that these two agree. The reasoning behind
49
+ * the value — why a screenful rather than the thousands where an app's undo
50
+ * actually stops being credible — is written once, over there, and is not
51
+ * restated here so that there is still only one place it can be argued with.
52
+ */
53
+ export const COMMIT_ASK_ABOVE = 25;
54
+ const STOP_NOTE = {
55
+ // Nothing to add: the model's own prose is already in the transcript.
56
+ answered: null,
57
+ silent: "The model replied with nothing. That is usually a bug in `think`.",
58
+ "max-steps": "Stopped: this took more steps than allowed. Ask again, more specifically.",
59
+ stuck: "Stopped: the same call kept being refused, so going on would not have helped.",
60
+ "over-budget": "Stopped: this app's limit on what one session may spend is reached. Asking again will " +
61
+ "not help — the limit is set by the app, not by the panel.",
62
+ aborted: "Stopped.",
63
+ };
64
+ /**
65
+ * What a receipt says, as one short line of plain text.
66
+ *
67
+ * A pure function and exported, for two reasons. It is what the card renders
68
+ * into its `role="status"`, and a status line is the one piece of this that a
69
+ * screen reader user gets instead of the layout, so it is asserted directly in
70
+ * the suite rather than through a renderer. And a host replacing the card keeps
71
+ * the wording without having to re-derive it from the phase — the phases are a
72
+ * state machine and the sentences are a product decision, and a host should be
73
+ * able to take the second without reimplementing the first.
74
+ */
75
+ export function receiptLine(entry) {
76
+ switch (entry.phase) {
77
+ case "asking":
78
+ return "Waiting for your decision.";
79
+ case "allowed":
80
+ return entry.via ? `Allowed by your rule: ${entry.via}. Running.` : "Approved, running.";
81
+ case "allowed-ok":
82
+ return "Approved. Finished.";
83
+ // Approved and then refused by the app anyway. The receipt says both,
84
+ // because a reader who is told only the first has been told the half that
85
+ // flatters us.
86
+ case "allowed-refused":
87
+ return `Approved, but the app refused it: ${entry.refused ?? "refused"}.`;
88
+ case "denied":
89
+ return entry.via ? `Refused by your rule: ${entry.via}.` : "Denied. Nothing was changed.";
90
+ case "stopped":
91
+ return "The run was stopped before this ran. Nothing was changed.";
92
+ case "lapsed":
93
+ return "The panel closed before anybody answered. Nothing was changed.";
94
+ }
95
+ }
96
+ /** The step list's outcome phrase, given a result. Pure, so the suite can read
97
+ * it without a renderer, and so a host's own row renders the same words. */
98
+ export function stepOutcome(ok, refused, count) {
99
+ if (!ok)
100
+ return `refused: ${refused ?? "refused"}`;
101
+ return count === undefined ? "ok" : `ok · ${commas(count)} matched`;
102
+ }
103
+ export function createPanelStore(driver, options) {
104
+ const Abort = options.AbortController ?? globalThis.AbortController;
105
+ const askAbove = options.commitAskAbove ?? COMMIT_ASK_ABOVE;
106
+ let entries = [];
107
+ let messages = [];
108
+ let running = null;
109
+ let active = null;
110
+ let runState = "running";
111
+ let paceMs = options.pace ?? 600;
112
+ let permits = 0;
113
+ let stepMode = options.stepMode === true;
114
+ let confirmCommits = options.confirmCommits !== false;
115
+ let grants = [];
116
+ let live = true;
117
+ let ids = 0;
118
+ /**
119
+ * Which conversation we are in. Kept for exactly the reason the vanilla
120
+ * widget keeps it, and the reason survives the move to React unchanged: an
121
+ * abort stops `drive` at its next await, so a call it had already announced
122
+ * can still arrive afterwards, and a step row about it would appear in a
123
+ * transcript the person has just emptied. React does not help with this —
124
+ * a `setState` from a stale async callback is exactly as wrong as an
125
+ * `appendChild` from one.
126
+ */
127
+ let era = 0;
128
+ /**
129
+ * The run's last `describe` count, which is the number the model just put on
130
+ * the screen. Cleared when a question is asked, because that is when it has
131
+ * been put in front of somebody and spoken for.
132
+ */
133
+ let lastCount;
134
+ const listeners = new Set();
135
+ /** Open questions, by entry id. */
136
+ const open = new Map();
137
+ /** Allowed questions waiting for the app's verdict, oldest first per verb. */
138
+ const awaiting = [];
139
+ let snapshot = build();
140
+ function build() {
141
+ const pending = entries.find((e) => e.kind === "approval" && e.phase === "asking");
142
+ return {
143
+ entries,
144
+ busy: running !== null,
145
+ runState,
146
+ paceMs,
147
+ permits,
148
+ stepMode,
149
+ confirmCommits,
150
+ ...(driver.budget ? { budget: driver.budget() } : {}),
151
+ grants,
152
+ ...(pending ? { pending } : {}),
153
+ era,
154
+ };
155
+ }
156
+ /** One new snapshot per change, and one notification. A fresh `entries`
157
+ * array every time, because a mutated array is a snapshot React cannot tell
158
+ * from the last one. */
159
+ function bump() {
160
+ entries = entries.slice();
161
+ snapshot = build();
162
+ for (const listener of [...listeners])
163
+ listener();
164
+ }
165
+ function id() {
166
+ return `dk${++ids}`;
167
+ }
168
+ function say(kind, text) {
169
+ entries.push({ kind, id: id(), text });
170
+ bump();
171
+ }
172
+ function patch(entry, changes) {
173
+ const at = entries.indexOf(entry);
174
+ if (at < 0)
175
+ return;
176
+ entries[at] = { ...entry, ...changes };
177
+ bump();
178
+ }
179
+ // ---- the gate ----------------------------------------------------------
180
+ //
181
+ // The rules below are the vanilla widget's, restated because they have to be
182
+ // the same rules: one of the two panels being laxer about a commit than the
183
+ // other would make "which panel is this app using" a security question.
184
+ /** How many rows the question is about, from the screen alone. */
185
+ function countFor(shot) {
186
+ return shot.selectedCount ?? shot.selected?.length;
187
+ }
188
+ /** Whether this commit gets a question. The three options' whole meaning. */
189
+ function shouldAsk(req, count) {
190
+ if (!confirmCommits)
191
+ return false;
192
+ // Absent means the app made no claim, which is gated: a commit that has not
193
+ // said there is a way back is treated as one that has not got one.
194
+ const reversible = req.verb.reversible === true;
195
+ const large = count !== undefined && count > askAbove;
196
+ return !reversible || options.confirmEveryCommit === true || large;
197
+ }
198
+ /** Whether `driver.call()` already asks, so this panel must not. */
199
+ function coreAsks() {
200
+ const policy = driver.approval?.policy;
201
+ return policy === "hook" || policy === "adopted";
202
+ }
203
+ /** Hold the core's no-other-calls lock while a question is open, so a second
204
+ * agent over the relay cannot press an approve button while the card sits
205
+ * there unanswered. */
206
+ function withLock(verb, ask) {
207
+ const hold = driver.approval?.hold;
208
+ return hold ? hold(verb, ask) : ask();
209
+ }
210
+ /** The rule a person would install from this card, in the words they read. */
211
+ function grantRule(verb, allow) {
212
+ return allow
213
+ ? `Always allow “${verb}” for the rest of this session, without asking`
214
+ : `Always refuse “${verb}” for the rest of this session, without asking`;
215
+ }
216
+ function grantFor(verb) {
217
+ return grants.find((g) => g.verb === verb);
218
+ }
219
+ /**
220
+ * Render the question and wait for an answer.
221
+ *
222
+ * `teardown` is the answer to give if the panel goes away with the question
223
+ * still on screen, and it is a parameter rather than a constant because the
224
+ * two callers are owed different answers — a veto for the in-page run that is
225
+ * being torn down with it, and `{ timedOut: true }` for a call that arrived
226
+ * from outside and has somebody waiting on an approval nobody will now give.
227
+ * Confusing those two is what the core's `timedOut` exists to stop.
228
+ */
229
+ function askPerson(req, count, signal, teardown) {
230
+ const entry = {
231
+ kind: "approval",
232
+ id: id(),
233
+ verb: req.name,
234
+ describe: req.verb.describe,
235
+ args: req.args,
236
+ ...(count === undefined ? {} : { count }),
237
+ reversible: req.verb.reversible === true,
238
+ large: count !== undefined && count > askAbove,
239
+ phase: "asking",
240
+ ...(options.grants ? { grantOffer: grantRule(req.name, true) } : {}),
241
+ };
242
+ entries.push(entry);
243
+ bump();
244
+ return new Promise((resolve) => {
245
+ let answered = false;
246
+ /**
247
+ * The buttons go and the receipt stays, in the same entry.
248
+ *
249
+ * This is the whole point of the area. The question keeps its id, its
250
+ * place in the transcript and its own words; only `phase` moves. A card
251
+ * that unmounted on decision and left a separate outcome line behind
252
+ * would break the question/answer link in scrollback, which is the one
253
+ * link the only auditable feature in the library depends on.
254
+ */
255
+ const answer = (approval, phase, note) => {
256
+ if (answered)
257
+ return;
258
+ answered = true;
259
+ open.delete(entry.id);
260
+ const found = entries.find((e) => e.id === entry.id);
261
+ const row = found ?? entry;
262
+ patch(row, {
263
+ phase,
264
+ ...(note === undefined || note === "" ? {} : { note }),
265
+ });
266
+ // Allowed and inside a run: the app has still to have its say, and the
267
+ // receipt is not finished until it has. Parked by verb name, oldest
268
+ // first, which is how `onResult` finds it again.
269
+ if (phase === "allowed" && running) {
270
+ const settled = entries.find((e) => e.id === entry.id);
271
+ if (settled)
272
+ awaiting.push(settled);
273
+ }
274
+ resolve(approval);
275
+ };
276
+ open.set(entry.id, { entry, answer });
277
+ // An abort answers the question, and the only safe answer is no. Without
278
+ // this a stop would leave the loop waiting on a promise nobody resolves
279
+ // and the panel busy forever.
280
+ signal?.addEventListener("abort", () => answer("the run was stopped before this ran", "stopped"));
281
+ if (signal?.aborted)
282
+ answer("the run was stopped before this ran", "stopped");
283
+ // Registered after the signal check, so the map only holds genuinely open
284
+ // questions.
285
+ if (answered)
286
+ return;
287
+ open.set(entry.id, {
288
+ entry,
289
+ answer,
290
+ });
291
+ teardowns.set(entry.id, () => answer(teardown, "lapsed"));
292
+ });
293
+ }
294
+ const teardowns = new Map();
295
+ function decide(entryId, decision) {
296
+ const slot = open.get(entryId);
297
+ if (!slot)
298
+ return;
299
+ teardowns.delete(entryId);
300
+ const note = decision.note?.trim() ?? "";
301
+ // The rule is installed from the text that was on the card, not from a
302
+ // string built again here, so what was agreed to and what was stored
303
+ // cannot differ.
304
+ if (decision.always === true && options.grants) {
305
+ grants = [
306
+ ...grants.filter((g) => g.verb !== slot.entry.verb),
307
+ {
308
+ verb: slot.entry.verb,
309
+ rule: grantRule(slot.entry.verb, decision.allow),
310
+ allow: decision.allow,
311
+ },
312
+ ];
313
+ }
314
+ if (decision.allow) {
315
+ // `true` and never the note. The decision is the authorization; a note
316
+ // beside it is a comment on the record. Reading consent out of typed text
317
+ // would let the text authorize the call.
318
+ slot.answer(true, "allowed", note);
319
+ }
320
+ else {
321
+ // A denial's note IS load-bearing, in the other direction: the core turns
322
+ // a string into the hint the model is told, so "not until finance signs
323
+ // off" reaches the model where "declined" would not.
324
+ slot.answer(note === "" ? false : note, "denied", note);
325
+ }
326
+ }
327
+ /** This panel's dialog, as a `MountOptions.approve` hook. */
328
+ async function approve(req) {
329
+ const standing = options.grants ? grantFor(req.name) : undefined;
330
+ if (standing)
331
+ return receipt(req, standing);
332
+ // `lastCount` only while a run is in flight, and then first: a commit that
333
+ // arrived between runs has no run to have counted anything.
334
+ const count = (running ? lastCount : undefined) ?? countFor(req.snapshot);
335
+ // Not `true`. A gate that let this through without asking must not be
336
+ // recorded as a person saying yes — `{ asked: false }` is the core's word
337
+ // for this answer.
338
+ if (!shouldAsk(req, count))
339
+ return { asked: false };
340
+ lastCount = undefined;
341
+ const was = runState;
342
+ if (active)
343
+ show("awaiting-approval");
344
+ try {
345
+ // No `withLock`: the core takes its lock before calling an approver, and
346
+ // a second take would assert what is already true.
347
+ return await askPerson(req, count, running?.signal, CLOSED_LAPSE);
348
+ }
349
+ finally {
350
+ if (active)
351
+ show(was);
352
+ }
353
+ }
354
+ /**
355
+ * A commit answered by a standing rule. Posted as a receipt all the same.
356
+ *
357
+ * A rule that silenced the question must not also silence the record: the
358
+ * entry says which rule answered, so scrollback shows both that the commit
359
+ * happened and why nobody was asked. The answer handed back is
360
+ * `{ asked: false }` rather than `true`, because nobody WAS asked this time —
361
+ * which is exactly the distinction the core added that answer for. An app
362
+ * that needs every allowed commit to carry a person's yes in the audit record
363
+ * should leave `grants` off.
364
+ */
365
+ function receipt(req, rule) {
366
+ const count = (running ? lastCount : undefined) ?? countFor(req.snapshot);
367
+ const entry = {
368
+ kind: "approval",
369
+ id: id(),
370
+ verb: req.name,
371
+ describe: req.verb.describe,
372
+ args: req.args,
373
+ ...(count === undefined ? {} : { count }),
374
+ reversible: req.verb.reversible === true,
375
+ large: count !== undefined && count > askAbove,
376
+ phase: rule.allow ? "allowed" : "denied",
377
+ via: rule.rule,
378
+ };
379
+ entries.push(entry);
380
+ bump();
381
+ if (rule.allow) {
382
+ if (running)
383
+ awaiting.push(entries[entries.length - 1]);
384
+ return { asked: false };
385
+ }
386
+ return rule.rule;
387
+ }
388
+ const CLOSED_VETO = "the panel was closed before this was approved";
389
+ const CLOSED_LAPSE = {
390
+ timedOut: true,
391
+ hint: "the approval panel was closed while this was waiting to be approved, so nobody " +
392
+ "answered. **The verb did not run and nothing changed.** Ask the person to reopen the " +
393
+ "assistant, then call it again.",
394
+ };
395
+ // ---- the run -----------------------------------------------------------
396
+ function show(state) {
397
+ runState = state;
398
+ bump();
399
+ }
400
+ async function ask(text) {
401
+ if (!live || running)
402
+ return;
403
+ say("you", text);
404
+ const mine = era;
405
+ const controller = new Abort();
406
+ running = controller;
407
+ const control = (options.controls ?? runControls)({
408
+ pace: paceMs,
409
+ stepMode,
410
+ });
411
+ active = control;
412
+ // The controls have more than one owner — this panel's buttons move them
413
+ // and `drive` moves them too — so the panel reads them rather than
414
+ // remembering what it last asked for.
415
+ const unsubscribe = control.subscribe(() => {
416
+ paceMs = control.paceMs;
417
+ permits = control.permits;
418
+ bump();
419
+ });
420
+ paceMs = control.paceMs;
421
+ permits = control.permits;
422
+ show("running");
423
+ const steps = new Map();
424
+ lastCount = undefined;
425
+ /** The built-in gate, per run. Not installed when the core already asks. */
426
+ function confirmCommit(req) {
427
+ const standing = options.grants ? grantFor(req.name) : undefined;
428
+ if (standing) {
429
+ // `CommitDecision` has no `{ asked: false }`: it is `drive`'s option,
430
+ // not the core's hook, so a grant on this path can only say yes. The
431
+ // entry still records the rule, which is the half the panel owns.
432
+ const answer = receipt(req, standing);
433
+ return Promise.resolve(standing.allow ? true : answer);
434
+ }
435
+ const count = lastCount ?? countFor(req.snapshot);
436
+ if (!shouldAsk(req, count))
437
+ return Promise.resolve(true);
438
+ lastCount = undefined;
439
+ return withLock(req.name, async () => (await askPerson(req, count, controller.signal, CLOSED_VETO)));
440
+ }
441
+ const gate = options.onBeforeCommit ?? (coreAsks() ? undefined : confirmCommit);
442
+ function row(e) {
443
+ const found = steps.get(e.call.id);
444
+ if (found)
445
+ return found;
446
+ const entry = {
447
+ kind: "step",
448
+ id: id(),
449
+ callId: e.call.id,
450
+ verb: e.call.name,
451
+ ...(e.kind === undefined ? {} : { verbKind: e.kind }),
452
+ args: e.call.args,
453
+ ...(e.at === undefined ? {} : { at: e.at }),
454
+ commit: e.kind === "commit",
455
+ status: "pending",
456
+ };
457
+ entries.push(entry);
458
+ steps.set(e.call.id, entry);
459
+ bump();
460
+ return entry;
461
+ }
462
+ function current(e) {
463
+ const found = entries.find((x) => x.id === e.id);
464
+ return found ?? e;
465
+ }
466
+ const paced = {
467
+ think: options.think,
468
+ task: text,
469
+ history: messages,
470
+ ...(options.instructions === undefined ? {} : { instructions: options.instructions }),
471
+ ...(options.maxSteps === undefined ? {} : { maxSteps: options.maxSteps }),
472
+ ...(options.refusalLimit === undefined ? {} : { refusalLimit: options.refusalLimit }),
473
+ ...(gate ? { onBeforeCommit: gate } : {}),
474
+ signal: controller.signal,
475
+ controls: control,
476
+ pace: paceMs,
477
+ ...(options.clock === undefined ? {} : { clock: options.clock }),
478
+ // A row appears on `onBeforeCall`, which fires before the pace wait and
479
+ // before any hold — the only way "you can see it coming and stop it" is
480
+ // true rather than aspirational.
481
+ onBeforeCall: (e) => {
482
+ if (era !== mine)
483
+ return;
484
+ const entry = row(e);
485
+ const now = current(entry);
486
+ steps.set(e.call.id, now);
487
+ patch(now, { status: "pending" });
488
+ options.onAim?.(e.at);
489
+ },
490
+ onCall: (e) => {
491
+ if (era !== mine)
492
+ return;
493
+ const entry = steps.get(e.call.id) ?? row(e);
494
+ patch(current(entry), { status: "running" });
495
+ options.onAim?.(e.at);
496
+ },
497
+ onControl: ({ state }) => {
498
+ if (era !== mine)
499
+ return;
500
+ show(state);
501
+ },
502
+ onResult: ({ call, kind, result }) => {
503
+ if (era !== mine)
504
+ return;
505
+ if (kind === "describe" && result?.ok)
506
+ lastCount = result.count;
507
+ options.onAim?.(undefined);
508
+ settleReceipt(call.name, result);
509
+ const entry = steps.get(call.id);
510
+ if (!entry)
511
+ return;
512
+ const now = current(entry);
513
+ if (result === null) {
514
+ patch(now, { status: "done", outcome: "looked" });
515
+ return;
516
+ }
517
+ if (result.ok) {
518
+ // The count is repeated on the row on purpose. It is the number a
519
+ // commit decision turns on, and the person watching should be able to
520
+ // see "1,000 matched" without reading the model's summary of it.
521
+ patch(now, {
522
+ status: "done",
523
+ outcome: stepOutcome(true, undefined, result.count),
524
+ ...(result.count === undefined ? {} : { count: result.count }),
525
+ });
526
+ }
527
+ else {
528
+ // A refusal is an OUTCOME and not an error. The app said no, on
529
+ // purpose, in its own vocabulary, and the model is about to adapt to
530
+ // it; rendering it as a failure would teach the person to read a
531
+ // working app as a broken one.
532
+ patch(now, { status: "refused", outcome: stepOutcome(false, result.refused) });
533
+ }
534
+ },
535
+ onSay: ({ text: prose }) => {
536
+ if (era !== mine)
537
+ return;
538
+ say("assistant", prose);
539
+ },
540
+ };
541
+ try {
542
+ const out = await drive(driver, paced);
543
+ if (era !== mine)
544
+ return;
545
+ messages = out.messages;
546
+ const note = STOP_NOTE[out.stop];
547
+ if (note)
548
+ say("note", note);
549
+ }
550
+ catch (err) {
551
+ // Handed to `onError` whichever conversation it belonged to, and said in
552
+ // the transcript only if that transcript is still the one it is about.
553
+ options.onError?.(err);
554
+ if (era === mine) {
555
+ say("note", `Something went wrong talking to the model: ${message(err)}`);
556
+ }
557
+ }
558
+ finally {
559
+ unsubscribe();
560
+ running = null;
561
+ active = null;
562
+ lastCount = undefined;
563
+ runState = "running";
564
+ options.onAim?.(undefined);
565
+ if (era === mine) {
566
+ // Rows for calls that never ran. A stop during a pace wait or a hold
567
+ // abandons them unrun and no `onResult` is coming, so leaving them
568
+ // pending would be a panel saying something is about to happen when the
569
+ // run is already over.
570
+ for (const entry of steps.values()) {
571
+ const now = current(entry);
572
+ if (now.status === "pending" || now.status === "running") {
573
+ patch(now, { status: "skipped", outcome: "not run" });
574
+ }
575
+ }
576
+ // And receipts for commits that were approved and then abandoned. The
577
+ // card must not be left reading "running" for something that never ran.
578
+ for (const entry of awaiting.slice()) {
579
+ const now = entries.find((x) => x.id === entry.id);
580
+ if (now && now.phase === "allowed")
581
+ patch(now, { phase: "stopped" });
582
+ }
583
+ }
584
+ awaiting.length = 0;
585
+ bump();
586
+ }
587
+ }
588
+ /**
589
+ * Move an approved receipt on to its final phase, from the app's own verdict.
590
+ *
591
+ * Correlated by verb name, oldest first. The gate is handed a
592
+ * `CommitRequest` carrying a name and arguments and no call id — the id
593
+ * exists one layer out, on the `ToolCall` — so a name is what there is to
594
+ * match on. It is sound for the case that exists: the core holds its
595
+ * no-other-calls lock across an approval, so a second commit of the same verb
596
+ * cannot be in flight while the first is still being asked about.
597
+ */
598
+ function settleReceipt(verb, result) {
599
+ const at = awaiting.findIndex((e) => e.verb === verb);
600
+ if (at < 0 || result === null)
601
+ return;
602
+ const [entry] = awaiting.splice(at, 1);
603
+ if (!entry)
604
+ return;
605
+ const now = entries.find((x) => x.id === entry.id);
606
+ if (!now || now.phase !== "allowed")
607
+ return;
608
+ patch(now, result.ok
609
+ ? { phase: "allowed-ok" }
610
+ : {
611
+ phase: "allowed-refused",
612
+ ...(result.refused === undefined ? {} : { refused: result.refused }),
613
+ });
614
+ }
615
+ function clear() {
616
+ // First, and through the run's own controller: the loop must not be left
617
+ // holding `messages` the panel has just thrown away.
618
+ running?.abort();
619
+ era++;
620
+ entries = [];
621
+ messages = [];
622
+ awaiting.length = 0;
623
+ if (options.greeting !== undefined) {
624
+ entries.push({ kind: "note", id: id(), text: options.greeting });
625
+ }
626
+ bump();
627
+ }
628
+ if (options.greeting !== undefined) {
629
+ entries.push({ kind: "note", id: id(), text: options.greeting });
630
+ snapshot = build();
631
+ }
632
+ return {
633
+ subscribe: (listener) => {
634
+ listeners.add(listener);
635
+ return () => listeners.delete(listener);
636
+ },
637
+ getSnapshot: () => snapshot,
638
+ ask,
639
+ stop: () => running?.abort(),
640
+ clear,
641
+ pause: () => active?.pause(),
642
+ resume: () => active?.resume(),
643
+ step: () => active?.step(),
644
+ setPace: (ms) => {
645
+ if (!Number.isFinite(ms) || ms < 0)
646
+ return;
647
+ paceMs = ms;
648
+ // Live, which is the whole reason the controls have a setter: the moment
649
+ // somebody wants the agent slowed down is while it is going.
650
+ active?.pace(ms);
651
+ bump();
652
+ },
653
+ setStepMode: (on) => {
654
+ stepMode = on;
655
+ bump();
656
+ },
657
+ setConfirmCommits: (on) => {
658
+ // Read per commit rather than per run, so turning confirmations off — or
659
+ // back on — in the middle of a run takes effect on the next commit. That
660
+ // is what somebody who has just watched a commit go past expects of the
661
+ // switch they reached for.
662
+ confirmCommits = on;
663
+ bump();
664
+ },
665
+ decide,
666
+ revoke: (verb) => {
667
+ grants = grants.filter((g) => g.verb !== verb);
668
+ bump();
669
+ },
670
+ approve,
671
+ destroyed: () => !live,
672
+ destroy: () => {
673
+ live = false;
674
+ // The open questions are lapsed BEFORE the run is aborted, and the order
675
+ // is the whole difference between two records. An abort answers an open
676
+ // question `stopped` through the signal listener in `ask`, and on an
677
+ // unmount that would be the less true of the two available facts: the
678
+ // run was stopped because the panel went away, and "the panel closed
679
+ // before anybody answered" is what somebody reading the receipt needs.
680
+ // Lapsing first is safe — a lapse answers the core with a refusal
681
+ // string, never an allow — and the abort still lands before the loop
682
+ // resumes, because it runs synchronously here and the loop can only
683
+ // continue on a later microtask.
684
+ for (const lapse of [...teardowns.values()])
685
+ lapse();
686
+ teardowns.clear();
687
+ running?.abort();
688
+ listeners.clear();
689
+ },
690
+ };
691
+ }
692
+ function message(err) {
693
+ return err instanceof Error ? err.message : String(err);
694
+ }
695
+ //# sourceMappingURL=store.js.map