@lubomirklimes/character-runtime 0.0.0-stage → 0.1.0-preview.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.
Files changed (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/dist/acs/acs15.d.ts +9 -0
  4. package/dist/acs/acs15.js +382 -0
  5. package/dist/acs/acs2-reader.d.ts +2 -0
  6. package/dist/acs/acs2-reader.js +277 -0
  7. package/dist/acs/binary.d.ts +1 -0
  8. package/dist/acs/binary.js +107 -0
  9. package/dist/acs/compound-file.d.ts +1 -0
  10. package/dist/acs/compound-file.js +326 -0
  11. package/dist/acs/document.d.ts +33 -0
  12. package/dist/acs/document.js +99 -0
  13. package/dist/acs/errors.d.ts +28 -0
  14. package/dist/acs/errors.js +41 -0
  15. package/dist/acs/image.d.ts +30 -0
  16. package/dist/acs/image.js +113 -0
  17. package/dist/acs/index.d.ts +11 -0
  18. package/dist/acs/index.js +10 -0
  19. package/dist/acs/lz.d.ts +7 -0
  20. package/dist/acs/lz.js +102 -0
  21. package/dist/acs/metadata.d.ts +14 -0
  22. package/dist/acs/metadata.js +126 -0
  23. package/dist/acs/model.d.ts +130 -0
  24. package/dist/acs/model.js +12 -0
  25. package/dist/acs/mouth.d.ts +37 -0
  26. package/dist/acs/mouth.js +43 -0
  27. package/dist/acs/wave.d.ts +53 -0
  28. package/dist/acs/wave.js +422 -0
  29. package/dist/browser/animation-frame-clock.d.ts +18 -0
  30. package/dist/browser/animation-frame-clock.js +42 -0
  31. package/dist/browser/canvas-renderer.d.ts +50 -0
  32. package/dist/browser/canvas-renderer.js +145 -0
  33. package/dist/browser/host.d.ts +84 -0
  34. package/dist/browser/host.js +206 -0
  35. package/dist/browser/index.d.ts +6 -0
  36. package/dist/browser/index.js +8 -0
  37. package/dist/browser/web-audio.d.ts +48 -0
  38. package/dist/browser/web-audio.js +205 -0
  39. package/dist/browser/web-speech.d.ts +131 -0
  40. package/dist/browser/web-speech.js +302 -0
  41. package/dist/core/activities.d.ts +10 -0
  42. package/dist/core/activities.js +479 -0
  43. package/dist/core/agent.d.ts +263 -0
  44. package/dist/core/agent.js +764 -0
  45. package/dist/core/audio.d.ts +17 -0
  46. package/dist/core/audio.js +174 -0
  47. package/dist/core/balloon.d.ts +43 -0
  48. package/dist/core/balloon.js +94 -0
  49. package/dist/core/clock.d.ts +32 -0
  50. package/dist/core/clock.js +51 -0
  51. package/dist/core/compositor.d.ts +22 -0
  52. package/dist/core/compositor.js +67 -0
  53. package/dist/core/events.d.ts +131 -0
  54. package/dist/core/events.js +1 -0
  55. package/dist/core/host.d.ts +29 -0
  56. package/dist/core/host.js +77 -0
  57. package/dist/core/index.d.ts +16 -0
  58. package/dist/core/index.js +13 -0
  59. package/dist/core/lipsync.d.ts +41 -0
  60. package/dist/core/lipsync.js +209 -0
  61. package/dist/core/random.d.ts +52 -0
  62. package/dist/core/random.js +105 -0
  63. package/dist/core/request.d.ts +68 -0
  64. package/dist/core/request.js +131 -0
  65. package/dist/core/resources.d.ts +70 -0
  66. package/dist/core/resources.js +243 -0
  67. package/dist/core/scheduler.d.ts +25 -0
  68. package/dist/core/scheduler.js +766 -0
  69. package/dist/core/source.d.ts +21 -0
  70. package/dist/core/source.js +54 -0
  71. package/dist/core/speech.d.ts +91 -0
  72. package/dist/core/speech.js +86 -0
  73. package/dist/core/text.d.ts +38 -0
  74. package/dist/core/text.js +97 -0
  75. package/dist/index.d.ts +2 -0
  76. package/dist/index.js +4 -0
  77. package/package.json +68 -4
@@ -0,0 +1,77 @@
1
+ import { DisposedError, InvalidArgumentError } from '../acs/errors.js';
2
+ import { CharacterAgent } from './agent.js';
3
+ import { ManualClock, SystemClock } from './clock.js';
4
+ import { CharacterSource } from './source.js';
5
+ /**
6
+ * Several independent agents on one clock, advanced in the order they were added (Runtime.md §17). The host shares only time and the
7
+ * update order, which makes cross-agent waits deterministic.
8
+ */
9
+ export class AgentHost {
10
+ list = [];
11
+ disposed = false;
12
+ clock;
13
+ constructor(clock = new SystemClock()) {
14
+ this.clock = clock;
15
+ }
16
+ get agents() {
17
+ return [...this.list];
18
+ }
19
+ /** Creates an agent for a source on this host's clock and adds it. */
20
+ create(source, options = {}) {
21
+ return this.add(new CharacterAgent(source, { ...options, clock: this.clock }));
22
+ }
23
+ /** Loads a character (URL, Blob/File, ArrayBuffer or typed array) and adds an agent for it. */
24
+ async load(input, options = {}) {
25
+ return this.create(await CharacterSource.load(input), options);
26
+ }
27
+ /** Adds an agent created on this host's clock (advanced after the agents added before it). */
28
+ add(agent) {
29
+ if (agent.clock !== this.clock)
30
+ throw new InvalidArgumentError('The agent uses another clock; create it on this host.');
31
+ if (this.disposed)
32
+ throw new DisposedError('The host has been disposed.');
33
+ if (!this.list.includes(agent))
34
+ this.list.push(agent);
35
+ return agent;
36
+ }
37
+ /** Removes and disposes one agent (its requests are cancelled, which releases waits of other agents on them). */
38
+ unload(agent) {
39
+ const index = this.list.indexOf(agent);
40
+ if (index < 0)
41
+ return false;
42
+ this.list.splice(index, 1);
43
+ agent.dispose();
44
+ return true;
45
+ }
46
+ /** Advances every agent to `now` (default: the clock), in the order added, and returns all their events. */
47
+ advance(now = this.clock.nowMs) {
48
+ if (this.disposed)
49
+ return [];
50
+ const all = [];
51
+ for (const agent of [...this.list])
52
+ all.push(...agent.advance(now));
53
+ return all;
54
+ }
55
+ /** With a manual clock: advances in steps until `done()` holds or `maxMs` passed. */
56
+ runUntil(done, stepMs = 10, maxMs = 600_000) {
57
+ const clock = this.clock;
58
+ if (!(clock instanceof ManualClock))
59
+ throw new InvalidArgumentError('runUntil needs a ManualClock.');
60
+ const end = clock.nowMs + maxMs;
61
+ this.advance();
62
+ while (!done() && clock.nowMs < end) {
63
+ clock.advance(stepMs);
64
+ this.advance();
65
+ }
66
+ }
67
+ /** Disposes every agent; every request handle completes. */
68
+ dispose() {
69
+ if (this.disposed)
70
+ return;
71
+ this.disposed = true;
72
+ const agents = [...this.list];
73
+ this.list.length = 0;
74
+ for (const agent of agents)
75
+ agent.dispose();
76
+ }
77
+ }
@@ -0,0 +1,16 @@
1
+ export { ManualClock, SystemClock, DelegateClock, type Clock } from './clock.js';
2
+ export { AgentRandom, ScriptedRandom, splitMix64, type RandomSource } from './random.js';
3
+ export { CharacterSource, type CharacterInput } from './source.js';
4
+ export { CharacterResources, type ResourceBudget, type ResourceStatistics, type CacheStatistics } from './resources.js';
5
+ export { composeIndexed, composeFrame, composeMouthFrame, type IndexedLayer } from './compositor.js';
6
+ export { CharacterAgent, type AgentOptions, type BalloonOptions, type SpeakOptions, type PresentedFrame, type SpeechState, type StopKinds, } from './agent.js';
7
+ export { AgentHost } from './host.js';
8
+ export { AgentRequest, type RequestResult, type SpeechProgress } from './request.js';
9
+ export { ALL_REQUEST_KINDS, STOP_ALL_DEFAULT_KINDS, RequestFailureCode, type RequestKind, type RequestStatus, type RequestEndReason, } from './scheduler.js';
10
+ export type { AgentEvent, AgentEventType, AgentEventOf, AgentVisibility, AnimationCause } from './events.js';
11
+ export type { AudioOutput, AudioLimits } from './audio.js';
12
+ export type { IdleOptions } from './activities.js';
13
+ export { balloonStyleFor, DEFAULT_BALLOON_STYLE, HIDDEN_BALLOON, type BalloonKind, type BalloonState, type BalloonStyle, type Point, } from './balloon.js';
14
+ export { buildLipSync, approximateCues, boundCues, cuesFromPhonemes, visemeOfPhoneme, shapeOfViseme, letterClass, MAX_CUES, type LipSyncSource, type VisemeCue, type SpeechPhoneme, } from './lipsync.js';
15
+ export { selectVoice, languageOfLangId, FakeSpeechProvider, silentPcm, type SpeechProvider, type SpeechVoice, type SpeechVoiceGender, type SpeechSynthesisRequest, type SpeechAudio, type SpeechContent, type SpeechVoiceDecision, type FakeSpeechOptions, } from './speech.js';
16
+ export { pacedSpeech, wrapText, textWords, textLength, type SpeechWordMark, type TextWord, type PacingOptions } from './text.js';
@@ -0,0 +1,13 @@
1
+ export { ManualClock, SystemClock, DelegateClock } from './clock.js';
2
+ export { AgentRandom, ScriptedRandom, splitMix64 } from './random.js';
3
+ export { CharacterSource } from './source.js';
4
+ export { CharacterResources } from './resources.js';
5
+ export { composeIndexed, composeFrame, composeMouthFrame } from './compositor.js';
6
+ export { CharacterAgent, } from './agent.js';
7
+ export { AgentHost } from './host.js';
8
+ export { AgentRequest } from './request.js';
9
+ export { ALL_REQUEST_KINDS, STOP_ALL_DEFAULT_KINDS, RequestFailureCode, } from './scheduler.js';
10
+ export { balloonStyleFor, DEFAULT_BALLOON_STYLE, HIDDEN_BALLOON, } from './balloon.js';
11
+ export { buildLipSync, approximateCues, boundCues, cuesFromPhonemes, visemeOfPhoneme, shapeOfViseme, letterClass, MAX_CUES, } from './lipsync.js';
12
+ export { selectVoice, languageOfLangId, FakeSpeechProvider, silentPcm, } from './speech.js';
13
+ export { pacedSpeech, wrapText, textWords, textLength } from './text.js';
@@ -0,0 +1,41 @@
1
+ import { type SpeechWordMark } from './text.js';
2
+ /** Where the mouth timing of a speech comes from (Runtime.md §15.1). */
3
+ export type LipSyncSource = 'none' | 'provider-visemes' | 'phonemes' | 'recorded-cues' | 'approximate';
4
+ /** A mouth cue: from `timeMs` on, the ACS shape `shape` (null = the frame's own mouth, no overlay). */
5
+ export interface VisemeCue {
6
+ readonly timeMs: number;
7
+ readonly shape: number | null;
8
+ }
9
+ /** A phoneme in IPA as a provider reports it. */
10
+ export interface SpeechPhoneme {
11
+ readonly offsetMs: number;
12
+ readonly durationMs: number;
13
+ readonly ipa: string;
14
+ }
15
+ /** Most cues of one speech. */
16
+ export declare const MAX_CUES = 4096;
17
+ /** The ACS shape of a SAPI 5 viseme class; class 0 (silence) is null. */
18
+ export declare function shapeOfViseme(sapiViseme: number): number | null;
19
+ /** The SAPI 5 viseme class of an IPA phoneme (length and stress marks ignored; unknown symbols by their first character, else 19). */
20
+ export declare function visemeOfPhoneme(ipa: string): number;
21
+ /** The SAPI 5 viseme class the spelling approximation uses for a letter (Runtime.md §15.2). */
22
+ export declare function letterClass(c: string): number;
23
+ /** Sorted, bounded cues that end with the frame's own mouth at the speech end; consecutive equal shapes are merged. */
24
+ export declare function boundCues(cues: readonly VisemeCue[], durationMs: number): VisemeCue[];
25
+ /** Phoneme timing mapped through the SAPI classes. */
26
+ export declare function cuesFromPhonemes(phonemes: readonly SpeechPhoneme[], durationMs: number): VisemeCue[];
27
+ /**
28
+ * Approximate lip-sync from spelling (not phoneme-accurate): each word's interval (from word marks, or the text distributed by length)
29
+ * is shared equally by its letters over 85 % of it (at least all but 80 ms); punctuation and the gaps between words close the mouth.
30
+ */
31
+ export declare function approximateCues(text: string, marks: readonly SpeechWordMark[], durationMs: number): VisemeCue[];
32
+ /** The cues of a speech and their source, in order of preference (Runtime.md §15.1). */
33
+ export declare function buildLipSync(speech: {
34
+ durationMs: number;
35
+ words: readonly SpeechWordMark[];
36
+ visemes: readonly VisemeCue[];
37
+ phonemes: readonly SpeechPhoneme[];
38
+ }, text: string, recorded: boolean): {
39
+ cues: VisemeCue[];
40
+ source: LipSyncSource;
41
+ };
@@ -0,0 +1,209 @@
1
+ import { InvalidArgumentError } from '../acs/errors.js';
2
+ import { textWords } from './text.js';
3
+ /** Most cues of one speech. */
4
+ export const MAX_CUES = 4096;
5
+ /** The ACS shape of each SAPI 5 viseme class 0–21 (class 0, silence, is shown as no overlay). */
6
+ const SAPI_SHAPES = [0, 2, 4, 5, 3, 2, 5, 6, 6, 5, 6, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0];
7
+ /** The ACS shape of a SAPI 5 viseme class; class 0 (silence) is null. */
8
+ export function shapeOfViseme(sapiViseme) {
9
+ if (sapiViseme === 0)
10
+ return null;
11
+ const shape = SAPI_SHAPES[sapiViseme];
12
+ if (shape === undefined)
13
+ throw new RangeError('SAPI viseme classes are 0..21.');
14
+ return shape;
15
+ }
16
+ /** The SAPI 5 viseme class of an IPA phoneme (length and stress marks ignored; unknown symbols by their first character, else 19). */
17
+ export function visemeOfPhoneme(ipa) {
18
+ const p = trimEnd(trimStart(ipa.trim(), 'ˈˌ'), 'ː:ˈˌ');
19
+ switch (p) {
20
+ case '':
21
+ case '_':
22
+ case '.': return 0;
23
+ case 'æ':
24
+ case 'ə':
25
+ case 'ʌ':
26
+ case 'a': return 1;
27
+ case 'ɑ':
28
+ case 'ɒ': return 2;
29
+ case 'ɔ': return 3;
30
+ case 'ɛ':
31
+ case 'e':
32
+ case 'eɪ':
33
+ case 'ʊ': return 4;
34
+ case 'ɝ':
35
+ case 'ɚ':
36
+ case 'ɜ': return 5;
37
+ case 'j':
38
+ case 'i':
39
+ case 'ɪ':
40
+ case 'ɨ':
41
+ case 'y': return 6;
42
+ case 'w':
43
+ case 'u': return 7;
44
+ case 'oʊ':
45
+ case 'o':
46
+ case 'əʊ': return 8;
47
+ case 'aʊ': return 9;
48
+ case 'ɔɪ': return 10;
49
+ case 'aɪ': return 11;
50
+ case 'h': return 12;
51
+ case 'ɹ':
52
+ case 'r':
53
+ case 'ɾ': return 13;
54
+ case 'l': return 14;
55
+ case 's':
56
+ case 'z': return 15;
57
+ case 'ʃ':
58
+ case 'tʃ':
59
+ case 'dʒ':
60
+ case 'ʒ': return 16;
61
+ case 'θ':
62
+ case 'ð': return 17;
63
+ case 'f':
64
+ case 'v': return 18;
65
+ case 'd':
66
+ case 't':
67
+ case 'n': return 19;
68
+ case 'k':
69
+ case 'g':
70
+ case 'ɡ':
71
+ case 'ŋ': return 20;
72
+ case 'p':
73
+ case 'b':
74
+ case 'm': return 21;
75
+ default: return p.length > 1 ? visemeOfPhoneme(p.substring(0, 1)) : 19;
76
+ }
77
+ }
78
+ function trimStart(s, chars) {
79
+ let i = 0;
80
+ while (i < s.length && chars.includes(s[i]))
81
+ i++;
82
+ return s.substring(i);
83
+ }
84
+ function trimEnd(s, chars) {
85
+ let i = s.length;
86
+ while (i > 0 && chars.includes(s[i - 1]))
87
+ i--;
88
+ return s.substring(0, i);
89
+ }
90
+ const LETTER = /^\p{L}$/u;
91
+ /** The SAPI 5 viseme class the spelling approximation uses for a letter (Runtime.md §15.2). */
92
+ export function letterClass(c) {
93
+ const lower = c.toLowerCase();
94
+ const l = lower.length === 1 ? lower : c;
95
+ if ('aáàâäãåą'.includes(l))
96
+ return 2;
97
+ if ('eéěèêëę'.includes(l))
98
+ return 4;
99
+ if ('iíìîïyýÿ'.includes(l))
100
+ return 6;
101
+ if ('oóòôöõő'.includes(l))
102
+ return 8;
103
+ if ('uúůùûüűw'.includes(l))
104
+ return 7;
105
+ if ('mbp'.includes(l))
106
+ return 21;
107
+ if ('fv'.includes(l))
108
+ return 18;
109
+ return LETTER.test(l) ? 19 : 0;
110
+ }
111
+ /** Sorted, bounded cues that end with the frame's own mouth at the speech end; consecutive equal shapes are merged. */
112
+ export function boundCues(cues, durationMs) {
113
+ const sorted = cues.filter((c) => Number.isFinite(c.timeMs) && c.timeMs >= 0).map((c, i) => ({ c, i }))
114
+ .sort((a, b) => a.c.timeMs - b.c.timeMs || a.i - b.i).map((x) => x.c);
115
+ const result = [];
116
+ for (const cue of sorted) {
117
+ if (result.length > 0 && result[result.length - 1].shape === cue.shape)
118
+ continue;
119
+ if (result.length >= MAX_CUES - 1)
120
+ break;
121
+ result.push(cue);
122
+ }
123
+ const end = Math.max(durationMs, result.length > 0 ? result[result.length - 1].timeMs : 0);
124
+ if (result.length === 0 || result[result.length - 1].shape !== null)
125
+ result.push({ timeMs: end, shape: null });
126
+ return result;
127
+ }
128
+ /** Phoneme timing mapped through the SAPI classes. */
129
+ export function cuesFromPhonemes(phonemes, durationMs) {
130
+ return [...phonemes.map((p) => ({ timeMs: p.offsetMs, shape: shapeOfViseme(visemeOfPhoneme(p.ipa)) })), { timeMs: durationMs, shape: null }];
131
+ }
132
+ /**
133
+ * Approximate lip-sync from spelling (not phoneme-accurate): each word's interval (from word marks, or the text distributed by length)
134
+ * is shared equally by its letters over 85 % of it (at least all but 80 ms); punctuation and the gaps between words close the mouth.
135
+ */
136
+ export function approximateCues(text, marks, durationMs) {
137
+ const words = textWords(text);
138
+ if (words.length === 0 || !(durationMs > 0))
139
+ return [];
140
+ const spans = [];
141
+ if (marks.length > 0) {
142
+ for (let i = 0; i < words.length; i++) {
143
+ const w = words[i];
144
+ let start = i === 0 ? 0 : spans[i - 1].start;
145
+ for (const m of marks)
146
+ if (m.textStart >= w.start && m.textStart < w.start + w.length) {
147
+ start = m.offsetMs;
148
+ break;
149
+ }
150
+ spans.push({ start, end: -1, word: w });
151
+ }
152
+ }
153
+ else {
154
+ const total = text.length;
155
+ for (const w of words)
156
+ spans.push({ start: (durationMs * w.start) / total, end: -1, word: w });
157
+ }
158
+ for (let i = 0; i < spans.length; i++) {
159
+ const next = i + 1 < spans.length ? spans[i + 1].start : durationMs;
160
+ const length = Math.max(0, next - spans[i].start);
161
+ spans[i].end = spans[i].start + Math.min(length, Math.max(length * 0.85, length - 80));
162
+ }
163
+ const cues = [];
164
+ for (const { start, end, word } of spans) {
165
+ if (end <= start)
166
+ continue;
167
+ const step = (end - start) / Math.max(1, word.length);
168
+ for (let k = 0; k < word.length; k++)
169
+ cues.push({ timeMs: start + k * step, shape: shapeOfViseme(letterClass(text[word.start + k])) });
170
+ cues.push({ timeMs: end, shape: null });
171
+ }
172
+ return boundCues(cues, durationMs);
173
+ }
174
+ /** The cues of a speech and their source, in order of preference (Runtime.md §15.1). */
175
+ export function buildLipSync(speech, text, recorded) {
176
+ if (speech.visemes.length > 0)
177
+ return { cues: boundCues(speech.visemes, speech.durationMs), source: recorded ? 'recorded-cues' : 'provider-visemes' };
178
+ if (speech.phonemes.length > 0)
179
+ return { cues: boundCues(cuesFromPhonemes(speech.phonemes, speech.durationMs), speech.durationMs), source: 'phonemes' };
180
+ if (textWords(text).length === 0)
181
+ return { cues: [], source: 'none' };
182
+ return { cues: approximateCues(text, speech.words, speech.durationMs), source: 'approximate' };
183
+ }
184
+ /** @internal A mouth timeline: the shape at a time is the latest cue at or before it. */
185
+ export class MouthTimeline {
186
+ cues = [];
187
+ load(source) {
188
+ if (source.length > MAX_CUES)
189
+ throw new InvalidArgumentError('Viseme event limit exceeded.');
190
+ let last = -1;
191
+ for (const cue of source) {
192
+ if (!Number.isFinite(cue.timeMs) || cue.timeMs < 0 || cue.timeMs < last || (cue.shape !== null && !(Number.isInteger(cue.shape) && cue.shape >= 0 && cue.shape <= 6)))
193
+ throw new InvalidArgumentError('Invalid viseme timestamp/order/shape.');
194
+ last = cue.timeMs;
195
+ }
196
+ this.cues = source;
197
+ }
198
+ at(time) {
199
+ let lo = 0, hi = this.cues.length;
200
+ while (lo < hi) {
201
+ const mid = (lo + hi) >> 1;
202
+ if (this.cues[mid].timeMs <= time)
203
+ lo = mid + 1;
204
+ else
205
+ hi = mid;
206
+ }
207
+ return lo === 0 ? null : this.cues[lo - 1].shape;
208
+ }
209
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The random source of the runtime (Runtime.md §3): branch selection draws {@link RandomSource.nextPercent}, state and idle selection
3
+ * draw {@link RandomSource.nextInt}.
4
+ */
5
+ export interface RandomSource {
6
+ /** A sample in [0, 100). */
7
+ nextPercent(): number;
8
+ /** A uniformly distributed sample in [0, bound). */
9
+ nextInt(bound: number): number;
10
+ }
11
+ /** One SplitMix64 step on a 64-bit state; returns the new state and the output. */
12
+ export declare function splitMix64(state: bigint): {
13
+ state: bigint;
14
+ value: bigint;
15
+ };
16
+ /**
17
+ * The specified CharacterRuntime generator, version 1: xoshiro128** on four 32-bit words, seeded by two SplitMix64 outputs. The seed's
18
+ * 64-bit two's-complement value is the SplitMix64 state. 64-bit arithmetic (BigInt) is used only while seeding.
19
+ */
20
+ export declare class AgentRandom implements RandomSource {
21
+ private s0;
22
+ private s1;
23
+ private s2;
24
+ private s3;
25
+ /** @param seed An integer seed (a safe integer or a bigint in the signed 64-bit range). */
26
+ constructor(seed?: number | bigint);
27
+ /** The state words (s0, s1, s2, s3). */
28
+ get state(): readonly [number, number, number, number];
29
+ /** The next 32-bit output (an unsigned integer). */
30
+ nextUint32(): number;
31
+ /** A uniformly distributed integer in [0, bound) for 1 ≤ bound < 2^31: threshold = 2^32 mod bound; words below it are rejected. */
32
+ nextInt(bound: number): number;
33
+ nextPercent(): number;
34
+ }
35
+ /**
36
+ * A source that supplies percent samples from a list (tests): bounded integers up to 100 draw samples and reject those at or above
37
+ * 100 − (100 mod bound). Throws when the samples run out.
38
+ */
39
+ export declare class ScriptedRandom implements RandomSource {
40
+ private readonly samples;
41
+ private readonly onExhausted;
42
+ private next;
43
+ constructor(samples: readonly number[], onExhausted?: () => Error);
44
+ /** Samples drawn so far. */
45
+ get drawn(): number;
46
+ nextPercent(): number;
47
+ nextInt(bound: number): number;
48
+ }
49
+ /** Bounded sampling over percent samples (bounds 1–100): the documented rejection of the biased tail. */
50
+ export declare function percentNextInt(source: {
51
+ nextPercent(): number;
52
+ }, bound: number): number;
@@ -0,0 +1,105 @@
1
+ const MASK64 = (1n << 64n) - 1n;
2
+ /** One SplitMix64 step on a 64-bit state; returns the new state and the output. */
3
+ export function splitMix64(state) {
4
+ const next = (state + 0x9e3779b97f4a7c15n) & MASK64;
5
+ let z = next;
6
+ z = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & MASK64;
7
+ z = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & MASK64;
8
+ return { state: next, value: z ^ (z >> 31n) };
9
+ }
10
+ const rotl = (x, k) => ((x << k) | (x >>> (32 - k))) >>> 0;
11
+ /**
12
+ * The specified CharacterRuntime generator, version 1: xoshiro128** on four 32-bit words, seeded by two SplitMix64 outputs. The seed's
13
+ * 64-bit two's-complement value is the SplitMix64 state. 64-bit arithmetic (BigInt) is used only while seeding.
14
+ */
15
+ export class AgentRandom {
16
+ s0;
17
+ s1;
18
+ s2;
19
+ s3;
20
+ /** @param seed An integer seed (a safe integer or a bigint in the signed 64-bit range). */
21
+ constructor(seed = 0) {
22
+ if (typeof seed === 'number' && !Number.isSafeInteger(seed))
23
+ throw new RangeError('The seed must be a safe integer.');
24
+ let state = BigInt.asUintN(64, BigInt(seed));
25
+ const a = splitMix64(state);
26
+ state = a.state;
27
+ const b = splitMix64(state);
28
+ this.s0 = Number(a.value & 0xffffffffn);
29
+ this.s1 = Number(a.value >> 32n);
30
+ this.s2 = Number(b.value & 0xffffffffn);
31
+ this.s3 = Number(b.value >> 32n);
32
+ if ((this.s0 | this.s1 | this.s2 | this.s3) === 0)
33
+ this.s0 = 1;
34
+ }
35
+ /** The state words (s0, s1, s2, s3). */
36
+ get state() {
37
+ return [this.s0, this.s1, this.s2, this.s3];
38
+ }
39
+ /** The next 32-bit output (an unsigned integer). */
40
+ nextUint32() {
41
+ const result = Math.imul(rotl(Math.imul(this.s1, 5) >>> 0, 7), 9) >>> 0;
42
+ const t = (this.s1 << 9) >>> 0;
43
+ this.s2 = (this.s2 ^ this.s0) >>> 0;
44
+ this.s3 = (this.s3 ^ this.s1) >>> 0;
45
+ this.s1 = (this.s1 ^ this.s2) >>> 0;
46
+ this.s0 = (this.s0 ^ this.s3) >>> 0;
47
+ this.s2 = (this.s2 ^ t) >>> 0;
48
+ this.s3 = rotl(this.s3, 11);
49
+ return result;
50
+ }
51
+ /** A uniformly distributed integer in [0, bound) for 1 ≤ bound < 2^31: threshold = 2^32 mod bound; words below it are rejected. */
52
+ nextInt(bound) {
53
+ if (!Number.isInteger(bound) || bound < 1 || bound > 0x7fffffff)
54
+ throw new RangeError('The bound must be an integer in [1, 2^31).');
55
+ const threshold = 0x100000000 % bound;
56
+ for (;;) {
57
+ const r = this.nextUint32();
58
+ if (r >= threshold)
59
+ return r % bound;
60
+ }
61
+ }
62
+ nextPercent() {
63
+ return this.nextInt(100);
64
+ }
65
+ }
66
+ /**
67
+ * A source that supplies percent samples from a list (tests): bounded integers up to 100 draw samples and reject those at or above
68
+ * 100 − (100 mod bound). Throws when the samples run out.
69
+ */
70
+ export class ScriptedRandom {
71
+ samples;
72
+ onExhausted;
73
+ next = 0;
74
+ constructor(samples, onExhausted = () => new Error('The scripted random source ran out of samples.')) {
75
+ this.samples = samples;
76
+ this.onExhausted = onExhausted;
77
+ }
78
+ /** Samples drawn so far. */
79
+ get drawn() {
80
+ return this.next;
81
+ }
82
+ nextPercent() {
83
+ if (this.next >= this.samples.length)
84
+ throw this.onExhausted();
85
+ return this.samples[this.next++];
86
+ }
87
+ nextInt(bound) {
88
+ return percentNextInt(this, bound);
89
+ }
90
+ }
91
+ /** Bounded sampling over percent samples (bounds 1–100): the documented rejection of the biased tail. */
92
+ export function percentNextInt(source, bound) {
93
+ if (!Number.isInteger(bound) || bound < 1 || bound > 100)
94
+ throw new RangeError('Percent-sample sources support bounds 1..100.');
95
+ if (bound === 1)
96
+ return 0;
97
+ const limit = 100 - (100 % bound);
98
+ let sample;
99
+ do {
100
+ sample = source.nextPercent();
101
+ if (!(sample >= 0 && sample < 100))
102
+ throw new Error('nextPercent must return a value in [0, 100).');
103
+ } while (sample >= limit);
104
+ return sample % bound;
105
+ }
@@ -0,0 +1,68 @@
1
+ import type { CharacterAgent } from './agent.js';
2
+ import type { RequestEndReason, RequestKind, RequestStatus } from './scheduler.js';
3
+ /** The terminal outcome of a request. */
4
+ export interface RequestResult {
5
+ readonly requestId: number;
6
+ readonly kind: RequestKind;
7
+ readonly name: string;
8
+ readonly status: RequestStatus;
9
+ readonly reason: RequestEndReason;
10
+ /** Diagnostic text (not normative). */
11
+ readonly detail: string;
12
+ /** The failure code of a failed request (Runtime.md §4.2), otherwise an empty string. */
13
+ readonly failureCode: string;
14
+ readonly startedAtMs: number | null;
15
+ readonly endedAtMs: number;
16
+ }
17
+ /** Progress of the speech of a Speak or Think request. */
18
+ export type SpeechProgress = 'none' | 'synthesizing' | 'ready' | 'speaking' | 'ended';
19
+ /**
20
+ * The handle of one submitted request. Every accepted request reaches exactly one terminal state; {@link started} and
21
+ * {@link completion} always resolve, never reject.
22
+ */
23
+ export declare class AgentRequest {
24
+ readonly agent: CharacterAgent;
25
+ readonly kind: RequestKind;
26
+ readonly name: string;
27
+ readonly waitTarget: AgentRequest | null;
28
+ /** The request id within its agent (1, 2, 3 … in submission order). */
29
+ id: number;
30
+ private statusValue;
31
+ private reasonValue;
32
+ private detailValue;
33
+ private failureCodeValue;
34
+ private startedAt;
35
+ private endedAt;
36
+ private speechValue;
37
+ private speechAudio;
38
+ private speechMs;
39
+ private speechNoteValue;
40
+ private resolveStarted;
41
+ private resolveCompletion;
42
+ private startedSettled;
43
+ /** Resolves with true when the request started, false when it ended without starting. */
44
+ readonly started: Promise<boolean>;
45
+ /** Resolves with the outcome once the request is terminal. */
46
+ readonly completion: Promise<RequestResult>;
47
+ get status(): RequestStatus;
48
+ get reason(): RequestEndReason;
49
+ get detail(): string;
50
+ get failureCode(): string;
51
+ get startedAtMs(): number | null;
52
+ /** The logical time of the terminal state, or null while queued or running. */
53
+ get endedAtMs(): number | null;
54
+ get isTerminal(): boolean;
55
+ /** Speak/Think: where the speech is. */
56
+ get speechProgress(): SpeechProgress;
57
+ /** Speak/Think: the speech has audio (synthesized or recorded). */
58
+ get speechHasAudio(): boolean;
59
+ /** Speak/Think: the speech duration once known. */
60
+ get speechDurationMs(): number | null;
61
+ /** Speak/Think: how the speech is produced and why it has no audio, when it has none. */
62
+ get speechNote(): string;
63
+ /** Cancels the request (queued: removed; running: stops gracefully). False when it is already terminal. */
64
+ cancel(): boolean;
65
+ /** Cancels the request gracefully when `signal` aborts. The outcome is still reported by {@link completion}. */
66
+ cancelOn(signal: AbortSignal): this;
67
+ private settleStarted;
68
+ }