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
@@ -1,10 +1,9 @@
1
- // SPDX-License-Identifier: AGPL-3.0-or-later
2
- // Modified for Agent Speed (2026-11-26): additive pose, gait, gaze and expression from one activity layer.
3
1
  /**
4
2
  * The pet kit: a body that stands on the floor of the stage (or anywhere on it, `ground: 'free'`), walks, runs, jumps, sits, sleeps,
5
3
  * is picked up and thrown, makes faces and short gestures, with particles (hearts, tears, z's,
6
4
  * dust, notes) and a shadow. A figure pack builds its body on it (`createBody`) and only draws:
7
- * Packs may also ignore the kit and answer the body contract (web/figure-frame.js) on their own.
5
+ * Coo (web/coo/figure.js) and the whale (web/whale/figure.js) both do. A pack may also ignore the
6
+ * kit and answer the body contract (web/figure-frame.js) on its own.
8
7
  *
9
8
  * Coordinates: the figure is drawn in logo units, facing right, ground at y=256, inside a 256 square.
10
9
  * The stage places it with translate(AX AY) rotate(rot) scale(kx ky) translate(-ax -ay); `toStage`
@@ -14,8 +13,6 @@
14
13
  * happens to the body is told through `opts.onEvent`; the page around the frame does the rest.
15
14
  */
16
15
  export { createRig } from './rig.js';
17
- // A pack may import the kit directly through a different URL from the frame.
18
- export const activityLayer = Symbol.for('agent-speed.coopanion.activityLayer');
19
16
 
20
17
  export const f = n => Math.round(n * 10) / 10;
21
18
  export const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
@@ -40,7 +37,7 @@ export function heartD(cx, cy, s) {
40
37
 
41
38
  /* ---------- faces ----------
42
39
  What a face asks of the body and the figure: eye shapes and sizes, mouth gap, blush, marks over
43
- the head, particles. Each figure reads the channels it knows how to draw. */
40
+ the head, particles. Coo draws these as they are; a figure with its own art reads what it can. */
44
41
  const ring = o => ({ shape: 'ring', rx: 16, ry: 16, ...o });
45
42
  const yawn = t => { const p = (t % 4.2) / 1.6; return p < 1 ? Math.sin(Math.PI * p) ** 2 : 0; };
46
43
 
@@ -144,9 +141,6 @@ export function createPet(els, opts) {
144
141
  const onEvent = opts.onEvent || (() => {});
145
142
  const words = opts.words || {};
146
143
  let W = 0, H = 0, floorY = 0, S = .42, T = 0;
147
- let activity = null;
148
- const affordActivity = () => activity && !press && !pet.pulse && !pet.listening &&
149
- (pet.mode === 'idle' || pet.mode === 'walk' || pet.mode === 'run');
150
144
  let roam = opts.roam ?? 'free';
151
145
  let skin = opts.skin || null;
152
146
  let hold = 0; // until T: an order from outside is in progress, free roaming waits
@@ -164,6 +158,8 @@ export function createPet(els, opts) {
164
158
  pulse: null, walkId: 0, walkWord: null, listening: false, thinking: false, thoughtShown: false, placed: false, noteAt: 0, tearN: 0,
165
159
  cursor: '', status: null,
166
160
  };
161
+ let activityPose = null;
162
+ const activityLook = [0, 0];
167
163
  const pointer = { x: -1e4, y: -1e4, inside: false, vx: 0, samples: [] };
168
164
  let press = null, strokeAcc = 0, petCool = 0;
169
165
  /** Whether the last frame found the horizontal speed not finite: a run of such frames is logged once. */
@@ -378,7 +374,6 @@ export function createPet(els, opts) {
378
374
  if (m === 'sleep') return 'sleep';
379
375
  if (pet.expr && T < pet.exprUntil) return pet.expr;
380
376
  if (pet.thinking) return 'thinking';
381
- if (affordActivity() && activity.face) return activity.face;
382
377
  if (m === 'sit') return 'content';
383
378
  if (m === 'run') return 'run';
384
379
  return 'neutral';
@@ -421,11 +416,6 @@ export function createPet(els, opts) {
421
416
  let tk = 160, tc = 12, drowseT = 0;
422
417
  const still = !!opts.still?.();
423
418
  const free = roam !== 'off' && T > hold && !opts.dialogOpen?.() && !still;
424
- const accent = affordActivity() ? activity.energy : 0;
425
- const focus = affordActivity() ? activity.focus : 0;
426
- const beat = activity?.phase ?? 0;
427
- if ((m === 'sleep' || m === 'sit') && !press && !still &&
428
- ((activity?.energy ?? 0) > .13 || (activity?.focus ?? 0) > .35)) setMode('wake', { startle: true });
429
419
 
430
420
  pet.blinkT -= dt; pet.blinkAge += dt;
431
421
  if (pet.blinkT <= 0) { pet.blinkAge = 0; pet.blinkT = Math.random() < .2 ? .28 : rnd(2.2, 5.2); }
@@ -449,7 +439,7 @@ export function createPet(els, opts) {
449
439
  if (pet.turnAcc > .9) { pet.facing *= -1; pet.turnAcc = 0; }
450
440
  } else pet.turnAcc = 0;
451
441
  if (pet.listening) { lookT = [3, -4]; tiltT = -7; leanT = -2; }
452
- if (free && !accent && !focus && !pet.listening && T > pet.nextAt && !(pet.expr && T < pet.exprUntil)) decide();
442
+ if (free && !pet.listening && T > pet.nextAt && !(pet.expr && T < pet.exprUntil)) decide();
453
443
  break;
454
444
  }
455
445
  case 'walk': case 'run': {
@@ -591,29 +581,6 @@ export function createPet(els, opts) {
591
581
  }
592
582
  }
593
583
 
594
- // On the spot: a phase-continuous stepped sway. For a body already walking, shape the
595
- // existing gait instead of changing modes or issuing a second motion command.
596
- if (accent || focus) {
597
- const step = Math.sin(beat), sway = Math.sin(2 * beat);
598
- strideT += 10 * accent;
599
- liftT += 11 * accent;
600
- bobT += 8 * accent;
601
- sqT += accent * (.045 + .065 * sway);
602
- tiltT += step * accent * 9 - focus * 6;
603
- leanT += accent * (5 + 4 * sway) - focus * 3;
604
- lookT = [lookT[0] * (1 - .55 * focus) + 2 * accent * step + 2 * focus,
605
- lookT[1] * (1 - .55 * focus) - 2.5 * focus - accent * sway];
606
- }
607
-
608
- const liveGesture = accent ? activity.gesture : null;
609
- if (liveGesture && !custom?.gestures?.includes(liveGesture.kind) && !words[liveGesture.kind]?.motion) {
610
- const { kind, k } = liveGesture;
611
- const reach = envelope(k, .16, .75) * accent;
612
- if (kind === 'nod') leanT += 8 * Math.sin(k * Math.PI * 2) * reach;
613
- else if (kind === 'wave' || kind === 'dance') tiltT += 9 * Math.sin(k * Math.PI * 4) * reach;
614
- else if (kind === 'look') lookT[0] += 3 * reach;
615
- }
616
-
617
584
  // short gestures layered over whatever the body is doing
618
585
  // (a figure that lists a gesture in `figure.gestures` draws it itself, from the frame's `gesture`)
619
586
  if (pet.pulse) {
@@ -666,7 +633,7 @@ export function createPet(els, opts) {
666
633
  pet.look[0] = lerp(pet.look[0], lookT[0], ease(9, dt));
667
634
  pet.look[1] = lerp(pet.look[1], lookT[1], ease(9, dt));
668
635
  pet.gap[0] = lerp(pet.gap[0], fc.gap[0], ease(8, dt));
669
- pet.gap[1] = lerp(pet.gap[1], Math.min(64, fc.gap[1] + 6 * accent * Math.abs(Math.sin(beat))), ease(8, dt));
636
+ pet.gap[1] = lerp(pet.gap[1], fc.gap[1], ease(8, dt));
670
637
  // turning reads as a quick card flip rather than a mirror snap
671
638
  pet.faceVis = lerp(pet.faceVis, pet.facing, ease(15, dt));
672
639
  if (m !== 'walk' && m !== 'run' && m !== 'dance') pet.phase = lerp(pet.phase, Math.round(pet.phase / Math.PI) * Math.PI, ease(6, dt));
@@ -684,19 +651,18 @@ export function createPet(els, opts) {
684
651
  } else velXBad = false;
685
652
  pet.prevA = AX;
686
653
  // dancing stays put but rocks: the rock swings what hangs off the body (ears, hair, skirt), as moving does
687
- const swingT = clamp(-(pet.velX * .06 + (m === 'dance' || accent ? pet.tiltV * .22 : 0)) * Math.sign(pet.faceVis || 1) - 6 * accent * Math.sin(beat), -28, 28);
654
+ const swingT = clamp(-(pet.velX * .06 + (m === 'dance' ? pet.tiltV * .22 : 0)) * Math.sign(pet.faceVis || 1), -28, 28);
688
655
  pet.swingV += ((swingT - pet.swing) * 110 - pet.swingV * 7) * dt;
689
656
  pet.swing = clamp(pet.swing + pet.swingV * dt, -40, 40);
690
657
 
691
- const gaitPhase = m === 'idle' && accent ? beat : pet.phase;
692
- pet.low = pet.sitK * 29 + pet.bob * Math.abs(Math.sin(gaitPhase));
658
+ pet.low = pet.sitK * 29 + pet.bob * Math.abs(Math.sin(pet.phase));
693
659
  pet.feet.forEach((ft, i) => {
694
660
  const hx = HIPS[i][0], hy = HIPS[i][1] + pet.low;
695
661
  let tx, ty;
696
662
  if (m === 'drag') { tx = hx + 7 * Math.sin(T * 11 + i * 2.2); ty = hy + 36; }
697
663
  else if (m === 'air') { tx = hx + (i ? 9 : -9); ty = hy + 33; }
698
664
  else {
699
- const ph = gaitPhase + i * Math.PI;
665
+ const ph = pet.phase + i * Math.PI;
700
666
  const sx = hx + pet.stride * Math.sin(ph), sy = FOOT_Y - pet.lift * Math.max(0, Math.cos(ph));
701
667
  tx = lerp(sx, hx + 26, pet.sitK); ty = lerp(sy, FOOT_Y, pet.sitK);
702
668
  }
@@ -750,19 +716,23 @@ export function createPet(els, opts) {
750
716
  function render(draw = true) {
751
717
  const fc = pet._fc || FACES.neutral.f(0), fname = pet._fname || 'neutral';
752
718
  const drag = pet.mode === 'drag';
719
+ // Overlay activity on the existing stance: feet stay anchored and interaction/physics keep control.
720
+ const activity = !press && !pet.listening && !pet.thinking &&
721
+ (pet.mode === 'idle' || pet.mode === 'walk' || pet.mode === 'run') ? activityPose : null;
722
+ const energy = activity?.energy ?? 0, focus = activity?.focus ?? 0;
723
+ const beat = energy ? Math.sin(activity.phase) : 0;
753
724
  const br = Math.sin(T * (pet.mode === 'sleep' ? 1.7 : 2.4));
754
- const sx = (1 + pet.sq * .7) * (1 - .05 * pet.stretch) * (1 - .009 * br);
755
- const sy = (1 - pet.sq) * (1 + .09 * pet.stretch) * (1 + .016 * br);
725
+ const bounce = beat * energy;
726
+ const sx = (1 + pet.sq * .7) * (1 - .05 * pet.stretch) * (1 - .009 * br - .043 * bounce + .025 * focus);
727
+ const sy = (1 - pet.sq) * (1 + .09 * pet.stretch) * (1 + .016 * br + .086 * bounce - .048 * focus);
756
728
  const ax = 128, ay = drag ? 36 : 256;
757
729
  let AX = drag ? pet.dx : pet.x, AY = drag ? pet.dy : pet.fy;
758
- if (affordActivity() && pet.mode === 'idle') {
759
- AY -= S * 5 * activity.energy * Math.abs(Math.sin(activity.phase));
760
- }
761
730
  if (fc.shake) AX += Math.sin(T * 60) * 1.4;
762
731
  else if (pet.pulse?.kind === 'shiver') AX += Math.sin(T * 75) * 1.1 * envelope((T - pet.pulse.t0) / pet.pulse.dur, .08, .85);
763
732
  // a figure may keep tilt and lean off the whole group and bend its own parts instead
764
- const kx = S * pet.faceVis * sx, ky = S * sy, lean = pet.lean * pet.faceVis;
765
- const rot = custom?.groupTilt ? custom.groupTilt(pet.mode, pet.tilt, lean) : pet.tilt + lean;
733
+ const kx = S * pet.faceVis * sx, ky = S * sy, lean = (pet.lean + 5 * focus + 3 * energy) * pet.faceVis;
734
+ const baseRot = custom?.groupTilt ? custom.groupTilt(pet.mode, pet.tilt, lean) : pet.tilt + lean;
735
+ const rot = baseRot + (2.8 * bounce + 2 * focus) * pet.faceVis;
766
736
  pet.xf = { AX, AY, ax, ay, kx, ky, rot };
767
737
  const extent = figureExtent();
768
738
  if (!drag && extent && Math.min(...sideReach(extent)) < DEFAULT_HALF_WIDTH) {
@@ -783,13 +753,16 @@ export function createPet(els, opts) {
783
753
  if (pet.swapAge < .07 && pet.eyePrev) { eyes = pet.eyePrev; eyeClose = pet.swapAge / .07; }
784
754
  else if (pet.swapAge < .16) eyeClose = 1 - (pet.swapAge - .07) / .09;
785
755
  const face = { ...fc, eyes, gap: pet.gap.map(g => Math.min(64, g + pet.talkK * 12)), blush: pet.blushK };
786
- const reacting = affordActivity();
787
- const gesture = pet.pulse ? { kind: pet.pulse.kind, k: clamp((T - pet.pulse.t0) / pet.pulse.dur, 0, 1) }
788
- : reacting && activity.gesture ? { ...activity.gesture } : null;
756
+ const gesture = pet.pulse ? { kind: pet.pulse.kind, k: clamp((T - pet.pulse.t0) / pet.pulse.dur, 0, 1) } : null;
757
+ let look = pet.look;
758
+ if (energy || focus) {
759
+ activityLook[0] = look[0] + beat * 5 * energy + 3 * focus;
760
+ activityLook[1] = look[1] - beat * 3 * energy + 6 * focus;
761
+ look = activityLook;
762
+ }
789
763
  custom.draw(petG, face, {
790
- look: pet.look, legs, low: pet.low, t: T, blink, eyeClose, acc: skin, swing: pet.swing,
764
+ look, legs, low: pet.low, t: T, blink, eyeClose, acc: skin, swing: pet.swing,
791
765
  face: fname, mode: pet.mode, modeT: pet.modeT, talk: pet.talkK, status: pet.status, drowse: pet.drowse, sit: pet.sitK, facing: pet.faceVis, tilt: pet.tilt, lean, groupRot: rot, gesture,
792
- activity: activity && { kind: activity.kind, energy: activity.energy, focus: activity.focus, phase: activity.phase },
793
766
  });
794
767
 
795
768
  const footY = drag ? pet.dy + 220 * S * 1.09 : pet.fy;
@@ -970,8 +943,8 @@ export function createPet(els, opts) {
970
943
  custom?.setSkin?.(skin);
971
944
  return {
972
945
  pet, step, render, resize, act, setExpr, doWord, walkTo, stopWalk, toStage, hitPet, busy, layout,
946
+ setActivityPose: (pose) => { activityPose = pose; },
973
947
  pointerDown, pointerMove, pointerUp, pointerLeave, dropAt, shiftDrag,
974
- setActivity(value) { activity = value; },
975
948
  get pressing() { return !!press; },
976
949
  /** Pressed, carried, airborne, walking, running, dancing, turning round, or in a short gesture (nod, wave, bow…): motion that frames far apart show as jumps. */
977
950
  get moving() {
@@ -1068,10 +1041,10 @@ export function createBody(host, opts) {
1068
1041
  });
1069
1042
  return {
1070
1043
  step(dt, draw = true) { ctl.step(dt); ctl.render(draw); },
1044
+ setActivityPose: ctl.setActivityPose,
1071
1045
  layout: ctl.layout,
1072
1046
  resize: ctl.resize,
1073
1047
  do: ctl.doWord,
1074
- [activityLayer]: ctl.setActivity,
1075
1048
  words: [...KIT_EXPRESSIONS, ...KIT_MOTIONS, ...Object.keys(opts.words ?? {}).filter((w) => opts.words[w]?.expression || opts.words[w]?.motion)],
1076
1049
  walk: (x, run, id) => ctl.walkTo(x, run, id),
1077
1050
  stopWalk: (id) => ctl.stopWalk(id),
package/web/looks.js ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Saved looks (src/config.ts `SavedLook`): read at `GET /api/looks` and written whole through `POST /api/looks`.
3
+ * The dressing page saves, renames and removes them; the look wheel over the pet switches between them.
4
+ */
5
+ import { PALETTES, mini, normalizeSkin } from './coo/coo.js';
6
+
7
+ /** Resolves to the saved looks, or null when they could not be read. */
8
+ export const fetchLooks = () => fetch('/api/looks').then((r) => (r.ok ? r.json() : null)).then((l) => (Array.isArray(l) ? l : null)).catch(() => null);
9
+
10
+ /** Writes the whole list; resolves to the list the World kept, or null when the write failed. */
11
+ export const writeLooks = (looks) => fetch('/api/looks', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ looks }) })
12
+ .then((r) => (r.ok ? r.json() : null)).catch(() => null);
13
+
14
+ /** What tells two skins apart: a pack and its pick, or Coo's palette, accessories and their colors. */
15
+ function lookKey(raw) {
16
+ const s = normalizeSkin(raw);
17
+ return s.figure && s.figure !== 'coo'
18
+ ? JSON.stringify([s.figure, s.scheme ?? ''])
19
+ : JSON.stringify(['coo', s.palette, s.head, s.side, s.glasses, s.neck, s.colors]);
20
+ }
21
+ export const sameLook = (a, b) => lookKey(a) === lookKey(b);
22
+
23
+ /** The option of each axis a pack's `scheme` picks: a preset id, or the options joined by `-` in axis order. */
24
+ function picksOf(pack, scheme) {
25
+ const preset = pack.presets?.find((p) => p.id === scheme);
26
+ const parts = (scheme || '').split('-');
27
+ return (pack.axes ?? []).map((a, i) => (preset ? preset.pick?.[a.id] : parts[i]));
28
+ }
29
+
30
+ /**
31
+ * The picture of a pack's pick: the thumb of the last axis whose pick differs from the pack's first preset (an
32
+ * outfit changed shows the outfit, a palette changed the palette), else the first axis's; the pack's own without one.
33
+ */
34
+ function packThumb(pack, scheme) {
35
+ const axes = pack.axes ?? [];
36
+ const picks = picksOf(pack, scheme), base = picksOf(pack, pack.presets?.[0]?.id);
37
+ let i = axes.length - 1;
38
+ while (i > 0 && picks[i] === base[i]) i--;
39
+ return axes[i]?.options.find((o) => o.id === picks[i])?.thumb ?? pack.thumb ?? null;
40
+ }
41
+
42
+ const escAttr = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
43
+
44
+ /** Whether the look's figure is on hand: Coo always, a pack while it is installed. */
45
+ export const lookAvailable = (skin, packs) => { const f = normalizeSkin(skin).figure; return !f || f === 'coo' || !!packs?.some((p) => p.id === f); };
46
+
47
+ /**
48
+ * How much of its tile a look's picture fills for the size on screen it keeps: by the square root of the size, 72% at
49
+ * 100%, the whole tile from about 2× up, 40% at the least; a look without a size is drawn as at 100%.
50
+ */
51
+ const pictureFill = (scale) => Math.min(1, Math.max(.4, .72 * Math.sqrt(typeof scale === 'number' ? scale : 1)));
52
+
53
+ /**
54
+ * A look's picture as HTML: Coo drawn in its palette, or the pack's thumbnail, standing on the tile's bottom edge at
55
+ * `pictureFill(scale)` of it (`.look-pic`, drawn by the page); empty when the pack is gone.
56
+ */
57
+ export function lookPicture(skin, packs, dark, scale) {
58
+ const s = normalizeSkin(skin);
59
+ let pic = '';
60
+ if (!s.figure || s.figure === 'coo') {
61
+ const p = PALETTES.find((x) => x.id === s.palette) ?? PALETTES[0];
62
+ const [ink, eye] = dark ? p.d : p.l;
63
+ pic = `<svg viewBox="18 18 220 220" aria-hidden="true" style="--skin-ink:${ink};--skin-eye:${eye}">${mini('neutral', s)}</svg>`;
64
+ } else {
65
+ const pack = packs?.find((p) => p.id === s.figure);
66
+ const thumb = pack && packThumb(pack, s.scheme);
67
+ if (thumb) pic = `<img alt="" src="${escAttr(pack.base + thumb)}">`;
68
+ }
69
+ return pic && `<span class="look-pic" style="--look-fill:${pictureFill(scale).toFixed(3)}">${pic}</span>`;
70
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Microphone tap: mono float input at the context rate → 16 kHz PCM16 in 20 ms frames (320
3
+ * samples), posted to the page. Resampling averages the input samples that fall into each
4
+ * output sample, which is enough for speech recognition.
5
+ */
6
+ class PetMic extends AudioWorkletProcessor {
7
+ constructor() {
8
+ super();
9
+ this.step = sampleRate / 16000;
10
+ this.acc = 0;
11
+ this.sum = 0;
12
+ this.n = 0;
13
+ this.frame = new Int16Array(320);
14
+ this.at = 0;
15
+ }
16
+ process(inputs) {
17
+ const ch = inputs[0] && inputs[0][0];
18
+ if (!ch) return true;
19
+ for (let i = 0; i < ch.length; i++) {
20
+ this.sum += ch[i]; this.n++; this.acc += 1;
21
+ if (this.acc >= this.step) {
22
+ this.acc -= this.step;
23
+ const v = Math.max(-1, Math.min(1, this.sum / this.n));
24
+ this.sum = 0; this.n = 0;
25
+ this.frame[this.at++] = v < 0 ? v * 32768 : v * 32767;
26
+ if (this.at === this.frame.length) {
27
+ this.port.postMessage(this.frame.buffer, [this.frame.buffer]);
28
+ this.frame = new Int16Array(320);
29
+ this.at = 0;
30
+ }
31
+ }
32
+ }
33
+ return true;
34
+ }
35
+ }
36
+ registerProcessor('pet-mic', PetMic);
package/web/mic.js ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The pet page's microphone: 16 kHz mono through web/mic-worklet.js while the World asks for it.
3
+ * The capture opens on the chosen device while the inputs list it and on the system default input
4
+ * otherwise; a device change that moves this target (the default changing, the chosen device leaving
5
+ * or coming back) closes the stream and opens the new target. A capture whose track ended is opened
6
+ * again, and an open that failed for any reason but a permission denial is tried again on the next
7
+ * device change.
8
+ *
9
+ * `prefs.mic` is whether the World wants the microphone, `prefs.micDevice` the chosen deviceId or
10
+ * '' for the default; `send(msg)` goes to the World, `sendAudio(data)` carries the worklet's chunks.
11
+ */
12
+ export function createMic({ prefs, send, sendAudio }) {
13
+ const media = navigator.mediaDevices;
14
+ /** null, `{ starting }` while opening, or the open capture. */
15
+ let mic = null;
16
+ let retry = false;
17
+
18
+ /**
19
+ * Reports the inputs to the World and returns the capture's target: `deviceId` is the chosen device,
20
+ * or '' for the system default, and `key` changes when the input behind the target changes.
21
+ * Undefined when the inputs cannot be read or, before microphone access, told apart.
22
+ */
23
+ async function reportDevices() {
24
+ try {
25
+ const inputs = (await media.enumerateDevices()).filter((d) => d.kind === 'audioinput');
26
+ // before microphone access is granted the entries have an empty deviceId
27
+ const list = inputs.filter((d) => d.deviceId && d.deviceId !== 'default' && d.deviceId !== 'communications');
28
+ send({ t: 'devices', list: list.map((d) => ({ id: d.deviceId, label: d.label })) });
29
+ if (!inputs.some((d) => d.deviceId)) return undefined;
30
+ if (prefs.micDevice && list.some((d) => d.deviceId === prefs.micDevice)) return { deviceId: prefs.micDevice, key: prefs.micDevice };
31
+ // Chromium's 'default' entry keeps its deviceId when the input behind it changes
32
+ const input = inputs.find((d) => d.deviceId === 'default') ?? inputs[0];
33
+ return { deviceId: '', key: JSON.stringify([input.deviceId, input.groupId, input.label]) };
34
+ } catch (err) {
35
+ console.error(err);
36
+ return undefined;
37
+ }
38
+ }
39
+
40
+ async function start() {
41
+ if (mic) return;
42
+ retry = false;
43
+ const opening = mic = { starting: true };
44
+ // 拿到一半就失败时也要停麦关声卡,否则录音指示灯常亮到页面刷新
45
+ let stream = null, ctx = null;
46
+ try {
47
+ // read before opening: a report after it may already see the next default
48
+ const target = await reportDevices();
49
+ if (mic !== opening) return;
50
+ // AGC can change the system microphone volume on Windows.
51
+ const audio = { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: false };
52
+ // inputs that cannot be told apart yet: the chosen device is asked for by its id
53
+ const deviceId = target ? target.deviceId : prefs.micDevice;
54
+ if (deviceId) audio.deviceId = { exact: deviceId };
55
+ stream = await media.getUserMedia({ audio });
56
+ ctx = new AudioContext({ sampleRate: 16000 });
57
+ await ctx.audioWorklet.addModule('/web/mic-worklet.js');
58
+ // closed, or closed and opened again, while this one was opening
59
+ if (mic !== opening) { stream.getTracks().forEach((t) => t.stop()); ctx.close(); return; }
60
+ const node = new AudioWorkletNode(ctx, 'pet-mic');
61
+ const active = mic = { stream, ctx, node, deviceId, key: target?.key };
62
+ // chunks a replaced capture still had queued are dropped
63
+ node.port.onmessage = (e) => { if (mic === active) sendAudio(e.data); };
64
+ ctx.createMediaStreamSource(stream).connect(node);
65
+ for (const track of stream.getAudioTracks()) {
66
+ track.addEventListener('ended', () => {
67
+ if (mic !== active) return;
68
+ stop();
69
+ if (prefs.mic) void start();
70
+ });
71
+ }
72
+ send({ t: 'mic', state: 'on', detail: stream.getAudioTracks()[0]?.label || null });
73
+ // the labels are readable now; a change while opening may have moved the target away from this capture
74
+ void follow();
75
+ } catch (err) {
76
+ stream?.getTracks().forEach((t) => t.stop());
77
+ ctx?.close();
78
+ if (mic !== opening) return;
79
+ mic = null;
80
+ const denied = err?.name === 'NotAllowedError';
81
+ retry = !denied;
82
+ send({ t: 'mic', state: denied ? 'denied' : 'error', detail: String(err?.message || err) });
83
+ // access was granted, so the labels are readable: list the devices, another one may open where this one did not
84
+ if (!denied) void reportDevices();
85
+ }
86
+ }
87
+
88
+ /** Reopens the capture when its target is no longer the input it opened on. */
89
+ async function follow() {
90
+ const current = mic;
91
+ const target = await reportDevices();
92
+ if (mic !== current || target === undefined) return;
93
+ // opened before the inputs could be told apart: it is on the target when it asked for the same device
94
+ if (current.key === undefined && target.deviceId === current.deviceId) { current.key = target.key; return; }
95
+ if (target.key !== current.key) {
96
+ stop();
97
+ void start();
98
+ }
99
+ }
100
+
101
+ function stop() {
102
+ const m = mic;
103
+ mic = null;
104
+ retry = false;
105
+ if (!m || m.starting) return;
106
+ m.stream.getTracks().forEach((t) => t.stop());
107
+ m.ctx.close();
108
+ send({ t: 'mic', state: 'off' });
109
+ }
110
+
111
+ media?.addEventListener('devicechange', () => {
112
+ if (!mic) { if (prefs.mic && retry) void start(); }
113
+ else if (!mic.starting) void follow();
114
+ });
115
+
116
+ return { start, stop };
117
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Motion that code writes frame by frame, shared by the pet's pages and (bundled) the settings window. Each helper
3
+ * takes the time that passed or the clock, never a frame count, so it runs at the same speed on any display, and
4
+ * reads the window's motion level (motion-level.js) itself: low lands at once, medium drops overshoot. The callers
5
+ * keep their own frame clocks (frame-loop.js, the settings window's `lifecycle.frame`).
6
+ */
7
+ import { motionLevel } from './motion-level.js';
8
+
9
+ /**
10
+ * The share of the gap to a target (which may keep moving) one frame of `dt` seconds closes, `1 - e^(-rate·dt)`, so
11
+ * the easing runs at the same speed on any display; 1 at low motion.
12
+ */
13
+ export function approachShare(rate, dt, win = globalThis.window) {
14
+ if (motionLevel(win) === 'low') return 1;
15
+ return dt > 0 ? 1 - Math.exp(-rate * dt) : 0;
16
+ }
17
+
18
+ /**
19
+ * How far a change that started at `start` and runs `ms` milliseconds is at `now`, 0 to 1, linear; 1 at low motion.
20
+ * For callers that combine several timed changes and apply their curves themselves.
21
+ */
22
+ export function progress(start, ms, now, win = globalThis.window) {
23
+ if (motionLevel(win) === 'low' || ms <= 0) return 1;
24
+ return Math.min(1, Math.max(0, (now - start) / ms));
25
+ }
26
+
27
+ /**
28
+ * A duration the stylesheet gives `el` (or inherits to it) as a custom property, `--name: 160ms` or `.16s`, in
29
+ * milliseconds; `fallback` where it has none (no stylesheet, as in the tests). Scripts that wait for a CSS animation
30
+ * read its length here, so it is written once.
31
+ */
32
+ export function cssMs(el, name, fallback) {
33
+ const view = el?.ownerDocument?.defaultView;
34
+ const m = /^\s*(\d*\.?\d+)(ms|s)\s*$/.exec(view?.getComputedStyle?.(el).getPropertyValue(name) ?? '');
35
+ return m ? Math.round(parseFloat(m[1]) * (m[2] === 's' ? 1000 : 1)) : fallback;
36
+ }
37
+
38
+ /** A curve without overshoot, for medium motion: ease-out cubic. */
39
+ const steady = (k) => 1 - (1 - k) ** 3;
40
+
41
+ /**
42
+ * From `from` to `to` over `ms` milliseconds, starting at `start` (a `performance.now()` time): `at(now)` gives
43
+ * the value and `done(now)` whether it has arrived. `ease` maps 0–1 to 0–1; `overshoots` says it goes past 1,
44
+ * which medium motion replaces with a steady curve. At low motion it is at `to` at once.
45
+ */
46
+ export function tween(from, to, ms, { ease = steady, overshoots = false, start = performance.now(), win = globalThis.window } = {}) {
47
+ const level = motionLevel(win);
48
+ const curve = level === 'medium' && overshoots ? steady : ease;
49
+ const share = (now) => progress(start, ms, now, win);
50
+ return {
51
+ at: (now) => { const k = share(now); return k >= 1 ? to : from + (to - from) * curve(k); },
52
+ done: (now) => share(now) >= 1,
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Grows or shrinks `el` from the size it had (`was`: `w` and/or `h`, in pixels as offsetWidth/offsetHeight give
58
+ * them) to the one it has now, after the caller changed its content. Returns the animation, or nothing when the
59
+ * size did not change or at low motion (it is at its size already). `overshoots` marks an easing that goes past
60
+ * the end, which below full motion becomes a steady one.
61
+ */
62
+ export function growFrom(el, was, { duration, easing = 'ease', overshoots = false } = {}) {
63
+ const win = el.ownerDocument.defaultView, level = motionLevel(win);
64
+ if (level === 'low' || !el.animate) return undefined;
65
+ const now = { w: el.offsetWidth, h: el.offsetHeight };
66
+ const from = {}, to = {};
67
+ if (was.w !== undefined && was.w !== now.w) { from.width = was.w + 'px'; to.width = now.w + 'px'; }
68
+ if (was.h !== undefined && was.h !== now.h) { from.height = was.h + 'px'; to.height = now.h + 'px'; }
69
+ if (!Object.keys(from).length) return undefined;
70
+ return el.animate([from, to], { duration, easing: overshoots && level !== 'high' ? 'cubic-bezier(.2,.7,.3,1)' : easing });
71
+ }
72
+
73
+ /**
74
+ * How many of `length` characters are shown after `elapsed` seconds at `perSecond` characters a second; all of
75
+ * them at low motion.
76
+ */
77
+ export function typeOut(length, perSecond, elapsed, win = globalThis.window) {
78
+ if (motionLevel(win) === 'low' || !(perSecond > 0)) return length;
79
+ return Math.min(length, Math.max(0, Math.floor(elapsed * perSecond)));
80
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * How much interface motion a window shows: 'low', 'medium' or 'high'. Coo's own body is not part of it
3
+ * (walking has its own setting). The choice is 'system' (the default: 'low' when the system asks for reduced
4
+ * motion, 'high' otherwise) or one of the levels. `watchMotion` writes the level on the root element as
5
+ * `data-motion`, which the stylesheets read, and keeps it current as the system setting changes; scripts ask
6
+ * `motionLevel`. Used by the pet's pages and, bundled, by the settings window.
7
+ */
8
+
9
+ const QUERY = '(prefers-reduced-motion: reduce)';
10
+ const LEVELS = ['low', 'medium', 'high'];
11
+ /** @type {WeakMap<Window, string>} */
12
+ const choices = new WeakMap();
13
+ /** @type {WeakSet<Window>} */
14
+ const watched = new WeakSet();
15
+
16
+ const systemLevel = (win) => (win?.matchMedia?.(QUERY).matches ? 'low' : 'high');
17
+
18
+ /** The level for `win`: its choice, or the system's when the choice is 'system'. */
19
+ export function motionLevel(win) {
20
+ if (!win) return 'high';
21
+ const choice = choices.get(win);
22
+ if (choice && LEVELS.includes(choice)) return choice;
23
+ return systemLevel(win);
24
+ }
25
+
26
+ const apply = (win) => { win.document.documentElement.dataset.motion = motionLevel(win); };
27
+
28
+ /** Sets `win`'s choice ('system', 'low', 'medium' or 'high'; anything else counts as 'system') and applies it. */
29
+ export function setMotionChoice(win, choice) {
30
+ choices.set(win, LEVELS.includes(choice) ? choice : 'system');
31
+ if (watched.has(win)) apply(win);
32
+ }
33
+
34
+ /** Writes `data-motion` on `win`'s root now and whenever the level changes. Calling it again does nothing. */
35
+ export function watchMotion(win) {
36
+ if (watched.has(win)) return;
37
+ watched.add(win);
38
+ apply(win);
39
+ win.matchMedia?.(QUERY).addEventListener?.('change', () => apply(win));
40
+ }