@escapeaihq/client-core 0.42.0 → 0.49.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.
- package/README.md +4 -4
- package/dist/admin.d.ts +123 -0
- package/dist/admin.d.ts.map +1 -1
- package/dist/admin.js +74 -0
- package/dist/admin.js.map +1 -1
- package/dist/api.d.ts +328 -2
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +198 -3
- package/dist/api.js.map +1 -1
- package/dist/conversation/binding.d.ts +18 -3
- package/dist/conversation/binding.d.ts.map +1 -1
- package/dist/conversation/binding.js +8 -2
- package/dist/conversation/binding.js.map +1 -1
- package/dist/conversation/controller.d.ts.map +1 -1
- package/dist/conversation/controller.js +8 -0
- package/dist/conversation/controller.js.map +1 -1
- package/dist/websocket.d.ts +19 -0
- package/dist/websocket.d.ts.map +1 -1
- package/dist/websocket.js.map +1 -1
- package/package.json +1 -1
- package/src/__tests__/api.test.ts +83 -0
- package/src/__tests__/conversation/binding.test.ts +62 -0
- package/src/__tests__/conversation/controller.test.ts +35 -0
- package/src/__tests__/monitoring.test.ts +162 -0
- package/src/__tests__/persona-generation.test.ts +352 -0
- package/src/__tests__/websocket.test.ts +50 -0
- package/src/admin.ts +207 -0
- package/src/api.ts +507 -2
- package/src/conversation/binding.ts +22 -3
- package/src/conversation/controller.ts +8 -0
- package/src/websocket.ts +24 -0
package/README.md
CHANGED
|
@@ -18,13 +18,13 @@ ESM-only. The published `package.json` points `exports[".".import]` at `./dist/i
|
|
|
18
18
|
| `audio` | `MicrophoneRecorder`, `AudioFramePlayer`, `PlaybackTracker`, `AudioSessionClient`, `AudioPipeline`. Web Audio API based. Clean barge-in via `GainNode` + tracked `activeSources`. Sentence-boundary viseme scheduling. |
|
|
19
19
|
| `visemeScheduler` | Maps Inworld TTS 1.5 phoneme timing to mouth shape changes via `requestAnimationFrame`, locked to `AudioContext.currentTime`. Stops the loop when idle. |
|
|
20
20
|
| `visemeGeometry` | Pure path math: derive inner-lip donut, mouth clip ellipse, teeth/tongue geometry from existing `mouth_paths` data |
|
|
21
|
-
| `websocket` | `ChatWebSocket` — auto-reconnecting wrapper around native WebSocket with text/binary multiplexing. `sendPlaybackState(state: PlaybackState)` publishes `{ action: 'playback_state', videoId, currentTime, shotId?, paused, clientTs }` for cross-device video↔chat sync (`src/websocket.ts:493` `sendPlaybackState` + `src/websocket.ts:69` `PlaybackState`). Fire-and-forget: drops silently when the socket isn't OPEN. See `specs/2026-05-17-cross-device-playback-sync.md`. **Phase 2 vision signaling:** `sendVisionOffer({ sdp, fps })` (`src/websocket.ts:578`), `sendVisionIce({ candidate, sdpMid, sdpMLineIndex })` (`src/websocket.ts:594`), and `sendVisionClose()` (`src/websocket.ts:614`) forward SDP/ICE over the existing chat-ws WebSocket; inbound `vision_answer`, `vision_ice`, and `vision_status` events are surfaced via typed event handlers. |
|
|
21
|
+
| `websocket` | `ChatWebSocket` — auto-reconnecting wrapper around native WebSocket with text/binary multiplexing. `sendPlaybackState(state: PlaybackState)` publishes `{ action: 'playback_state', videoId, currentTime, shotId?, paused, clientTs }` for cross-device video↔chat sync (`src/websocket.ts:493` `sendPlaybackState` + `src/websocket.ts:69` `PlaybackState`). Fire-and-forget: drops silently when the socket isn't OPEN. See `specs/2026-05-17-cross-device-playback-sync.md`. **Phase 2 vision signaling:** `sendVisionOffer({ sdp, fps })` (`src/websocket.ts:578`), `sendVisionIce({ candidate, sdpMid, sdpMLineIndex })` (`src/websocket.ts:594`), and `sendVisionClose()` (`src/websocket.ts:614`) forward SDP/ICE over the existing chat-ws WebSocket; inbound `vision_answer`, `vision_ice`, and `vision_status` events are surfaced via typed event handlers. **0.49.0 (dashboard A-DM0):** the `ChatWsEvent` union gains a `dm_directive` member `{ type, timestamp?, directive: DmDirectiveKind, params }` (mirrors `ChatEventType.DM_DIRECTIVE` in `shared/chat_dispatcher.py`) — a DM-issued scene-control directive (`enter_world`/`exit_world`/`seek_video`/`set_experience_source`). Additive; `ConversationRuntime.applyFrame` drops it via its default arm (no consumer wired yet — A-DM0 is dark). |
|
|
22
22
|
| `vision/` | **Phase 2:** `VisionPublisher` (`src/vision/VisionPublisher.ts:1`) — framework-agnostic class taking any `MediaStreamTrack` + `ChatWebSocket` + optional `VisionRtcCredentials` and managing the `RTCPeerConnection` lifecycle (SDP offer/answer, ICE trickle, restart-on-disconnect). **Dual-mode signaling**: `credentials.mode === 'kvs'` dynamically imports the optional `amazon-kinesis-video-streams-webrtc` peer dep and connects via Amazon KVS WebRTC against a backend-minted SigV4-presigned wss:// URL; otherwise (or when no credentials passed) uses the existing chat-WS `vision_offer`/`vision_ice`/`vision_close` protocol. `ChatWebSocket.sendVisionAttach({clientId})` (KVS mode only) binds the chat session to the KVS viewer ClientId so the backend dispatcher can find the FrameBuffer. `visionScheduler.ts` adjusts published fps from backend `vision_status` back-pressure (pure helper). `types.ts` exports `VisionPublisherConfig`, `VisionPublisherOptions`, `VisionRtcCredentials`, `VisionStatus`, `VisionStatusListener`, `VisionErrorListener`. Source-agnostic by design — consumers wire `<video>.captureStream()`, `getUserMedia()`, or future Reactor/Helios/PlayCanvas surfaces (Issue #150). **0.10.0 additions:** `toVisionRtcCredentials(response)` (`src/vision/credentials.ts:23`) — pure mapping helper that converts a `ChatVisionRtcCredentialsResponse` API wire shape into `VisionRtcCredentials`, coercing `null` ICE fields to `undefined`. `startVisionPublisher(opts)` (`src/vision/startVisionPublisher.ts:42`) — framework-agnostic factory: construct→subscribe→start→cleanup in one call, returning `VisionPublisherHandle { publisher, stop() }`. Used by both `/watch` and `/chat-ws` React hooks so the construct/teardown sequence has exactly one implementation. **0.31.0 (R3a — vision-source picker):** `sourceKinds.ts` — `VISION_SOURCE_KINDS` (`webcam`/`playing-video`/`server-render`, the frozen constant + `VisionSourceKind` union) and the `VisionSourceDescriptor` tagged union (`{kind:'webcam',constraints?}` vs `{kind:'playing-video'|'server-render', element, waitForFrame?}`) so the controller never queries the DOM. `VisionSourceController.ts` (`src/vision/VisionSourceController.ts:89`) — the framework-agnostic owner of "turn a chosen local source into a published feed": `start(descriptor)` acquires (getUserMedia vs `element.captureStream()`, with the `waitForFrame` black-frame gate lifted from the watch hook), mints credentials AFTER acquisition, then DELEGATES to `startVisionPublisher`; `switchSource()` tears the previous publisher + tracks down BEFORE acquiring the next; `stop()` is idempotent, leaves zero live tracks, and epoch-guards in-flight starts (a racing stop/switch releases the late stream, no error); `currentKind` + `isStarting` expose the published source and the in-flight phase. Environmental failures → `onError` (restartable); misuse (`start()` while active) throws. `ws` must be the SAME authenticated `ChatWebSocket` as the chat turns (frames are keyed to the WS session server-side). Land-dark until R3b–R3d wire the surfaces; sources are LOCAL only (cross-device vision deferred). |
|
|
23
|
-
| `api` | `ApiClient` REST client + all backend response/request type definitions. Constructor takes `baseURL` and `chatBaseUrl` from the caller (no env-var coupling). Image-tool wrappers since 0.3.0: `extractImage`, `regenerateImage`, `pollVisemeBundleUntilDone`. Bundle resolution since 0.5.0: `loadBundleManifest` (handles the inline-vs-S3 body_svg split internally) + canonical `VisemeBundleManifest` type. Reactor/Helios wrappers: `getReactorToken`, `getSeedImageBlob`, `upsampleReactorPrompt`. Chat-model registry (since the LLM-provider phase): `listChatModels()` returns `ChatModelsResponse` with `ChatModelInfo` entries (`id`, `provider`, `capabilities: ChatModelCapability[]`, context window, etc.) — public endpoint so it works before login. **0.10.0 additions:** `getSystemPrompt()` returns `SystemPromptComponents` (`src/api.ts:205,2132`) with `{ film_qa, guardrails, audio_markup, full_default }` — calls `GET /api/v1/chat/system-prompt`. **0.13.0 additions (M7 Phase 1a):** `getGraphSchema()` returns `GraphSchemaResponse` (`{ traceId, labels: Record<string,{pk,editable[]}>, edges: Record<string,{editable[]}> }`) — calls `GET /api/v1/tools/graph/schema`. **Graph-editor signature changes:** `deleteGraphNode` / `deleteGraphEdge` now send **query params** (no request body — tech-debt #42), and `UpdateNodeRequest` / `DeleteNodeRequest` input types **dropped `idProperty`** (backend derives the PK — tech-debt #44). These are input-type narrowings (callers pass less); additive otherwise. **0.14.0 additions (M7 Phase 1b):** `NarrativeAct` (`src/api.ts:751`) gains **optional** `actId` / `index` / `title` / `summary` / `t0` / `t1` — **additive only**; the existing `act` / `timeRange` / `description` fields are retained (per the client-core API-is-a-contract rule, no public export removed/renamed). Acts and `themes` / `mainCharacterNames` are now read **from the graph** — `Act`-labelled `GraphNode`s and the `Video` node properties returned by `getVideoGraph()` — rather than parsed from `getEnrichments()`; `GraphNode` / `VideoGraphResponse` carry `Act` nodes with no schema change. **0.15.0 additions (M7 Phase 3a):** `createGraphNode(data: CreateNodeRequest): Promise<CreateNodeResponse>` (`POST /api/v1/tools/graph/nodes`) and `createGraphEdge(data: CreateEdgeRequest): Promise<CreateEdgeResponse>` (`POST /api/v1/tools/graph/edges`) — both **additive** (no public export removed/renamed, per the API-is-a-contract rule). New request/response types `CreateNodeRequest` `{ videoId, label, properties }` / `CreateNodeResponse` `{ traceId, nodeId, properties }` and `CreateEdgeRequest` `{ videoId, sourceId, targetId, type, properties? }` / `CreateEdgeResponse` `{ traceId, edgeId, properties }`. The 201 JSON body is parsed by the existing `makeRequest` path (only 204 is special-cased); a 422 surfaces the FastAPI `detail` message unchanged. **Source-document CRUD (M7 Phase 4, package version 0.14.0):** shapes mirror the **authoritative backend Pydantic models** (`api/tools/schemas.py`). `uploadDocument(file, meta, onProgress?)` (multipart XHR mirroring `uploadVideo`; file sent under the multipart field **`upload`**; `POST /api/v1/ingestion/documents` → `{ traceId, document }`, HTTP 202 new / 200 idempotent dedupe), `listDocuments({ videoId?, seriesId?, limit?, nextToken? })`, `getDocument(docId)` (→ `{ traceId, document }` — suggestions are **nested** in `document.suggestions`, no top-level field), `acceptSuggestion(docId, sid)` (201 `{ traceId, suggestionId, graphId }`, writes graph node/edge with provenance `document`), `rejectSuggestion(docId, sid)` (204), `deleteDocument(docId)` (204) — all on the tools/ingestion base URL, not chat. New types/constants: `DocumentKind`, `DocumentStatus` + `DOC_STATUS_*`, `SuggestionStatus` + `SUGGESTION_STATUS_*`, `Suggestion`, `DocumentRecord` (mirrors `DocumentResponse`: `suggestions` always present; no `ownerUserId`/`s3Key`/`contentHash`), `UploadDocumentMeta`, `UploadDocumentResponse` `{ traceId, document }`, `ListDocumentsResponse`, `GetDocumentResponse` `{ traceId, document }`, `AcceptSuggestionResponse` `{ traceId, suggestionId, graphId }`. **0.16.0 additions (M7 Phase 6 — narrative regeneration):** `startRegeneration(videoId, request: RegenerateRequest): Promise<RegenerationRunResponse>` (`POST /api/v1/tools/graph/{videoId}/regenerate` → 202; `statusUrl`/`Location` to the run's poll URL; a 409 lock / 429 cap / 422 bad-scope surfaces the FastAPI `detail`), `listRegenerations(videoId, { limit?, cursor? }?)` (`GET .../regenerations` → `RegenerationListResponse` newest-first + `nextCursor`), `getRegeneration(videoId, runId, { signal? }?)` (`GET .../regenerations/{runId}`, 404 absent), and `pollRegenerationUntilDone(videoId, runId, { intervalMs?, timeoutMs?, signal? }?)` (5s cadence, abortable — resolves on `complete`/`cancelled`, throws on `failed`, mirrors `pollVisemeBundleUntilDone`). New types/constants `RegenerationRunStatus` + `REGENERATION_STATUS` const map + `REGENERATION_TERMINAL_STATUSES`, `RegenerationScopeKind` + `REGEN_SCOPE_BARE_KINDS`/`REGEN_SCOPE_TARGETED_KINDS`/`REGEN_SCOPE_SEPARATOR` + `buildRegenerationScope(kind, targetId?)` (builds `acts`/`characters`/`scene:<id>`/`arc:<id>`; throws on a bare+target or targeted-without-id contract violation), `RegenerateRequest` `{ scope, promptAddon? }`, `RegenerationRunResponse` `{ traceId, runId, videoId, scope, status, statusUrl, createdAt, promptAddon?, startedAt?, completedAt?, delta, error? }`, `RegenerationListResponse` `{ traceId, videoId, runs, nextCursor }`. **0.21.0 additions (M9 Story Engine Phase 8a — Adventure Runtime):** `startAdventure(request: StartAdventureRequest, { signal? }?): Promise<AdventureResponse>` (`POST /api/v1/adventures` → 201, `Location` to the session GET URL; a 422 `Persona is not a Dungeon Master` / 404 / 403 surfaces the FastAPI `detail`), `getAdventure(sessionId, { signal? }?): Promise<GetAdventureResponse>` (`GET /api/v1/adventures/{sessionId}`, 404 absent/not-owned), `deleteAdventure(sessionId, { signal? }?): Promise<void>` (`DELETE .../{sessionId}` → 204). New camelCase-wire types `TurnRecord` `{ turn, beatId, summary }`, `AdventureState` `{ sessionId, ownerUserId, storyId, videoId, dmPersonaId, partyPersonaIds, currentBeatId?, visitedBeatIds, flags, inventory, turnHistory, createdAt, updatedAt }`, `StartAdventureRequest` `{ storyId, videoId, dmPersonaId, initialBeatId? }`, `AdventureResponse` `{ traceId, sessionId, state }`, `GetAdventureResponse` `{ traceId, state }`. `PersonaConfig` / `CreatePersonaRequest` / `UpdatePersonaRequest` gain optional snake_case `is_dungeon_master` (read defaults `false`). `ChatWebSocket.send()` options + `buildHelloPayload()` gain optional `adventureSessionId` (spread only when set → land-dark). **0.22.0 additions:** `listAdventures(storyId?, { signal? }?): Promise<ListAdventuresResponse>` (`GET /api/v1/adventures`, owner-scoped newest-first, optional `storyId` filter) + `ListAdventuresResponse` `{ traceId, adventures }`. **0.23.0 additions (M10 Story Engine Phase 9a — multi-persona scene orchestrator):** `addPartyMember(sessionId, personaId, { signal? }?): Promise<GetAdventureResponse>` and `removePartyMember(sessionId, personaId, { signal? }?): Promise<GetAdventureResponse>` — both `PATCH /api/v1/adventures/{sessionId}/party` with `{ action, personaId }` (add: 422 for a DM / non-character / unowned persona; remove: idempotent 200 no-op; 404 for a missing adventure). New types/constants `PARTY_ACTION` (`{ ADD:'add', REMOVE:'remove' }`) + `PartyAction` + `PartyUpdateRequest` `{ action, personaId }`; `StartAdventureRequest` gains optional `partyPersonaIds?: string[]`. `ChatWebSocket.send()` options + `buildHelloPayload()` gain optional `partyPersonaIds?: string[]` (spread only when non-empty → land-dark; advisory — the server's `AdventureState.party_persona_ids` is authoritative). `ChatWsEvent` gains a `turn_changed` member `{ type, timestamp?, personaId, previousPersonaId? }` (mirrors `ChatEventType.TURN_CHANGED`) and an optional `personaId?` on the `token`/`done`/`citation`/`image`/`audio_chunk` members (orchestrator-stamped; undefined elsewhere → land-dark; per-turn TTS voice swap on audio deferred). **R1c additions (Platform Experience Restructure — image adapter registry, no version bump, release is R1e):** `listImageModels(): Promise<ImageModelsResponse>` (`GET /api/v1/images/models`, **authenticated** — unlike chat/models it is NOT in `DEFAULT_PUBLIC_PATHS`; served on the **chat** base URL via `chatRequest`) + `ImageModelInfo` `{ id, displayName, provider, capabilities: string[], isDefault, isFallback }` / `ImageModelsResponse` `{ models }`. **Additive only** (no public export removed/renamed). **0.32.0 additions (Platform Experience Restructure R5a+R5c — cast-with-persona projection):** `getCast(videoId): Promise<CastWithPersonaResponse>` (`GET /api/v1/tools/videos/{videoId}/cast`, tools base URL) — one call returns the character cast pre-joined to bound-persona display fields (the server resolves the PORTRAYS binding; replaces the CastGrid `getVideoGraph`+`listPersonas` client-side `entity_id` join since R5c). New types `CastArc`/`CastScene`/`CastCharacter`/`CastPersonaSummary`/`CastEntry`/`CastWithPersonaResponse` (`CastCharacter.scenes: CastScene[]` carries `{sceneId, title}` so a Cast drawer renders scene titles without the graph payload). New `castWithPersona(response): CastEntry[]` (`src/castProjection.ts`) — the framework-agnostic pure normalizer (deterministic ordering, list coalescing, title/name fallbacks, input never mutated) every Cast consumer shares. **0.32.0 additions (R5b — story-detail graph read):** `getVideoGraph(videoId, detail?)` gains an optional `detail` arg — `GRAPH_DETAIL.STORY` requests the server-collapsed story view (Acts/Scenes/cast/narrative edges; Shots collapsed to per-Scene `shotCount` properties; DialogLine/Event/MENTIONS omitted), `GRAPH_DETAIL.RAW` the full graph; omitting it sends NO query param (byte-identical pre-R5b request). New exports `GRAPH_DETAIL` + `GraphDetail` (mirror of `shared/graph_schema.py`). **0.33.0 additions (Platform Experience Restructure R6b — image filtering params):** `listImages(params)` gains optional `model?: string` + `status?: ImageStatus` filters, mirroring the new `GET /api/v1/images` query params. `model` ids come from R1's image-model registry (discoverable via `listImageModels()`); the backend rejects an unregistered id with 400 — **no client-core image-model descriptor is added** (R1's `imageAdapter.ts` stays the sole catalogue owner). `status` reuses the existing `ImageStatus` union (`ImageRecord['status']`) — no parallel status enum. Omitting both leaves the request byte-identical to 0.32.0 (additive only). See [CHANGELOG.md](./CHANGELOG.md). |
|
|
24
|
-
| `admin` | **0.19.0 (GitHub #215 Phase 2):** `AdminClient` — the prompt-defaults editor surface. Constructed with the **chat** base URL + session token (the admin router is mounted in `api/chat/app.py`). Methods: `listPromptDefaults()` → `PromptDefaultsListResponse`; `getPromptDefault(key)` / `updatePromptDefault(key, {value})` / `revertPromptDefault(key)` → `PromptDefaultDetail`. Types: `PromptDefaultSource` (`'db'|'code'`), `PromptDefaultSummary`, `PromptDefaultDetail`, `UpdatePromptDefaultRequest`. **0.24.0 (M12 Slice 5 — eval-observability reader):** added `listEvalRuns(params, {signal})` → `EvalRunsListResponse` (one cursor page) and `listAllEvalRuns(params, {signal})` → `AllEvalRunsResult` (`{runs, truncated}`; follows `nextCursor` until null, capped at `MAX_EVAL_RUN_PAGES = 50` — stops not throws, and sets `truncated: true` when the cap is hit with pages still pending so the page warns rather than presenting a partial series as complete). `params` carries the XOR selector `benchmarkId` **or** `promptVersion` (server returns 422 on neither/both) + optional `limit`/`cursor`. Types: `EvalRunSummary`, `EvalRunsListResponse`, `ListEvalRunsParams`, `AllEvalRunsResult` (mirror `api/admin/schemas.py` exactly). The `/observability` web page is the consumer (charts metric scores per `promptVersion`, one line per `modelId`, grouped client-side). **Additive only** — no `ApiClient` export changed. Shares the internal `http.ts` `requestJson` helper that `ApiClient.makeRequest` now also delegates to (DRY, private — not re-exported). The server enforces the editable-key carve-out (extraction keys are not editable → 404 → thrown `Error`). **R6d (read-only regen base prompts):** added `listRegenBasePrompts()` → `RegenBasePromptsResponse` (`GET /api/v1/admin/regen-prompts`; types `RegenBasePrompt`/`RegenBasePromptsResponse` mirror `api/admin/schemas.py`; `editable` always `false`, no write method exists). Also additive on `api.ts`: `RegenerateRequest.appliedDocumentIds?: string[] | null` (cap 20; server silently dedups + drops unknown ids) and `RegenerationRunResponse.appliedDocumentIds?: string[]` mirror the R6c backend fields. |
|
|
23
|
+
| `api` | `ApiClient` REST client + all backend response/request type definitions. Constructor takes `baseURL` and `chatBaseUrl` from the caller (no env-var coupling). Image-tool wrappers since 0.3.0: `extractImage`, `regenerateImage`, `pollVisemeBundleUntilDone`. Bundle resolution since 0.5.0: `loadBundleManifest` (handles the inline-vs-S3 body_svg split internally) + canonical `VisemeBundleManifest` type. Reactor/Helios wrappers: `getReactorToken`, `getSeedImageBlob`, `upsampleReactorPrompt`. Chat-model registry (since the LLM-provider phase): `listChatModels()` returns `ChatModelsResponse` with `ChatModelInfo` entries (`id`, `provider`, `capabilities: ChatModelCapability[]`, context window, etc.) — public endpoint so it works before login. **0.10.0 additions:** `getSystemPrompt()` returns `SystemPromptComponents` (`src/api.ts:205,2132`) with `{ film_qa, guardrails, audio_markup, full_default }` — calls `GET /api/v1/chat/system-prompt`. **0.13.0 additions (M7 Phase 1a):** `getGraphSchema()` returns `GraphSchemaResponse` (`{ traceId, labels: Record<string,{pk,editable[]}>, edges: Record<string,{editable[]}> }`) — calls `GET /api/v1/tools/graph/schema`. **Graph-editor signature changes:** `deleteGraphNode` / `deleteGraphEdge` now send **query params** (no request body — tech-debt #42), and `UpdateNodeRequest` / `DeleteNodeRequest` input types **dropped `idProperty`** (backend derives the PK — tech-debt #44). These are input-type narrowings (callers pass less); additive otherwise. **0.14.0 additions (M7 Phase 1b):** `NarrativeAct` (`src/api.ts:751`) gains **optional** `actId` / `index` / `title` / `summary` / `t0` / `t1` — **additive only**; the existing `act` / `timeRange` / `description` fields are retained (per the client-core API-is-a-contract rule, no public export removed/renamed). Acts and `themes` / `mainCharacterNames` are now read **from the graph** — `Act`-labelled `GraphNode`s and the `Video` node properties returned by `getVideoGraph()` — rather than parsed from `getEnrichments()`; `GraphNode` / `VideoGraphResponse` carry `Act` nodes with no schema change. **0.15.0 additions (M7 Phase 3a):** `createGraphNode(data: CreateNodeRequest): Promise<CreateNodeResponse>` (`POST /api/v1/tools/graph/nodes`) and `createGraphEdge(data: CreateEdgeRequest): Promise<CreateEdgeResponse>` (`POST /api/v1/tools/graph/edges`) — both **additive** (no public export removed/renamed, per the API-is-a-contract rule). New request/response types `CreateNodeRequest` `{ videoId, label, properties }` / `CreateNodeResponse` `{ traceId, nodeId, properties }` and `CreateEdgeRequest` `{ videoId, sourceId, targetId, type, properties? }` / `CreateEdgeResponse` `{ traceId, edgeId, properties }`. The 201 JSON body is parsed by the existing `makeRequest` path (only 204 is special-cased); a 422 surfaces the FastAPI `detail` message unchanged. **Source-document CRUD (M7 Phase 4, package version 0.14.0):** shapes mirror the **authoritative backend Pydantic models** (`api/tools/schemas.py`). `uploadDocument(file, meta, onProgress?)` (multipart XHR mirroring `uploadVideo`; file sent under the multipart field **`upload`**; `POST /api/v1/ingestion/documents` → `{ traceId, document }`, HTTP 202 new / 200 idempotent dedupe), `listDocuments({ videoId?, seriesId?, limit?, nextToken? })`, `getDocument(docId)` (→ `{ traceId, document }` — suggestions are **nested** in `document.suggestions`, no top-level field), `acceptSuggestion(docId, sid)` (201 `{ traceId, suggestionId, graphId }`, writes graph node/edge with provenance `document`), `rejectSuggestion(docId, sid)` (204), `deleteDocument(docId)` (204) — all on the tools/ingestion base URL, not chat. New types/constants: `DocumentKind`, `DocumentStatus` + `DOC_STATUS_*`, `SuggestionStatus` + `SUGGESTION_STATUS_*`, `Suggestion`, `DocumentRecord` (mirrors `DocumentResponse`: `suggestions` always present; no `ownerUserId`/`s3Key`/`contentHash`), `UploadDocumentMeta`, `UploadDocumentResponse` `{ traceId, document }`, `ListDocumentsResponse`, `GetDocumentResponse` `{ traceId, document }`, `AcceptSuggestionResponse` `{ traceId, suggestionId, graphId }`. **0.16.0 additions (M7 Phase 6 — narrative regeneration):** `startRegeneration(videoId, request: RegenerateRequest): Promise<RegenerationRunResponse>` (`POST /api/v1/tools/graph/{videoId}/regenerate` → 202; `statusUrl`/`Location` to the run's poll URL; a 409 lock / 429 cap / 422 bad-scope surfaces the FastAPI `detail`), `listRegenerations(videoId, { limit?, cursor? }?)` (`GET .../regenerations` → `RegenerationListResponse` newest-first + `nextCursor`), `getRegeneration(videoId, runId, { signal? }?)` (`GET .../regenerations/{runId}`, 404 absent), and `pollRegenerationUntilDone(videoId, runId, { intervalMs?, timeoutMs?, signal? }?)` (5s cadence, abortable — resolves on `complete`/`cancelled`, throws on `failed`, mirrors `pollVisemeBundleUntilDone`). New types/constants `RegenerationRunStatus` + `REGENERATION_STATUS` const map + `REGENERATION_TERMINAL_STATUSES`, `RegenerationScopeKind` + `REGEN_SCOPE_BARE_KINDS`/`REGEN_SCOPE_TARGETED_KINDS`/`REGEN_SCOPE_SEPARATOR` + `buildRegenerationScope(kind, targetId?)` (builds `acts`/`characters`/`scene:<id>`/`arc:<id>`; throws on a bare+target or targeted-without-id contract violation), `RegenerateRequest` `{ scope, promptAddon? }`, `RegenerationRunResponse` `{ traceId, runId, videoId, scope, status, statusUrl, createdAt, promptAddon?, startedAt?, completedAt?, delta, error? }`, `RegenerationListResponse` `{ traceId, videoId, runs, nextCursor }`. **0.21.0 additions (M9 Story Engine Phase 8a — Adventure Runtime):** `startAdventure(request: StartAdventureRequest, { signal? }?): Promise<AdventureResponse>` (`POST /api/v1/adventures` → 201, `Location` to the session GET URL; a 422 `Persona is not a Dungeon Master` / 404 / 403 surfaces the FastAPI `detail`), `getAdventure(sessionId, { signal? }?): Promise<GetAdventureResponse>` (`GET /api/v1/adventures/{sessionId}`, 404 absent/not-owned), `deleteAdventure(sessionId, { signal? }?): Promise<void>` (`DELETE .../{sessionId}` → 204). New camelCase-wire types `TurnRecord` `{ turn, beatId, summary }`, `AdventureState` `{ sessionId, ownerUserId, storyId, videoId, dmPersonaId, partyPersonaIds, currentBeatId?, visitedBeatIds, flags, inventory, turnHistory, createdAt, updatedAt }`, `StartAdventureRequest` `{ storyId, videoId, dmPersonaId, initialBeatId? }`, `AdventureResponse` `{ traceId, sessionId, state }`, `GetAdventureResponse` `{ traceId, state }`. `PersonaConfig` / `CreatePersonaRequest` / `UpdatePersonaRequest` gain optional snake_case `is_dungeon_master` (read defaults `false`). `ChatWebSocket.send()` options + `buildHelloPayload()` gain optional `adventureSessionId` (spread only when set → land-dark). **0.22.0 additions:** `listAdventures(storyId?, { signal? }?): Promise<ListAdventuresResponse>` (`GET /api/v1/adventures`, owner-scoped newest-first, optional `storyId` filter) + `ListAdventuresResponse` `{ traceId, adventures }`. **0.23.0 additions (M10 Story Engine Phase 9a — multi-persona scene orchestrator):** `addPartyMember(sessionId, personaId, { signal? }?): Promise<GetAdventureResponse>` and `removePartyMember(sessionId, personaId, { signal? }?): Promise<GetAdventureResponse>` — both `PATCH /api/v1/adventures/{sessionId}/party` with `{ action, personaId }` (add: 422 for a DM / non-character / unowned persona; remove: idempotent 200 no-op; 404 for a missing adventure). New types/constants `PARTY_ACTION` (`{ ADD:'add', REMOVE:'remove' }`) + `PartyAction` + `PartyUpdateRequest` `{ action, personaId }`; `StartAdventureRequest` gains optional `partyPersonaIds?: string[]`. `ChatWebSocket.send()` options + `buildHelloPayload()` gain optional `partyPersonaIds?: string[]` (spread only when non-empty → land-dark; advisory — the server's `AdventureState.party_persona_ids` is authoritative). `ChatWsEvent` gains a `turn_changed` member `{ type, timestamp?, personaId, previousPersonaId? }` (mirrors `ChatEventType.TURN_CHANGED`) and an optional `personaId?` on the `token`/`done`/`citation`/`image`/`audio_chunk` members (orchestrator-stamped; undefined elsewhere → land-dark; per-turn TTS voice swap on audio deferred). **R1c additions (Platform Experience Restructure — image adapter registry, no version bump, release is R1e):** `listImageModels(): Promise<ImageModelsResponse>` (`GET /api/v1/images/models`, **authenticated** — unlike chat/models it is NOT in `DEFAULT_PUBLIC_PATHS`; served on the **chat** base URL via `chatRequest`) + `ImageModelInfo` `{ id, displayName, provider, capabilities: string[], isDefault, isFallback }` / `ImageModelsResponse` `{ models }`. **Additive only** (no public export removed/renamed). **0.32.0 additions (Platform Experience Restructure R5a+R5c — cast-with-persona projection):** `getCast(videoId): Promise<CastWithPersonaResponse>` (`GET /api/v1/tools/videos/{videoId}/cast`, tools base URL) — one call returns the character cast pre-joined to bound-persona display fields (the server resolves the PORTRAYS binding; replaces the CastGrid `getVideoGraph`+`listPersonas` client-side `entity_id` join since R5c). New types `CastArc`/`CastScene`/`CastCharacter`/`CastPersonaSummary`/`CastEntry`/`CastWithPersonaResponse` (`CastCharacter.scenes: CastScene[]` carries `{sceneId, title}` so a Cast drawer renders scene titles without the graph payload). New `castWithPersona(response): CastEntry[]` (`src/castProjection.ts`) — the framework-agnostic pure normalizer (deterministic ordering, list coalescing, title/name fallbacks, input never mutated) every Cast consumer shares. **0.32.0 additions (R5b — story-detail graph read):** `getVideoGraph(videoId, detail?)` gains an optional `detail` arg — `GRAPH_DETAIL.STORY` requests the server-collapsed story view (Acts/Scenes/cast/narrative edges; Shots collapsed to per-Scene `shotCount` properties; DialogLine/Event/MENTIONS omitted), `GRAPH_DETAIL.RAW` the full graph; omitting it sends NO query param (byte-identical pre-R5b request). New exports `GRAPH_DETAIL` + `GraphDetail` (mirror of `shared/graph_schema.py`). **0.33.0 additions (Platform Experience Restructure R6b — image filtering params):** `listImages(params)` gains optional `model?: string` + `status?: ImageStatus` filters, mirroring the new `GET /api/v1/images` query params. `model` ids come from R1's image-model registry (discoverable via `listImageModels()`); the backend rejects an unregistered id with 400 — **no client-core image-model descriptor is added** (R1's `imageAdapter.ts` stays the sole catalogue owner). `status` reuses the existing `ImageStatus` union (`ImageRecord['status']`) — no parallel status enum. Omitting both leaves the request byte-identical to 0.32.0 (additive only). **0.44.0 additions (C3a persona-generation, spec Step 11 — auto-generate trigger + job tracking):** `getPersonaGenSettings(): Promise<PersonaGenerationSettings|null>` (`GET /api/v1/personas/settings/generation`, null when unsaved), `updatePersonaGenSettings(body): Promise<PersonaGenerationSettings>` (`PUT` partial merge — `UpdatePersonaGenSettingsRequest` all-optional), `generatePersonasForVideo(videoId): Promise<GeneratePersonasJobResponse>` (`POST /api/v1/videos/{videoId}/personas/generate`, 202 envelope, idempotent on the active `(user,video)` job), `getPersonaJob(jobId): Promise<AutoGenerationJob>` (`GET /api/v1/persona-jobs/{jobId}`, owner-scoped poll — all in `src/api.ts`), and `listPersonasByVideo(sourceVideoId)` + a new optional `sourceVideoId` on `listPersonas({ sourceVideoId })` (→ the `source_video_id` query param). New exported types `PersonaGenerationSettings`, `UpdatePersonaGenSettingsRequest`, `AutoGenerationJob`, `PersonaJobProgress`, `PersonaJobError`, `GeneratePersonasJobResponse`, `PersonaJobStatus`, `PersonaJobErrorStage`; `PersonaConfig` (+`CreatePersonaRequest`/`UpdatePersonaRequest` for the first four) gain optional snake_case `entity_name`/`is_auto_generated`/`source_video_id`/`available_clip_indices`/`clips_used`. **camelCase wire keys** (`jobId`/`traceId`) on `GeneratePersonasJobResponse` ONLY — the backend serializes that model with aliases; `AutoGenerationJob`/`PersonaGenerationSettings` are snake_case (no backend aliases). **0.45.0 additions (C3a persona-generation, spec Step 13 — review/audition page):** `auditionPersona(personaId, body?, { signal? }?): Promise<Blob>` (`POST /api/v1/personas/{id}/audition` — renders a short TTS sample in the persona's current voice; returns the `audio/wav` blob the review page plays via `URL.createObjectURL`+`<audio>`; an omitted body uses the backend default sample text; bypasses the JSON wrapper since the response is binary, same pattern as `getSeedImageBlob`) and `reclonePersona(personaId): Promise<ReclonedPersonaResponse>` (`POST /api/v1/personas/{id}/reclone` — re-clones the voice from a different subset of the cached `persona-clips` WITHOUT re-downloading video; swaps `voice_id`, appends to `clips_used`). New exported types `AuditionRequest`, `ReclonedPersonaResponse` (**camelCase** wire — `personaId`/`voiceId`/`clipsUsed`), `RecloneConflictCode`, and a `RecloneConflictError` class — `reclonePersona` bypasses the generic JSON error path to raise this typed error on a `409` (whose `detail` is a structured object the flattener would render as `[object Object]`) so the review UI can branch on `voice_clone_max_retries_exhausted` vs `no_candidate_clips_remaining` and disable the Reclone control. Additive only; no public export removed/renamed (`../Web-App` pins this package). The persona-gen *pages* (settings/review/list — spec Steps 12–14) consume these. **0.46.0 additions (C3a-f1 — persona-gen trigger relocated to Studio Cast):** `generatePersonasForVideo(videoId, opts?: { entityIds?: string[] })` gains an OPTIONAL second arg — a non-empty `entityIds` sends a snake_case `{ entity_ids: [...] }` body (mirrors the new `GeneratePersonasRequest` backend model) restricting generation to a character subset (Cast per-member "Generate persona"); omitting it (or `entityIds: []`) sends NO body — byte-identical to the prior 1-arg call (whole-video). The prior signature still type-checks (additive). **0.49.0 additions (dashboard A-DM0 — DM scene control):** `DmDirectiveKind` (`'enter_world'|'exit_world'|'seek_video'|'set_experience_source'` — single-sourced with the backend `DM_DIRECTIVE_KINDS`) + `DmDirectiveEvent` `{ type:'dm_directive'; timestamp?; directive: DmDirectiveKind; params: Record<string,unknown> }`. Additive type exports only; no public export removed/renamed. See [CHANGELOG.md](./CHANGELOG.md). |
|
|
24
|
+
| `admin` | **0.19.0 (GitHub #215 Phase 2):** `AdminClient` — the prompt-defaults editor surface. Constructed with the **chat** base URL + session token (the admin router is mounted in `api/chat/app.py`). Methods: `listPromptDefaults()` → `PromptDefaultsListResponse`; `getPromptDefault(key)` / `updatePromptDefault(key, {value})` / `revertPromptDefault(key)` → `PromptDefaultDetail`. Types: `PromptDefaultSource` (`'db'|'code'`), `PromptDefaultSummary`, `PromptDefaultDetail`, `UpdatePromptDefaultRequest`. **0.24.0 (M12 Slice 5 — eval-observability reader):** added `listEvalRuns(params, {signal})` → `EvalRunsListResponse` (one cursor page) and `listAllEvalRuns(params, {signal})` → `AllEvalRunsResult` (`{runs, truncated}`; follows `nextCursor` until null, capped at `MAX_EVAL_RUN_PAGES = 50` — stops not throws, and sets `truncated: true` when the cap is hit with pages still pending so the page warns rather than presenting a partial series as complete). `params` carries the XOR selector `benchmarkId` **or** `promptVersion` (server returns 422 on neither/both) + optional `limit`/`cursor`. Types: `EvalRunSummary`, `EvalRunsListResponse`, `ListEvalRunsParams`, `AllEvalRunsResult` (mirror `api/admin/schemas.py` exactly). The `/observability` web page is the consumer (charts metric scores per `promptVersion`, one line per `modelId`, grouped client-side). **Additive only** — no `ApiClient` export changed. Shares the internal `http.ts` `requestJson` helper that `ApiClient.makeRequest` now also delegates to (DRY, private — not re-exported). The server enforces the editable-key carve-out (extraction keys are not editable → 404 → thrown `Error`). **R6d (read-only regen base prompts):** added `listRegenBasePrompts()` → `RegenBasePromptsResponse` (`GET /api/v1/admin/regen-prompts`; types `RegenBasePrompt`/`RegenBasePromptsResponse` mirror `api/admin/schemas.py`; `editable` always `false`, no write method exists). Also additive on `api.ts`: `RegenerateRequest.appliedDocumentIds?: string[] | null` (cap 20; server silently dedups + drops unknown ids) and `RegenerationRunResponse.appliedDocumentIds?: string[]` mirror the R6c backend fields. **0.47.0 (C4 Phase 3 — admin monitoring tools, data layer):** added a separate read-only `MonitoringClient` (also chat-base + session token) wrapping `/api/v1/admin/monitoring/*`: `listMetrics()` → `MonitoringMetricCatalogResponse` (the allowlist; pick a `metricId` — no raw namespace/name pass-through), `getMetricSeries(metricId, {rangeSeconds, periodSeconds}, {signal})` → `MonitoringMetricSeriesResponse` (CloudWatch GetMetricData; unknown id → 404 → thrown `Error`), `listTraces({jobId, videoId, rangeSeconds}, {signal})` → `MonitoringTraceSummariesResponse` (X-Ray; bad annotation id → 422), `getTraceDetail(xrayTraceId, {signal})` → `MonitoringTraceDetailResponse` (`found=false` when X-Ray has no such trace). Types mirror `api/admin/schemas.py` exactly. **Additive only** — no `ApiClient` export changed. |
|
|
25
25
|
| `reactor/` | Pure builders for the `/interactive` page in seer-agent (and reusable by the Vue Web-App). `buildRegenPrompt(input)` produces deterministic Gemini Flash Image prompts with locked 16:9 + identity guarantees plus a creative-direction escape hatch. `buildUpsamplePrompt(input)` returns `{system, user}` message blocks for any LLM transport, encoding the Helios prompt-guide rules and weaving in entity/persona/previous-prompt context. `aggregateEntityContext` and `aggregatePersonaContext` adapt our existing `ImageRecord` / `EnrichmentRecord` / `PersonaConfig` types into the canonical context shapes. **Phase 2:** `mapEnrichmentToTimeline(enrichment, opts)` consumes a `EnrichmentRecord` and returns a `TimelineBeat[]` (chunk-pinned prompts) for the `/interactive/director` timeline UI. Defensively probes multiple Pegasus result shapes. **Phase 3:** `heliosTools.ts` — `HeliosCommand` (discriminated union), `parseHeliosCommands(text)` (extracts `[SET_SCENE: "…"]`-style inline markers from streamed chat output), `stripHeliosCommands(text)` (removes markers from the displayed transcript), and the future-use `BEDROCK_TOOL_SCHEMAS` Converse-tool-spec export. `toolPromptAddon.ts` — `HELIOS_STEERING_ADDON_ID`, `getHeliosSteeringAddonText()`, idempotent `buildHeliosSteeringSystemPrompt(base)` for personas with `prompt_addon_ids: ['helios-world-steering']`. `entitySearch.ts` — `findEntityImageBySeedName(apiClient, videoId, name)` resolves an entity name to its `ImageRecord` (searches `extracted` then `character`, case-insensitive). Per-`(videoId, category)` in-process cache so repeat SWAP_SEED commands skip the API round-trip; `forceRefresh: true` and `clearEntitySearchCache()` bypass it. `heliosCommandDispatcher.ts` — `dispatchHeliosCommand(cmd, ctx)` executes a `HeliosCommand` against a structural Reactor bridge (`sendCommand` + `uploadFile`); pure async function, no React. `HeliosToolContext.signal?: AbortSignal` cancels in-flight upsample + seed-image work on unmount. `seedImageOrchestrator.ts` — `loadSeedImageFile(imageId, apiClient)` + `sendSeedFileToReactor(file, reactor, opts)` + convenience `loadAndApplySeedImage`. Used by all three `/interactive` React pages AND by the SWAP_SEED branch of the dispatcher, so the load → upload → set_image sequence has exactly one implementation. No `@reactor-team/js-sdk` dependency — that stays in the consuming app. `applyScenePrompt.ts` — `applyScenePrompt({prompt, apiClient, reactor, currentChunk, isRunning, ...})`: shared submit policy for a live Helios session. `!isRunning` → `set_prompt` + `start`; running → `schedule_prompt` at `currentChunk + 2`. Upsample failure falls back to the raw prompt; abort propagates. Used by both `InteractiveController` and the watch-page `HeliosWorldControls` so the two pages cannot diverge. **LongLive-v2 director initiative (Step 2, additive, land-dark — no version bump, R1e releases):** `longLiveCommandDispatcher.ts` — `dispatchLongLiveCommand(cmd, ctx)`, the `dispatchHeliosCommand` analogue for the Reactor **LongLive-v2** world model over the **SAME Reactor transport** (only the `modelName` differs). `LongLiveCommand` is its OWN discriminated union (`set_shot`/`scene_cut`/`schedule_shot`/`schedule_scene_cut`/`pause`/`resume`/`reset`/`set_seed`) — NOT a `HeliosCommand`. Mappings to `reactor.sendCommand`: `set_shot{prompt}` → `set_shot` then `start` **only when `!ctx.hasStarted`** (the opening-shot-then-start guard, mirroring Helios `set_scene` chunk-0); `scene_cut{prompt}` → `scene_cut` (a HARD, memory-purging transition Helios lacks); `schedule_shot`/`schedule_scene_cut` use the snake_case `at_session_chunk` wire field; `pause`/`resume`/`reset` → `{}`; `set_seed{seed}` → `set_seed`. `LongLiveToolContext` is NARROWER than `HeliosToolContext`: `reactor: Pick<HeliosReactorBridge, 'sendCommand'>` (reuses the structural bridge — **no rename, no `uploadFile`**: LongLive is text-to-video with NO image conditioning, hence **NO `swap_seed`**), `hasStarted?`, `signal?`, `onUserWarning?`. Same failure policy: clean abort silent (reuses `isAbortError`), other failures logged + skipped. **SDK-free** (no `@reactor-team/js-sdk` import). **R8.1 (0.39.0):** `storyTimeline.ts` — `deriveStoryTimeline(scenes: SceneView[], options?)` maps the collapsed R5 `detail=story` projection (one `SceneView` per scene) to `TimelineBeat[]`: one beat per scene, prompt grounded in the scene summary + featured-character names + location label, scene-id provenance in the `label`. The **story-graph-driven sibling** of `mapEnrichmentToTimeline` (which stays the labelled FALLBACK for graph-less videos). `chunkDistribution.ts` (internal — NOT barrel-exported) holds the shared `computeChunkIndices`/`enforceSpacing` so BOTH mappers share ONE chunk-distribution algorithm (extracted from `scenesFromEnrichment.ts`; DRY — one place can break). `StoryTimelineOptions` mirrors `MapEnrichmentOptions`. Spec: [`specs/interactive-helios-prototype.md`](../../specs/interactive-helios-prototype.md). |
|
|
26
26
|
| `adapters/` | **R1a (Platform Experience Restructure):** the framework-agnostic model-adapter registry primitive every later R1 adapter (image / world / director domains) registers into. **Zero React / DOM / provider-SDK imports** — same discipline as `reactor/` and `vision/`. `capabilities.ts` — `Capability` is the single capability union, formed by **extending** the existing `ChatModelCapability` (`api.ts:499`, the source of truth that mirrors `shared/model_config.py:CAPABILITY_*`) with the net-new TS-only domains `ImageCapability` (`'image_gen'|'image_edit'|'identity_preserve'`), `WorldCapability` (`'world_stream'|'set_scene'|'swap_seed'|'pause_resume'`), `DirectorCapability` (`'timeline_schedule'|'enrichment_driven'`). There is **no parallel `CAPABILITY` const map** — extend the union, don't re-spell the four chat strings. `registry.ts` — `AdapterRegistry<TDescriptor extends ModelAdapterDescriptor>` ({ `domain`, `routes`, `fallbackRouteName` }): `register()` is additive and **throws on a duplicate id** (no silent overwrite); `get`/`list`/`listWithCapability(cap)`; `resolveRoute(name)` returns the named route's adapter and **degrades to the fallback route's adapter when the route's adapterId is unregistered — NEVER throws** (parity with `shared/model_router.py:344-360`); `satisfies(id, required)` is true iff the id is registered and advertises every required cap. Route names are the exported `ROUTE_DEFAULT`/`ROUTE_FALLBACK`/`ROUTE_HIGH_QUALITY` string constants (the `ROUTE_*` analogue of `shared/model_router.py:56-59`), never inline literals. `ModelAdapterDescriptor.metadata` is opaque/forward-compat — carried, not interpreted. **R1b** adds `chatAdapter.ts` — `loadChatAdapterRegistry(client)` hydrates an `AdapterRegistry<ChatAdapterDescriptor>` from `GET /api/v1/chat/models` and is a **FACADE over the backend**: model selection stays server-side in `shared/model_router.py`, so there is **no `route()` / client-side selection table** here — it only mirrors the catalogue (one descriptor per model, `capabilities` copied VERBATIM) so the UI can list / `listWithCapability` / auto-switch. `ROUTE_DEFAULT`/`ROUTE_FALLBACK` both mirror the resolved default id (parity with `api/chat/app.py:686-697`: `defaultModelId` when present in models, else the first model by `(provider, id)`; empty models → `''` sentinel so the constructor guard still passes and `resolveRoute` degrades to `undefined`, never throws). **R1c** adds `imageAdapter.ts` — `loadImageAdapterRegistry(client)` hydrates an `AdapterRegistry<ImageAdapterDescriptor>` from `GET /api/v1/images/models` (via `ApiClient.listImageModels()`, served on the **chat** base URL since the images API is mounted on the chat app). Same FACADE discipline as the chat adapter — image generation still resolves to Gemini in the pipeline unchanged (R1c is land-dark); this only mirrors the catalogue so a future UI (R6) can list / `listWithCapability('identity_preserve')`. `ROUTE_DEFAULT` mirrors the `isDefault`-flagged model id (else first by id), and `ROUTE_FALLBACK` the `isFallback`-flagged model (the registry's real fallback; mirrors default when none flagged) — empty models → `''` sentinel so the constructor guard still passes and `resolveRoute` degrades to `undefined`. `ImageModelInfo`/`ImageModelsResponse` wire types live in `api.ts` (`capabilities: string[]` — cast to `Capability[]` only inside the adapter to avoid an `api.ts`↔`capabilities.ts` cycle). **R1d** adds `worldAdapter.ts` + `directorAdapter.ts` — the net-new WORLD (step-into-video) and DIRECTOR registries, seeded with the one model that exists today: **Helios**. `worldAdapter.ts` — `WorldAdapterDescriptor` extends `ModelAdapterDescriptor` with `supportedCommands: readonly string[]` (**model-agnostic** — the registry holds heterogeneous world models; a sibling such as a Reactor LongLive adapter has its OWN command vocabulary `set_shot`/`scene_cut`/… that is not a `HeliosCommand`); `heliosWorldAdapter` (`id:'helios'`, provider `'reactor'`, caps `['world_stream','set_scene','swap_seed','pause_resume']`, `supportedCommands` = the EXACT `HeliosCommand` variant set from `reactor/heliosTools.ts:32-37`) **CENTRALIZES the `'helios'` model-name literal** so the R8 page rewire stops hard-coding it; `createWorldRegistry()` pre-registers it with `ROUTE_DEFAULT`+`ROUTE_FALLBACK` both → its id; `requiredCapabilityForCommand(cmd)` is the pure exhaustive-switch mapping (`set_scene`→`'set_scene'`, `swap_seed`→`'swap_seed'`, `pause_world`/`resume_world`→`'pause_resume'`, `reset_world`→`'world_stream'`). `dispatchWorldCommand(adapterId, cmd, ctx)` routes **in FRONT of the existing `dispatchHeliosCommand`** (NOT a rewrite): the Helios branch delegates with **IDENTICAL args** — the live Helios path is UNCHANGED (LAND-DARK) — and an unknown id throws the typed `UnsupportedWorldAdapterError` WITHOUT touching the bridge. It reuses the structural `HeliosReactorBridge` via `HeliosToolContext` — **no `@reactor-team/js-sdk` import**, the adapters/ submodule stays SDK-free. `directorAdapter.ts` — `DirectorAdapterDescriptor` extends `ModelAdapterDescriptor` with `worldAdapterId`; `heliosDirectorAdapter` (`id:'helios-director'`) backs onto `heliosWorldAdapter` and its `capabilities` are the director members `['timeline_schedule','enrichment_driven']` **plus the four world caps it inherits via `worldAdapterId`** (deduped); `createDirectorRegistry()` pre-registers it. **LongLive-v2 director initiative (Step 2 — additive, land-dark, no version bump):** `worldAdapter.ts` adds `longLiveWorldAdapter` (`id:'longlive-v2'`, displayName `'LongLive 2.0'`, provider `'reactor'`, caps `['world_stream','set_scene','scene_cut','pause_resume']`, `supportedCommands` = its 8 LongLive command strings). The **ASYMMETRIC capability matrix** holds via `registry.satisfies`: Helios HAS `swap_seed` and NOT `scene_cut`; LongLive HAS `scene_cut` (a hard memory-purging transition) and NOT `swap_seed` (text-to-video, no image conditioning). `createWorldRegistry()` now registers **both** adapters; **world `ROUTE_DEFAULT`+`ROUTE_FALLBACK` STAY Helios** (plain `/interactive` unchanged — LongLive is resolvable by id + `listWithCapability('scene_cut')` but is NOT the world default). `dispatchWorldCommand` is **widened via FUNCTION OVERLOADS** that keep exact `(adapterId, cmd, ctx)` typing per adapter — `'helios'` → `dispatchHeliosCommand` (BYTE-IDENTICAL to R1d), `'longlive-v2'` → `dispatchLongLiveCommand`, unknown → throw. **No per-command runtime capability gate** (the R1d review removed the unreachable `satisfies` scaffolding): the overloads enforce the cmd/adapter match at compile time, and the asymmetric-matrix INFO is consumed via `registry.satisfies()` by the Step-3 director UI (to hide the seed-image control for LongLive), not a dispatch gate (resolves tech-debt #414). `directorAdapter.ts` adds `longLiveDirectorAdapter` (`id:'longlive-director'`, backs onto `longLiveWorldAdapter`, inherits `scene_cut` + the director members, NOT `swap_seed`). **THE DIRECTOR-DEFAULT FLIP:** `createDirectorRegistry()` registers both directors and points `ROUTE_DEFAULT` → `'longlive-director'`, `ROUTE_FALLBACK` → `'helios-director'` (the world default stays Helios; only the DIRECTOR default flips). LAND-DARK — nothing reads the director route until **Step 3 wires the web director page**; the live `/interactive` and `/interactive/director` pages are UNCHANGED (their `modelName="helios"` literals stay; **R8 migrates the pages**). **Purely additive to client-core** — no existing public export removed/renamed (the sibling Vue Web-App pins this package); Steps 1–2 carried no version bump (the release is R1e). **R1e (0.25.0 — R1's release):** `index.ts` adds the aggregator `createPlatformRegistries(client): Promise<PlatformRegistries>` — the **single entry** every downstream wave imports to get all four registries pre-wired. `world` + `director` are synchronous seeds (Helios world default; LongLive-v2 director default); `chat` + `image` load from their backend catalogues via the existing facades in parallel. It makes NO selection decision — it only composes `loadChatAdapterRegistry`/`loadImageAdapterRegistry`/`createWorldRegistry`/`createDirectorRegistry` (DRY). `PlatformRegistries` = `{ chat, image, world, director }`. The `seer-agent` `web/` `/admin/adapters` showroom inspector is the first consumer; additive-only (no export removed/renamed). |
|
|
27
|
-
| `conversation/` | **R2.1 (0.26.0 — Conversation panel core):** the framework-agnostic, headless **conversation state** primitive that lets React (R2.2) and a game engine (PlayCanvas, R7) render the **same** controller. **Zero DOM** — same discipline as `reactor/`/`adapters/`. `participant.ts` — `ConversationParticipant` `{ participantId; personaId?; role; presence; modelId?; capabilities? }` + the frozen constant objects `ParticipantRole` (`persona`/`dm`/`user`) and `PresenceKind` (`PRESENCE_NONE`/`PRESENCE_FACE_2D`/`PRESENCE_AVATAR_3D`) — constants, never inline literals. `presenceRegistry.ts` — `PresenceRendererRegistry` (mirrors `reactor/promptAddonRegistry.ts`): `register(kind, factory)`/`resolve(kind)`/`has(kind)`; a factory returns an opaque `PresenceHandle` (`mount`/`update`/`destroy`) so React and a game engine register their own renderer; **THROWS on duplicate register** (fail-loud) and **returns the `PRESENCE_NONE` no-op for any unregistered kind** (fail-soft — this is what lets the reserved `PRESENCE_AVATAR_3D` stub render nothing until R7; tech-debt #421). `binding.ts` — `ConversationContextBinding` `{ kind: 'video'|'studio_session'|'none'; videoId?; entityId?; adventureSessionId?; partyPersonaIds? }` + the `ConversationContextKind` constant + a single `toHelloArgs(binding)` mapper that maps **1:1 onto `buildHelloPayload`** so there is exactly one hello-builder (DRY). `effectiveModel.ts` — `resolveEffectiveModel({ boundModelId, capabilities, needed, override, registry })` is the **single, pure** capability auto-switch (no I/O; R3's vision picker CONSUMES it — there is no parallel `resolveVisionCapability`): returns `{ modelId; reason: 'bound'|'override'|'auto_switch'; switchedFrom?; needed }`. Capability facts come ONLY from the injected R1 chat registry (`listWithCapability`/`satisfies`, typed as a narrow `Pick<>` so the helper depends on just those two methods) — R2 never hardcodes which models are vision-capable, and **fails SOFT to `bound`** when no model advertises the needed capability (a config state the panel surfaces, not a crash). `controller.ts` — `ConversationController`, a **thin state+reducer over the existing `ChatWebSocket`** (it does NOT reimplement transport/reconnect/protocol): holds participants/activeParticipant/`contextBinding`/`modelOverride?` + a reference to the R1 chat registry; `connect()`/`send(text)`/`setModelOverride`/`clearModelOverride`/`addParticipant`/`removeParticipant`/`setActiveParticipant`/`dispose()`; emits a typed `onState(snapshot)` callback (no framework events); the sole `buildHello()` builds the hello once via `buildHelloPayload(toHelloArgs(binding))`; re-derives advisory `partyPersonaIds` (matching `chat-ws/adventureMode.ts`) on participant changes. **Socket adoption:** the constructor takes an optional `existingSocket?: ChatWebSocket` — when supplied it ADOPTS that socket (opens none) and `dispose()` does **NOT** close it (the owner does) — the Watch shared-socket invariant (R2.4) so the dispatcher reads one `FrameBuffer`. **ADDITIVE-ONLY:** `Citation`/`PlaybackState`/`ChatModelCapability` are IMPORTED from `websocket.ts`/`api.ts`, never re-declared (avoids the ambiguous-export trap). **R2.3 (0.30.0):** the controller's hello is **`mode:'text'`, always** (it previously inherited `buildHelloPayload`'s `tts_stt` default, which would have routed the first self-driving `connect()` into the backend voice pipeline — the controller owns TEXT conversations; the voice hello stays page-owned per the R2.2 finding), `onMessage(handler): () => void` is the additive reply-event seam (a passthrough to `ChatWebSocket.onMessage`/`offMessage`) so a renderer can consume `token`/`citation`/`done`/`error`/`turn_changed` frames without reaching into a privately-owned socket, and `send(text, opts?)` gains additive `opts.messages` (`ConversationSendOptions`/`ConversationHistoryMessage`) — the transcript-owning renderer passes prior turns per send because the backend builds `conversation_history` solely from each send's `messages` field (omitted/empty ⇒ wire unchanged). **R7.1 (0.35.0 — portable conversation runtime):** the multi-persona runtime joins the subsystem. `router.ts` — advisory routing helpers lifted verbatim from `web/app/chat-ws/adventureMode.ts` (`MultiPersonaFrameFields`, `turnChangedSpeakerId`, `resolvePersonaPill`+`PillPersona`, `advisoryPartyPersonaIds`); **ADVISORY ONLY** — the server `agents/orchestrator/persona_router.py` `resolve_addressed_persona` is authoritative, the client never routes a turn, it only renders the server's `turn_changed`. `roster.ts` — `ADVENTURE_MUTATION_TOOLS` (the SINGLE copy of the four DM mutation tool names, mirroring `shared/tool_schemas.py`), `isAdventureMutationTool`, `shouldRefreshAdventureRail` (the one land-dark gate on adventure-state refresh), `filterPartyCandidates`+`PartyCandidatePersona`. `runtime.ts` — `ConversationRuntime` (`src/conversation/runtime.ts:33`): a pure reducer/observer over the existing `ChatWsEvent` union — `applyFrame(event)` / `getState(): ConversationRuntimeState` / `subscribe(listener)` (fault-isolated, returns unsubscribe) / `acknowledgeAdventureState()` / `releaseTurn(personaId)` (R7.2, additive: the host removed the persona holding the turn — `activePersonaId` returns to null; the only host-driven speaker transition, `turn_changed` remains the only way the speaker MOVES to a persona). The speaker ONLY moves on a server `turn_changed` while an adventure is active; `done` finalizes the per-message persona pill; a DM-mutation `tool_result` sets `staleAdventureState` for the host to re-fetch+ack. Immutable state-per-transition, listeners fire only on actual change. `types.ts` — `RosterParticipant`/`ConversationRuntimeState`/`ConversationRuntimeOptions` (REUSES the R2.1 `PresenceKind` constants — never re-declared, per the ambiguous-export trap). **PlayCanvas portability:** the runtime has zero React/DOM imports and runs in plain node — a 3D host feeds it the same frames and renders `ConversationRuntimeState` directly; the renderer seam (`PresenceAdapter`) lands in R7.3. Caveat for any engine host: client routing stays advisory — never promote the router helpers to a turn decision. **R7.3 (0.36.0 — `PresenceAdapter` seam, the portability contract):** `presence.ts` — `PresenceAdapter`, the renderer-agnostic interface the runtime drives: `mount(participant)`/`unmount(personaId)`/`setActiveParticipant(personaId|null)`/`setSpeaking(personaId, speaking)`/`applyViseme(personaId, viseme: VisemeSymbol)` — every method keyed by `personaId` (N participants → N presence slots, renderer-independent); `applyViseme` takes the *scheduled viseme value* from the existing `visemeScheduler` pipeline, NEVER a DOM node (the React adapter applies it to SVG, a PlayCanvas adapter to morph targets); `presenceKindHasStage(kind)` is the single text-only gate (a `PRESENCE_NONE` seat receives nothing beyond `mount`/`unmount`). Adapter *selection* stays on the R2.1 `PresenceRendererRegistry` — no parallel kind→factory map. `presenceBus.ts` — `bindPresence(runtime, adapter): PresenceBinding`, pure glue (no renderer dependency): bind mounts the roster + stages the initial speaker; a speaker swap emits `setActiveParticipant(next)` + `setSpeaking(prev,false)` + `setSpeaking(next,true)`; an unstaged/unknown speaker clears the stage to `null`; `PresenceBinding.applyViseme` is the SINGLE viseme delivery path (R7.5's voice module consumes it — never instantiate a second path); `dispose()` is idempotent. **Headless conformance harness:** `src/__tests__/conversation/headlessRenderer.ts` (`RecordingPresenceAdapter`) + `presenceBus.test.ts` pin the exact call sequence a real renderer receives for a 3-participant cue chain, in plain node — the executable proof of PlayCanvas-portability; an engine implements `PresenceAdapter` against that sequence with zero client-core changes. **R7.4 (0.37.0 — Studio cast roster projection):** `rosterProjection.ts` — `castToRoster({ cast, dmPersona, partyPersonaIds })` (`src/conversation/rosterProjection.ts:55`): the single DRY projection turning R5's one-call cast-with-persona response (`getCast` → `CastEntry[]`) + the active `AdventureState` into `RosterParticipant[]` (DM seat first, then party members in party order; de-duplicated, DM never doubled; every server-party member gets a seat even when absent from the cast so a `turn_changed` speaker can always be staged). This is the one place the renderer-facing roster is built — it replaces the pre-R7.4 client-side `entity_id ∈ storyCharacterEntityIds` join across two stores. Pure (no I/O/DOM/React). **R7.5 (0.38.0 — overlay voice parity):** `voice.ts` — `VoiceSession` (`src/conversation/voice.ts`): the framework-agnostic voice pipeline driving a full STT/TTS/mic/viseme round-trip over the SAME `ChatWebSocket` the controller owns/adopts. A THIN composition (not a re-implementation): it composes the existing `AudioPipeline` (player + `VisemeScheduler` + `AudioSessionClient` barge-in + sentence anchoring) + `MicrophoneRecorder`, and builds the voice (`tts_stt`) hello through the SINGLE `buildHelloPayload` — **no second viseme scheduler, no second hello-construction site**. `buildHello()` is fixture-diffed against the page's `startVoiceChat()` payload (the parity oracle, `voice.test.ts`); `start()` mirrors the page's iOS user-gesture priming order EXACTLY (player + `recorder.prime()` in the synchronous prefix — callers MUST invoke it from a click handler's sync prefix); `interrupt()` = barge-in; `dispose()` NEVER closes the socket (the Watch shared-socket invariant). Visemes flow through one `onViseme` callback the renderer routes onto R7.3's `PresenceAdapter.applyViseme` (the single delivery path). `ConversationController` gains additive `voiceSocket()` (hands the shared socket to a `VoiceSession`) + `voiceHelloArgs()` (the single hello-args input: context + active persona/model). The text-only overlay default is unchanged (`mode:'text'`; voice is per-conversation opt-in); `/chat-ws` stays the page-owned parity oracle (its collapse onto `VoiceSession` is tech-debt #470). |
|
|
27
|
+
| `conversation/` | **R2.1 (0.26.0 — Conversation panel core):** the framework-agnostic, headless **conversation state** primitive that lets React (R2.2) and a game engine (PlayCanvas, R7) render the **same** controller. **Zero DOM** — same discipline as `reactor/`/`adapters/`. `participant.ts` — `ConversationParticipant` `{ participantId; personaId?; role; presence; modelId?; capabilities? }` + the frozen constant objects `ParticipantRole` (`persona`/`dm`/`user`) and `PresenceKind` (`PRESENCE_NONE`/`PRESENCE_FACE_2D`/`PRESENCE_AVATAR_3D`) — constants, never inline literals. `presenceRegistry.ts` — `PresenceRendererRegistry` (mirrors `reactor/promptAddonRegistry.ts`): `register(kind, factory)`/`resolve(kind)`/`has(kind)`; a factory returns an opaque `PresenceHandle` (`mount`/`update`/`destroy`) so React and a game engine register their own renderer; **THROWS on duplicate register** (fail-loud) and **returns the `PRESENCE_NONE` no-op for any unregistered kind** (fail-soft — this is what lets the reserved `PRESENCE_AVATAR_3D` stub render nothing until R7; tech-debt #421). `binding.ts` — `ConversationContextBinding` `{ kind: 'video'|'studio_session'|'persona'|'none'; videoId?; personaId?; entityId?; adventureSessionId?; partyPersonaIds? }` + the `ConversationContextKind` constant + a single `toHelloArgs(binding)` mapper that maps **1:1 onto `buildHelloPayload`** so there is exactly one hello-builder (DRY). **0.48.0 (dashboard B1):** the `PERSONA` kind + the `personaId` field make a standalone persona-face chat a DISTINCT binding so the floater's switch-persona path rebinds (`conversationBindingKey` keys on `personaId`) instead of colliding on a shared `NONE` key; `personaId` is also a `buildHelloPayload` arg (same falsy-drop land-dark contract as the other id fields), and the controller still overlays the active participant's `personaId` on top. `effectiveModel.ts` — `resolveEffectiveModel({ boundModelId, capabilities, needed, override, registry })` is the **single, pure** capability auto-switch (no I/O; R3's vision picker CONSUMES it — there is no parallel `resolveVisionCapability`): returns `{ modelId; reason: 'bound'|'override'|'auto_switch'; switchedFrom?; needed }`. Capability facts come ONLY from the injected R1 chat registry (`listWithCapability`/`satisfies`, typed as a narrow `Pick<>` so the helper depends on just those two methods) — R2 never hardcodes which models are vision-capable, and **fails SOFT to `bound`** when no model advertises the needed capability (a config state the panel surfaces, not a crash). `controller.ts` — `ConversationController`, a **thin state+reducer over the existing `ChatWebSocket`** (it does NOT reimplement transport/reconnect/protocol): holds participants/activeParticipant/`contextBinding`/`modelOverride?` + a reference to the R1 chat registry; `connect()`/`send(text)`/`setModelOverride`/`clearModelOverride`/`addParticipant`/`removeParticipant`/`setActiveParticipant`/`dispose()`; emits a typed `onState(snapshot)` callback (no framework events); the sole `buildHello()` builds the hello once via `buildHelloPayload(toHelloArgs(binding))`; re-derives advisory `partyPersonaIds` (matching `chat-ws/adventureMode.ts`) on participant changes. **Socket adoption:** the constructor takes an optional `existingSocket?: ChatWebSocket` — when supplied it ADOPTS that socket (opens none) and `dispose()` does **NOT** close it (the owner does) — the Watch shared-socket invariant (R2.4) so the dispatcher reads one `FrameBuffer`. **ADDITIVE-ONLY:** `Citation`/`PlaybackState`/`ChatModelCapability` are IMPORTED from `websocket.ts`/`api.ts`, never re-declared (avoids the ambiguous-export trap). **R2.3 (0.30.0):** the controller's hello is **`mode:'text'`, always** (it previously inherited `buildHelloPayload`'s `tts_stt` default, which would have routed the first self-driving `connect()` into the backend voice pipeline — the controller owns TEXT conversations; the voice hello stays page-owned per the R2.2 finding), `onMessage(handler): () => void` is the additive reply-event seam (a passthrough to `ChatWebSocket.onMessage`/`offMessage`) so a renderer can consume `token`/`citation`/`done`/`error`/`turn_changed` frames without reaching into a privately-owned socket, and `send(text, opts?)` gains additive `opts.messages` (`ConversationSendOptions`/`ConversationHistoryMessage`) — the transcript-owning renderer passes prior turns per send because the backend builds `conversation_history` solely from each send's `messages` field (omitted/empty ⇒ wire unchanged). **R7.1 (0.35.0 — portable conversation runtime):** the multi-persona runtime joins the subsystem. `router.ts` — advisory routing helpers lifted verbatim from `web/app/chat-ws/adventureMode.ts` (`MultiPersonaFrameFields`, `turnChangedSpeakerId`, `resolvePersonaPill`+`PillPersona`, `advisoryPartyPersonaIds`); **ADVISORY ONLY** — the server `agents/orchestrator/persona_router.py` `resolve_addressed_persona` is authoritative, the client never routes a turn, it only renders the server's `turn_changed`. `roster.ts` — `ADVENTURE_MUTATION_TOOLS` (the SINGLE copy of the four DM mutation tool names, mirroring `shared/tool_schemas.py`), `isAdventureMutationTool`, `shouldRefreshAdventureRail` (the one land-dark gate on adventure-state refresh), `filterPartyCandidates`+`PartyCandidatePersona`. `runtime.ts` — `ConversationRuntime` (`src/conversation/runtime.ts:33`): a pure reducer/observer over the existing `ChatWsEvent` union — `applyFrame(event)` / `getState(): ConversationRuntimeState` / `subscribe(listener)` (fault-isolated, returns unsubscribe) / `acknowledgeAdventureState()` / `releaseTurn(personaId)` (R7.2, additive: the host removed the persona holding the turn — `activePersonaId` returns to null; the only host-driven speaker transition, `turn_changed` remains the only way the speaker MOVES to a persona). The speaker ONLY moves on a server `turn_changed` while an adventure is active; `done` finalizes the per-message persona pill; a DM-mutation `tool_result` sets `staleAdventureState` for the host to re-fetch+ack. Immutable state-per-transition, listeners fire only on actual change. `types.ts` — `RosterParticipant`/`ConversationRuntimeState`/`ConversationRuntimeOptions` (REUSES the R2.1 `PresenceKind` constants — never re-declared, per the ambiguous-export trap). **PlayCanvas portability:** the runtime has zero React/DOM imports and runs in plain node — a 3D host feeds it the same frames and renders `ConversationRuntimeState` directly; the renderer seam (`PresenceAdapter`) lands in R7.3. Caveat for any engine host: client routing stays advisory — never promote the router helpers to a turn decision. **R7.3 (0.36.0 — `PresenceAdapter` seam, the portability contract):** `presence.ts` — `PresenceAdapter`, the renderer-agnostic interface the runtime drives: `mount(participant)`/`unmount(personaId)`/`setActiveParticipant(personaId|null)`/`setSpeaking(personaId, speaking)`/`applyViseme(personaId, viseme: VisemeSymbol)` — every method keyed by `personaId` (N participants → N presence slots, renderer-independent); `applyViseme` takes the *scheduled viseme value* from the existing `visemeScheduler` pipeline, NEVER a DOM node (the React adapter applies it to SVG, a PlayCanvas adapter to morph targets); `presenceKindHasStage(kind)` is the single text-only gate (a `PRESENCE_NONE` seat receives nothing beyond `mount`/`unmount`). Adapter *selection* stays on the R2.1 `PresenceRendererRegistry` — no parallel kind→factory map. `presenceBus.ts` — `bindPresence(runtime, adapter): PresenceBinding`, pure glue (no renderer dependency): bind mounts the roster + stages the initial speaker; a speaker swap emits `setActiveParticipant(next)` + `setSpeaking(prev,false)` + `setSpeaking(next,true)`; an unstaged/unknown speaker clears the stage to `null`; `PresenceBinding.applyViseme` is the SINGLE viseme delivery path (R7.5's voice module consumes it — never instantiate a second path); `dispose()` is idempotent. **Headless conformance harness:** `src/__tests__/conversation/headlessRenderer.ts` (`RecordingPresenceAdapter`) + `presenceBus.test.ts` pin the exact call sequence a real renderer receives for a 3-participant cue chain, in plain node — the executable proof of PlayCanvas-portability; an engine implements `PresenceAdapter` against that sequence with zero client-core changes. **R7.4 (0.37.0 — Studio cast roster projection):** `rosterProjection.ts` — `castToRoster({ cast, dmPersona, partyPersonaIds })` (`src/conversation/rosterProjection.ts:55`): the single DRY projection turning R5's one-call cast-with-persona response (`getCast` → `CastEntry[]`) + the active `AdventureState` into `RosterParticipant[]` (DM seat first, then party members in party order; de-duplicated, DM never doubled; every server-party member gets a seat even when absent from the cast so a `turn_changed` speaker can always be staged). This is the one place the renderer-facing roster is built — it replaces the pre-R7.4 client-side `entity_id ∈ storyCharacterEntityIds` join across two stores. Pure (no I/O/DOM/React). **R7.5 (0.38.0 — overlay voice parity):** `voice.ts` — `VoiceSession` (`src/conversation/voice.ts`): the framework-agnostic voice pipeline driving a full STT/TTS/mic/viseme round-trip over the SAME `ChatWebSocket` the controller owns/adopts. A THIN composition (not a re-implementation): it composes the existing `AudioPipeline` (player + `VisemeScheduler` + `AudioSessionClient` barge-in + sentence anchoring) + `MicrophoneRecorder`, and builds the voice (`tts_stt`) hello through the SINGLE `buildHelloPayload` — **no second viseme scheduler, no second hello-construction site**. `buildHello()` is fixture-diffed against the page's `startVoiceChat()` payload (the parity oracle, `voice.test.ts`); `start()` mirrors the page's iOS user-gesture priming order EXACTLY (player + `recorder.prime()` in the synchronous prefix — callers MUST invoke it from a click handler's sync prefix); `interrupt()` = barge-in; `dispose()` NEVER closes the socket (the Watch shared-socket invariant). Visemes flow through one `onViseme` callback the renderer routes onto R7.3's `PresenceAdapter.applyViseme` (the single delivery path). `ConversationController` gains additive `voiceSocket()` (hands the shared socket to a `VoiceSession`) + `voiceHelloArgs()` (the single hello-args input: context + active persona/model). The text-only overlay default is unchanged (`mode:'text'`; voice is per-conversation opt-in); `/chat-ws` stays the page-owned parity oracle (its collapse onto `VoiceSession` is tech-debt #470). |
|
|
28
28
|
|
|
29
29
|
## Layout
|
|
30
30
|
|
package/dist/admin.d.ts
CHANGED
|
@@ -121,6 +121,84 @@ export interface AllEvalRunsResult {
|
|
|
121
121
|
runs: EvalRunSummary[];
|
|
122
122
|
truncated: boolean;
|
|
123
123
|
}
|
|
124
|
+
/** One allowlisted metric the admin tools may chart (catalog view). */
|
|
125
|
+
export interface MonitoringMetricCatalogEntry {
|
|
126
|
+
metricId: string;
|
|
127
|
+
namespace: string;
|
|
128
|
+
metricName: string;
|
|
129
|
+
stat: string;
|
|
130
|
+
unit: string;
|
|
131
|
+
label: string;
|
|
132
|
+
dimensionKeys: string[];
|
|
133
|
+
}
|
|
134
|
+
/** Response for `GET /api/v1/admin/monitoring/metrics` (catalog list). */
|
|
135
|
+
export interface MonitoringMetricCatalogResponse {
|
|
136
|
+
metrics: MonitoringMetricCatalogEntry[];
|
|
137
|
+
traceId: string;
|
|
138
|
+
}
|
|
139
|
+
/** One (timestamp, value) point on a metric series. */
|
|
140
|
+
export interface MonitoringMetricDatapoint {
|
|
141
|
+
timestamp: string;
|
|
142
|
+
value: number;
|
|
143
|
+
}
|
|
144
|
+
/** A resolved CloudWatch series for one allowlisted metric. */
|
|
145
|
+
export interface MonitoringMetricSeriesResponse {
|
|
146
|
+
metricId: string;
|
|
147
|
+
label: string;
|
|
148
|
+
unit: string;
|
|
149
|
+
periodSeconds: number;
|
|
150
|
+
startTime: string;
|
|
151
|
+
endTime: string;
|
|
152
|
+
/** May be empty (no data in window / seam not yet instrumented). */
|
|
153
|
+
datapoints: MonitoringMetricDatapoint[];
|
|
154
|
+
traceId: string;
|
|
155
|
+
}
|
|
156
|
+
/** One X-Ray trace in the explorer list view. */
|
|
157
|
+
export interface MonitoringTraceSummary {
|
|
158
|
+
traceId: string;
|
|
159
|
+
durationSeconds: number | null;
|
|
160
|
+
responseTimeSeconds: number | null;
|
|
161
|
+
hasError: boolean;
|
|
162
|
+
hasFault: boolean;
|
|
163
|
+
hasThrottle: boolean;
|
|
164
|
+
httpStatus: number | null;
|
|
165
|
+
}
|
|
166
|
+
/** Response for `GET /api/v1/admin/monitoring/traces` (X-Ray summaries). */
|
|
167
|
+
export interface MonitoringTraceSummariesResponse {
|
|
168
|
+
startTime: string;
|
|
169
|
+
endTime: string;
|
|
170
|
+
/** Empty until more seams are instrumented (only bedrock.converse so far). */
|
|
171
|
+
traces: MonitoringTraceSummary[];
|
|
172
|
+
traceId: string;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Response for `GET /api/v1/admin/monitoring/traces/{xrayTraceId}`.
|
|
176
|
+
*
|
|
177
|
+
* `found=false` (200, empty `segments`) when X-Ray has no such trace. `segments`
|
|
178
|
+
* is the raw X-Ray segment-document list for the client-side waterfall renderer.
|
|
179
|
+
*/
|
|
180
|
+
export interface MonitoringTraceDetailResponse {
|
|
181
|
+
xrayTraceId: string;
|
|
182
|
+
found: boolean;
|
|
183
|
+
segments: Array<Record<string, unknown>>;
|
|
184
|
+
traceId: string;
|
|
185
|
+
}
|
|
186
|
+
/** Query params for `getMetricSeries`. */
|
|
187
|
+
export interface MetricSeriesParams {
|
|
188
|
+
/** Look-back window in seconds (server clamps to <= 14 days). */
|
|
189
|
+
rangeSeconds?: number;
|
|
190
|
+
/** Aggregation bucket in seconds (server clamps to [60, 86400]). */
|
|
191
|
+
periodSeconds?: number;
|
|
192
|
+
}
|
|
193
|
+
/** Query params for `listTraces`. */
|
|
194
|
+
export interface ListTracesParams {
|
|
195
|
+
/** Filter by the seer.job_id span annotation. */
|
|
196
|
+
jobId?: string;
|
|
197
|
+
/** Filter by the seer.video_id span annotation. */
|
|
198
|
+
videoId?: string;
|
|
199
|
+
/** Look-back window in seconds (server clamps to <= 6 hours). */
|
|
200
|
+
rangeSeconds?: number;
|
|
201
|
+
}
|
|
124
202
|
/**
|
|
125
203
|
* Safety cap on `listAllEvalRuns` pagination. A misbehaving server that always
|
|
126
204
|
* returns a non-null `nextCursor` would otherwise loop forever; 50 pages at the
|
|
@@ -197,4 +275,49 @@ export declare class AdminClient {
|
|
|
197
275
|
signal?: AbortSignal;
|
|
198
276
|
}): Promise<AllEvalRunsResult>;
|
|
199
277
|
}
|
|
278
|
+
/**
|
|
279
|
+
* Client for the C4 Phase-3 admin monitoring tools (read-only).
|
|
280
|
+
*
|
|
281
|
+
* Wraps the four `require_admin`-gated `/api/v1/admin/monitoring/*` read proxies
|
|
282
|
+
* over CloudWatch (GetMetricData) + X-Ray (GetTraceSummaries / BatchGetTraces).
|
|
283
|
+
* Like {@link AdminClient}, it targets the CHAT API base (the router is mounted
|
|
284
|
+
* in `api/chat/app.py`) and carries the Descope session token. Additive — it
|
|
285
|
+
* does NOT touch the public `ApiClient` surface. A metric is selected by its
|
|
286
|
+
* allowlist `metricId` (from {@link listMetrics}); there is no raw
|
|
287
|
+
* namespace/metric-name pass-through.
|
|
288
|
+
*/
|
|
289
|
+
export declare class MonitoringClient {
|
|
290
|
+
private chatBaseUrl;
|
|
291
|
+
private sessionToken?;
|
|
292
|
+
constructor(chatBaseUrl: string, sessionToken?: string);
|
|
293
|
+
/** Update the bearer token (e.g. after a Descope session refresh). */
|
|
294
|
+
setSessionToken(token: string | undefined): void;
|
|
295
|
+
/** List the allowlisted metric catalog (what can be charted; no AWS call). */
|
|
296
|
+
listMetrics(options?: {
|
|
297
|
+
signal?: AbortSignal;
|
|
298
|
+
}): Promise<MonitoringMetricCatalogResponse>;
|
|
299
|
+
/**
|
|
300
|
+
* Fetch a CloudWatch series for ONE allowlisted metric over a clamped window.
|
|
301
|
+
* An unknown `metricId` yields a 404 (thrown `Error`); an empty `datapoints`
|
|
302
|
+
* is normal (no data / seam not yet wired).
|
|
303
|
+
*/
|
|
304
|
+
getMetricSeries(metricId: string, params?: MetricSeriesParams, options?: {
|
|
305
|
+
signal?: AbortSignal;
|
|
306
|
+
}): Promise<MonitoringMetricSeriesResponse>;
|
|
307
|
+
/**
|
|
308
|
+
* List recent X-Ray traces, optionally filtered by `jobId` / `videoId` (the
|
|
309
|
+
* `seer.*` span annotations) + window. An empty list is normal until more
|
|
310
|
+
* seams are instrumented. A malformed id (quotes/whitespace) yields a 422.
|
|
311
|
+
*/
|
|
312
|
+
listTraces(params?: ListTracesParams, options?: {
|
|
313
|
+
signal?: AbortSignal;
|
|
314
|
+
}): Promise<MonitoringTraceSummariesResponse>;
|
|
315
|
+
/**
|
|
316
|
+
* Fetch the full segment documents for ONE X-Ray trace (for the waterfall
|
|
317
|
+
* view). `found=false` (with empty `segments`) when X-Ray has no such trace.
|
|
318
|
+
*/
|
|
319
|
+
getTraceDetail(xrayTraceId: string, options?: {
|
|
320
|
+
signal?: AbortSignal;
|
|
321
|
+
}): Promise<MonitoringTraceDetailResponse>;
|
|
322
|
+
}
|
|
200
323
|
//# sourceMappingURL=admin.d.ts.map
|
package/dist/admin.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin.d.ts","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,6EAA6E;AAC7E,MAAM,MAAM,mBAAmB,GAAG,IAAI,GAAG,MAAM,CAAC;AAEhD,gFAAgF;AAChF,MAAM,WAAW,oBAAoB;IACnC,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,mBAAmB,CAAC;IAC5B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,gDAAgD;AAChD,MAAM,WAAW,0BAA0B;IACzC,OAAO,EAAE,oBAAoB,EAAE,CAAC;IAChC,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,kFAAkF;AAClF,MAAM,WAAW,mBAAmB;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,mBAAmB,CAAC;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,SAAS,EAAE,MAAM,GA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;GAUG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,YAAY,CAAC,CAAS;gBAElB,WAAW,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM;IAKtD,sEAAsE;IACtE,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;IAIhD,8EAA8E;IACxE,WAAW,CACf,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAO,GACrC,OAAO,CAAC,+BAA+B,CAAC;IAS3C;;;;OAIG;IACG,eAAe,CACnB,QAAQ,EAAE,MAAM,EAChB,MAAM,GAAE,kBAAuB,EAC/B,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAO,GACrC,OAAO,CAAC,8BAA8B,CAAC;IAmB1C;;;;OAIG;IACG,UAAU,CACd,MAAM,GAAE,gBAAqB,EAC7B,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAO,GACrC,OAAO,CAAC,gCAAgC,CAAC;IAsB5C;;;OAGG;IACG,cAAc,CAClB,WAAW,EAAE,MAAM,EACnB,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAO,GACrC,OAAO,CAAC,6BAA6B,CAAC;CAQ1C"}
|
package/dist/admin.js
CHANGED
|
@@ -12,6 +12,7 @@ import { requestJson } from './http.js';
|
|
|
12
12
|
const ADMIN_PROMPTS_PATH = '/api/v1/admin/prompts';
|
|
13
13
|
const ADMIN_EVAL_RUNS_PATH = '/api/v1/admin/eval-runs';
|
|
14
14
|
const ADMIN_REGEN_PROMPTS_PATH = '/api/v1/admin/regen-prompts';
|
|
15
|
+
const ADMIN_MONITORING_PATH = '/api/v1/admin/monitoring';
|
|
15
16
|
/**
|
|
16
17
|
* Safety cap on `listAllEvalRuns` pagination. A misbehaving server that always
|
|
17
18
|
* returns a non-null `nextCursor` would otherwise loop forever; 50 pages at the
|
|
@@ -121,4 +122,77 @@ export class AdminClient {
|
|
|
121
122
|
return { runs, truncated: true };
|
|
122
123
|
}
|
|
123
124
|
}
|
|
125
|
+
/**
|
|
126
|
+
* Client for the C4 Phase-3 admin monitoring tools (read-only).
|
|
127
|
+
*
|
|
128
|
+
* Wraps the four `require_admin`-gated `/api/v1/admin/monitoring/*` read proxies
|
|
129
|
+
* over CloudWatch (GetMetricData) + X-Ray (GetTraceSummaries / BatchGetTraces).
|
|
130
|
+
* Like {@link AdminClient}, it targets the CHAT API base (the router is mounted
|
|
131
|
+
* in `api/chat/app.py`) and carries the Descope session token. Additive — it
|
|
132
|
+
* does NOT touch the public `ApiClient` surface. A metric is selected by its
|
|
133
|
+
* allowlist `metricId` (from {@link listMetrics}); there is no raw
|
|
134
|
+
* namespace/metric-name pass-through.
|
|
135
|
+
*/
|
|
136
|
+
export class MonitoringClient {
|
|
137
|
+
chatBaseUrl;
|
|
138
|
+
sessionToken;
|
|
139
|
+
constructor(chatBaseUrl, sessionToken) {
|
|
140
|
+
this.chatBaseUrl = chatBaseUrl;
|
|
141
|
+
this.sessionToken = sessionToken;
|
|
142
|
+
}
|
|
143
|
+
/** Update the bearer token (e.g. after a Descope session refresh). */
|
|
144
|
+
setSessionToken(token) {
|
|
145
|
+
this.sessionToken = token;
|
|
146
|
+
}
|
|
147
|
+
/** List the allowlisted metric catalog (what can be charted; no AWS call). */
|
|
148
|
+
async listMetrics(options = {}) {
|
|
149
|
+
return requestJson(this.chatBaseUrl, `${ADMIN_MONITORING_PATH}/metrics`, this.sessionToken, { signal: options.signal });
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Fetch a CloudWatch series for ONE allowlisted metric over a clamped window.
|
|
153
|
+
* An unknown `metricId` yields a 404 (thrown `Error`); an empty `datapoints`
|
|
154
|
+
* is normal (no data / seam not yet wired).
|
|
155
|
+
*/
|
|
156
|
+
async getMetricSeries(metricId, params = {}, options = {}) {
|
|
157
|
+
const search = new URLSearchParams();
|
|
158
|
+
if (params.rangeSeconds !== undefined) {
|
|
159
|
+
search.set('rangeSeconds', String(params.rangeSeconds));
|
|
160
|
+
}
|
|
161
|
+
if (params.periodSeconds !== undefined) {
|
|
162
|
+
search.set('periodSeconds', String(params.periodSeconds));
|
|
163
|
+
}
|
|
164
|
+
const qs = search.toString();
|
|
165
|
+
const base = `${ADMIN_MONITORING_PATH}/metrics/${encodeURIComponent(metricId)}`;
|
|
166
|
+
const path = qs ? `${base}?${qs}` : base;
|
|
167
|
+
return requestJson(this.chatBaseUrl, path, this.sessionToken, { signal: options.signal });
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* List recent X-Ray traces, optionally filtered by `jobId` / `videoId` (the
|
|
171
|
+
* `seer.*` span annotations) + window. An empty list is normal until more
|
|
172
|
+
* seams are instrumented. A malformed id (quotes/whitespace) yields a 422.
|
|
173
|
+
*/
|
|
174
|
+
async listTraces(params = {}, options = {}) {
|
|
175
|
+
const search = new URLSearchParams();
|
|
176
|
+
if (params.jobId !== undefined) {
|
|
177
|
+
search.set('jobId', params.jobId);
|
|
178
|
+
}
|
|
179
|
+
if (params.videoId !== undefined) {
|
|
180
|
+
search.set('videoId', params.videoId);
|
|
181
|
+
}
|
|
182
|
+
if (params.rangeSeconds !== undefined) {
|
|
183
|
+
search.set('rangeSeconds', String(params.rangeSeconds));
|
|
184
|
+
}
|
|
185
|
+
const qs = search.toString();
|
|
186
|
+
const base = `${ADMIN_MONITORING_PATH}/traces`;
|
|
187
|
+
const path = qs ? `${base}?${qs}` : base;
|
|
188
|
+
return requestJson(this.chatBaseUrl, path, this.sessionToken, { signal: options.signal });
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Fetch the full segment documents for ONE X-Ray trace (for the waterfall
|
|
192
|
+
* view). `found=false` (with empty `segments`) when X-Ray has no such trace.
|
|
193
|
+
*/
|
|
194
|
+
async getTraceDetail(xrayTraceId, options = {}) {
|
|
195
|
+
return requestJson(this.chatBaseUrl, `${ADMIN_MONITORING_PATH}/traces/${encodeURIComponent(xrayTraceId)}`, this.sessionToken, { signal: options.signal });
|
|
196
|
+
}
|
|
197
|
+
}
|
|
124
198
|
//# sourceMappingURL=admin.js.map
|
package/dist/admin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin.js","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"admin.js","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AA4NrC,MAAM,kBAAkB,GAAG,uBAAuB,CAAC;AACnD,MAAM,oBAAoB,GAAG,yBAAyB,CAAC;AACvD,MAAM,wBAAwB,GAAG,6BAA6B,CAAC;AAC/D,MAAM,qBAAqB,GAAG,0BAA0B,CAAC;AAEzD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAErC;;;;;;;;GAQG;AACH,MAAM,OAAO,WAAW;IACd,WAAW,CAAS;IACpB,YAAY,CAAU;IAE9B,YAAY,WAAmB,EAAE,YAAqB;QACpD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACnC,CAAC;IAED,sEAAsE;IACtE,eAAe,CAAC,KAAyB;QACvC,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;IAC5B,CAAC;IAED,iFAAiF;IACjF,KAAK,CAAC,kBAAkB,CACtB,UAAoC,EAAE;QAEtC,OAAO,WAAW,CAChB,IAAI,CAAC,WAAW,EAChB,kBAAkB,EAClB,IAAI,CAAC,YAAY,EACjB,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAC3B,CAAC;IACJ,CAAC;IAED,+EAA+E;IAC/E,KAAK,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