@adea-ai/spatial-protocol 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # @adea-ai/spatial-protocol
2
+
3
+ Shell↔engine contract for the spatial view. Pure types, mount manifests, URL
4
+ helpers, and telemetry schema — no rendering, no binaries, no secrets.
5
+
6
+ - `manifests.ts` — `hqHomeManifest` / `hqWorkManifest` mount constants (mirrors
7
+ the engine's room layout; the engine is source of truth).
8
+ - `scene-spawn.ts` — cross-app spawn encode/parse and portal URL helpers.
9
+ - `telemetry.ts` — `ScenePerformanceReport` schema, validation, envelope, and
10
+ navigation instrumentation.
11
+ - `data/` — tracked scene manifests (`home/`, `work/`), mirrored from the
12
+ engine's `scenes/sim/assets/`; staged into the web public dir by
13
+ `scripts/sync-assets.mjs`.
@@ -0,0 +1,12 @@
1
+ export type { SceneManifest, SceneStartPosition, SceneZone } from '@adea-ai/asset-manifests';
2
+ export { hqHomeManifest, hqWorkManifest } from './manifests';
3
+ export { appRouteHref, encodeSceneStartPosition, portalNavigationHref, readSceneStartPosition, type PortalNavigation, type SceneApp, } from './scene-spawn';
4
+ export { createSceneTelemetryEnvelope, MAX_SCENE_TELEMETRY_BYTES, onRouterTransitionStart, parseScenePerformanceReport, recordNavigation, SCENE_TELEMETRY_LOG_PREFIX, type SceneNavigationType, type ScenePerformanceReport, type SceneRuntimeStats, type SceneTelemetryEnvelope, } from './telemetry';
5
+ export declare const configurableCharacterId = "configurable";
6
+ export declare const DEFAULT_CHARACTER_ID = "configurable";
7
+ /**
8
+ * Shell-side character param check. The engine validates against its
9
+ * reference/preset catalogs on mount; the shell only needs a plausible
10
+ * non-empty value to thread through.
11
+ */
12
+ export declare function isPlausibleCharacterId(value: string | undefined): value is string;
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ export { hqHomeManifest, hqWorkManifest } from './manifests';
2
+ export { appRouteHref, encodeSceneStartPosition, portalNavigationHref, readSceneStartPosition, } from './scene-spawn';
3
+ export { createSceneTelemetryEnvelope, MAX_SCENE_TELEMETRY_BYTES, onRouterTransitionStart, parseScenePerformanceReport, recordNavigation, SCENE_TELEMETRY_LOG_PREFIX, } from './telemetry';
4
+ export const configurableCharacterId = 'configurable';
5
+ export const DEFAULT_CHARACTER_ID = configurableCharacterId;
6
+ /**
7
+ * Shell-side character param check. The engine validates against its
8
+ * reference/preset catalogs on mount; the shell only needs a plausible
9
+ * non-empty value to thread through.
10
+ */
11
+ export function isPlausibleCharacterId(value) {
12
+ return typeof value === 'string' && value.length > 0 && value.length <= 128;
13
+ }
@@ -0,0 +1,3 @@
1
+ import type { SceneManifest } from '@adea-ai/asset-manifests';
2
+ export declare const hqHomeManifest: SceneManifest;
3
+ export declare const hqWorkManifest: SceneManifest;
@@ -0,0 +1,26 @@
1
+ const sceneConfig = {
2
+ home: { label: 'Home', floorVersion: 20, foliageVersion: 10 },
3
+ work: { label: 'Work', floorVersion: 21, foliageVersion: 11 },
4
+ };
5
+ // Start height mirrors the engine's ROOM_GALLERY_FOUNDATION_TOP_Y (slab base 0
6
+ // + height 6) plus the authored 135-unit lift. The engine's room-config is
7
+ // the simulation source of truth; this package carries the mount constants
8
+ // the shell needs without depending on engine code.
9
+ const START_Y = 6 + 135;
10
+ function createHqManifest(scene) {
11
+ const { label, floorVersion, foliageVersion } = sceneConfig[scene];
12
+ const sceneId = `hq-${scene}`;
13
+ return {
14
+ id: sceneId,
15
+ label,
16
+ availability: 'ready',
17
+ entryAssetUrl: `/assets/worlds/${sceneId}/floor.glb?v=${floorVersion}`,
18
+ collisionAssetUrl: `/assets/worlds/${sceneId}/floor-collision.glb?v=${floorVersion}`,
19
+ foliageManifestUrl: `/assets/worlds/${sceneId}/foliage.json?v=${foliageVersion}`,
20
+ assignedPropsManifestUrl: `/assets/worlds/${sceneId}/props-runtime.json?v=room-layout`,
21
+ zones: [],
22
+ startPosition: { x: 0, y: START_Y, z: 0, yaw: 0, pitch: -0.2 },
23
+ };
24
+ }
25
+ export const hqHomeManifest = createHqManifest('home');
26
+ export const hqWorkManifest = createHqManifest('work');
@@ -0,0 +1,15 @@
1
+ import type { SceneStartPosition } from '@adea-ai/asset-manifests';
2
+ export type SceneApp = 'world' | 'hq';
3
+ /** Encode a scene start position for a cross-app navigation URL. */
4
+ export declare function encodeSceneStartPosition(position: SceneStartPosition): string;
5
+ /** Parse a validated scene start position from a route's `spawn` query. */
6
+ export declare function readSceneStartPosition(value: string | string[] | undefined): SceneStartPosition | undefined;
7
+ /** Resolve a route for the sibling World or HQ app in dev and production. */
8
+ export declare function appRouteHref(app: SceneApp, path: string, currentHref?: string): string;
9
+ export type PortalNavigation = {
10
+ app: SceneApp;
11
+ path: string;
12
+ spawn?: SceneStartPosition;
13
+ };
14
+ /** Build a portal URL while carrying the selected character and target spawn. */
15
+ export declare function portalNavigationHref(navigation: PortalNavigation, currentHref?: string): string;
@@ -0,0 +1,88 @@
1
+ const SPAWN_QUERY_KEY = 'spawn';
2
+ const APP_DEV_PORTS = { world: '3000', hq: '3004' };
3
+ const APP_PORTLESS_URLS = {
4
+ world: 'https://world.localhost',
5
+ hq: 'https://adea.localhost',
6
+ };
7
+ function firstValue(value) {
8
+ return Array.isArray(value) ? value[0] : value;
9
+ }
10
+ function finiteNumber(value) {
11
+ if (!value)
12
+ return undefined;
13
+ const parsed = Number(value);
14
+ return Number.isFinite(parsed) ? parsed : undefined;
15
+ }
16
+ /** Encode a scene start position for a cross-app navigation URL. */
17
+ export function encodeSceneStartPosition(position) {
18
+ return [
19
+ position.x,
20
+ position.y,
21
+ position.z,
22
+ position.yaw ?? '',
23
+ position.pitch ?? '',
24
+ position.snapToGround == null ? '' : position.snapToGround ? '1' : '0',
25
+ ].join(',');
26
+ }
27
+ /** Parse a validated scene start position from a route's `spawn` query. */
28
+ export function readSceneStartPosition(value) {
29
+ const parts = firstValue(value)?.split(',');
30
+ if (!parts || parts.length < 3 || parts.length > 6)
31
+ return undefined;
32
+ const x = finiteNumber(parts[0]);
33
+ const y = finiteNumber(parts[1]);
34
+ const z = finiteNumber(parts[2]);
35
+ if (x == null || y == null || z == null)
36
+ return undefined;
37
+ const yaw = finiteNumber(parts[3]);
38
+ const pitch = finiteNumber(parts[4]);
39
+ const snap = parts[5];
40
+ if (parts[3] && yaw == null)
41
+ return undefined;
42
+ if (parts[4] && pitch == null)
43
+ return undefined;
44
+ if (snap && snap !== '0' && snap !== '1')
45
+ return undefined;
46
+ return {
47
+ x,
48
+ y,
49
+ z,
50
+ ...(yaw == null ? {} : { yaw }),
51
+ ...(pitch == null ? {} : { pitch }),
52
+ ...(snap === '0' ? { snapToGround: false } : snap === '1' ? { snapToGround: true } : {}),
53
+ };
54
+ }
55
+ function configuredAppBase(app) {
56
+ const configured = app === 'world' ? process.env.NEXT_PUBLIC_ADEA_WORLD_URL : process.env.NEXT_PUBLIC_ADEA_HQ_URL;
57
+ return configured?.trim() || undefined;
58
+ }
59
+ function isDevelopmentHost(hostname) {
60
+ return (hostname === 'localhost' ||
61
+ hostname === '127.0.0.1' ||
62
+ hostname === '0.0.0.0' ||
63
+ hostname === 'amf-mb-pro' ||
64
+ hostname.endsWith('.localhost') ||
65
+ hostname.endsWith('.ts.net'));
66
+ }
67
+ /** Resolve a route for the sibling World or HQ app in dev and production. */
68
+ export function appRouteHref(app, path, currentHref) {
69
+ const current = new URL(currentHref ?? window.location.href);
70
+ const configuredBase = configuredAppBase(app);
71
+ const isPortlessHost = current.hostname.endsWith('.localhost');
72
+ const target = new URL(path, configuredBase ?? (isPortlessHost ? APP_PORTLESS_URLS[app] : current.origin));
73
+ if (!configuredBase && !isPortlessHost && isDevelopmentHost(current.hostname)) {
74
+ target.port = APP_DEV_PORTS[app];
75
+ }
76
+ return target.toString();
77
+ }
78
+ /** Build a portal URL while carrying the selected character and target spawn. */
79
+ export function portalNavigationHref(navigation, currentHref) {
80
+ const current = new URL(currentHref ?? window.location.href);
81
+ const target = new URL(appRouteHref(navigation.app, navigation.path, current.toString()));
82
+ const character = current.searchParams.get('character');
83
+ if (character)
84
+ target.searchParams.set('character', character);
85
+ if (navigation.spawn)
86
+ target.searchParams.set(SPAWN_QUERY_KEY, encodeSceneStartPosition(navigation.spawn));
87
+ return target.toString();
88
+ }
@@ -0,0 +1,106 @@
1
+ export type SceneNavigationType = 'navigate' | 'push' | 'replace' | 'traverse' | 'scene-mount';
2
+ export type ScenePerformanceReport = {
3
+ version: 1;
4
+ event: 'load' | 'runtime' | 'dispose' | 'error';
5
+ release?: string;
6
+ scene: string;
7
+ path: string;
8
+ navigation: {
9
+ id: string;
10
+ type: SceneNavigationType;
11
+ startTime: number;
12
+ };
13
+ milestones: {
14
+ firstRenderedFrameMs?: number;
15
+ playableCharacterMs?: number;
16
+ phasesMs: Record<string, number>;
17
+ };
18
+ network: {
19
+ requests: number;
20
+ networkRequests: number;
21
+ cacheHits: number;
22
+ unknownCacheStatus: number;
23
+ transferBytes: number;
24
+ encodedBodyBytes: number;
25
+ decodedBodyBytes: number;
26
+ };
27
+ runtime: {
28
+ sampleWindowMs: number;
29
+ frames: number;
30
+ fps?: number;
31
+ p50FrameMs?: number;
32
+ p95FrameMs?: number;
33
+ longestFrameMs?: number;
34
+ p95FrameIntervalMs?: number;
35
+ longestFrameIntervalMs?: number;
36
+ longTasks: number;
37
+ longTaskDurationMs: number;
38
+ drawCalls?: number;
39
+ drawCallsP95?: number;
40
+ drawCallsMax?: number;
41
+ triangles?: number;
42
+ geometries?: number;
43
+ textures?: number;
44
+ programs?: number;
45
+ reactCommits?: number;
46
+ reactCommitDurationMs?: number;
47
+ reactMaxCommitMs?: number;
48
+ };
49
+ renderables: SceneRuntimeStats;
50
+ lifecycle: {
51
+ disposedGeometries: number;
52
+ disposedMaterials: number;
53
+ disposedTextures: number;
54
+ };
55
+ device: {
56
+ tier: 'high' | 'standard' | 'low';
57
+ mobile: boolean;
58
+ devicePixelRatio: number;
59
+ hardwareConcurrency: number;
60
+ deviceMemoryGb?: number;
61
+ webglVersion: string;
62
+ gpu?: string;
63
+ maxTextureSize?: number;
64
+ };
65
+ error?: string;
66
+ };
67
+ export type SceneRuntimeStats = {
68
+ meshes: number;
69
+ visibleMeshes: number;
70
+ frustumCulledMeshes: number;
71
+ materials: number;
72
+ instancedMeshes: number;
73
+ instances: number;
74
+ foliageMeshes: number;
75
+ foliageInstances: number;
76
+ fenceMeshes: number;
77
+ fenceInstances: number;
78
+ repeatedGeometryGroups: number;
79
+ repeatedGeometryInstances: number;
80
+ };
81
+ export declare const SCENE_TELEMETRY_LOG_PREFIX = "[scene-telemetry] ";
82
+ export declare const MAX_SCENE_TELEMETRY_BYTES: number;
83
+ export type SceneTelemetryEnvelope = {
84
+ receivedAt: string;
85
+ deployment?: string;
86
+ report: ScenePerformanceReport;
87
+ };
88
+ export declare function parseScenePerformanceReport(value: unknown): ScenePerformanceReport | null;
89
+ export declare function createSceneTelemetryEnvelope(report: ScenePerformanceReport, receivedAt?: Date, deployment?: string | undefined): SceneTelemetryEnvelope;
90
+ type NavigationStart = {
91
+ id: string;
92
+ url: string;
93
+ startTime: number;
94
+ type: 'navigate' | 'push' | 'replace' | 'traverse';
95
+ claimed?: boolean;
96
+ };
97
+ declare global {
98
+ interface Window {
99
+ __ADEA_NAVIGATION_START__?: NavigationStart;
100
+ __ADEA_SCENE_TELEMETRY_ENDPOINT__?: string;
101
+ __ADEA_RELEASE__?: string;
102
+ }
103
+ }
104
+ export declare function recordNavigation(url: string, type: 'navigate' | 'push' | 'replace' | 'traverse', startTime: number): void;
105
+ export declare function onRouterTransitionStart(url: string, navigationType: 'push' | 'replace' | 'traverse'): void;
106
+ export {};
@@ -0,0 +1,79 @@
1
+ export const SCENE_TELEMETRY_LOG_PREFIX = '[scene-telemetry] ';
2
+ export const MAX_SCENE_TELEMETRY_BYTES = 64 * 1024;
3
+ function isFiniteNumber(value) {
4
+ return typeof value === 'number' && Number.isFinite(value);
5
+ }
6
+ function isRecord(value) {
7
+ return value != null && typeof value === 'object' && !Array.isArray(value);
8
+ }
9
+ function validReport(value) {
10
+ if (!isRecord(value))
11
+ return false;
12
+ if (value.version !== 1 || !['load', 'runtime', 'dispose', 'error'].includes(String(value.event)))
13
+ return false;
14
+ if (typeof value.scene !== 'string' || value.scene.length < 1 || value.scene.length > 80)
15
+ return false;
16
+ if (typeof value.path !== 'string' || value.path.length < 1 || value.path.length > 256)
17
+ return false;
18
+ if (value.release != null && (typeof value.release !== 'string' || value.release.length > 128))
19
+ return false;
20
+ if (!isRecord(value.navigation) ||
21
+ typeof value.navigation.id !== 'string' ||
22
+ !isFiniteNumber(value.navigation.startTime))
23
+ return false;
24
+ if (!isRecord(value.milestones) || !isRecord(value.milestones.phasesMs))
25
+ return false;
26
+ if (!isRecord(value.network) ||
27
+ !isFiniteNumber(value.network.requests) ||
28
+ !isFiniteNumber(value.network.transferBytes))
29
+ return false;
30
+ if (!isRecord(value.runtime) ||
31
+ !isFiniteNumber(value.runtime.sampleWindowMs) ||
32
+ !isFiniteNumber(value.runtime.frames))
33
+ return false;
34
+ if (!isRecord(value.device) || !['high', 'standard', 'low'].includes(String(value.device.tier)))
35
+ return false;
36
+ if (typeof value.device.mobile !== 'boolean' || !isFiniteNumber(value.device.devicePixelRatio))
37
+ return false;
38
+ return true;
39
+ }
40
+ export function parseScenePerformanceReport(value) {
41
+ return validReport(value) ? value : null;
42
+ }
43
+ export function createSceneTelemetryEnvelope(report, receivedAt = new Date(), deployment = process.env.DEPLOY_GIT_COMMIT_SHA) {
44
+ return {
45
+ receivedAt: receivedAt.toISOString(),
46
+ ...(deployment ? { deployment } : {}),
47
+ report,
48
+ };
49
+ }
50
+ export function recordNavigation(url, type, startTime) {
51
+ window.__ADEA_NAVIGATION_START__ = {
52
+ id: `nav-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
53
+ url,
54
+ startTime,
55
+ type,
56
+ };
57
+ }
58
+ try {
59
+ const navigation = performance.getEntriesByType('navigation')[0];
60
+ recordNavigation(window.location.href, 'navigate', navigation?.startTime ?? 0);
61
+ const endpoint = process.env.NEXT_PUBLIC_SCENE_TELEMETRY_ENDPOINT ||
62
+ (process.env.NODE_ENV === 'production' ? '/api/telemetry/scene-performance' : undefined);
63
+ if (endpoint)
64
+ window.__ADEA_SCENE_TELEMETRY_ENDPOINT__ = endpoint;
65
+ const release = process.env.NEXT_PUBLIC_DEPLOY_GIT_COMMIT_SHA;
66
+ if (release)
67
+ window.__ADEA_RELEASE__ = release;
68
+ }
69
+ catch {
70
+ // Telemetry must never interfere with page initialization.
71
+ }
72
+ export function onRouterTransitionStart(url, navigationType) {
73
+ try {
74
+ recordNavigation(new URL(url, window.location.href).href, navigationType, performance.now());
75
+ }
76
+ catch {
77
+ // Invalid route metadata should not affect navigation.
78
+ }
79
+ }
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@adea-ai/spatial-protocol",
3
+ "version": "0.12.1",
4
+ "description": "Shell↔engine contract for the Adea spatial view: scene mount manifests, spawn URL helpers, and scene telemetry schemas. Pure types — no rendering, no binaries.",
5
+ "keywords": [
6
+ "manifest",
7
+ "protocol",
8
+ "scene",
9
+ "spatial",
10
+ "telemetry",
11
+ "threejs"
12
+ ],
13
+ "homepage": "https://github.com/adea-ai/adea#readme",
14
+ "bugs": "https://github.com/adea-ai/adea/issues",
15
+ "license": "Apache-2.0",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/adea-ai/adea.git",
19
+ "directory": "packages/spatial-protocol"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "src",
24
+ "tsconfig.json",
25
+ "README.md"
26
+ ],
27
+ "type": "module",
28
+ "main": "dist/index.js",
29
+ "types": "dist/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "development": "./src/index.ts",
34
+ "import": "./dist/index.js"
35
+ }
36
+ },
37
+ "scripts": {
38
+ "lint": "oxlint",
39
+ "build": "tsc -p tsconfig.json",
40
+ "dev": "tsc -p tsconfig.json --watch --preserveWatchOutput",
41
+ "test": "bun test test/*.test.ts",
42
+ "typecheck": "tsc -p tsconfig.json --noEmit"
43
+ },
44
+ "dependencies": {
45
+ "@adea-ai/asset-manifests": "^0.12.1"
46
+ }
47
+ }
package/src/index.ts ADDED
@@ -0,0 +1,33 @@
1
+ export type { SceneManifest, SceneStartPosition, SceneZone } from '@adea-ai/asset-manifests'
2
+ export { hqHomeManifest, hqWorkManifest } from './manifests'
3
+ export {
4
+ appRouteHref,
5
+ encodeSceneStartPosition,
6
+ portalNavigationHref,
7
+ readSceneStartPosition,
8
+ type PortalNavigation,
9
+ type SceneApp,
10
+ } from './scene-spawn'
11
+ export {
12
+ createSceneTelemetryEnvelope,
13
+ MAX_SCENE_TELEMETRY_BYTES,
14
+ onRouterTransitionStart,
15
+ parseScenePerformanceReport,
16
+ recordNavigation,
17
+ SCENE_TELEMETRY_LOG_PREFIX,
18
+ type SceneNavigationType,
19
+ type ScenePerformanceReport,
20
+ type SceneRuntimeStats,
21
+ type SceneTelemetryEnvelope,
22
+ } from './telemetry'
23
+ export const configurableCharacterId = 'configurable'
24
+ export const DEFAULT_CHARACTER_ID = configurableCharacterId
25
+
26
+ /**
27
+ * Shell-side character param check. The engine validates against its
28
+ * reference/preset catalogs on mount; the shell only needs a plausible
29
+ * non-empty value to thread through.
30
+ */
31
+ export function isPlausibleCharacterId(value: string | undefined): value is string {
32
+ return typeof value === 'string' && value.length > 0 && value.length <= 128
33
+ }
@@ -0,0 +1,41 @@
1
+ import type { SceneManifest } from '@adea-ai/asset-manifests'
2
+
3
+ // Scene ids mirror @adea-ai/app-core's HqSceneId, which remains the canonical
4
+ // shell-side scene identity. This package only carries mount constants.
5
+ type HqSceneId = 'home' | 'work'
6
+
7
+ type HqSceneConfig = {
8
+ label: string
9
+ floorVersion: number
10
+ foliageVersion: number
11
+ }
12
+
13
+ const sceneConfig = {
14
+ home: { label: 'Home', floorVersion: 20, foliageVersion: 10 },
15
+ work: { label: 'Work', floorVersion: 21, foliageVersion: 11 },
16
+ } as const satisfies Record<HqSceneId, HqSceneConfig>
17
+
18
+ // Start height mirrors the engine's ROOM_GALLERY_FOUNDATION_TOP_Y (slab base 0
19
+ // + height 6) plus the authored 135-unit lift. The engine's room-config is
20
+ // the simulation source of truth; this package carries the mount constants
21
+ // the shell needs without depending on engine code.
22
+ const START_Y = 6 + 135
23
+
24
+ function createHqManifest(scene: HqSceneId): SceneManifest {
25
+ const { label, floorVersion, foliageVersion } = sceneConfig[scene]
26
+ const sceneId = `hq-${scene}`
27
+ return {
28
+ id: sceneId,
29
+ label,
30
+ availability: 'ready',
31
+ entryAssetUrl: `/assets/worlds/${sceneId}/floor.glb?v=${floorVersion}`,
32
+ collisionAssetUrl: `/assets/worlds/${sceneId}/floor-collision.glb?v=${floorVersion}`,
33
+ foliageManifestUrl: `/assets/worlds/${sceneId}/foliage.json?v=${foliageVersion}`,
34
+ assignedPropsManifestUrl: `/assets/worlds/${sceneId}/props-runtime.json?v=room-layout`,
35
+ zones: [],
36
+ startPosition: { x: 0, y: START_Y, z: 0, yaw: 0, pitch: -0.2 },
37
+ }
38
+ }
39
+
40
+ export const hqHomeManifest = createHqManifest('home')
41
+ export const hqWorkManifest = createHqManifest('work')
@@ -0,0 +1,107 @@
1
+ import type { SceneStartPosition } from '@adea-ai/asset-manifests'
2
+
3
+ export type SceneApp = 'world' | 'hq'
4
+
5
+ const SPAWN_QUERY_KEY = 'spawn'
6
+ const APP_DEV_PORTS: Record<SceneApp, string> = { world: '3000', hq: '3004' }
7
+ const APP_PORTLESS_URLS: Record<SceneApp, string> = {
8
+ world: 'https://world.localhost',
9
+ hq: 'https://adea.localhost',
10
+ }
11
+
12
+ function firstValue(value: string | string[] | undefined): string | undefined {
13
+ return Array.isArray(value) ? value[0] : value
14
+ }
15
+
16
+ function finiteNumber(value: string | undefined): number | undefined {
17
+ if (!value) return undefined
18
+ const parsed = Number(value)
19
+ return Number.isFinite(parsed) ? parsed : undefined
20
+ }
21
+
22
+ /** Encode a scene start position for a cross-app navigation URL. */
23
+ export function encodeSceneStartPosition(position: SceneStartPosition): string {
24
+ return [
25
+ position.x,
26
+ position.y,
27
+ position.z,
28
+ position.yaw ?? '',
29
+ position.pitch ?? '',
30
+ position.snapToGround == null ? '' : position.snapToGround ? '1' : '0',
31
+ ].join(',')
32
+ }
33
+
34
+ /** Parse a validated scene start position from a route's `spawn` query. */
35
+ export function readSceneStartPosition(
36
+ value: string | string[] | undefined
37
+ ): SceneStartPosition | undefined {
38
+ const parts = firstValue(value)?.split(',')
39
+ if (!parts || parts.length < 3 || parts.length > 6) return undefined
40
+ const x = finiteNumber(parts[0])
41
+ const y = finiteNumber(parts[1])
42
+ const z = finiteNumber(parts[2])
43
+ if (x == null || y == null || z == null) return undefined
44
+ const yaw = finiteNumber(parts[3])
45
+ const pitch = finiteNumber(parts[4])
46
+ const snap = parts[5]
47
+ if (parts[3] && yaw == null) return undefined
48
+ if (parts[4] && pitch == null) return undefined
49
+ if (snap && snap !== '0' && snap !== '1') return undefined
50
+ return {
51
+ x,
52
+ y,
53
+ z,
54
+ ...(yaw == null ? {} : { yaw }),
55
+ ...(pitch == null ? {} : { pitch }),
56
+ ...(snap === '0' ? { snapToGround: false } : snap === '1' ? { snapToGround: true } : {}),
57
+ }
58
+ }
59
+
60
+ function configuredAppBase(app: SceneApp): string | undefined {
61
+ const configured =
62
+ app === 'world' ? process.env.NEXT_PUBLIC_ADEA_WORLD_URL : process.env.NEXT_PUBLIC_ADEA_HQ_URL
63
+ return configured?.trim() || undefined
64
+ }
65
+
66
+ function isDevelopmentHost(hostname: string): boolean {
67
+ return (
68
+ hostname === 'localhost' ||
69
+ hostname === '127.0.0.1' ||
70
+ hostname === '0.0.0.0' ||
71
+ hostname === 'amf-mb-pro' ||
72
+ hostname.endsWith('.localhost') ||
73
+ hostname.endsWith('.ts.net')
74
+ )
75
+ }
76
+
77
+ /** Resolve a route for the sibling World or HQ app in dev and production. */
78
+ export function appRouteHref(app: SceneApp, path: string, currentHref?: string): string {
79
+ const current = new URL(currentHref ?? window.location.href)
80
+ const configuredBase = configuredAppBase(app)
81
+ const isPortlessHost = current.hostname.endsWith('.localhost')
82
+ const target = new URL(
83
+ path,
84
+ configuredBase ?? (isPortlessHost ? APP_PORTLESS_URLS[app] : current.origin)
85
+ )
86
+ if (!configuredBase && !isPortlessHost && isDevelopmentHost(current.hostname)) {
87
+ target.port = APP_DEV_PORTS[app]
88
+ }
89
+ return target.toString()
90
+ }
91
+
92
+ export type PortalNavigation = {
93
+ app: SceneApp
94
+ path: string
95
+ spawn?: SceneStartPosition
96
+ }
97
+
98
+ /** Build a portal URL while carrying the selected character and target spawn. */
99
+ export function portalNavigationHref(navigation: PortalNavigation, currentHref?: string): string {
100
+ const current = new URL(currentHref ?? window.location.href)
101
+ const target = new URL(appRouteHref(navigation.app, navigation.path, current.toString()))
102
+ const character = current.searchParams.get('character')
103
+ if (character) target.searchParams.set('character', character)
104
+ if (navigation.spawn)
105
+ target.searchParams.set(SPAWN_QUERY_KEY, encodeSceneStartPosition(navigation.spawn))
106
+ return target.toString()
107
+ }
@@ -0,0 +1,202 @@
1
+ export type SceneNavigationType = 'navigate' | 'push' | 'replace' | 'traverse' | 'scene-mount'
2
+
3
+ export type ScenePerformanceReport = {
4
+ version: 1
5
+ event: 'load' | 'runtime' | 'dispose' | 'error'
6
+ release?: string
7
+ scene: string
8
+ path: string
9
+ navigation: { id: string; type: SceneNavigationType; startTime: number }
10
+ milestones: {
11
+ firstRenderedFrameMs?: number
12
+ playableCharacterMs?: number
13
+ phasesMs: Record<string, number>
14
+ }
15
+ network: {
16
+ requests: number
17
+ networkRequests: number
18
+ cacheHits: number
19
+ unknownCacheStatus: number
20
+ transferBytes: number
21
+ encodedBodyBytes: number
22
+ decodedBodyBytes: number
23
+ }
24
+ runtime: {
25
+ sampleWindowMs: number
26
+ frames: number
27
+ fps?: number
28
+ p50FrameMs?: number
29
+ p95FrameMs?: number
30
+ longestFrameMs?: number
31
+ p95FrameIntervalMs?: number
32
+ longestFrameIntervalMs?: number
33
+ longTasks: number
34
+ longTaskDurationMs: number
35
+ drawCalls?: number
36
+ drawCallsP95?: number
37
+ drawCallsMax?: number
38
+ triangles?: number
39
+ geometries?: number
40
+ textures?: number
41
+ programs?: number
42
+ reactCommits?: number
43
+ reactCommitDurationMs?: number
44
+ reactMaxCommitMs?: number
45
+ }
46
+ renderables: SceneRuntimeStats
47
+ lifecycle: {
48
+ disposedGeometries: number
49
+ disposedMaterials: number
50
+ disposedTextures: number
51
+ }
52
+ device: {
53
+ tier: 'high' | 'standard' | 'low'
54
+ mobile: boolean
55
+ devicePixelRatio: number
56
+ hardwareConcurrency: number
57
+ deviceMemoryGb?: number
58
+ webglVersion: string
59
+ gpu?: string
60
+ maxTextureSize?: number
61
+ }
62
+ error?: string
63
+ }
64
+
65
+ export type SceneRuntimeStats = {
66
+ meshes: number
67
+ visibleMeshes: number
68
+ frustumCulledMeshes: number
69
+ materials: number
70
+ instancedMeshes: number
71
+ instances: number
72
+ foliageMeshes: number
73
+ foliageInstances: number
74
+ fenceMeshes: number
75
+ fenceInstances: number
76
+ repeatedGeometryGroups: number
77
+ repeatedGeometryInstances: number
78
+ }
79
+
80
+ export const SCENE_TELEMETRY_LOG_PREFIX = '[scene-telemetry] '
81
+ export const MAX_SCENE_TELEMETRY_BYTES = 64 * 1024
82
+
83
+ export type SceneTelemetryEnvelope = {
84
+ receivedAt: string
85
+ deployment?: string
86
+ report: ScenePerformanceReport
87
+ }
88
+
89
+ function isFiniteNumber(value: unknown): value is number {
90
+ return typeof value === 'number' && Number.isFinite(value)
91
+ }
92
+
93
+ function isRecord(value: unknown): value is Record<string, unknown> {
94
+ return value != null && typeof value === 'object' && !Array.isArray(value)
95
+ }
96
+
97
+ function validReport(value: unknown): value is ScenePerformanceReport {
98
+ if (!isRecord(value)) return false
99
+ if (value.version !== 1 || !['load', 'runtime', 'dispose', 'error'].includes(String(value.event)))
100
+ return false
101
+ if (typeof value.scene !== 'string' || value.scene.length < 1 || value.scene.length > 80)
102
+ return false
103
+ if (typeof value.path !== 'string' || value.path.length < 1 || value.path.length > 256)
104
+ return false
105
+ if (value.release != null && (typeof value.release !== 'string' || value.release.length > 128))
106
+ return false
107
+ if (
108
+ !isRecord(value.navigation) ||
109
+ typeof value.navigation.id !== 'string' ||
110
+ !isFiniteNumber(value.navigation.startTime)
111
+ )
112
+ return false
113
+ if (!isRecord(value.milestones) || !isRecord(value.milestones.phasesMs)) return false
114
+ if (
115
+ !isRecord(value.network) ||
116
+ !isFiniteNumber(value.network.requests) ||
117
+ !isFiniteNumber(value.network.transferBytes)
118
+ )
119
+ return false
120
+ if (
121
+ !isRecord(value.runtime) ||
122
+ !isFiniteNumber(value.runtime.sampleWindowMs) ||
123
+ !isFiniteNumber(value.runtime.frames)
124
+ )
125
+ return false
126
+ if (!isRecord(value.device) || !['high', 'standard', 'low'].includes(String(value.device.tier)))
127
+ return false
128
+ if (typeof value.device.mobile !== 'boolean' || !isFiniteNumber(value.device.devicePixelRatio))
129
+ return false
130
+ return true
131
+ }
132
+
133
+ export function parseScenePerformanceReport(value: unknown): ScenePerformanceReport | null {
134
+ return validReport(value) ? value : null
135
+ }
136
+
137
+ export function createSceneTelemetryEnvelope(
138
+ report: ScenePerformanceReport,
139
+ receivedAt = new Date(),
140
+ deployment = process.env.DEPLOY_GIT_COMMIT_SHA
141
+ ): SceneTelemetryEnvelope {
142
+ return {
143
+ receivedAt: receivedAt.toISOString(),
144
+ ...(deployment ? { deployment } : {}),
145
+ report,
146
+ }
147
+ }
148
+
149
+ type NavigationStart = {
150
+ id: string
151
+ url: string
152
+ startTime: number
153
+ type: 'navigate' | 'push' | 'replace' | 'traverse'
154
+ claimed?: boolean
155
+ }
156
+
157
+ declare global {
158
+ interface Window {
159
+ __ADEA_NAVIGATION_START__?: NavigationStart
160
+ __ADEA_SCENE_TELEMETRY_ENDPOINT__?: string
161
+ __ADEA_RELEASE__?: string
162
+ }
163
+ }
164
+
165
+ export function recordNavigation(
166
+ url: string,
167
+ type: 'navigate' | 'push' | 'replace' | 'traverse',
168
+ startTime: number
169
+ ): void {
170
+ window.__ADEA_NAVIGATION_START__ = {
171
+ id: `nav-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
172
+ url,
173
+ startTime,
174
+ type,
175
+ }
176
+ }
177
+
178
+ try {
179
+ const navigation = performance.getEntriesByType('navigation')[0] as
180
+ | PerformanceNavigationTiming
181
+ | undefined
182
+ recordNavigation(window.location.href, 'navigate', navigation?.startTime ?? 0)
183
+ const endpoint =
184
+ process.env.NEXT_PUBLIC_SCENE_TELEMETRY_ENDPOINT ||
185
+ (process.env.NODE_ENV === 'production' ? '/api/telemetry/scene-performance' : undefined)
186
+ if (endpoint) window.__ADEA_SCENE_TELEMETRY_ENDPOINT__ = endpoint
187
+ const release = process.env.NEXT_PUBLIC_DEPLOY_GIT_COMMIT_SHA
188
+ if (release) window.__ADEA_RELEASE__ = release
189
+ } catch {
190
+ // Telemetry must never interfere with page initialization.
191
+ }
192
+
193
+ export function onRouterTransitionStart(
194
+ url: string,
195
+ navigationType: 'push' | 'replace' | 'traverse'
196
+ ): void {
197
+ try {
198
+ recordNavigation(new URL(url, window.location.href).href, navigationType, performance.now())
199
+ } catch {
200
+ // Invalid route metadata should not affect navigation.
201
+ }
202
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": { "rootDir": "src", "outDir": "dist", "declaration": true },
4
+ "include": ["src"]
5
+ }