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
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # driverkit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Make a web app drivable by an agent. No pixels, no selectors, no model.
4
+
5
+ Your app declares what it can do and what is on screen. An agent calls those
6
+ verbs by name. The app's own functions run, and the UI moves the way it would
7
+ have if somebody had clicked.
8
+
9
+ ```sh
10
+ npm i driverkit
11
+ ```
12
+
13
+ ```ts
14
+ import { mount } from "driverkit";
15
+
16
+ const driver = mount({
17
+ app: "Contacts",
18
+ verbs: [
19
+ { name: "search", kind: "read", describe: "filter the list",
20
+ args: { q: { type: "string", describe: "what to search for" } },
21
+ run: ({ q }) => store.search(q) },
22
+
23
+ { name: "select-where", kind: "describe", describe: "select every contact at a company",
24
+ args: { company: { type: "string", describe: "company name" } },
25
+ run: ({ company }) => ({ count: store.select(company) }) },
26
+
27
+ { name: "accept-selected", kind: "commit", describe: "accept the current selection",
28
+ refuses: ["nothing-selected"],
29
+ run: (_, ctx) => store.selected.size ? store.accept() : ctx.refuse("nothing-selected") },
30
+ ],
31
+ visible: () => ({
32
+ where: "contacts",
33
+ rev: store.rev,
34
+ rows: store.onScreen(),
35
+ page: { index: store.page, size: 20, total: store.total },
36
+ selected: store.visibleSelection(),
37
+ selectedCount: store.selected.size,
38
+ }),
39
+ });
40
+ ```
41
+
42
+ That is the whole integration: one new file in your app, one import.
43
+
44
+ ## Entry points
45
+
46
+ One package, one version, one changelog. Tree-shaking keeps a page free of
47
+ what it does not import.
48
+
49
+ | import | what |
50
+ |---|---|
51
+ | `driverkit` | the registry: verbs, the screen, one `call` |
52
+ | `driverkit/widget` | a chat panel in the corner of your own app |
53
+ | `driverkit/agent` | the loop behind it, provider-neutral |
54
+ | `driverkit/controls` | three generic verbs over elements you marked `data-dk-control` — see [CONTROLS.md](CONTROLS.md) |
55
+ | `driverkit/browser` | the page side of the relay: one SSE stream, held open |
56
+ | `driverkit/relay` | the relay — **Node only** |
57
+
58
+ `driverkit/relay` imports `node:http`, so it is published under a `"node"`
59
+ export condition and no other. A browser-targeted build that asks for it fails
60
+ at build time with the import named, rather than pulling Node builtins into a
61
+ page bundle. There is no browser shim on purpose: a `createRelay` that
62
+ resolved to an empty module would silently do nothing, which is worse than a
63
+ build error.
64
+
65
+ Pre-1.0, so one version covers everything — a widget fix bumps this number
66
+ too. That is deliberate: there is one number that says which driverkit you are
67
+ running, and no matrix of which widget works with which core.
68
+
69
+ No runtime dependencies. `@types/node` is a types-only dependency, there
70
+ because the relay's own `.d.ts` files re-export `node:http` types in their
71
+ public surface; nothing is emitted into a page bundle by it.
72
+
73
+ ## The two things it drives
74
+
75
+ **A chat panel in the corner of your app.** The page holds the driver, so
76
+ there is no transport at all — a loop asks a model what to do and calls the
77
+ verb. Your API key stays on your backend behind one endpoint.
78
+
79
+ ```ts
80
+ import { mountWidget } from "driverkit/widget";
81
+ import { backendThink } from "driverkit/agent";
82
+
83
+ mountWidget(driver, { think: backendThink("/api/chat") });
84
+ ```
85
+
86
+ **An agent somewhere else** — another process, another machine, a voice
87
+ assistant. Nothing can call *into* a browser tab, so the tab dials out to a
88
+ relay and holds the line open. The agent talks to the relay over MCP.
89
+
90
+ ```
91
+ agent ──► MCP ──► relay ──► your tab ──► your app's function
92
+ ```
93
+
94
+ The relay ships twice, once here and once on PyPI (`pip install driverkit`,
95
+ which also carries the MCP server). The two implementations are tested against
96
+ each other, frame for frame.
97
+
98
+ ## Status
99
+
100
+ Early. Treat the APIs as unstable until there is a tagged release.
101
+
102
+ The full README, the wire protocol, the design arguments and a 3,412-row demo
103
+ that is drivable both ways live in the repository.
104
+
105
+ MIT.
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The default deployment story, in thirty lines.
3
+ *
4
+ * A browser cannot hold an API key. So the shape that actually ships is: the
5
+ * page posts the conversation to the app's own backend, the backend — which
6
+ * already authenticates this person and already holds the key — calls whatever
7
+ * model it likes and answers with prose or tool calls. This is that post.
8
+ *
9
+ * It is a convenience and not a layer. `Think` is a function; if your backend
10
+ * speaks a different shape, write the fetch yourself and do not use this. The
11
+ * reason it is here at all is that the first thing anybody asks of a package
12
+ * with no model client in it is "so what do I pass", and the answer should be
13
+ * code rather than a paragraph.
14
+ *
15
+ * **What the backend should do with the two static fields.** `system` and
16
+ * `tools` are byte-identical on every request within a run, and across runs
17
+ * and across users for as long as the app's verbs do not change. A backend
18
+ * that forwards them with its provider's caching marker on (Anthropic's
19
+ * `cache_control`, or whatever the equivalent is wherever you are sending it)
20
+ * pays for the app's whole capability list once instead of once per turn. A
21
+ * backend that appends its own per-request string to `system` before
22
+ * forwarding — a user id, a clock — gives that saving back and will not notice,
23
+ * because nothing breaks. It just costs more.
24
+ *
25
+ * **What the backend must not do.** Trust the verb names. The page tells the
26
+ * model what the app can do, and the model's reply comes back through here and
27
+ * is executed against the driver mounted in *this* page, under *this* person's
28
+ * session — which is the same authority model the relay has and PROTOCOL.md's
29
+ * "Who is allowed to do this" applies unchanged. But a backend that stores or
30
+ * replays these messages is storing the app's row data, because the snapshots
31
+ * are in them.
32
+ */
33
+ import type { Think } from "./types.ts";
34
+ /** The slice of `fetch` this needs. Narrow so a test can satisfy it and so
35
+ * this file does not depend on DOM lib types. */
36
+ export interface FetchLike {
37
+ (url: string, init: {
38
+ method: string;
39
+ headers: Record<string, string>;
40
+ body: string;
41
+ signal?: AbortSignal;
42
+ }): Promise<ResponseLike>;
43
+ }
44
+ /** The slice of `Response` this reads. `text` is optional so a hand-written
45
+ * fake that only answers `json()` still satisfies the type; see `detailOf`. */
46
+ export interface ResponseLike {
47
+ ok: boolean;
48
+ status: number;
49
+ json(): Promise<unknown>;
50
+ text?(): Promise<string>;
51
+ }
52
+ export interface BackendThinkOptions {
53
+ /** Extra headers — a CSRF token, usually. */
54
+ headers?: Record<string, string>;
55
+ /** Injected, defaulting to the global. Same reason as everywhere else in
56
+ * this repository: a module that can only run in a browser is a module
57
+ * whose error path is tested by hand. */
58
+ fetch?: FetchLike;
59
+ }
60
+ /**
61
+ * `Think` over one HTTP endpoint.
62
+ *
63
+ * Posts `{ system, tools, messages }` and expects `{ text?, calls? }` back.
64
+ * Credentials ride on the request the way the rest of the app's requests do —
65
+ * `same-origin` is the browser default for a same-origin URL, so a session
66
+ * cookie is already attached and there is nothing to configure.
67
+ */
68
+ export declare function backendThink(url: string, options?: BackendThinkOptions): Think;
69
+ //# sourceMappingURL=backend.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backend.d.ts","sourceRoot":"","sources":["../../src/agent/backend.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAyB,MAAM,YAAY,CAAC;AAE/D;kDACkD;AAClD,MAAM,WAAW,SAAS;IACxB,CACE,GAAG,EAAE,MAAM,EACX,IAAI,EAAE;QACJ,MAAM,EAAE,MAAM,CAAC;QACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAChC,IAAI,EAAE,MAAM,CAAC;QACb,MAAM,CAAC,EAAE,WAAW,CAAC;KACtB,GACA,OAAO,CAAC,YAAY,CAAC,CAAC;CAC1B;AAED;gFACgF;AAChF,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,OAAO,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IACzB,IAAI,CAAC,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;CAC1B;AAED,MAAM,WAAW,mBAAmB;IAClC,6CAA6C;IAC7C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC;;8CAE0C;IAC1C,KAAK,CAAC,EAAE,SAAS,CAAC;CACnB;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,KAAK,CAsClF"}
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The default deployment story, in thirty lines.
3
+ *
4
+ * A browser cannot hold an API key. So the shape that actually ships is: the
5
+ * page posts the conversation to the app's own backend, the backend — which
6
+ * already authenticates this person and already holds the key — calls whatever
7
+ * model it likes and answers with prose or tool calls. This is that post.
8
+ *
9
+ * It is a convenience and not a layer. `Think` is a function; if your backend
10
+ * speaks a different shape, write the fetch yourself and do not use this. The
11
+ * reason it is here at all is that the first thing anybody asks of a package
12
+ * with no model client in it is "so what do I pass", and the answer should be
13
+ * code rather than a paragraph.
14
+ *
15
+ * **What the backend should do with the two static fields.** `system` and
16
+ * `tools` are byte-identical on every request within a run, and across runs
17
+ * and across users for as long as the app's verbs do not change. A backend
18
+ * that forwards them with its provider's caching marker on (Anthropic's
19
+ * `cache_control`, or whatever the equivalent is wherever you are sending it)
20
+ * pays for the app's whole capability list once instead of once per turn. A
21
+ * backend that appends its own per-request string to `system` before
22
+ * forwarding — a user id, a clock — gives that saving back and will not notice,
23
+ * because nothing breaks. It just costs more.
24
+ *
25
+ * **What the backend must not do.** Trust the verb names. The page tells the
26
+ * model what the app can do, and the model's reply comes back through here and
27
+ * is executed against the driver mounted in *this* page, under *this* person's
28
+ * session — which is the same authority model the relay has and PROTOCOL.md's
29
+ * "Who is allowed to do this" applies unchanged. But a backend that stores or
30
+ * replays these messages is storing the app's row data, because the snapshots
31
+ * are in them.
32
+ */
33
+ /**
34
+ * `Think` over one HTTP endpoint.
35
+ *
36
+ * Posts `{ system, tools, messages }` and expects `{ text?, calls? }` back.
37
+ * Credentials ride on the request the way the rest of the app's requests do —
38
+ * `same-origin` is the browser default for a same-origin URL, so a session
39
+ * cookie is already attached and there is nothing to configure.
40
+ */
41
+ export function backendThink(url, options = {}) {
42
+ const doFetch = options.fetch ?? globalThis.fetch?.bind(globalThis);
43
+ return async ({ system, tools, messages, signal }) => {
44
+ if (!doFetch)
45
+ throw new Error("driverkit: no fetch available; pass one");
46
+ const response = await doFetch(url, {
47
+ method: "POST",
48
+ headers: { "content-type": "application/json", ...options.headers },
49
+ body: JSON.stringify({ system, tools, messages }),
50
+ ...(signal ? { signal } : {}),
51
+ });
52
+ if (!response.ok) {
53
+ // Thrown, not returned as empty prose. A 500 from your own backend is
54
+ // not the model declining to act, and swallowing it would surface as an
55
+ // agent that silently stops having opinions. The loop lets it propagate
56
+ // to the caller of `drive`, which is where a retry or a visible error
57
+ // belongs.
58
+ // With the body, because the body is where the diagnosis is. A backend
59
+ // that answers `{"error": "no API key configured"}` has already told you
60
+ // what is wrong; a panel that renders `answered 503` sends somebody to
61
+ // read server logs for a sentence that was in the response all along.
62
+ const detail = await detailOf(response);
63
+ throw new Error(`driverkit: ${url} answered ${response.status}` + (detail ? ` — ${detail}` : ""));
64
+ }
65
+ const body = (await response.json());
66
+ const calls = Array.isArray(body.calls) ? body.calls : undefined;
67
+ const result = {
68
+ ...(typeof body.text === "string" && body.text ? { text: body.text } : {}),
69
+ ...(calls && calls.length ? { calls } : {}),
70
+ };
71
+ return result;
72
+ };
73
+ }
74
+ /** How much of an error body may reach the thrown message. Enough for a
75
+ * sentence, short enough that an HTML error page or a stack trace cannot turn
76
+ * an exception into a wall of text in somebody's chat panel. */
77
+ const DETAIL_LIMIT = 400;
78
+ /**
79
+ * The most useful sentence an error response has to offer, or `""`.
80
+ *
81
+ * Three shapes, in the order they are worth having. A JSON body with an
82
+ * `error` string is a backend speaking on purpose and is used verbatim. Plain
83
+ * text — a proxy's `502 Bad Gateway`, a stack trace — is still better than a
84
+ * bare status, so a trimmed snippet of it goes in. An empty body yields
85
+ * nothing, and the message stays as it was.
86
+ *
87
+ * Nothing in here may throw. This runs on the failure path, and an exception
88
+ * raised while explaining an exception replaces the diagnosis with its own —
89
+ * the one failure mode worse than the bug being fixed. So the body read, the
90
+ * JSON parse and the field read are each allowed to fail quietly.
91
+ */
92
+ async function detailOf(response) {
93
+ let raw;
94
+ try {
95
+ if (typeof response.text === "function") {
96
+ raw = await response.text();
97
+ }
98
+ else {
99
+ // A fake, or a client that only exposes `json()`. Re-serialising is not
100
+ // the prettiest route to a string but it is the only one available, and
101
+ // the `error` field survives it.
102
+ raw = JSON.stringify(await response.json());
103
+ }
104
+ }
105
+ catch {
106
+ return "";
107
+ }
108
+ if (typeof raw !== "string")
109
+ return "";
110
+ const text = raw.trim();
111
+ if (!text)
112
+ return "";
113
+ try {
114
+ const parsed = JSON.parse(text);
115
+ if (parsed && typeof parsed === "object") {
116
+ const error = parsed.error;
117
+ if (typeof error === "string" && error.trim())
118
+ return clip(error.trim());
119
+ }
120
+ }
121
+ catch {
122
+ // Not JSON. Fall through: the raw text is still the best thing to hand on.
123
+ }
124
+ return clip(text);
125
+ }
126
+ function clip(text) {
127
+ const flat = text.replace(/\s+/g, " ").trim();
128
+ return flat.length > DETAIL_LIMIT ? flat.slice(0, DETAIL_LIMIT) + "…" : flat;
129
+ }
130
+ //# sourceMappingURL=backend.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backend.js","sourceRoot":"","sources":["../../src/agent/backend.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * The default deployment story, in thirty lines.\n *\n * A browser cannot hold an API key. So the shape that actually ships is: the\n * page posts the conversation to the app's own backend, the backend — which\n * already authenticates this person and already holds the key — calls whatever\n * model it likes and answers with prose or tool calls. This is that post.\n *\n * It is a convenience and not a layer. `Think` is a function; if your backend\n * speaks a different shape, write the fetch yourself and do not use this. The\n * reason it is here at all is that the first thing anybody asks of a package\n * with no model client in it is \"so what do I pass\", and the answer should be\n * code rather than a paragraph.\n *\n * **What the backend should do with the two static fields.** `system` and\n * `tools` are byte-identical on every request within a run, and across runs\n * and across users for as long as the app's verbs do not change. A backend\n * that forwards them with its provider's caching marker on (Anthropic's\n * `cache_control`, or whatever the equivalent is wherever you are sending it)\n * pays for the app's whole capability list once instead of once per turn. A\n * backend that appends its own per-request string to `system` before\n * forwarding — a user id, a clock — gives that saving back and will not notice,\n * because nothing breaks. It just costs more.\n *\n * **What the backend must not do.** Trust the verb names. The page tells the\n * model what the app can do, and the model's reply comes back through here and\n * is executed against the driver mounted in *this* page, under *this* person's\n * session — which is the same authority model the relay has and PROTOCOL.md's\n * \"Who is allowed to do this\" applies unchanged. But a backend that stores or\n * replays these messages is storing the app's row data, because the snapshots\n * are in them.\n */\n\nimport type { Think, ThinkResult, ToolCall } from \"./types.ts\";\n\n/** The slice of `fetch` this needs. Narrow so a test can satisfy it and so\n * this file does not depend on DOM lib types. */\nexport interface FetchLike {\n (\n url: string,\n init: {\n method: string;\n headers: Record<string, string>;\n body: string;\n signal?: AbortSignal;\n },\n ): Promise<ResponseLike>;\n}\n\n/** The slice of `Response` this reads. `text` is optional so a hand-written\n * fake that only answers `json()` still satisfies the type; see `detailOf`. */\nexport interface ResponseLike {\n ok: boolean;\n status: number;\n json(): Promise<unknown>;\n text?(): Promise<string>;\n}\n\nexport interface BackendThinkOptions {\n /** Extra headers — a CSRF token, usually. */\n headers?: Record<string, string>;\n /** Injected, defaulting to the global. Same reason as everywhere else in\n * this repository: a module that can only run in a browser is a module\n * whose error path is tested by hand. */\n fetch?: FetchLike;\n}\n\n/**\n * `Think` over one HTTP endpoint.\n *\n * Posts `{ system, tools, messages }` and expects `{ text?, calls? }` back.\n * Credentials ride on the request the way the rest of the app's requests do —\n * `same-origin` is the browser default for a same-origin URL, so a session\n * cookie is already attached and there is nothing to configure.\n */\nexport function backendThink(url: string, options: BackendThinkOptions = {}): Think {\n const doFetch =\n options.fetch ?? (globalThis.fetch?.bind(globalThis) as FetchLike | undefined);\n\n return async ({ system, tools, messages, signal }) => {\n if (!doFetch) throw new Error(\"driverkit: no fetch available; pass one\");\n\n const response = await doFetch(url, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", ...options.headers },\n body: JSON.stringify({ system, tools, messages }),\n ...(signal ? { signal } : {}),\n });\n\n if (!response.ok) {\n // Thrown, not returned as empty prose. A 500 from your own backend is\n // not the model declining to act, and swallowing it would surface as an\n // agent that silently stops having opinions. The loop lets it propagate\n // to the caller of `drive`, which is where a retry or a visible error\n // belongs.\n // With the body, because the body is where the diagnosis is. A backend\n // that answers `{\"error\": \"no API key configured\"}` has already told you\n // what is wrong; a panel that renders `answered 503` sends somebody to\n // read server logs for a sentence that was in the response all along.\n const detail = await detailOf(response);\n throw new Error(\n `driverkit: ${url} answered ${response.status}` + (detail ? ` — ${detail}` : \"\"),\n );\n }\n\n const body = (await response.json()) as { text?: unknown; calls?: unknown };\n const calls = Array.isArray(body.calls) ? (body.calls as ToolCall[]) : undefined;\n const result: ThinkResult = {\n ...(typeof body.text === \"string\" && body.text ? { text: body.text } : {}),\n ...(calls && calls.length ? { calls } : {}),\n };\n return result;\n };\n}\n\n/** How much of an error body may reach the thrown message. Enough for a\n * sentence, short enough that an HTML error page or a stack trace cannot turn\n * an exception into a wall of text in somebody's chat panel. */\nconst DETAIL_LIMIT = 400;\n\n/**\n * The most useful sentence an error response has to offer, or `\"\"`.\n *\n * Three shapes, in the order they are worth having. A JSON body with an\n * `error` string is a backend speaking on purpose and is used verbatim. Plain\n * text — a proxy's `502 Bad Gateway`, a stack trace — is still better than a\n * bare status, so a trimmed snippet of it goes in. An empty body yields\n * nothing, and the message stays as it was.\n *\n * Nothing in here may throw. This runs on the failure path, and an exception\n * raised while explaining an exception replaces the diagnosis with its own —\n * the one failure mode worse than the bug being fixed. So the body read, the\n * JSON parse and the field read are each allowed to fail quietly.\n */\nasync function detailOf(response: ResponseLike): Promise<string> {\n let raw: string;\n try {\n if (typeof response.text === \"function\") {\n raw = await response.text();\n } else {\n // A fake, or a client that only exposes `json()`. Re-serialising is not\n // the prettiest route to a string but it is the only one available, and\n // the `error` field survives it.\n raw = JSON.stringify(await response.json());\n }\n } catch {\n return \"\";\n }\n\n if (typeof raw !== \"string\") return \"\";\n const text = raw.trim();\n if (!text) return \"\";\n\n try {\n const parsed: unknown = JSON.parse(text);\n if (parsed && typeof parsed === \"object\") {\n const error = (parsed as { error?: unknown }).error;\n if (typeof error === \"string\" && error.trim()) return clip(error.trim());\n }\n } catch {\n // Not JSON. Fall through: the raw text is still the best thing to hand on.\n }\n\n return clip(text);\n}\n\nfunction clip(text: string): string {\n const flat = text.replace(/\\s+/g, \" \").trim();\n return flat.length > DETAIL_LIMIT ? flat.slice(0, DETAIL_LIMIT) + \"…\" : flat;\n}\n"]}
@@ -0,0 +1,148 @@
1
+ /**
2
+ * driverkit/agent — pacing and run controls.
3
+ *
4
+ * `drive()` on its own goes as fast as the model answers, which is right for a
5
+ * headless caller and wrong for the case this package was built for: the agent
6
+ * is moving the screen a person is looking at. A run nobody can follow is a run
7
+ * nobody can stop, and "it already accepted them" is not a thing a person
8
+ * should learn after the fact. So there are two mechanisms in here, and they
9
+ * are deliberately separate.
10
+ *
11
+ * **Pacing** is a wait before each verb call. Its only job is to make the run
12
+ * legible — a row appears, glows, then the verb fires — and the one property it
13
+ * must have is that it is *cancellable*. A stop button that takes 600ms to
14
+ * notice is a stop button a person presses twice; worse, a stop pressed during
15
+ * a wait that is not cancellable gets the abort processed only after the wait,
16
+ * which on a page with a 2s pace reads as a frozen panel.
17
+ *
18
+ * **Run controls** are pause, resume and step. These are not an abort: an abort
19
+ * ends the run and abandons the model's calls, whereas a pause holds the run
20
+ * open with its conversation intact so it can go on. Both exist because they
21
+ * answer different questions — "stop, I have seen enough" and "wait, let me
22
+ * read that before you do the next one".
23
+ *
24
+ * Three decisions worth stating, because they are what the tests pin:
25
+ *
26
+ * **1. A pause holds BETWEEN calls, never inside one.** The call in flight runs
27
+ * to completion and its result is fed back. Anything else would need the app's
28
+ * verb to be interruptible halfway, which no app promises and which would leave
29
+ * the screen in a state neither the person nor the model can describe.
30
+ *
31
+ * **2. An abort outranks a pause.** A paused run that could not be stopped
32
+ * would be the worst outcome of the whole feature: the person presses stop, the
33
+ * loop is parked on a promise nobody will resolve, and the panel is wedged.
34
+ * Every wait in here — the pace wait and the control gate both — takes the
35
+ * run's signal and returns immediately when it fires.
36
+ *
37
+ * **3. None of this reaches the model.** Pacing and control state are runtime
38
+ * state. `system` and `tools` are computed once from the manifest and must stay
39
+ * byte-identical across turns, and a model told "the run is paused" would
40
+ * start reasoning about the pause.
41
+ */
42
+ import type { Clock, RunControls } from "./types.ts";
43
+ /**
44
+ * A pace a person can actually watch, in milliseconds.
45
+ *
46
+ * Exported rather than left as a literal in two places, because the choice of
47
+ * default belongs to the *caller* and the two callers want different ones.
48
+ * `drive()` defaults to 0: it is a library primitive driven by backend jobs,
49
+ * tests and CLIs, where nobody is watching and an invented 600ms per call is
50
+ * pure latency added to work that has no eyes on it. A widget mounted in a page
51
+ * defaults to this, because there is a person in front of it by definition.
52
+ * Same shape as `onBeforeCommit`, which is off in `drive` and on in
53
+ * `mountWidget`, and for the same reason.
54
+ *
55
+ * 600ms is a judgement, not a measurement: long enough that a row appearing and
56
+ * then firing reads as two events rather than one flicker, short enough that a
57
+ * five-step run still finishes in about the time a person will sit through.
58
+ */
59
+ export declare const WATCHABLE_PACE = 600;
60
+ /**
61
+ * The real timer, and the only place in this package that touches one.
62
+ *
63
+ * Injectable for one reason: a suite that actually slept its paces would take
64
+ * seconds to assert something that is pure logic, and a slow suite is a suite
65
+ * that gets run less. The tests hand `drive` a fake clock and count the waits.
66
+ */
67
+ export declare const realClock: Clock;
68
+ /** What `paceWait` needs. An object rather than four positional arguments,
69
+ * because three of them are optional and two of those are functions. */
70
+ export interface PaceWaitOptions {
71
+ /** The pace in milliseconds. A function is re-read on every re-arm, which is
72
+ * what lets a live `controls.pace()` reach a wait already running. */
73
+ ms: number | (() => number);
74
+ clock: Clock;
75
+ signal?: AbortSignal;
76
+ /** Subscribe to "the pace may have changed"; returns an unsubscribe. Usually
77
+ * `RunControls.subscribe`. Without it the wait is armed once. */
78
+ watch?: (listener: () => void) => () => void;
79
+ }
80
+ /**
81
+ * Wait out the pace, or return at once if the run is aborted — whichever first.
82
+ *
83
+ * A pace of 0 (or a negative, or a NaN from a parsed input) schedules no timer
84
+ * at all rather than a zero-delay one. Not a micro-optimisation: a headless run
85
+ * is the default, and "pacing off" should mean the pacing code is not in the
86
+ * path, so that a `drive()` with no human watching cannot be made slower by a
87
+ * bug in here.
88
+ *
89
+ * **The wait is re-armed against the pace rather than fixed at the value it
90
+ * started with.** Cutting 5s to 200ms with 4s still to run is exactly the
91
+ * moment somebody is jabbing at the slider, and a wait that rode out its old
92
+ * value would be the thing they are already annoyed about, happening again. So
93
+ * every wake — the timer firing, or the pace changing — recomputes
94
+ * `pace - elapsed`, and a wait already longer than the new pace ends at once.
95
+ * Lengthening works the same way round. Elapsed is measured from when the wait
96
+ * started, so moving the slider never restarts the wait and cannot be used to
97
+ * hold a run open.
98
+ *
99
+ * The abort path resolves rather than rejects, and is checked on every wake.
100
+ * Every caller in the loop checks `signal.aborted` on the next line anyway, and
101
+ * a rejection would turn an ordinary stop into an exception that the loop's one
102
+ * `try` was not written to catch.
103
+ */
104
+ export declare function paceWait({ ms, clock, signal, watch }: PaceWaitOptions): Promise<void>;
105
+ /** Options for `runControls`. */
106
+ export interface RunControlsOptions {
107
+ /** The pace to start with, in milliseconds. `drive`'s own `pace` option
108
+ * overrides it at the start of a run — the run is the thing being paced —
109
+ * and `pace()` then wins over both. */
110
+ pace?: number;
111
+ /**
112
+ * Start paused, so every call needs its own `step()`. This is "step mode",
113
+ * and it is not a second mode: there is no flag for it beyond this, because a
114
+ * `stepMode` that lived alongside `state` would be a second source of truth
115
+ * able to disagree with the first. Step mode IS "paused, and stepped one call
116
+ * at a time".
117
+ */
118
+ stepMode?: boolean;
119
+ }
120
+ /**
121
+ * Pause, resume and step for a run.
122
+ *
123
+ * ```ts
124
+ * const controls = runControls();
125
+ * drive(driver, { think, task, controls, pace: WATCHABLE_PACE, signal });
126
+ * controls.pause(); // finishes the call in flight, then holds
127
+ * controls.step(); // exactly one more call, then holds again
128
+ * controls.resume(); // carry on
129
+ * ```
130
+ *
131
+ * **Why an object passed in and not a handle returned from `drive`.** `drive`
132
+ * returns a promise that settles when the run is *over*, so anything returned
133
+ * from it is unreachable during the only window in which pausing means
134
+ * anything. The alternatives were to change `drive` to return
135
+ * `{ controls, done }` — which breaks every existing caller and every test that
136
+ * awaits the outcome directly — or to hand the controls out through a callback,
137
+ * which is a handle with extra steps. Passing one in keeps `drive`'s signature,
138
+ * matches `AbortController`/`AbortSignal` (which this sits beside and must not
139
+ * contradict), and lets a caller build the control surface before the run
140
+ * starts and reuse it across runs.
141
+ *
142
+ * It is a plain object with methods: no DOM, no events, no framework. A CLI can
143
+ * call `pause()` from a keypress handler, a test can call it from inside a
144
+ * scripted `think`, and the widget can wire it to buttons without this package
145
+ * knowing a button exists.
146
+ */
147
+ export declare function runControls(options?: RunControlsOptions): RunControls;
148
+ //# sourceMappingURL=control.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"control.d.ts","sourceRoot":"","sources":["../../src/agent/control.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAgB,WAAW,EAAE,MAAM,YAAY,CAAC;AAEnE;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,cAAc,MAAM,CAAC;AAElC;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,EAAE,KAIvB,CAAC;AAEF;yEACyE;AACzE,MAAM,WAAW,eAAe;IAC9B;2EACuE;IACvE,EAAE,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,CAAC;IAC5B,KAAK,EAAE,KAAK,CAAC;IACb,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB;sEACkE;IAClE,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,IAAI,KAAK,MAAM,IAAI,CAAC;CAC9C;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,QAAQ,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAgDrF;AAmBD,iCAAiC;AACjC,MAAM,WAAW,kBAAkB;IACjC;;4CAEwC;IACxC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,WAAW,CAAC,OAAO,GAAE,kBAAuB,GAAG,WAAW,CAyJzE"}