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 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/agent/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG","sourcesContent":["/**\n * driverkit/agent — the contract with the model, and nothing else.\n *\n * This package contains **no model client and no API key handling**, and that\n * is the load-bearing decision rather than a scoping convenience. Three\n * reasons, in order of how much they cost to get wrong:\n *\n * 1. **A browser cannot hold an API key.** Anything shipped to a page is\n * readable by whoever has the page, so a widget that takes an `apiKey`\n * option is a widget that leaks one. The realistic deployment is that\n * `think` does `fetch(\"/api/chat\")` against the app's own backend, which\n * already authenticates the person and already holds the key. That is the\n * documented default story — see `backendThink` — and nothing in these\n * types assumes a model is reachable from the page at all.\n *\n * 2. **Vendor neutrality has to be structural.** A `provider: \"anthropic\" |\n * \"openai\"` option means this package grows a translation layer per vendor\n * and a release per API change. A function pointer means it grows neither,\n * and a local model, a proxy, a queue or a scripted fake all satisfy it.\n *\n * 3. **It is how the loop gets tested.** Every test in this package drives a\n * real `mount()`ed driver with a scripted `think`. If the model were inside,\n * the loop's hard parts — the refusal path, the commit gate, the bounds —\n * would be verified by paying a vendor and hoping.\n *\n * The shapes below are deliberately the *intersection* of the tool-use APIs,\n * not the union: a system string, a flat message list, a tool list, and either\n * prose or calls coming back. Mapping that onto a vendor's wire format is\n * twenty lines in the caller and does not belong here.\n */\n\nimport type { Manifest, Result, Scalar, Snapshot, VerbKind } from \"../core/index.ts\";\n\n/**\n * One tool, as the model sees it.\n *\n * This is the MCP `tools/list` shape, down to the field names, because the\n * Python MCP server in this same repository emits exactly that and the two\n * halves of one library must not describe the same verbs differently. A model\n * driving an app from outside through MCP and a model driving it from inside\n * through this loop read the same sentences about the same verbs. See\n * `tools.ts`, and `python/src/driverkit/mcp_server.py` for the other end.\n */\nexport interface ToolSpec {\n name: string;\n description: string;\n inputSchema: {\n type: \"object\";\n properties: Record<string, JsonSchema>;\n required: string[];\n additionalProperties: false;\n };\n}\n\n/** The sliver of JSON Schema a driverkit `ArgSpec` can produce. Hand-rolled to\n * keep the zero-dependency promise the core makes. */\nexport interface JsonSchema {\n type: \"string\" | \"number\" | \"boolean\" | \"integer\";\n description: string;\n /** From `ArgSpec.oneOf`, which is JSON Schema's `enum` and emphatically not\n * JSON Schema's `oneOf`: the names look alike and the meanings diverge, and\n * emitting the latter produces a schema that validates anything. */\n enum?: Scalar[];\n}\n\n/** A verb the model wants run. `id` is the vendor's correlation id, passed\n * straight back on the tool turn; this package never interprets it. */\nexport interface ToolCall {\n id: string;\n name: string;\n args: Record<string, Scalar>;\n}\n\n/**\n * One message. A flat list of these, in order, is the uncached half.\n *\n * Three roles rather than a vendor's content-block union: it is the least that\n * can express a tool-use loop, and widening it would mean this package taking\n * a position on image blocks, thinking blocks and citations, each of which is\n * spelled differently by every vendor and needed by none of this.\n */\nexport type Turn =\n | { role: \"user\"; text: string }\n | { role: \"assistant\"; text?: string; calls?: ToolCall[] }\n | { role: \"tool\"; callId: string; name: string; text: string };\n\n/**\n * What `think` is handed.\n *\n * The split in here is the whole cost argument, restated as a function\n * signature: `system` and `tools` are the static half and are **byte-identical\n * on every call within a run**, so a caller can hand them to a provider with\n * caching turned on and pay for them once. `messages` is the growing tail.\n *\n * A caller that folds anything per-turn into `system` — a timestamp, the\n * current screen, a step counter — busts the prefix cache on every turn and\n * the loop stops being cheap. `drive` computes `system` once, before the loop,\n * from the manifest alone, which is the only way to make that structural\n * rather than a rule in a comment. There is a test that asserts it.\n */\nexport interface ThinkInput {\n /** Static for the whole run. Cache it. */\n system: string;\n /** Static for the whole run. Cache it. */\n tools: ToolSpec[];\n /** The tail: the person's message, the model's own turns, and one tool turn\n * per verb that ran, each carrying the screen as it was after it ran. */\n messages: Turn[];\n /** The run's cancellation, forwarded so a `fetch` can be torn down mid\n * flight. A `think` that ignores it still works; `drive` checks it again on\n * the way out and will not run a verb for an aborted run. */\n signal?: AbortSignal;\n}\n\n/**\n * What `think` returns.\n *\n * No `calls` (or an empty list) means the model answered, and the run ends\n * with `text` as the answer. That is the only stop condition the model\n * controls, and it is the same convention every tool-use API already uses, so\n * an adapter is a field rename rather than a state machine.\n */\nexport interface ThinkResult {\n text?: string;\n calls?: ToolCall[];\n}\n\nexport type Think = (input: ThinkInput) => Promise<ThinkResult>;\n\n/** Why the run ended. Returned rather than thrown: `max-steps` and `stuck` are\n * ordinary outcomes a UI has to render, and an exception would push every\n * caller into a try/catch that treats a bounded run as a failure. */\nexport type StopReason =\n /** The model answered in prose. The only ending the model chooses. */\n | \"answered\"\n /** `maxSteps` was reached with the model still calling verbs. */\n | \"max-steps\"\n /** The `AbortSignal` fired. */\n | \"aborted\"\n /** The same verb was refused the same way `refusalLimit` times. */\n | \"stuck\"\n /**\n * The app's own `MountOptions.budget` ceiling was reached, so the driver\n * refused `budget-spent` and going on was pointless.\n *\n * A separate reason and not folded into `stuck`, which is what it would\n * otherwise have become: the loop refuses the same way `refusalLimit` times\n * and then reports \"the same call kept being refused\". That sentence is true\n * and it is read as \"the model is confused\", which sends somebody to rewrite\n * a prompt for an app that has simply run out of allowance — and it spends\n * two more model round trips proving it, against the budget that just ran\n * out. `budget-spent` is the one refusal in `RESERVED_REFUSALS` whose honest\n * repair is \"do not try again\", so the loop stops on the first one.\n */\n | \"over-budget\"\n /** `think` returned neither prose nor calls. A broken adapter, usually. */\n | \"silent\";\n\n/** Handed to `onBeforeCommit`. Carries the manifest's `kind` and `refuses` so\n * a host app can word its own confirmation using the app's own vocabulary\n * rather than re-deriving it from the verb name. */\nexport interface CommitRequest {\n name: string;\n args: Record<string, Scalar>;\n verb: Manifest[\"verbs\"][number];\n /** The screen as it is right now, so a confirmation can show the selection\n * the commit is about to act on. */\n snapshot: Snapshot;\n}\n\n/**\n * `true` (or nothing) lets the commit run. `false` vetoes it. A string vetoes\n * it and becomes the hint the model is told.\n *\n * The veto reaches the model as an ordinary refusal — the `declined-by-user`\n * slug — and never as an exception. A thrown veto would abort the run and the\n * model would never learn why, so the next thing the person saw would be a\n * dead panel instead of \"you declined that; want me to narrow it first?\".\n */\nexport type CommitDecision = boolean | string | void;\n\n/**\n * What the run controls are asking for right now.\n *\n * Two states and not three: there is no \"stopped\". A stop is the `AbortSignal`,\n * which ends the run rather than changing how it is being driven, and folding\n * the two together would invite a `state === \"stopped\"` check that a paused run\n * could never recover from.\n */\nexport type ControlState = \"running\" | \"paused\";\n\n/**\n * What a UI should say the run is doing.\n *\n * The control states plus the one wait the controls do not own: a run sitting\n * in front of `onBeforeCommit` is not paused and is not running either, it is\n * waiting for a person to answer, and a panel that showed \"running\" there would\n * be telling the person to wait for the thing that is waiting for them.\n */\nexport type RunState = ControlState | \"awaiting-approval\";\n\n/**\n * Pause, resume and step, as a plain object. Built by `runControls`.\n *\n * Passed into `drive` rather than returned from it, because `drive`'s promise\n * settles when the run is over and a handle you can only hold afterwards is a\n * handle you cannot pause with. See `runControls` for the rest of that\n * argument.\n */\nexport interface RunControls {\n /** `\"paused\"` means the run will hold before its next call. The call in\n * flight, if any, still finishes: a pause is a gate between calls and never\n * an interruption inside one. */\n readonly state: ControlState;\n /** Outstanding `step()` permits. For a UI that wants to show that a step has\n * been asked for and not yet spent. */\n readonly permits: number;\n /** Hold before the next call. The call in flight finishes first. */\n pause(): void;\n /** Carry on. Drops any unspent `step()` permit, since running is the stronger\n * statement. */\n resume(): void;\n /** Run exactly one more call, then hold again. Valid from either state. */\n step(): void;\n /**\n * The delay before each call, in milliseconds, right now.\n *\n * Readable so a slider can render the run's real pace rather than its own\n * last write — which are different numbers the moment anything else sets it,\n * and the second one is the one a person would call a bug.\n */\n readonly paceMs: number;\n /**\n * Change the pace of the run **in flight**: from the next wait onwards, and\n * including the wait already running.\n *\n * Live because the moment a person wants the agent slowed down is while it is\n * going. A slider that quietly applied next run would be worse than no\n * slider: they move it, nothing happens, and they conclude it is broken.\n *\n * 0 means the next wait does not happen at all. Values that are not a claim\n * about a speed — `NaN`, `Infinity`, anything non-finite — are **ignored**,\n * and the current pace is kept: reading them as 0 would make the agent faster\n * than the person asked for, and reading `Infinity` as a delay would park the\n * run on a timer nobody meant to set. A negative is clamped to 0, since \"less\n * than no wait\" has only one sensible meaning.\n */\n pace(ms: number): void;\n /**\n * Be told when any of the above changes, for a UI that has to stay in step\n * with controls it is not the only owner of. Returns an unsubscribe.\n *\n * Fires on a real change to `state`, `permits` or `paceMs`, and on nothing\n * else. The listener is handed no arguments and reads whichever getter it\n * cares about, so this cannot grow a snapshot shape that drifts from the\n * object it describes.\n *\n * `onControl` already reports state during a run; this covers what that\n * cannot, which is a `step()` or a pace change made **between** runs, when\n * there is no loop to report anything. `drive` subscribes as well, which is\n * how a pace change reaches a wait that has already started.\n */\n subscribe(listener: () => void): () => void;\n /**\n * Block until the run may proceed. **`drive` calls this; a caller does not.**\n *\n * On the public interface because the waiting and the state have to live\n * together — a gate that polled a `state` getter would either spin or add a\n * latency of its own — and because a host with an exotic control surface (a\n * queue, a remote operator, a test) can implement this interface itself and\n * `drive` will drive it.\n *\n * `what` distinguishes a model round trip from a verb call: only a call spends\n * a `step()` permit. Resolves immediately, without holding, if `signal` is\n * already aborted or fires while parked — an abort outranks a pause, always.\n */\n gate(what: \"think\" | \"call\", signal?: AbortSignal): Promise<void>;\n}\n\n/**\n * The timer `pace` uses. Injectable so the suite does not actually sleep.\n *\n * Deliberately smaller than `setTimeout`: no arguments forwarded, no return\n * type promised. `unknown` for the handle because the real one is a `number` in\n * a browser and a `Timeout` object in Node, and a package that named either\n * would stop compiling in the other.\n */\nexport interface Clock {\n set(fn: () => void, ms: number): unknown;\n clear(handle: unknown): void;\n /**\n * Milliseconds since some fixed point. Defaults to `Date.now`.\n *\n * Here because a pace that can change mid-wait has to know how much of the\n * wait has already elapsed, and a suite that could inject the timer but not\n * the clock would have to sleep to test it.\n */\n now?(): number;\n}\n\n/** The common shape of the three per-call events. Shared so a widget can write\n * one function that renders a row and call it from all three. */\nexport interface CallEvent {\n step: number;\n call: ToolCall;\n /** From the manifest, and undefined when the app declared none — this package\n * does not manufacture a safety claim the app did not make, in either\n * direction. */\n kind?: VerbKind;\n /**\n * The verb's `at` selector, if the app declared one: a hint about which\n * element on the page this call is about, so a UI can outline it.\n *\n * Passed straight through from the manifest and used by nothing in here.\n * driverkit does not resolve selectors — see `Verb.at` in the core, which\n * says why that is a promise and not an omission. A UI is free to query it; a\n * UI is the only thing that should.\n */\n at?: string;\n /** Position within this turn's calls, 0-based. A model may ask for several\n * verbs in one turn, and a step list that showed them without their order\n * would be hiding the one thing the person needs: what ran before what. */\n index: number;\n /** How many calls this turn asked for. */\n of: number;\n}\n\nexport interface DriveEvents {\n /** About to spend a model round trip. `step` is 1-based. */\n onStep?: (e: { step: number }) => void;\n /** The model said something in prose, mid-run or as its answer. */\n onSay?: (e: { step: number; text: string }) => void;\n /**\n * A call is going to be attempted — fired **before** the pace wait and before\n * any pause gate, so a row for it can be on screen and glowing while the\n * person still has time to stop it. This is the event a pending step list is\n * built from; `onCall` then means \"running\" and `onResult` means \"done\".\n *\n * It is not a promise that the call will run. A stop pressed during the pace\n * wait, or while the run is held, abandons it unrun — `onStop` fires with\n * `aborted` and anything still pending should be settled from there, since no\n * `onResult` is coming for a call that never happened.\n */\n onBeforeCall?: (e: CallEvent) => void;\n /** A verb is about to run, after any pacing and any hold: the last event\n * before the app is touched. Pre-dates `onBeforeCall` and keeps its exact\n * meaning and timing — with no pacing and no controls the two fire back to\n * back, which is what an existing caller already sees. */\n onCall?: (e: CallEvent) => void;\n /** A verb ran. `result` is null for the one tool that is not a verb\n * (`read_screen`) and for a call to a name the manifest does not have. */\n onResult?: (\n e: CallEvent & {\n result: Result | null;\n /** What the model was told, verbatim. A UI showing this shows exactly\n * what the model is reasoning from, which is the honest thing to show. */\n text: string;\n },\n ) => void;\n /**\n * The run's control state changed. Fires once at the start of the run with\n * the initial state, then on every transition.\n *\n * There at all because the state has more than one owner. The caller moves it\n * with `pause`/`step`/`resume`, but `drive` moves it too — a step permit\n * spent leaves the run paused again, and the commit gate parks it in\n * `awaiting-approval` — and a UI that tracked it by watching its own buttons\n * would be wrong in exactly the cases that matter. One event, from the thing\n * that knows.\n *\n * `step` is the model turn in flight, and 0 for the opening event, before any\n * turn has been spent.\n */\n onControl?: (e: { step: number; state: RunState }) => void;\n /** The run ended, for any reason including abort. Always fires once. */\n onStop?: (e: { stop: StopReason; steps: number; text?: string }) => void;\n}\n\nexport interface DriveOptions extends DriveEvents {\n think: Think;\n /** What the person asked for. Appended as the newest user turn, together\n * with the current screen. Omit it to continue a `history` that already\n * ends in a user turn. */\n task?: string;\n /** Earlier turns, as returned by a previous `drive`. The loop keeps no state\n * between runs: a conversation is the caller's array, which is what lets a\n * widget hold one and a server hold another without this package owning a\n * session concept. */\n history?: Turn[];\n /**\n * Extra guidance from THIS HOST, folded into the system prompt after the\n * app's own `Manifest.instructions`.\n *\n * Static, like everything else in there. A per-user or per-screen string\n * here is the one mistake that makes the whole prefix uncacheable **across\n * users**, which is where most of the saving actually lives.\n *\n * What belongs here is what this embedding wants said and the app itself\n * would not say — a house tone, a rule about this deployment. What the APP\n * has to say about itself belongs in `MountOptions.instructions`, which\n * reaches an agent arriving over the relay as well as this one; a briefing\n * put here is visible to one of driverkit's two paths and not the other,\n * which is the gap that field exists to close.\n */\n instructions?: string;\n /**\n * Hard cap on model round trips. Default 12.\n *\n * There is a cap at all because an agent that loops forever inside somebody\n * else's web page is the thing that gets the library uninstalled. 12 is\n * enough for read → describe → check the count → commit → answer with room\n * to recover from two refusals, and small enough that a confused model costs\n * cents rather than a tab that is still spending at lunchtime.\n */\n maxSteps?: number;\n /**\n * Stop after this many identical refusals. Default 3.\n *\n * Identical means the same verb refused with the same slug. Counted across\n * the run and not merely consecutively: a model that alternates a refused\n * commit with a free read has not learned anything, it has just put a cheap\n * call between two expensive mistakes.\n */\n refusalLimit?: number;\n /** Cancel the run. Checked before every model call and before every verb,\n * and it outranks a pause: a held run is still abortable, never wedged. */\n signal?: AbortSignal;\n /**\n * Milliseconds to wait before each call the model asked for — a verb or a\n * `read_screen` — so a person can follow. **0 by default, which means no\n * waiting at all.**\n *\n * Two defaults, on purpose, and the split is the same one `onBeforeCommit`\n * makes. `drive` is a library primitive: it is driven by backend jobs, tests,\n * CLIs and servers, where nobody is watching and a delay per call is latency\n * charged to work with no eyes on it. So the default here is 0. `mountWidget`\n * defaults it to `WATCHABLE_PACE`, because a panel in a page has a person in\n * front of it by definition, and the whole reason the widget exists is that\n * the person should be able to see what is being done to their screen and\n * stop it. A library that invented 600ms of latency for a cron job to make a\n * UI it cannot see feel better would have the defaults the wrong way round.\n *\n * The wait is before every call including the first, which is the one the\n * person has had least chance to react to. It is cancellable: a stop during a\n * pace wait returns at once rather than after the wait.\n *\n * It is not a wait per model turn. Those are already slow and already\n * visible, and pacing them would double the latency of the part that costs\n * money without making anything more legible.\n */\n pace?: number;\n /**\n * Pause, resume and step. Build one with `runControls()`.\n *\n * Absent means a run that cannot be held, which is the right default for a\n * caller with no UI: an unattended run with nobody to resume it would park\n * forever on the first hold.\n */\n controls?: RunControls;\n /** The timer `pace` uses, and the clock a duration is measured against.\n * Defaults to `setTimeout` and `Date.now`. Injectable so a suite can assert\n * the waits without sleeping through them — and, with `timing`, so a run can\n * produce a byte-exact transcript; see `renderDuration`. */\n clock?: Clock;\n /**\n * Whether a call's elapsed time reaches the model, and when.\n *\n * The problem this answers: asked \"compare how long it takes to fetch X and\n * Y\", an agent driving this library had nothing to go on. `AuditEvent.ms` is\n * recorded on every call and goes to the HOST's logger; no byte of a rendered\n * turn ever carried a duration, so a model asked about speed was guessing.\n *\n * `\"off\"` — no duration ever. **The default here**, and the reason is\n * the same one `onBeforeCommit` is off by default in `drive`\n * and on by default in `mountWidget`: this is a library\n * primitive driven by a widget, a backend job, a test and a\n * CLI, and a caller that opted into nothing must get the\n * transcript it got before this field existed, byte for byte.\n * Anything else would move every existing eval's cached\n * prompts on upgrade.\n * `\"slow\"` — a line only on calls at or above `SLOW_MS`. What\n * `mountWidget` turns on. The whole token argument is here:\n * a snappy app pays nothing, and the bytes are spent only\n * where elapsed time is a fact about the app rather than\n * noise. `pruneScreens` cut a ten-step run from 5,775 to\n * 1,397 characters and this must not quietly give that back.\n * `\"always\"` — a line on every call, down to tenths of a second. For the\n * run that was actually asked to compare two fast verbs,\n * where \"both were under a second\" is not the answer\n * somebody wanted. Costs about five tokens per call forever,\n * which is why it is not the default.\n *\n * What is measured is the app's own work: the clock runs across\n * `driver.call()` and nothing else. The pace wait, a `controls` hold and this\n * loop's own `onBeforeCommit` dialog are all outside it by construction\n * rather than by subtraction. For a gate that lives INSIDE `driver.call()` —\n * which is what `mountWidget` installs, through `DriverApproval.adopt` — see\n * `waited`.\n */\n timing?: \"off\" | \"slow\" | \"always\";\n /**\n * Total milliseconds this host has spent waiting on a PERSON, ever.\n *\n * Read before and after `driver.call()`, and the difference is subtracted\n * from what the model is told. Monotonic and cumulative on purpose: a\n * counter that the loop diffs cannot be got wrong by a dialog that opens\n * twice, and the loop never has to be told when a question was asked.\n *\n * It exists because of one lie. A host may gate commits inside\n * `driver.call()` rather than through `onBeforeCommit` — `mountWidget` does,\n * via `DriverApproval.adopt`, so that a commit arriving over the relay gets\n * the same dialog — and then the wall-clock time of the call includes\n * somebody reading a confirmation. Reporting \"this call took 40 seconds\"\n * when 38 of them were a person deciding is a false claim about the app's\n * speed, and a model that believes it will route around a verb that is not\n * slow.\n *\n * Absent means nothing is subtracted, which is correct for every host whose\n * gate is `onBeforeCommit`: that one is already outside the measurement.\n * Ignored entirely when `timing` is `\"off\"`.\n */\n waited?: () => number;\n /**\n * Opt-in gate in front of every `commit` verb.\n *\n * Off by default **here, and only here**. `drive` is a library primitive: it\n * is driven by a widget, a backend job, a test, a CLI, and a caller that has\n * its own approval policy should not have to disable one it never asked for.\n *\n * It is a different judgement one level up. `mountWidget` defaults this ON,\n * because a person watching a chatbot move their own screen should not learn\n * about a thousand accepted rows afterwards — and the gate is cheap there\n * for a reason worth stating: a `commit` verb takes no predicate and acts on\n * the whole current selection, so accepting a thousand rows is ONE call and\n * therefore one question, not a thousand. That makes it the cheapest\n * possible place to put a human in front of the expensive failure.\n *\n * A veto reaches the model as a `declined-by-user` refusal — see `DECLINED`\n * and PROTOCOL.md's reserved list — so the model adapts instead of retrying.\n */\n onBeforeCommit?: (req: CommitRequest) => CommitDecision | Promise<CommitDecision>;\n}\n\nexport interface DriveOutcome {\n stop: StopReason;\n /** The model's last prose. The thing to show the person.\n *\n * Present for `answered`; also present for the other endings when the model\n * happened to narrate before it was cut off, because half an explanation is\n * better than a bare \"stopped\". */\n text?: string;\n /** Model round trips spent. */\n steps: number;\n /** `history` plus everything this run added. Pass it back as the next run's\n * `history` to continue the conversation.\n *\n * Not a verbatim transcript: every turn but the newest one carrying a screen\n * has had its screen block replaced — the person's turns and the tool turns\n * alike — so that a model is never shown two screens and left to work out\n * which one is now true, and so that a ten-step run is not ten screens long.\n * A tool turn keeps its outcome line either way, and no turn is ever dropped\n * or re-paired: every `tool_use` in here still has its result. See\n * `pruneScreens`. */\n messages: Turn[];\n}\n"]}
@@ -0,0 +1,92 @@
1
+ /**
2
+ * driverkit/browser — keeping a spend ceiling across a page load.
3
+ *
4
+ * `MountOptions.budget` bounded one mounted driver, and that was one word short
5
+ * of bounding anything. Navigation is one of the agent's own verbs: `goto` is a
6
+ * `read`, an agent calls it freely, and a `goto` that is a full page load tears
7
+ * the driver down and mounts a fresh one with the counters back at zero. So the
8
+ * agent could refresh its way to a new allowance, and `budget-spent`'s hint —
9
+ * "it does not refill, and waiting or retrying will not change it" — was a
10
+ * sentence the library could not keep.
11
+ *
12
+ * This is the twenty lines that make it true. Nothing clever lives here: the
13
+ * core owns what the numbers mean, when an allowance has expired, and what a
14
+ * broken store does to the next call. See `BudgetStore` and `Budget.store` in
15
+ * the core, which carry that argument. What is here is bytes, a scope, and one
16
+ * decision about which way to fail.
17
+ *
18
+ * **WHY `localStorage` AND NOT `sessionStorage`, when the widget's transcript
19
+ * goes the other way.** The two are scoped differently on purpose and the
20
+ * reason is the same reason in both directions. A transcript belongs to a tab:
21
+ * two tabs of one app are two conversations, and `sessionStorage` is per tab by
22
+ * definition, which also means a conversation does not outlive the tab it was
23
+ * had in. A ceiling belongs to the app: if it were per tab, "open a second tab"
24
+ * would be a budget-doubling move, which is the reload bypass again in a
25
+ * different hat. One allowance per app per origin, shared by every tab, spent by
26
+ * whichever one gets there first. Yes — one tab can exhaust another's. That is
27
+ * one ceiling behaving like one ceiling, exactly as a server-side counter would,
28
+ * and the alternative fails in the direction that costs money.
29
+ *
30
+ * **IT IS A COST CONTROL AND NOT A SECURITY BOUNDARY.** The person sitting
31
+ * there can edit this key in devtools, and clearing site data drops it. That is
32
+ * fine — they own the machine and they are the one paying — and the type says so
33
+ * plainly rather than implying a guarantee the browser cannot give. A ceiling
34
+ * that must hold against the person belongs on the server, behind the API the
35
+ * verbs call.
36
+ */
37
+ import type { BudgetStore } from "../core/index.ts";
38
+ import type { StorageLike } from "../widget/dom.ts";
39
+ export interface LocalBudgetStoreOptions {
40
+ /** The app, as `MountOptions.app`. The key is namespaced by it so two
41
+ * driverkit apps on one origin do not share an allowance — which would make
42
+ * one app's runaway into the other app's outage. */
43
+ app: string;
44
+ /** Defaults to `localStorage`, or to nothing at all where reaching for it
45
+ * throws. Injectable so this is an ordinary unit test and not a browser one;
46
+ * see `StorageLike`. */
47
+ storage?: StorageLike;
48
+ }
49
+ /** What a stored allowance is filed under. Exported so a host-side support
50
+ * tool, or a test, can clear it without guessing at the string. */
51
+ export declare function budgetKey(app: string): string;
52
+ /** A `BudgetStore` with a `forget()`, which is the host-side reset in
53
+ * `Budget.epoch`'s list of ways an allowance can start again — and the only
54
+ * one that needs no deploy. Deliberately a method on an object the HOST holds:
55
+ * an agent drives through verbs and has no verb for this. */
56
+ export interface LocalBudgetStore extends BudgetStore {
57
+ /** Drop the stored allowance. The next `mount()` starts a fresh one. */
58
+ forget(): void;
59
+ }
60
+ /**
61
+ * A `Budget.store` over `localStorage`, scoped per app per origin.
62
+ *
63
+ * ```ts
64
+ * mount({
65
+ * app: "contacts",
66
+ * verbs,
67
+ * visible,
68
+ * budget: {
69
+ * calls: 200,
70
+ * // Two hundred calls a day, and a reload does not refill them.
71
+ * window: 24 * 60 * 60 * 1000,
72
+ * store: localBudgetStore({ app: "contacts" }),
73
+ * },
74
+ * });
75
+ * ```
76
+ *
77
+ * **WHICH WAY THIS FAILS, AND WHY IT IS THE OPPOSITE OF EVERYTHING ELSE IN THE
78
+ * PACKAGE.** `position.ts` and `settings.ts` swallow every storage failure and
79
+ * fall back to a default, because the worst case there is a forgotten pane
80
+ * position and the alternative — a chat panel that does not render in a private
81
+ * window — is a far worse bug. Here the worst case is an uncapped agent, so
82
+ * every failure is reported rather than smoothed over: `load()` answers
83
+ * `{ ok: false }` and `save()` throws, and the core turns either into a
84
+ * `budget-spent` refusal that names the cause. The app stays usable by the
85
+ * person; it is the agent that stops.
86
+ *
87
+ * A corrupt or garbled record is `{ ok: false }` too, and that is the one worth
88
+ * saying out loud. It cannot be told apart from somebody having edited the key,
89
+ * and of the two ways to guess, exactly one has a bill attached.
90
+ */
91
+ export declare function localBudgetStore(options: LocalBudgetStoreOptions): LocalBudgetStore;
92
+ //# sourceMappingURL=budget.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budget.d.ts","sourceRoot":"","sources":["../../src/browser/budget.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,OAAO,KAAK,EAAgB,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAGpD,MAAM,WAAW,uBAAuB;IACtC;;yDAEqD;IACrD,GAAG,EAAE,MAAM,CAAC;IACZ;;6BAEyB;IACzB,OAAO,CAAC,EAAE,WAAW,CAAC;CACvB;AAED;oEACoE;AACpE,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE7C;AAED;;;8DAG8D;AAC9D,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,wEAAwE;IACxE,MAAM,IAAI,IAAI,CAAC;CAChB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,uBAAuB,GAAG,gBAAgB,CAqEnF"}
@@ -0,0 +1,151 @@
1
+ /**
2
+ * driverkit/browser — keeping a spend ceiling across a page load.
3
+ *
4
+ * `MountOptions.budget` bounded one mounted driver, and that was one word short
5
+ * of bounding anything. Navigation is one of the agent's own verbs: `goto` is a
6
+ * `read`, an agent calls it freely, and a `goto` that is a full page load tears
7
+ * the driver down and mounts a fresh one with the counters back at zero. So the
8
+ * agent could refresh its way to a new allowance, and `budget-spent`'s hint —
9
+ * "it does not refill, and waiting or retrying will not change it" — was a
10
+ * sentence the library could not keep.
11
+ *
12
+ * This is the twenty lines that make it true. Nothing clever lives here: the
13
+ * core owns what the numbers mean, when an allowance has expired, and what a
14
+ * broken store does to the next call. See `BudgetStore` and `Budget.store` in
15
+ * the core, which carry that argument. What is here is bytes, a scope, and one
16
+ * decision about which way to fail.
17
+ *
18
+ * **WHY `localStorage` AND NOT `sessionStorage`, when the widget's transcript
19
+ * goes the other way.** The two are scoped differently on purpose and the
20
+ * reason is the same reason in both directions. A transcript belongs to a tab:
21
+ * two tabs of one app are two conversations, and `sessionStorage` is per tab by
22
+ * definition, which also means a conversation does not outlive the tab it was
23
+ * had in. A ceiling belongs to the app: if it were per tab, "open a second tab"
24
+ * would be a budget-doubling move, which is the reload bypass again in a
25
+ * different hat. One allowance per app per origin, shared by every tab, spent by
26
+ * whichever one gets there first. Yes — one tab can exhaust another's. That is
27
+ * one ceiling behaving like one ceiling, exactly as a server-side counter would,
28
+ * and the alternative fails in the direction that costs money.
29
+ *
30
+ * **IT IS A COST CONTROL AND NOT A SECURITY BOUNDARY.** The person sitting
31
+ * there can edit this key in devtools, and clearing site data drops it. That is
32
+ * fine — they own the machine and they are the one paying — and the type says so
33
+ * plainly rather than implying a guarantee the browser cannot give. A ceiling
34
+ * that must hold against the person belongs on the server, behind the API the
35
+ * verbs call.
36
+ */
37
+ import { defaultStorage } from "../widget/position.js";
38
+ /** What a stored allowance is filed under. Exported so a host-side support
39
+ * tool, or a test, can clear it without guessing at the string. */
40
+ export function budgetKey(app) {
41
+ return `driverkit:budget:${app}`;
42
+ }
43
+ /**
44
+ * A `Budget.store` over `localStorage`, scoped per app per origin.
45
+ *
46
+ * ```ts
47
+ * mount({
48
+ * app: "contacts",
49
+ * verbs,
50
+ * visible,
51
+ * budget: {
52
+ * calls: 200,
53
+ * // Two hundred calls a day, and a reload does not refill them.
54
+ * window: 24 * 60 * 60 * 1000,
55
+ * store: localBudgetStore({ app: "contacts" }),
56
+ * },
57
+ * });
58
+ * ```
59
+ *
60
+ * **WHICH WAY THIS FAILS, AND WHY IT IS THE OPPOSITE OF EVERYTHING ELSE IN THE
61
+ * PACKAGE.** `position.ts` and `settings.ts` swallow every storage failure and
62
+ * fall back to a default, because the worst case there is a forgotten pane
63
+ * position and the alternative — a chat panel that does not render in a private
64
+ * window — is a far worse bug. Here the worst case is an uncapped agent, so
65
+ * every failure is reported rather than smoothed over: `load()` answers
66
+ * `{ ok: false }` and `save()` throws, and the core turns either into a
67
+ * `budget-spent` refusal that names the cause. The app stays usable by the
68
+ * person; it is the agent that stops.
69
+ *
70
+ * A corrupt or garbled record is `{ ok: false }` too, and that is the one worth
71
+ * saying out loud. It cannot be told apart from somebody having edited the key,
72
+ * and of the two ways to guess, exactly one has a bill attached.
73
+ */
74
+ export function localBudgetStore(options) {
75
+ const key = budgetKey(options.app);
76
+ // Resolved once, at construction, like the widget's: `defaultStorage()`
77
+ // itself throws where site data is blocked, which is why it is a function
78
+ // with a try inside rather than a property read.
79
+ const storage = options.storage ?? defaultStorage();
80
+ return {
81
+ load() {
82
+ // No storage at all is NOT "nothing stored". It is "I cannot look", which
83
+ // is the distinction the whole fail-closed design rests on; collapsing
84
+ // the two here would undo it a layer below the core that depends on it.
85
+ if (storage === undefined)
86
+ return { ok: false };
87
+ let raw;
88
+ try {
89
+ raw = storage.getItem(key);
90
+ }
91
+ catch {
92
+ return { ok: false };
93
+ }
94
+ // Empty slot and empty string alike: storage worked and holds nothing, so
95
+ // this is a genuinely fresh allowance. The one `{ ok: true, spent: null }`
96
+ // in the file, and the only shape that may ever mean "spend from zero".
97
+ if (!raw)
98
+ return { ok: true, spent: null };
99
+ try {
100
+ const parsed = JSON.parse(raw);
101
+ if (!parsed || typeof parsed !== "object")
102
+ return { ok: false };
103
+ const { calls, commits, since, epoch } = parsed;
104
+ if (!Number.isInteger(calls) || !Number.isInteger(commits))
105
+ return { ok: false };
106
+ if (!Number.isFinite(since))
107
+ return { ok: false };
108
+ if (epoch !== undefined && typeof epoch !== "string")
109
+ return { ok: false };
110
+ return {
111
+ ok: true,
112
+ spent: {
113
+ calls: calls,
114
+ commits: commits,
115
+ since: since,
116
+ ...(epoch === undefined ? {} : { epoch }),
117
+ },
118
+ };
119
+ }
120
+ catch {
121
+ return { ok: false };
122
+ }
123
+ },
124
+ save(record) {
125
+ // Not `saveJson`, and this is the one place in the package that does not
126
+ // use it. `saveJson` swallows, by design and correctly, for everything
127
+ // whose failure costs a remembered preference. A swallowed failure here
128
+ // is an allowance that quietly stops being kept, so the throw is the
129
+ // contract: see `BudgetStore.save`.
130
+ if (storage === undefined)
131
+ throw new Error("driverkit: no storage for the spend ceiling");
132
+ storage.setItem(key, JSON.stringify(record));
133
+ },
134
+ forget() {
135
+ // Written empty rather than removed, because `StorageLike` is two methods
136
+ // and `removeItem` is not one of them — and `load` above reads an empty
137
+ // string as an empty slot, which is the same thing a removal would leave.
138
+ // Swallowed, unlike `save`: a reset that could not be written has changed
139
+ // nothing and broken nothing, and throwing out of a support action would
140
+ // be noise.
141
+ try {
142
+ storage?.setItem(key, "");
143
+ }
144
+ catch {
145
+ // No storage, blocked site data, a full quota. Nothing was spent and
146
+ // nothing was reset; the ceiling stands where it stood.
147
+ }
148
+ },
149
+ };
150
+ }
151
+ //# sourceMappingURL=budget.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budget.js","sourceRoot":"","sources":["../../src/browser/budget.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAIH,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAavD;oEACoE;AACpE,MAAM,UAAU,SAAS,CAAC,GAAW;IACnC,OAAO,oBAAoB,GAAG,EAAE,CAAC;AACnC,CAAC;AAWD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAgC;IAC/D,MAAM,GAAG,GAAG,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACnC,wEAAwE;IACxE,0EAA0E;IAC1E,iDAAiD;IACjD,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,cAAc,EAAE,CAAC;IAEpD,OAAO;QACL,IAAI;YACF,0EAA0E;YAC1E,uEAAuE;YACvE,wEAAwE;YACxE,IAAI,OAAO,KAAK,SAAS;gBAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;YAChD,IAAI,GAAkB,CAAC;YACvB,IAAI,CAAC;gBACH,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YAC7B,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;YACvB,CAAC;YACD,0EAA0E;YAC1E,2EAA2E;YAC3E,wEAAwE;YACxE,IAAI,CAAC,GAAG;gBAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;YAC3C,IAAI,CAAC;gBACH,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAiC,CAAC;gBAC/D,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ;oBAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;gBAChE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,MAAM,CAAC;gBAChD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC;oBAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;gBACjF,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;oBAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;gBAClD,IAAI,KAAK,KAAK,SAAS,IAAI,OAAO,KAAK,KAAK,QAAQ;oBAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;gBAC3E,OAAO;oBACL,EAAE,EAAE,IAAI;oBACR,KAAK,EAAE;wBACL,KAAK,EAAE,KAAe;wBACtB,OAAO,EAAE,OAAiB;wBAC1B,KAAK,EAAE,KAAe;wBACtB,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC;qBAC1C;iBACF,CAAC;YACJ,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;YACvB,CAAC;QACH,CAAC;QAED,IAAI,CAAC,MAAoB;YACvB,yEAAyE;YACzE,uEAAuE;YACvE,wEAAwE;YACxE,qEAAqE;YACrE,oCAAoC;YACpC,IAAI,OAAO,KAAK,SAAS;gBAAE,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;YAC1F,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;QAC/C,CAAC;QAED,MAAM;YACJ,0EAA0E;YAC1E,wEAAwE;YACxE,0EAA0E;YAC1E,0EAA0E;YAC1E,yEAAyE;YACzE,YAAY;YACZ,IAAI,CAAC;gBACH,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YAC5B,CAAC;YAAC,MAAM,CAAC;gBACP,qEAAqE;gBACrE,wDAAwD;YAC1D,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * driverkit/browser — keeping a spend ceiling across a page load.\n *\n * `MountOptions.budget` bounded one mounted driver, and that was one word short\n * of bounding anything. Navigation is one of the agent's own verbs: `goto` is a\n * `read`, an agent calls it freely, and a `goto` that is a full page load tears\n * the driver down and mounts a fresh one with the counters back at zero. So the\n * agent could refresh its way to a new allowance, and `budget-spent`'s hint —\n * \"it does not refill, and waiting or retrying will not change it\" — was a\n * sentence the library could not keep.\n *\n * This is the twenty lines that make it true. Nothing clever lives here: the\n * core owns what the numbers mean, when an allowance has expired, and what a\n * broken store does to the next call. See `BudgetStore` and `Budget.store` in\n * the core, which carry that argument. What is here is bytes, a scope, and one\n * decision about which way to fail.\n *\n * **WHY `localStorage` AND NOT `sessionStorage`, when the widget's transcript\n * goes the other way.** The two are scoped differently on purpose and the\n * reason is the same reason in both directions. A transcript belongs to a tab:\n * two tabs of one app are two conversations, and `sessionStorage` is per tab by\n * definition, which also means a conversation does not outlive the tab it was\n * had in. A ceiling belongs to the app: if it were per tab, \"open a second tab\"\n * would be a budget-doubling move, which is the reload bypass again in a\n * different hat. One allowance per app per origin, shared by every tab, spent by\n * whichever one gets there first. Yes — one tab can exhaust another's. That is\n * one ceiling behaving like one ceiling, exactly as a server-side counter would,\n * and the alternative fails in the direction that costs money.\n *\n * **IT IS A COST CONTROL AND NOT A SECURITY BOUNDARY.** The person sitting\n * there can edit this key in devtools, and clearing site data drops it. That is\n * fine — they own the machine and they are the one paying — and the type says so\n * plainly rather than implying a guarantee the browser cannot give. A ceiling\n * that must hold against the person belongs on the server, behind the API the\n * verbs call.\n */\n\nimport type { BudgetRecord, BudgetStore } from \"../core/index.ts\";\nimport type { StorageLike } from \"../widget/dom.ts\";\nimport { defaultStorage } from \"../widget/position.ts\";\n\nexport interface LocalBudgetStoreOptions {\n /** The app, as `MountOptions.app`. The key is namespaced by it so two\n * driverkit apps on one origin do not share an allowance — which would make\n * one app's runaway into the other app's outage. */\n app: string;\n /** Defaults to `localStorage`, or to nothing at all where reaching for it\n * throws. Injectable so this is an ordinary unit test and not a browser one;\n * see `StorageLike`. */\n storage?: StorageLike;\n}\n\n/** What a stored allowance is filed under. Exported so a host-side support\n * tool, or a test, can clear it without guessing at the string. */\nexport function budgetKey(app: string): string {\n return `driverkit:budget:${app}`;\n}\n\n/** A `BudgetStore` with a `forget()`, which is the host-side reset in\n * `Budget.epoch`'s list of ways an allowance can start again — and the only\n * one that needs no deploy. Deliberately a method on an object the HOST holds:\n * an agent drives through verbs and has no verb for this. */\nexport interface LocalBudgetStore extends BudgetStore {\n /** Drop the stored allowance. The next `mount()` starts a fresh one. */\n forget(): void;\n}\n\n/**\n * A `Budget.store` over `localStorage`, scoped per app per origin.\n *\n * ```ts\n * mount({\n * app: \"contacts\",\n * verbs,\n * visible,\n * budget: {\n * calls: 200,\n * // Two hundred calls a day, and a reload does not refill them.\n * window: 24 * 60 * 60 * 1000,\n * store: localBudgetStore({ app: \"contacts\" }),\n * },\n * });\n * ```\n *\n * **WHICH WAY THIS FAILS, AND WHY IT IS THE OPPOSITE OF EVERYTHING ELSE IN THE\n * PACKAGE.** `position.ts` and `settings.ts` swallow every storage failure and\n * fall back to a default, because the worst case there is a forgotten pane\n * position and the alternative — a chat panel that does not render in a private\n * window — is a far worse bug. Here the worst case is an uncapped agent, so\n * every failure is reported rather than smoothed over: `load()` answers\n * `{ ok: false }` and `save()` throws, and the core turns either into a\n * `budget-spent` refusal that names the cause. The app stays usable by the\n * person; it is the agent that stops.\n *\n * A corrupt or garbled record is `{ ok: false }` too, and that is the one worth\n * saying out loud. It cannot be told apart from somebody having edited the key,\n * and of the two ways to guess, exactly one has a bill attached.\n */\nexport function localBudgetStore(options: LocalBudgetStoreOptions): LocalBudgetStore {\n const key = budgetKey(options.app);\n // Resolved once, at construction, like the widget's: `defaultStorage()`\n // itself throws where site data is blocked, which is why it is a function\n // with a try inside rather than a property read.\n const storage = options.storage ?? defaultStorage();\n\n return {\n load(): { ok: true; spent: BudgetRecord | null } | { ok: false } {\n // No storage at all is NOT \"nothing stored\". It is \"I cannot look\", which\n // is the distinction the whole fail-closed design rests on; collapsing\n // the two here would undo it a layer below the core that depends on it.\n if (storage === undefined) return { ok: false };\n let raw: string | null;\n try {\n raw = storage.getItem(key);\n } catch {\n return { ok: false };\n }\n // Empty slot and empty string alike: storage worked and holds nothing, so\n // this is a genuinely fresh allowance. The one `{ ok: true, spent: null }`\n // in the file, and the only shape that may ever mean \"spend from zero\".\n if (!raw) return { ok: true, spent: null };\n try {\n const parsed = JSON.parse(raw) as Partial<BudgetRecord> | null;\n if (!parsed || typeof parsed !== \"object\") return { ok: false };\n const { calls, commits, since, epoch } = parsed;\n if (!Number.isInteger(calls) || !Number.isInteger(commits)) return { ok: false };\n if (!Number.isFinite(since)) return { ok: false };\n if (epoch !== undefined && typeof epoch !== \"string\") return { ok: false };\n return {\n ok: true,\n spent: {\n calls: calls as number,\n commits: commits as number,\n since: since as number,\n ...(epoch === undefined ? {} : { epoch }),\n },\n };\n } catch {\n return { ok: false };\n }\n },\n\n save(record: BudgetRecord): void {\n // Not `saveJson`, and this is the one place in the package that does not\n // use it. `saveJson` swallows, by design and correctly, for everything\n // whose failure costs a remembered preference. A swallowed failure here\n // is an allowance that quietly stops being kept, so the throw is the\n // contract: see `BudgetStore.save`.\n if (storage === undefined) throw new Error(\"driverkit: no storage for the spend ceiling\");\n storage.setItem(key, JSON.stringify(record));\n },\n\n forget(): void {\n // Written empty rather than removed, because `StorageLike` is two methods\n // and `removeItem` is not one of them — and `load` above reads an empty\n // string as an empty slot, which is the same thing a removal would leave.\n // Swallowed, unlike `save`: a reset that could not be written has changed\n // nothing and broken nothing, and throwing out of a support action would\n // be noise.\n try {\n storage?.setItem(key, \"\");\n } catch {\n // No storage, blocked site data, a full quota. Nothing was spent and\n // nothing was reset; the ceiling stands where it stood.\n }\n },\n };\n}\n"]}