@escapeaihq/client-core 0.8.0 → 0.42.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 +48 -4
- package/dist/adapters/capabilities.d.ts +10 -0
- package/dist/adapters/capabilities.d.ts.map +1 -0
- package/dist/adapters/capabilities.js +2 -0
- package/dist/adapters/capabilities.js.map +1 -0
- package/dist/adapters/chatAdapter.d.ts +38 -0
- package/dist/adapters/chatAdapter.d.ts.map +1 -0
- package/dist/adapters/chatAdapter.js +88 -0
- package/dist/adapters/chatAdapter.js.map +1 -0
- package/dist/adapters/directorAdapter.d.ts +62 -0
- package/dist/adapters/directorAdapter.d.ts.map +1 -0
- package/dist/adapters/directorAdapter.js +71 -0
- package/dist/adapters/directorAdapter.js.map +1 -0
- package/dist/adapters/imageAdapter.d.ts +44 -0
- package/dist/adapters/imageAdapter.d.ts.map +1 -0
- package/dist/adapters/imageAdapter.js +73 -0
- package/dist/adapters/imageAdapter.js.map +1 -0
- package/dist/adapters/index.d.ts +47 -0
- package/dist/adapters/index.d.ts.map +1 -0
- package/dist/adapters/index.js +41 -0
- package/dist/adapters/index.js.map +1 -0
- package/dist/adapters/registry.d.ts +98 -0
- package/dist/adapters/registry.d.ts.map +1 -0
- package/dist/adapters/registry.js +106 -0
- package/dist/adapters/registry.js.map +1 -0
- package/dist/adapters/worldAdapter.d.ts +142 -0
- package/dist/adapters/worldAdapter.d.ts.map +1 -0
- package/dist/adapters/worldAdapter.js +164 -0
- package/dist/adapters/worldAdapter.js.map +1 -0
- package/dist/admin.d.ts +200 -0
- package/dist/admin.d.ts.map +1 -0
- package/dist/admin.js +124 -0
- package/dist/admin.js.map +1 -0
- package/dist/api.d.ts +1299 -3
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +683 -95
- package/dist/api.js.map +1 -1
- package/dist/audio.d.ts +33 -1
- package/dist/audio.d.ts.map +1 -1
- package/dist/audio.js +4 -1
- package/dist/audio.js.map +1 -1
- package/dist/castProjection.d.ts +35 -0
- package/dist/castProjection.d.ts.map +1 -0
- package/dist/castProjection.js +80 -0
- package/dist/castProjection.js.map +1 -0
- package/dist/conversation/binding.d.ts +62 -0
- package/dist/conversation/binding.d.ts.map +1 -0
- package/dist/conversation/binding.js +51 -0
- package/dist/conversation/binding.js.map +1 -0
- package/dist/conversation/controller.d.ts +209 -0
- package/dist/conversation/controller.d.ts.map +1 -0
- package/dist/conversation/controller.js +342 -0
- package/dist/conversation/controller.js.map +1 -0
- package/dist/conversation/effectiveModel.d.ts +62 -0
- package/dist/conversation/effectiveModel.d.ts.map +1 -0
- package/dist/conversation/effectiveModel.js +73 -0
- package/dist/conversation/effectiveModel.js.map +1 -0
- package/dist/conversation/index.d.ts +27 -0
- package/dist/conversation/index.d.ts.map +1 -0
- package/dist/conversation/index.js +27 -0
- package/dist/conversation/index.js.map +1 -0
- package/dist/conversation/participant.d.ts +66 -0
- package/dist/conversation/participant.d.ts.map +1 -0
- package/dist/conversation/participant.js +36 -0
- package/dist/conversation/participant.js.map +1 -0
- package/dist/conversation/presence.d.ts +56 -0
- package/dist/conversation/presence.d.ts.map +1 -0
- package/dist/conversation/presence.js +34 -0
- package/dist/conversation/presence.js.map +1 -0
- package/dist/conversation/presenceBus.d.ts +42 -0
- package/dist/conversation/presenceBus.d.ts.map +1 -0
- package/dist/conversation/presenceBus.js +81 -0
- package/dist/conversation/presenceBus.js.map +1 -0
- package/dist/conversation/presenceRegistry.d.ts +49 -0
- package/dist/conversation/presenceRegistry.d.ts.map +1 -0
- package/dist/conversation/presenceRegistry.js +59 -0
- package/dist/conversation/presenceRegistry.js.map +1 -0
- package/dist/conversation/roster.d.ts +72 -0
- package/dist/conversation/roster.d.ts.map +1 -0
- package/dist/conversation/roster.js +69 -0
- package/dist/conversation/roster.js.map +1 -0
- package/dist/conversation/rosterProjection.d.ts +52 -0
- package/dist/conversation/rosterProjection.d.ts.map +1 -0
- package/dist/conversation/rosterProjection.js +74 -0
- package/dist/conversation/rosterProjection.js.map +1 -0
- package/dist/conversation/router.d.ts +74 -0
- package/dist/conversation/router.d.ts.map +1 -0
- package/dist/conversation/router.js +58 -0
- package/dist/conversation/router.js.map +1 -0
- package/dist/conversation/runtime.d.ts +64 -0
- package/dist/conversation/runtime.d.ts.map +1 -0
- package/dist/conversation/runtime.js +172 -0
- package/dist/conversation/runtime.js.map +1 -0
- package/dist/conversation/types.d.ts +99 -0
- package/dist/conversation/types.d.ts.map +1 -0
- package/dist/conversation/types.js +13 -0
- package/dist/conversation/types.js.map +1 -0
- package/dist/conversation/voice.d.ts +185 -0
- package/dist/conversation/voice.d.ts.map +1 -0
- package/dist/conversation/voice.js +307 -0
- package/dist/conversation/voice.js.map +1 -0
- package/dist/graphSchema.d.ts +260 -0
- package/dist/graphSchema.d.ts.map +1 -0
- package/dist/graphSchema.js +354 -0
- package/dist/graphSchema.js.map +1 -0
- package/dist/http.d.ts +20 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +57 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -1
- package/dist/platformAssistant.d.ts +155 -0
- package/dist/platformAssistant.d.ts.map +1 -0
- package/dist/platformAssistant.js +256 -0
- package/dist/platformAssistant.js.map +1 -0
- package/dist/reactor/abortUtils.d.ts +16 -0
- package/dist/reactor/abortUtils.d.ts.map +1 -0
- package/dist/reactor/abortUtils.js +26 -0
- package/dist/reactor/abortUtils.js.map +1 -0
- package/dist/reactor/applyScenePrompt.d.ts +75 -0
- package/dist/reactor/applyScenePrompt.d.ts.map +1 -0
- package/dist/reactor/applyScenePrompt.js +60 -0
- package/dist/reactor/applyScenePrompt.js.map +1 -0
- package/dist/reactor/chunkDistribution.d.ts +43 -0
- package/dist/reactor/chunkDistribution.d.ts.map +1 -0
- package/dist/reactor/chunkDistribution.js +85 -0
- package/dist/reactor/chunkDistribution.js.map +1 -0
- package/dist/reactor/heliosCommandDispatcher.d.ts.map +1 -1
- package/dist/reactor/heliosCommandDispatcher.js +10 -15
- package/dist/reactor/heliosCommandDispatcher.js.map +1 -1
- package/dist/reactor/index.d.ts +4 -0
- package/dist/reactor/index.d.ts.map +1 -1
- package/dist/reactor/index.js +7 -0
- package/dist/reactor/index.js.map +1 -1
- package/dist/reactor/longLiveCommandDispatcher.d.ts +103 -0
- package/dist/reactor/longLiveCommandDispatcher.d.ts.map +1 -0
- package/dist/reactor/longLiveCommandDispatcher.js +87 -0
- package/dist/reactor/longLiveCommandDispatcher.js.map +1 -0
- package/dist/reactor/sceneEntry.d.ts +40 -6
- package/dist/reactor/sceneEntry.d.ts.map +1 -1
- package/dist/reactor/sceneEntry.js +63 -24
- package/dist/reactor/sceneEntry.js.map +1 -1
- package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -1
- package/dist/reactor/scenesFromEnrichment.js +2 -66
- package/dist/reactor/scenesFromEnrichment.js.map +1 -1
- package/dist/reactor/seedImageOrchestrator.d.ts +42 -2
- package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
- package/dist/reactor/seedImageOrchestrator.js +173 -4
- package/dist/reactor/seedImageOrchestrator.js.map +1 -1
- package/dist/reactor/storyTimeline.d.ts +44 -0
- package/dist/reactor/storyTimeline.d.ts.map +1 -0
- package/dist/reactor/storyTimeline.js +95 -0
- package/dist/reactor/storyTimeline.js.map +1 -0
- package/dist/storyGraph.d.ts +70 -0
- package/dist/storyGraph.d.ts.map +1 -0
- package/dist/storyGraph.js +178 -0
- package/dist/storyGraph.js.map +1 -0
- package/dist/timeFormat.d.ts +10 -0
- package/dist/timeFormat.d.ts.map +1 -1
- package/dist/timeFormat.js +12 -0
- package/dist/timeFormat.js.map +1 -1
- package/dist/toolSchemas.d.ts +370 -0
- package/dist/toolSchemas.d.ts.map +1 -0
- package/dist/toolSchemas.js +182 -0
- package/dist/toolSchemas.js.map +1 -0
- package/dist/vision/VisionPublisher.d.ts +115 -0
- package/dist/vision/VisionPublisher.d.ts.map +1 -0
- package/dist/vision/VisionPublisher.js +475 -0
- package/dist/vision/VisionPublisher.js.map +1 -0
- package/dist/vision/VisionSourceController.d.ts +127 -0
- package/dist/vision/VisionSourceController.d.ts.map +1 -0
- package/dist/vision/VisionSourceController.js +284 -0
- package/dist/vision/VisionSourceController.js.map +1 -0
- package/dist/vision/credentials.d.ts +22 -0
- package/dist/vision/credentials.d.ts.map +1 -0
- package/dist/vision/credentials.js +34 -0
- package/dist/vision/credentials.js.map +1 -0
- package/dist/vision/index.d.ts +18 -0
- package/dist/vision/index.d.ts.map +1 -0
- package/dist/vision/index.js +13 -0
- package/dist/vision/index.js.map +1 -0
- package/dist/vision/sourceKinds.d.ts +65 -0
- package/dist/vision/sourceKinds.d.ts.map +1 -0
- package/dist/vision/sourceKinds.js +26 -0
- package/dist/vision/sourceKinds.js.map +1 -0
- package/dist/vision/startVisionPublisher.d.ts +38 -0
- package/dist/vision/startVisionPublisher.d.ts.map +1 -0
- package/dist/vision/startVisionPublisher.js +44 -0
- package/dist/vision/startVisionPublisher.js.map +1 -0
- package/dist/vision/types.d.ts +95 -0
- package/dist/vision/types.d.ts.map +1 -0
- package/dist/vision/types.js +12 -0
- package/dist/vision/types.js.map +1 -0
- package/dist/vision/visionScheduler.d.ts +63 -0
- package/dist/vision/visionScheduler.d.ts.map +1 -0
- package/dist/vision/visionScheduler.js +67 -0
- package/dist/vision/visionScheduler.js.map +1 -0
- package/dist/websocket.d.ts +195 -0
- package/dist/websocket.d.ts.map +1 -1
- package/dist/websocket.js +179 -1
- package/dist/websocket.js.map +1 -1
- package/package.json +11 -1
- package/src/__tests__/adapters-capabilities.test.ts +46 -0
- package/src/__tests__/adapters-chat.test.ts +172 -0
- package/src/__tests__/adapters-director.test.ts +95 -0
- package/src/__tests__/adapters-image.test.ts +133 -0
- package/src/__tests__/adapters-platform.test.ts +95 -0
- package/src/__tests__/adapters-registry.test.ts +189 -0
- package/src/__tests__/adapters-world.test.ts +296 -0
- package/src/__tests__/admin.test.ts +312 -0
- package/src/__tests__/adventures-party.test.ts +219 -0
- package/src/__tests__/adventures.test.ts +282 -0
- package/src/__tests__/api-pollers.test.ts +104 -0
- package/src/__tests__/api.clip-lookup.test.ts +64 -0
- package/src/__tests__/api.list-images-filters.test.ts +103 -0
- package/src/__tests__/api.test.ts +470 -0
- package/src/__tests__/audio.test.ts +65 -0
- package/src/__tests__/cast.test.ts +95 -0
- package/src/__tests__/castProjection.test.ts +167 -0
- package/src/__tests__/chat-auth.test.ts +91 -0
- package/src/__tests__/conversation/controller.test.ts +697 -0
- package/src/__tests__/conversation/effectiveModel.test.ts +169 -0
- package/src/__tests__/conversation/headlessRenderer.ts +46 -0
- package/src/__tests__/conversation/presenceBus.test.ts +236 -0
- package/src/__tests__/conversation/presenceRegistry.test.ts +73 -0
- package/src/__tests__/conversation/roster.test.ts +100 -0
- package/src/__tests__/conversation/rosterProjection.test.ts +142 -0
- package/src/__tests__/conversation/router.test.ts +81 -0
- package/src/__tests__/conversation/runtime.test.ts +206 -0
- package/src/__tests__/conversation/voice.test.ts +440 -0
- package/src/__tests__/documents.test.ts +360 -0
- package/src/__tests__/graphSchema.test.ts +326 -0
- package/src/__tests__/longLiveCommandDispatcher.test.ts +185 -0
- package/src/__tests__/platformAssistant.test.ts +484 -0
- package/src/__tests__/reactor/applyScenePrompt.test.ts +192 -0
- package/src/__tests__/reactor/heliosCommandDispatcher.test.ts +4 -3
- package/src/__tests__/reactor/sceneEntry.test.ts +134 -10
- package/src/__tests__/reactor/seedImageOrchestrator.test.ts +51 -16
- package/src/__tests__/reactor/storyTimeline.test.ts +186 -0
- package/src/__tests__/regeneration.test.ts +486 -0
- package/src/__tests__/stories.test.ts +171 -0
- package/src/__tests__/storyGraph.test.ts +134 -0
- package/src/__tests__/timeFormat.test.ts +22 -1
- package/src/__tests__/toolSchemas.test.ts +57 -0
- package/src/__tests__/tools-wrappers.test.ts +272 -0
- package/src/__tests__/videoGraph.test.ts +94 -0
- package/src/__tests__/websocket-vision.test.ts +265 -0
- package/src/__tests__/websocket.test.ts +213 -0
- package/src/adapters/capabilities.ts +24 -0
- package/src/adapters/chatAdapter.ts +114 -0
- package/src/adapters/directorAdapter.ts +126 -0
- package/src/adapters/imageAdapter.ts +100 -0
- package/src/adapters/index.ts +67 -0
- package/src/adapters/registry.ts +159 -0
- package/src/adapters/worldAdapter.ts +272 -0
- package/src/admin.ts +310 -0
- package/src/api.ts +1890 -162
- package/src/audio.ts +35 -0
- package/src/castProjection.ts +95 -0
- package/src/conversation/binding.ts +81 -0
- package/src/conversation/controller.ts +439 -0
- package/src/conversation/effectiveModel.ts +111 -0
- package/src/conversation/index.ts +27 -0
- package/src/conversation/participant.ts +71 -0
- package/src/conversation/presence.ts +60 -0
- package/src/conversation/presenceBus.ts +109 -0
- package/src/conversation/presenceRegistry.ts +83 -0
- package/src/conversation/roster.ts +111 -0
- package/src/conversation/rosterProjection.ts +98 -0
- package/src/conversation/router.ts +96 -0
- package/src/conversation/runtime.ts +188 -0
- package/src/conversation/types.ts +100 -0
- package/src/conversation/voice.ts +402 -0
- package/src/graphSchema.ts +532 -0
- package/src/http.ts +72 -0
- package/src/index.ts +12 -0
- package/src/platformAssistant.ts +347 -0
- package/src/reactor/abortUtils.ts +22 -0
- package/src/reactor/applyScenePrompt.ts +136 -0
- package/src/reactor/chunkDistribution.ts +98 -0
- package/src/reactor/heliosCommandDispatcher.ts +10 -18
- package/src/reactor/index.ts +7 -0
- package/src/reactor/longLiveCommandDispatcher.ts +156 -0
- package/src/reactor/sceneEntry.ts +104 -33
- package/src/reactor/scenesFromEnrichment.ts +11 -76
- package/src/reactor/seedImageOrchestrator.ts +200 -4
- package/src/reactor/storyTimeline.ts +127 -0
- package/src/storyGraph.ts +298 -0
- package/src/timeFormat.ts +13 -0
- package/src/toolSchemas.ts +225 -0
- package/src/vision/VisionPublisher.ts +553 -0
- package/src/vision/VisionSourceController.ts +354 -0
- package/src/vision/__tests__/VisionPublisher.kvs.test.ts +244 -0
- package/src/vision/__tests__/VisionPublisher.test.ts +301 -0
- package/src/vision/__tests__/VisionSourceController.test.ts +719 -0
- package/src/vision/__tests__/startVisionPublisher.test.ts +251 -0
- package/src/vision/__tests__/toVisionRtcCredentials.test.ts +113 -0
- package/src/vision/__tests__/visionScheduler.test.ts +149 -0
- package/src/vision/credentials.ts +39 -0
- package/src/vision/index.ts +44 -0
- package/src/vision/sourceKinds.ts +75 -0
- package/src/vision/startVisionPublisher.ts +64 -0
- package/src/vision/types.ts +101 -0
- package/src/vision/visionScheduler.ts +102 -0
- package/src/websocket.ts +334 -4
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Headless Platform Assistant controller (R4c).
|
|
3
|
+
*
|
|
4
|
+
* The framework-agnostic owner of a Platform Assistant conversation: it holds
|
|
5
|
+
* the running message list + the current `routeContext`, calls
|
|
6
|
+
* `ApiClient.streamAssistant`, parses the returned SSE event stream, and fans
|
|
7
|
+
* the decoded `AssistantStreamEvent` variants out to host-provided callbacks.
|
|
8
|
+
* It has ZERO framework imports — React (R4c web overlay), Vue, and PlayCanvas
|
|
9
|
+
* all drive this same controller (mirrors the R2.1 `ConversationController`
|
|
10
|
+
* decoupling mandate). A test reads this source and asserts no UI-framework
|
|
11
|
+
* import.
|
|
12
|
+
*
|
|
13
|
+
* It does NOT re-implement transport or the SSE wire: it delegates the fetch +
|
|
14
|
+
* body-reader to `ApiClient.streamAssistant` (the single SSE plumbing shared
|
|
15
|
+
* with `streamChat`) and decodes each `data: {…}\n\n` frame exactly the way the
|
|
16
|
+
* existing chat consumer does (TextDecoder streaming + line buffering +
|
|
17
|
+
* `[DONE]` terminator) — no second decoder.
|
|
18
|
+
*
|
|
19
|
+
* It performs NO mutation: a `suggestion` event is surfaced verbatim to
|
|
20
|
+
* `onSuggestion`; the HOST page that owns the form decides whether to apply it.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type {
|
|
24
|
+
ApiClient,
|
|
25
|
+
AssistantRouteContext,
|
|
26
|
+
AssistantStreamEvent,
|
|
27
|
+
ChatMessage,
|
|
28
|
+
} from './api';
|
|
29
|
+
|
|
30
|
+
/** Conversation roles the assistant history carries (derived from the single
|
|
31
|
+
* source of truth — `ChatMessage['role']` — so it cannot drift). */
|
|
32
|
+
type AssistantMessageRole = ChatMessage['role'];
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A `propose_form_fields` suggestion surfaced to the host. Mirrors the
|
|
36
|
+
* `suggestion` variant of `AssistantStreamEvent` (the wire contract shared with
|
|
37
|
+
* `api/assistant`), re-exported as a named type so the host overlay imports it
|
|
38
|
+
* verbatim rather than re-deriving the `Extract<…>`.
|
|
39
|
+
*/
|
|
40
|
+
export interface PlatformAssistantSuggestion {
|
|
41
|
+
/** The target form id the proposed fields belong to (e.g. `persona`). */
|
|
42
|
+
targetForm: string;
|
|
43
|
+
/** The proposed `{ fieldName: value }` map the host reviews + applies. */
|
|
44
|
+
fields: Record<string, string>;
|
|
45
|
+
/** Optional human-readable rationale for the proposal. */
|
|
46
|
+
rationale?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Host callbacks the controller invokes as the corresponding
|
|
51
|
+
* `AssistantStreamEvent` variants arrive. All optional — a host wires only the
|
|
52
|
+
* variants it renders. `token` -> onTextDelta, `suggestion` -> onSuggestion,
|
|
53
|
+
* `error` -> onError, `done` -> onDone. The `tool_use` / `tool_result` /
|
|
54
|
+
* `citation` variants are intentionally not surfaced (minimal assistant
|
|
55
|
+
* surface); a future PR can add callbacks for them additively.
|
|
56
|
+
*/
|
|
57
|
+
export interface PlatformAssistantCallbacks {
|
|
58
|
+
/** A streamed answer token (append to the in-flight assistant message). */
|
|
59
|
+
onTextDelta?: (text: string) => void;
|
|
60
|
+
/** A `propose_form_fields` suggestion the host maps onto its own form. */
|
|
61
|
+
onSuggestion?: (suggestion: PlatformAssistantSuggestion) => void;
|
|
62
|
+
/** A streamed error message (the turn failed server-side). */
|
|
63
|
+
onError?: (message: string) => void;
|
|
64
|
+
/**
|
|
65
|
+
* The turn ended. Fires once whenever the stream CLOSES — a `done`/`[DONE]`
|
|
66
|
+
* terminator, a self-abort, OR the connection simply dropping. So for a
|
|
67
|
+
* server-side SSE `error` frame, BOTH onError and onDone fire (error surfaced,
|
|
68
|
+
* then the stream closed); for a TRANSPORT error (the request itself throws)
|
|
69
|
+
* only onError fires. Treat onDone as "stop showing the spinner", not "success".
|
|
70
|
+
*/
|
|
71
|
+
onDone?: () => void;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface PlatformAssistantControllerOptions {
|
|
75
|
+
/** The client-core API client whose `streamAssistant` the controller drives. */
|
|
76
|
+
apiClient: Pick<ApiClient, 'streamAssistant'>;
|
|
77
|
+
/** The route the assistant is summoned on (scopes its suggestions). */
|
|
78
|
+
routeContext: AssistantRouteContext;
|
|
79
|
+
/** Host callbacks for the streamed events. */
|
|
80
|
+
callbacks: PlatformAssistantCallbacks;
|
|
81
|
+
/**
|
|
82
|
+
* Optional explicit model pin. Omitted = the server resolves the model via
|
|
83
|
+
* the same `resolve_model_id` -> `shared/model_router.py` seam the chat uses.
|
|
84
|
+
*/
|
|
85
|
+
modelId?: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Per-turn options for {@link PlatformAssistantController.ask} (R11.2). Optional
|
|
90
|
+
* + additive — `ask(prompt)` is unchanged. `documentContext` carries a large
|
|
91
|
+
* "operate on this document" draft (e.g. a long prompt to refine) that the
|
|
92
|
+
* server places in MODEL CONTEXT, never the user turn, so the small `prompt`
|
|
93
|
+
* cap keeps its prompt-injection floor.
|
|
94
|
+
*/
|
|
95
|
+
export interface PlatformAssistantAskOptions {
|
|
96
|
+
/** A large document/draft for the assistant to operate ON (model context). */
|
|
97
|
+
documentContext?: string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const ROLE_USER: AssistantMessageRole = 'user';
|
|
101
|
+
const ROLE_ASSISTANT: AssistantMessageRole = 'assistant';
|
|
102
|
+
|
|
103
|
+
/** SSE `data:` line prefix + the stream terminator sentinel. */
|
|
104
|
+
const SSE_DATA_PREFIX = 'data: ';
|
|
105
|
+
const SSE_DONE_SENTINEL = '[DONE]';
|
|
106
|
+
|
|
107
|
+
export class PlatformAssistantController {
|
|
108
|
+
private readonly apiClient: Pick<ApiClient, 'streamAssistant'>;
|
|
109
|
+
private readonly callbacks: PlatformAssistantCallbacks;
|
|
110
|
+
private readonly modelId?: string;
|
|
111
|
+
private routeContext: AssistantRouteContext;
|
|
112
|
+
/** The running conversation history threaded into each `ask`. */
|
|
113
|
+
private messages: ChatMessage[] = [];
|
|
114
|
+
/** Abort controller for the in-flight `ask` stream (so `abort()` cancels it). */
|
|
115
|
+
private inflight: AbortController | undefined;
|
|
116
|
+
/** Set by `dispose()` — guards against driving a new stream after teardown. */
|
|
117
|
+
private disposed = false;
|
|
118
|
+
|
|
119
|
+
constructor(opts: PlatformAssistantControllerOptions) {
|
|
120
|
+
this.apiClient = opts.apiClient;
|
|
121
|
+
this.routeContext = opts.routeContext;
|
|
122
|
+
this.callbacks = opts.callbacks;
|
|
123
|
+
this.modelId = opts.modelId;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Point the assistant at a new surface/form (the host re-binds on navigation). */
|
|
127
|
+
setRouteContext(routeContext: AssistantRouteContext): void {
|
|
128
|
+
this.routeContext = routeContext;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A defensive copy of the running message history (host-render convenience). */
|
|
132
|
+
getMessages(): ChatMessage[] {
|
|
133
|
+
return this.messages.map((m) => ({ ...m }));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Send a user prompt: append it to the history, stream the assistant reply
|
|
138
|
+
* via `ApiClient.streamAssistant` (threading the running history + the current
|
|
139
|
+
* `routeContext`), and fan the decoded events out to the host callbacks. The
|
|
140
|
+
* accumulated assistant text is appended to the history on completion so the
|
|
141
|
+
* NEXT `ask` carries the full transcript.
|
|
142
|
+
*
|
|
143
|
+
* Resolves when the stream completes (or aborts). A single `ask` is allowed
|
|
144
|
+
* in flight at a time — calling `ask` again before the previous resolves
|
|
145
|
+
* aborts the prior stream first (so only one stream owns the callbacks).
|
|
146
|
+
*
|
|
147
|
+
* NEVER rejects: a transport/network error is surfaced via the `onError`
|
|
148
|
+
* callback (the same channel as SSE `error` frames) and a self-abort resolves
|
|
149
|
+
* silently — so framework-agnostic callers need not wrap `ask` in try/catch.
|
|
150
|
+
*
|
|
151
|
+
* `options.documentContext` (R11.2, optional) threads a large draft into the
|
|
152
|
+
* request's `documentContext` field — the server places it in model context,
|
|
153
|
+
* not the user turn. Omitted ⇒ the request carries no `documentContext`
|
|
154
|
+
* (byte-identical to the pre-R11.2 wire payload).
|
|
155
|
+
*/
|
|
156
|
+
async ask(prompt: string, options?: PlatformAssistantAskOptions): Promise<void> {
|
|
157
|
+
if (this.disposed) {
|
|
158
|
+
// Disposed is NOT thrown — honor the "never rejects" contract (a
|
|
159
|
+
// navigation may dispose() while a queued ask() is still pending). Surface
|
|
160
|
+
// it through onError so a framework-agnostic caller need not try/catch.
|
|
161
|
+
this.callbacks.onError?.('PlatformAssistantController: ask() after dispose().');
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
// Abort any prior in-flight stream so only one stream drives the callbacks.
|
|
165
|
+
this.abort();
|
|
166
|
+
|
|
167
|
+
// The prior COMMITTED history threads into the request. The new user turn is
|
|
168
|
+
// NOT pushed yet — it commits (paired with the assistant reply) only once the
|
|
169
|
+
// stream produces a reply (see the finally), so a re-entrant ask() that
|
|
170
|
+
// aborts this one before any reply never leaves a dangling user turn.
|
|
171
|
+
const priorMessages = this.getMessages();
|
|
172
|
+
|
|
173
|
+
const abortController = new AbortController();
|
|
174
|
+
this.inflight = abortController;
|
|
175
|
+
|
|
176
|
+
let assistantText = '';
|
|
177
|
+
try {
|
|
178
|
+
const reader = await this.apiClient.streamAssistant(
|
|
179
|
+
{
|
|
180
|
+
prompt,
|
|
181
|
+
messages: priorMessages,
|
|
182
|
+
routeContext: this.routeContext,
|
|
183
|
+
...(this.modelId ? { modelId: this.modelId } : {}),
|
|
184
|
+
// R11.2 — only include documentContext when a non-empty draft is
|
|
185
|
+
// supplied, so a plain ask() emits a wire payload byte-identical to
|
|
186
|
+
// the pre-R11.2 one (no `documentContext` key at all).
|
|
187
|
+
...(options?.documentContext
|
|
188
|
+
? { documentContext: options.documentContext }
|
|
189
|
+
: {}),
|
|
190
|
+
},
|
|
191
|
+
abortController.signal,
|
|
192
|
+
);
|
|
193
|
+
assistantText = await this.consume(reader);
|
|
194
|
+
} catch (err) {
|
|
195
|
+
// A self-abort (a re-entrant ask(), dispose(), or an explicit abort() —
|
|
196
|
+
// e.g. a future Cancel button) is a clean cancel, NOT an error: fire onDone
|
|
197
|
+
// so the turn ends and a host relying on it to flip "streaming" off isn't
|
|
198
|
+
// left stuck (when the reader THROWS AbortError, the terminal onDone below
|
|
199
|
+
// is skipped). Any other error (transport/network) surfaces through onError
|
|
200
|
+
// — the SAME channel SSE `error` frames use, so a consumer has ONE error
|
|
201
|
+
// channel and ask() NEVER rejects (the framework-agnostic seam: a
|
|
202
|
+
// Vue/PlayCanvas caller need not wrap ask() in try/catch).
|
|
203
|
+
if (err instanceof Error && err.name === 'AbortError') {
|
|
204
|
+
this.callbacks.onDone?.();
|
|
205
|
+
} else {
|
|
206
|
+
this.callbacks.onError?.(err instanceof Error ? err.message : String(err));
|
|
207
|
+
}
|
|
208
|
+
} finally {
|
|
209
|
+
// Commit the user turn + the assistant reply as a PAIR — but only if the
|
|
210
|
+
// turn produced a reply (a completed or partially-streamed one). An
|
|
211
|
+
// immediately self-aborted turn (empty reply) commits NOTHING, so a
|
|
212
|
+
// re-entrant ask() never leaves a dangling user turn with no assistant
|
|
213
|
+
// response. Then clear the in-flight handle if it is still ours.
|
|
214
|
+
if (assistantText) {
|
|
215
|
+
this.messages.push({ role: ROLE_USER, content: prompt });
|
|
216
|
+
this.messages.push({ role: ROLE_ASSISTANT, content: assistantText });
|
|
217
|
+
}
|
|
218
|
+
if (this.inflight === abortController) {
|
|
219
|
+
this.inflight = undefined;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Abort the in-flight stream (no-op when nothing is streaming). */
|
|
225
|
+
abort(): void {
|
|
226
|
+
this.inflight?.abort();
|
|
227
|
+
this.inflight = undefined;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Tear down: abort any in-flight stream and reject further `ask` calls. */
|
|
231
|
+
dispose(): void {
|
|
232
|
+
this.disposed = true;
|
|
233
|
+
this.abort();
|
|
234
|
+
this.messages = [];
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ── internals ──────────────────────────────────────────────────────────────
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Drain the SSE reader, decoding each `data: {…}\n\n` frame into an
|
|
241
|
+
* `AssistantStreamEvent` and dispatching it to the host callbacks. Returns the
|
|
242
|
+
* concatenated `token` text so the caller can persist the assistant turn.
|
|
243
|
+
*
|
|
244
|
+
* Reuses the EXACT decode discipline the web chat consumer uses (TextDecoder
|
|
245
|
+
* with `{ stream: true }`, line buffering with a trailing-partial carry-over,
|
|
246
|
+
* `data: ` prefix slice, `[DONE]` terminator) — no second SSE decoder.
|
|
247
|
+
*/
|
|
248
|
+
private async consume(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<string> {
|
|
249
|
+
const decoder = new TextDecoder();
|
|
250
|
+
let buffer = '';
|
|
251
|
+
let text = '';
|
|
252
|
+
|
|
253
|
+
try {
|
|
254
|
+
for (;;) {
|
|
255
|
+
const { done, value } = await reader.read();
|
|
256
|
+
if (done) break;
|
|
257
|
+
if (value) buffer += decoder.decode(value, { stream: true });
|
|
258
|
+
|
|
259
|
+
const lines = buffer.split('\n');
|
|
260
|
+
// Keep the trailing partial line in the buffer until its newline arrives.
|
|
261
|
+
buffer = lines.pop() ?? '';
|
|
262
|
+
|
|
263
|
+
// We never break on `done` (the reader closes right after) — the terminal
|
|
264
|
+
// onDone after the loop covers every exit path.
|
|
265
|
+
for (const line of lines) text += this.handleLine(line);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Flush the streaming decoder's buffered multi-byte tail, then process any
|
|
269
|
+
// final UNTERMINATED frame left in the buffer. Well-formed SSE ends with
|
|
270
|
+
// `\n\n` so the buffer is normally empty here — but a server that closes
|
|
271
|
+
// mid-frame without a trailing newline would otherwise drop its last token,
|
|
272
|
+
// and a multi-byte char split across the final chunk would be corrupted.
|
|
273
|
+
buffer += decoder.decode();
|
|
274
|
+
if (buffer) text += this.handleLine(buffer);
|
|
275
|
+
|
|
276
|
+
// The reader closing IS the completion signal — fire `onDone` once here
|
|
277
|
+
// regardless of whether a `done` event / `[DONE]` sentinel arrived. A server
|
|
278
|
+
// that closes the connection mid-stream (crash, network drop, Lambda
|
|
279
|
+
// timeout) sends neither, but the turn IS over, so a host relying on `onDone`
|
|
280
|
+
// to flip "streaming" off must still get it (otherwise the UI sticks).
|
|
281
|
+
this.callbacks.onDone?.();
|
|
282
|
+
return text;
|
|
283
|
+
} finally {
|
|
284
|
+
// Release the response-body reader lock on EVERY exit path (normal close OR
|
|
285
|
+
// a thrown AbortError caught by ask()). The abort signal already tears the
|
|
286
|
+
// fetch down, but releasing explicitly is correct stream hygiene. Optional-
|
|
287
|
+
// chained so a hand-rolled reader mock (tests) without releaseLock no-ops.
|
|
288
|
+
reader.releaseLock?.();
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Decode one buffered SSE line into an `AssistantStreamEvent`, dispatch it to
|
|
294
|
+
* the host callbacks, and return the `token` text the line contributed (empty
|
|
295
|
+
* for a non-token frame, the `[DONE]` sentinel, a non-`data:` line, or a
|
|
296
|
+
* malformed frame — a single bad line is SKIPPED, never aborting the stream).
|
|
297
|
+
*
|
|
298
|
+
* The single line-parse path shared by the streaming loop and the final-buffer
|
|
299
|
+
* flush in `consume`, so the loop and the close-time tail can never decode a
|
|
300
|
+
* frame differently.
|
|
301
|
+
*/
|
|
302
|
+
private handleLine(line: string): string {
|
|
303
|
+
if (!line.startsWith(SSE_DATA_PREFIX)) return '';
|
|
304
|
+
const data = line.slice(SSE_DATA_PREFIX.length);
|
|
305
|
+
if (data === SSE_DONE_SENTINEL) return '';
|
|
306
|
+
let event: AssistantStreamEvent;
|
|
307
|
+
try {
|
|
308
|
+
event = JSON.parse(data) as AssistantStreamEvent;
|
|
309
|
+
} catch {
|
|
310
|
+
return '';
|
|
311
|
+
}
|
|
312
|
+
this.dispatch(event);
|
|
313
|
+
return event.type === 'token' ? event.content : '';
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Dispatch one decoded event to the matching host callback. `done` needs no
|
|
318
|
+
* handling here — `consume` fires `onDone` once when the reader closes (the
|
|
319
|
+
* close is the completion signal). `tool_use` / `tool_result` / `citation` are
|
|
320
|
+
* intentionally ignored (minimal surface).
|
|
321
|
+
*/
|
|
322
|
+
private dispatch(event: AssistantStreamEvent): void {
|
|
323
|
+
switch (event.type) {
|
|
324
|
+
case 'token':
|
|
325
|
+
this.callbacks.onTextDelta?.(event.content);
|
|
326
|
+
return;
|
|
327
|
+
case 'suggestion':
|
|
328
|
+
this.callbacks.onSuggestion?.({
|
|
329
|
+
targetForm: event.targetForm,
|
|
330
|
+
// String-coerce each value: the event is a `JSON.parse` cast with no
|
|
331
|
+
// runtime guarantee, and an LLM may emit a non-string (e.g. a number)
|
|
332
|
+
// — the host expects `Record<string, string>`, so normalize here.
|
|
333
|
+
fields: Object.fromEntries(
|
|
334
|
+
Object.entries(event.fields ?? {}).map(([k, v]) => [k, String(v)]),
|
|
335
|
+
),
|
|
336
|
+
...(event.rationale !== undefined ? { rationale: event.rationale } : {}),
|
|
337
|
+
});
|
|
338
|
+
return;
|
|
339
|
+
case 'error':
|
|
340
|
+
this.callbacks.onError?.(event.message);
|
|
341
|
+
return;
|
|
342
|
+
default:
|
|
343
|
+
// done / tool_use / tool_result / citation — no per-event handling.
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared abort-detection helper for the reactor submodule. Three call
|
|
3
|
+
* sites used to carry their own copy of this 6-liner — drift between
|
|
4
|
+
* them would silently change cancellation semantics (an abort being
|
|
5
|
+
* mistaken for a real error logs noise; a real error being mistaken
|
|
6
|
+
* for an abort silently swallows it), so we consolidate here.
|
|
7
|
+
*
|
|
8
|
+
* Accepts both `DOMException { name: 'AbortError' }` (native `fetch`
|
|
9
|
+
* + browser `AbortController`) and plain `Error { name: 'AbortError'
|
|
10
|
+
* }` (some polyfills, the project's own pollers). Also accepts
|
|
11
|
+
* `Error { code: 'ABORT_ERR' }` which some libraries use as their
|
|
12
|
+
* abort signal shape. Keep the union broad so a future polyfill or
|
|
13
|
+
* SSR runtime swap doesn't silently break cancellation handling.
|
|
14
|
+
*/
|
|
15
|
+
export function isAbortError(err: unknown): boolean {
|
|
16
|
+
if (err instanceof DOMException && err.name === 'AbortError') return true;
|
|
17
|
+
if (err instanceof Error) {
|
|
18
|
+
if (err.name === 'AbortError') return true;
|
|
19
|
+
if ((err as Error & { code?: string }).code === 'ABORT_ERR') return true;
|
|
20
|
+
}
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Submit a user-authored or model-authored scene prompt to a live
|
|
3
|
+
* Reactor session. Encapsulates the chunk-0-vs-running policy that
|
|
4
|
+
* previously lived inline in `InteractiveController.handleSubmit` and
|
|
5
|
+
* has now been extracted so the watch-page `HeliosWorldControls`
|
|
6
|
+
* reuses the same logic without duplication.
|
|
7
|
+
*
|
|
8
|
+
* `dispatchHeliosCommand.handleSetScene` (the chat-tool driver) does
|
|
9
|
+
* NOT call into this helper — it keeps its own copy because it needs
|
|
10
|
+
* a distinct `hasStarted` guard for the chat flow (see the comment
|
|
11
|
+
* at the top of `heliosCommandDispatcher.ts::handleSetScene`).
|
|
12
|
+
*
|
|
13
|
+
* Framework-agnostic — no React, no DOM beyond what Reactor's bridge
|
|
14
|
+
* surface already accepts. Errors propagate (unlike `dispatchHelios-
|
|
15
|
+
* Command`, which swallows them to keep the chat loop alive). UI
|
|
16
|
+
* consumers can wrap the call in try/catch to surface a banner.
|
|
17
|
+
*
|
|
18
|
+
* Upsample policy is identical to the prior inline implementation:
|
|
19
|
+
* a non-abort failure logs a warning and falls back to the raw prompt
|
|
20
|
+
* (`buildUpsamplePrompt` is best-effort grounding, not a hard
|
|
21
|
+
* dependency). Abort errors are re-thrown so callers stop awaiting.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type { ApiClient } from '../api';
|
|
25
|
+
import { isAbortError } from './abortUtils';
|
|
26
|
+
import type { EntityContext, PersonaContext } from './types';
|
|
27
|
+
|
|
28
|
+
/** Minimal Reactor surface this helper needs. `applyScenePrompt` only
|
|
29
|
+
* ever issues `set_prompt`, `start`, and `schedule_prompt` — it never
|
|
30
|
+
* uploads a file. Kept narrow so callers don't have to thread an
|
|
31
|
+
* unused `uploadFile` reference; the broader `HeliosReactorBridge`
|
|
32
|
+
* (which adds `uploadFile`) is for the swap-seed / set-image paths. */
|
|
33
|
+
export interface ApplyScenePromptReactorBridge {
|
|
34
|
+
sendCommand: (command: string, data: unknown) => Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ApplyScenePromptInput {
|
|
38
|
+
/** The prompt to apply. May be raw user text or a model-emitted
|
|
39
|
+
* Helios-shaped prompt; either way the upsampler is run as a
|
|
40
|
+
* grounding pass and its output (or the raw prompt on failure) is
|
|
41
|
+
* forwarded to Reactor. */
|
|
42
|
+
prompt: string;
|
|
43
|
+
apiClient: ApiClient;
|
|
44
|
+
reactor: ApplyScenePromptReactorBridge;
|
|
45
|
+
/** Live `current_chunk` from Reactor's `state` messages. */
|
|
46
|
+
currentChunk: number;
|
|
47
|
+
/** Whether the world is currently running (Reactor model state
|
|
48
|
+
* `current_frame > 0`). When false, this is the first prompt and
|
|
49
|
+
* we issue `set_prompt` + `start`. When true, we issue
|
|
50
|
+
* `schedule_prompt` at `currentChunk + 2` (the two-chunk lead is
|
|
51
|
+
* what Helios accepts mid-stream). */
|
|
52
|
+
isRunning: boolean;
|
|
53
|
+
/** Optional context plumbed into the upsampler. */
|
|
54
|
+
imageId?: string;
|
|
55
|
+
entityContext?: EntityContext;
|
|
56
|
+
personaContext?: PersonaContext;
|
|
57
|
+
/** Previous prompt for the upsampler's narrative-continuity heuristic. */
|
|
58
|
+
previousPrompt?: string;
|
|
59
|
+
/** When false, skip the upsample call and forward `prompt` to Reactor
|
|
60
|
+
* verbatim. Defaults to `true` so existing callers keep their current
|
|
61
|
+
* behavior. UIs that surface a user-facing upsample toggle (and run
|
|
62
|
+
* the upsample preview separately via `apiClient.upsampleReactorPrompt`
|
|
63
|
+
* to populate an editable textarea) should pass `false` on the
|
|
64
|
+
* send-step so the operator's exact text reaches Helios. */
|
|
65
|
+
shouldUpsample?: boolean;
|
|
66
|
+
signal?: AbortSignal;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface ApplyScenePromptResult {
|
|
70
|
+
/** The prompt actually sent to Reactor — either the upsampler's
|
|
71
|
+
* output or the raw input when upsample failed. */
|
|
72
|
+
appliedPrompt: string;
|
|
73
|
+
/** When non-null, the chunk index Helios will activate the prompt at
|
|
74
|
+
* (`schedule_prompt`). When null, the prompt was set via
|
|
75
|
+
* `set_prompt` and `start` was issued — this was the first prompt
|
|
76
|
+
* for the session. */
|
|
77
|
+
scheduledAtChunk: number | null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function applyScenePrompt(
|
|
81
|
+
input: ApplyScenePromptInput,
|
|
82
|
+
): Promise<ApplyScenePromptResult> {
|
|
83
|
+
const {
|
|
84
|
+
prompt: rawPrompt,
|
|
85
|
+
apiClient,
|
|
86
|
+
reactor,
|
|
87
|
+
currentChunk,
|
|
88
|
+
isRunning,
|
|
89
|
+
imageId,
|
|
90
|
+
entityContext,
|
|
91
|
+
personaContext,
|
|
92
|
+
previousPrompt,
|
|
93
|
+
shouldUpsample = true,
|
|
94
|
+
signal,
|
|
95
|
+
} = input;
|
|
96
|
+
|
|
97
|
+
let prompt = rawPrompt;
|
|
98
|
+
if (shouldUpsample) {
|
|
99
|
+
try {
|
|
100
|
+
const res = await apiClient.upsampleReactorPrompt(
|
|
101
|
+
{
|
|
102
|
+
prompt: rawPrompt,
|
|
103
|
+
...(previousPrompt ? { previousPrompt } : {}),
|
|
104
|
+
...(imageId ? { imageId } : {}),
|
|
105
|
+
...(entityContext ? { entityContext } : {}),
|
|
106
|
+
...(personaContext ? { personaContext } : {}),
|
|
107
|
+
},
|
|
108
|
+
{ signal },
|
|
109
|
+
);
|
|
110
|
+
if (res?.upsampledPrompt) prompt = res.upsampledPrompt;
|
|
111
|
+
} catch (err) {
|
|
112
|
+
if (isAbortError(err)) throw err;
|
|
113
|
+
console.warn(
|
|
114
|
+
'[applyScenePrompt] upsample failed; falling back to raw prompt',
|
|
115
|
+
err,
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (signal?.aborted) {
|
|
121
|
+
throw new DOMException('Aborted', 'AbortError');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (!isRunning) {
|
|
125
|
+
await reactor.sendCommand('set_prompt', { prompt });
|
|
126
|
+
await reactor.sendCommand('start', {});
|
|
127
|
+
return { appliedPrompt: prompt, scheduledAtChunk: null };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const targetChunk = currentChunk + 2;
|
|
131
|
+
await reactor.sendCommand('schedule_prompt', {
|
|
132
|
+
prompt,
|
|
133
|
+
chunk: targetChunk,
|
|
134
|
+
});
|
|
135
|
+
return { appliedPrompt: prompt, scheduledAtChunk: targetChunk };
|
|
136
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* chunkDistribution — the shared chunk-index distribution + minimum-spacing
|
|
3
|
+
* rules used by BOTH timeline mappers (`mapEnrichmentToTimeline` over raw
|
|
4
|
+
* Pegasus enrichment, and `deriveStoryTimeline` over the R5 story projection).
|
|
5
|
+
*
|
|
6
|
+
* Extracted in R8.1 so the two mappers share ONE distribution algorithm — a
|
|
7
|
+
* second copy could drift the chunk math silently (CLAUDE.md DRY). The rules
|
|
8
|
+
* are documented on `scenesFromEnrichment.ts` and unit-tested via both mappers.
|
|
9
|
+
*
|
|
10
|
+
* The helpers operate on the minimal {@link TimedItem} timing shape so any
|
|
11
|
+
* caller (raw scene, story scene) can reuse them without a shared scene type.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Shared default chunk budget (Helios prototype: ~33 fpc, 30 chunks ≈ 16s). */
|
|
15
|
+
export const DEFAULT_MAX_CHUNKS = 30;
|
|
16
|
+
/** Shared default minimum chunk gap between consecutive kept beats. */
|
|
17
|
+
export const DEFAULT_MIN_CHUNK_SPACING = 2;
|
|
18
|
+
|
|
19
|
+
/** The minimal timing shape the distribution rules read. */
|
|
20
|
+
export interface TimedItem {
|
|
21
|
+
start?: number;
|
|
22
|
+
end?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Compute one chunk index per item.
|
|
27
|
+
*
|
|
28
|
+
* If every item carries numeric `start`/`end` with a positive total span, the
|
|
29
|
+
* chunk index is scaled proportionally from each item's start across
|
|
30
|
+
* `[0, maxChunks)` (first item pinned to chunk 0, clamped to `maxChunks - 1`).
|
|
31
|
+
* Otherwise distribute evenly across `[0, maxChunks)` (first at 0, last at
|
|
32
|
+
* `maxChunks - 1`, linear spacing between).
|
|
33
|
+
*/
|
|
34
|
+
export function computeChunkIndices(items: readonly TimedItem[], maxChunks: number): number[] {
|
|
35
|
+
if (items.length === 0) return [];
|
|
36
|
+
if (items.length === 1) return [0];
|
|
37
|
+
|
|
38
|
+
const allTimed = items.every(
|
|
39
|
+
(s) => typeof s.start === 'number' && typeof s.end === 'number',
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
// If timings are present and meaningful (positive span), scale.
|
|
43
|
+
if (allTimed) {
|
|
44
|
+
const starts = items.map((s) => s.start as number);
|
|
45
|
+
const ends = items.map((s) => s.end as number);
|
|
46
|
+
const minStart = Math.min(...starts);
|
|
47
|
+
const maxEnd = Math.max(...ends);
|
|
48
|
+
const span = maxEnd - minStart;
|
|
49
|
+
if (span > 0) {
|
|
50
|
+
return items.map((s, i) => {
|
|
51
|
+
if (i === 0) return 0;
|
|
52
|
+
const start = s.start as number;
|
|
53
|
+
const frac = (start - minStart) / span;
|
|
54
|
+
const chunk = Math.round(frac * (maxChunks - 1));
|
|
55
|
+
// Clamp into [0, maxChunks - 1].
|
|
56
|
+
return Math.max(0, Math.min(maxChunks - 1, chunk));
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Fallback — even distribution. First item at 0, last item at
|
|
62
|
+
// maxChunks - 1, with linear spacing between.
|
|
63
|
+
return items.map((_, i) => {
|
|
64
|
+
if (i === 0) return 0;
|
|
65
|
+
const frac = i / (items.length - 1);
|
|
66
|
+
return Math.round(frac * (maxChunks - 1));
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Apply `minSpacing`. Walks in order, always keeps the first item (forced to
|
|
72
|
+
* chunk 0), drops any item whose chunk is closer than `minSpacing` to the
|
|
73
|
+
* previously-kept item. Returns the kept items paired with their final chunk
|
|
74
|
+
* and original index.
|
|
75
|
+
*/
|
|
76
|
+
export function enforceSpacing<T extends TimedItem>(
|
|
77
|
+
items: readonly T[],
|
|
78
|
+
chunks: readonly number[],
|
|
79
|
+
minSpacing: number,
|
|
80
|
+
): { item: T; chunk: number; index: number }[] {
|
|
81
|
+
const kept: { item: T; chunk: number; index: number }[] = [];
|
|
82
|
+
for (let i = 0; i < items.length; i++) {
|
|
83
|
+
const item = items[i];
|
|
84
|
+
let chunk = chunks[i];
|
|
85
|
+
if (kept.length === 0) {
|
|
86
|
+
// First item is always pinned to chunk 0.
|
|
87
|
+
chunk = 0;
|
|
88
|
+
kept.push({ item, chunk, index: i });
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const prev = kept[kept.length - 1].chunk;
|
|
92
|
+
if (chunk - prev < minSpacing) {
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
kept.push({ item, chunk, index: i });
|
|
96
|
+
}
|
|
97
|
+
return kept;
|
|
98
|
+
}
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import type { ApiClient, ImageRecord } from '../api';
|
|
18
|
+
import { isAbortError } from './abortUtils';
|
|
18
19
|
import { findEntityImageBySeedName } from './entitySearch';
|
|
19
20
|
import type { HeliosCommand } from './heliosTools';
|
|
20
21
|
import {
|
|
@@ -94,23 +95,6 @@ export interface HeliosToolContext {
|
|
|
94
95
|
signal?: AbortSignal;
|
|
95
96
|
}
|
|
96
97
|
|
|
97
|
-
/**
|
|
98
|
-
* Dispatch a single `HeliosCommand` to the live Reactor session.
|
|
99
|
-
* Resolves with no value on both success and failure — the caller
|
|
100
|
-
* just awaits the dispatch and continues to the next command.
|
|
101
|
-
*/
|
|
102
|
-
/** True when `err` is an `AbortError` (or carries that name). Browsers
|
|
103
|
-
* emit `DOMException('AbortError')`; fetch + apiClient already pass
|
|
104
|
-
* this through unchanged. The `code === 'ABORT_ERR'` branch covers
|
|
105
|
-
* custom error classes some libraries use; the `name` check handles
|
|
106
|
-
* every browser DOMException + standard polyfill. */
|
|
107
|
-
function isAbortError(err: unknown): boolean {
|
|
108
|
-
return (
|
|
109
|
-
err instanceof Error &&
|
|
110
|
-
(err.name === 'AbortError' || (err as Error & { code?: string }).code === 'ABORT_ERR')
|
|
111
|
-
);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
98
|
/**
|
|
115
99
|
* Dispatch a single `HeliosCommand` to the live Reactor session.
|
|
116
100
|
* Resolves with no value on both success and failure — the caller
|
|
@@ -170,13 +154,21 @@ export async function dispatchHeliosCommand(
|
|
|
170
154
|
/**
|
|
171
155
|
* SET_SCENE: knowledge-grounded upsample then a prompt change.
|
|
172
156
|
*
|
|
173
|
-
* Mirrors `InteractiveController.handleSubmit
|
|
157
|
+
* Mirrors `InteractiveController.handleSubmit` and
|
|
158
|
+
* `applyScenePrompt` (the shared helper used by the React controls):
|
|
174
159
|
* - chunk 0 (no frames rendered yet) → `set_prompt`
|
|
175
160
|
* - mid-stream → `schedule_prompt` at `currentChunk + 2`
|
|
176
161
|
*
|
|
177
162
|
* Upsample failure falls back to the raw model-emitted prompt rather
|
|
178
163
|
* than aborting — the model is already doing the Helios prompt-guide
|
|
179
164
|
* shaping; upsample just adds knowledge-graph grounding.
|
|
165
|
+
*
|
|
166
|
+
* Not implemented in terms of `applyScenePrompt` because the chat-tool
|
|
167
|
+
* path has a distinct `hasStarted` guard: when SET_SCENE fires at
|
|
168
|
+
* chunk 0 against an already-running world, we skip the `start`
|
|
169
|
+
* re-emit. `applyScenePrompt`'s UI callers track running via
|
|
170
|
+
* `current_frame > 0` instead, which is authoritative for the
|
|
171
|
+
* operator-driven flow.
|
|
180
172
|
*/
|
|
181
173
|
async function handleSetScene(
|
|
182
174
|
modelPrompt: string,
|
package/src/reactor/index.ts
CHANGED
|
@@ -8,10 +8,17 @@ export * from './regenTemplate';
|
|
|
8
8
|
export * from './upsamplePrompt';
|
|
9
9
|
export * from './entityContext';
|
|
10
10
|
export * from './scenesFromEnrichment';
|
|
11
|
+
// R8.1 — story-graph-driven timeline mapper (sibling of scenesFromEnrichment).
|
|
12
|
+
// The shared chunk-distribution helpers in `./chunkDistribution` stay internal
|
|
13
|
+
// (imported by both mappers); they are deliberately NOT re-exported here.
|
|
14
|
+
export * from './storyTimeline';
|
|
11
15
|
export * from './heliosTools';
|
|
12
16
|
export * from './toolPromptAddon';
|
|
13
17
|
export * from './entitySearch';
|
|
14
18
|
export * from './heliosCommandDispatcher';
|
|
19
|
+
export * from './longLiveCommandDispatcher';
|
|
15
20
|
export * from './seedImageOrchestrator';
|
|
16
21
|
export * from './promptAddonRegistry';
|
|
17
22
|
export * from './sceneEntry';
|
|
23
|
+
export * from './applyScenePrompt';
|
|
24
|
+
export * from './abortUtils';
|