cortico-world-agent-speed 0.2.0 → 0.2.2

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 (189) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/LICENSE +0 -14
  3. package/README.md +29 -11
  4. package/THIRD_PARTY_NOTICES.md +69 -0
  5. package/activity.d.ts +15 -0
  6. package/activity.js +88 -3
  7. package/describe.json +806 -0
  8. package/dist/webui.css +2 -0
  9. package/dist/webui.css.map +7 -0
  10. package/dist/webui.js +2 -0
  11. package/dist/webui.js.map +7 -0
  12. package/host/app-store.cjs +68 -0
  13. package/host/cursor.cjs +67 -0
  14. package/host/electron-main.cjs +666 -0
  15. package/host/input-shape.cjs +63 -0
  16. package/host/mouse-lease.cjs +77 -0
  17. package/host/overlay.cjs +139 -0
  18. package/host/portrait.cjs +52 -0
  19. package/host/preload.cjs +60 -14
  20. package/host/renderer-gone.cjs +24 -0
  21. package/host/windows.cjs +251 -0
  22. package/package.json +27 -7
  23. package/scripts/build-webui.mjs +40 -0
  24. package/scripts/speech-bank/build.py +166 -0
  25. package/scripts/speech-bank/dicts.py +76 -0
  26. package/src/ENV_PROMPT.en.md +51 -0
  27. package/src/ENV_PROMPT.md +51 -0
  28. package/src/asr/address.ts +25 -0
  29. package/src/asr/hotkey.ts +335 -0
  30. package/src/asr/result.ts +51 -0
  31. package/src/asr/segmenter.ts +269 -0
  32. package/src/asr/sherpa.ts +280 -0
  33. package/src/asr/simplify.ts +38 -0
  34. package/src/asr/system-recognizer.ts +292 -0
  35. package/src/asr/system-sapi.ps1 +173 -0
  36. package/src/asr/transcription-api.ts +176 -0
  37. package/src/chat.ts +212 -0
  38. package/src/config.ts +481 -0
  39. package/src/cua/ENV_PROMPT.en.md +29 -0
  40. package/src/cua/ENV_PROMPT.md +29 -0
  41. package/src/cua/config.ts +88 -0
  42. package/src/cua/cua.ts +712 -0
  43. package/src/cua/engine/darwin.ts +410 -0
  44. package/src/cua/engine/display.ts +55 -0
  45. package/src/cua/engine/fail.ts +15 -0
  46. package/src/cua/engine/foreground.ts +8 -0
  47. package/src/cua/engine/image.ts +57 -0
  48. package/src/cua/engine/keys.ts +70 -0
  49. package/src/cua/engine/linux-keys.ts +29 -0
  50. package/src/cua/engine/linux.ts +343 -0
  51. package/src/cua/engine/mac-keys.ts +57 -0
  52. package/src/cua/engine/user-activity.ts +54 -0
  53. package/src/cua/engine/wait-idle.ts +31 -0
  54. package/src/cua/engine/win32.ts +299 -0
  55. package/src/cua/engine-child.ts +274 -0
  56. package/src/cua/engine-ipc.ts +140 -0
  57. package/src/cua/i18n/de.ts +53 -0
  58. package/src/cua/i18n/en.ts +63 -0
  59. package/src/cua/i18n/es-419.ts +53 -0
  60. package/src/cua/i18n/fr.ts +53 -0
  61. package/src/cua/i18n/index.ts +26 -0
  62. package/src/cua/i18n/it.ts +53 -0
  63. package/src/cua/i18n/ja.ts +53 -0
  64. package/src/cua/i18n/ko.ts +53 -0
  65. package/src/cua/i18n/pt-BR.ts +53 -0
  66. package/src/cua/i18n/ru.ts +59 -0
  67. package/src/cua/i18n/zh-Hant.ts +53 -0
  68. package/src/cua/i18n/zh.ts +59 -0
  69. package/src/cua/model-text.ts +252 -0
  70. package/src/cua/terminal.ts +31 -0
  71. package/src/cua/tools.ts +153 -0
  72. package/src/definition.ts +146 -0
  73. package/src/host-reason.ts +32 -0
  74. package/src/i18n/de.ts +409 -0
  75. package/src/i18n/en.ts +443 -0
  76. package/src/i18n/es-419.ts +409 -0
  77. package/src/i18n/fr.ts +409 -0
  78. package/src/i18n/index.ts +56 -0
  79. package/src/i18n/it.ts +409 -0
  80. package/src/i18n/ja.ts +409 -0
  81. package/src/i18n/ko.ts +409 -0
  82. package/src/i18n/pt-BR.ts +409 -0
  83. package/src/i18n/ru.ts +415 -0
  84. package/src/i18n/zh-Hant.ts +409 -0
  85. package/src/i18n/zh.ts +440 -0
  86. package/src/index.ts +15 -0
  87. package/src/model-text.ts +344 -0
  88. package/src/moves.ts +101 -0
  89. package/src/pack-import.ts +361 -0
  90. package/src/packs.ts +449 -0
  91. package/src/runtime/download.ts +29 -0
  92. package/src/runtime/store.ts +293 -0
  93. package/src/script.ts +202 -0
  94. package/src/self.ts +247 -0
  95. package/src/server.ts +479 -0
  96. package/src/speech/data/CMUDICT-LICENSE +33 -0
  97. package/src/speech/data/IPADIC-COPYING +71 -0
  98. package/src/speech/data/UNICODE-LICENSE +39 -0
  99. package/src/speech/data/en.tsv.gz +0 -0
  100. package/src/speech/data/ja-ipadic.tsv.gz +0 -0
  101. package/src/speech/data/ja-unihan.tsv.gz +0 -0
  102. package/src/speech/data/zh.json +1 -0
  103. package/src/speech/index.ts +204 -0
  104. package/src/speech/ipa.ts +83 -0
  105. package/src/speech/japanese.ts +105 -0
  106. package/src/speech/jukujikun.ts +22 -0
  107. package/src/speech/korean.ts +35 -0
  108. package/src/speech/lang.ts +151 -0
  109. package/src/speech/rules.ts +72 -0
  110. package/src/speech/syllable.ts +76 -0
  111. package/src/status.ts +164 -0
  112. package/src/tools.ts +110 -0
  113. package/src/webui/api-rows.css +2 -0
  114. package/src/webui/api-rows.ts +44 -0
  115. package/src/webui/client.ts +451 -0
  116. package/src/webui/dress-dialog.css +14 -0
  117. package/src/webui/dress-dialog.ts +117 -0
  118. package/src/webui/dress-panel.ts +160 -0
  119. package/src/webui/key-capture.ts +60 -0
  120. package/src/webui/shared/modal.css +13 -0
  121. package/src/webui/shared/modal.ts +77 -0
  122. package/src/webui/shared/problem.css +15 -0
  123. package/src/webui/shared/problem.ts +217 -0
  124. package/src/webui/shared/strings.ts +5 -0
  125. package/src/webui/style.css +50 -0
  126. package/src/window-host.ts +116 -0
  127. package/src/world.ts +2926 -0
  128. package/web/activity-motion.js +117 -0
  129. package/web/appearance.js +60 -0
  130. package/web/body-host.js +257 -0
  131. package/web/coo/coo.js +384 -0
  132. package/web/coo/figure.js +15 -0
  133. package/web/coo/figure.json +1224 -0
  134. package/web/dist/dress-dialog.css +1 -0
  135. package/web/dist/dress-dialog.js +1 -0
  136. package/web/drag-row.js +49 -0
  137. package/web/drag.js +149 -0
  138. package/web/dress.css +170 -0
  139. package/web/dress.html +37 -0
  140. package/web/dress.js +786 -0
  141. package/web/figure-frame.html +16 -0
  142. package/web/figure-frame.js +128 -0
  143. package/web/frame-loop.js +55 -0
  144. package/web/hints.js +77 -0
  145. package/web/i18n/de.js +170 -0
  146. package/web/i18n/en.js +177 -0
  147. package/web/i18n/es-419.js +170 -0
  148. package/web/i18n/fr.js +170 -0
  149. package/web/i18n/it.js +170 -0
  150. package/web/i18n/ja.js +170 -0
  151. package/web/i18n/ko.js +170 -0
  152. package/web/i18n/pt-BR.js +170 -0
  153. package/web/i18n/ru.js +170 -0
  154. package/web/i18n/zh-Hant.js +170 -0
  155. package/web/i18n/zh.js +175 -0
  156. package/web/i18n.js +54 -0
  157. package/{renderer/vendor → web}/kit/body.js +31 -58
  158. package/web/looks.js +70 -0
  159. package/web/mic-worklet.js +36 -0
  160. package/web/mic.js +117 -0
  161. package/web/motion-frames.js +80 -0
  162. package/web/motion-level.js +40 -0
  163. package/web/new-year-2027.svg +238 -0
  164. package/web/overlay.html +16 -0
  165. package/web/overlay.js +100 -0
  166. package/web/pet-app.js +3000 -0
  167. package/web/pet.css +642 -0
  168. package/web/pet.html +21 -0
  169. package/web/scale-slider.js +259 -0
  170. package/web/show-hide.js +49 -0
  171. package/web/sound.js +245 -0
  172. package/web/speech/zh.json +1 -0
  173. package/web/speech/zh.ogg +0 -0
  174. package/web/speech.js +197 -0
  175. package/web/stage.js +160 -0
  176. package/web/swap-motion.js +119 -0
  177. package/web/ui.js +195 -0
  178. package/host/launch.js +0 -187
  179. package/host/library.cjs +0 -638
  180. package/host/main.cjs +0 -389
  181. package/index.js +0 -93
  182. package/renderer/index.html +0 -22
  183. package/renderer/pet-sandbox.html +0 -11
  184. package/renderer/pet.css +0 -38
  185. package/renderer/pet.js +0 -251
  186. package/renderer/vendor/activity-motion.js +0 -101
  187. package/renderer/vendor/figure-frame.js +0 -115
  188. package/renderer/vendor/pack.css +0 -2
  189. /package/{renderer/vendor → web}/kit/rig.js +0 -0
@@ -0,0 +1,117 @@
1
+ // Activity is advisory: the host remains in charge of input, clips and locomotion.
2
+ const FRESH_MS = 5000;
3
+ const FINISH_MS = 1200;
4
+ const TAU = Math.PI * 2;
5
+ const PROFILES = {
6
+ tools: ['thinking', 'look', 'determined', 'nod', 'confused', 'curious', 'focused'],
7
+ slow: ['thinking', 'nod', 'look', 'happy', 'content', 'wink'],
8
+ medium: ['nod', 'happy', 'hop', 'wave', 'wink', 'look'],
9
+ fast: ['flap', 'excited', 'dance', 'hop', 'happy', 'cheer', 'wave', 'spin'],
10
+ done: ['bow', 'happy', 'wave', 'nod', 'flap', 'excited', 'cheer'],
11
+ };
12
+ const STOCK = new Set(Object.values(PROFILES).flat());
13
+
14
+ function kind(sample, now) {
15
+ if (!sample || !Number.isFinite(now) || !Number.isFinite(sample.updatedAtMs) ||
16
+ sample.updatedAtMs > now || now - sample.updatedAtMs > FRESH_MS) return null;
17
+ return sample.generating > 0 ? 'output' : sample.tools > 0 ? 'tools' : 'idle';
18
+ }
19
+
20
+ // Only infer actions whose whole identifier describes a known stationary gesture or
21
+ // expression. Arbitrary pack words may have side effects even when not lasting.
22
+ function customCategory(word) {
23
+ const id = word.id.toLowerCase();
24
+ if (!/^[a-z]+(?:[_-][a-z]+)*$/.test(id)) return null;
25
+ if (word.kind === 'expression') {
26
+ if (/^(?:thinking|focused|curious|determined|confused)(?:[_-](?:face|expression))?$/.test(id)) return 'thought';
27
+ if (/^(?:happy|content|excited|cheerful|joyful|smile|smiling|wink)(?:[_-](?:face|expression))?$/.test(id)) return 'joy';
28
+ }
29
+ if (word.kind === 'motion' && /^(?:(?:small|little|gentle|happy|quick)[_-])?(?:nod|wave|bow|hop|flap|dance|look)(?:[_-](?:once|twice))?$/.test(id)) return 'gesture';
30
+ return null;
31
+ }
32
+
33
+ export function createActivityMotion() {
34
+ let sample = null;
35
+ let finishUntil = 0;
36
+ let nextCue = 0;
37
+ let lastCue = null;
38
+ let rotation = 0;
39
+ const pose = { energy: 0, focus: 0, phase: 0, cue: null };
40
+
41
+ return {
42
+ receive(value, now) {
43
+ const before = kind(sample, now);
44
+ const after = kind(value, now);
45
+ if (after === 'idle' && value?.complete === true && (before === 'output' || before === 'tools')) {
46
+ finishUntil = now + FINISH_MS;
47
+ } else if (after !== 'idle' || value?.complete !== true) {
48
+ finishUntil = 0;
49
+ }
50
+ // Samples must not restart an active clip or reset the scheduler.
51
+ sample = value;
52
+ },
53
+ step(now, dt, eligible, canCue, words, reported) {
54
+ const activity = kind(sample, now);
55
+ const rate = activity === 'output' && Number.isFinite(sample.outputPerSecond)
56
+ ? Math.max(0, Math.min(240, sample.outputPerSecond)) : 0;
57
+ const targetEnergy = activity === 'output' ? 0.28 + 0.72 * rate / 240 : 0;
58
+ const targetFocus = activity === 'tools' ? 1 : 0;
59
+ const seconds = Number.isFinite(dt) ? Math.max(0, Math.min(dt, 0.25)) : 0;
60
+ pose.cue = null;
61
+ if (!eligible) {
62
+ pose.energy = 0;
63
+ pose.focus = 0;
64
+ pose.phase = 0;
65
+ } else {
66
+ const blend = 1 - Math.exp(-seconds * (targetEnergy || targetFocus ? 5 : 3));
67
+ pose.energy += (targetEnergy - pose.energy) * blend;
68
+ pose.focus += (targetFocus - pose.focus) * blend;
69
+ if (!targetEnergy && pose.energy < .004) pose.energy = 0;
70
+ if (!targetFocus && pose.focus < .004) pose.focus = 0;
71
+ pose.phase = (pose.phase + seconds * (1.5 + pose.energy * 5)) % TAU;
72
+ }
73
+
74
+ if (!activity || now > finishUntil) finishUntil = 0;
75
+ // A suppressed completion is discarded, never replayed after a modal or action.
76
+ if (!eligible || !canCue) {
77
+ finishUntil = 0;
78
+ return pose;
79
+ }
80
+ const finishing = finishUntil > 0;
81
+ if ((!finishing && activity !== 'output' && activity !== 'tools') || now < nextCue) return pose;
82
+ const profile = finishing ? 'done' : activity === 'tools' ? 'tools' : rate < 45 ? 'slow' : rate < 120 ? 'medium' : 'fast';
83
+ const choices = [];
84
+ const allowed = word => word && typeof word.id === 'string' && !word.lasting &&
85
+ (word.kind === 'motion' || word.kind === 'expression') &&
86
+ (reported === null || (Array.isArray(reported) && reported.includes(word.id)));
87
+ for (const id of PROFILES[profile]) {
88
+ const word = words?.get(id);
89
+ if (allowed(word)) choices.push(word);
90
+ }
91
+ if (words) {
92
+ for (const word of words.values()) {
93
+ if (!allowed(word) || STOCK.has(word.id)) continue;
94
+ const category = customCategory(word);
95
+ if (category && (profile === 'tools' ? category === 'thought' : profile === 'done' || profile === 'fast' ? category !== 'thought' : true)) {
96
+ choices.push(word);
97
+ }
98
+ }
99
+ }
100
+ if (choices.length) {
101
+ // Rotate the ranked pool, avoiding an immediate repeat when possible.
102
+ let index = rotation++ % choices.length;
103
+ if (choices.length > 1 && choices[index].id === lastCue) index = (index + 1) % choices.length;
104
+ const word = choices[index];
105
+ pose.cue = lastCue = word.id;
106
+ const duration = Number.isFinite(word.seconds) ? Math.max(0, word.seconds) : 0;
107
+ const interval = activity === 'output' ? 3.8 - rate / 240 * 1.5 : 3.8;
108
+ nextCue = now + 1000 * Math.max(interval, duration + 0.35);
109
+ if (finishing) finishUntil = 0;
110
+ } else {
111
+ nextCue = now + 1000;
112
+ if (finishing) finishUntil = 0;
113
+ }
114
+ return pose;
115
+ },
116
+ };
117
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Editor chrome follows the embedding console, its light/dark and its accent; pet palette remains a separate setting.
3
+ * A console that asks for it (`?fit=1`) is told how tall the page is (`companion:height`), sizes the frame to it and
4
+ * scrolls it with the window instead of a scrollbar of the frame's own (dress.css `[data-embedded]`).
5
+ */
6
+ /** The origin of the settings window that opened the page (its referrer, on this host), or null. */
7
+ function hostOrigin(doc, win) {
8
+ try {
9
+ const ref = new URL(doc.referrer);
10
+ return ref.protocol === win.location.protocol && ref.hostname === win.location.hostname ? ref.origin : null;
11
+ } catch { return null; }
12
+ }
13
+
14
+ /** The host renders the same structured dialog as the standalone page. Files retain their relative paths. */
15
+ export function hostDressDialogs(doc, win) {
16
+ const origin = win.parent === win ? null : hostOrigin(doc, win);
17
+ if (!origin) return null;
18
+ let sequence = 0, current = null;
19
+ const receive = (e) => {
20
+ if (!current || e.source !== win.parent || e.origin !== origin || e.data?.type !== 'companion:dialog-action' || e.data.id !== current?.id) return;
21
+ const answer = current.answer; current = null; answer(e.data.result);
22
+ };
23
+ win.addEventListener('message', receive);
24
+ win.addEventListener('pagehide', () => { current = null; win.removeEventListener('message', receive); }, { once: true });
25
+ return {
26
+ show(view, answer) {
27
+ current = { id: ++sequence, answer };
28
+ win.parent.postMessage({ type: 'companion:dialog', id: current.id, view }, origin);
29
+ },
30
+ close() { current = null; win.parent.postMessage({ type: 'companion:dialog-close' }, origin); },
31
+ };
32
+ }
33
+
34
+ export function bindAppearance(doc, win) {
35
+ const params = new URLSearchParams(win.location.search);
36
+ const initial = params.get('appearance');
37
+ const apply = (mode) => {
38
+ if (mode === 'light' || mode === 'dark') doc.documentElement.dataset.uiTheme = mode;
39
+ };
40
+ apply(initial);
41
+ const parentOrigin = hostOrigin(doc, win);
42
+ const applyAccent = (accent) => {
43
+ if (/^#[0-9a-f]{6}$/i.test(String(accent ?? ''))) doc.documentElement.style.setProperty('--host-accent', accent);
44
+ };
45
+ const onMessage = (event) => {
46
+ if (!parentOrigin || event.source !== win.parent || event.origin !== parentOrigin) return;
47
+ if (event.data?.type !== 'companion:appearance') return;
48
+ apply(event.data.mode);
49
+ applyAccent(event.data.accent);
50
+ };
51
+ win.addEventListener('message', onMessage);
52
+ let sizes = null;
53
+ if (parentOrigin && win.parent !== win && params.get('fit') === '1') {
54
+ doc.documentElement.dataset.embedded = '';
55
+ const report = () => win.parent.postMessage({ type: 'companion:height', height: Math.ceil(doc.body.getBoundingClientRect().height) }, parentOrigin);
56
+ sizes = new win.ResizeObserver(report);
57
+ sizes.observe(doc.body);
58
+ }
59
+ return () => { win.removeEventListener('message', onMessage); sizes?.disconnect(); };
60
+ }
@@ -0,0 +1,257 @@
1
+ /**
2
+ * The page's side of a figure pack's body (Coo's too): the pack's code runs inside a sandboxed frame
3
+ * (`/figure-frame`, figure-frame.js) that fills `layer`, laid over the page's stage under its bubbles
4
+ * and buttons. The page drives it once a frame (`tick`), forwards the pointer, asks it to do things,
5
+ * and reads back where it is (`layout`), what happened to it (`onEvent`) and what it wants heard
6
+ * (`onSound`).
7
+ *
8
+ * The pack's code is not trusted, so the page holds the line here:
9
+ * - the body's box is kept inside the stage and to the most the kit itself ever stretches a body
10
+ * (BOX_MAX), and only its hit circles inside that box take the pointer: a pack cannot spread
11
+ * its clickable area over the screen and swallow clicks meant for the windows underneath;
12
+ * - a touch (poke, pat, pick-up, throw) counts only right after the page passed it pointer input
13
+ * (TOUCH_MS), and a crash only after a throw: a pack cannot make up touches that wake the bot;
14
+ * - the bubble's spot and the hover buttons' point stay on the stage;
15
+ * - the windows on the desktop go only to a pack whose manifest `needs` them.
16
+ *
17
+ * `onError(err)` is called when the pack's code fails after it was ready; before that the returned
18
+ * promise rejects. Either way the frame is gone.
19
+ */
20
+ import { language, t } from './i18n.js';
21
+
22
+ /** A pack that has not drawn its first frame by then is taken as broken: its scripts or textures did not load. */
23
+ const READY_MS = 20_000;
24
+ /**
25
+ * The longest side of a body's box, in 256-unit squares at the body's scale: the kit squashes a body up to 1.33
26
+ * wide and stretches it to 1.5 tall (squash, drag stretch and breath together), and a box turned any way grows by √2.
27
+ */
28
+ const BOX_MAX = 1.5 * Math.SQRT2;
29
+ /**
30
+ * How long after the page passed pointer input a body may report a touch. The body answers in the frame after the
31
+ * input, a few tens of milliseconds at the resting frame rate; a second covers a frame held up by a stalled page.
32
+ */
33
+ const TOUCH_MS = 1000;
34
+ const TOUCHES = new Set(['poke', 'pet', 'grab', 'drop', 'throw', 'crash']);
35
+ /**
36
+ * How far around the body's box the halo reaches, as a share of the box's width and height each side (the SVG filter
37
+ * region the halo had before bodies moved into their frame), and at least HALO_REACH pixels, the drop shadows' spread.
38
+ * Drawn with a CSS filter over the whole stage, the halo blurs the full window on every frame the body redraws: on a
39
+ * Mac, where it is always on, that kept the GPU busy at 60 to 90 percent behind the whale.
40
+ */
41
+ const HALO_PAD = .4, HALO_REACH = 24;
42
+
43
+ const num = (v, fallback = 0) => (typeof v === 'number' && Number.isFinite(v) ? v : fallback);
44
+ const clampTo = (v, a, b) => Math.max(a, Math.min(b, v));
45
+
46
+ /**
47
+ * A body's layout report as the page takes it (`size`: the stage, { W, H, S }): numbers where numbers belong, and the limits above.
48
+ * `y`, where a body that stands off the floor has its feet, is kept only when the body gives one.
49
+ */
50
+ export function readLayout(l, size) {
51
+ if (!l || typeof l !== 'object') return null;
52
+ const { W, H, S } = size, side = 256 * S * BOX_MAX;
53
+ const b = l.box ?? {};
54
+ const w = clampTo(num(b.w), 0, side), h = clampTo(num(b.h), 0, side);
55
+ const x0 = clampTo(num(b.x), -w, W), y0 = clampTo(num(b.y), -h, H);
56
+ const box = { x: Math.max(0, x0), y: Math.max(0, y0), w: Math.min(W, x0 + w) - Math.max(0, x0), h: Math.min(H, y0 + h) - Math.max(0, y0) };
57
+ const pt = (p) => ({ x: clampTo(num(p?.x), 0, W), y: clampTo(num(p?.y), 0, H) });
58
+ return {
59
+ x: clampTo(num(l.x, W / 2), 0, W), ...(typeof l.y === 'number' && Number.isFinite(l.y) ? { y: clampTo(l.y, 0, H) } : {}), facing: l.facing === -1 ? -1 : 1, mode: typeof l.mode === 'string' ? l.mode.slice(0, 32) : 'idle',
60
+ busy: !!l.busy, moving: !!l.moving, pressing: !!l.pressing,
61
+ cursor: l.cursor === 'grab' || l.cursor === 'grabbing' ? l.cursor : '',
62
+ box,
63
+ hit: (Array.isArray(l.hit) ? l.hit : []).map((c) => ({ x: num(c?.x), y: num(c?.y), r: Math.max(0, num(c?.r)) })),
64
+ bubble: pt(l.bubble), side: { ...pt(l.side), reach: clampTo(num(l.side?.reach), 0, side / 2) },
65
+ };
66
+ }
67
+
68
+ /** Whether stage point `p` is on a body with `layout` (readLayout's): in its box and in one of its hit circles. */
69
+ export function onBody(layout, p) {
70
+ const b = layout?.box;
71
+ if (!b || p.x < b.x || p.y < b.y || p.x > b.x + b.w || p.y > b.y + b.h) return false;
72
+ return layout.hit.some((c) => Math.hypot(p.x - c.x, p.y - c.y) < c.r);
73
+ }
74
+
75
+ /**
76
+ * The window the halo is drawn in for a body with `layout` (readLayout's) on a `size` stage: its box with HALO_PAD
77
+ * around it, and at least HALO_REACH, three times the halo's `reach`, or the pack's `effects` reach (`fx`, in 256-unit
78
+ * squares), in whole pixels inside the stage; null when there is no box to draw around.
79
+ */
80
+ export function haloRect(layout, size, reach = 7, fx = 0) {
81
+ const b = layout?.box;
82
+ if (!b || !(b.w > 0) || !(b.h > 0)) return null;
83
+ // the drop shadows spread about three times their blur: a wider halo needs a wider window
84
+ const room = Math.max(HALO_REACH, reach * 3, clampTo(num(fx), 0, BOX_MAX) * 256 * size.S);
85
+ const px = Math.max(room, b.w * HALO_PAD), py = Math.max(room, b.h * HALO_PAD);
86
+ const x = Math.max(0, Math.floor(b.x - px)), y = Math.max(0, Math.floor(b.y - py));
87
+ const w = Math.min(Math.ceil(size.W), Math.ceil(b.x + b.w + px)) - x, h = Math.min(Math.ceil(size.H), Math.ceil(b.y + b.h + py)) - y;
88
+ return w > 0 && h > 0 ? { x, y, w, h } : null;
89
+ }
90
+
91
+ /**
92
+ * Which touches a body reports are taken: `input(now)` when the page passes it pointer input, `take(kind, now)`
93
+ * for each touch it reports (ms clock).
94
+ */
95
+ export function touchGate() {
96
+ let inputAt = -Infinity, thrown = false;
97
+ return {
98
+ input(now) { inputAt = now; },
99
+ take(kind, now) {
100
+ if (!TOUCHES.has(kind)) return false;
101
+ if (kind === 'crash' ? !thrown : now - inputAt > TOUCH_MS) return false;
102
+ thrown = kind === 'throw';
103
+ return true;
104
+ },
105
+ };
106
+ }
107
+
108
+ /**
109
+ * `scheme` as `pack` knows it: one of its presets, else each axis's option in it, the axis's first where it names
110
+ * one the pack does not have (an update of the pack took it away). The pack's own code only ever gets these.
111
+ */
112
+ export function knownScheme(pack, scheme) {
113
+ if (pack.presets.some((p) => p.id === scheme)) return scheme;
114
+ const parts = String(scheme ?? '').split('-');
115
+ return pack.axes.map((a, i) => (a.options.some((o) => o.id === parts[i]) ? parts[i] : a.options[0].id)).join('-');
116
+ }
117
+
118
+ /**
119
+ * `pack`: the entry of `/api/figures`; `start`: { x, facing, enter, skin }; `bounds`: { W, H, floorY, S };
120
+ * `theme`: 'dark' | 'light'. Resolves to the body once it is ready.
121
+ */
122
+ export function loadBody({ layer, pack, start, theme, bounds, onEvent, onSound, onError }) {
123
+ return new Promise((resolve, reject) => {
124
+ const frame = document.createElement('iframe');
125
+ frame.setAttribute('sandbox', 'allow-scripts');
126
+ frame.setAttribute('aria-hidden', 'true');
127
+ frame.tabIndex = -1;
128
+ frame.className = 'figure-frame';
129
+ // the server lets the frame fetch the files of the pack it names (an installed one)
130
+ frame.src = `/figure-frame?pack=${encodeURIComponent(pack.id)}`;
131
+ // the frame's window onto the stage: all of it, or with the halo on, the halo's rect around the body (haloRect)
132
+ const clip = document.createElement('div');
133
+ clip.className = 'figure-clip';
134
+ clip.appendChild(frame);
135
+ let haloAt = '';
136
+ let ready = false, gone = false, seq = 0, size = bounds;
137
+ let layout = null, z = null, words = null;
138
+ const touches = touchGate();
139
+ const waits = new Map();
140
+ const post = (m) => { if (!gone) frame.contentWindow?.postMessage(m, '*'); };
141
+ const timer = setTimeout(() => fail(new Error(t('figure.notReady', { seconds: READY_MS / 1000 }))), READY_MS);
142
+
143
+ function close() {
144
+ if (gone) return;
145
+ gone = true;
146
+ clearTimeout(timer);
147
+ removeEventListener('message', onMessage);
148
+ clip.remove();
149
+ for (const done of waits.values()) done();
150
+ waits.clear();
151
+ }
152
+ function fail(err) {
153
+ if (gone) return;
154
+ close();
155
+ if (ready) onError?.(err); else reject(err);
156
+ }
157
+
158
+ const body = {
159
+ pack: pack.id,
160
+ get layout() { return layout; },
161
+ /** The frame's window on the stage, for animating the body as a whole (swap-motion.js); its inline style is the halo's. */
162
+ get el() { return clip; },
163
+ get z() { return z; },
164
+ /** The words of the pack's vocabulary its body said it knows, or null when it did not say. */
165
+ get words() { return words; },
166
+ /** Whether stage point `p` is on the body. */
167
+ hit: (p) => onBody(layout, p),
168
+ /** Advances the body `dt` seconds; with `draw` false (the pet window is hidden) it need not draw. */
169
+ tick(dt, draw = true, activity = null) { if (ready) post({ t: 'tick', dt, draw, activity }); },
170
+ do: (word) => post({ t: 'do', word }),
171
+ walk: (x, run, id) => post({ t: 'walk', x, run, id }),
172
+ /** One of the pack's own targets, `{ to, run, params }` as the World checked it. */
173
+ move: (args, id) => post({ t: 'move', args, id }),
174
+ /** Whether the pack asked for the windows (`setWindows`). */
175
+ needsWindows: Array.isArray(pack.needs) && pack.needs.includes('windows'),
176
+ /** The windows (`{ ledges, windows }` in stage pixels, or null), passed on only when the pack asked for them. */
177
+ setWindows(desk) { if (body.needsWindows) post({ t: 'windows', ledges: desk?.ledges ?? null, windows: desk?.windows ?? null }); },
178
+ stopWalk: (id) => post({ t: 'stop-walk', id }),
179
+ /** `type`: down, move, up, cancel, leave; `p` in stage pixels with `t` (ms). */
180
+ pointer(type, p) { if (type !== 'leave') touches.input(performance.now()); post({ t: 'pointer', type, p }); },
181
+ drop(p) { touches.input(performance.now()); post({ t: 'drop', p }); },
182
+ shift: (dx, dy) => post({ t: 'shift', dx, dy }),
183
+ place: (x, facing, y) => post({ t: 'place', x, facing, ...(typeof y === 'number' ? { y } : {}) }),
184
+ /** The page's states (see the kit's `set`), and `bounds` when the stage changed size. */
185
+ set(state) { if (state.bounds) size = state.bounds; post({ t: 'set', state }); },
186
+ cue: (kind) => post({ t: 'cue', kind }),
187
+ talk: () => post({ t: 'talk' }),
188
+ setScheme(id, o = {}) {
189
+ if (gone) return Promise.resolve();
190
+ const s = ++seq;
191
+ post({ t: 'scheme', id: knownScheme(pack, id), fade: o.fade ?? 0, seq: s });
192
+ return new Promise((done) => waits.set(s, done));
193
+ },
194
+ /**
195
+ * The light halo behind the body (pet-app's backdrop), as a CSS filter on the frame's window cut down to
196
+ * the body's surroundings (haloRect), so it blurs only those; a `k` or `reach` of 0 removes it. Called once a frame: it follows the body.
197
+ */
198
+ setHalo(k, reach) {
199
+ const r = k && reach > 0 ? haloRect(layout, size, reach, pack.effects?.reach) : null;
200
+ const c = r ? `rgba(184,184,184,${k.toFixed(2)})` : '';
201
+ // two blurs, the inner one 3/7 of the outer (the halo's look at the default reach of 7)
202
+ const inner = Math.max(1, Math.round(reach * 3 / 7));
203
+ const at = r ? `${r.x},${r.y},${r.w},${r.h},${c},${reach}` : '';
204
+ if (at === haloAt) return;
205
+ haloAt = at;
206
+ if (!r) { clip.removeAttribute('style'); frame.removeAttribute('style'); return; }
207
+ Object.assign(clip.style, { inset: 'auto', left: `${r.x}px`, top: `${r.y}px`, width: `${r.w}px`, height: `${r.h}px`, overflow: 'hidden', filter: `drop-shadow(0 0 ${inner}px ${c}) drop-shadow(0 0 ${reach}px ${c})` });
208
+ // the frame keeps the stage's size and place, so the body inside it neither moves nor resizes
209
+ Object.assign(frame.style, { inset: 'auto', left: `${-r.x}px`, top: `${-r.y}px`, width: `${size.W}px`, height: `${size.H}px` });
210
+ },
211
+ dispose: close,
212
+ };
213
+
214
+ async function onMessage(e) {
215
+ if (e.source !== frame.contentWindow) return;
216
+ const m = e.data || {};
217
+ if (m.t === 'loaded' && !ready) {
218
+ try {
219
+ const model = pack.model ? await (await fetch(new URL(pack.base + pack.model, location.href))).json() : null;
220
+ post({
221
+ t: 'init', entry: new URL(pack.base + pack.entry, location.href).href, export: pack.export,
222
+ base: new URL(pack.base, location.href).href, model, scheme: knownScheme(pack, start.scheme), start: { x: start.x, facing: start.facing, enter: start.enter, skin: start.skin }, theme, bounds: size,
223
+ language: language(),
224
+ });
225
+ } catch (err) { fail(err); }
226
+ } else if (m.t === 'ready' && !ready) {
227
+ ready = true;
228
+ clearTimeout(timer);
229
+ z = typeof m.z === 'string' ? m.z : null;
230
+ // only the manifest's words matter, and the list goes on to the World
231
+ if (Array.isArray(m.words)) words = pack.vocab.map((w) => w.id).filter((id) => m.words.includes(id));
232
+ resolve(body);
233
+ } else if (m.t === 'frame' && ready) {
234
+ layout = readLayout(m.layout, size);
235
+ z = typeof m.z === 'string' ? m.z : null;
236
+ for (const s of Array.isArray(m.sounds) ? m.sounds : []) {
237
+ if (typeof s?.name === 'string') onSound?.(s.name.slice(0, 64), typeof s.kind === 'string' ? s.kind : '', ...(Array.isArray(s.args) ? s.args.filter((a) => typeof a === 'number' || typeof a === 'boolean') : []));
238
+ }
239
+ for (const ev of Array.isArray(m.events) ? m.events : []) {
240
+ if (!ev || typeof ev.kind !== 'string') continue;
241
+ const d = ev.detail && typeof ev.detail === 'object' ? ev.detail : {};
242
+ // a touch only right after real pointer input, a crash only after a throw
243
+ if (ev.kind === 'touch' && !touches.take(d.kind, performance.now())) continue;
244
+ onEvent?.(ev.kind, d);
245
+ }
246
+ } else if (m.t === 'scheme') {
247
+ z = typeof m.z === 'string' ? m.z : null;
248
+ waits.get(m.seq)?.();
249
+ waits.delete(m.seq);
250
+ } else if (m.t === 'error') {
251
+ fail(new Error(m.message));
252
+ }
253
+ }
254
+ addEventListener('message', onMessage);
255
+ layer.appendChild(clip);
256
+ });
257
+ }