@escapeaihq/client-core 0.6.0 → 0.7.0

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 (120) hide show
  1. package/README.md +27 -2
  2. package/dist/api.d.ts +180 -2
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/api.js +134 -0
  5. package/dist/api.js.map +1 -1
  6. package/dist/audio.d.ts +1 -1
  7. package/dist/index.d.ts +2 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +2 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/reactor/entityContext.d.ts +34 -0
  12. package/dist/reactor/entityContext.d.ts.map +1 -0
  13. package/dist/reactor/entityContext.js +119 -0
  14. package/dist/reactor/entityContext.js.map +1 -0
  15. package/dist/reactor/entitySearch.d.ts +71 -0
  16. package/dist/reactor/entitySearch.d.ts.map +1 -0
  17. package/dist/reactor/entitySearch.js +93 -0
  18. package/dist/reactor/entitySearch.js.map +1 -0
  19. package/dist/reactor/heliosCommandDispatcher.d.ts +98 -0
  20. package/dist/reactor/heliosCommandDispatcher.d.ts.map +1 -0
  21. package/dist/reactor/heliosCommandDispatcher.js +181 -0
  22. package/dist/reactor/heliosCommandDispatcher.js.map +1 -0
  23. package/dist/reactor/heliosTools.d.ts +156 -0
  24. package/dist/reactor/heliosTools.d.ts.map +1 -0
  25. package/dist/reactor/heliosTools.js +241 -0
  26. package/dist/reactor/heliosTools.js.map +1 -0
  27. package/dist/reactor/index.d.ts +17 -0
  28. package/dist/reactor/index.d.ts.map +1 -0
  29. package/dist/reactor/index.js +17 -0
  30. package/dist/reactor/index.js.map +1 -0
  31. package/dist/reactor/promptAddonRegistry.d.ts +37 -0
  32. package/dist/reactor/promptAddonRegistry.d.ts.map +1 -0
  33. package/dist/reactor/promptAddonRegistry.js +38 -0
  34. package/dist/reactor/promptAddonRegistry.js.map +1 -0
  35. package/dist/reactor/regenTemplate.d.ts +23 -0
  36. package/dist/reactor/regenTemplate.d.ts.map +1 -0
  37. package/dist/reactor/regenTemplate.js +103 -0
  38. package/dist/reactor/regenTemplate.js.map +1 -0
  39. package/dist/reactor/sceneEntry.d.ts +79 -0
  40. package/dist/reactor/sceneEntry.d.ts.map +1 -0
  41. package/dist/reactor/sceneEntry.js +177 -0
  42. package/dist/reactor/sceneEntry.js.map +1 -0
  43. package/dist/reactor/scenesFromEnrichment.d.ts +67 -0
  44. package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -0
  45. package/dist/reactor/scenesFromEnrichment.js +344 -0
  46. package/dist/reactor/scenesFromEnrichment.js.map +1 -0
  47. package/dist/reactor/seedImageOrchestrator.d.ts +81 -0
  48. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -0
  49. package/dist/reactor/seedImageOrchestrator.js +79 -0
  50. package/dist/reactor/seedImageOrchestrator.js.map +1 -0
  51. package/dist/reactor/toolPromptAddon.d.ts +44 -0
  52. package/dist/reactor/toolPromptAddon.d.ts.map +1 -0
  53. package/dist/reactor/toolPromptAddon.js +129 -0
  54. package/dist/reactor/toolPromptAddon.js.map +1 -0
  55. package/dist/reactor/toolPromptAddonId.d.ts +10 -0
  56. package/dist/reactor/toolPromptAddonId.d.ts.map +1 -0
  57. package/dist/reactor/toolPromptAddonId.js +10 -0
  58. package/dist/reactor/toolPromptAddonId.js.map +1 -0
  59. package/dist/reactor/types.d.ts +149 -0
  60. package/dist/reactor/types.d.ts.map +1 -0
  61. package/dist/reactor/types.js +2 -0
  62. package/dist/reactor/types.js.map +1 -0
  63. package/dist/reactor/upsamplePrompt.d.ts +30 -0
  64. package/dist/reactor/upsamplePrompt.d.ts.map +1 -0
  65. package/dist/reactor/upsamplePrompt.js +118 -0
  66. package/dist/reactor/upsamplePrompt.js.map +1 -0
  67. package/dist/timeFormat.d.ts +28 -0
  68. package/dist/timeFormat.d.ts.map +1 -0
  69. package/dist/timeFormat.js +48 -0
  70. package/dist/timeFormat.js.map +1 -0
  71. package/dist/visemeGeometry.d.ts +15 -0
  72. package/dist/visemeGeometry.d.ts.map +1 -1
  73. package/dist/visemeGeometry.js +26 -0
  74. package/dist/visemeGeometry.js.map +1 -1
  75. package/dist/visemeScheduler.d.ts +12 -0
  76. package/dist/visemeScheduler.d.ts.map +1 -1
  77. package/dist/visemeScheduler.js +24 -0
  78. package/dist/visemeScheduler.js.map +1 -1
  79. package/dist/websocket.d.ts +51 -3
  80. package/dist/websocket.d.ts.map +1 -1
  81. package/dist/websocket.js +52 -7
  82. package/dist/websocket.js.map +1 -1
  83. package/package.json +1 -1
  84. package/src/__tests__/reactor/__snapshots__/regenTemplate.test.ts.snap +5 -0
  85. package/src/__tests__/reactor/__snapshots__/scenesFromEnrichment.test.ts.snap +34 -0
  86. package/src/__tests__/reactor/api-reactor.test.ts +253 -0
  87. package/src/__tests__/reactor/entityContext.test.ts +237 -0
  88. package/src/__tests__/reactor/entitySearch.test.ts +223 -0
  89. package/src/__tests__/reactor/heliosCommandDispatcher.test.ts +438 -0
  90. package/src/__tests__/reactor/heliosTools.test.ts +164 -0
  91. package/src/__tests__/reactor/promptAddonRegistry.test.ts +40 -0
  92. package/src/__tests__/reactor/regenTemplate.test.ts +156 -0
  93. package/src/__tests__/reactor/sceneEntry.test.ts +342 -0
  94. package/src/__tests__/reactor/scenesFromEnrichment.test.ts +760 -0
  95. package/src/__tests__/reactor/seedImageOrchestrator.test.ts +139 -0
  96. package/src/__tests__/reactor/toolPromptAddon.test.ts +104 -0
  97. package/src/__tests__/reactor/upsamplePrompt.test.ts +245 -0
  98. package/src/__tests__/timeFormat.test.ts +80 -0
  99. package/src/__tests__/tools-wrappers.test.ts +219 -0
  100. package/src/__tests__/websocket.test.ts +278 -0
  101. package/src/api.ts +279 -2
  102. package/src/index.ts +2 -0
  103. package/src/reactor/entityContext.ts +147 -0
  104. package/src/reactor/entitySearch.ts +139 -0
  105. package/src/reactor/heliosCommandDispatcher.ts +293 -0
  106. package/src/reactor/heliosTools.ts +260 -0
  107. package/src/reactor/index.ts +17 -0
  108. package/src/reactor/promptAddonRegistry.ts +52 -0
  109. package/src/reactor/regenTemplate.ts +142 -0
  110. package/src/reactor/sceneEntry.ts +267 -0
  111. package/src/reactor/scenesFromEnrichment.ts +393 -0
  112. package/src/reactor/seedImageOrchestrator.ts +132 -0
  113. package/src/reactor/toolPromptAddon.ts +135 -0
  114. package/src/reactor/toolPromptAddonId.ts +9 -0
  115. package/src/reactor/types.ts +158 -0
  116. package/src/reactor/upsamplePrompt.ts +154 -0
  117. package/src/timeFormat.ts +57 -0
  118. package/src/visemeGeometry.ts +30 -0
  119. package/src/visemeScheduler.ts +25 -0
  120. package/src/websocket.ts +86 -7
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Type definitions for the Reactor / Helios integration layer.
3
+ *
4
+ * These are the framework-agnostic shapes consumed by both seer-agent's
5
+ * React `web/` app and the Vue sibling repo. They describe the inputs
6
+ * and outputs of the pure-function builders in this `reactor/` submodule:
7
+ *
8
+ * - `EntityContext` / `PersonaContext` — knowledge-graph grounding the
9
+ * Seer side aggregates from `ImageRecord` + `EnrichmentRecord` +
10
+ * `PersonaConfig`. Both are LLM-agnostic.
11
+ * - `RegenTemplateInput` — structured form-state for the Gemini Flash
12
+ * Image regen step (consumed by `buildRegenPrompt`). 16:9 is locked
13
+ * at the type level — Helios's reference image must be 16:9, so we
14
+ * enforce it everywhere upstream.
15
+ * - `UpsampleInput` / `UpsampleResult` — input/output for the
16
+ * LLM-agnostic message-pair builder (`buildUpsamplePrompt`). The
17
+ * Seer route translates these into Bedrock Converse messages; the
18
+ * Web-App can route them through a different provider.
19
+ *
20
+ * No runtime exports — type definitions only.
21
+ *
22
+ * `TimelineBeat` and `MapEnrichmentOptions` live in their own
23
+ * module (`./scenesFromEnrichment`) because they're tightly coupled to
24
+ * the mapper's algorithm doc-comments; we re-export them from here so
25
+ * callers importing from `reactor/types` get a single named-type
26
+ * surface.
27
+ */
28
+ export type { TimelineBeat, MapEnrichmentOptions } from './scenesFromEnrichment';
29
+ export type { HeliosCommand } from './heliosTools';
30
+
31
+ /**
32
+ * Knowledge-graph grounding for a single entity from a source video.
33
+ * Aggregated by `aggregateEntityContext` from an `ImageRecord` plus the
34
+ * matching `EnrichmentRecord` for the source video.
35
+ */
36
+ export interface EntityContext {
37
+ /** Display name of the entity, e.g. "Leo". */
38
+ name: string;
39
+ /** Free-text 1-2 sentence summary of where this entity appears in the
40
+ * source video. Derived from the Pegasus enrichment for the source
41
+ * video. May be undefined when the source video has no enrichment yet,
42
+ * or when the timestamp doesn't match any captured scene. */
43
+ sceneContext?: string;
44
+ /** Source video the image was extracted from. Informational only. */
45
+ sourceVideoId?: string;
46
+ /** Timestamp in the source video (seconds). Informational. */
47
+ sourceTimestamp?: number;
48
+ }
49
+
50
+ /**
51
+ * Persona grounding pulled from a `PersonaConfig`. The backstory is the
52
+ * canonical `custom_system_prompt`, truncated to a snippet length sane
53
+ * for prompt injection (~400 chars by convention).
54
+ */
55
+ export interface PersonaContext {
56
+ /** Persona display name. */
57
+ name: string;
58
+ /** PersonaConfig.custom_system_prompt — the canonical backstory.
59
+ * Truncated to a snippet length so prompts stay within budget. */
60
+ backstory: string;
61
+ }
62
+
63
+ /**
64
+ * Structured form-state for the optional Gemini Flash Image regen step.
65
+ *
66
+ * The `aspectRatio` is a literal `'16:9'` because Helios's reference image
67
+ * must be 16:9 — locking it in the type prevents accidentally generating
68
+ * an image Helios will reject.
69
+ *
70
+ * `styleFamily: 'custom'` requires a non-empty `customStyle`. We can't
71
+ * express that cleanly at the type level without discriminated unions
72
+ * that would explode the call sites, so `buildRegenPrompt` performs the
73
+ * runtime check and throws.
74
+ */
75
+ export interface RegenTemplateInput {
76
+ /** Locked 16:9 — Helios reference images must be 16:9. */
77
+ aspectRatio: '16:9';
78
+ /** When true (default for the UI), the prompt instructs the model to
79
+ * preserve the source entity's identity. When false, the model is
80
+ * allowed to reinterpret freely. */
81
+ preserveIdentity: boolean;
82
+
83
+ /** Camera framing keyword. */
84
+ framing: 'wide' | 'medium' | 'medium-close-up' | 'close-up';
85
+ /** Lighting style keyword. */
86
+ lighting: 'cinematic' | 'golden-hour' | 'noir' | 'natural' | 'studio';
87
+ /** Style-family preset, or `'custom'` to provide a free-text style. */
88
+ styleFamily:
89
+ | 'photoreal'
90
+ | 'anime'
91
+ | 'watercolor'
92
+ | 'pixar'
93
+ | 'film-35mm'
94
+ | 'custom';
95
+ /** Required when `styleFamily === 'custom'`. Free-text style descriptor
96
+ * appended in place of the preset. Runtime-validated by
97
+ * `buildRegenPrompt`. */
98
+ customStyle?: string;
99
+
100
+ /** Entity grounding — required because regenerated images are entity-anchored. */
101
+ entity: EntityContext;
102
+ /** Optional persona context. When present, the persona backstory is woven
103
+ * into the prompt as character grounding. */
104
+ persona?: PersonaContext;
105
+
106
+ /** Free-form creative direction appended verbatim to the prompt. */
107
+ creativeDirection?: string;
108
+ /** Optional structured override — describes what the subject should wear. */
109
+ clothingOverride?: string;
110
+ /** Optional structured override — describes pose/action. */
111
+ poseOverride?: string;
112
+ }
113
+
114
+ /**
115
+ * Input shape for `buildUpsamplePrompt`. All fields except `userPrompt`
116
+ * are optional — the builder includes a section only when its input is
117
+ * present, so callers can pass exactly what they have without padding.
118
+ */
119
+ export interface UpsampleInput {
120
+ /** Short prompt the user typed. */
121
+ userPrompt: string;
122
+ /** Previous prompt in the same Helios session, if any — used for
123
+ * continuity in follow-up beats. */
124
+ previousPrompt?: string;
125
+ /** Entity grounding — name + scene context from the knowledge graph. */
126
+ entity?: EntityContext;
127
+ /** Persona grounding — backstory from `custom_system_prompt`. */
128
+ persona?: PersonaContext;
129
+ /** Optional small base64 thumbnail (≤ 64KB recommended) of the seed
130
+ * image. When present, it becomes the first content block in the
131
+ * user message so the LLM has a visual reference. */
132
+ thumbnailBase64?: string;
133
+ /** Media type for the thumbnail. Defaults to `'image/jpeg'`. */
134
+ thumbnailMediaType?: string;
135
+ }
136
+
137
+ /**
138
+ * LLM-agnostic message pair returned by `buildUpsamplePrompt`. The
139
+ * caller translates these into whichever provider's request shape
140
+ * they're using (Bedrock Converse, Anthropic Messages, OpenAI Chat,
141
+ * etc.).
142
+ *
143
+ * `user` is a `ReadonlyArray` of content blocks rather than a plain
144
+ * string because the upsampler can attach an image reference. Even
145
+ * text-only callers receive an array (with a single `text` block) for
146
+ * shape consistency.
147
+ */
148
+ export interface UpsampleResult {
149
+ /** System message: encodes the Helios prompt-engineering rules and
150
+ * the 80-120 word target. Provider-agnostic prose. */
151
+ system: string;
152
+ /** User message content blocks. Image blocks (when present) precede
153
+ * the text block so the LLM grounds its response on the image. */
154
+ user: ReadonlyArray<
155
+ | { type: 'text'; text: string }
156
+ | { type: 'image'; mediaType: string; base64: string }
157
+ >;
158
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * `buildUpsamplePrompt` — LLM-agnostic system/user message-pair builder
3
+ * for the knowledge-grounded prompt-upsample step that turns a short
4
+ * user prompt into a Helios-quality dense paragraph.
5
+ *
6
+ * Returns `{system, user}` where `user` is a content-block array so
7
+ * thumbnails can sit alongside text. The caller (web app's Bedrock
8
+ * upsample route, or the Vue sibling) translates this into the
9
+ * provider-specific request shape.
10
+ *
11
+ * The system prompt encodes the Helios prompt-engineering rules
12
+ * (`ai_docs/reference/reactor/helios-prompt-guide.md`):
13
+ * - Detailed scene description with subject + environment + lighting +
14
+ * mood + camera framing
15
+ * - Exactly one new beat per follow-up
16
+ * - Re-anchor the subject with a short identifying phrase
17
+ * - Always specify camera framing
18
+ * - Describe light by its effect on surfaces
19
+ * - Show emotion through behavior, not abstract labels
20
+ * - Be physically specific (textures, materials, spatial relations)
21
+ * - 80-120 word target, ending with a complete sentence
22
+ * - Output only — no preamble or commentary
23
+ *
24
+ * User-message-block ordering: when a thumbnail is present, the image
25
+ * block comes first so the LLM grounds its description on the visual
26
+ * reference before reading the text instructions.
27
+ */
28
+
29
+ import type {
30
+ EntityContext,
31
+ PersonaContext,
32
+ UpsampleInput,
33
+ UpsampleResult,
34
+ } from './types';
35
+
36
+ // The Python twin of this builder is
37
+ // `api/reactor/app.py::_build_system_prompt(has_previous)`. Both encode
38
+ // the same Helios prompt-guide rules and BOTH gate the continuity
39
+ // section on whether a previous prompt is provided — this keeps
40
+ // cold-start prompts tighter (fewer rules = less noise) and matches
41
+ // the Python behavior. Keep the two in sync when prompt-engineering
42
+ // changes land.
43
+ const BASE_SYSTEM_RULES = `You expand short user prompts into detailed scene descriptions for a real-time interactive video generation model (Helios). Write a single dense paragraph of strictly 80–120 words. You MUST finish with a complete sentence — never cut off mid-sentence. Output only the expanded prompt, with no preamble, no commentary, and no quotation marks.
44
+
45
+ Follow these rules, drawn from the Helios prompt guide:
46
+
47
+ 1. **Scene bible on the first prompt.** When no previous prompt is provided, establish subject + environment + lighting + mood + camera framing in one pass.
48
+ 2. **Re-anchor the subject.** Each prompt opens with a short identifying phrase for the main character (e.g. "Leo maintains his regal position", not the full re-description).
49
+ 3. **Always specify camera framing.** Every prompt names the shot type (close-up, medium close-up, medium shot, wide shot, tracking shot, static shot) and optionally the motion (slow pullback, smooth tracking).
50
+ 4. **Describe light by its effect.** Never say "good lighting" or "bright". Say what the light does to surfaces — "dappled sunlight filtering through the canopy", "neon signs blur across the hood".
51
+ 5. **Show emotion through behavior.** Convey feelings through physical actions, posture, and body language. Not "she was curious" but "her eyes momentarily softened as she lowered her head to sniff".
52
+ 6. **Be physically specific.** Describe textures, materials, spatial relationships, weight, and motion concretely.
53
+
54
+ If grounding context is provided (entity name, source-scene description, persona backstory, a reference image), incorporate it. Use the entity's real name. Echo specifics from the source scene where they fit. Carry persona traits through into physical behavior. If a reference image is attached, ground the visual description on what you see.`;
55
+
56
+ const CONTINUITY_RULES = `A previous prompt from the same Helios session is provided. Maintain visual continuity: keep the same character identity, environment, palette, and camera style. Re-anchor the subject with a short identifying phrase rather than re-describing them in full.
57
+
58
+ Introduce exactly one new narrative beat — a new action, object, or event — and let everything else evolve naturally. Do not introduce multiple changes at once.`;
59
+
60
+ function buildSystemPrompt(hasPrevious: boolean): string {
61
+ return hasPrevious
62
+ ? `${BASE_SYSTEM_RULES}\n\n${CONTINUITY_RULES}`
63
+ : BASE_SYSTEM_RULES;
64
+ }
65
+
66
+ function buildContextSection(opts: {
67
+ entity?: EntityContext;
68
+ persona?: PersonaContext;
69
+ }): string | undefined {
70
+ // Structure mirrors `api/reactor/app.py::_build_user_text` — including
71
+ // the source-video + timestamp anchors when present so the LLM has the
72
+ // same temporal grounding from either transport. Format chosen as a
73
+ // light key/value block (rather than free prose) so the model can
74
+ // parse it reliably even when several context fields are populated.
75
+ const lines: string[] = [];
76
+ if (opts.entity) {
77
+ if (opts.entity.sceneContext) {
78
+ lines.push(
79
+ `This is ${opts.entity.name}, who in the source video appears in a scene where ${opts.entity.sceneContext}`,
80
+ );
81
+ } else {
82
+ lines.push(`This is ${opts.entity.name}.`);
83
+ }
84
+ if (opts.entity.sourceVideoId) {
85
+ lines.push(`Source video: ${opts.entity.sourceVideoId}`);
86
+ }
87
+ if (typeof opts.entity.sourceTimestamp === 'number') {
88
+ lines.push(
89
+ `Source timestamp: ${opts.entity.sourceTimestamp.toFixed(2)}s`,
90
+ );
91
+ }
92
+ }
93
+ if (opts.persona) {
94
+ lines.push(
95
+ `Persona backstory for ${opts.persona.name}: ${opts.persona.backstory}`,
96
+ );
97
+ }
98
+ return lines.length > 0 ? lines.join('\n\n') : undefined;
99
+ }
100
+
101
+ export function buildUpsamplePrompt(input: UpsampleInput): UpsampleResult {
102
+ const userBlocks: Array<
103
+ | { type: 'text'; text: string }
104
+ | { type: 'image'; mediaType: string; base64: string }
105
+ > = [];
106
+
107
+ // Image block first — give the LLM the visual reference before the
108
+ // instructions, so it grounds the description on what it actually sees.
109
+ if (input.thumbnailBase64) {
110
+ const mediaType = input.thumbnailMediaType ?? 'image/jpeg';
111
+ // Strip a data-URL prefix if the caller passed a raw data URL.
112
+ const base64 = input.thumbnailBase64.replace(/^data:image\/\w+;base64,/, '');
113
+ userBlocks.push({ type: 'image', mediaType, base64 });
114
+ }
115
+
116
+ // Build the text block. Sections are joined with double newlines so the
117
+ // LLM perceives them as distinct context fields, not a run-on sentence.
118
+ const textParts: string[] = [];
119
+
120
+ const contextSection = buildContextSection({
121
+ entity: input.entity,
122
+ persona: input.persona,
123
+ });
124
+ if (contextSection) {
125
+ textParts.push(contextSection);
126
+ }
127
+
128
+ if (input.previousPrompt) {
129
+ textParts.push(
130
+ `The previous scene was:\n"${input.previousPrompt}"\n\nIntroduce exactly one new beat (a new action, object, or event). Keep the world, lighting, and camera stable. Re-anchor the subject with a short identifying phrase.`,
131
+ );
132
+ }
133
+
134
+ // Hint that the thumbnail is a reference image, but only when we actually
135
+ // attached one — keeps the text instructions truthful.
136
+ if (input.thumbnailBase64) {
137
+ textParts.push(
138
+ 'The attached image is a visual reference for the subject and setting. Ground the scene description on what you see.',
139
+ );
140
+ }
141
+
142
+ // The user's short prompt always goes last — it's the most-recent-tokens
143
+ // anchor that the model expands.
144
+ textParts.push(
145
+ `Expand this prompt into a Helios-quality 80–120 word paragraph: "${input.userPrompt}"`,
146
+ );
147
+
148
+ userBlocks.push({ type: 'text', text: textParts.join('\n\n') });
149
+
150
+ return {
151
+ system: buildSystemPrompt(Boolean(input.previousPrompt)),
152
+ user: userBlocks,
153
+ };
154
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Format a duration in seconds as a human-readable time string.
3
+ *
4
+ * Unifies the five inline implementations that lived in
5
+ * `web/app/{chat,chat-ws,jobs,videos,watch}/*` before this lift. Each
6
+ * call site had a slightly different shape:
7
+ * - `m:ss` (jobs page, watch page, videos durations)
8
+ * - `m:ss.cc` with sub-second centiseconds (chat / chat-ws citations)
9
+ * - `m:ss` returning `"-"` for null inputs (videos table)
10
+ * - None supported `h:mm:ss` so 90-minute videos rendered as `90:00`
11
+ *
12
+ * Defaults to `m:ss`, auto-extends to `h:mm:ss` when `seconds >= 3600`,
13
+ * opts into centiseconds via `centiseconds: true`, and returns
14
+ * `fallback` (default `"0:00"`) on null/undefined/NaN/±Infinity/negative
15
+ * inputs so call sites can render gracefully without input guards.
16
+ *
17
+ * @example
18
+ * formatTimestamp(65) // "1:05"
19
+ * formatTimestamp(3725) // "1:02:05" (auto h:mm:ss past 60 min)
20
+ * formatTimestamp(42.34, { centiseconds: true }) // "0:42.34"
21
+ * formatTimestamp(null) // "0:00"
22
+ * formatTimestamp(null, { fallback: '-' }) // "-"
23
+ */
24
+ export function formatTimestamp(
25
+ seconds: number | null | undefined,
26
+ options: { centiseconds?: boolean; fallback?: string } = {},
27
+ ): string {
28
+ const fallback = options.fallback ?? '0:00';
29
+ if (
30
+ seconds === null ||
31
+ seconds === undefined ||
32
+ !Number.isFinite(seconds) ||
33
+ seconds < 0
34
+ ) {
35
+ return fallback;
36
+ }
37
+
38
+ const total = Math.floor(seconds);
39
+ const h = Math.floor(total / 3600);
40
+ const m = Math.floor((total % 3600) / 60);
41
+ const s = total % 60;
42
+
43
+ const pad2 = (n: number) => n.toString().padStart(2, '0');
44
+
45
+ const base = h > 0 ? `${h}:${pad2(m)}:${pad2(s)}` : `${m}:${pad2(s)}`;
46
+
47
+ if (options.centiseconds) {
48
+ // 1/100 of a second precision — sufficient for chat citation
49
+ // boundaries and avoids a third trailing digit that adds noise
50
+ // without precision. (Previously called "ms" in chat-ws code; the
51
+ // name was misleading — it's always been centiseconds.)
52
+ const cs = Math.floor((seconds - total) * 100);
53
+ return `${base}.${pad2(cs)}`;
54
+ }
55
+
56
+ return base;
57
+ }
@@ -7,6 +7,36 @@
7
7
  * without rendering a React tree.
8
8
  */
9
9
 
10
+ import type { VisemeSymbol } from './visemeScheduler';
11
+
12
+ /**
13
+ * Fallback SVG path table used by mouth renderers BEFORE a persona's
14
+ * viseme bundle has finished loading (and as a backstop for personas
15
+ * that don't ship a custom bundle). Each value is the `d` attribute
16
+ * for the `<path>` driven by the viseme switch.
17
+ *
18
+ * Coordinates assume a 200×100 viewBox centered horizontally — the
19
+ * same canvas the Web-App `seer-character-face.vue` and seer-agent
20
+ * `CharacterFace.tsx` renderers use. Promoted from
21
+ * `seer-character-face.vue` so both renderers can share the source
22
+ * of truth; this is the §7 cleanup from
23
+ * `specs/2026-05-14-client-core-cleanup-plan.md`.
24
+ */
25
+ export const DEFAULT_MOUTH_PATHS: Record<VisemeSymbol, string> = {
26
+ rest: 'M 40,50 C 60,50 140,50 160,50 C 160,52 140,54 100,54 C 60,54 40,52 40,50 C 40,50 40,50 40,50',
27
+ aei: 'M 40,38 C 60,32 140,32 160,38 C 160,56 140,72 100,74 C 60,72 40,56 40,38 C 40,38 40,38 40,38',
28
+ o: 'M 62,34 C 78,28 122,28 138,34 C 142,50 138,70 100,72 C 62,70 58,50 62,34 C 62,34 62,34 62,34',
29
+ ee: 'M 28,44 C 52,40 148,40 172,44 C 172,52 148,58 100,58 C 52,58 28,52 28,44 C 28,44 28,44 28,44',
30
+ bmp: 'M 48,48 C 68,46 132,46 152,48 C 152,52 132,54 100,54 C 68,54 48,52 48,48 C 48,48 48,48 48,48',
31
+ fv: 'M 42,44 C 62,42 138,42 158,44 C 158,52 138,58 100,58 C 62,58 42,52 42,44 C 42,44 42,44 42,44',
32
+ l: 'M 42,40 C 62,36 138,36 158,40 C 158,54 138,64 100,66 C 62,64 42,54 42,40 C 42,40 42,40 42,40',
33
+ r: 'M 52,38 C 72,34 128,34 148,38 C 148,52 128,64 100,66 C 72,64 52,52 52,38 C 52,38 52,38 52,38',
34
+ th: 'M 42,42 C 62,38 138,38 158,42 C 158,52 138,60 100,62 C 62,60 42,52 42,42 C 42,42 42,42 42,42',
35
+ qw: 'M 58,36 C 76,30 124,30 142,36 C 146,52 138,68 100,70 C 62,68 54,52 58,36 C 58,36 58,36 58,36',
36
+ cdgknstxyz:
37
+ 'M 44,46 C 64,43 136,43 156,46 C 156,53 136,57 100,57 C 64,57 44,53 44,46 C 44,46 44,46 44,46',
38
+ };
39
+
10
40
  export interface Point {
11
41
  x: number;
12
42
  y: number;
@@ -34,6 +34,31 @@ const VALID_VISEMES: ReadonlySet<string> = new Set<string>([
34
34
  'cdgknstxyz',
35
35
  ]);
36
36
 
37
+ /**
38
+ * Map VisemeSymbol → 0-14 integer index expected by the PlayCanvas
39
+ * iframe TTS bridge (Web-App: `utils/seer/iframeMessaging.ts`).
40
+ *
41
+ * The indices are intentionally sparse (gaps at 4, 6, 7, 11): they
42
+ * match the PlayCanvas mouth animation channel constants and **must
43
+ * not be re-densified** without updating the engine side. Promoted to
44
+ * client-core so the next renderer (or a future seer-agent PlayCanvas
45
+ * iframe consumer) inherits the same mapping — §8 in
46
+ * `specs/2026-05-14-client-core-cleanup-plan.md`.
47
+ */
48
+ export const iframeVisemeIndexMap: Readonly<Record<VisemeSymbol, number>> = {
49
+ rest: 0,
50
+ bmp: 1,
51
+ fv: 2,
52
+ th: 3,
53
+ cdgknstxyz: 5,
54
+ l: 8,
55
+ r: 9,
56
+ aei: 10,
57
+ ee: 12,
58
+ o: 13,
59
+ qw: 14,
60
+ };
61
+
37
62
  interface ScheduledViseme {
38
63
  startTime: number; // Absolute AudioContext.currentTime
39
64
  endTime: number;
package/src/websocket.ts CHANGED
@@ -207,12 +207,45 @@ export type BinaryHandler = (data: ArrayBuffer) => void;
207
207
 
208
208
  export interface ChatWebSocketOptions {
209
209
  url: string;
210
+ /**
211
+ * Static token baked into the URL at construction time. Reused on
212
+ * every reconnect attempt — fine for tokens that don't expire, but
213
+ * stale for ephemeral tokens (e.g. seer-agent's 10-min `ws-token`).
214
+ * Prefer {@link ChatWebSocketOptions.fetchToken} for ephemeral tokens.
215
+ */
210
216
  authToken?: string;
217
+ /**
218
+ * Async supplier invoked once per connect attempt (initial + every
219
+ * reconnect). Takes precedence over `authToken` when both are
220
+ * provided. Typical wiring:
221
+ *
222
+ * ```ts
223
+ * fetchToken: () => apiClient.getChatWsToken().then(r => r.wsToken),
224
+ * ```
225
+ *
226
+ * If this throws on a reconnect attempt, the failure counts against
227
+ * `maxReconnectAttempts` and the loop schedules another attempt with
228
+ * the existing backoff. On the initial connect the rejection
229
+ * propagates to the caller of `connect()`.
230
+ */
231
+ fetchToken?: () => Promise<string>;
211
232
  onOpen?: () => void;
212
233
  onClose?: () => void;
213
234
  onError?: (error: Event) => void;
214
235
  onReconnecting?: (attempt: number) => void;
215
236
  onReconnected?: () => void;
237
+ /**
238
+ * Called after a successful reconnect, immediately before
239
+ * `onReconnected`. If the caller returns a {@link HelloPayload}, it
240
+ * is serialized and sent so the server can restore voice/session
241
+ * state; returning `null` skips the send (e.g. text-only sessions
242
+ * that don't need a hello).
243
+ *
244
+ * Synchronous on purpose — the payload is built from in-memory
245
+ * state, and we want to send it on the same tick the socket opens
246
+ * to avoid racing other queued messages.
247
+ */
248
+ onReconnect?: () => HelloPayload | null;
216
249
  }
217
250
 
218
251
  export class ChatWebSocket {
@@ -221,11 +254,13 @@ export class ChatWebSocket {
221
254
  private binaryHandlers: BinaryHandler[] = [];
222
255
  private url: string;
223
256
  private authToken?: string;
257
+ private fetchToken?: () => Promise<string>;
224
258
  private onOpenCallback?: () => void;
225
259
  private onCloseCallback?: () => void;
226
260
  private onErrorCallback?: (error: Event) => void;
227
261
  private onReconnectingCallback?: (attempt: number) => void;
228
262
  private onReconnectedCallback?: () => void;
263
+ private onReconnectCallback?: () => HelloPayload | null;
229
264
 
230
265
  // Reconnection state
231
266
  private maxReconnectAttempts = 5;
@@ -237,11 +272,13 @@ export class ChatWebSocket {
237
272
  constructor(options: ChatWebSocketOptions) {
238
273
  this.url = options.url;
239
274
  this.authToken = options.authToken;
275
+ this.fetchToken = options.fetchToken;
240
276
  this.onOpenCallback = options.onOpen;
241
277
  this.onCloseCallback = options.onClose;
242
278
  this.onErrorCallback = options.onError;
243
279
  this.onReconnectingCallback = options.onReconnecting;
244
280
  this.onReconnectedCallback = options.onReconnected;
281
+ this.onReconnectCallback = options.onReconnect;
245
282
  }
246
283
 
247
284
  /**
@@ -252,15 +289,43 @@ export class ChatWebSocket {
252
289
  return this._connect(false);
253
290
  }
254
291
 
292
+ /**
293
+ * Resolve the auth token for the next connect attempt. `fetchToken`
294
+ * wins over `authToken` when both are set — the supplier is the
295
+ * forward-looking path; `authToken` is back-compat.
296
+ */
297
+ private async _resolveToken(): Promise<string | undefined> {
298
+ if (this.fetchToken) {
299
+ return await this.fetchToken();
300
+ }
301
+ return this.authToken;
302
+ }
303
+
255
304
  /**
256
305
  * Internal connect method. When isReconnect is true, calls
257
- * onReconnected instead of onOpen on success.
306
+ * onReconnected (and dispatches any onReconnect hello payload)
307
+ * instead of onOpen on success.
258
308
  */
259
- private _connect(isReconnect: boolean): Promise<void> {
309
+ private async _connect(isReconnect: boolean): Promise<void> {
310
+ let token: string | undefined;
311
+ try {
312
+ token = await this._resolveToken();
313
+ } catch (err) {
314
+ // Token fetch failed before any socket was opened, so onclose
315
+ // can't fire to drive the next reconnect attempt. On a reconnect
316
+ // pass we explicitly schedule another attempt so transient
317
+ // token-fetch failures (network blip, brief 502 on the token
318
+ // endpoint) don't kill the loop. On the initial connect we let
319
+ // the caller see the failure.
320
+ if (isReconnect && !this.intentionalDisconnect) {
321
+ this._attemptReconnect();
322
+ }
323
+ throw err;
324
+ }
325
+
260
326
  return new Promise((resolve, reject) => {
261
- // Append auth token to URL if provided
262
- const urlWithAuth = this.authToken
263
- ? `${this.url}?token=${encodeURIComponent(this.authToken)}`
327
+ const urlWithAuth = token
328
+ ? `${this.url}?token=${encodeURIComponent(token)}`
264
329
  : this.url;
265
330
 
266
331
  this.ws = new WebSocket(urlWithAuth);
@@ -270,6 +335,14 @@ export class ChatWebSocket {
270
335
  console.log('WebSocket connected');
271
336
  this.reconnectAttempts = 0;
272
337
  if (isReconnect) {
338
+ // Re-send hello BEFORE onReconnected so the caller observes
339
+ // a fully restored session, not a half-open one. Skip when
340
+ // the caller returns null (text-only sessions don't need a
341
+ // hello to resume).
342
+ const helloPayload = this.onReconnectCallback?.();
343
+ if (helloPayload && this.ws) {
344
+ this.ws.send(JSON.stringify(helloPayload));
345
+ }
273
346
  this.onReconnectedCallback?.();
274
347
  }
275
348
  this.onOpenCallback?.();
@@ -476,17 +549,23 @@ export class ChatWebSocket {
476
549
  }
477
550
 
478
551
  /**
479
- * Example usage:
552
+ * Example usage with an ephemeral token + voice-session restore:
480
553
  *
481
554
  * ```typescript
482
555
  * const ws = new ChatWebSocket({
483
556
  * url: 'ws://localhost:8080/api/chat/ws',
484
- * authToken: 'Bearer xyz123',
557
+ * fetchToken: () => apiClient.getChatWsToken().then((r) => r.wsToken),
558
+ * onReconnect: () => (voiceModeActive ? buildHelloPayload(...) : null),
485
559
  * onOpen: () => console.log('Connected!'),
486
560
  * onClose: () => console.log('Disconnected'),
487
561
  * onError: (error) => console.error('Error:', error),
488
562
  * });
489
563
  *
564
+ * // Back-compat: static-token sessions still work without `fetchToken`.
565
+ * const wsLegacy = new ChatWebSocket({
566
+ * url: 'ws://localhost:8080/api/chat/ws',
567
+ * authToken: 'Bearer xyz123',
568
+ *
490
569
  * await ws.connect();
491
570
  *
492
571
  * ws.onMessage((message) => {