driverkit 0.0.0-stage → 0.0.1
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.
- package/CONTROLS.md +578 -0
- package/REACT.md +477 -0
- package/README.md +104 -2
- package/dist/agent/backend.d.ts +69 -0
- package/dist/agent/backend.d.ts.map +1 -0
- package/dist/agent/backend.js +130 -0
- package/dist/agent/backend.js.map +1 -0
- package/dist/agent/control.d.ts +148 -0
- package/dist/agent/control.d.ts.map +1 -0
- package/dist/agent/control.js +342 -0
- package/dist/agent/control.js.map +1 -0
- package/dist/agent/index.d.ts +9 -0
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/index.js +6 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/agent/loop.d.ts +136 -0
- package/dist/agent/loop.d.ts.map +1 -0
- package/dist/agent/loop.js +824 -0
- package/dist/agent/loop.js.map +1 -0
- package/dist/agent/render.d.ts +173 -0
- package/dist/agent/render.d.ts.map +1 -0
- package/dist/agent/render.js +425 -0
- package/dist/agent/render.js.map +1 -0
- package/dist/agent/tools.d.ts +138 -0
- package/dist/agent/tools.d.ts.map +1 -0
- package/dist/agent/tools.js +622 -0
- package/dist/agent/tools.js.map +1 -0
- package/dist/agent/types.d.ts +566 -0
- package/dist/agent/types.d.ts.map +1 -0
- package/dist/agent/types.js +32 -0
- package/dist/agent/types.js.map +1 -0
- package/dist/browser/budget.d.ts +92 -0
- package/dist/browser/budget.d.ts.map +1 -0
- package/dist/browser/budget.js +151 -0
- package/dist/browser/budget.js.map +1 -0
- package/dist/browser/connect.d.ts +368 -0
- package/dist/browser/connect.d.ts.map +1 -0
- package/dist/browser/connect.js +1038 -0
- package/dist/browser/connect.js.map +1 -0
- package/dist/browser/elsewhere.d.ts +89 -0
- package/dist/browser/elsewhere.d.ts.map +1 -0
- package/dist/browser/elsewhere.js +91 -0
- package/dist/browser/elsewhere.js.map +1 -0
- package/dist/browser/frames.d.ts +85 -0
- package/dist/browser/frames.d.ts.map +1 -0
- package/dist/browser/frames.js +11 -0
- package/dist/browser/frames.js.map +1 -0
- package/dist/browser/index.d.ts +8 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +9 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/check/check.d.ts +171 -0
- package/dist/check/check.d.ts.map +1 -0
- package/dist/check/check.js +666 -0
- package/dist/check/check.js.map +1 -0
- package/dist/check/index.d.ts +3 -0
- package/dist/check/index.d.ts.map +1 -0
- package/dist/check/index.js +2 -0
- package/dist/check/index.js.map +1 -0
- package/dist/check/types.d.ts +149 -0
- package/dist/check/types.d.ts.map +1 -0
- package/dist/check/types.js +29 -0
- package/dist/check/types.js.map +1 -0
- package/dist/controls/controls.d.ts +198 -0
- package/dist/controls/controls.d.ts.map +1 -0
- package/dist/controls/controls.js +742 -0
- package/dist/controls/controls.js.map +1 -0
- package/dist/controls/dom.d.ts +108 -0
- package/dist/controls/dom.d.ts.map +1 -0
- package/dist/controls/dom.js +56 -0
- package/dist/controls/dom.js.map +1 -0
- package/dist/controls/index.d.ts +26 -0
- package/dist/controls/index.d.ts.map +1 -0
- package/dist/controls/index.js +23 -0
- package/dist/controls/index.js.map +1 -0
- package/dist/controls/rows.d.ts +66 -0
- package/dist/controls/rows.d.ts.map +1 -0
- package/dist/controls/rows.js +127 -0
- package/dist/controls/rows.js.map +1 -0
- package/dist/core/index.d.ts +3 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +15 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/registry.d.ts +192 -0
- package/dist/core/registry.d.ts.map +1 -0
- package/dist/core/registry.js +2799 -0
- package/dist/core/registry.js.map +1 -0
- package/dist/core/types.d.ts +2468 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/core/types.js +19 -0
- package/dist/core/types.js.map +1 -0
- package/dist/otel/index.d.ts +122 -0
- package/dist/otel/index.d.ts.map +1 -0
- package/dist/otel/index.js +157 -0
- package/dist/otel/index.js.map +1 -0
- package/dist/react/index.d.ts +191 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +547 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/runtime.d.ts +95 -0
- package/dist/react/runtime.d.ts.map +1 -0
- package/dist/react/runtime.js +54 -0
- package/dist/react/runtime.js.map +1 -0
- package/dist/react/store.d.ts +333 -0
- package/dist/react/store.d.ts.map +1 -0
- package/dist/react/store.js +695 -0
- package/dist/react/store.js.map +1 -0
- package/dist/relay/auth.d.ts +244 -0
- package/dist/relay/auth.d.ts.map +1 -0
- package/dist/relay/auth.js +391 -0
- package/dist/relay/auth.js.map +1 -0
- package/dist/relay/frames.d.ts +141 -0
- package/dist/relay/frames.d.ts.map +1 -0
- package/dist/relay/frames.js +20 -0
- package/dist/relay/frames.js.map +1 -0
- package/dist/relay/index.d.ts +8 -0
- package/dist/relay/index.d.ts.map +1 -0
- package/dist/relay/index.js +4 -0
- package/dist/relay/index.js.map +1 -0
- package/dist/relay/relay.d.ts +277 -0
- package/dist/relay/relay.d.ts.map +1 -0
- package/dist/relay/relay.js +1026 -0
- package/dist/relay/relay.js.map +1 -0
- package/dist/relay/serve.d.ts +33 -0
- package/dist/relay/serve.d.ts.map +1 -0
- package/dist/relay/serve.js +86 -0
- package/dist/relay/serve.js.map +1 -0
- package/dist/widget/chat.d.ts +290 -0
- package/dist/widget/chat.d.ts.map +1 -0
- package/dist/widget/chat.js +486 -0
- package/dist/widget/chat.js.map +1 -0
- package/dist/widget/css.d.ts +49 -0
- package/dist/widget/css.d.ts.map +1 -0
- package/dist/widget/css.js +532 -0
- package/dist/widget/css.js.map +1 -0
- package/dist/widget/dom.d.ts +143 -0
- package/dist/widget/dom.d.ts.map +1 -0
- package/dist/widget/dom.js +27 -0
- package/dist/widget/dom.js.map +1 -0
- package/dist/widget/highlight.d.ts +64 -0
- package/dist/widget/highlight.d.ts.map +1 -0
- package/dist/widget/highlight.js +136 -0
- package/dist/widget/highlight.js.map +1 -0
- package/dist/widget/index.d.ts +9 -0
- package/dist/widget/index.d.ts.map +1 -0
- package/dist/widget/index.js +20 -0
- package/dist/widget/index.js.map +1 -0
- package/dist/widget/position.d.ts +166 -0
- package/dist/widget/position.d.ts.map +1 -0
- package/dist/widget/position.js +497 -0
- package/dist/widget/position.js.map +1 -0
- package/dist/widget/settings.d.ts +116 -0
- package/dist/widget/settings.d.ts.map +1 -0
- package/dist/widget/settings.js +117 -0
- package/dist/widget/settings.js.map +1 -0
- package/dist/widget/widget.d.ts +442 -0
- package/dist/widget/widget.d.ts.map +1 -0
- package/dist/widget/widget.js +2005 -0
- package/dist/widget/widget.js.map +1 -0
- package/package.json +144 -4
|
@@ -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"}
|
|
@@ -0,0 +1,342 @@
|
|
|
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
|
+
/**
|
|
43
|
+
* A pace a person can actually watch, in milliseconds.
|
|
44
|
+
*
|
|
45
|
+
* Exported rather than left as a literal in two places, because the choice of
|
|
46
|
+
* default belongs to the *caller* and the two callers want different ones.
|
|
47
|
+
* `drive()` defaults to 0: it is a library primitive driven by backend jobs,
|
|
48
|
+
* tests and CLIs, where nobody is watching and an invented 600ms per call is
|
|
49
|
+
* pure latency added to work that has no eyes on it. A widget mounted in a page
|
|
50
|
+
* defaults to this, because there is a person in front of it by definition.
|
|
51
|
+
* Same shape as `onBeforeCommit`, which is off in `drive` and on in
|
|
52
|
+
* `mountWidget`, and for the same reason.
|
|
53
|
+
*
|
|
54
|
+
* 600ms is a judgement, not a measurement: long enough that a row appearing and
|
|
55
|
+
* then firing reads as two events rather than one flicker, short enough that a
|
|
56
|
+
* five-step run still finishes in about the time a person will sit through.
|
|
57
|
+
*/
|
|
58
|
+
export const WATCHABLE_PACE = 600;
|
|
59
|
+
/**
|
|
60
|
+
* The real timer, and the only place in this package that touches one.
|
|
61
|
+
*
|
|
62
|
+
* Injectable for one reason: a suite that actually slept its paces would take
|
|
63
|
+
* seconds to assert something that is pure logic, and a slow suite is a suite
|
|
64
|
+
* that gets run less. The tests hand `drive` a fake clock and count the waits.
|
|
65
|
+
*/
|
|
66
|
+
export const realClock = {
|
|
67
|
+
set: (fn, ms) => setTimeout(fn, ms),
|
|
68
|
+
clear: (handle) => clearTimeout(handle),
|
|
69
|
+
now: () => Date.now(),
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Wait out the pace, or return at once if the run is aborted — whichever first.
|
|
73
|
+
*
|
|
74
|
+
* A pace of 0 (or a negative, or a NaN from a parsed input) schedules no timer
|
|
75
|
+
* at all rather than a zero-delay one. Not a micro-optimisation: a headless run
|
|
76
|
+
* is the default, and "pacing off" should mean the pacing code is not in the
|
|
77
|
+
* path, so that a `drive()` with no human watching cannot be made slower by a
|
|
78
|
+
* bug in here.
|
|
79
|
+
*
|
|
80
|
+
* **The wait is re-armed against the pace rather than fixed at the value it
|
|
81
|
+
* started with.** Cutting 5s to 200ms with 4s still to run is exactly the
|
|
82
|
+
* moment somebody is jabbing at the slider, and a wait that rode out its old
|
|
83
|
+
* value would be the thing they are already annoyed about, happening again. So
|
|
84
|
+
* every wake — the timer firing, or the pace changing — recomputes
|
|
85
|
+
* `pace - elapsed`, and a wait already longer than the new pace ends at once.
|
|
86
|
+
* Lengthening works the same way round. Elapsed is measured from when the wait
|
|
87
|
+
* started, so moving the slider never restarts the wait and cannot be used to
|
|
88
|
+
* hold a run open.
|
|
89
|
+
*
|
|
90
|
+
* The abort path resolves rather than rejects, and is checked on every wake.
|
|
91
|
+
* Every caller in the loop checks `signal.aborted` on the next line anyway, and
|
|
92
|
+
* a rejection would turn an ordinary stop into an exception that the loop's one
|
|
93
|
+
* `try` was not written to catch.
|
|
94
|
+
*/
|
|
95
|
+
export function paceWait({ ms, clock, signal, watch }) {
|
|
96
|
+
const pace = typeof ms === "function" ? ms : () => ms;
|
|
97
|
+
const now = clock.now ? () => clock.now() : Date.now;
|
|
98
|
+
if (!(pace() > 0) || signal?.aborted)
|
|
99
|
+
return Promise.resolve();
|
|
100
|
+
return new Promise((resolve) => {
|
|
101
|
+
const started = now();
|
|
102
|
+
let handle;
|
|
103
|
+
let settled = false;
|
|
104
|
+
let unwatch;
|
|
105
|
+
const finish = () => {
|
|
106
|
+
if (settled)
|
|
107
|
+
return;
|
|
108
|
+
settled = true;
|
|
109
|
+
if (handle !== undefined)
|
|
110
|
+
clock.clear(handle);
|
|
111
|
+
unwatch?.();
|
|
112
|
+
signal?.removeEventListener?.("abort", finish);
|
|
113
|
+
resolve();
|
|
114
|
+
};
|
|
115
|
+
/** Re-read the pace and schedule what is left of it, or end the wait.
|
|
116
|
+
*
|
|
117
|
+
* Also the timer's own callback: a timer that fires lands here, finds
|
|
118
|
+
* nothing left and finishes, so "the timer fired" and "the pace moved" are
|
|
119
|
+
* one piece of arithmetic rather than two that can come to disagree. */
|
|
120
|
+
const arm = () => {
|
|
121
|
+
if (settled)
|
|
122
|
+
return;
|
|
123
|
+
if (signal?.aborted)
|
|
124
|
+
return finish();
|
|
125
|
+
if (handle !== undefined) {
|
|
126
|
+
clock.clear(handle);
|
|
127
|
+
handle = undefined;
|
|
128
|
+
}
|
|
129
|
+
const remaining = pace() - (now() - started);
|
|
130
|
+
// `!(remaining > 0)` rather than `<= 0`, so a NaN that got past the check
|
|
131
|
+
// above ends the wait instead of scheduling a timer for NaN.
|
|
132
|
+
if (!(remaining > 0))
|
|
133
|
+
return finish();
|
|
134
|
+
// Assigned after the call, and checked, because a fake clock in a test may
|
|
135
|
+
// fire synchronously — in which case `arm` has already run again and this
|
|
136
|
+
// handle is the stale one.
|
|
137
|
+
const scheduled = clock.set(arm, remaining);
|
|
138
|
+
if (!settled && handle === undefined)
|
|
139
|
+
handle = scheduled;
|
|
140
|
+
};
|
|
141
|
+
unwatch = watch?.(arm);
|
|
142
|
+
signal?.addEventListener?.("abort", finish, { once: true });
|
|
143
|
+
arm();
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* A pace value, or `fallback` if it is not one.
|
|
148
|
+
*
|
|
149
|
+
* Three rules, and the asymmetry between them is the point. A negative becomes
|
|
150
|
+
* 0, because "less than no wait" has exactly one sensible reading. Anything
|
|
151
|
+
* non-finite — `NaN` from a parsed input, `Infinity` from a divide, `undefined`
|
|
152
|
+
* from an unset option — is **refused**, keeping what was there before: reading
|
|
153
|
+
* it as 0 would make the agent run faster than the person asked, and reading
|
|
154
|
+
* `Infinity` as a delay would park the run on a timer nobody meant to set.
|
|
155
|
+
* Neither is a thing to guess at, and the current pace is the one value that is
|
|
156
|
+
* certainly not a surprise.
|
|
157
|
+
*/
|
|
158
|
+
function clean(ms, fallback) {
|
|
159
|
+
if (typeof ms !== "number" || !Number.isFinite(ms))
|
|
160
|
+
return fallback;
|
|
161
|
+
return ms < 0 ? 0 : ms;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Pause, resume and step for a run.
|
|
165
|
+
*
|
|
166
|
+
* ```ts
|
|
167
|
+
* const controls = runControls();
|
|
168
|
+
* drive(driver, { think, task, controls, pace: WATCHABLE_PACE, signal });
|
|
169
|
+
* controls.pause(); // finishes the call in flight, then holds
|
|
170
|
+
* controls.step(); // exactly one more call, then holds again
|
|
171
|
+
* controls.resume(); // carry on
|
|
172
|
+
* ```
|
|
173
|
+
*
|
|
174
|
+
* **Why an object passed in and not a handle returned from `drive`.** `drive`
|
|
175
|
+
* returns a promise that settles when the run is *over*, so anything returned
|
|
176
|
+
* from it is unreachable during the only window in which pausing means
|
|
177
|
+
* anything. The alternatives were to change `drive` to return
|
|
178
|
+
* `{ controls, done }` — which breaks every existing caller and every test that
|
|
179
|
+
* awaits the outcome directly — or to hand the controls out through a callback,
|
|
180
|
+
* which is a handle with extra steps. Passing one in keeps `drive`'s signature,
|
|
181
|
+
* matches `AbortController`/`AbortSignal` (which this sits beside and must not
|
|
182
|
+
* contradict), and lets a caller build the control surface before the run
|
|
183
|
+
* starts and reuse it across runs.
|
|
184
|
+
*
|
|
185
|
+
* It is a plain object with methods: no DOM, no events, no framework. A CLI can
|
|
186
|
+
* call `pause()` from a keypress handler, a test can call it from inside a
|
|
187
|
+
* scripted `think`, and the widget can wire it to buttons without this package
|
|
188
|
+
* knowing a button exists.
|
|
189
|
+
*/
|
|
190
|
+
export function runControls(options = {}) {
|
|
191
|
+
let state = options.stepMode ? "paused" : "running";
|
|
192
|
+
/**
|
|
193
|
+
* Outstanding `step()` permits — in practice 0 or 1.
|
|
194
|
+
*
|
|
195
|
+
* A permit rather than a "run one more call" boolean because it has to be
|
|
196
|
+
* spendable: `step()` has to mean exactly one call, and the only way to be
|
|
197
|
+
* sure of that is for the thing granting it to be consumed by the call that
|
|
198
|
+
* uses it.
|
|
199
|
+
*/
|
|
200
|
+
let permits = 0;
|
|
201
|
+
/** The live pace. Owned here rather than in `drive`, because it has to
|
|
202
|
+
* outlive any single wait and be settable from outside the loop. */
|
|
203
|
+
let paceMs = clean(options.pace, 0);
|
|
204
|
+
/** Parked gates, each of which re-checks the state when woken. A Set and not
|
|
205
|
+
* an array that gets emptied: one `step()` wakes everybody and only one of
|
|
206
|
+
* them may consume the permit, so the losers have to stay parked. */
|
|
207
|
+
const waiters = new Set();
|
|
208
|
+
const wake = () => {
|
|
209
|
+
for (const waiter of [...waiters])
|
|
210
|
+
waiter();
|
|
211
|
+
};
|
|
212
|
+
/** Subscribers to "something here changed". Kept apart from `waiters`: one
|
|
213
|
+
* set is the loop being let through, the other is a UI being told, and
|
|
214
|
+
* conflating them would mean a UI listener could hold up the run. */
|
|
215
|
+
const listeners = new Set();
|
|
216
|
+
const notify = () => {
|
|
217
|
+
// One broken listener must not stop the others being told, and above all
|
|
218
|
+
// must not stop `drive`'s own re-arm being told, since the live pace rides
|
|
219
|
+
// on it — a panel whose redraw throws would otherwise silently take pacing
|
|
220
|
+
// down with it. So everybody is told first and the failure is raised after.
|
|
221
|
+
let failure;
|
|
222
|
+
let failed = false;
|
|
223
|
+
for (const listener of [...listeners]) {
|
|
224
|
+
try {
|
|
225
|
+
listener();
|
|
226
|
+
}
|
|
227
|
+
catch (err) {
|
|
228
|
+
if (!failed) {
|
|
229
|
+
failed = true;
|
|
230
|
+
failure = err;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
// Raised rather than swallowed, and raised synchronously at whoever called
|
|
235
|
+
// `pause`/`step`/`resume`/`pace`: it is their listener and their stack, and
|
|
236
|
+
// a silently eaten exception in a UI callback is a bug that gets found
|
|
237
|
+
// weeks later. The control change itself has already happened and stands —
|
|
238
|
+
// a listener cannot veto it.
|
|
239
|
+
if (failed)
|
|
240
|
+
throw failure;
|
|
241
|
+
};
|
|
242
|
+
return {
|
|
243
|
+
get state() {
|
|
244
|
+
return state;
|
|
245
|
+
},
|
|
246
|
+
get permits() {
|
|
247
|
+
return permits;
|
|
248
|
+
},
|
|
249
|
+
get paceMs() {
|
|
250
|
+
return paceMs;
|
|
251
|
+
},
|
|
252
|
+
pause() {
|
|
253
|
+
const was = `${state}:${permits}`;
|
|
254
|
+
state = "paused";
|
|
255
|
+
// A pending step is dropped. "Pause" from a person who just pressed step
|
|
256
|
+
// means "no, not even that one" — honouring the permit would run a call
|
|
257
|
+
// after they asked for the run to hold.
|
|
258
|
+
permits = 0;
|
|
259
|
+
if (was !== `${state}:${permits}`)
|
|
260
|
+
notify();
|
|
261
|
+
},
|
|
262
|
+
resume() {
|
|
263
|
+
const was = `${state}:${permits}`;
|
|
264
|
+
state = "running";
|
|
265
|
+
permits = 0;
|
|
266
|
+
wake();
|
|
267
|
+
if (was !== `${state}:${permits}`)
|
|
268
|
+
notify();
|
|
269
|
+
},
|
|
270
|
+
step() {
|
|
271
|
+
// Paused with one permit, whichever state we were in. Stepping from a
|
|
272
|
+
// running run is a legitimate thing to ask for — "do the next one and
|
|
273
|
+
// then wait" — and it must not need two calls to express.
|
|
274
|
+
const was = `${state}:${permits}`;
|
|
275
|
+
state = "paused";
|
|
276
|
+
permits = 1;
|
|
277
|
+
wake();
|
|
278
|
+
if (was !== `${state}:${permits}`)
|
|
279
|
+
notify();
|
|
280
|
+
},
|
|
281
|
+
pace(ms) {
|
|
282
|
+
const next = clean(ms, paceMs);
|
|
283
|
+
if (next === paceMs)
|
|
284
|
+
return;
|
|
285
|
+
paceMs = next;
|
|
286
|
+
// Last, so a listener that reads `paceMs` — `drive`'s re-arm included —
|
|
287
|
+
// sees the new value rather than the one it is replacing.
|
|
288
|
+
notify();
|
|
289
|
+
},
|
|
290
|
+
subscribe(listener) {
|
|
291
|
+
listeners.add(listener);
|
|
292
|
+
return () => {
|
|
293
|
+
listeners.delete(listener);
|
|
294
|
+
};
|
|
295
|
+
},
|
|
296
|
+
gate(what, signal) {
|
|
297
|
+
// Aborted runs are never held. The loop checks `signal.aborted` straight
|
|
298
|
+
// after this returns and will end the run there; parking here would wedge
|
|
299
|
+
// it instead.
|
|
300
|
+
if (signal?.aborted)
|
|
301
|
+
return Promise.resolve();
|
|
302
|
+
if (state === "running")
|
|
303
|
+
return Promise.resolve();
|
|
304
|
+
if (permits > 0) {
|
|
305
|
+
// Only a verb call spends the permit. A model round trip rides along on
|
|
306
|
+
// it unspent, because `step()` promises one more CALL and a call cannot
|
|
307
|
+
// happen without the turn that asks for it — charging the permit to the
|
|
308
|
+
// `think` would make every step need two presses, with the second one
|
|
309
|
+
// doing the thing the first one asked for.
|
|
310
|
+
if (what === "call")
|
|
311
|
+
permits--;
|
|
312
|
+
return Promise.resolve();
|
|
313
|
+
}
|
|
314
|
+
return new Promise((resolve) => {
|
|
315
|
+
let settled = false;
|
|
316
|
+
const finish = () => {
|
|
317
|
+
if (settled)
|
|
318
|
+
return;
|
|
319
|
+
settled = true;
|
|
320
|
+
waiters.delete(attempt);
|
|
321
|
+
signal?.removeEventListener?.("abort", finish);
|
|
322
|
+
resolve();
|
|
323
|
+
};
|
|
324
|
+
const attempt = () => {
|
|
325
|
+
if (settled)
|
|
326
|
+
return;
|
|
327
|
+
if (state === "running")
|
|
328
|
+
return finish();
|
|
329
|
+
if (permits > 0) {
|
|
330
|
+
if (what === "call")
|
|
331
|
+
permits--;
|
|
332
|
+
finish();
|
|
333
|
+
}
|
|
334
|
+
// Still paused with nothing granted: stay parked.
|
|
335
|
+
};
|
|
336
|
+
waiters.add(attempt);
|
|
337
|
+
signal?.addEventListener?.("abort", finish, { once: true });
|
|
338
|
+
});
|
|
339
|
+
},
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
//# sourceMappingURL=control.js.map
|