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,2799 @@
1
+ /**
2
+ * driverkit/core — the registry.
3
+ *
4
+ * One function, `mount`, and one invariant: every way of driving the app goes
5
+ * through `call`. The in-page chatbot calls it directly, the relay calls it
6
+ * after a websocket frame arrives, a test calls it with no transport at all.
7
+ * There is deliberately no second path, because a second path is a second set
8
+ * of validation and staleness rules and one of the two will be the wrong one.
9
+ *
10
+ * The core renders nothing and imports nothing. No React, no model SDK, no
11
+ * websocket. Those live in sibling packages so an app that only wants to be
12
+ * drivable from outside does not pull a UI into its bundle.
13
+ */
14
+ const REFUSAL = "refusal";
15
+ /**
16
+ * The slugs an app may not use as a refusal of its own, or as a verb name.
17
+ *
18
+ * PROTOCOL.md's reserved list, in code, because a list that lives only in prose
19
+ * is a list nothing checks. Seven come from the core itself, three from the
20
+ * relay and three from the approval gate, and they have one property in common:
21
+ * each says something about WHERE a call stopped, not about the app's rules. An
22
+ * app that refuses with `timeout` has taken away an agent's only way to tell
23
+ * "the app said no, phrase it differently" from "your call never landed,
24
+ * reconnect or pick another tab" — and an agent that cannot tell those apart
25
+ * will retry a commit that may already have run.
26
+ *
27
+ * `wrong-screen` is the newest, and the only one that was ever an app's own. An
28
+ * app with six screens wrote the check by hand and had to invent a word for it;
29
+ * the next app would have picked `not-on-this-screen`, and an agent that had
30
+ * learned one would not recognise the other. The slug says where a call
31
+ * stopped — you are not there — so it belongs here with the rest, and
32
+ * `Verb.screen` with `CallOptions.screen` is how an app now gets the check for
33
+ * nothing. An app that was refusing it by hand is told so at mount; see below.
34
+ */
35
+ export const RESERVED_REFUSALS = [
36
+ "stale",
37
+ "wrong-screen",
38
+ "unknown-verb",
39
+ "bad-argument",
40
+ "unmounted",
41
+ "threw",
42
+ "no-such-tab",
43
+ "tab-went-away",
44
+ "timeout",
45
+ "declined-by-user",
46
+ // The two the approval gate added when it moved into the core.
47
+ //
48
+ // `approval-pending` says a call arrived while this driver was waiting for a
49
+ // person to answer a question about another one. It is a refusal rather than
50
+ // a queue on purpose: the call an agent is most likely to make in that
51
+ // window is the Approve button of the dialog that is asking it
52
+ // (webmachinelearning/webmcp#288), and the second most likely is the same
53
+ // commit again, to race the dialog. Both are answered "not while somebody is
54
+ // being asked".
55
+ //
56
+ // `approval-timeout` is NOT the relay's `timeout` and must never be folded
57
+ // into it. The relay's means the call was accepted and no answer came back,
58
+ // so the outcome is UNKNOWN and a commit may already have run; this one
59
+ // means nobody answered the question, so the verb was never reached and
60
+ // nothing changed. The two call for opposite next moves — read the screen
61
+ // before touching anything, versus ask again — which is exactly why
62
+ // PROTOCOL.md reserves slugs at all.
63
+ "approval-pending",
64
+ "approval-timeout",
65
+ // The one the plan token added, and it is a WHAT YOU ARE ACTING ON slug
66
+ // rather than a WHERE YOU ARE one, which is why it is not folded into
67
+ // `stale`.
68
+ //
69
+ // `stale` says the screen moved and the fix is to read it again.
70
+ // `stale-plan` says the SELECTION is not the one whose count was read and
71
+ // approved, and the fix is strictly larger: run the `describe` again, read
72
+ // the new count, check it is still the number the person asked for, and only
73
+ // then commit. An agent told `stale` re-reads and carries straight on, which
74
+ // is exactly the move that accepts 3,418 rows after a person approved 3,412.
75
+ // Two different repairs, so two slugs.
76
+ "stale-plan",
77
+ // The one the cost ceiling added, and it is a WHAT IT COST slug rather than
78
+ // a WHERE YOU ARE or a WHAT YOU ARE ACTING ON one.
79
+ //
80
+ // Every other slug on this list describes something an agent can repair.
81
+ // `budget-spent` is the only one whose honest hint is "do not try again" —
82
+ // the ceiling was declared by whoever mounted the app, it does not reset, and
83
+ // the only thing that moves it is a person changing `MountOptions.budget`. It
84
+ // is reserved for the usual reason: an app that refused `budget-spent` on a
85
+ // business rule would be telling an agent to stop forever over something it
86
+ // could have phrased differently.
87
+ //
88
+ // ONE SLUG FOR BOTH CEILINGS, and the ladder is why. Two slugs earn their
89
+ // place when two repairs differ — `stale` versus `stale-plan` is the live
90
+ // example on this list. The call budget and the commit budget end in the
91
+ // identical repair, which is no repair: stop, and tell the person. So the
92
+ // slug is one and the HINT names which ceiling, with both numbers.
93
+ "budget-spent",
94
+ // The one cross-tab staleness added, and it is a WHAT YOU ARE ACTING ON slug
95
+ // like `stale` and `stale-plan` rather than a new kind of thing.
96
+ //
97
+ // It is the only slug on this list that the core originates from something it
98
+ // was TOLD rather than something it can see. Every other staleness check
99
+ // compares two values out of `visible()`; this one fires because another
100
+ // driver of the same app said a commit landed, which is a fact no value in
101
+ // this tab can carry. See `MountOptions.elsewhere`.
102
+ //
103
+ // WHY NOT `stale`. `stale` means "the number you echoed is not the number on
104
+ // screen, read again", and re-reading is a repair that WORKS. Here the number
105
+ // on screen matches and is wrong, so an agent told `stale` would re-read,
106
+ // get the same rev, believe itself current and commit — which is the silent
107
+ // failure this exists to end, re-created by reusing the slug. The repair is
108
+ // different and much larger: this tab's copy of the data is behind and only
109
+ // the app refreshing fixes it.
110
+ "changed-elsewhere",
111
+ // The three the question verb added. All three say WHY NOBODY ANSWERED, which
112
+ // is a fourth kind of thing on this list — not where the call stopped, not
113
+ // what it was acting on, not what it cost — and the reason there are three of
114
+ // them rather than one is the reason there are two of `stale` and
115
+ // `stale-plan`: the repairs differ.
116
+ //
117
+ // `ask-unanswered` — the question was put in front of somebody and no answer
118
+ // came back. The channel works and this question went unanswered, so asking
119
+ // once more, or asking something shorter, is a move that can succeed. **The
120
+ // verb did not run and nothing changed**, exactly as with `approval-timeout`,
121
+ // and for the same reason that slug is not the relay's `timeout`: nobody is
122
+ // in any doubt about what happened.
123
+ //
124
+ // `nobody-to-ask` — there is no person on this path at all: a cron run, a
125
+ // test harness, an app that declared no way to ask. Every further question is
126
+ // wasted, so the repair is strictly larger — decide from what is known, or
127
+ // stop and say what is missing. An agent told `ask-unanswered` for this will
128
+ // ask again into an empty room until something else stops it, which is why
129
+ // folding the two would be the same mistake as folding `stale` into
130
+ // `stale-plan`.
131
+ //
132
+ // `asks-spent` — the app's question allowance is gone, so this one was never
133
+ // put. Deliberately NOT `budget-spent`, and this is the one departure from
134
+ // "one slug for both ceilings" a few lines up. That rule's own justification
135
+ // is that the call ceiling and the commit ceiling "end in the identical
136
+ // repair, which is no repair: stop, and tell the person" — and a spent
137
+ // question allowance ends in a real one: say in your answer what you would
138
+ // have asked. It also must not be `budget-spent` because `drive` ends the
139
+ // whole run on that slug, which would mean an agent that asked one question
140
+ // too many could no longer finish the sentence it was asking about.
141
+ "ask-unanswered",
142
+ "nobody-to-ask",
143
+ "asks-spent",
144
+ ];
145
+ const RESERVED = new Set(RESERVED_REFUSALS);
146
+ /** Spelled once. The core originates this slug from two checks and names it in
147
+ * a third message, and three string literals is how the three come to
148
+ * disagree. */
149
+ const WRONG_SCREEN = "wrong-screen";
150
+ /** Spelled once, for the same reason `WRONG_SCREEN` is. `driverkit/agent`
151
+ * exports its own `DECLINED` with the same value: that one is the slug the
152
+ * in-page loop's own gate emits and it predates this, and the string is
153
+ * PROTOCOL.md's rather than either file's. */
154
+ const DECLINED = "declined-by-user";
155
+ const APPROVAL_PENDING = "approval-pending";
156
+ const APPROVAL_TIMEOUT = "approval-timeout";
157
+ const STALE_PLAN = "stale-plan";
158
+ const BUDGET_SPENT = "budget-spent";
159
+ const CHANGED_ELSEWHERE = "changed-elsewhere";
160
+ const ASK_UNANSWERED = "ask-unanswered";
161
+ const NOBODY_TO_ASK = "nobody-to-ask";
162
+ const ASKS_SPENT = "asks-spent";
163
+ /** What a `stale-plan` refusal tells an agent to do when it HAD a plan and the
164
+ * plan is no longer good. Spelled once because four of the five reasons end in
165
+ * this same repair, and four copies is how three of them come to say something
166
+ * slightly different. It is the pairing rule, stated as the fix. */
167
+ const PLAN_REPAIR = "Run the app's `describe` verb again, read the `count` it reports, check it is still the " +
168
+ "number the person asked for, and call this with the `plan` that describe hands back. Do " +
169
+ "not re-send this one.";
170
+ /**
171
+ * The repair for the fifth reason: no plan was presented at all.
172
+ *
173
+ * A SEPARATE SENTENCE, and the separation is the whole point of this constant
174
+ * existing. "The plan you had is out of date" and "you brought no plan" are
175
+ * different mistakes with different fixes, and the first one's fix is actively
176
+ * dangerous as an answer to the second.
177
+ *
178
+ * An eval found it. "Accept the selected contacts" with nothing selected was
179
+ * answered `stale-plan` — correctly, since the check is before the verb body —
180
+ * with a hint that said run the describe again. With an empty selection the
181
+ * only describe that mints a non-empty plan is one that INVENTS a selection,
182
+ * so the hint was pointing at improvising in the one situation where
183
+ * improvising is most expensive. The same eval watched an agent improvise its
184
+ * way to a bulk decline of 403 rows, so this is not a theoretical reading of
185
+ * the sentence.
186
+ *
187
+ * So this one says to go and count the rows the PERSON asked about, and says
188
+ * out loud that picking a selection to give the call something to act on is
189
+ * the wrong move. The empty case gets that said twice, from `checkPlan`.
190
+ */
191
+ const PLAN_MISSING_REPAIR = "Run the app's `describe` verb for the rows the person actually asked about, read the " +
192
+ "`count` it reports, and call this with the `plan` it hands back. If you cannot tell which " +
193
+ "rows they meant, or the app has no verb that selects them, say so and ask — do NOT select " +
194
+ "something near enough to give this call a plan to run on.";
195
+ /** The token's own prefix and version, so a token from a future shape of this
196
+ * can be told from a corrupt one. Opaque to everybody but `mount()`. */
197
+ const PLAN_PREFIX = "dkp1";
198
+ /** Counts mounted drivers, only so each one's plan salt differs from the last.
199
+ * Module-level because two drivers in one page must not agree. */
200
+ let planSeq = 0;
201
+ /** Counts mounted drivers, only so each one can tell its own cross-tab notices
202
+ * from a sibling's. Module-level for the reason `planSeq` is: two drivers in
203
+ * one page must not agree, and two drivers in one page is exactly the case a
204
+ * test of this feature sets up. */
205
+ let elsewhereSeq = 0;
206
+ const DECLINED_HINT = "A person was asked to approve this and said no. Do not retry it, do not try another verb " +
207
+ "that does the same thing, and do not press a control that does it — the answer was about " +
208
+ "the action and not about how you asked. Say what you were about to do and ask what they " +
209
+ "would like instead.";
210
+ const PENDING_HINT = "this app is waiting for a person to approve something, so it is not taking calls. Nothing " +
211
+ "ran. Wait for the answer and read the screen; in particular, pressing an approve or confirm " +
212
+ "control yourself is not a way to answer the question, and that is why this is refused.";
213
+ /**
214
+ * What stands in for a `sensitive` argument's value in an audit record.
215
+ *
216
+ * Fixed rather than configurable, and exported rather than private. A marker
217
+ * an app can change is a marker that the person reading somebody else's log
218
+ * cannot recognise, and a marker nobody can import is one every test and every
219
+ * sink spells out by hand and eventually spells differently. See
220
+ * `ArgSpec.sensitive`.
221
+ */
222
+ export const REDACTED = "[redacted]";
223
+ /**
224
+ * A verb's `screen` as a list, whatever shape the app declared it in.
225
+ *
226
+ * One string and `["one-string"]` mean the same thing to every check in here,
227
+ * and the alternative — `Array.isArray` at each of the three places that reads
228
+ * the field — is how two of the three come to disagree about the one-element
229
+ * case. The declared shape is still what goes in the manifest and in the
230
+ * fingerprint; this is only for deciding and for phrasing.
231
+ */
232
+ function screensOf(screen) {
233
+ return Array.isArray(screen) ? screen : [screen];
234
+ }
235
+ /**
236
+ * `a`, `b` and `c` — for a hint a person and a model both read.
237
+ *
238
+ * It reads naturally for one as well as for several, which is the point: the
239
+ * refusal for a verb on one screen must not acquire a comma or the word "and"
240
+ * because the field can now hold a list. One screen phrases exactly as it did
241
+ * before this field could be an array.
242
+ */
243
+ function naming(screens) {
244
+ const quoted = screens.map((s) => `\`${s}\``);
245
+ if (quoted.length <= 1)
246
+ return quoted.join("");
247
+ return `${quoted.slice(0, -1).join(", ")} and ${quoted[quoted.length - 1]}`;
248
+ }
249
+ /**
250
+ * Say so once, and keep running.
251
+ *
252
+ * Deliberately not a throw. An undeclared refusal slug is discovered while a
253
+ * verb is refusing — the path an app takes when it is working correctly and
254
+ * merely saying no — and turning that into an exception would take a live app
255
+ * down over a documentation mistake. Silence is not the alternative: `refuses`
256
+ * is documented as checked, and a check nobody can observe is the bug this
257
+ * exists to fix.
258
+ *
259
+ * Deduped per message, so a model looping on one refused verb cannot turn this
260
+ * into a console flood. Deduping rather than a build flag is also how this
261
+ * stays dev-shaped in a package with no build step and no `process.env` to
262
+ * read: a correct app prints nothing, ever, and an incorrect one prints once.
263
+ */
264
+ const warned = new Set();
265
+ function warn(message) {
266
+ if (warned.has(message))
267
+ return;
268
+ warned.add(message);
269
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
270
+ console.warn(`driverkit: ${message}`);
271
+ }
272
+ }
273
+ /**
274
+ * The reserved navigation verb, and the two names that go with it.
275
+ *
276
+ * Reserved in the weak sense and on purpose: `goto` is NOT in
277
+ * `RESERVED_REFUSALS`, so an app may still declare a verb of its own by that
278
+ * name and the core leaves it alone. The reserved refusal slugs are reserved
279
+ * strictly because an app that refuses `timeout` takes away a distinction an
280
+ * agent cannot recover; a verb named `goto` takes nothing away from anybody —
281
+ * it either navigates, which is what the name says, or the author has a reason
282
+ * the core cannot see. The same rule as the `rev` and `screen` arguments
283
+ * `driverkit/agent` hoists into every tool schema: the app's meaning wins
284
+ * over ours.
285
+ *
286
+ * What "reserved" buys is one name instead of one per app. Before this, every
287
+ * multi-screen app wrote its own navigation verb — `go`, `navigate`,
288
+ * `open-screen`, `route-to` — and an agent that had learned one did not
289
+ * recognise the next, which is the same argument that made `wrong-screen` a
290
+ * reserved refusal rather than a word each app invents.
291
+ */
292
+ const GOTO = "goto";
293
+ /** The name of `goto`'s one always-present argument. Spelled once: it is
294
+ * checked against every screen's own argument names and named in the refusal,
295
+ * and three string literals is how the three come to disagree. */
296
+ const GOTO_SCREEN_ARG = "screen";
297
+ /** The one refusal the core itself originates from `goto`. Not reserved — it
298
+ * is a fact about the call and not about where the call stopped — and
299
+ * deliberately not declared in `goto.refuses`; see the verb. */
300
+ const BAD_SCREEN_ARG = "bad-screen-argument";
301
+ /**
302
+ * `goto`'s description, which every agent reads in the cached half.
303
+ *
304
+ * Here rather than in `driverkit/agent` and `mcp_core.py`, which is where
305
+ * every other piece of tool prose lives, because this verb is the core's own:
306
+ * the two renderers describe what an APP declared, and a sentence about a verb
307
+ * the core implements written twice in two languages is a sentence that
308
+ * drifts. The screens themselves are not listed in here — they are rendered
309
+ * into the system prompt and the MCP server instructions from
310
+ * `Manifest.screens`, next to the flows — so this text says what the verb does
311
+ * and where the map is, and the `oneOf` on its argument carries the ids.
312
+ */
313
+ const GOTO_DESCRIBE = "go to one of this app's screens, the way clicking its own navigation does. Pass the " +
314
+ "screen's id; your instructions list every screen this app has, what each one is for, " +
315
+ "and which ones need an argument of their own — a screen that shows one record needs to " +
316
+ "be told which record. Refused as `bad-screen-argument` when a screen's own argument is " +
317
+ "missing or the wrong type, and the app may refuse it for its own reasons, such as a " +
318
+ "screen this person is not allowed to open.";
319
+ /**
320
+ * The reserved question verb.
321
+ *
322
+ * Reserved in the same WEAK sense `goto` is, and the same rule decides it: an
323
+ * app that declares its own verb named `ask` keeps it and the core adds
324
+ * nothing, because the app's meaning wins over ours. What "reserved" buys is
325
+ * one name instead of one per app — `ask`, `ask-user`, `clarify`, `check-with-
326
+ * me`, none of which the next agent recognises — which is the argument that
327
+ * made `goto` reserved and `wrong-screen` a reserved refusal.
328
+ *
329
+ * It is NOT in `RESERVED_REFUSALS`, so a verb may be named this. The three
330
+ * slugs the mechanism added are, for the usual reason: an app that refused
331
+ * `nobody-to-ask` on a business rule would be telling an agent to stop asking
332
+ * for the rest of a run over something it could have phrased differently.
333
+ */
334
+ const ASK = "ask";
335
+ /** The name of `ask`'s one argument. Spelled once: it is named in the schema,
336
+ * in two refusals and in the record. */
337
+ const ASK_QUESTION_ARG = "question";
338
+ /**
339
+ * How long a question waits for an answer when the app did not say.
340
+ *
341
+ * **45 seconds, and the number is chosen against the relay's 60.** See
342
+ * `MountOptions.askTimeout`: a question that outlives the transport's deadline
343
+ * converts "nobody answered", which is a fact the agent can act on, into the
344
+ * relay's `timeout`, which PROTOCOL.md defines as outcome unknown. Of the two
345
+ * errors, firing late is the expensive one here — the opposite way round from
346
+ * `approvalTimeout`, which waits forever because a lapsed approval DENIES a
347
+ * commit and a lapsed question denies nothing.
348
+ *
349
+ * Exported so the two numbers can be reasoned about together rather than being
350
+ * two literals in two packages.
351
+ */
352
+ const DEFAULT_ASK_TIMEOUT_MS = 45_000;
353
+ export { ASK, ASK_QUESTION_ARG, DEFAULT_ASK_TIMEOUT_MS };
354
+ /**
355
+ * `ask`'s description, which every agent reads in the cached half.
356
+ *
357
+ * Here rather than in `driverkit/agent` and `mcp_core.py` for the reason
358
+ * `GOTO_DESCRIBE` is: this verb is the core's own, the two renderers describe
359
+ * what an APP declared, and a sentence about a core verb written twice in two
360
+ * languages is a sentence that drifts.
361
+ *
362
+ * THREE THINGS IT HAS TO SAY, and the third is the one the whole mechanism
363
+ * stands on. What the verb is for: an instruction you cannot carry out without
364
+ * guessing. What the three refusals mean, since the difference between "nobody
365
+ * answered" and "there is nobody" decides whether asking again is worth a turn.
366
+ * And that **an answer is not an approval** — because the single most likely
367
+ * misuse of this verb is to ask "shall I accept these 3,412?", read a yes, and
368
+ * treat it as the consent the approval gate exists to collect. The core refuses
369
+ * that structurally, and a model that has been told so does not spend a turn
370
+ * discovering it.
371
+ */
372
+ const ASK_DESCRIBE = "ask the person a question and get their answer back as this call's result. For an " +
373
+ "instruction you cannot carry out without guessing — two records match the name they " +
374
+ "gave, nothing is selected and you do not know which rows they meant, the company they " +
375
+ "named does not exist. Asking is better than guessing and far better than acting on a " +
376
+ "guess.\n\n" +
377
+ "It is not free and it is not unlimited: each question costs the person's attention, the " +
378
+ "app may cap how many you get, and nothing else runs while one is open. So ask once, ask " +
379
+ "the narrowest question that unblocks you, and put everything you already know into it — " +
380
+ "`which Ada Duarte did you mean: the one at Acme or the one at Initech?` rather than " +
381
+ "`which one?`.\n\n" +
382
+ "**An answer is not permission.** A commit still goes to whoever approves commits in this " +
383
+ "app, whatever the person told you here, and a `yes` to a question of yours authorises " +
384
+ "nothing — so do not ask for approval with this, and do not report a commit as approved " +
385
+ "because an answer sounded like a yes.\n\n" +
386
+ "Refused as `ask-unanswered` when the question was put and nobody answered: the question " +
387
+ "was seen by nobody who replied, nothing in the app changed, and asking again later or " +
388
+ "more briefly may work. Refused as `nobody-to-ask` when there is no person on this run at " +
389
+ "all — a scheduled job, a test — in which case stop asking: say what you need and what you " +
390
+ "could not decide. Refused as `asks-spent` when the app's question allowance is gone, " +
391
+ "which means the same thing for the rest of this run.";
392
+ /**
393
+ * The documented size budgets, in characters.
394
+ *
395
+ * NOT arbitrary, and not a limit for its own sake. Apple's app skills ship
396
+ * with exactly this pair — a description of at most 1024 characters on one
397
+ * line, and a body of at most 10,000 — and a budget is worth copying because
398
+ * of what the absence of one does: `instructions` had no documented bound, so
399
+ * the honest answer to "how much may I write?" was "nobody has said", and the
400
+ * field drifted toward being a README. Everything here is in the cached prefix
401
+ * of every session of every user, which is exactly why it is cheap and exactly
402
+ * why it is tempting: the cost is real, it is just paid once and invisibly, so
403
+ * a number is the only thing that makes anybody weigh it. The second cost is
404
+ * the one a budget really guards: text in the prefix competes with the verb
405
+ * list for a model's attention, and a thousand words about the app is a
406
+ * thousand words read instead of the tool that commits data.
407
+ *
408
+ * `describe` is one line because it is a label a model chooses on, not a
409
+ * paragraph it reasons from — selection between flows is made on the
410
+ * description and not on the individual steps, which is the finding this whole
411
+ * field is shaped by.
412
+ *
413
+ * New fields throw when they exceed these; `instructions`, which predates
414
+ * having a budget at all, warns. See `mount`.
415
+ */
416
+ export const SIZE_LIMITS = {
417
+ /** `FlowSpec.describe` and `ScreenSpec.describe`: one line, at most this.
418
+ * Also `FlowStep.skipWhen`, which is a one-line condition for the same
419
+ * reason — it is read beside the step, not reasoned from. */
420
+ describe: 1024,
421
+ /** A whole flow's steps — every `section`, `verb`, `hint` and `skipWhen`
422
+ * together. Everything rendered into the prefix counts, so moving a sentence
423
+ * out of a `hint` and into a `skipWhen` buys no room. */
424
+ body: 10_000,
425
+ /** `MountOptions.instructions`. Warned about rather than refused. */
426
+ instructions: 10_000,
427
+ };
428
+ /**
429
+ * RFC 6570 simple string expansion, and nothing else.
430
+ *
431
+ * `"#/companies/{slug}"` with `{ slug: "acme-industrial" }` becomes
432
+ * `"#/companies/acme-industrial"`. A variable with no value expands to
433
+ * nothing, which is the spec's own rule for an undefined variable.
434
+ *
435
+ * WHY A HAND-ROLLED SUBSET RATHER THAN THE LIBRARY. `uri-templates` is in the
436
+ * repository and is used in the tests as the oracle this is checked against,
437
+ * but the core promises zero runtime dependencies, and that promise is not
438
+ * decoration: the worked example loads these very `.ts` files into a browser
439
+ * through a type-stripper with no bundler and no `node_modules`, so one bare
440
+ * `import "uri-templates"` in here stops the demo from running at all. The
441
+ * SYNTAX is the spec's, which is the part that matters — an author can hand
442
+ * the same template to any RFC 6570 implementation, and a template is never
443
+ * rewritten to suit us — and a route is level 1, so what the core implements
444
+ * is the level a route needs. The same argument as `ArgSpec` being a hand-
445
+ * rolled subset of JSON Schema.
446
+ *
447
+ * Expansion is percent-encoding of everything outside RFC 3986's unreserved
448
+ * set, which is `encodeURIComponent` plus the five characters it leaves alone.
449
+ * A slug with a slash in it must not silently become another path segment.
450
+ */
451
+ function expand(template, args) {
452
+ return template.replace(/\{([^{}]+)\}/g, (_whole, name) => {
453
+ const value = args[name];
454
+ if (value === undefined || value === null)
455
+ return "";
456
+ return encodeURIComponent(String(value)).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
457
+ });
458
+ }
459
+ /**
460
+ * A twelve-character hash of a string. Not cryptographic and does not need to
461
+ * be; see `fingerprint`, which this was lifted out of unchanged so that the
462
+ * plan token and the manifest version cannot drift into two hashes.
463
+ */
464
+ function hash12(shape) {
465
+ let h1 = 0x811c9dc5;
466
+ let h2 = 0x01000193;
467
+ for (let i = 0; i < shape.length; i++) {
468
+ const c = shape.charCodeAt(i);
469
+ h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0;
470
+ h2 = Math.imul(h2 + c, 0x85ebca6b) >>> 0;
471
+ }
472
+ return (h1.toString(16).padStart(8, "0") + h2.toString(16).padStart(8, "0")).slice(0, 12);
473
+ }
474
+ /**
475
+ * An identity for a set of row ids, for `Snapshot.selectionId`.
476
+ *
477
+ * Exported, and that is the point of it existing rather than being left to
478
+ * each app. The core mints the plan token so an app cannot get the token's
479
+ * binding wrong; this is the other half of the same argument, because an app
480
+ * hand-rolling the identity can get it wrong in exactly the way that matters —
481
+ * a hash over `selected.join(",")` is order-DEPENDENT, so clicking two rows in
482
+ * the other order reads as a different selection and every commit is refused,
483
+ * and a hash over the count alone reads as the same selection when one row has
484
+ * been swapped for another, which is the failure the identity exists to catch.
485
+ *
486
+ * Order-independent, so the same membership gives the same string however it
487
+ * was built. The size is folded in as well, so an empty selection is distinct
488
+ * from one whose hashes happen to cancel.
489
+ *
490
+ * One pass over the ids, which is cheap for the hundreds an on-screen selection
491
+ * holds. An app whose selection runs to tens of thousands should keep a running
492
+ * value instead and not call this inside `visible()`, which runs on every call.
493
+ */
494
+ export function selectionId(ids) {
495
+ let xor = 0;
496
+ let sum = 0;
497
+ let n = 0;
498
+ for (const id of ids) {
499
+ let h = 0x811c9dc5;
500
+ for (let i = 0; i < id.length; i++)
501
+ h = Math.imul(h ^ id.charCodeAt(i), 0x01000193) >>> 0;
502
+ xor = (xor ^ h) >>> 0;
503
+ sum = (sum + h) >>> 0;
504
+ n += 1;
505
+ }
506
+ return `${n.toString(36)}-${xor.toString(16).padStart(8, "0")}${sum.toString(16).padStart(8, "0")}`;
507
+ }
508
+ /** Build the value a verb returns to decline. Exported because app code
509
+ * sometimes wants to refuse from a helper rather than inline. */
510
+ export function refusal(reason, hint) {
511
+ return { __driverkit: REFUSAL, reason, ...(hint === undefined ? {} : { hint }) };
512
+ }
513
+ function isRefusal(v) {
514
+ return typeof v === "object" && v !== null && v.__driverkit === REFUSAL;
515
+ }
516
+ /**
517
+ * Validate one argument against its spec.
518
+ *
519
+ * Returns a reason string, or null when the value is acceptable. Kept separate
520
+ * from `call` so the failure messages can be unit-tested without mounting
521
+ * anything, and so they read the same whether the caller was a chatbot or a
522
+ * relay frame — a model that learns one phrasing of "bad argument" should not
523
+ * meet a different phrasing depending on how it connected.
524
+ */
525
+ export function checkArg(name, spec, value) {
526
+ if (value === undefined || value === null) {
527
+ return spec.optional ? null : `missing argument \`${name}\``;
528
+ }
529
+ if (typeof value !== spec.type) {
530
+ return `argument \`${name}\` wants a ${spec.type}, got ${typeof value}`;
531
+ }
532
+ if (spec.oneOf && !spec.oneOf.includes(value)) {
533
+ // The accepted values are listed rather than counted. An agent that is
534
+ // told "invalid value" has to guess again; one that is told the set can
535
+ // fix the call on the next turn without another read.
536
+ return `argument \`${name}\` must be one of ${spec.oneOf.map((v) => JSON.stringify(v)).join(", ")}`;
537
+ }
538
+ return null;
539
+ }
540
+ /**
541
+ * Make an app drivable.
542
+ *
543
+ * ```ts
544
+ * const driver = mount({
545
+ * app: "Contacts",
546
+ * verbs: [
547
+ * { name: "open", kind: "read", describe: "open one contact",
548
+ * args: { id: { type: "string", describe: "contact id" } },
549
+ * run: ({ id }) => router.push(`/contacts/${id}`) },
550
+ *
551
+ * // A describe/commit pair. The predicate is resolved inside the app,
552
+ * // where the rows already are, so selecting a thousand contacts is one
553
+ * // call and not a thousand -- and the count comes back before anything
554
+ * // irreversible happens.
555
+ * { name: "select-where", kind: "describe", describe: "select every contact matching a filter",
556
+ * args: { where: { type: "string", describe: "e.g. company=Acme" } },
557
+ * run: ({ where }) => store.select(where) },
558
+ * // `consumes` is the half that makes the count a guarantee rather than
559
+ * // advice: this cannot be called bare, only with the `plan` token the
560
+ * // describe above handed back, so the set it touches is provably the set
561
+ * // that was counted. See `Verb.consumes`.
562
+ * { name: "accept-selected", kind: "commit", consumes: "plan",
563
+ * describe: "accept the current selection",
564
+ * refuses: ["nothing-selected"],
565
+ * run: (_, ctx) => store.selected.length ? api.accept(store.selected)
566
+ * : ctx.refuse("nothing-selected") },
567
+ * ],
568
+ * visible: () => ({ where: "contacts", rev: store.rev, rows: store.onScreen(),
569
+ * selectionId: selectionId(store.selected) }),
570
+ * });
571
+ * ```
572
+ *
573
+ * Nothing above is specific to a framework or a kind of app. `run` bodies call
574
+ * whatever the app already has -- a store action, an API client, or, in an app
575
+ * with neither, a click on a button the author marked themselves. That last
576
+ * case is four lines the app writes -- the README shows them -- and the
577
+ * library ships no reader for it, because a reader is a guess at a data shape
578
+ * and guessing shapes is the thing this library exists not to do.
579
+ */
580
+ export function mount(options) {
581
+ const verbs = new Map();
582
+ let live = true;
583
+ /** How to stop listening on `MountOptions.elsewhere`, if the channel gave us
584
+ * one. Held here rather than beside the channel because `unmount` is at the
585
+ * bottom of the file and a subscription nothing unsubscribes is a leak per
586
+ * mounted driver -- which in a hot-reloading dev server is one per save. */
587
+ let unlisten;
588
+ // Thrown at mount, where a typo costs one stack trace at startup, and never
589
+ // on a call path. A misspelt policy — `approve: "unnattended"`, or a truthy
590
+ // object somebody meant as options — must not degrade to "no policy
591
+ // declared": that is the one failure mode where the app believes it has a
592
+ // gate and has not got one, which is worse than having no gate knowingly.
593
+ const declared = options.approve;
594
+ if (declared !== undefined && typeof declared !== "function" && declared !== "unattended") {
595
+ throw new Error(`driverkit: \`approve\` must be a function or the string "unattended"; got ` +
596
+ `${JSON.stringify(declared)}. A function is asked before every commit; "unattended" ` +
597
+ `says out loud that commits on this driver run with nobody in front of them.`);
598
+ }
599
+ const approveFn = typeof declared === "function" ? declared : undefined;
600
+ /** What the app itself said, for all time. `connect()` reads this one. */
601
+ const declaredPolicy = approveFn !== undefined ? "hook" : declared === "unattended" ? "unattended" : "none";
602
+ /**
603
+ * An approver installed after mount, by a dialog that lives in the page.
604
+ *
605
+ * `DriverApproval.adopt` carries the argument; this is the mechanism, and it
606
+ * is two variables because releasing has to be safe. The hook is what the
607
+ * gate calls; the token is who owns it, so a disposer handed out earlier
608
+ * cannot unhook whoever adopted after it — which is the shape every
609
+ * "unsubscribe twice" bug has.
610
+ *
611
+ * Only ever set when the app declared nothing. An app with its own `hook` is
612
+ * already asked on every path, and `unattended` is an app saying commits
613
+ * here run with nobody watching; installing a dialog over either of those
614
+ * would be the library overruling a sentence somebody wrote.
615
+ */
616
+ let adopted;
617
+ let adoptedBy;
618
+ /** Who is asked right now, which is what a record has to say. See
619
+ * `DriverApproval.policy`: `adopted` is deliberately not `hook`. */
620
+ function policyNow() {
621
+ if (approveFn !== undefined)
622
+ return "hook";
623
+ if (declared === "unattended")
624
+ return "unattended";
625
+ return adopted !== undefined ? "adopted" : "none";
626
+ }
627
+ /**
628
+ * Where the records go, or nowhere.
629
+ *
630
+ * Read once, into a `const`, because an app that passes no hook has to behave
631
+ * byte-identically to one mounted before audit existed -- and the test for
632
+ * that is `onAudit === undefined`, checked once per call rather than a field
633
+ * lookup on an options object somebody might mutate afterwards. Not validated
634
+ * at mount the way `approve` is: a misspelt policy makes an app believe it has
635
+ * a gate it has not got, which is a safety claim, while a hook that is not a
636
+ * function throws on the first call and is caught by `record` -- reported, the
637
+ * call unaffected. The asymmetry is the point.
638
+ */
639
+ const onAudit = options.onAudit;
640
+ /**
641
+ * The verb an approval is open for, or null.
642
+ *
643
+ * The whole of point 3's strongest layer, and it is three lines because it
644
+ * has to be: while this is set, `call()` refuses everything. It closes the
645
+ * bypass for ANY approval UI rather than for ours — a host's own modal gets
646
+ * it through `hold` — and it does not depend on an author remembering to
647
+ * mark their Approve button with an attribute, which is the failure mode of
648
+ * every opt-out mechanism. The gated call's own `run` is not blocked,
649
+ * because the core clears this before it runs.
650
+ */
651
+ let pending = null;
652
+ // ---- the cost ceiling ---------------------------------------------------
653
+ //
654
+ // Two counters and a validation. `MountOptions.budget` carries the argument
655
+ // for what is bounded and what was rejected; what is here is the mechanism.
656
+ //
657
+ // Validated at mount for the reason the approval policy is: a budget of 0 or
658
+ // -1 means the app is never drivable, which nobody means, and discovering it
659
+ // as `budget-spent` on the very first call is the one shape where an author
660
+ // believes they configured a ceiling and have in fact configured a wall.
661
+ const budget = options.budget;
662
+ if (budget !== undefined) {
663
+ for (const field of ["calls", "commits", "asks"]) {
664
+ const limit = budget[field];
665
+ if (limit === undefined)
666
+ continue;
667
+ if (!Number.isInteger(limit) || limit < 1) {
668
+ throw new Error(`driverkit: \`budget.${field}\` is ${JSON.stringify(limit)}; it must be a positive ` +
669
+ `integer, or absent to mean no ceiling. A budget of ${JSON.stringify(limit)} is not ` +
670
+ `a tight ceiling, it is an app that refuses its first call — and it would do that ` +
671
+ `with a \`budget-spent\` hint, which reads as a runaway rather than as a typo.`);
672
+ }
673
+ }
674
+ }
675
+ /** Every `call()` that got past the approval lock, refused ones included.
676
+ * Kept whether or not a ceiling was declared: `Driver.budget` reports it
677
+ * either way, and a number somebody debugging a chatty app can read is
678
+ * worth two increments. */
679
+ let callsUsed = 0;
680
+ /** `commit` verbs that actually reached `run`. */
681
+ let commitsUsed = 0;
682
+ /** Questions that actually reached a person. A question refused for a spent
683
+ * allowance, or one the app answered `{ nobody: true }` to, is not counted:
684
+ * neither took anybody's attention, which is the thing this number bounds. */
685
+ let asksUsed = 0;
686
+ /** When this allowance began, for `Budget.window`. `Date.now()` here means
687
+ * "this mount started one", and a record read back below replaces it with
688
+ * the moment the allowance it belongs to actually started. */
689
+ let budgetSince = budget?.store === undefined ? 0 : Date.now();
690
+ /**
691
+ * Why the ceiling can no longer be kept, or null while it can be.
692
+ *
693
+ * The fail-closed flag, and the asymmetry it encodes is deliberate: a
694
+ * transcript that cannot be stored costs a conversation, and a budget that
695
+ * cannot be stored costs whatever an agent in a loop spends between now and
696
+ * somebody noticing. So a store that cannot be read, or that throws on a
697
+ * write, stops the AGENT — every later call is refused `budget-spent` with
698
+ * this sentence in the hint — and does not stop the app, which the person at
699
+ * the keyboard goes on using exactly as before.
700
+ *
701
+ * A string rather than a boolean because the two causes need different
702
+ * sentences. "I could not read your allowance" is usually a private window
703
+ * and is nobody's bug; "I could not write it down" is usually a full quota
704
+ * and is the one where somebody has to act.
705
+ */
706
+ let budgetBroken = null;
707
+ /**
708
+ * Whether this driver is keeping its allowance in a store at all.
709
+ *
710
+ * A `store` with no ceiling declared enforces nothing: an app that passed one
711
+ * and set neither `calls` nor `commits` has asked for nothing to be enforced,
712
+ * and refusing its calls because its storage is blocked would be a ceiling
713
+ * invented out of a field that set none.
714
+ */
715
+ const budgetKept = budget?.store !== undefined &&
716
+ (budget.calls !== undefined || budget.commits !== undefined || budget.asks !== undefined);
717
+ /**
718
+ * Pull the stored allowance into the counters, taking the HIGHER figure.
719
+ *
720
+ * **Called at mount and again before every charge, and the re-read is what
721
+ * makes "one app, one ceiling" true rather than aspirational.** Two tabs open
722
+ * at once each hold their own copy of the counters, so a mount-time read
723
+ * alone gave each of them the whole allowance — two tabs, two ceilings, which
724
+ * is the reload bypass wearing a different hat. A tab that charges has to
725
+ * look at what the others have spent.
726
+ *
727
+ * **Higher wins, never lower.** `localStorage` has no compare-and-swap, so
728
+ * two tabs charging in the same millisecond can lose one increment — an
729
+ * off-by-one, bounded, and vastly better than an off-by-a-factor-of-tabs. But
730
+ * a read that answered with a SMALLER figure, from a tab that was behind or a
731
+ * record somebody edited, must never hand an allowance back; `Math.max` is
732
+ * the whole of that guarantee.
733
+ *
734
+ * `Number.isInteger` and `Math.max(0, ...)` because this came off a store the
735
+ * person sitting there can edit. Tampering is explicitly out of scope — see
736
+ * `Budget.store`, it is a cost control and not a security boundary — but a
737
+ * negative or fractional figure is the one input that would make the ceiling
738
+ * comparison never fire at all, and that is worth one guard.
739
+ */
740
+ function syncSpend() {
741
+ if (!budgetKept || budgetBroken !== null)
742
+ return;
743
+ const read = budget.store.load();
744
+ if (!read.ok) {
745
+ budgetBroken =
746
+ "the stored record of this app's spend ceiling could not be read, so there is no way " +
747
+ "to tell how much of the allowance is already spent. Rather than assume none of it is, " +
748
+ "this driver refuses every call: an unreadable ceiling that let calls through would be " +
749
+ "no ceiling at all. The app itself still works normally for the person at the keyboard.";
750
+ return;
751
+ }
752
+ if (read.spent === null)
753
+ return;
754
+ const record = read.spent;
755
+ // Two reasons to throw a record away, both host-held and neither reachable
756
+ // by the agent. See `Budget.epoch` and `Budget.window`.
757
+ if ((record.epoch ?? undefined) !== budget.epoch)
758
+ return;
759
+ if (budget.window !== undefined && Date.now() - record.since >= budget.window)
760
+ return;
761
+ if (Number.isInteger(record.calls))
762
+ callsUsed = Math.max(callsUsed, record.calls);
763
+ if (Number.isInteger(record.commits))
764
+ commitsUsed = Math.max(commitsUsed, record.commits);
765
+ // Absent on a record written before questions were counted, which is read
766
+ // as 0 rather than as a reason to throw the record away: see
767
+ // `BudgetRecord.asks`. The other two numbers in it are still true, and
768
+ // discarding an allowance because a field was added would hand every app
769
+ // with a store a fresh ceiling on upgrade.
770
+ if (Number.isInteger(record.asks))
771
+ asksUsed = Math.max(asksUsed, record.asks);
772
+ if (Number.isFinite(record.since))
773
+ budgetSince = record.since;
774
+ }
775
+ /**
776
+ * Write the counters down, and fail closed if that cannot be done.
777
+ *
778
+ * Called after each increment rather than on an interval or at unload. The
779
+ * event this exists for is a page that goes away without warning — a reload,
780
+ * a crash, a `goto` — so any scheme that batches is a scheme that loses
781
+ * exactly the calls it was built to remember.
782
+ *
783
+ * The throw is caught HERE and not left to the caller, because the call it is
784
+ * about has already happened: the verb ran, the data moved, and failing the
785
+ * `Result` now would tell an agent nothing happened when something did. What
786
+ * a failed write changes is the FUTURE — from here on nothing is allowed,
787
+ * because nothing more can be accounted for.
788
+ */
789
+ function rememberSpend() {
790
+ if (!budgetKept || budgetBroken !== null)
791
+ return;
792
+ try {
793
+ budget.store.save({
794
+ calls: callsUsed,
795
+ commits: commitsUsed,
796
+ // Written whatever the app declared, like the two above, so that adding
797
+ // `budget.asks` later does not have to treat every existing record as
798
+ // having asked nothing since the epoch.
799
+ asks: asksUsed,
800
+ since: budgetSince,
801
+ ...(budget.epoch === undefined ? {} : { epoch: budget.epoch }),
802
+ });
803
+ }
804
+ catch {
805
+ budgetBroken =
806
+ "this app's spend ceiling could not be written down — storage is full, or blocked — so " +
807
+ "from here on there is no way to carry the count across a page load. Rather than let " +
808
+ "an uncounted call through, this driver refuses every later one. The app itself still " +
809
+ "works normally for the person at the keyboard; somebody has to free up storage or " +
810
+ "lift the ceiling.";
811
+ }
812
+ }
813
+ // At mount, so `Driver.budget` reports the true figure to a panel before a
814
+ // single call is made -- a settings view that said "0 of 200" on a page whose
815
+ // allowance was half spent would be the panel lying about the one number it
816
+ // is there to show.
817
+ syncSpend();
818
+ for (const verb of options.verbs) {
819
+ if (verbs.has(verb.name)) {
820
+ // Thrown, not refused: two verbs sharing a name is a programming error
821
+ // that makes one of them permanently unreachable, and it should fail at
822
+ // mount rather than silently shadow on the first call.
823
+ throw new Error(`driverkit: two verbs are both named \`${verb.name}\``);
824
+ }
825
+ // Thrown at mount for the same reason the duplicate name above is: both are
826
+ // static facts about the verb surface, both make the app permanently
827
+ // ambiguous to every agent that reads the manifest, and mount runs at
828
+ // startup rather than on a refusal path — so failing here costs a developer
829
+ // one stack trace and costs a running app nothing. The call-time check
830
+ // below, which can only fire while an app is refusing, is a warning
831
+ // instead; see `warn`.
832
+ if (RESERVED.has(verb.name)) {
833
+ throw new Error(`driverkit: a verb may not be named \`${verb.name}\`: that is a reserved refusal slug ` +
834
+ `(${RESERVED_REFUSALS.join(", ")}). An agent could not tell a refusal from this verb ` +
835
+ `apart from a refusal about it.`);
836
+ }
837
+ // Thrown at mount, the way a duplicate name is, and for the same reason: it
838
+ // is a static fact about the surface that makes the verb permanently
839
+ // uncallable. `screen: []` says the verb works on no screen at all, which
840
+ // no author means — it is what a `.filter()` over a list of screens
841
+ // produces when the list was empty, or what a config file hands over when
842
+ // a key is missing. The author who meant "anywhere" leaves the field out,
843
+ // and that is said here rather than guessed at, because guessing either
844
+ // way is wrong: treating it as "anywhere" silently makes a scoped verb
845
+ // global, and treating it as "nowhere" leaves a verb in everybody's cached
846
+ // prefix that can only ever be refused.
847
+ if (Array.isArray(verb.screen) && verb.screen.length === 0) {
848
+ throw new Error(`driverkit: the verb \`${verb.name}\` declares \`screen: []\`, which says it works on ` +
849
+ `no screen at all. Omit \`screen\` to mean "anywhere", or name the screens it works ` +
850
+ `on.`);
851
+ }
852
+ // THE ONE KIND AN APP MAY NOT DECLARE, and this throw is the structural
853
+ // half of "a question is not consent".
854
+ //
855
+ // Every other kind is a claim about what the app's own code does, and the
856
+ // app is the only thing that can make it. `ask` is a claim about a PERSON,
857
+ // and the core is the only thing that can make it good: it owns the lock
858
+ // that stops the agent acting while a question is open, the deadline that
859
+ // keeps "nobody answered" a fact rather than the relay's unknown outcome,
860
+ // the allowance, and the audit row. A verb wearing the kind with none of
861
+ // those behind it would be a question nothing counted and nothing locked --
862
+ // and the first thing anybody would build with it is a confirmation
863
+ // dialog, whose yes would then be the one thing `MountOptions.approve`
864
+ // exists to be asked for. So the kind is the core's and the hook is the
865
+ // app's; see `MountOptions.ask`.
866
+ //
867
+ // Thrown rather than warned because it is a safety claim being made
868
+ // falsely, which is the same grounds the misspelt `approve` policy throws
869
+ // on. Additive, because no app can already be declaring it: it was not a
870
+ // value of `VerbKind` until this feature, so nothing that compiles today
871
+ // can hit this.
872
+ if (verb.kind === ASK) {
873
+ throw new Error(`driverkit: the verb \`${verb.name}\` declares \`kind: "ask"\`, which only the core ` +
874
+ `may mint. A question has to be locked, deadlined, counted against ` +
875
+ `\`budget.asks\` and recorded, and none of that can be true of a verb body — a ` +
876
+ `verb wearing this kind would be a question nothing counted, and a "yes" to it ` +
877
+ `would look like the approval \`approve\` exists to collect. Pass ` +
878
+ `\`ask: ({ question }) => …\` to \`mount()\` and the core offers the \`ask\` verb ` +
879
+ `itself; declare this verb with the kind it really has, or leave \`kind\` off.`);
880
+ }
881
+ // Thrown at mount, like the two above, and for the same reason: it is a
882
+ // static fact about the surface that an agent reads from the manifest and
883
+ // caches. `consumes` on anything but a `commit` is an authoring mistake
884
+ // with a cost that is easy to miss -- a `describe` that demands a token
885
+ // makes the pairing circular, because the only thing that can mint one is
886
+ // a `describe`, and a `read` that demands one teaches an agent to go and
887
+ // fetch a receipt before it is allowed to look at anything. A token is a
888
+ // claim about data that is about to move; a verb that has promised no data
889
+ // moves has nothing to make the claim about.
890
+ //
891
+ // A misspelt value is caught here too. `consumes: "plans"` would otherwise
892
+ // be falsy to no check and truthy to the fingerprint, so the app would
893
+ // believe it had the guarantee, the version would have moved, and every
894
+ // commit would run bare -- the one failure mode worth a stack trace at
895
+ // startup.
896
+ if (verb.consumes !== undefined) {
897
+ if (verb.consumes !== "plan") {
898
+ throw new Error(`driverkit: the verb \`${verb.name}\` declares \`consumes: ` +
899
+ `${JSON.stringify(verb.consumes)}\`; the only value is "plan". A verb that asks ` +
900
+ `for something the core does not mint would run with no check at all, which is ` +
901
+ `the one outcome worse than not asking.`);
902
+ }
903
+ if (verb.kind !== "commit") {
904
+ throw new Error(`driverkit: the verb \`${verb.name}\` declares \`consumes: "plan"\` and ` +
905
+ `${verb.kind ? `\`kind: "${verb.kind}"\`` : "no `kind`"}. A plan token is the ` +
906
+ `receipt for a count that a \`describe\` reported, so only a \`commit\` can ` +
907
+ `consume one: a \`describe\` that demanded one could never be called, since a ` +
908
+ `\`describe\` is the only thing that mints them.`);
909
+ }
910
+ }
911
+ for (const slug of verb.refuses ?? []) {
912
+ if (RESERVED.has(slug)) {
913
+ throw new Error(`driverkit: the verb \`${verb.name}\` declares the reserved refusal \`${slug}\` ` +
914
+ `(reserved: ${RESERVED_REFUSALS.join(", ")}). Reserved slugs say where a call ` +
915
+ `stopped, not what your app decided; pick a name from your own vocabulary.` +
916
+ // Named, because this is the one reserved slug an app may already
917
+ // be using: it was an app's invention before it was the core's, and
918
+ // an author who hits this wants the replacement rather than a rule.
919
+ // At mount, where it costs one stack trace at startup, and never on
920
+ // a refusal path.
921
+ (slug === WRONG_SCREEN
922
+ ? ` \`${WRONG_SCREEN}\` is now the core's: put \`screen: "<the screen this verb ` +
923
+ `is on>"\` on the verb, give \`Snapshot.screen\` the screen that is live, and ` +
924
+ `the refusal — naming both screens — comes back without this guard.`
925
+ : ""));
926
+ }
927
+ }
928
+ verbs.set(verb.name, verb);
929
+ }
930
+ // ---- the app's map, and the one verb the core implements ---------------
931
+ //
932
+ // After the verb loop, because the reserved `goto` is a verb like any other
933
+ // and has to be checked for a collision against the app's own; before the
934
+ // manifest, because it has to appear in it. See `ScreenSpec`.
935
+ const screens = options.screens ?? [];
936
+ const byScreen = new Map();
937
+ /** The union of every screen's declared args, hoisted onto `goto`.
938
+ *
939
+ * A verb takes `Record<string, Scalar>` — no nested objects, because an
940
+ * argument that cannot survive JSON cannot cross the relay — so `goto`
941
+ * cannot take `{ screen, args: {...} }`. The arguments are flattened
942
+ * instead: every name any screen declares becomes one optional argument of
943
+ * `goto`, which keeps the schema static and cacheable, and the core checks
944
+ * the ones THIS screen needs at call time. Optional in the schema because
945
+ * whether an argument is required depends on which screen was asked for,
946
+ * and a schema that said otherwise would make a client reject
947
+ * `goto("contacts")` for want of a contact id. */
948
+ const screenArgs = {};
949
+ for (const screen of screens) {
950
+ if (typeof screen.id !== "string" || screen.id === "") {
951
+ throw new Error(`driverkit: a screen in \`screens\` has no \`id\`. The id is the string ` +
952
+ `\`Verb.screen\` and \`Snapshot.screen\` are compared against, so a screen without ` +
953
+ `one cannot be matched, navigated to or refused.`);
954
+ }
955
+ if (byScreen.has(screen.id)) {
956
+ // Thrown at mount, like a duplicate verb name, and for the same reason:
957
+ // two screens with one id makes one of them permanently unreachable, and
958
+ // the app's map — the thing an agent caches — is ambiguous about which.
959
+ throw new Error(`driverkit: two screens are both named \`${screen.id}\``);
960
+ }
961
+ if (screen.describe !== undefined && screen.describe.length > SIZE_LIMITS.describe) {
962
+ throw new Error(`driverkit: the screen \`${screen.id}\` has a \`describe\` of ` +
963
+ `${screen.describe.length} characters; the budget is ${SIZE_LIMITS.describe}. ` +
964
+ `See \`SIZE_LIMITS\`: this text is in the cached prefix of every session of every ` +
965
+ `user, so a paragraph here is a paragraph everybody pays to carry.`);
966
+ }
967
+ byScreen.set(screen.id, screen);
968
+ for (const [argName, spec] of Object.entries(screen.args ?? {})) {
969
+ if (argName === GOTO_SCREEN_ARG) {
970
+ throw new Error(`driverkit: the screen \`${screen.id}\` declares an argument named ` +
971
+ `\`${GOTO_SCREEN_ARG}\`, which is the name \`goto\` uses for the screen itself. ` +
972
+ `Rename it — \`id\` or \`slug\` is usually what it is.`);
973
+ }
974
+ const already = screenArgs[argName];
975
+ if (already && JSON.stringify(already) !== JSON.stringify({ ...spec, optional: true })) {
976
+ // Thrown rather than resolved in favour of one of them. The two specs
977
+ // become one optional argument of `goto`, so disagreeing describes
978
+ // would put one screen's sentence on the other screen's argument, and
979
+ // disagreeing types would make one of the two screens impossible to
980
+ // reach with a value the schema accepts.
981
+ throw new Error(`driverkit: two screens declare the argument \`${argName}\` differently, and ` +
982
+ `\`goto\` has one argument of that name for all of them. Give them the same ` +
983
+ `\`type\`, \`describe\` and \`oneOf\`, or name them apart.`);
984
+ }
985
+ // Optional, always: see `screenArgs`. The spec is otherwise the app's
986
+ // own, `oneOf` included, so a wrong value is refused with the accepted
987
+ // set listed.
988
+ screenArgs[argName] = { ...spec, optional: true };
989
+ }
990
+ }
991
+ if (screens.length && options.navigate === undefined) {
992
+ // Said once, not thrown. Publishing a map and no way to walk it is a
993
+ // legitimate thing to do — an agent that knows the screens exist and what
994
+ // their addresses look like knows more than one that does not — but it is
995
+ // the less likely of the two readings, and a `goto` that silently did not
996
+ // appear is a bad half-hour. Refusing to mount would be worse: the map is
997
+ // additive and useful on its own.
998
+ warn("`screens` was declared without `navigate`, so the reserved `goto` verb is not " +
999
+ "offered: the core has no router and cannot navigate on its own. Pass " +
1000
+ "`navigate: ({ screen, args, url }) => …` to get `goto`, or ignore this if the map " +
1001
+ "is all you wanted.");
1002
+ }
1003
+ if (screens.length && options.navigate !== undefined && verbs.has(GOTO)) {
1004
+ // The app claimed the name, so the app keeps it. The same rule as the
1005
+ // `rev` and `screen` arguments `driverkit/agent` hoists into every tool
1006
+ // schema: an app that declared its own wins, because the app's meaning
1007
+ // wins over ours. Said once all the same, because the author who hits this
1008
+ // is likelier to have two navigation verbs by accident than on purpose.
1009
+ warn("`screens` and `navigate` were both declared and this app also declares its own verb " +
1010
+ "named `goto`, so the core's reserved one is not added and `navigate` is never " +
1011
+ "called. The app's verb wins; drop one of the two.");
1012
+ }
1013
+ if (screens.length && options.navigate !== undefined && !verbs.has(GOTO)) {
1014
+ const navigate = options.navigate;
1015
+ const ids = [...byScreen.keys()];
1016
+ verbs.set(GOTO, {
1017
+ name: GOTO,
1018
+ // A `read` by the ladder's own definition, which is what the reworded
1019
+ // `read` comment was reworded for: `goto` changes no data and reports no
1020
+ // count, and what it does do — move the person's screen out from under
1021
+ // them — is what `read` now says out loud a read may do. A fourth kind
1022
+ // for navigation was the alternative and it was refused there: the three
1023
+ // kinds are a ladder of what a wrong call COSTS you, and a wrong
1024
+ // navigation costs exactly what a wrong read costs, which is that the
1025
+ // person has to look somewhere else.
1026
+ kind: "read",
1027
+ describe: GOTO_DESCRIBE,
1028
+ args: {
1029
+ [GOTO_SCREEN_ARG]: {
1030
+ type: "string",
1031
+ describe: "the screen's id. Your instructions list every screen this app has and what " +
1032
+ "each one is for.",
1033
+ // The accepted set, in the schema. Static — these are the names of
1034
+ // the app's screens, which are the same for every user forever — so
1035
+ // it is cacheable, and an id that is not one of them is refused by
1036
+ // the core's own argument check WITH THE WHOLE LIST in the reason,
1037
+ // which is a fix the model can make on its next turn without a read.
1038
+ oneOf: ids,
1039
+ },
1040
+ ...screenArgs,
1041
+ },
1042
+ // No `refuses`, and that is deliberate rather than an omission. Most of
1043
+ // what `goto` can say no to belongs to the app: the navigate hook is
1044
+ // where "you may not open that screen" and "there is no such record"
1045
+ // are said, in the app's own vocabulary, which the core cannot
1046
+ // enumerate. Declaring a partial list would turn `refuses` from
1047
+ // documentation into a check that warns at an app for refusing
1048
+ // correctly. The one slug the core itself originates is named in the
1049
+ // description instead.
1050
+ run: async (args, ctx) => {
1051
+ const id = String(args[GOTO_SCREEN_ARG]);
1052
+ const screen = byScreen.get(id);
1053
+ if (!screen) {
1054
+ // Reached only if `oneOf` was bypassed -- a hand-written caller, or
1055
+ // a future core that stops checking. Named rather than left to
1056
+ // throw.
1057
+ return ctx.refuse(BAD_SCREEN_ARG, `no screen named \`${id}\`. This app has: ${ids.join(", ")}.`);
1058
+ }
1059
+ const supplied = {};
1060
+ for (const [argName, spec] of Object.entries(screen.args ?? {})) {
1061
+ const value = args[argName];
1062
+ const reason = checkArg(argName, spec, value);
1063
+ if (reason) {
1064
+ // The screen is named as well as the argument. "missing argument
1065
+ // `slug`" on a verb that takes six optional arguments does not say
1066
+ // which screen wanted it, and the agent's next guess is another
1067
+ // refused call.
1068
+ return ctx.refuse(BAD_SCREEN_ARG, `the \`${id}\` screen needs its own arguments and ${reason}`);
1069
+ }
1070
+ if (value !== undefined && value !== null)
1071
+ supplied[argName] = value;
1072
+ }
1073
+ const url = screen.url === undefined ? undefined : expand(screen.url, supplied);
1074
+ return navigate({ screen: id, args: supplied, ...(url === undefined ? {} : { url }) }, ctx);
1075
+ },
1076
+ });
1077
+ }
1078
+ // ---- the one question the core implements ------------------------------
1079
+ //
1080
+ // Added exactly as `goto` is: after the app's own verbs so a collision can be
1081
+ // seen, before the manifest because it has to appear in it, and only when the
1082
+ // app supplied the one function the core cannot write. See `MountOptions.ask`.
1083
+ //
1084
+ // The whole of the mechanism's behaviour is in `decide()`, not in the `run`
1085
+ // below. That is not an accident of where it fitted: the lock, the deadline,
1086
+ // the allowance and the `waitedMs` the record needs are all things `call()`
1087
+ // owns and a verb body cannot see. What `run` is for is the dead placeholder
1088
+ // underneath -- see the comment on it.
1089
+ const askFn = options.ask;
1090
+ if (askFn !== undefined && typeof askFn !== "function") {
1091
+ // Thrown at mount for the reason a misspelt `approve` is: an app that
1092
+ // believes it can ask and cannot has a verb in everybody's cached prefix
1093
+ // that only ever refuses, and the author finds out from a model's
1094
+ // transcript rather than from a stack trace.
1095
+ throw new Error(`driverkit: \`ask\` must be a function; got ${JSON.stringify(askFn)}. It is handed ` +
1096
+ `\`{ question }\` and returns the person's words, \`{ answered: false }\` when nobody ` +
1097
+ `replied, or \`{ nobody: true }\` when there is nobody on this path.`);
1098
+ }
1099
+ if (askFn !== undefined && verbs.has(ASK)) {
1100
+ // The app claimed the name, so the app keeps it -- the `goto` rule, and the
1101
+ // `rev`/`screen` argument rule one layer up: the app's meaning wins over
1102
+ // ours. Said once all the same, because an author with two ways to ask the
1103
+ // same person the same thing has one of them by accident.
1104
+ warn("`ask` was declared and this app also declares its own verb named `ask`, so the " +
1105
+ "core's reserved one is not added and the `ask` hook is never called. The app's " +
1106
+ "verb wins; drop one of the two. Note that an app's own ask verb is gated, " +
1107
+ "counted and recorded as an ordinary verb and gets none of what the core's does: " +
1108
+ "no lock while the question is open, no deadline, no `budget.asks`.");
1109
+ }
1110
+ /** Whether the core's own `ask` is the verb under that name, so `decide` can
1111
+ * tell it from an app's verb that happens to be called the same thing. An
1112
+ * identity check and not a name check, because the name is the thing an app
1113
+ * is allowed to take. */
1114
+ let coreAsk;
1115
+ if (askFn !== undefined && !verbs.has(ASK)) {
1116
+ coreAsk = {
1117
+ name: ASK,
1118
+ kind: ASK,
1119
+ describe: ASK_DESCRIBE,
1120
+ // No `refuses`. The three slugs this verb can come back with are all
1121
+ // reserved, and `refuses` may not name a reserved slug -- which is the
1122
+ // right answer rather than an awkward one: they say where the question
1123
+ // stopped and not what the app decided, so they belong in the reserved
1124
+ // list and are named in the description instead. The same shape as
1125
+ // `goto`, whose one core refusal is also described rather than declared.
1126
+ args: {
1127
+ [ASK_QUESTION_ARG]: {
1128
+ type: "string",
1129
+ describe: "what to ask, in your own words, as one short question. Put everything you " +
1130
+ "already know into it so the person can answer in a word.",
1131
+ },
1132
+ },
1133
+ /**
1134
+ * The dead placeholder, and it is load-bearing.
1135
+ *
1136
+ * Lifted straight from the pattern that works elsewhere: a tool whose
1137
+ * body returns a plain, honest "no response was recorded for this", so
1138
+ * that if the mechanism above it is ever skipped the model is told the
1139
+ * truth instead of reading an `ok` for a question nobody saw. `decide()`
1140
+ * answers every `ask` before `run` is reached, so **this should be
1141
+ * unreachable** — which is exactly why it has to say something a model
1142
+ * can act on rather than throw or return nothing.
1143
+ *
1144
+ * It refuses rather than reporting, because `ok — …` is the shape an
1145
+ * ANSWER has and a placeholder that borrowed it would be a fabricated
1146
+ * answer. `nobody-to-ask` is the honest slug: no question was put to
1147
+ * anybody.
1148
+ */
1149
+ run: (_args, ctx) => ctx.refuse(NOBODY_TO_ASK, "no question was put to anybody: this app offers the `ask` verb and the call did " +
1150
+ "not reach the person. Nothing in the app changed and no answer was recorded. " +
1151
+ "Do not treat this as a reply, and do not ask again — say what you needed to " +
1152
+ "know and what you could not decide without it."),
1153
+ };
1154
+ verbs.set(ASK, coreAsk);
1155
+ }
1156
+ // ---- the app's recipes --------------------------------------------------
1157
+ const flows = options.flows ?? [];
1158
+ const flowIds = new Set();
1159
+ for (const flow of flows) {
1160
+ if (typeof flow.id !== "string" || flow.id === "") {
1161
+ throw new Error("driverkit: a flow in `flows` has no `id`");
1162
+ }
1163
+ if (flowIds.has(flow.id)) {
1164
+ throw new Error(`driverkit: two flows are both named \`${flow.id}\``);
1165
+ }
1166
+ flowIds.add(flow.id);
1167
+ if (typeof flow.describe !== "string" || flow.describe === "") {
1168
+ throw new Error(`driverkit: the flow \`${flow.id}\` has no \`describe\`. It is the field a model ` +
1169
+ `chooses a flow on — the selection is made on the description and not on the ` +
1170
+ `individual steps — so a flow without one is a flow nothing will pick.`);
1171
+ }
1172
+ if (flow.describe.length > SIZE_LIMITS.describe || /[\n\r]/.test(flow.describe)) {
1173
+ throw new Error(`driverkit: the flow \`${flow.id}\` must have a one-line \`describe\` of at most ` +
1174
+ `${SIZE_LIMITS.describe} characters (got ${flow.describe.length}` +
1175
+ `${/[\n\r]/.test(flow.describe) ? ", with a line break" : ""}). See \`SIZE_LIMITS\`.`);
1176
+ }
1177
+ if (!Array.isArray(flow.steps) || flow.steps.length === 0) {
1178
+ throw new Error(`driverkit: the flow \`${flow.id}\` has no \`steps\`. A flow with no steps is a ` +
1179
+ `sentence, and \`instructions\` is where a sentence goes.`);
1180
+ }
1181
+ // `skipWhen` is in the sum because it is rendered into the same cached
1182
+ // prefix as the hint it was lifted out of. A flow that moved a sentence
1183
+ // from one field to the other must not be able to grow a budget by doing
1184
+ // it.
1185
+ const body = flow.steps
1186
+ .map((s) => `${s.section ?? ""}${s.verb}${s.hint}${s.skipWhen ?? ""}`)
1187
+ .join("");
1188
+ if (body.length > SIZE_LIMITS.body) {
1189
+ throw new Error(`driverkit: the flow \`${flow.id}\` has ${body.length} characters of steps; the ` +
1190
+ `budget is ${SIZE_LIMITS.body}. See \`SIZE_LIMITS\`.`);
1191
+ }
1192
+ for (const step of flow.steps) {
1193
+ // Thrown at mount, the way a duplicate verb name is. A recipe citing a
1194
+ // verb nobody implemented is a dead end whose only symptom is an agent
1195
+ // halfway through a job meeting `unknown-verb` -- after the navigation
1196
+ // and before the commit, which is the worst place to find out. Checked
1197
+ // against the map AFTER `goto` was added to it, so a flow may name the
1198
+ // reserved verb like any other.
1199
+ if (!verbs.has(step.verb)) {
1200
+ const known = [...verbs.keys()].sort().join(", ");
1201
+ throw new Error(`driverkit: the flow \`${flow.id}\` names the verb \`${step.verb}\`, which this ` +
1202
+ `app does not have. known: ${known}. A flow is a recipe an agent reads and ` +
1203
+ `follows with real verbs, so a step naming one that does not exist is a dead ` +
1204
+ `end it would find halfway through the job.`);
1205
+ }
1206
+ if (typeof step.hint !== "string" || step.hint === "") {
1207
+ throw new Error(`driverkit: the step \`${step.verb}\` of the flow \`${flow.id}\` has no \`hint\`. ` +
1208
+ `The verb's own \`describe\` already says what the verb does; the hint is what ` +
1209
+ `to do with it here, which is the part that makes this a recipe.`);
1210
+ }
1211
+ // An empty `skipWhen` is the one that has to be caught, because the field
1212
+ // being PRESENT is what makes a step optional: a step marked skippable
1213
+ // with no stated condition tells a model it may drop a step whenever it
1214
+ // likes, which is the opposite of what an author who typed the field
1215
+ // meant. The length and the newline are the `describe` rule, for the
1216
+ // `describe` reason -- it is a one-line condition rendered beside the
1217
+ // step, not a paragraph to reason from.
1218
+ if (step.skipWhen !== undefined) {
1219
+ if (typeof step.skipWhen !== "string" || step.skipWhen === "") {
1220
+ throw new Error(`driverkit: the step \`${step.verb}\` of the flow \`${flow.id}\` has an empty ` +
1221
+ `\`skipWhen\`. Present means this step may be skipped, so the field has to say ` +
1222
+ `WHEN — "the person already named the company". A skippable step with no ` +
1223
+ `condition is an invitation to drop it for no reason.`);
1224
+ }
1225
+ if (step.skipWhen.length > SIZE_LIMITS.describe || /[\n\r]/.test(step.skipWhen)) {
1226
+ throw new Error(`driverkit: the \`skipWhen\` on the step \`${step.verb}\` of the flow ` +
1227
+ `\`${flow.id}\` must be one line of at most ${SIZE_LIMITS.describe} characters ` +
1228
+ `(got ${step.skipWhen.length}` +
1229
+ `${/[\n\r]/.test(step.skipWhen) ? ", with a line break" : ""}). ` +
1230
+ `See \`SIZE_LIMITS\`.`);
1231
+ }
1232
+ }
1233
+ }
1234
+ // THE ONE PIECE OF DATA FLOW BETWEEN STEPS, CHECKED WHERE IT CAN BE SEEN.
1235
+ //
1236
+ // A `commit` that declares `consumes: "plan"` can only be called with the
1237
+ // token a `describe` returned beside its count. So a flow that reaches such
1238
+ // a step without an earlier `describe` step is a recipe whose only possible
1239
+ // ending is `stale-plan`: the agent follows it, arrives at the commit with
1240
+ // no token, and is refused -- after the navigation and before anything
1241
+ // moves, which is the same worst moment a step naming a missing verb is
1242
+ // found at, and the same reason this throws rather than waits.
1243
+ //
1244
+ // Statically visible and therefore the core's job: the step order is fixed,
1245
+ // the verbs' `kind` and `consumes` are declared, and nothing per-user is
1246
+ // involved. It is also the whole of what a flow can honestly say about
1247
+ // values crossing steps -- see the note under `FlowStep` for why there is
1248
+ // no `from: "step2.slug"` to go with it.
1249
+ //
1250
+ // It throws on `flows`, which is new, by the rule stated at the
1251
+ // `instructions` budget above: a new throw on an old field would break an
1252
+ // app that mounted yesterday, and a new one cannot have mounted yet.
1253
+ let minted;
1254
+ for (const step of flow.steps) {
1255
+ const verb = verbs.get(step.verb);
1256
+ if (verb.consumes === "plan" && minted === undefined) {
1257
+ throw new Error(`driverkit: the flow \`${flow.id}\` reaches \`${step.verb}\`, which consumes a ` +
1258
+ `plan, with no earlier \`describe\` step to mint one. A plan token comes from ` +
1259
+ `the \`describe\` verb that counted the selection, so an agent following this ` +
1260
+ `recipe arrives at the commit with nothing to pass and is refused ` +
1261
+ `\`stale-plan\`. Put the counting step in the flow.`);
1262
+ }
1263
+ if (verb.kind === "describe")
1264
+ minted = step.verb;
1265
+ }
1266
+ }
1267
+ if (options.instructions && options.instructions.length > SIZE_LIMITS.instructions) {
1268
+ // Warned and not thrown, which is the one inconsistency in here and it is
1269
+ // deliberate. `instructions` existed before it had a budget, so an app
1270
+ // that mounted yesterday with a very long briefing must still mount today:
1271
+ // a new throw on an old field is exactly the kind of change the additive
1272
+ // rule forbids. `screens` and `flows` are new, nothing can already be over
1273
+ // their budget, and so they throw.
1274
+ warn(`\`instructions\` is ${options.instructions.length} characters; the documented budget ` +
1275
+ `is ${SIZE_LIMITS.instructions}. It is sent in the cached prefix of every session, ` +
1276
+ `so the cost is paid once per person rather than once per turn — but a briefing ` +
1277
+ `this long is competing with the verbs for the model's attention. See \`SIZE_LIMITS\`.`);
1278
+ }
1279
+ // ALL OR NONE, said once at mount.
1280
+ //
1281
+ // An eval found the hole this exists to name. The worked example declared
1282
+ // `consumes: "plan"` on `accept-selected` and left `decline-selected` bare,
1283
+ // and an agent asked for a job the app could not do improvised its way to the
1284
+ // bare one: 403 rows changed status with no count read and nothing gated. The
1285
+ // verb an agent reaches for when it is off its intended path is the
1286
+ // least-declared one, so a guarantee is only as strong as its weakest
1287
+ // sibling.
1288
+ //
1289
+ // WHY A WARNING AND NOT A THROW. Because adopting this field one verb at a
1290
+ // time is a legitimate state to be in for the length of an afternoon, and an
1291
+ // app that cannot mount halfway through its own migration is an app whose
1292
+ // author reverts the first half. The author who is told, once, at startup, in
1293
+ // the words of the two verbs involved, fixes it; a throw would be a change
1294
+ // that breaks an app for declaring a safety field on one verb, which teaches
1295
+ // the opposite lesson.
1296
+ //
1297
+ // WHAT IT CAN AND CANNOT SEE. The signal is a `commit` with NO ARGUMENTS: a
1298
+ // verb that takes nothing can only be acting on ambient state, which is the
1299
+ // selection or the open record, which is the thing a plan is a receipt for.
1300
+ // Deliberately narrow. `set-setting(name, value)` names what it changes and
1301
+ // must not be nagged about; `set-status(status)`, which changes the one record
1302
+ // whose screen is open, has an argument and will NOT be caught — a false
1303
+ // negative that is accepted on purpose, because the honest alternative is
1304
+ // warning about every commit with an argument, which is a warning on
1305
+ // everything and therefore a warning on nothing. The rule in `Verb.consumes`
1306
+ // is the thing to remember; this catches the shape that bit us.
1307
+ const consuming = [...verbs.values()].filter((v) => v.consumes === "plan");
1308
+ if (consuming.length) {
1309
+ const bare = [...verbs.values()].filter((v) => v.kind === "commit" && v.consumes === undefined && v.args === undefined);
1310
+ if (bare.length) {
1311
+ warn(`\`${consuming[0].name}\` consumes a plan but ${bare.map((v) => `\`${v.name}\``).join(", ")} ` +
1312
+ `${bare.length > 1 ? "are commits" : "is a commit"} that takes no arguments and asks ` +
1313
+ `for no plan. A commit with no arguments acts on the selection, so an agent that ` +
1314
+ `wants to move rows without a counted plan will use that one — which makes the ` +
1315
+ `check on \`${consuming[0].name}\` advisory. Declare \`consumes: "plan"\` on every ` +
1316
+ `commit that acts on the selection, or on none of them.`);
1317
+ }
1318
+ }
1319
+ // Computed once. The manifest is the half that gets cached by whoever is
1320
+ // driving, so it must not vary call to call; deriving it lazily on every
1321
+ // read would invite someone to fold `visible()` into it.
1322
+ const manifest = {
1323
+ version: fingerprint(options.app, verbs, options.instructions, options.screens, options.flows),
1324
+ app: options.app,
1325
+ // The app's own briefing, in the half that is cached once. Omitted rather
1326
+ // than sent as an empty string, so an app that passes nothing produces the
1327
+ // manifest it produced before this field existed -- byte for byte, which
1328
+ // is what the fingerprint hashes.
1329
+ ...(options.instructions ? { instructions: options.instructions } : {}),
1330
+ verbs: [...verbs.values()].map((v) => ({
1331
+ name: v.name,
1332
+ describe: v.describe,
1333
+ ...(v.kind ? { kind: v.kind } : {}),
1334
+ // Copied through untouched and never read by anything in here. `at` is a
1335
+ // hint for whoever is drawing the run, not a way to find an element; see
1336
+ // `Verb.at`.
1337
+ ...(v.at ? { at: v.at } : {}),
1338
+ // `screen` IS read in here, by `call` below, and it is still copied for
1339
+ // the same reason `kind` is: the manifest is the only description of this
1340
+ // verb an agent gets, and "works only on the companies list" is a fact it
1341
+ // should read in the cached half rather than discover by being refused.
1342
+ //
1343
+ // Copied in the shape the app declared, a string staying a string rather
1344
+ // than being normalised to a one-element array. Every client reading
1345
+ // `verbs[].screen` today reads it as a string, and normalising would move
1346
+ // every single-screen app's manifest -- and its fingerprint -- for a
1347
+ // change that app did not make.
1348
+ ...(v.screen ? { screen: v.screen } : {}),
1349
+ ...(v.reversible ? { reversible: v.reversible } : {}),
1350
+ // Copied for the reason `screen` is, and more urgently: `screen` tells an
1351
+ // agent WHERE a verb can be called and this tells it HOW. A client that
1352
+ // did not see this renders a tool with no `plan` property and no sentence
1353
+ // about the pairing, so the model calls the commit bare and is refused
1354
+ // every time, with nothing in the half it cached to explain the fix.
1355
+ ...(v.consumes ? { consumes: v.consumes } : {}),
1356
+ ...(v.args ? { args: v.args } : {}),
1357
+ ...(v.refuses ? { refuses: v.refuses } : {}),
1358
+ })),
1359
+ // The map and the recipes, copied through as declared. Both omitted
1360
+ // entirely when the app declared neither, so the manifest of an app that
1361
+ // uses neither is the document it was before these fields existed -- byte
1362
+ // for byte, which is what the fingerprint hashes and what every stored
1363
+ // `Manifest.version` out there was computed from.
1364
+ ...(options.screens ? { screens: options.screens } : {}),
1365
+ ...(options.flows ? { flows: options.flows } : {}),
1366
+ };
1367
+ // ---- what another tab did ----------------------------------------------
1368
+ //
1369
+ // Six lines of state and a sentence, and the sentence is the point: see
1370
+ // `ElsewhereChannel` for the hole, and `MountOptions.elsewhere` for what this
1371
+ // does and does not buy.
1372
+ const channel = options.elsewhere;
1373
+ /** This driver's identity on the channel, so it can ignore its own notices.
1374
+ * A `BroadcastChannel` does not echo to the sender, but a websocket relay
1375
+ * fanning out to every subscriber does, and a channel that poisoned the tab
1376
+ * that committed would refuse the second half of every two-step job. */
1377
+ const elsewhereId = `dke${(elsewhereSeq += 1)}.${Math.random().toString(36).slice(2)}`;
1378
+ /**
1379
+ * The notice this driver is sitting on, or null.
1380
+ *
1381
+ * `at` is the `rev` this app was showing when the notice arrived, and it is
1382
+ * the whole expiry rule: the notice is outstanding for exactly as long as
1383
+ * this app's own `rev` has not moved. One notice, not a list — a second
1384
+ * commit elsewhere while the first is still outstanding tells an agent
1385
+ * nothing new, and the repair is the same one.
1386
+ */
1387
+ let elsewhere = null;
1388
+ /** Said to the model, in the snapshot's own `note`, for as long as the notice
1389
+ * stands. The one sentence that turns a silent lie into a visible one. */
1390
+ const elsewhereNote = (verb) => `WARNING: another tab of this app committed \`${verb}\` after this screen was read, so ` +
1391
+ `the rows and the rev above may be out of date even though the rev has not moved. ` +
1392
+ `A commit here is refused as \`changed-elsewhere\` until this tab refreshes.`;
1393
+ /**
1394
+ * `visible()`, plus the notice if there is one.
1395
+ *
1396
+ * EVERY read goes through here -- `driver.snapshot()`, the snapshot on every
1397
+ * `Result`, the one an approval hook is handed, the one `connect()` pushes to
1398
+ * the relay -- because a warning that reached some of those and not others
1399
+ * would be a guarantee that holds on one path, which is the defect
1400
+ * `MountOptions.approve` was moved into the core to fix.
1401
+ *
1402
+ * Carried in `note`, which is already "anything else the agent needs and the
1403
+ * rows cannot carry", and which BOTH renderers already print. The
1404
+ * alternatives were a new field on `Snapshot` -- app-published, and this is
1405
+ * the core speaking, not the app -- or a second channel to the model that
1406
+ * only one of the two renderers knew about.
1407
+ *
1408
+ * The app's own `note` is kept and appended to, never replaced: the app may
1409
+ * be saying something the person needs and this is not more important than
1410
+ * that.
1411
+ *
1412
+ * The clear lives here rather than in a timer because this is the only place
1413
+ * the core learns what `rev` is now. An app that never reads is an app
1414
+ * nothing is being driven in.
1415
+ */
1416
+ function read() {
1417
+ const snap = options.visible();
1418
+ if (elsewhere === null)
1419
+ return snap;
1420
+ if (snap.rev !== elsewhere.at) {
1421
+ elsewhere = null;
1422
+ return snap;
1423
+ }
1424
+ const sentence = elsewhereNote(elsewhere.verb);
1425
+ return { ...snap, note: snap.note ? `${snap.note} ${sentence}` : sentence };
1426
+ }
1427
+ if (channel !== undefined) {
1428
+ const stop = channel.listen((notice) => {
1429
+ // Its own notice, or a malformed one. Dropped rather than warned about:
1430
+ // a channel shared with a future version of this library may carry
1431
+ // frames this one does not understand, and taking a driver out of service
1432
+ // over one is how a forward-compatible addition becomes an outage.
1433
+ if (!notice || typeof notice.verb !== "string" || notice.from === elsewhereId)
1434
+ return;
1435
+ if (!live)
1436
+ return;
1437
+ // `options.visible()` and not `read()`: this is where `at` is set, so
1438
+ // reading through the annotator would be asking what the note says in
1439
+ // order to decide what the note says.
1440
+ let now;
1441
+ try {
1442
+ now = options.visible().rev;
1443
+ }
1444
+ catch {
1445
+ // `visible()` threw outside a call, which is an app bug the core
1446
+ // cannot report to anybody here. The notice is kept against a rev
1447
+ // nothing can equal, so it stands until a successful read clears it --
1448
+ // the safe direction.
1449
+ now = Number.NaN;
1450
+ }
1451
+ elsewhere = { verb: notice.verb, at: now };
1452
+ });
1453
+ if (typeof stop === "function")
1454
+ unlisten = stop;
1455
+ }
1456
+ /**
1457
+ * Tell the other tabs a commit landed here.
1458
+ *
1459
+ * POSTED AFTER `run`, and only for a `commit`, and not when the verb refused.
1460
+ * Each of those three is a decision:
1461
+ *
1462
+ * - after rather than before, because a notice sent first is a claim about a
1463
+ * change that has not happened yet, and the sibling tab would clear it on
1464
+ * its next `rev` move -- possibly before the write landed;
1465
+ * - `commit` only, because `read` and `describe` promise no data moves and
1466
+ * announcing them would refuse every commit in every other tab for every
1467
+ * read anybody did, which is a warning on everything;
1468
+ * - not on an app refusal, because the app saying no means nothing moved.
1469
+ * A verb that THREW does get announced: it may have changed half a
1470
+ * selection, which is the same reason the plan token is burned on
1471
+ * entering `run` rather than on returning from it.
1472
+ */
1473
+ function announce(name) {
1474
+ if (channel === undefined)
1475
+ return;
1476
+ try {
1477
+ channel.post({ verb: name, from: elsewhereId });
1478
+ }
1479
+ catch (err) {
1480
+ // A commit that already happened is not turned into a failure because
1481
+ // the announcement could not go out. Said once, in the app author's
1482
+ // console, because a channel that never delivers makes the whole check
1483
+ // silently absent -- which is the one thing this feature must not be.
1484
+ warn(`the \`elsewhere\` channel threw while announcing \`${name}\` ` +
1485
+ `(${err instanceof Error ? err.message : String(err)}), so other tabs of this app ` +
1486
+ `were not told. The commit itself ran.`);
1487
+ }
1488
+ }
1489
+ /**
1490
+ * A per-driver salt, folded into every token's hash.
1491
+ *
1492
+ * Two things make this necessary rather than decorative. Without it, two
1493
+ * drivers mounted from the same verb table and driven through the same calls
1494
+ * mint the SAME token string — the bound fields are identical — so a plan
1495
+ * from one app would be honoured by another, which is a receipt that proves
1496
+ * nothing about where it came from. And with the formula sitting in this file
1497
+ * in plain sight, an agent that wanted to skip the describe could compute a
1498
+ * token for itself; a salt it has never seen is what stops that being a
1499
+ * three-line bypass of the whole mechanism.
1500
+ *
1501
+ * `Math.random` rather than a crypto import, because the core has no
1502
+ * dependencies and this is not a security boundary: the thing on the other
1503
+ * end is a confused agent, not an attacker with the page's own privileges,
1504
+ * and anything that could read this variable could already call the verb.
1505
+ */
1506
+ const planSalt = `${(planSeq += 1)}.${Math.random().toString(36).slice(2)}`;
1507
+ const plans = new Map();
1508
+ /** The `rev` every record in `plans` was minted at, which is what keeps the
1509
+ * map to one rev's worth: it is cleared the moment a newer one mints. Not
1510
+ * the expiry check -- that is `plansGoodAt` -- so this stays the honest
1511
+ * answer to "when was this counted" and goes on bounding the memory. */
1512
+ let plansAt = -1;
1513
+ /**
1514
+ * The `rev` the outstanding plans are still good AT, which starts equal to
1515
+ * `plansAt` and is the only thing `checkPlan` compares against.
1516
+ *
1517
+ * THE DEFECT THIS SPLITS IN TWO. `Snapshot.rev` means "the snapshot
1518
+ * changed", and a read-only navigation genuinely changes the snapshot: the
1519
+ * person is looking at a different screen. So one number was answering two
1520
+ * questions. `stale` asks "is what you were looking at still what is on
1521
+ * screen?" -- and navigation really does invalidate that, which is why the
1522
+ * `stale` check still compares the raw `rev` and is untouched here. A plan
1523
+ * token asks "is the selection you counted still the selection?" -- and
1524
+ * navigation does not touch that at all. Conflating them priced the
1525
+ * double-check above the blind commit: `select-where` then `goto` then
1526
+ * `accept-selected` was refused `stale-plan` although nothing about the
1527
+ * selection had moved, so the cheap path was to commit without re-reading.
1528
+ * The whole mechanism exists to make an agent read the number before it
1529
+ * moves 3,412 rows, and teaching it that looking first costs two extra calls
1530
+ * teaches exactly the wrong habit.
1531
+ *
1532
+ * WHAT CARRIES IT FORWARD, and every clause is a safety condition rather
1533
+ * than a convenience; see the carry in `call()`. A verb that DECLARED
1534
+ * `kind: "read"` -- the kind whose own documentation says "changes no data
1535
+ * and reports no count. It may still move what the person is looking at:
1536
+ * navigation is a read" -- that moved `rev`, while the app publishes a
1537
+ * `Snapshot.selectionId` and that string is unchanged across the call.
1538
+ *
1539
+ * WHAT DOES NOT. An app that publishes no `selectionId` carries nothing and
1540
+ * behaves exactly as it did before this existed: its token still dies on the
1541
+ * first `rev` move of any kind. That is the fail-safe direction and it is the
1542
+ * reason this was done with `selectionId` rather than with a second counter
1543
+ * an author has to remember to bump -- an author who forgot the counter would
1544
+ * get a token that never expires, which is the 3,412-row bug. A `commit`
1545
+ * carries nothing, since a commit is the thing a plan is a receipt against. A
1546
+ * verb with no declared `kind` carries nothing, because an absent `kind`
1547
+ * makes no safety claim in either direction. And a `rev` that moved with no
1548
+ * verb behind it at all -- a websocket landing between two calls -- carries
1549
+ * nothing, because the plan was already dead by the time the next verb
1550
+ * started: the carry requires that the plans were still good at the rev the
1551
+ * read STARTED from.
1552
+ */
1553
+ let plansGoodAt = -1;
1554
+ /**
1555
+ * The `Snapshot.selectionId` the outstanding plans were minted against, or
1556
+ * undefined in an app that publishes none.
1557
+ *
1558
+ * Driver-level rather than per-plan because every outstanding plan shares it:
1559
+ * `mint` clears the map whenever `rev` moves, so the map only ever holds
1560
+ * plans taken at one rev, and one rev is one selection. It is kept separately
1561
+ * from the plans all the same, so the carry can be decided when the map is
1562
+ * empty and without picking an arbitrary entry out of it.
1563
+ */
1564
+ let plansSelection;
1565
+ let planCount = 0;
1566
+ /**
1567
+ * Whether this app uses plans at all, decided once, statically.
1568
+ *
1569
+ * An app with no `consumes` verb gets no tokens minted, so its `describe`
1570
+ * verbs return exactly the `Result` they returned before this existed —
1571
+ * byte for byte, which matters because that result is rendered into a
1572
+ * transcript and asserted on. Minting unconditionally would put a `plan`
1573
+ * field, and a line of rendered text, into every app in the world for a
1574
+ * feature none of them had asked for.
1575
+ */
1576
+ const usesPlans = [...verbs.values()].some((v) => v.consumes === "plan");
1577
+ /** How large a selection says it is, as the screen reports it.
1578
+ *
1579
+ * `selectedCount` first and `selected.length` only as a fallback, which is
1580
+ * the order those two fields document: `selected` is by design just the ids
1581
+ * on screen, so reading it first would report 20 for a selection of 3,412
1582
+ * and the `stale-plan` hint would name a number nobody was ever shown. */
1583
+ const sizeOf = (s) => s.selectedCount ?? (s.selected ? s.selected.length : undefined);
1584
+ /**
1585
+ * Mint a token for the selection a `describe` just left behind.
1586
+ *
1587
+ * The token is opaque to everybody but this driver, and it carries its `rev`
1588
+ * in clear on purpose: a plan is retired the moment a newer one is minted, so
1589
+ * a token that is no longer in the map must still be able to say whether it
1590
+ * was a plan from two revs ago — which is a useful refusal naming both
1591
+ * numbers — or a string that was never a plan at all. The hash is over every
1592
+ * bound field, so a token cannot be edited into a claim about another verb,
1593
+ * another rev or another selection.
1594
+ */
1595
+ function mint(verb, after, count) {
1596
+ if (after.rev !== plansAt) {
1597
+ plans.clear();
1598
+ plansAt = after.rev;
1599
+ }
1600
+ // Reset on every mint, carried plans included. A fresh describe is a fresh
1601
+ // count, so whatever a previous plan had been carried to is irrelevant from
1602
+ // here; and the clear above means a carried plan from an older rev is
1603
+ // retired by this mint exactly as it was before the carry existed.
1604
+ plansGoodAt = after.rev;
1605
+ plansSelection = after.selectionId;
1606
+ // A guard, not a policy. An app whose `rev` never moves could mint without
1607
+ // limit, and this driver may live for the life of a tab. The oldest goes,
1608
+ // and an agent holding it is refused `stale-plan` -- which is the right
1609
+ // answer for a plan that is some thousands of describes old.
1610
+ if (plans.size >= 64) {
1611
+ const oldest = plans.keys().next().value;
1612
+ if (oldest !== undefined)
1613
+ plans.delete(oldest);
1614
+ }
1615
+ planCount += 1;
1616
+ const n = planCount;
1617
+ const bound = JSON.stringify([planSalt, verb, after.rev, after.selectionId ?? null, count, n]);
1618
+ const token = `${PLAN_PREFIX}.${after.rev}.${n}.${hash12(bound)}`;
1619
+ plans.set(token, {
1620
+ verb,
1621
+ rev: after.rev,
1622
+ ...(after.selectionId === undefined ? {} : { selection: after.selectionId }),
1623
+ count,
1624
+ used: false,
1625
+ });
1626
+ return token;
1627
+ }
1628
+ /** The `rev` a token says it was minted at, or null when it is not a token
1629
+ * this core could have produced. Only ever used to phrase a refusal. */
1630
+ function revOf(token) {
1631
+ const parts = token.split(".");
1632
+ if (parts.length !== 4 || parts[0] !== PLAN_PREFIX)
1633
+ return null;
1634
+ const rev = Number(parts[1]);
1635
+ return Number.isSafeInteger(rev) ? rev : null;
1636
+ }
1637
+ /**
1638
+ * The five ways a plan can fail, and the hint for each.
1639
+ *
1640
+ * Returns the hint to refuse with, or null to allow. Every branch names the
1641
+ * same repair — see `PLAN_REPAIR` — and the branches differ only in what they
1642
+ * say went wrong, because "your plan is stale" with no account of how is a
1643
+ * dead end in exactly the way a bare `wrong-screen` was.
1644
+ */
1645
+ function checkPlan(name, token, before) {
1646
+ if (token === undefined || token === "") {
1647
+ const empty = sizeOf(before) === 0;
1648
+ return (`\`${name}\` acts on the current selection, so it may only be called with the ` +
1649
+ `\`plan\` token from the \`describe\` verb that counted it. You sent none, so nothing ` +
1650
+ `ran: without one, the number you read and the rows that move are two different ` +
1651
+ `claims.` +
1652
+ // Said when the app reports an empty selection, because this is the
1653
+ // case where the generic advice reads as an instruction to go and find
1654
+ // something to act on. Only when the app actually counts -- an absent
1655
+ // `selectedCount` means "I do not count", and "nothing is selected" is
1656
+ // not a thing to assert from a missing field.
1657
+ (empty
1658
+ ? ` Nothing is selected right now, so there is no count for a plan to be taken on` +
1659
+ ` and nothing for this verb to do.`
1660
+ : "") +
1661
+ ` ${PLAN_MISSING_REPAIR}`);
1662
+ }
1663
+ const plan = plans.get(token);
1664
+ if (!plan) {
1665
+ const was = revOf(token);
1666
+ if (was !== null && was !== before.rev) {
1667
+ // The common case, and the one the whole feature is about: the agent
1668
+ // is holding a receipt from before something moved.
1669
+ return (`that plan was taken at rev ${was} and the screen is now at rev ${before.rev}, so ` +
1670
+ `the selection it counted is not the selection on screen. ${PLAN_REPAIR}`);
1671
+ }
1672
+ return (`\`${token}\` is not a plan this app has outstanding — it was never minted here, or it ` +
1673
+ `has been superseded by a later one. Nothing ran. ${PLAN_REPAIR}`);
1674
+ }
1675
+ // BOTH NUMBERS, in every refusal about a plan this driver actually minted,
1676
+ // the way `wrong-screen` names both screens. "Your plan is stale" sends a
1677
+ // model back to re-read and work out what changed; "you were shown 3,412
1678
+ // and the selection is now 3,418" is a sentence it can say to the person
1679
+ // who approved the first number, which is the whole job. Appended to each
1680
+ // reason rather than built into one, so each branch still says what went
1681
+ // wrong as well as by how much.
1682
+ const now = sizeOf(before);
1683
+ const both = ` You were shown ${plan.count}; the selection is now ` +
1684
+ `${now === undefined ? "not counted by the app" : String(now)}.`;
1685
+ if (plan.used) {
1686
+ // Single use, and the refusal says so rather than saying "stale", because
1687
+ // an agent told "stale" will re-read and try the same token again.
1688
+ return (`that plan has already been used by a commit. A plan is good for one commit, so that a ` +
1689
+ `count a person approved once cannot be acted on twice.${both} ${PLAN_REPAIR}`);
1690
+ }
1691
+ // `plansGoodAt` and not `plan.rev`, which is the whole of the fix. The two
1692
+ // are the same number until a read-only move carries them apart, and they
1693
+ // are compared here rather than in `call()` so that the one refusal still
1694
+ // names the rev the count was actually taken at.
1695
+ if (plansGoodAt !== before.rev) {
1696
+ return (`that plan was taken at rev ${plan.rev} and the screen is now at rev ${before.rev}, so ` +
1697
+ `the selection it counted is not the selection on screen.${both} ${PLAN_REPAIR}`);
1698
+ }
1699
+ // The case `rev` alone cannot catch: an app that changed its selection
1700
+ // without moving its `rev`.
1701
+ if (plan.selection !== undefined && plan.selection !== before.selectionId) {
1702
+ return (`that plan named a different selection from the one on screen now.${both} ` +
1703
+ `${PLAN_REPAIR}`);
1704
+ }
1705
+ if (plan.selection === undefined) {
1706
+ // Said once, not refused, and it is the honest disclosure of how strong
1707
+ // this check actually is in this app. The verb asked for a plan, the app
1708
+ // publishes no `selectionId`, so the token binds the `rev` and the count
1709
+ // and nothing else -- which catches every change the app bumps its `rev`
1710
+ // for and no change it makes quietly. Refusing instead would break an
1711
+ // app that adopted `consumes` before `selectionId`; saying nothing would
1712
+ // let the weaker check be mistaken for the stronger one. See `warn`.
1713
+ warn(`the verb \`${name}\` consumes a plan but \`visible()\` returns no \`selectionId\`, so ` +
1714
+ `the token can only bind the \`rev\` and the count. A selection that changes without ` +
1715
+ `moving \`rev\` will not be caught. Fill in \`Snapshot.selectionId\` — ` +
1716
+ `\`selectionId(ids)\` from this package is the one to use.`);
1717
+ }
1718
+ return null;
1719
+ }
1720
+ /** The manifest entry for a verb, which is what an approval hook is handed.
1721
+ * Built from the manifest rather than from the `Verb` so a gate reads the
1722
+ * declared facts and cannot reach `run`; see `ApprovalRequest`. */
1723
+ const entries = new Map(manifest.verbs.map((v) => [v.name, v]));
1724
+ const ctx = { refuse: refusal };
1725
+ /**
1726
+ * Ask, and turn the three answers into the three outcomes.
1727
+ *
1728
+ * Returns null to allow, or the refusal to send back. The lock is taken for
1729
+ * the duration and released in a `finally`: a hook that throws must not
1730
+ * leave a driver that refuses every later call, and it must not be read as
1731
+ * consent either — a failed ask is a no, which is the rule
1732
+ * `onBeforeCommit` already had and the only safe way round it is a person.
1733
+ */
1734
+ async function askApproval(ask, name, args, before, trail) {
1735
+ const req = { name, args, verb: entries.get(name), snapshot: before };
1736
+ const was = pending;
1737
+ pending = { verb: name, question: false };
1738
+ // The one wait in this file that is a PERSON rather than the app, and
1739
+ // therefore the one worth timing separately. Read only when a record is
1740
+ // going to be built -- an app with no `onAudit` reads no clock here, the
1741
+ // same promise `call` already makes.
1742
+ const askedAt = onAudit === undefined ? 0 : Date.now();
1743
+ let decision;
1744
+ try {
1745
+ decision = await deadline(ask(req), { timedOut: true }, options.approvalTimeout);
1746
+ }
1747
+ catch (err) {
1748
+ decision = `the approval could not be asked for (${err instanceof Error ? err.message : String(err)}), and a failed ask is a no, never a yes`;
1749
+ }
1750
+ finally {
1751
+ pending = was;
1752
+ // In the `finally`, so EVERY exit is timed: a yes, a no, a deadline, and
1753
+ // a hook that threw. A person who spent two minutes and then declined is
1754
+ // exactly as interesting to an auditor as one who spent two minutes and
1755
+ // approved, and a figure recorded only on the happy path is one that
1756
+ // vanishes from the records somebody is most likely to be reading.
1757
+ if (onAudit !== undefined)
1758
+ trail.waitedMs = Math.max(0, Date.now() - askedAt);
1759
+ }
1760
+ // The answer, written down as one of four words before it is turned into a
1761
+ // refusal. Four and not three because `declined` and `not-asked` are the
1762
+ // two an audit reader must never confuse -- one is a person refusing, the
1763
+ // other is a gate that was not there -- and a hook that THREW is recorded
1764
+ // as `declined`, deliberately, because that is the decision the core made
1765
+ // from it: a failed ask is a no.
1766
+ if (decision === undefined || decision === true) {
1767
+ trail.approval = "allowed";
1768
+ return null;
1769
+ }
1770
+ // Read through one probe rather than narrowed member by member, because
1771
+ // the two object answers have no field in common and the next one will not
1772
+ // either: a gate answers in the shapes it needs, and the core's job is to
1773
+ // recognise them without caring what else is on the object.
1774
+ const shape = typeof decision === "object" && decision !== null
1775
+ ? decision
1776
+ : undefined;
1777
+ // Allowed the call, and nobody was asked. The ONE answer that allows
1778
+ // without claiming consent, and it is here so the panel's dialog can let a
1779
+ // small reversible commit past -- or let everything past when the person
1780
+ // has switched confirmations off -- without the record saying a person
1781
+ // said yes. `trail.approval` stays `not-asked`, which it already is, and
1782
+ // `policy` says there was a gate that chose not to ask. See `Approval`.
1783
+ if (shape?.asked === false) {
1784
+ // Nobody was asked, so there was no wait -- and `waitedMs` promises that
1785
+ // its absence means no question was open. The gate returned in no time
1786
+ // at all, which is indistinguishable from an instant answer by the
1787
+ // clock; `asked: false` is the one thing that tells them apart, so it is
1788
+ // what the field is cleared on.
1789
+ delete trail.waitedMs;
1790
+ return null;
1791
+ }
1792
+ trail.approval = shape?.timedOut === true ? "timed-out" : "declined";
1793
+ if (decision === false)
1794
+ return no(DECLINED, DECLINED_HINT, read());
1795
+ if (typeof decision === "string")
1796
+ return no(DECLINED, decision, read());
1797
+ if (shape?.timedOut === true) {
1798
+ return no(APPROVAL_TIMEOUT, (typeof shape.hint === "string" ? shape.hint : undefined) ??
1799
+ `\`${name}\` needed a person's approval and nobody answered. **The verb did not ` +
1800
+ `run and nothing changed** — this is not the relay's \`timeout\`, which means the ` +
1801
+ `outcome is unknown. Ask the person, then call it again.`, read());
1802
+ }
1803
+ // An answer the core does not recognise is a denial. Reading an unknown
1804
+ // shape as consent is how a refactor of a hook's return type silently
1805
+ // removes the gate, and the cost of being wrong the other way is one
1806
+ // refused commit.
1807
+ warn(`the \`approve\` hook answered with ${JSON.stringify(decision)}, which is not an ` +
1808
+ `approval. Treated as a refusal. Return true, false, a reason, ` +
1809
+ `{ timedOut: true }, or { asked: false }.`);
1810
+ return no(DECLINED, "the app's approval hook answered with something that is not a decision, so this was " +
1811
+ "not allowed. That is a bug in the app rather than in your call.", read());
1812
+ }
1813
+ /**
1814
+ * Put the agent's question to the person, and answer the agent honestly.
1815
+ *
1816
+ * THE FIVE THINGS THIS OWNS, none of which a verb body could:
1817
+ *
1818
+ * 1. **The lock.** `pending` is held for as long as the question is open, so
1819
+ * every other call on this driver -- from this agent or another one over
1820
+ * the relay -- is refused `approval-pending`. An agent that could carry
1821
+ * on acting while somebody is mid-decision is an agent acting on a screen
1822
+ * the person is about to change, and over the relay it is two agents, one
1823
+ * of which asked.
1824
+ * 2. **The deadline.** `MountOptions.askTimeout`, defaulting to 45 seconds,
1825
+ * which is under the relay's 60. That is what keeps "nobody answered" a
1826
+ * FACT rather than the relay's `timeout`, which means outcome unknown.
1827
+ * 3. **The allowance.** `budget.asks`, checked before the question is put
1828
+ * and charged only when it actually reached somebody.
1829
+ * 4. **The record.** `trail.waitedMs`, written on every exit, which is the
1830
+ * field that tells an auditor a question was genuinely put and for how
1831
+ * long it stood. See `AuditEvent`.
1832
+ * 5. **Keeping nothing.** The answer is turned into this call's `Result` and
1833
+ * is not stored anywhere. That is the whole of "a question is not
1834
+ * consent": there is no remembered yes for a later commit to consult, so
1835
+ * the separation is structural rather than a policy somebody could
1836
+ * relax. `ApprovalRequest` has no field that could carry one.
1837
+ *
1838
+ * It is called from `decide` rather than from `run` because four of those
1839
+ * five are things `call()` owns, and because the fifth is only true if the
1840
+ * answer never leaves this function.
1841
+ */
1842
+ async function putQuestion(args, before, trail) {
1843
+ const question = String(args[ASK_QUESTION_ARG] ?? "").trim();
1844
+ // An empty question after trimming. `checkArg` has already refused a
1845
+ // missing or non-string one, so what is left is whitespace -- which would
1846
+ // put a blank box in front of somebody and is the one argument error worth
1847
+ // catching here rather than passing on.
1848
+ if (question === "") {
1849
+ return no("bad-argument", `\`${ASK_QUESTION_ARG}\` is blank. Ask something: the person sees this text and ` +
1850
+ `nothing else, so a blank question is a box they cannot answer.`, before);
1851
+ }
1852
+ // Bounded, and refused rather than truncated. `SIZE_LIMITS.describe` is the
1853
+ // library's one-line budget and a question is a one-line thing; truncating
1854
+ // would put half a question in front of somebody, which reads as the whole
1855
+ // of a different question. An agent that needs a paragraph has not worked
1856
+ // out what it does not know.
1857
+ if (question.length > SIZE_LIMITS.describe) {
1858
+ return no("bad-argument", `that question is ${question.length} characters and the limit is ` +
1859
+ `${SIZE_LIMITS.describe}. Ask the narrowest question that unblocks you, in one ` +
1860
+ `line: a wall of text in front of somebody is a question they will dismiss. Say ` +
1861
+ `the rest in your final answer.`, before);
1862
+ }
1863
+ // The allowance, BEFORE the question is put and before the lock is taken.
1864
+ // The order matters for the same reason the commit ceiling sits one line
1865
+ // above the approval gate: nobody is interrupted for a call that was
1866
+ // already going to be refused.
1867
+ if (budget?.asks !== undefined && asksUsed >= budget.asks) {
1868
+ return no(ASKS_SPENT, `this app allows ${budget.asks} question${budget.asks === 1 ? "" : "s"} per mounted ` +
1869
+ `session and all ${budget.asks} have been asked, so this one was not put to ` +
1870
+ `anybody. It does not refill, and no further question will reach them. **The rest ` +
1871
+ `of the app still works**: this is a ceiling on the person's attention, not on ` +
1872
+ `your calls. Carry on with what you can decide, and in your final answer say ` +
1873
+ `exactly what you would have asked and what you could not settle without it.`, before);
1874
+ }
1875
+ const was = pending;
1876
+ pending = { verb: ASK, question: true };
1877
+ // Read only when a record is going to be built, the promise `call` and
1878
+ // `askApproval` both already make: an app with no `onAudit` reads no clock.
1879
+ const askedAt = onAudit === undefined ? 0 : Date.now();
1880
+ let answer;
1881
+ try {
1882
+ answer = await askDeadline(askFn({ question }), options.askTimeout);
1883
+ }
1884
+ catch (err) {
1885
+ // A question UI that throws must not take the app down, and must not be
1886
+ // read as an answer. The precedent is `ApprovalHook`, where a failed ask
1887
+ // is a no; here a failed ask is an UNANSWERED question and emphatically
1888
+ // not `nobody-to-ask` -- a broken panel is not evidence that nobody is
1889
+ // sitting there, and saying it is would tell an agent to stop asking for
1890
+ // the rest of the run over one exception. The message is folded in
1891
+ // because the author reading the transcript is the one who can fix it.
1892
+ answer = { answered: false };
1893
+ warn(`the \`ask\` hook threw, so the question was treated as unanswered: ` +
1894
+ `${err instanceof Error ? err.message : String(err)}. A failed ask is an ` +
1895
+ `unanswered question, never an answer and never a claim that nobody is there.`);
1896
+ }
1897
+ finally {
1898
+ pending = was;
1899
+ // In the `finally`, so EVERY exit is timed -- an answer, a silence, a
1900
+ // deadline, a hook that threw. A question somebody read for two minutes
1901
+ // and then ignored is exactly as interesting to an auditor as one they
1902
+ // answered, and a figure recorded only on the happy path vanishes from
1903
+ // the records somebody is most likely to be reading. The one exit that
1904
+ // deliberately does NOT get a figure is `{ nobody: true }`, below: see
1905
+ // `AuditEvent`, where the presence of `waitedMs` is what says a question
1906
+ // reached somebody.
1907
+ if (onAudit !== undefined)
1908
+ trail.waitedMs = Math.max(0, Date.now() - askedAt);
1909
+ }
1910
+ const shape = typeof answer === "object" && answer !== null
1911
+ ? answer
1912
+ : undefined;
1913
+ // Nobody is there. The question was never put, so nothing is charged and
1914
+ // the record carries no wait: both of those are the honest reading, and
1915
+ // both are what tell this apart from a question that stood in front of
1916
+ // somebody for 45 seconds.
1917
+ if (shape?.nobody === true) {
1918
+ delete trail.waitedMs;
1919
+ return no(NOBODY_TO_ASK, "there is nobody to ask on this run: this app is being driven with no person in " +
1920
+ "front of it. The question was not put to anybody, nothing in the app changed, " +
1921
+ "and no later question will reach them either — so stop asking. Decide from what " +
1922
+ "you already know if you honestly can, and if you cannot, say what you needed to " +
1923
+ "know and what you could not settle without it.", before);
1924
+ }
1925
+ // Charged here and nowhere else: the question reached somebody, whether or
1926
+ // not they answered. A question that sat in front of a person and was
1927
+ // ignored has spent their attention as surely as one they replied to, and a
1928
+ // counter that only counted replies would never fire on the agent that
1929
+ // interrupts somebody who has stopped reading it.
1930
+ asksUsed++;
1931
+ rememberSpend();
1932
+ if (typeof answer === "string" && answer.trim() !== "") {
1933
+ // THE ANSWER IS THE RESULT, which is the one structural thing about this
1934
+ // feature worth saying twice. It rides in `Report.note`, so it renders
1935
+ // through `ok — …` exactly as every other verb's note does and no
1936
+ // renderer in either language needed a line for it. A side channel --
1937
+ // another field on `Result`, a block in the snapshot -- would have been a
1938
+ // second place a model has to learn to look, and would have put a
1939
+ // person's words somewhere this core could keep them.
1940
+ //
1941
+ // Attributed, because `ok — yes, the one at Acme` is indistinguishable
1942
+ // from the app reporting something. The quotes and the words "the person
1943
+ // answered" are the core saying whose sentence this is, and they are the
1944
+ // core's words rather than the app's for the reason `ASK_DESCRIBE` is
1945
+ // here: a sentence written twice in two languages is a sentence that
1946
+ // drifts.
1947
+ //
1948
+ // The answer itself is passed through verbatim and never parsed. Nothing
1949
+ // in here looks for "yes": a core that classified an answer would be one
1950
+ // step from a core that acted on the classification, which is the
1951
+ // approval bypass this whole design is shaped against.
1952
+ const said = answer.trim();
1953
+ return {
1954
+ ok: true,
1955
+ note: `the person answered: "${said}"`,
1956
+ snapshot: read(),
1957
+ };
1958
+ }
1959
+ // Everything else is an unanswered question, including an answer shape this
1960
+ // core does not recognise and an empty string. The same rule `Approval`
1961
+ // applies to an unknown shape, pointed the other way: there the safe
1962
+ // reading of a shape nobody recognises is a DENIAL, and here it is that
1963
+ // nobody spoke. Reading it as an answer would put words in a person's mouth
1964
+ // and let a model act on them, which is strictly the worse of the two
1965
+ // mistakes.
1966
+ if (shape?.answered !== false) {
1967
+ warn(`the \`ask\` hook answered with ${JSON.stringify(answer)}, which is not an answer. ` +
1968
+ `Treated as unanswered. Return the person's words as a string, ` +
1969
+ `{ answered: false }, or { nobody: true }.`);
1970
+ }
1971
+ return no(ASK_UNANSWERED, "the question was put to the person and no answer came back — they closed it, walked " +
1972
+ "away, or it stood too long. **Nothing in the app changed and the verb did not " +
1973
+ "run**; this is not the transport `timeout`, where nobody knows what happened. Do " +
1974
+ "not invent an answer and do not act on what you were going to ask about. You may " +
1975
+ "ask once more, shorter, if it is genuinely the one thing in the way; otherwise say " +
1976
+ "what you needed to know and stop.", before);
1977
+ }
1978
+ /**
1979
+ * Hand one record to the app's hook, and survive the hook.
1980
+ *
1981
+ * NOT AWAITED, and not deadlined. See `MountOptions.onAudit`: an approval is
1982
+ * asked before the decision and its answer IS the decision, so it has to be
1983
+ * waited for; a record is emitted after the outcome is settled and, for a
1984
+ * commit, after the data has moved, so waiting on the sink can only delay the
1985
+ * agent and failing the call would make a broken logging backend into a
1986
+ * broken app. A thrown error — synchronous or from the promise — is reported
1987
+ * once rather than swallowed, because a record that vanished in silence is
1988
+ * the one failure an audit trail cannot survive.
1989
+ */
1990
+ function record(name, args, opts, trail, result, started) {
1991
+ // The DECLARED facts, from the manifest entry, exactly as the approval hook
1992
+ // is handed them: a record of what the app claimed about this verb, and no
1993
+ // reach into `run`.
1994
+ const entry = entries.get(name);
1995
+ const shown = {};
1996
+ const redacted = [];
1997
+ for (const [key, value] of Object.entries(args)) {
1998
+ // Declared `sensitive`, so the value is replaced HERE -- before the hook,
1999
+ // which is the boundary a record is most likely to leave the box
2000
+ // across -- and the field is named, so `"[redacted]"` can never be read
2001
+ // as a string the agent actually sent. See `ArgSpec.sensitive`.
2002
+ if (entry?.args?.[key]?.sensitive === true) {
2003
+ shown[key] = REDACTED;
2004
+ redacted.push(key);
2005
+ }
2006
+ else {
2007
+ shown[key] = value;
2008
+ }
2009
+ }
2010
+ const at = Date.now();
2011
+ const event = {
2012
+ at,
2013
+ ms: at - started,
2014
+ // Approval-inclusive `ms`, and the human share of it beside rather than
2015
+ // taken out of it. See `AuditEvent.waitedMs`: "41 seconds, 38 of them
2016
+ // waiting" answers both questions an auditor has and the sum alone
2017
+ // answers neither.
2018
+ ...(trail.waitedMs === undefined ? {} : { waitedMs: trail.waitedMs }),
2019
+ app: options.app,
2020
+ verb: name,
2021
+ args: shown,
2022
+ // The rev the call ran against, falling back to the one in the result's
2023
+ // own snapshot for the three refusals that answer before `visible()` is
2024
+ // read for comparison -- unmounted, approval-pending, unknown-verb. For
2025
+ // those the two are the same read, so this is not a guess.
2026
+ rev: trail.rev ?? result.snapshot.rev,
2027
+ ok: result.ok,
2028
+ approval: trail.approval,
2029
+ // Read now, not captured at mount: a page that acquires a gate halfway
2030
+ // through its life has records on both sides of that, and both are true.
2031
+ policy: policyNow(),
2032
+ };
2033
+ const screen = trail.screen ?? result.snapshot.screen;
2034
+ if (screen !== undefined)
2035
+ event.screen = screen;
2036
+ if (entry?.kind !== undefined)
2037
+ event.kind = entry.kind;
2038
+ if (entry?.reversible !== undefined)
2039
+ event.reversible = entry.reversible;
2040
+ if (redacted.length > 0)
2041
+ event.redacted = redacted;
2042
+ if (opts.rev !== undefined || opts.screen !== undefined) {
2043
+ event.claimed = {
2044
+ ...(opts.rev === undefined ? {} : { rev: opts.rev }),
2045
+ ...(opts.screen === undefined ? {} : { screen: opts.screen }),
2046
+ };
2047
+ }
2048
+ if (result.ok) {
2049
+ if (result.count !== undefined)
2050
+ event.count = result.count;
2051
+ }
2052
+ else {
2053
+ event.refused = result.refused;
2054
+ }
2055
+ if (trail.plan !== undefined)
2056
+ event.plan = trail.plan;
2057
+ if (trail.minted !== undefined)
2058
+ event.minted = trail.minted;
2059
+ try {
2060
+ const answered = onAudit(event);
2061
+ if (answered !== undefined && typeof answered.then === "function") {
2062
+ void answered.catch((err) => audited(name, err));
2063
+ }
2064
+ }
2065
+ catch (err) {
2066
+ audited(name, err);
2067
+ }
2068
+ }
2069
+ /** Said out loud, once per distinct message, when a record did not get out. */
2070
+ function audited(name, err) {
2071
+ warn(`the \`onAudit\` hook threw on \`${name}\`, so that call's audit record was lost: ` +
2072
+ `${err instanceof Error ? err.message : String(err)}. The call itself was unaffected — ` +
2073
+ `a record is emitted after the outcome is decided, so there is nothing left to refuse — ` +
2074
+ `but a record that vanishes in silence is the one failure an audit trail cannot survive.`);
2075
+ }
2076
+ /**
2077
+ * `decide`, and then the record of what it decided.
2078
+ *
2079
+ * The split is what makes the record impossible to disagree with the
2080
+ * `Result`: there is one `Result` object, `decide` produced it at whichever
2081
+ * of its dozen exits applied, and the event is built from THAT object rather
2082
+ * than from a second look at the app. A per-exit emit would have been a dozen
2083
+ * places to forget one.
2084
+ *
2085
+ * With no hook this is the function it was before audit existed, plus one
2086
+ * object literal and one comparison: no clock is read and no record is built.
2087
+ */
2088
+ async function call(name, args = {}, opts = {}) {
2089
+ const trail = { approval: "not-asked" };
2090
+ const started = onAudit === undefined ? 0 : Date.now();
2091
+ const result = await decide(name, args, opts, trail);
2092
+ if (onAudit !== undefined)
2093
+ record(name, args, opts, trail, result, started);
2094
+ return result;
2095
+ }
2096
+ async function decide(name, args, opts, trail) {
2097
+ if (!live)
2098
+ return no("unmounted", "this driver was unmounted", read());
2099
+ // BEFORE the verb is even looked up, and that order is the point. This is
2100
+ // not a fact about the call, it is a fact about the app: somebody is being
2101
+ // asked a question and nothing else runs until they answer. Checking it
2102
+ // after the lookup would answer `unknown-verb` to a call made during an
2103
+ // approval, which is a true statement about the wrong thing.
2104
+ //
2105
+ // It is also what makes point 4 structural rather than hopeful: the second
2106
+ // call for a verb whose approval is open cannot race the dialog, because
2107
+ // it is refused here — including when it is the same verb, and including
2108
+ // when it is the gate's own Approve button arriving as a `press`.
2109
+ if (pending !== null) {
2110
+ // One slug for both kinds of open question, and a different sentence.
2111
+ //
2112
+ // The slug is `approval-pending` either way because to the AGENT the two
2113
+ // are the same fact and call for the same move: nothing ran, somebody is
2114
+ // being asked something, wait. A second slug would be a second word for
2115
+ // one repair, which is what `RESERVED_REFUSALS` keeps refusing to add.
2116
+ //
2117
+ // The hint differs because the two are not the same thing to the PERSON
2118
+ // reading a transcript, and because the hazard the approval wording
2119
+ // exists for -- an agent pressing the Approve button of the dialog that
2120
+ // is asking it -- is not what a question is about. An agent told
2121
+ // "`accept-selected` is waiting to be approved" while what is actually
2122
+ // on screen is "which Ada Duarte did you mean?" has been told something
2123
+ // false about its own app.
2124
+ return no(APPROVAL_PENDING, pending.question
2125
+ ? `this app has put a question of yours to the person and is waiting for their ` +
2126
+ `answer, so it is not taking calls. Nothing ran. Wait for the answer: it comes ` +
2127
+ `back as the result of the \`${ASK}\` call you already made, and asking again ` +
2128
+ `will not reach them any sooner.`
2129
+ : `\`${pending.verb}\` is waiting to be approved, so ${PENDING_HINT}`, read());
2130
+ }
2131
+ // AFTER the approval lock and BEFORE the verb lookup, and both halves of
2132
+ // that position are decisions.
2133
+ //
2134
+ // After the lock, because a call refused `approval-pending` reached nothing
2135
+ // and must not be charged for: a confused agent polling while a person
2136
+ // reads a dialog would otherwise eat the whole ceiling without a single
2137
+ // verb running, and the ceiling is for spend, not for impatience.
2138
+ //
2139
+ // Before the lookup, because a spent budget is the widest true thing there
2140
+ // is to say about this call. Every other check in here answers "this
2141
+ // particular call is wrong, here is the repair"; this one answers "nothing
2142
+ // will work again, and no repair exists at this end". Answering
2143
+ // `unknown-verb` to a call made past the ceiling would send an agent off to
2144
+ // find a verb name that was never the problem — which is the same ordering
2145
+ // argument `wrong-screen` is above `stale` for, taken one step further out.
2146
+ //
2147
+ // Charged for whatever happens next, refusals included. See `Budget`: an
2148
+ // agent looping on `bad-argument` is the runaway this field exists for, and
2149
+ // a counter that only counted successful calls would watch it spin.
2150
+ // Before the counter comparison, because when the ceiling cannot be
2151
+ // accounted for there is no counter worth comparing. Same slug as a spent
2152
+ // ceiling on purpose: to the agent the two are the same fact — nothing more
2153
+ // will run here and no repair exists at this end — and `drive` already
2154
+ // treats `budget-spent` as an ending rather than as a mistake to retry.
2155
+ // The hint is what differs, and it is the hint a human reads.
2156
+ // What the other tabs have spent, before this tab decides it has room. See
2157
+ // `syncSpend`: without this, two tabs open at once are two ceilings.
2158
+ syncSpend();
2159
+ if (budgetBroken !== null) {
2160
+ return no(BUDGET_SPENT, budgetBroken, read());
2161
+ }
2162
+ if (budget?.calls !== undefined && callsUsed >= budget.calls) {
2163
+ return no(BUDGET_SPENT, `this app allows ${budget.calls} verb call${budget.calls === 1 ? "" : "s"} per mounted ` +
2164
+ `session and all ${budget.calls} are spent, so \`${name}\` was not run. This is a ` +
2165
+ `ceiling the app set, not a rate limit: it does not refill, and waiting or retrying ` +
2166
+ `will not change it. Stop, and say what you had got through and what is left — ` +
2167
+ `somebody has to decide whether to raise it.`, read());
2168
+ }
2169
+ callsUsed++;
2170
+ rememberSpend();
2171
+ const verb = verbs.get(name);
2172
+ if (!verb) {
2173
+ // The known names are listed. An outside agent may be holding a manifest
2174
+ // from a previous version of the app, and the list is how it finds out
2175
+ // what moved without a second round trip.
2176
+ const known = [...verbs.keys()].sort().join(", ");
2177
+ return no("unknown-verb", `no verb named \`${name}\`. known: ${known}`, read());
2178
+ }
2179
+ const before = read();
2180
+ // Written down HERE, at the one read every check below compares against, so
2181
+ // the record says what the call ran against and not what the screen looked
2182
+ // like afterwards. On a successful bulk commit those are different revs,
2183
+ // and the one worth keeping is this one: it is the rev the count was taken
2184
+ // at and the rev a person approved.
2185
+ trail.rev = before.rev;
2186
+ if (before.screen !== undefined)
2187
+ trail.screen = before.screen;
2188
+ // Read HERE and kept, because the carry below needs it and the `read()`
2189
+ // that produces `after` is where a lapsed notice is cleared. A read-only
2190
+ // move clears the notice as a side effect -- a known weakness of `rev`,
2191
+ // documented on `MountOptions.elsewhere` -- so asking afterwards would
2192
+ // always answer no, and a plan would be carried across a navigation in a
2193
+ // tab the core had just been told was behind. See the carry.
2194
+ const behind = elsewhere !== null;
2195
+ // WHICH SCREEN comes before WHICH REV, which comes before the arguments.
2196
+ // Each check describes a wider mistake than the next, and the widest one is
2197
+ // the useful answer: if the agent is not on the screen it thinks it is,
2198
+ // then the rev and the arguments both describe something it never saw, and
2199
+ // answering "the number moved" sends it to re-read a screen when what it
2200
+ // needs is to navigate back. A `next-page` that lands on another company's
2201
+ // contact list and answers `ok` is the live bug this ordering exists to
2202
+ // make impossible.
2203
+ //
2204
+ // Both screen checks are skipped when the app does not fill in
2205
+ // `Snapshot.screen`. There is nothing to compare against, and inventing a
2206
+ // comparison -- treating absent as "not that one" -- would refuse every
2207
+ // screen-scoped verb in an app that simply has not adopted the field.
2208
+ if (opts.screen !== undefined && before.screen !== undefined && opts.screen !== before.screen) {
2209
+ return no(WRONG_SCREEN, `you believed you were on the \`${opts.screen}\` screen but the app is on ` +
2210
+ `\`${before.screen}\`; read the screen again before acting on it`, before);
2211
+ }
2212
+ if (verb.screen !== undefined) {
2213
+ const wants = screensOf(verb.screen);
2214
+ if (before.screen === undefined) {
2215
+ // Said once, not refused. The app declared a verb→screen mapping and no
2216
+ // live screen, so the check it asked for cannot run -- which is a
2217
+ // mistake in the app rather than in the call, and refusing a verb an
2218
+ // author believes they scoped correctly would break a working app over
2219
+ // a missing field. See `warn`.
2220
+ warn(`the verb \`${name}\` names ${wants.length > 1 ? "the screens" : "the screen"} ` +
2221
+ `${naming(wants)} but \`visible()\` returns no \`screen\`, so the check cannot run. ` +
2222
+ `Fill in \`Snapshot.screen\` with the id of the screen that is live, or drop ` +
2223
+ `\`screen\` from the verb.`);
2224
+ }
2225
+ else if (!wants.includes(before.screen)) {
2226
+ // ALL the screens are named, the live one and every one the verb works
2227
+ // on. `wrong-screen` on its own is a dead end: an agent that is told no
2228
+ // and not told where to go has to guess, and the guess is another
2229
+ // refused call. Naming only one of several would be a subtler version
2230
+ // of the same dead end -- it would send an agent to the contacts list
2231
+ // when the company screen it is two clicks from would have done. The
2232
+ // verb that navigates is the app's and cannot be named from here, which
2233
+ // is what `Manifest.instructions` is for.
2234
+ return no(WRONG_SCREEN, `you are on the \`${before.screen}\` screen; \`${name}\` works on the ` +
2235
+ `${naming(wants)} ${wants.length > 1 ? "screens" : "screen"}. Go ` +
2236
+ `${wants.length > 1 ? "to one of those" : "there"} first, then call it again.`, before);
2237
+ }
2238
+ }
2239
+ // WHAT ANOTHER TAB DID comes after WHICH SCREEN and above every staleness
2240
+ // check, including `stale-plan`, and the ladder's own rule is why.
2241
+ //
2242
+ // The ladder is widest first, because the widest answer's repair subsumes
2243
+ // the narrower ones'. This is the widest staleness there is: `stale` says
2244
+ // the rev moved, `stale-plan` says the selection moved, and both are
2245
+ // repaired by reading this tab again -- which is exactly the repair that
2246
+ // DOES NOT WORK here, because what moved is the data behind a tab whose
2247
+ // `rev` is unchanged. Answering `stale` or `stale-plan` first would hand an
2248
+ // agent a repair that appears to succeed and leaves it believing it is
2249
+ // current: it reads again, gets the same rev, and commits. That is the
2250
+ // silent failure this check exists to end, so it has to be answered before
2251
+ // either of them.
2252
+ //
2253
+ // ONLY A `commit`, and that is the one real judgement in here. A `read` or
2254
+ // a `describe` in a tab that is behind still returns the rows the person is
2255
+ // actually looking at, and its snapshot now says in words that they may be
2256
+ // behind -- see `read()`. Refusing those as well would make a tab whose app
2257
+ // does not refetch completely undrivable, and would do it by sending an
2258
+ // agent round a loop: refused, read again, same rev, refused. A commit is
2259
+ // the one call whose cost is not paid back by reading again, which is the
2260
+ // same line `MountOptions.approve` draws for the same reason.
2261
+ //
2262
+ // WHATEVER `rev` THE AGENT CLAIMED, including none. `rev` and `screen` are
2263
+ // checks an agent opts out of by making no claim, because an agent that
2264
+ // claims nothing has at least not claimed something false. This is not of
2265
+ // that kind: it is not a claim being checked, it is the core knowing the
2266
+ // data moved. `consumes: "plan"` already makes the same exception for the
2267
+ // same reason -- a guarantee a caller can decline is not a guarantee.
2268
+ // `before` was produced by `read()` above, which is where a notice whose rev
2269
+ // has moved on is cleared. So a non-null `elsewhere` here has already been
2270
+ // checked against the live rev, and calling `read()` again in this
2271
+ // condition would be asking the question that answers itself -- and would
2272
+ // null the field between the two halves of the `&&`.
2273
+ if (verb.kind === "commit" && elsewhere !== null) {
2274
+ return no(CHANGED_ELSEWHERE, `another tab of this app committed \`${elsewhere.verb}\` after this screen was read. ` +
2275
+ `This tab is at rev ${elsewhere.at} and has not moved, so its rows -- and any count ` +
2276
+ `taken from them -- may describe data that has already changed. Reading this screen ` +
2277
+ `again will NOT fix that: the rev will be the same and it will still be behind. ` +
2278
+ `Say what happened and let the person refresh the page or switch to the tab that ` +
2279
+ `made the change; do not retry this commit here.`, before);
2280
+ }
2281
+ // WHICH SELECTION comes after WHICH SCREEN and BEFORE WHICH REV, and this
2282
+ // is the one ordering decision in `call()` that is not obvious, so here is
2283
+ // the argument.
2284
+ //
2285
+ // The ladder is by how WIDE the mistake is, widest first, because the
2286
+ // widest answer is the one whose repair subsumes the others'. A wrong
2287
+ // screen is still the widest: a plan taken on another screen is a claim
2288
+ // about a selection the agent was never looking at, so there is nothing
2289
+ // useful to say about it until it is standing in the right place.
2290
+ //
2291
+ // But `stale-plan` is WIDER than `stale`, and that is why it goes above it
2292
+ // rather than below. The two overlap on everything that moves the
2293
+ // selection -- and where they do, the repairs are not the same size.
2294
+ //
2295
+ // They are no longer nested the way this comment once claimed. A read-only
2296
+ // move is `stale` and is NOT `stale-plan`: the screen the agent echoed is
2297
+ // not the screen on display, and the selection it counted is still the
2298
+ // selection, so the narrower answer is the true one and it is the one that
2299
+ // comes back. See `plansGoodAt`. The ordering is unchanged, because where
2300
+ // both apply the plan is still the wider mistake. `stale` says "read
2301
+ // again", and an
2302
+ // agent that reads again and carries on is the agent that accepts 3,418
2303
+ // rows after a person approved 3,412. `stale-plan` says "run the describe
2304
+ // again, read the new count, check it, then commit", which is the repair
2305
+ // that actually fixes a moved selection. Answering the narrower one first
2306
+ // would hand back the cheaper instruction for the more expensive mistake.
2307
+ //
2308
+ // It is also before the argument check for the reason `rev` is: a commit
2309
+ // whose selection has moved is not a commit whose arguments are worth
2310
+ // discussing. And it is before the approval gate, which is last, so nobody
2311
+ // is ever asked to approve a commit that was already going to be refused.
2312
+ if (verb.consumes === "plan") {
2313
+ // Recorded BEFORE the check and whatever the check says. A token that was
2314
+ // refused is the interesting one: it is how an audit reader finds the
2315
+ // agent that tried to spend a receipt for a count that had moved.
2316
+ if (opts.plan !== undefined && opts.plan !== "")
2317
+ trail.plan = opts.plan;
2318
+ const stale = checkPlan(name, opts.plan, before);
2319
+ if (stale)
2320
+ return no(STALE_PLAN, stale, before);
2321
+ }
2322
+ // Staleness is checked BEFORE arguments, and that order is deliberate. If
2323
+ // the screen has moved on, the arguments describe a row the agent never
2324
+ // saw, so complaining about their shape would be answering the wrong
2325
+ // question -- and the fix is the same either way: read again.
2326
+ if (opts.rev !== undefined && opts.rev !== before.rev) {
2327
+ return no("stale", `you acted on rev ${opts.rev} but the screen is at rev ${before.rev}; read again`, before);
2328
+ }
2329
+ if (verb.args) {
2330
+ for (const [argName, spec] of Object.entries(verb.args)) {
2331
+ const reason = checkArg(argName, spec, args[argName]);
2332
+ if (reason)
2333
+ return no("bad-argument", reason, before);
2334
+ }
2335
+ }
2336
+ // THE QUESTION, and it is answered here rather than by `verb.run` below.
2337
+ //
2338
+ // After the argument check, so a question with no text is `bad-argument`
2339
+ // like every other malformed call. Before the commit ceiling and the
2340
+ // approval gate, which cannot apply: an `ask` is not a `commit`, and that
2341
+ // is the first of the several reasons an answer cannot be consent.
2342
+ //
2343
+ // `verb === coreAsk` is an IDENTITY check and not a name check, because the
2344
+ // name is the one thing an app is allowed to take -- an app with its own
2345
+ // verb called `ask` falls straight through to `run` and is an ordinary
2346
+ // verb, which is what the warning at mount says out loud.
2347
+ if (coreAsk !== undefined && verb === coreAsk) {
2348
+ return await putQuestion(args, before, trail);
2349
+ }
2350
+ // LAST of the checks and immediately before `run`, which is the only place
2351
+ // it can go. Asking a person about a call that is about to be refused for
2352
+ // a stale rev, a wrong screen or a missing argument is asking them to
2353
+ // approve something that was never going to happen — and the second time
2354
+ // that happens they stop reading the question.
2355
+ //
2356
+ // The commit ceiling is checked HERE, one line above the gate, and the
2357
+ // order is the gate's own argument reused: nobody is asked to approve a
2358
+ // commit that was already going to be refused. It is also the last check
2359
+ // before `run`, which is where a bound on data moved belongs — a commit
2360
+ // refused for a stale plan did not move anything and must not be charged
2361
+ // for one.
2362
+ if (verb.kind === "commit" && budget?.commits !== undefined && commitsUsed >= budget.commits) {
2363
+ return no(BUDGET_SPENT, `this app allows ${budget.commits} commit${budget.commits === 1 ? "" : "s"} per mounted ` +
2364
+ `session and all ${budget.commits} have run, so \`${name}\` was not run and no data ` +
2365
+ `moved. Reads and describes may still work; it is commits that are spent. This ` +
2366
+ `ceiling does not refill — stop, and say which commits went through.`, before);
2367
+ }
2368
+ // The app's own hook if it declared one, otherwise whatever the page
2369
+ // installed through `adopt`, otherwise nothing. Read HERE and not at
2370
+ // mount, because a panel can be mounted after the driver is and the
2371
+ // commits that arrive after it must go through it -- that is the whole of
2372
+ // what adoption buys, and a captured `const` would have made the first
2373
+ // page load the only one that counted.
2374
+ const approver = approveFn ?? adopted;
2375
+ if (verb.kind === "commit" && approver !== undefined) {
2376
+ const refused = await askApproval(approver, name, args, before, trail);
2377
+ if (refused)
2378
+ return refused;
2379
+ }
2380
+ // Charged on ENTERING `run`, beside the plan token and for the same reason:
2381
+ // a commit that changes half a selection and then throws has moved data,
2382
+ // and a counter that only counted clean returns would not know it.
2383
+ if (verb.kind === "commit") {
2384
+ commitsUsed++;
2385
+ rememberSpend();
2386
+ }
2387
+ // Burned HERE, between the last check and `run`, and the position is the
2388
+ // decision rather than an accident of where it fitted.
2389
+ //
2390
+ // A plan is single-use. Terraform's model is a saved plan that performs
2391
+ // exactly the steps it holds, and replaying one that has already been
2392
+ // applied is the double-apply; here it is the double-accept, which is the
2393
+ // single most expensive thing an agent can do with a bulk verb. The count
2394
+ // was shown once and approved once, so it buys one commit.
2395
+ //
2396
+ // Burned on ENTERING `run` rather than on a successful return, so a verb
2397
+ // that changes half a selection and then throws cannot have its token
2398
+ // re-presented. And burned AFTER the approval gate, not before, so a commit
2399
+ // that a person declined -- or that lapsed with nobody answering -- leaves
2400
+ // the token alive: nothing moved, the count is still the count, and making
2401
+ // somebody re-run the describe because they hesitated is how a gate teaches
2402
+ // people to stop reading it.
2403
+ if (verb.consumes === "plan" && opts.plan !== undefined) {
2404
+ const spent = plans.get(opts.plan);
2405
+ if (spent)
2406
+ spent.used = true;
2407
+ }
2408
+ let outcome;
2409
+ try {
2410
+ outcome = await verb.run(args, ctx);
2411
+ }
2412
+ catch (err) {
2413
+ // Announced, because a commit that threw may have moved half a selection
2414
+ // -- the same reason the plan token is burned on entering `run`. The
2415
+ // other tabs are told something changed and the agent is told the call
2416
+ // failed, and both of those are true at once.
2417
+ if (verb.kind === "commit")
2418
+ announce(name);
2419
+ // An app bug is reported as a failed call rather than allowed to
2420
+ // propagate. The alternative kills the websocket pump in the relay, and
2421
+ // a driver that dies on one bad verb takes every other verb with it.
2422
+ return no("threw", `the verb \`${name}\` threw: ${err instanceof Error ? err.message : String(err)}`, read());
2423
+ }
2424
+ if (isRefusal(outcome)) {
2425
+ if (RESERVED.has(outcome.reason)) {
2426
+ // Reported as `threw` rather than passed through, and rather than
2427
+ // raised. Passing it through is the bug: the agent now reads `timeout`
2428
+ // from a call that landed and answered, and the reserved list stops
2429
+ // meaning anything. Raising would be worse — this is reached only while
2430
+ // a working app is saying no, and killing the run over a slug turns a
2431
+ // declined commit into a dead panel. `threw` is already the core's word
2432
+ // for "the app's own code is broken", which is exactly what this is,
2433
+ // and it leaves the reserved slugs saying only what they are for.
2434
+ warn(`the verb \`${name}\` refused with the reserved slug \`${outcome.reason}\`; ` +
2435
+ `reported as \`threw\`. Reserved: ${RESERVED_REFUSALS.join(", ")}.`);
2436
+ return no("threw", `the verb \`${name}\` refused with \`${outcome.reason}\`, which is a reserved slug and ` +
2437
+ `not an app refusal. This is a bug in the app, not something to retry differently.`, read());
2438
+ }
2439
+ // Declaring `refuses` opts the verb into the check; leaving it absent
2440
+ // makes no claim, the same way an absent `kind` makes no safety claim.
2441
+ // Warning on every app that never filled the field in would be a warning
2442
+ // on everything and therefore a warning on nothing.
2443
+ if (verb.refuses && !verb.refuses.includes(outcome.reason)) {
2444
+ warn(`the verb \`${name}\` refused with \`${outcome.reason}\`, which is not in its declared ` +
2445
+ `refuses [${verb.refuses.join(", ")}]. The manifest is the only description of this ` +
2446
+ `verb an agent gets, and an undeclared refusal is one it cannot plan around.`);
2447
+ }
2448
+ return no(outcome.reason, outcome.hint, read());
2449
+ }
2450
+ // Read again after running, not before: the point of returning a snapshot
2451
+ // is to show what the call did.
2452
+ //
2453
+ // `count` is forwarded with `?? undefined` rather than a truthiness check,
2454
+ // because a `describe` verb that matched nothing must report `0` and not
2455
+ // silently become "I do not count" — those are different answers, and the
2456
+ // difference decides whether a commit should follow.
2457
+ // Before `read()`, so the snapshot this call returns is the one the OTHER
2458
+ // tabs are being warned about -- and after the refusal branches above, so
2459
+ // an app that said no has announced nothing. A driver ignores its own
2460
+ // notice, so this does not annotate the result below.
2461
+ if (verb.kind === "commit")
2462
+ announce(name);
2463
+ const after = read();
2464
+ // THE CARRY. A read-only move does not spend a plan.
2465
+ //
2466
+ // `Snapshot.rev` answers two questions and only one of them is the plan's;
2467
+ // see `plansGoodAt` for the argument and for why this is gated on
2468
+ // `selectionId` rather than on a second counter. What is left here is the
2469
+ // list of conditions, each of which is the safe direction of one choice:
2470
+ //
2471
+ // - `usesPlans` and a non-empty map: nothing to carry otherwise, and an
2472
+ // app with no consuming verb must not grow a line of behaviour it never
2473
+ // asked for.
2474
+ // - `kind === "read"`, read from the DECLARATION. `describe` is excluded
2475
+ // because it is the kind that changes what is selected -- and one that
2476
+ // counted has just minted a fresh plan anyway, which retires this one.
2477
+ // `commit` is excluded because it is the thing a plan is a receipt
2478
+ // against. An absent `kind` is excluded because it makes no claim.
2479
+ // - `before.rev === plansGoodAt`: the plans were still good when this
2480
+ // verb STARTED. A `rev` that had already moved for some other reason --
2481
+ // a websocket between two calls -- has already killed them, and a read
2482
+ // must not resurrect a plan by walking past the rev that buried it.
2483
+ // - `after.rev !== before.rev`: there is a move to forgive at all.
2484
+ // - `!behind`: no `changed-elsewhere` notice stands. The notice says this
2485
+ // tab's data may be stale at a `rev` that has not moved, and carrying a
2486
+ // plan over a navigation that silently cleared it would turn one extra
2487
+ // describe into none.
2488
+ // - a defined `selectionId`, unchanged across the call. This is the whole
2489
+ // guarantee: the plan counted a selection, and the app is saying that
2490
+ // the selection is the same one. An app that publishes nothing here
2491
+ // carries nothing and keeps the behaviour it has always had, which is
2492
+ // the fail-safe an un-adopted app needs -- and the core already warns
2493
+ // that author once, at their first plan check.
2494
+ if (usesPlans &&
2495
+ verb.kind === "read" &&
2496
+ plans.size > 0 &&
2497
+ before.rev === plansGoodAt &&
2498
+ after.rev !== before.rev &&
2499
+ !behind &&
2500
+ after.selectionId !== undefined &&
2501
+ after.selectionId === plansSelection) {
2502
+ plansGoodAt = after.rev;
2503
+ }
2504
+ // The mint, and everything about when it happens is load-bearing.
2505
+ //
2506
+ // AFTER `run`, from the snapshot the call left behind, because the whole
2507
+ // claim is about the selection that now exists and not the one that did a
2508
+ // moment ago.
2509
+ //
2510
+ // Only on a `describe`, and only on one that reported a `count`. Those two
2511
+ // conditions are the same condition said twice: `describe` is the kind that
2512
+ // promises a pending count, and a `count` is the number a commit decision
2513
+ // turns on. A `read` leaves nothing pending and a `commit` has already
2514
+ // moved the data, so a token from either would be a receipt for a decision
2515
+ // nobody is about to make.
2516
+ //
2517
+ // Only in an app that has a verb consuming them, which is what keeps this
2518
+ // additive: every `describe` in every app written before this returns the
2519
+ // exact `Result` it returned before, with no `plan` field and no extra line
2520
+ // in anything that renders it.
2521
+ //
2522
+ // `count` is forwarded with `!== undefined` rather than a truthiness check,
2523
+ // because a `describe` verb that matched nothing must report `0` and not
2524
+ // silently become "I do not count" — those are different answers, and the
2525
+ // difference decides whether a commit should follow. A plan is minted for a
2526
+ // count of `0` for the same reason: "commit on nothing" is a decision an
2527
+ // agent can make, and it should be made against a receipt like any other.
2528
+ const counted = outcome && outcome.count !== undefined ? outcome.count : undefined;
2529
+ const plan = usesPlans && verb.kind === "describe" && counted !== undefined
2530
+ ? mint(name, after, counted)
2531
+ : undefined;
2532
+ // The other half of the join. The event carrying this as `minted` is the
2533
+ // one that reported the count; the event carrying the same string as `plan`
2534
+ // is the commit that spent it. Together they are the answer to "3,412 rows
2535
+ // were counted here, approved here, and moved here", which is the question
2536
+ // the whole record exists for and the one no single event can answer.
2537
+ if (plan !== undefined)
2538
+ trail.minted = plan;
2539
+ return {
2540
+ ok: true,
2541
+ ...(counted === undefined ? {} : { count: counted }),
2542
+ ...(outcome && outcome.note !== undefined ? { note: outcome.note } : {}),
2543
+ ...(plan === undefined ? {} : { plan }),
2544
+ snapshot: after,
2545
+ };
2546
+ }
2547
+ function no(refused, hint, snapshot) {
2548
+ return { ok: false, refused, ...(hint === undefined ? {} : { hint }), snapshot };
2549
+ }
2550
+ return {
2551
+ manifest: () => manifest,
2552
+ snapshot: read,
2553
+ call,
2554
+ approval: {
2555
+ // A getter, because this one moves: `none` before a panel mounts and
2556
+ // `adopted` after. A snapshotted value would have made every record on
2557
+ // the page agree with whichever answer was true when `mount()` returned.
2558
+ get policy() {
2559
+ return policyNow();
2560
+ },
2561
+ declared: declaredPolicy,
2562
+ /**
2563
+ * Hand the gate to a dialog in the page, if nobody else has it.
2564
+ *
2565
+ * `DriverApproval.adopt` carries the whole argument. What is here is the
2566
+ * order of the two refusals, and it is the order on purpose: an app that
2567
+ * declared anything wins silently, because `approve: (req) =>
2568
+ * panel.approve(req)` is the documented wiring and warning about the
2569
+ * recommended arrangement is how a library teaches people to ignore its
2570
+ * console. A SECOND adopter is told out loud, because that one is
2571
+ * somebody's mistake and the symptom -- a dialog appearing in the other
2572
+ * panel -- is otherwise unreadable.
2573
+ */
2574
+ adopt: (hook) => {
2575
+ if (typeof hook !== "function") {
2576
+ warn(`\`approval.adopt\` was handed ${JSON.stringify(hook)}, which is not a function, ` +
2577
+ `so nothing was installed and commits on this driver are gated by whatever ` +
2578
+ `\`approve\` the app declared.`);
2579
+ return null;
2580
+ }
2581
+ if (declared !== undefined)
2582
+ return null;
2583
+ if (adopted !== undefined) {
2584
+ warn(`a second approval dialog tried to adopt \`${options.app}\` and was refused: the ` +
2585
+ `first one keeps the gate, because two gates for one commit is two dialogs. ` +
2586
+ `Commits will be confirmed in whichever panel adopted first — including commits ` +
2587
+ `started from this one. Mount one panel per driver, or declare the gate yourself ` +
2588
+ `with \`approve\` so that every panel asks through it.`);
2589
+ return null;
2590
+ }
2591
+ const token = {};
2592
+ adopted = hook;
2593
+ adoptedBy = token;
2594
+ return () => {
2595
+ // Only its own. A disposer that fired late and unhooked whoever
2596
+ // adopted after it would leave the live panel's dialog silently
2597
+ // bypassed, which is this whole change running backwards.
2598
+ if (adoptedBy !== token)
2599
+ return;
2600
+ adopted = undefined;
2601
+ adoptedBy = undefined;
2602
+ };
2603
+ },
2604
+ // Offered whatever the policy is, including `"none"`. The widget's
2605
+ // in-page dialog is an approval UI on a driver that may well have
2606
+ // declared nothing, and it needs the lock exactly as much as the core's
2607
+ // own hook does: the agent it is asking is not the only agent that can
2608
+ // reach this driver.
2609
+ hold: async (verb, ask) => {
2610
+ const was = pending;
2611
+ // `question: false`: this is the lock for an approval UI, which is what
2612
+ // `hold` is documented as being for. The core's own question verb takes
2613
+ // the lock through `putQuestion`, which sets the other flag.
2614
+ pending = { verb, question: false };
2615
+ try {
2616
+ return await ask();
2617
+ }
2618
+ finally {
2619
+ pending = was;
2620
+ }
2621
+ },
2622
+ },
2623
+ // Offered whether or not a ceiling was declared, so a panel renders one
2624
+ // shape. A fresh object per read: handing out a live one would let a UI
2625
+ // mutate the app's own accounting.
2626
+ budget: () => ({
2627
+ calls: { used: callsUsed, ...(budget?.calls === undefined ? {} : { limit: budget.calls }) },
2628
+ commits: {
2629
+ used: commitsUsed,
2630
+ ...(budget?.commits === undefined ? {} : { limit: budget.commits }),
2631
+ },
2632
+ asks: { used: asksUsed, ...(budget?.asks === undefined ? {} : { limit: budget.asks }) },
2633
+ }),
2634
+ unmount: () => {
2635
+ live = false;
2636
+ // Before `live` could matter again: a channel implementation that holds a
2637
+ // `BroadcastChannel` open keeps this driver's listener -- and through the
2638
+ // closure, this driver -- alive for the life of the page.
2639
+ const stop = unlisten;
2640
+ unlisten = undefined;
2641
+ try {
2642
+ stop?.();
2643
+ }
2644
+ catch (err) {
2645
+ warn(`the \`elsewhere\` channel threw on unmount ` +
2646
+ `(${err instanceof Error ? err.message : String(err)}); the driver is unmounted ` +
2647
+ `either way.`);
2648
+ }
2649
+ },
2650
+ };
2651
+ }
2652
+ /**
2653
+ * `promise`, or `{ timedOut: true }` after `ms`.
2654
+ *
2655
+ * Absent or non-positive `ms` waits forever, which is `MountOptions.approvalTimeout`'s
2656
+ * documented default: a deadline that denies while somebody is still reading
2657
+ * the rows teaches them the dialog is a race. The timer is always cleared, so
2658
+ * a hook that answers in time does not hold a Node process open for the rest
2659
+ * of the deadline.
2660
+ */
2661
+ function deadline(promise, lapsed, ms) {
2662
+ if (ms === undefined || !(ms > 0))
2663
+ return Promise.resolve(promise);
2664
+ let timer;
2665
+ const lapse = new Promise((resolve) => {
2666
+ // Deliberately NOT unref'd, and that is not an oversight. `unref` says the
2667
+ // timer is not work worth staying alive for -- true right up until the hook
2668
+ // never answers. Then the timer is the ONLY pending thing, the event loop
2669
+ // concludes it has nothing to do, and the process tears down with the
2670
+ // deadline unfired: the one case this helper exists for. In a test runner
2671
+ // that surfaced as every later test in the file being CANCELLED rather than
2672
+ // failing, which is a far harder symptom to read than a held process.
2673
+ // `clearTimeout` in `finally` already buys what `unref` was reaching for.
2674
+ timer = setTimeout(() => resolve(lapsed), ms);
2675
+ });
2676
+ return Promise.race([Promise.resolve(promise), lapse]).finally(() => {
2677
+ if (timer !== undefined)
2678
+ clearTimeout(timer);
2679
+ });
2680
+ }
2681
+ /**
2682
+ * `promise`, or an unanswered question after `ms` -- **defaulting to 45
2683
+ * seconds, unlike the approval deadline above, which defaults to forever.**
2684
+ *
2685
+ * The same timer, a different default, and the inversion is the whole point of
2686
+ * this wrapper existing rather than the call site passing a number. Waiting
2687
+ * forever on an approval is right because a lapse there DENIES a commit while
2688
+ * somebody is still reading; waiting forever on a question is wrong twice over:
2689
+ * a lapse denies nothing, and a question that outlives the relay's 60-second
2690
+ * deadline turns "nobody answered" into the relay's `timeout`, which means
2691
+ * nobody knows. Of the two errors, firing late is the expensive one here.
2692
+ *
2693
+ * The lapse value is `{ answered: false }` and not a `timedOut` shape of its
2694
+ * own, because an agent has no use for the difference: a question nobody
2695
+ * answered inside the deadline and a question the app reported unanswered are
2696
+ * the same fact and the same repair. `AskAnswer` therefore has three values and
2697
+ * not four. A non-positive `ms` waits forever, for the app that is only ever
2698
+ * driven in-page.
2699
+ */
2700
+ function askDeadline(promise, ms) {
2701
+ return deadline(promise, { answered: false }, ms ?? DEFAULT_ASK_TIMEOUT_MS);
2702
+ }
2703
+ /**
2704
+ * A short, stable hash of the verb surface.
2705
+ *
2706
+ * Only the parts an agent can observe go in: names, descriptions, argument
2707
+ * shapes, refusals. Not `run`, because reimplementing a verb's body without
2708
+ * changing its interface must not invalidate anybody's cached manifest.
2709
+ *
2710
+ * Not cryptographic and does not need to be. It answers one question -- "is
2711
+ * the copy I cached still the current one" -- and a collision costs a stale
2712
+ * manifest, not a security property.
2713
+ */
2714
+ function fingerprint(app, verbs, instructions, screens, flows) {
2715
+ // `kind` is in here on purpose. A verb reclassified from `describe` to
2716
+ // `commit` has not changed its name or its arguments, so without this the
2717
+ // fingerprint would not move and every agent holding a cached manifest would
2718
+ // go on believing an irreversible verb is free to try.
2719
+ //
2720
+ // So is `at`, for the weaker but real version of the same reason: it is part
2721
+ // of what a cached manifest claims about the surface, and a UI holding the
2722
+ // old copy would outline an element the verb no longer touches.
2723
+ //
2724
+ // `screen` and `reversible` are in for the strong version of it. Moving a
2725
+ // verb to another screen changes where a cached copy says it works, and so
2726
+ // does GIVING IT A SECOND ONE -- a verb that now also works on a company's
2727
+ // contact list is a verb whose cached description was wrong about where it
2728
+ // can be called. Dropping `reversible` from a commit changes whether an agent
2729
+ // was told there is a way back -- which is the same class of mistake as a
2730
+ // reclassified `kind`.
2731
+ //
2732
+ // The DECLARED shape is hashed, so `"contacts"` and `["contacts"]` give
2733
+ // different versions. That is not a wart: they are different bytes in the
2734
+ // manifest, a client caching the manifest would see a different document, and
2735
+ // a fingerprint that hid the difference would be claiming two cached copies
2736
+ // are interchangeable when they do not read the same. So is `instructions`: it is rendered straight into the
2737
+ // system prompt, so an agent holding the old manifest is briefed with the
2738
+ // app's old words.
2739
+ //
2740
+ // All three are APPENDED, and only when the app actually used them, so the
2741
+ // shape of an app that uses none is the exact string it was before these
2742
+ // fields existed. That is not neatness: every stored `Manifest.version` out
2743
+ // there was computed from the old string, and an upgrade of this library that
2744
+ // silently moved every app's version would tell every agent its cached
2745
+ // manifest had gone stale when nothing about the app had changed at all.
2746
+ //
2747
+ // `consumes` is in for the strongest version of the same reason, and it is
2748
+ // the one case where a cached copy being wrong costs a round trip every time:
2749
+ // a verb that has started requiring a plan token cannot be called bare any
2750
+ // more, so an agent holding the old manifest calls it the old way and is
2751
+ // refused `stale-plan` on every attempt, with nothing in its cached
2752
+ // description to explain why. Dropping `consumes` is the dangerous direction
2753
+ // of the same move -- a commit that USED to demand a receipt and no longer
2754
+ // does -- which is the same class of mistake as dropping `reversible`.
2755
+ const extras = (v) => {
2756
+ const e = {};
2757
+ if (v.screen)
2758
+ e.screen = v.screen;
2759
+ if (v.reversible)
2760
+ e.reversible = v.reversible;
2761
+ if (v.consumes)
2762
+ e.consumes = v.consumes;
2763
+ return Object.keys(e).length ? [e] : [];
2764
+ };
2765
+ const shape = JSON.stringify([
2766
+ app,
2767
+ [...verbs.values()]
2768
+ .map((v) => [
2769
+ v.name,
2770
+ v.describe,
2771
+ v.kind ?? null,
2772
+ v.at ?? null,
2773
+ v.args ?? null,
2774
+ v.refuses ?? null,
2775
+ ...extras(v),
2776
+ ])
2777
+ .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
2778
+ ...(instructions ? [instructions] : []),
2779
+ // Appended last and only when present, by the same rule as the three
2780
+ // above: an app that declares neither hashes the exact string it hashed
2781
+ // before these fields existed. Tagged rather than bare, because they are
2782
+ // appended at the position `instructions` occupies when an app has no
2783
+ // briefing, and two different claims about an app must not be able to hash
2784
+ // to one shape.
2785
+ //
2786
+ // `screens` is in here for the reason `screen` on a verb is: it is what a
2787
+ // cached copy claims about where this app can be driven, and a screen that
2788
+ // gained a url template or had its sentence rewritten is a screen a model
2789
+ // was briefed about in the app's old words. `flows` is in here for the
2790
+ // reason `instructions` is -- it is rendered straight into the cached
2791
+ // system prompt -- with one extra edge: a flow names verbs, so an app that
2792
+ // renames one leaves every cached copy holding a recipe that cites a verb
2793
+ // which no longer exists.
2794
+ ...(screens ? [{ screens }] : []),
2795
+ ...(flows ? [{ flows }] : []),
2796
+ ]);
2797
+ return hash12(shape);
2798
+ }
2799
+ //# sourceMappingURL=registry.js.map