@hackbuild/agents-views 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Moheeb Zara
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,154 @@
1
- # Temporary Holding Version
1
+ # @hackbuild/agents-views
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
+ The brain bars, the associations table and the eye card of a simulated animal, as views you mount on any page with the hackbuild-ui look.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@hackbuild/agents-views)](https://www.npmjs.com/package/@hackbuild/agents-views) [![licence MIT](https://img.shields.io/badge/licence-MIT-blue)](../../LICENSE) ![gzip 4.4 kB measured](https://img.shields.io/badge/gzip-4.4%20kB-blue) ![types included](https://img.shields.io/badge/types-included-blue)
6
+
7
+ ## What it does
8
+
9
+ - Draws what the animal is doing and why, what each act is worth now with the chosen one in pink, and how much it needs each thing.
10
+ - Draws what it has learned: cues by acts, each cell the net strength from 0 to 99, with how much it still pays attention to each cue.
11
+ - Makes an element the eye card: a canvas drawn from inside the animal's own eye, a switch for whose eyes, and a mode line.
12
+ - Ships each view three ways that draw the same markup: a plain function over a host element, a custom element and a Vue component.
13
+ - Reads @hackbuild/drives and @hackbuild/cameras objects by their shape, so it has no runtime dependency on either.
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ npm install @hackbuild/agents-views @hackbuild/drives @virgilvox/hackbuild-ui
19
+ ```
20
+
21
+ `@virgilvox/hackbuild-ui` (0.10 or 0.11) is a peer: the views write its classes and never style themselves, so load its `hackbuild.css` on the page. `vue` (3.5 or later) is an optional peer, needed only for the `@hackbuild/agents-views/vue` entry. @hackbuild/drives is what the quick start feeds the views; @hackbuild/cameras gives the eye card its `FirstPerson` eye. Neither is a dependency of this package.
22
+
23
+ ## Quick start
24
+
25
+ ```ts
26
+ import { associationsState, associationsTable, drivesBars, drivesBarsState } from "@hackbuild/agents-views";
27
+ import { Chooser, CueLearner, Drives, load, seededRng } from "@hackbuild/drives";
28
+
29
+ // the brain: two drives, three acts and a learner, all seeded
30
+ await load();
31
+ const rng = seededRng(7);
32
+ const drives = new Drives({ hunger: 1, play: 0.8 });
33
+ const chooser = new Chooser({ rng, options: ["idle", "eat", "fetch"] as const });
34
+ const learner = new CueLearner({ rng, actions: ["sit", "paw"] as const });
35
+
36
+ // the views: mount once, update each tick
37
+ const bars = drivesBars(document.body.appendChild(document.createElement("div")));
38
+ const table = associationsTable(document.body.appendChild(document.createElement("div")), { onReset: () => location.reload() });
39
+ let now = 0;
40
+ setInterval(() => {
41
+ now += 0.5;
42
+ drives.grow(0.5, { hunger: 0.02, play: 0.03 });
43
+ const d = chooser.update(now, { idle: 0.1, eat: drives.rewardOf({ hunger: -0.5 }), fetch: drives.rewardOf({ play: -0.4 }) });
44
+ bars.update(drivesBarsState(d, drives, { now }));
45
+ table.update(associationsState(learner));
46
+ }, 500);
47
+ ```
48
+
49
+ ## Live example
50
+
51
+ Three demo pages run one yard built in code through a scripted day, so the views move with nobody at the keys: [drive bars](https://hackbuild.github.io/hackbuild-agents/drives-bars/), [associations table](https://hackbuild.github.io/hackbuild-agents/associations-table/) and [eye card](https://hackbuild.github.io/hackbuild-agents/eye-inset/). The suite's [creature with drives](https://hackbuild.github.io/hackbuild-suite/#/examples/think/drives) puts the bars beside a running animal.
52
+
53
+ ## Concepts
54
+
55
+ ### a view is a function over a host
56
+
57
+ `drivesBars(host)`, `associationsTable(host, options)` and `eyeInset(host, options)` take an element you own, replace its children with the view and return a handle. Call `update(state)` each tick; `dispose()` empties the host. The drive and utility rows are rebuilt only when their keys change, so the bars move in place and a screen reader is not flooded.
58
+
59
+ ### state is plain data
60
+
61
+ Each view draws a plain object you can build by hand: `DrivesBarsState` (behaviour, why, utilities, drives, an optional pending switch) and `AssociationsState` (actions, cue rows, the last rewarded cell, a line on the last trial). `drivesBarsState(decision, drives, { now, seconds })` builds the first from a `Chooser` decision and a `Drives` object; `associationsState(learner)` builds the second from a `CueLearner`, with net strength as excitation minus inhibition.
62
+
63
+ ```ts
64
+ import { drivesBars } from "@hackbuild/agents-views";
65
+
66
+ const bars = drivesBars(document.querySelector("#brain") as HTMLElement);
67
+ bars.update({ behavior: "fetch", why: "play is high", utilities: { idle: 0.1, fetch: 0.6 }, drives: { play: 0.8, hunger: 0.3 } });
68
+ ```
69
+
70
+ ### the eye card draws inside the eye
71
+
72
+ `eyeInset(host, { who, draw })` takes a list of who entries, each with an optional `eye`. `frame()` calls your `draw(canvas, who)` inside `who.eye.render`, so a `FirstPerson` from @hackbuild/cameras hides the animal's own head for that render only. A string returned from `draw` becomes the mode line, such as "dichromat". Pass `canvas` when a renderer owns one already. The card is a hackbuild-ui inset marked `data-ux="inset"`.
73
+
74
+ ### custom elements and Vue
75
+
76
+ `defineViews()` registers `hb-drives-bars`, `hb-associations-table` (fires `reset`) and `hb-eye-inset` (set `.options`, call `frame()`, fires `who`); it is safe to call again. The single file build `dist/agents-views.iife.js` registers them when its script tag runs, so a page opened from file:// needs no bundler. `@hackbuild/agents-views/vue` has `DrivesBars`, `AssociationsTable` (emits `reset`) and `EyeInset` (v-model:selected and an exposed `frame()`).
77
+
78
+ ```html
79
+ <script src="agents-views.iife.js"></script>
80
+ <hb-drives-bars id="brain"></hb-drives-bars>
81
+ <script>document.getElementById("brain").state = { behavior: "idle", utilities: { idle: 0.1 }, drives: { hunger: 0.4 } };</script>
82
+ ```
83
+
84
+ ## API overview
85
+
86
+ | export | what it does |
87
+ |---|---|
88
+ | [`drivesBars`](../../docs/api/agents-views/index.md#drivesbars) | the behaviour, utility and drive panels in a host |
89
+ | [`drivesBarsState`](../../docs/api/agents-views/index.md#drivesbarsstate) | the bars' state from a `Chooser` decision and the drives |
90
+ | [`associationsTable`](../../docs/api/agents-views/index.md#associationstable) | the cues by acts table with attention and reset |
91
+ | [`associationsState`](../../docs/api/agents-views/index.md#associationsstate) | the table's state from a `CueLearner` |
92
+ | [`eyeInset`](../../docs/api/agents-views/index.md#eyeinset) | the eye card: canvas, who switch and mode line |
93
+ | [`defineViews`](../../docs/api/agents-views/index.md#defineviews) | registers the three custom elements |
94
+ | [`ELEMENT_NAMES`](../../docs/api/agents-views/index.md#element_names) | the tag names |
95
+ | [`DrivesBars`](../../docs/api/agents-views/vue.md#drivesbars) | the bars as a Vue component |
96
+ | [`AssociationsTable`](../../docs/api/agents-views/vue.md#associationstable) | the table as a Vue component |
97
+ | [`EyeInset`](../../docs/api/agents-views/vue.md#eyeinset) | the eye card as a Vue component |
98
+
99
+ The full reference is in [docs/api/agents-views](../../docs/api/agents-views/README.md).
100
+
101
+ ## Browser support
102
+
103
+ | feature | needs | Chrome | Safari | Firefox | phone |
104
+ |---|---|---|---|---|---|
105
+ | the three views | DOM and CSS custom properties | yes | yes (inferred) | yes (inferred) | yes (inferred) |
106
+ | custom elements | `customElements` | yes | yes (inferred) | yes (inferred) | yes (inferred) |
107
+ | eye card canvas | whatever your `draw` uses: 2D canvas or WebGL | yes | as your renderer | as your renderer | as your renderer |
108
+ | single file build from file:// | a classic script | yes | yes (inferred) | yes (inferred) | unknown |
109
+
110
+ The views draw no frames of their own: they cost what `update` and your `draw` cost.
111
+
112
+ ## Errors and troubleshooting
113
+
114
+ | message | cause | what to do |
115
+ |---|---|---|
116
+ | `@hackbuild/agents-views: eyeInset needs at least one who` | `eyeInset` got an empty `who` list | pass at least one who entry |
117
+
118
+ A view with no hackbuild-ui stylesheet on the page draws unstyled bars: load `hackbuild.css` from @virgilvox/hackbuild-ui. A custom element whose `.state` is never set stays empty.
119
+
120
+ ## Works with
121
+
122
+ - [@hackbuild/drives](../drives/README.md) gives the `Chooser`, `Drives` and `CueLearner` the bars and the table read.
123
+ - [@hackbuild/cameras](../cameras/README.md) gives the `FirstPerson` eye the card draws inside.
124
+ - [@hackbuild/scenario](../scenario/README.md) runs the scripted day of the demo pages.
125
+
126
+ ## Changelog and licences
127
+
128
+ Changes are in the repository [CHANGELOG](../../CHANGELOG.md). Code is MIT ([LICENSE](../../LICENSE)); this README is CC-BY-4.0 with its code samples also MIT.
129
+
130
+ ## What is verified, and what is not
131
+
132
+ ### Verified on this machine
133
+
134
+ | date | check | result |
135
+ |---|---|---|
136
+ | 2026-11-25 | `npx vitest run packages/agents-views` in happy-dom: utility rows with one current row from a real `Chooser` decision, drive bars that move in place, the pending switch line, the table from a real `CueLearner` with the attn column and reset, the eye card drawing inside a real `FirstPerson` (head at 0.001 during the draw, restored after), the custom elements, the Vue components following their props | 8 of 8 tests pass (counted) |
137
+ | 2026-11-25 | `node tools/smoke-views.mjs` in headless Chrome on the built pages | drive bars moved within 3 s, reset left the three prior cues, eye canvas brightness spread 212 of 255 (measured) |
138
+ | 2026-11-25 | the suite's screen gate on the three pages | passed at 1440 by 900 and 390 by 844 |
139
+
140
+ ### Not verified by anything
141
+
142
+ - Any view at real frame rate in a headful browser: nobody has looked.
143
+ - The dichromat matrix and the 1.2 px blur of the demo stand for dog vision by eye only; the views draw whatever `draw` paints.
144
+
145
+ ## Size budget
146
+
147
+ | file | gzip (measured) | ceiling |
148
+ |---|---|---|
149
+ | `dist/index.js` (main entry, imports external) | 4,420 bytes | 4,641 bytes |
150
+ | `dist/agents-views.iife.js` (single file build) | 4,553 bytes | 4,780 bytes |
151
+
152
+ Measured 2026-11-25 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
153
+ tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
154
+ 5 percent from its row.
@@ -0,0 +1,405 @@
1
+ var HackbuildAgentsViews = (function(exports) {
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ // src/dom.ts
4
+ function el(doc, tag, cls = "", text) {
5
+ const e = doc.createElement(tag);
6
+ if (cls) e.className = cls;
7
+ if (text !== void 0) e.textContent = text;
8
+ return e;
9
+ }
10
+ /** An instrument panel: an ink head with a quieter value at its right. */
11
+ function panel(doc, title, aux = "") {
12
+ const root = el(doc, "section", "hb-panel");
13
+ const hd = el(doc, "h3", "hb-panel-hd-inst");
14
+ const aside = el(doc, "span", "hb-hd-aux", aux);
15
+ hd.append(el(doc, "span", "", title), aside);
16
+ root.append(hd);
17
+ return {
18
+ root,
19
+ aux: aside
20
+ };
21
+ }
22
+ const clamp01 = (v) => Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : 0;
23
+ const f2 = (v) => Number.isFinite(v) ? v.toFixed(2) : "0.00";
24
+ /** The panels of a view, stacked as hackle's blocks (.hb-rack-stack). The column is a
25
+ * child, so the host keeps its own display and a hidden rack pane stays hidden. */
26
+ function stack(host) {
27
+ return el(host.ownerDocument, "div", "hb-rack-stack");
28
+ }
29
+ // src/associations-table.ts
30
+ /** Builds the table from a CueLearner: net strength is excitation minus inhibition. */
31
+ function associationsState(learner, o = {}) {
32
+ const actions = [...learner.actions];
33
+ const s = {
34
+ actions,
35
+ cues: Object.entries(learner.toJSON().cues).map(([cue, r]) => ({
36
+ cue,
37
+ values: actions.map((a) => clamp01((r.w[a] ?? 0) - (r.n[a] ?? 0))),
38
+ attention: clamp01(r.associability)
39
+ }))
40
+ };
41
+ if (o.last) s.last = o.last;
42
+ if (o.trial) s.trial = o.trial;
43
+ return s;
44
+ }
45
+ /** The explanation under the table: how net strength, attention and delayed credit work. */
46
+ const ASSOCIATIONS_NOTE = "rows are cues, columns are acts. cells show net strength, excitation minus a separate inhibition that fades faster, so an extinguished cue partly comes back after a break. the attn column is each cue's associability: it rises after surprises and falls as the outcome becomes predictable. credit fades with delay, so a slow treat can reward whatever it is doing when it lands. if nothing is strong it offers tricks it was rewarded for before; teach a new word by praising whatever it does.";
47
+ /** hackle's cell: .hb-heat.is-pink fills by --v, the figure paper past 0.55. */
48
+ function paint(td, v) {
49
+ const t = clamp01(v);
50
+ td.style.setProperty("--v", t.toFixed(2));
51
+ td.classList.toggle("is-hi", t > .55);
52
+ td.textContent = String(Math.round(t * 99));
53
+ }
54
+ /** Renders the associations panel into `host`. */
55
+ function associationsTable(host, o = {}) {
56
+ const doc = host.ownerDocument;
57
+ const col = stack(host);
58
+ const p = panel(doc, "associations", "rw + pearce kaye hall");
59
+ const scroll = el(doc, "div", "hb-scroll-x");
60
+ const table = el(doc, "table", "hb-heat is-pink");
61
+ const cap = el(doc, "caption", "hb-hint", "link strength 0 to 99, cue by act");
62
+ const thead = el(doc, "thead");
63
+ const tbody = el(doc, "tbody");
64
+ table.append(cap, thead, tbody);
65
+ scroll.append(table);
66
+ const trial = el(doc, "p", "hb-hint");
67
+ const note = el(doc, "p", "hb-note", o.note ?? "rows are cues, columns are acts. cells show net strength, excitation minus a separate inhibition that fades faster, so an extinguished cue partly comes back after a break. the attn column is each cue's associability: it rises after surprises and falls as the outcome becomes predictable. credit fades with delay, so a slow treat can reward whatever it is doing when it lands. if nothing is strong it offers tricks it was rewarded for before; teach a new word by praising whatever it does.");
68
+ const reset = el(doc, "button", "hb-btn", "reset learning");
69
+ reset.type = "button";
70
+ reset.addEventListener("click", () => o.onReset?.());
71
+ p.root.append(scroll, trial, note, reset);
72
+ col.append(p.root);
73
+ host.replaceChildren(col);
74
+ let head = "";
75
+ return {
76
+ root: host,
77
+ update(s) {
78
+ const key = s.actions.join("\n");
79
+ if (key !== head) {
80
+ head = key;
81
+ const tr = el(doc, "tr");
82
+ const corner = el(doc, "th", "", "cue");
83
+ corner.scope = "col";
84
+ tr.append(corner);
85
+ for (const a of s.actions) {
86
+ const th = el(doc, "th", "", a.slice(0, 4));
87
+ th.scope = "col";
88
+ th.title = a;
89
+ tr.append(th);
90
+ }
91
+ const at = el(doc, "th", "", "attn");
92
+ at.scope = "col";
93
+ at.title = "how much it still pays attention to the cue";
94
+ tr.append(at);
95
+ thead.replaceChildren(tr);
96
+ }
97
+ const shown = s.cues.slice(-(o.limit ?? 16));
98
+ if (!shown.length) {
99
+ const tr = el(doc, "tr");
100
+ const td = el(doc, "td", "hb-hint", "no cues yet. say a word, then praise whatever it does.");
101
+ td.colSpan = s.actions.length + 2;
102
+ tr.append(td);
103
+ tbody.replaceChildren(tr);
104
+ } else tbody.replaceChildren(...shown.map((r) => {
105
+ const tr = el(doc, "tr");
106
+ const th = el(doc, "th", "", r.cue.replace("gesture:", "g:"));
107
+ th.scope = "row";
108
+ th.title = r.cue;
109
+ tr.append(th);
110
+ s.actions.forEach((a, i) => {
111
+ const td = el(doc, "td");
112
+ paint(td, r.values[i] ?? 0);
113
+ if (s.last && s.last.cue === r.cue && s.last.action === a) td.setAttribute("aria-current", "true");
114
+ tr.append(td);
115
+ });
116
+ const td = el(doc, "td");
117
+ paint(td, r.attention);
118
+ tr.append(td);
119
+ return tr;
120
+ }));
121
+ trial.textContent = s.trial ?? "";
122
+ trial.hidden = !s.trial;
123
+ },
124
+ dispose() {
125
+ host.replaceChildren();
126
+ }
127
+ };
128
+ }
129
+ // src/drives-bars.ts
130
+ /** Builds the view state from a Chooser decision and the drives. */
131
+ function drivesBarsState(d, drives, o = {}) {
132
+ const values = "values" in drives && typeof drives.values === "object" ? drives.values : drives;
133
+ const s = {
134
+ behavior: o.behavior ?? d.current,
135
+ current: d.current,
136
+ why: o.why ?? d.why,
137
+ mode: o.sampled === false ? "argmax" : "sampled",
138
+ utilities: { ...d.utilities },
139
+ drives: { ...values },
140
+ pending: d.pending && o.now !== void 0 ? {
141
+ id: d.pending.id,
142
+ inMs: Math.max(0, (d.pending.at - o.now) * 1e3)
143
+ } : null
144
+ };
145
+ if (o.seconds !== void 0) s.seconds = o.seconds;
146
+ if (o.pink) s.pink = o.pink;
147
+ return s;
148
+ }
149
+ /** The note under the utility rows while no switch is pending. */
150
+ const DRIVES_NOTE = "each act scores by how much it would ease what it needs. it usually picks the best one and sticks with what it is doing.";
151
+ /** One gauge row per key, rebuilt only when the keys change. */
152
+ function rows(doc, r, label, items) {
153
+ const keys = items.map((i) => i.k).join("\n");
154
+ if (keys !== r.keys) {
155
+ r.keys = keys;
156
+ r.host.replaceChildren(...items.map((i) => {
157
+ const row = el(doc, "div", "hb-gauge");
158
+ row.setAttribute("role", "listitem");
159
+ const meter = el(doc, "div", "hb-meter");
160
+ meter.setAttribute("role", "meter");
161
+ meter.setAttribute("aria-label", `${label} ${i.k}`);
162
+ meter.setAttribute("aria-valuemin", "0");
163
+ meter.append(el(doc, "i"));
164
+ const lab = el(doc, "span", "hb-gauge-label", i.k);
165
+ lab.title = i.k;
166
+ row.append(lab, meter, el(doc, "span", "hb-gauge-value"));
167
+ return row;
168
+ }));
169
+ }
170
+ items.forEach((i, n) => {
171
+ const row = r.host.children[n];
172
+ row.classList.toggle("is-cur", i.cur);
173
+ const meter = row.children[1];
174
+ meter.setAttribute("aria-valuemax", String(i.max));
175
+ meter.setAttribute("aria-valuenow", f2(i.v));
176
+ meter.firstChild.style.width = `${(clamp01(i.v / i.max) * 100).toFixed(1)}%`;
177
+ row.children[2].textContent = f2(i.v);
178
+ });
179
+ }
180
+ /** Renders the behavior, utility and drives panels into `host`. */
181
+ function drivesBars(host, o = {}) {
182
+ const doc = host.ownerDocument;
183
+ const col = stack(host);
184
+ const beh = panel(doc, "behavior", "0.0 s");
185
+ const name = el(doc, "p", "hb-marker", "idle");
186
+ name.setAttribute("aria-live", "polite");
187
+ const why = el(doc, "p", "hb-note");
188
+ beh.root.append(name, why);
189
+ const util = panel(doc, "utility", "sampled");
190
+ const utilRows = el(doc, "div", "hb-gauges");
191
+ utilRows.setAttribute("role", "list");
192
+ utilRows.setAttribute("aria-label", "what each act is worth now");
193
+ const note = el(doc, "p", "hb-note", o.note ?? "each act scores by how much it would ease what it needs. it usually picks the best one and sticks with what it is doing.");
194
+ util.root.append(utilRows, note);
195
+ const drv = panel(doc, "drives", "need 0 to 1");
196
+ const driveRows = el(doc, "div", "hb-gauges");
197
+ driveRows.setAttribute("role", "list");
198
+ driveRows.setAttribute("aria-label", "drives");
199
+ drv.root.append(driveRows);
200
+ col.append(beh.root, util.root, drv.root);
201
+ host.replaceChildren(col);
202
+ const ur = {
203
+ host: utilRows,
204
+ keys: ""
205
+ };
206
+ const dr = {
207
+ host: driveRows,
208
+ keys: ""
209
+ };
210
+ return {
211
+ root: host,
212
+ update(s) {
213
+ name.textContent = s.behavior;
214
+ beh.aux.textContent = `${(s.seconds ?? 0).toFixed(1)} s`;
215
+ why.textContent = s.why ?? "";
216
+ why.hidden = !s.why;
217
+ util.aux.textContent = s.mode ?? "sampled";
218
+ const cur = s.current ?? s.behavior;
219
+ const u = Object.entries(s.utilities).map(([k, v]) => ({
220
+ k,
221
+ v: Number.isFinite(v) ? Math.max(0, v) : 0
222
+ }));
223
+ const max = Math.max(1, ...u.map((x) => x.v));
224
+ rows(doc, ur, "utility", u.map((x) => ({
225
+ ...x,
226
+ max,
227
+ cur: x.k === cur
228
+ })));
229
+ note.textContent = s.pending ? `next: ${s.pending.id} in ${Math.round(s.pending.inMs)} ms` : o.note ?? "each act scores by how much it would ease what it needs. it usually picks the best one and sticks with what it is doing.";
230
+ const pink = new Set(s.pink ?? []);
231
+ rows(doc, dr, "drive", Object.entries(s.drives).map(([k, v]) => ({
232
+ k,
233
+ v: clamp01(v),
234
+ max: 1,
235
+ cur: pink.has(k)
236
+ })));
237
+ },
238
+ dispose() {
239
+ host.replaceChildren();
240
+ }
241
+ };
242
+ }
243
+ // src/eye-inset.ts
244
+ /** Makes `host` the eye card: head with the mode line, the who switch, the canvas. */
245
+ function eyeInset(host, o) {
246
+ if (!o.who.length) throw new Error("@hackbuild/agents-views: eyeInset needs at least one who");
247
+ const doc = host.ownerDocument;
248
+ host.classList.add("hb-inset");
249
+ host.dataset.ux = "inset";
250
+ host.setAttribute("role", "figure");
251
+ const w = o.width ?? 320;
252
+ const h = o.height ?? 160;
253
+ let sel = o.who.find((x) => x.id === o.selected) ?? o.who[0];
254
+ const hd = el(doc, "div", "hb-inset-hd");
255
+ const title = el(doc, "span", "hb-inset-title", "eye");
256
+ const aux = el(doc, "span", "hb-hd-aux");
257
+ const whoGroup = el(doc, "span", "hb-inset-who");
258
+ whoGroup.setAttribute("role", "group");
259
+ whoGroup.setAttribute("aria-label", "whose eyes");
260
+ const buttons = o.who.map((x) => {
261
+ const b = el(doc, "button", "", x.label);
262
+ b.type = "button";
263
+ if (x.title) b.title = x.title;
264
+ b.addEventListener("click", () => pick(x.id, true));
265
+ return b;
266
+ });
267
+ whoGroup.append(...buttons);
268
+ hd.append(title, ...o.who.length > 1 ? [whoGroup] : [], aux);
269
+ const media = el(doc, "div", "hb-inset-media");
270
+ media.style.setProperty("--hb-inset-ratio", `${w} / ${h}`);
271
+ const canvas = o.canvas ?? el(doc, "canvas");
272
+ if (!o.canvas) {
273
+ canvas.width = w;
274
+ canvas.height = h;
275
+ }
276
+ canvas.setAttribute("role", "img");
277
+ media.append(canvas);
278
+ host.replaceChildren(hd, media);
279
+ function pick(id, user) {
280
+ const next = o.who.find((x) => x.id === id);
281
+ if (!next) return;
282
+ sel = next;
283
+ canvas.setAttribute("aria-label", sel.title ?? sel.label);
284
+ buttons.forEach((b, i) => b.setAttribute("aria-pressed", String(o.who[i] === sel)));
285
+ if (user) o.onWho?.(sel.id);
286
+ }
287
+ pick(sel.id, false);
288
+ return {
289
+ root: host,
290
+ canvas,
291
+ get who() {
292
+ return sel;
293
+ },
294
+ select: (id) => pick(id, false),
295
+ frame() {
296
+ const who = sel;
297
+ const run = () => {
298
+ const m = o.draw(canvas, who);
299
+ if (typeof m === "string") aux.textContent = m;
300
+ };
301
+ if (who.eye) who.eye.render(run);
302
+ else run();
303
+ },
304
+ mode(text) {
305
+ aux.textContent = text;
306
+ },
307
+ dispose() {
308
+ host.replaceChildren();
309
+ host.classList.remove("hb-inset");
310
+ delete host.dataset.ux;
311
+ }
312
+ };
313
+ }
314
+ // src/elements.ts
315
+ /** The tag names `defineViews` registers. */
316
+ const ELEMENT_NAMES = {
317
+ drivesBars: "hb-drives-bars",
318
+ associationsTable: "hb-associations-table",
319
+ eyeInset: "hb-eye-inset"
320
+ };
321
+ /** Defines the three elements once; safe to call again. */
322
+ function defineViews(registry = customElements) {
323
+ if (!registry.get(ELEMENT_NAMES.drivesBars)) registry.define(ELEMENT_NAMES.drivesBars, class extends HTMLElement {
324
+ #view = null;
325
+ #state = null;
326
+ get state() {
327
+ return this.#state;
328
+ }
329
+ set state(s) {
330
+ this.#state = s;
331
+ if (s) this.#view?.update(s);
332
+ }
333
+ connectedCallback() {
334
+ const note = this.getAttribute("note");
335
+ this.#view ??= drivesBars(this, note ? { note } : {});
336
+ if (this.#state) this.#view.update(this.#state);
337
+ }
338
+ });
339
+ if (!registry.get(ELEMENT_NAMES.associationsTable)) registry.define(ELEMENT_NAMES.associationsTable, class extends HTMLElement {
340
+ #view = null;
341
+ #state = null;
342
+ get state() {
343
+ return this.#state;
344
+ }
345
+ set state(s) {
346
+ this.#state = s;
347
+ if (s) this.#view?.update(s);
348
+ }
349
+ connectedCallback() {
350
+ this.#view ??= associationsTable(this, { onReset: () => this.dispatchEvent(new CustomEvent("reset", { bubbles: true })) });
351
+ if (this.#state) this.#view.update(this.#state);
352
+ }
353
+ });
354
+ if (!registry.get(ELEMENT_NAMES.eyeInset)) registry.define(ELEMENT_NAMES.eyeInset, class extends HTMLElement {
355
+ #view = null;
356
+ #options = null;
357
+ get options() {
358
+ return this.#options;
359
+ }
360
+ set options(o) {
361
+ this.#options = o;
362
+ this.#mount();
363
+ }
364
+ get view() {
365
+ return this.#view;
366
+ }
367
+ connectedCallback() {
368
+ this.#mount();
369
+ }
370
+ #mount() {
371
+ if (!this.#options || !this.isConnected) return;
372
+ this.#view?.dispose();
373
+ const o = this.#options;
374
+ this.#view = eyeInset(this, {
375
+ ...o,
376
+ onWho: (id) => {
377
+ o.onWho?.(id);
378
+ this.dispatchEvent(new CustomEvent("who", {
379
+ detail: id,
380
+ bubbles: true
381
+ }));
382
+ }
383
+ });
384
+ }
385
+ frame() {
386
+ this.#view?.frame();
387
+ }
388
+ mode(text) {
389
+ this.#view?.mode(text);
390
+ }
391
+ });
392
+ }
393
+ // src/single.ts
394
+ if (typeof customElements !== "undefined") defineViews();
395
+ exports.ASSOCIATIONS_NOTE = ASSOCIATIONS_NOTE;
396
+ exports.DRIVES_NOTE = DRIVES_NOTE;
397
+ exports.ELEMENT_NAMES = ELEMENT_NAMES;
398
+ exports.associationsState = associationsState;
399
+ exports.associationsTable = associationsTable;
400
+ exports.defineViews = defineViews;
401
+ exports.drivesBars = drivesBars;
402
+ exports.drivesBarsState = drivesBarsState;
403
+ exports.eyeInset = eyeInset;
404
+ return exports;
405
+ })({});
@@ -0,0 +1,66 @@
1
+ /** One cue row of the table. */
2
+ export interface AssociationsRow {
3
+ /** the cue, as a word or `gesture:name` */
4
+ cue: string;
5
+ /** net strength per action, 0 to 1, in the order of `actions` */
6
+ values: number[];
7
+ /** how much it still pays attention to the cue, 0 to 1 */
8
+ attention: number;
9
+ }
10
+ /** What the table draws. Built from a CueLearner with `associationsState`, or by hand. */
11
+ export interface AssociationsState {
12
+ /** the act columns */
13
+ actions: string[];
14
+ /** newest last; the table shows the last 16 */
15
+ cues: AssociationsRow[];
16
+ /** the cell of the last reward, outlined */
17
+ last?: {
18
+ cue: string;
19
+ action: string;
20
+ } | null;
21
+ /** one line on the last trial */
22
+ trial?: string;
23
+ }
24
+ /** The @hackbuild/drives LearnerState shape (CueLearner.toJSON()). */
25
+ export interface LearnerStateLike {
26
+ cues: Record<string, {
27
+ w: Record<string, number>;
28
+ n: Record<string, number>;
29
+ associability: number;
30
+ }>;
31
+ }
32
+ /** A @hackbuild/drives CueLearner, or anything with its actions and toJSON. */
33
+ export interface LearnerLike {
34
+ readonly actions: readonly string[];
35
+ toJSON(): LearnerStateLike;
36
+ }
37
+ /** Builds the table from a CueLearner: net strength is excitation minus inhibition. */
38
+ export declare function associationsState(learner: LearnerLike, o?: {
39
+ last?: {
40
+ cue: string;
41
+ action: string;
42
+ } | null;
43
+ trial?: string;
44
+ }): AssociationsState;
45
+ /** Options of `associationsTable`. */
46
+ export interface AssociationsOptions {
47
+ /** reset learning was pressed */
48
+ onReset?: () => void;
49
+ /** the explanation under the table; `ASSOCIATIONS_NOTE` by default */
50
+ note?: string;
51
+ /** rows shown, newest last (default 16) */
52
+ limit?: number;
53
+ }
54
+ /** What `associationsTable` returns: the host, an update and a dispose. */
55
+ export interface AssociationsHandle {
56
+ /** the host element */
57
+ readonly root: HTMLElement;
58
+ /** draws a new state */
59
+ update(state: AssociationsState): void;
60
+ /** empties the host */
61
+ dispose(): void;
62
+ }
63
+ /** The explanation under the table: how net strength, attention and delayed credit work. */
64
+ export declare const ASSOCIATIONS_NOTE = "rows are cues, columns are acts. cells show net strength, excitation minus a separate inhibition that fades faster, so an extinguished cue partly comes back after a break. the attn column is each cue's associability: it rises after surprises and falls as the outcome becomes predictable. credit fades with delay, so a slow treat can reward whatever it is doing when it lands. if nothing is strong it offers tricks it was rewarded for before; teach a new word by praising whatever it does.";
65
+ /** Renders the associations panel into `host`. */
66
+ export declare function associationsTable(host: HTMLElement, o?: AssociationsOptions): AssociationsHandle;