@escapeaihq/client-core 0.6.1 → 0.8.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 (109) hide show
  1. package/README.md +28 -3
  2. package/dist/api.d.ts +102 -2
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/api.js +92 -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/websocket.d.ts +31 -0
  72. package/dist/websocket.d.ts.map +1 -1
  73. package/dist/websocket.js +20 -0
  74. package/dist/websocket.js.map +1 -1
  75. package/package.json +1 -1
  76. package/src/__tests__/reactor/__snapshots__/regenTemplate.test.ts.snap +5 -0
  77. package/src/__tests__/reactor/__snapshots__/scenesFromEnrichment.test.ts.snap +34 -0
  78. package/src/__tests__/reactor/api-reactor.test.ts +253 -0
  79. package/src/__tests__/reactor/entityContext.test.ts +237 -0
  80. package/src/__tests__/reactor/entitySearch.test.ts +223 -0
  81. package/src/__tests__/reactor/heliosCommandDispatcher.test.ts +438 -0
  82. package/src/__tests__/reactor/heliosTools.test.ts +164 -0
  83. package/src/__tests__/reactor/promptAddonRegistry.test.ts +40 -0
  84. package/src/__tests__/reactor/regenTemplate.test.ts +156 -0
  85. package/src/__tests__/reactor/sceneEntry.test.ts +342 -0
  86. package/src/__tests__/reactor/scenesFromEnrichment.test.ts +760 -0
  87. package/src/__tests__/reactor/seedImageOrchestrator.test.ts +139 -0
  88. package/src/__tests__/reactor/toolPromptAddon.test.ts +104 -0
  89. package/src/__tests__/reactor/upsamplePrompt.test.ts +245 -0
  90. package/src/__tests__/timeFormat.test.ts +80 -0
  91. package/src/__tests__/websocket.test.ts +75 -0
  92. package/src/api.ts +170 -2
  93. package/src/index.ts +2 -0
  94. package/src/reactor/entityContext.ts +147 -0
  95. package/src/reactor/entitySearch.ts +139 -0
  96. package/src/reactor/heliosCommandDispatcher.ts +293 -0
  97. package/src/reactor/heliosTools.ts +260 -0
  98. package/src/reactor/index.ts +17 -0
  99. package/src/reactor/promptAddonRegistry.ts +52 -0
  100. package/src/reactor/regenTemplate.ts +142 -0
  101. package/src/reactor/sceneEntry.ts +267 -0
  102. package/src/reactor/scenesFromEnrichment.ts +393 -0
  103. package/src/reactor/seedImageOrchestrator.ts +132 -0
  104. package/src/reactor/toolPromptAddon.ts +135 -0
  105. package/src/reactor/toolPromptAddonId.ts +9 -0
  106. package/src/reactor/types.ts +158 -0
  107. package/src/reactor/upsamplePrompt.ts +154 -0
  108. package/src/timeFormat.ts +57 -0
  109. package/src/websocket.ts +42 -0
package/src/api.ts CHANGED
@@ -3,6 +3,10 @@
3
3
  */
4
4
 
5
5
  import type { AudioFormat } from './audioProtocol';
6
+ import type {
7
+ EntityContext as ReactorEntityContext,
8
+ PersonaContext as ReactorPersonaContext,
9
+ } from './reactor/types';
6
10
  import type { Citation } from './websocket';
7
11
 
8
12
  export interface IngestionJob {
@@ -86,11 +90,22 @@ export interface EnrichVideoResponse {
86
90
  status: string;
87
91
  }
88
92
 
93
+ /** Mirrors `shared/models.py::EnrichmentStatusType`. The enrichment
94
+ * pipeline writes one of these four values to DynamoDB — narrowing
95
+ * here lets callers compare against the exported constants below
96
+ * instead of bare string literals. */
97
+ export type EnrichmentStatus = 'QUEUED' | 'RUNNING' | 'SUCCEEDED' | 'FAILED';
98
+
99
+ export const ENRICHMENT_STATUS_QUEUED: EnrichmentStatus = 'QUEUED';
100
+ export const ENRICHMENT_STATUS_RUNNING: EnrichmentStatus = 'RUNNING';
101
+ export const ENRICHMENT_STATUS_SUCCEEDED: EnrichmentStatus = 'SUCCEEDED';
102
+ export const ENRICHMENT_STATUS_FAILED: EnrichmentStatus = 'FAILED';
103
+
89
104
  export interface EnrichmentRecord {
90
105
  enrichmentId: string;
91
106
  videoId: string;
92
107
  jobId: string;
93
- status: string;
108
+ status: EnrichmentStatus;
94
109
  pegasusPrompt?: string;
95
110
  pegasusTemperature?: number;
96
111
  pegasusMaxTokens?: number;
@@ -302,9 +317,20 @@ export interface ExtractImageRequest {
302
317
 
303
318
  export interface ExtractImageResponse {
304
319
  traceId: string;
320
+ /** Tracked `image_id` for the persisted `ImageRecord`. Null when the
321
+ * S3 upload succeeded but the metadata write failed (best-effort
322
+ * persistence — `ExtractImageResponse` still resolves so the caller
323
+ * gets `imageUrl`). Callers that need to stream the image bytes
324
+ * through the seed-image proxy (browser CORS) MUST require this
325
+ * field — `imageUrl` alone is unreachable from a browser without
326
+ * a same-origin proxy. */
327
+ imageId?: string | null;
305
328
  /** Presigned S3 URL for immediate display only. The URL has a short
306
329
  * TTL (typically 1h) and will 403 once expired — persist `imageS3Key`
307
- * if you need a stable handle and re-presign on read. */
330
+ * if you need a stable handle and re-presign on read. Note: the raw
331
+ * S3 origin has no CORS rules, so direct browser `fetch()` of this
332
+ * URL is blocked. Use `getSeedImageBlob(imageId)` for browser-side
333
+ * binary access. */
308
334
  imageUrl: string;
309
335
  imageS3Key: string;
310
336
  sourceTimestamp: number;
@@ -689,6 +715,45 @@ export interface DeleteRelationshipResponse {
689
715
  deleted: number;
690
716
  }
691
717
 
718
+ // ==================== Reactor / Helios types ====================
719
+
720
+ /**
721
+ * Response shape from the Reactor `/tokens` exchange, returned by the
722
+ * Next.js server-side broker at `/api/reactor/token`. The broker forwards
723
+ * the JWT verbatim; `expiresAt` is whatever Reactor reports (epoch ms or
724
+ * undefined if not provided).
725
+ */
726
+ export interface ReactorTokenResponse {
727
+ jwt: string;
728
+ expiresAt?: number;
729
+ }
730
+
731
+ /**
732
+ * Request body for the FastAPI route at `/api/v1/reactor/upsample`.
733
+ * `entityContext` and `personaContext` reuse the canonical types from
734
+ * `./reactor/types.ts` so that prompt-engineering or schema changes
735
+ * land in exactly one place. (Earlier revisions inlined these — a
736
+ * reviewer caught the divergence risk; importing keeps `api.ts` and
737
+ * the reactor submodule in lockstep.)
738
+ */
739
+ export interface UpsampleReactorPromptRequest {
740
+ /** The short user prompt to expand. */
741
+ prompt: string;
742
+ /** Previous prompt in the same session, for continuity. */
743
+ previousPrompt?: string;
744
+ /** Image ID — backend fetches and downsamples the thumbnail. */
745
+ imageId?: string;
746
+ /** Entity grounding (name + scene context). */
747
+ entityContext?: ReactorEntityContext;
748
+ /** Persona grounding (name + truncated backstory). */
749
+ personaContext?: ReactorPersonaContext;
750
+ }
751
+
752
+ export interface UpsampleReactorPromptResponse {
753
+ traceId: string;
754
+ upsampledPrompt: string;
755
+ }
756
+
692
757
  /**
693
758
  * Detect an abort (controller.abort(), unmount, signal expiry) so callers
694
759
  * can stay silent on expected cancellations while still surfacing real
@@ -1885,4 +1950,107 @@ export class ApiClient {
1885
1950
  }
1886
1951
  }
1887
1952
 
1953
+ // ==================== Reactor / Helios ====================
1954
+
1955
+ /**
1956
+ * Exchange the Seer-side `REACTOR_API_KEY` (held server-side in the
1957
+ * Next.js host) for a short-lived Reactor JWT.
1958
+ *
1959
+ * Targets the **same-origin** route `/api/reactor/token` because the
1960
+ * token broker is a Next.js Route Handler that lives in the web app,
1961
+ * NOT the FastAPI backend. We deliberately bypass `this.request()` /
1962
+ * `this.baseURL` here — relative-path `fetch` keeps us on whatever
1963
+ * origin served the page (localhost during dev, the Vercel deployment
1964
+ * in prod) and avoids cross-origin / preflight issues.
1965
+ *
1966
+ * Sends the Descope session JWT as the `Authorization` header so the
1967
+ * route handler has defense-in-depth on top of `web/middleware.ts` —
1968
+ * without this header the route returns 401 even if the middleware
1969
+ * is misconfigured. Mirrors the getSeedImageBlob auth pattern.
1970
+ */
1971
+ async getReactorToken(
1972
+ options: { signal?: AbortSignal } = {},
1973
+ ): Promise<ReactorTokenResponse> {
1974
+ const headers: Record<string, string> = {
1975
+ 'Content-Type': 'application/json',
1976
+ };
1977
+ if (this.sessionToken) {
1978
+ headers['Authorization'] = `Bearer ${this.sessionToken}`;
1979
+ }
1980
+ const response = await fetch('/api/reactor/token', {
1981
+ method: 'POST',
1982
+ headers,
1983
+ signal: options.signal,
1984
+ });
1985
+ if (!response.ok) {
1986
+ const detail = await response
1987
+ .json()
1988
+ .then((b: { detail?: string; error?: string }) => b.detail ?? b.error)
1989
+ .catch(() => undefined);
1990
+ throw new Error(detail || `Reactor token exchange failed: ${response.status}`);
1991
+ }
1992
+ return (await response.json()) as ReactorTokenResponse;
1993
+ }
1994
+
1995
+ /**
1996
+ * Fetch the raw bytes of an entity / character / regenerated image for
1997
+ * use as a Helios seed image. Targets the **same-origin** proxy route
1998
+ * `/api/reactor/seed-image?imageId=…` which re-presigns the S3 URL
1999
+ * server-side and streams the bytes back with the right
2000
+ * `Content-Type` — the bulletproof CORS-free path.
2001
+ *
2002
+ * Returns the raw `Blob` so the caller can hand it to
2003
+ * `reactor.uploadFile(blob)` without copying through a base64 detour.
2004
+ */
2005
+ async getSeedImageBlob(
2006
+ imageId: string,
2007
+ options: { signal?: AbortSignal } = {},
2008
+ ): Promise<Blob> {
2009
+ const url = `/api/reactor/seed-image?imageId=${encodeURIComponent(imageId)}`;
2010
+ // The Next.js proxy requires Authorization so it can forward our identity
2011
+ // to the FastAPI ImageRecord lookup. Bypassing `request()` means we have
2012
+ // to attach the bearer token ourselves here.
2013
+ const headers: Record<string, string> = {};
2014
+ if (this.sessionToken) {
2015
+ headers['Authorization'] = `Bearer ${this.sessionToken}`;
2016
+ }
2017
+ const response = await fetch(url, {
2018
+ method: 'GET',
2019
+ headers,
2020
+ signal: options.signal,
2021
+ });
2022
+ if (!response.ok) {
2023
+ const detail = await response
2024
+ .json()
2025
+ .then((b: { detail?: string; error?: string }) => b.detail ?? b.error)
2026
+ .catch(() => undefined);
2027
+ throw new Error(detail || `Seed image fetch failed: ${response.status}`);
2028
+ }
2029
+ return await response.blob();
2030
+ }
2031
+
2032
+ /**
2033
+ * Knowledge-grounded prompt upsample — expands a short user prompt
2034
+ * into a Helios-quality 80-120 word paragraph using Bedrock. Routes
2035
+ * through the FastAPI backend (`/api/v1/reactor/upsample`).
2036
+ *
2037
+ * The reactor router is mounted on the chat app (`api/chat/app.py`),
2038
+ * not the tools app, so this uses `chatRequest()` — in split local
2039
+ * dev (tools on 8080, chat on 8000) hitting the tools base would 404
2040
+ * and silently degrade to the raw user prompt.
2041
+ */
2042
+ async upsampleReactorPrompt(
2043
+ input: UpsampleReactorPromptRequest,
2044
+ options: { signal?: AbortSignal } = {},
2045
+ ): Promise<UpsampleReactorPromptResponse> {
2046
+ return this.chatRequest<UpsampleReactorPromptResponse>(
2047
+ '/api/v1/reactor/upsample',
2048
+ {
2049
+ method: 'POST',
2050
+ body: JSON.stringify(input),
2051
+ signal: options.signal,
2052
+ },
2053
+ );
2054
+ }
2055
+
1888
2056
  }
package/src/index.ts CHANGED
@@ -26,3 +26,5 @@ export * from './visemeScheduler';
26
26
  export * from './visemeGeometry';
27
27
  export * from './websocket';
28
28
  export * from './api';
29
+ export * from './reactor';
30
+ export * from './timeFormat';
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Aggregators that map Seer's wire types (ImageRecord, EnrichmentRecord,
3
+ * PersonaConfig) into the LLM-agnostic `EntityContext` / `PersonaContext`
4
+ * shapes consumed by `buildUpsamplePrompt` and `buildRegenPrompt`.
5
+ *
6
+ * Defensive by design — `EnrichmentRecord.result` is typed as
7
+ * `Record<string, unknown>` because the Pegasus output format isn't
8
+ * locked at the client. We probe a few common shapes (`{scenes: [...]}`,
9
+ * `{summary: string}`) and fall back to `undefined` when nothing matches.
10
+ * We never throw — a missing or mismatched scene just means the
11
+ * upsampler runs without the scene-context section.
12
+ */
13
+
14
+ import type {
15
+ EnrichmentRecord,
16
+ ImageRecord,
17
+ PersonaConfig,
18
+ } from '../api';
19
+ import type { EntityContext, PersonaContext } from './types';
20
+
21
+ /** Cap for `PersonaContext.backstory` so prompt budgets stay sane. */
22
+ const BACKSTORY_MAX_CHARS = 400;
23
+
24
+ /**
25
+ * Derive a short display label from an `ImageRecord` when `source_entity`
26
+ * is absent. The s3_key tends to look like `extracted/foo.png` — strip
27
+ * the directory and extension and use what's left, falling back to a
28
+ * generic "unknown entity" label.
29
+ */
30
+ function labelFromImageRecord(record: ImageRecord): string {
31
+ if (record.source_entity && record.source_entity.trim()) {
32
+ return record.source_entity.trim();
33
+ }
34
+ const key = record.s3_key ?? '';
35
+ const basename = key.split('/').pop() ?? '';
36
+ const stem = basename.replace(/\.[^.]+$/, '').trim();
37
+ return stem || 'unknown entity';
38
+ }
39
+
40
+ interface SceneCandidate {
41
+ start?: number;
42
+ end?: number;
43
+ description?: string;
44
+ }
45
+
46
+ function asNumber(v: unknown): number | undefined {
47
+ return typeof v === 'number' && Number.isFinite(v) ? v : undefined;
48
+ }
49
+
50
+ function asString(v: unknown): string | undefined {
51
+ return typeof v === 'string' && v.trim() ? v.trim() : undefined;
52
+ }
53
+
54
+ /**
55
+ * Probe a Pegasus enrichment `result` blob for a scene that brackets the
56
+ * given timestamp. Tolerates the two shapes we've seen in practice:
57
+ * - `{scenes: [{start, end, description}, ...]}` — the structured form
58
+ * - `{summary: "..."}` — flat summary fallback (no timestamp matching)
59
+ *
60
+ * Returns the matched scene description, or `undefined` if no match.
61
+ */
62
+ function findSceneContext(
63
+ result: Record<string, unknown> | undefined,
64
+ timestamp: number | undefined,
65
+ ): string | undefined {
66
+ if (!result) return undefined;
67
+
68
+ // Shape A — `{scenes: [...]}`. Only useful if we have a timestamp to
69
+ // bracket against.
70
+ const scenesRaw = result.scenes;
71
+ if (Array.isArray(scenesRaw) && typeof timestamp === 'number') {
72
+ for (const sceneRaw of scenesRaw) {
73
+ if (!sceneRaw || typeof sceneRaw !== 'object') continue;
74
+ const scene = sceneRaw as SceneCandidate;
75
+ const start = asNumber(scene.start);
76
+ const end = asNumber(scene.end);
77
+ const description = asString(scene.description);
78
+ if (description === undefined) continue;
79
+ if (start === undefined || end === undefined) continue;
80
+ if (timestamp >= start && timestamp <= end) {
81
+ return description;
82
+ }
83
+ }
84
+ }
85
+
86
+ // Shape B — flat `{summary: "..."}`. Used when we have no timestamp
87
+ // match (or no timestamp at all). The summary is a video-level
88
+ // description, so it's strictly worse than a per-scene match but
89
+ // still better than nothing.
90
+ const summary = asString(result.summary);
91
+ if (summary) return summary;
92
+
93
+ return undefined;
94
+ }
95
+
96
+ /**
97
+ * Build an `EntityContext` from an `ImageRecord`, optional matching
98
+ * `EnrichmentRecord`, and optional `PersonaConfig`. Never throws —
99
+ * missing fields collapse to `undefined`.
100
+ */
101
+ export function aggregateEntityContext(input: {
102
+ imageRecord: ImageRecord;
103
+ enrichment?: EnrichmentRecord;
104
+ persona?: PersonaConfig;
105
+ }): EntityContext {
106
+ const { imageRecord, enrichment } = input;
107
+
108
+ const name = labelFromImageRecord(imageRecord);
109
+ const sourceVideoId = imageRecord.source_video_id ?? undefined;
110
+ const sourceTimestamp =
111
+ typeof imageRecord.source_timestamp === 'number'
112
+ ? imageRecord.source_timestamp
113
+ : undefined;
114
+
115
+ const sceneContext = findSceneContext(
116
+ enrichment?.result,
117
+ sourceTimestamp,
118
+ );
119
+
120
+ const out: EntityContext = { name };
121
+ if (sceneContext !== undefined) out.sceneContext = sceneContext;
122
+ if (sourceVideoId !== undefined) out.sourceVideoId = sourceVideoId;
123
+ if (sourceTimestamp !== undefined) out.sourceTimestamp = sourceTimestamp;
124
+ return out;
125
+ }
126
+
127
+ /**
128
+ * Build a `PersonaContext` from a `PersonaConfig`. Pulls `name` and
129
+ * `custom_system_prompt`, truncating the backstory to
130
+ * `BACKSTORY_MAX_CHARS` (default 400) so prompt budgets stay sane.
131
+ * Returns `null` when no backstory is set — callers should treat that
132
+ * as "no persona context" rather than feeding an empty backstory to
133
+ * the upsampler.
134
+ */
135
+ export function aggregatePersonaContext(persona: PersonaConfig): PersonaContext | null {
136
+ const raw = persona.custom_system_prompt ?? '';
137
+ const trimmed = raw.trim();
138
+ if (!trimmed) return null;
139
+ const backstory =
140
+ trimmed.length > BACKSTORY_MAX_CHARS
141
+ ? trimmed.slice(0, BACKSTORY_MAX_CHARS).trimEnd() + '…'
142
+ : trimmed;
143
+ return {
144
+ name: persona.name,
145
+ backstory,
146
+ };
147
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Look up an `ImageRecord` for a named entity in a given source video.
3
+ *
4
+ * Lifted from `dispatchHeliosCommand`'s SWAP_SEED branch so the search
5
+ * can be reused by the Vue web-app and any other client-core consumer
6
+ * that needs "name a character, get its seed image."
7
+ *
8
+ * Search order: `extracted` first (the primary catalogue), then
9
+ * `character` (the highest-quality fallback for personas with rest-pose
10
+ * PNGs). Short-circuits on first match — most videos resolve from
11
+ * `extracted` alone, so the second `listImages` round-trip only fires
12
+ * when the entity isn't found there.
13
+ *
14
+ * Match policy: case-insensitive equality after trim on
15
+ * `source_entity`. The Helios steering addon hints "case sensitive" to
16
+ * the model, but that's a guidance hint rather than a hard contract; we
17
+ * accept whichever casing the model emits.
18
+ *
19
+ * Caching (per #119): the result lists from `listImages` are cached
20
+ * per `(videoId, category, limit)` tuple in an in-process map. The
21
+ * cache lives for the lifetime of the JS realm — a page reload clears
22
+ * it. Subsequent SWAP_SEED commands against the same video reuse the
23
+ * cached catalogue with zero round-trips. Pass `forceRefresh: true` to
24
+ * bust the cache for the current call (e.g. after a video re-ingest).
25
+ * The whole cache can also be cleared via `clearEntitySearchCache()`.
26
+ *
27
+ * Failure modes (per category):
28
+ * - `listImages` throws → log + continue to the next category. The
29
+ * failure is NOT cached, so a transient API blip won't poison the
30
+ * catalogue.
31
+ * - No match in any category → resolve with `undefined`. The empty
32
+ * result IS cached — a name the model invented once is likely to be
33
+ * invented again, and we don't want to re-query both categories.
34
+ */
35
+
36
+ import type { ApiClient } from '../api';
37
+ import type { ImageCategory, ImageRecord } from '../api';
38
+
39
+ /** Image categories searched in priority order when no override is passed. */
40
+ export const DEFAULT_SEED_SEARCH_CATEGORIES: readonly ImageCategory[] = [
41
+ 'extracted',
42
+ 'character',
43
+ ];
44
+
45
+ export interface FindEntityImageOptions {
46
+ /** Override the default category search order. */
47
+ categories?: readonly ImageCategory[];
48
+ /** Per-category result cap forwarded to `listImages`. Default 50 —
49
+ * matches the original SWAP_SEED behaviour and is plenty for any
50
+ * realistic single-video entity count. */
51
+ limit?: number;
52
+ /** Skip the in-process cache for this call. Re-fetches both
53
+ * categories from the API and refreshes the cache entry. Use after
54
+ * a video re-ingest or when a user manually adds an entity. */
55
+ forceRefresh?: boolean;
56
+ }
57
+
58
+ /**
59
+ * Cache key combines videoId + category + limit. Different limits hit
60
+ * different shaped responses so we don't share between them; in
61
+ * practice 99% of callers use the default limit so this is a
62
+ * single-entry map per (videoId, category).
63
+ *
64
+ * **Module-global state caveat.** This cache lives in module scope, so
65
+ * it's shared across all callers within the same JS realm. That's fine
66
+ * for the current consumers — both seer-agent's React `web/` and the
67
+ * Vue `~/Projects/Web-App` are client-only SPAs where each user owns
68
+ * their own realm. **Do not import this module from a Next.js server
69
+ * component, Edge function, or SSR-rendered Nuxt page** — the cache
70
+ * would leak catalogue data across requests (and across users). Use
71
+ * `clearEntitySearchCache()` between requests, or restructure to pass
72
+ * a per-request cache through `FindEntityImageOptions`, if a server
73
+ * context ever needs the helper.
74
+ */
75
+ type CacheKey = string;
76
+ const cache = new Map<CacheKey, ImageRecord[]>();
77
+
78
+ function makeKey(videoId: string, category: ImageCategory, limit: number): CacheKey {
79
+ return `${videoId}::${category}::${limit}`;
80
+ }
81
+
82
+ /**
83
+ * Clear the entire entity-search cache.
84
+ *
85
+ * @internal — exported for test setup (`beforeEach`) only. Production
86
+ * callers should use `forceRefresh: true` on a specific
87
+ * `findEntityImageBySeedName` call to invalidate a single entry
88
+ * instead of nuking the whole cache. Marked `@internal` rather than
89
+ * removed because Jest's `resetModules()` is too heavy-handed for the
90
+ * test setup pattern (re-imports every module).
91
+ */
92
+ export function clearEntitySearchCache(): void {
93
+ cache.clear();
94
+ }
95
+
96
+ /**
97
+ * Resolve an entity name to its `ImageRecord` in a given video.
98
+ *
99
+ * Returns `undefined` when the entity isn't found in any category;
100
+ * callers decide how to surface that (warning toast, fallback image,
101
+ * etc.). Returns `undefined` for empty / whitespace-only `entityName`
102
+ * without calling the API.
103
+ */
104
+ export async function findEntityImageBySeedName(
105
+ apiClient: ApiClient,
106
+ videoId: string,
107
+ entityName: string,
108
+ options: FindEntityImageOptions = {},
109
+ ): Promise<ImageRecord | undefined> {
110
+ const needle = entityName.trim().toLowerCase();
111
+ if (!needle) return undefined;
112
+
113
+ const categories = options.categories ?? DEFAULT_SEED_SEARCH_CATEGORIES;
114
+ const limit = options.limit ?? 50;
115
+ const isMatch = (img: ImageRecord) =>
116
+ (img.source_entity ?? '').trim().toLowerCase() === needle;
117
+
118
+ for (const category of categories) {
119
+ const key = makeKey(videoId, category, limit);
120
+ let images = !options.forceRefresh ? cache.get(key) : undefined;
121
+ if (!images) {
122
+ try {
123
+ const res = await apiClient.listImages({ videoId, category, limit });
124
+ images = res.images ?? [];
125
+ cache.set(key, images);
126
+ } catch (err) {
127
+ console.warn(
128
+ `[findEntityImageBySeedName] listImages(${category}) failed`,
129
+ err,
130
+ );
131
+ // Don't cache the failure — let the next call retry.
132
+ continue;
133
+ }
134
+ }
135
+ const match = images.find(isMatch);
136
+ if (match) return match;
137
+ }
138
+ return undefined;
139
+ }