@forgeax/engine-remote 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +269 -0
  3. package/dist/.tsbuildinfo +1 -0
  4. package/dist/__tests__/asset-runtime-inspection.unit.test.d.ts +2 -0
  5. package/dist/__tests__/asset-runtime-inspection.unit.test.d.ts.map +1 -0
  6. package/dist/__tests__/console.unit.test.d.ts +2 -0
  7. package/dist/__tests__/console.unit.test.d.ts.map +1 -0
  8. package/dist/__tests__/errors.unit.test.d.ts +2 -0
  9. package/dist/__tests__/errors.unit.test.d.ts.map +1 -0
  10. package/dist/__tests__/execute-browser-safe.unit.test.d.ts +2 -0
  11. package/dist/__tests__/execute-browser-safe.unit.test.d.ts.map +1 -0
  12. package/dist/__tests__/execute-profiler-root.browser.test.d.ts +2 -0
  13. package/dist/__tests__/execute-profiler-root.browser.test.d.ts.map +1 -0
  14. package/dist/__tests__/execute.async.test.d.ts +2 -0
  15. package/dist/__tests__/execute.async.test.d.ts.map +1 -0
  16. package/dist/__tests__/execution-report-root.unit.test.d.ts +2 -0
  17. package/dist/__tests__/execution-report-root.unit.test.d.ts.map +1 -0
  18. package/dist/__tests__/introspect-profiler.unit.test.d.ts +2 -0
  19. package/dist/__tests__/introspect-profiler.unit.test.d.ts.map +1 -0
  20. package/dist/__tests__/method-roster-profiler.test.d.ts +2 -0
  21. package/dist/__tests__/method-roster-profiler.test.d.ts.map +1 -0
  22. package/dist/__tests__/rhi-capture-remote.integration.test.d.ts +2 -0
  23. package/dist/__tests__/rhi-capture-remote.integration.test.d.ts.map +1 -0
  24. package/dist/__tests__/server.unit.test.d.ts +2 -0
  25. package/dist/__tests__/server.unit.test.d.ts.map +1 -0
  26. package/dist/error-messages.d.ts +3 -0
  27. package/dist/error-messages.d.ts.map +1 -0
  28. package/dist/errors.d.ts +82 -0
  29. package/dist/errors.d.ts.map +1 -0
  30. package/dist/errors.mjs +37 -0
  31. package/dist/errors.mjs.map +1 -0
  32. package/dist/execute.d.ts +31 -0
  33. package/dist/execute.d.ts.map +1 -0
  34. package/dist/execute.mjs +93 -0
  35. package/dist/execute.mjs.map +1 -0
  36. package/dist/index.d.ts +2 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.mjs +30 -0
  39. package/dist/index.mjs.map +1 -0
  40. package/dist/introspect.d.ts +21 -0
  41. package/dist/introspect.d.ts.map +1 -0
  42. package/dist/introspect.mjs +173 -0
  43. package/dist/introspect.mjs.map +1 -0
  44. package/dist/server.d.ts +35 -0
  45. package/dist/server.d.ts.map +1 -0
  46. package/dist/server.mjs +473 -0
  47. package/dist/server.mjs.map +1 -0
  48. package/package.json +78 -0
  49. package/src/__tests__/asset-runtime-inspection.unit.test.ts +16 -0
  50. package/src/__tests__/console.unit.test.ts +12 -0
  51. package/src/__tests__/errors.unit.test.ts +102 -0
  52. package/src/__tests__/execute-browser-safe.unit.test.ts +43 -0
  53. package/src/__tests__/execute-profiler-root.browser.test.ts +41 -0
  54. package/src/__tests__/execute.async.test.ts +369 -0
  55. package/src/__tests__/execution-report-root.unit.test.ts +38 -0
  56. package/src/__tests__/introspect-profiler.unit.test.ts +55 -0
  57. package/src/__tests__/method-roster-profiler.test.ts +80 -0
  58. package/src/__tests__/rhi-capture-remote.integration.test.ts +58 -0
  59. package/src/__tests__/server.unit.test.ts +856 -0
  60. package/src/__tests__/vm-async-eval-verify.mjs +149 -0
  61. package/src/error-messages.ts +9 -0
  62. package/src/errors.ts +143 -0
  63. package/src/execute.ts +152 -0
  64. package/src/index.ts +19 -0
  65. package/src/introspect.ts +223 -0
  66. package/src/server.ts +331 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,269 @@
1
+ # @forgeax/engine-remote
2
+
3
+ > **Single capability — `eval` a live engine.** Send a JavaScript snippet to a running engine instance, have it executed against the live World / Renderer / AssetRegistry, and receive a structured result. Aligned with [Bevy BRP](https://github.com/bevyengine/bevy/discussions/15323) and [Unreal Remote Control](https://dev.epicgames.com/documentation/en-us/unreal-engine/remote-control-api-http-reference-for-unreal-engine) — "evaluate code against a live instance" rather than "attach a debugger UI panel." Four required roots plus the optional `profiler` root are injected into eval scope; `_import(specifier)` enables dynamic ESM imports. No Registry, no pre-built commands, no read-only sandbox. A `switch` over the closed `RemoteErrorCode` union is the only error vocabulary.
4
+
5
+ ```mermaid
6
+ flowchart LR
7
+ AI["AI User / CLI / In-Process"] -->|"eval(script)"| CORE["eval Core (host realm new Function)"]
8
+ CORE -.->|"host import resolver"| ECS["@forgeax/engine-ecs<br/>World.query / QueryRow"]
9
+ CORE --> ROOTS["Eval Scope Live Roots<br/>world · renderer · assets · rhiCapture"]
10
+ ROOTS --> W["Running World / Renderer"]
11
+ ```
12
+
13
+ ## Overview
14
+
15
+ `@forgeax/engine-remote` provides a **single execution channel**: send a script string, get a `Result<unknown, RemoteError>` back. The package ships as:
16
+
17
+ | Role | Entry | Shape |
18
+ |:--|:--|:--|
19
+ | In-process client | `client.eval(script)` | Direct `async` call within the host process — zero network overhead |
20
+ | WS JSON-RPC 2.0 server | `ws://localhost:<port>` `{"method":"eval","params":{"script":"..."}}` | Host embeds via `startRemoteServer`; external tools (CLI / AI agents) connect over WebSocket |
21
+
22
+ All three paths converge on the same `eval(script)` protocol. The `createApp` entry point wires the server by default in dev mode (`app.remote` is non-undefined, port > 0) and leaves it off in production — **the only safety boundary is whether the host starts the server.**
23
+
24
+ ```mermaid
25
+ sequenceDiagram
26
+ participant C as Client (in-process / WS / CLI)
27
+ participant S as Server (port 5732)
28
+ participant E as eval (host realm)
29
+ participant W as World / Renderer / Assets
30
+
31
+ C->>S: { method: "eval", params: { script: "…" } }
32
+ S->>E: new Function(world, renderer, assets, rhiCapture, _import, body)
33
+ E->>E: await _import('@forgeax/engine-ecs')
34
+ E->>W: world.query(descriptor)
35
+ W-->>E: Query row iteration
36
+ E-->>S: Promise<unknown>
37
+ S-->>C: { result: { ok: true, value } } or Error
38
+ ```
39
+
40
+ ## Eval Recipes
41
+
42
+ ### Script contract
43
+
44
+ **Your script is the body of an async function** with `world` / `renderer` / `assets` /
45
+ `rhiCapture` / `_import` in scope. Concretely:
46
+
47
+ - **A lone expression is auto-returned** — `renderer.backend` yields `"webgpu"` (a trailing
48
+ semicolon is fine).
49
+ - **Top-level `await` is legal** — `await _import('@forgeax/engine-ecs')` works directly, no wrapper.
50
+ - **Top-level `return` is legal** — `return world.inspect().entityCount`.
51
+ - **A multi-statement script uses an explicit `return`** for its value (a statement list is not
52
+ auto-returned): `const m = await _import('@forgeax/engine-ecs'); return Object.keys(m)`.
53
+
54
+ The historical `(async () => { ... })()` IIFE form still works (its returned Promise is awaited), but
55
+ is no longer necessary. If a returned value is a Promise it is awaited before being sent back.
56
+
57
+ ### Prerequisites
58
+
59
+ Three live engine roots are always present in eval scope. Diagnostics are structural optional roots:
60
+
61
+ | Root | Type | Purpose |
62
+ |:--|:--|:--|
63
+ | `world` | `World` (from `@forgeax/engine-ecs`) | ECS read/write: `spawn`, `despawn`, `set`, `query` |
64
+ | `renderer` | `Renderer` | Renderer control: create/destroy render targets, read backbuffer |
65
+ | `assets` | `AssetRegistry` | Asset queries: `load(guid, expectedKind)`, `snapshot()`, `subscribe(listener)` |
66
+ | `rhiCapture` | `{ captureFrame(options?) } \| undefined` | Single-frame RHI capture returning one `{ kind: 'rhi-tape', digest, bytes }` artifact. **Only defined when the app was created with `FORGEAX_ENGINE_RHI_DEBUG=1`** (else `undefined` — guard before use). Browser capture uses the same `window.__forgeax.captureFrame(options?)` capability. |
67
+ | `profiler` | `Profiler \| undefined` | Bounded CPU capture: `startCapture({ frameLimit, eventLimit })`. **Only defined when the host passes `profiler` to `createApp` or `startServer`.** |
68
+ | `execution` | `{ report(): unknown; rebuild(): Promise<unknown> } \| undefined` | App-owned execution report and explicit poisoned-World rebuild. Remote imports no App or ECS execution type. |
69
+
70
+ The `_import(specifier)` injection enables dynamic ESM imports inside eval scope. **Plain `import` keyword is NOT available**; scripts use `await _import('@forgeax/engine-ecs')` to pull in engine packages.
71
+
72
+ The App host's ECS import resolver is explicit: when the host exposes
73
+ `@forgeax/engine-ecs`, it projects only `World`, `Entity`, `Update`,
74
+ `FixedUpdate`, `Time`, and `FixedTime`. The remote transport owns no engine
75
+ package vocabulary; another host can inject a different resolver through
76
+ `startServer({ importModule })`. Other package exports are not transported by
77
+ the App ECS projection; use the owning package's public import when a script
78
+ needs another domain token.
79
+
80
+ > [!NOTE]
81
+ > `rhiCapture`, `profiler`, and `execution` are conditional capabilities. Guard each before use. `world`, `renderer`, and `assets` are always present.
82
+
83
+ ### Handle and component discovery
84
+
85
+ The World-owned row iterator is available directly in eval scope. An empty descriptor visits every enabled entity; component tokens grant typed data access.
86
+
87
+ ```js
88
+ const handlesQuery = world.query({});
89
+ if (!handlesQuery.ok) throw handlesQuery.error;
90
+ const handles = Array.from(handlesQuery.value, (row) => row.entity);
91
+
92
+ const { MeshRenderer } = await _import('@forgeax/engine-render');
93
+ const { Transform } = await _import('@forgeax/engine-scene');
94
+ const visibleQuery = world.query({ read: [Transform], with: [MeshRenderer] });
95
+ if (!visibleQuery.ok) throw visibleQuery.error;
96
+ const results = Array.from(visibleQuery.value, (row) => ({
97
+ entity: row.entity,
98
+ position: Array.from(row.get(Transform).pos),
99
+ }));
100
+ ```
101
+
102
+ `Transform.pos` is the flat `array<f32, 3>` column, so row `i` starts at
103
+ `i * 3`; the same stride rule applies to `quat` (4), `scale` (3), and other
104
+ fixed-array fields.
105
+
106
+ ### Write / Lifecycle
107
+
108
+ ```js
109
+ // Spawn with components
110
+ const scene = await _import('@forgeax/engine-scene');
111
+ const h = world.spawn({
112
+ component: scene.Transform,
113
+ data: { pos: [0, 5, 0], quat: [0, 0, 0, 1], scale: [1, 1, 1] },
114
+ }).unwrap();
115
+
116
+ // Set — mutate existing component values
117
+ world.set(h, scene.Transform, { pos: [1, 2, 3] });
118
+
119
+ // Despawn
120
+ world.despawn(h);
121
+ ```
122
+
123
+ > [!IMPORTANT]
124
+ > Eval is full-access — no write interception, no `inspector-write-denied` error code, no `ECS_MUTATING_METHODS` blacklist. `spawn` / `set` / `despawn` execute directly. See [Transport and Security](#transport-and-security) for the safety model.
125
+
126
+ ### Frame Capture via rhiCapture
127
+
128
+ ```js
129
+ // Capture the current steady-state frame
130
+ if (rhiCapture === undefined) return { ok: false, error: { code: 'capture-unavailable' } };
131
+ const capture = await rhiCapture.captureFrame();
132
+ if (!capture.ok) return capture;
133
+ // Pass this single artifact to `forgeax run rhi.summary` or `rhi.inspect`.
134
+ return { kind: capture.value.kind, digest: capture.value.digest };
135
+ ```
136
+
137
+ Offline operations (`rhi.summary` and `rhi.inspect`) do not connect over WebSocket and are not routed through eval. See `@forgeax/engine-rhi-debug` README for the full capture/summary/inspect workflow.
138
+
139
+ ### CPU profiling via profiler
140
+
141
+ When the host opts in, use the existing `eval` method to start and finish a bounded CPU capture.
142
+ There is no profiler-specific JSON-RPC method and no new transport:
143
+
144
+ ```js
145
+ if (profiler === undefined) {
146
+ return { ok: false, error: { code: 'profiler-not-enabled' } };
147
+ }
148
+ const started = profiler.startCapture({ frameLimit: 120, eventLimit: 1024 });
149
+ if (!started.ok) return started;
150
+ const finished = started.value.finish();
151
+ return finished;
152
+ ```
153
+
154
+ The returned `ProfileCapture` is suitable for `@forgeax/engine-profiler` validation and offline
155
+ CLI analysis. The root does not add ECS, GPU, UI, or network-trace behavior to the remote package.
156
+
157
+ ## RemoteErrorCode
158
+
159
+ `RemoteErrorCode` is a **5-member closed union**. TypeScript `switch (err.code)` exhaustiveness is enforced at compile time — no `default` branch. The JSON-RPC 2.0 numeric segment `-32001..-32005` maps 1:1 to the 5 members.
160
+
161
+ | code | JSON-RPC | `.expected` | `.hint` |
162
+ |:--|:--|:--|:--|
163
+ | `script-syntax-error` | -32001 | `'script body is valid JavaScript'` | `'check syntax position in errMessage; fix and resubmit'` |
164
+ | `script-runtime-error` | -32002 | `'script executes without throwing'` | `'inspect error; verify symbol availability; eval has full access to world/renderer/assets'` |
165
+ | `server-startup-failed` | -32003 | `'server starts successfully on requested port'` | `'check if port is already in use (default 5732); pass different port; or kill existing process holding the port'` |
166
+ | `server-not-running` | -32004 | `'server is reachable at ws://localhost:<port>'` | `'start the demo first; verify app.remote is wired; pass --port to override default 5732'` |
167
+ | `eval-result-not-serializable` | -32005 | `'eval result is JSON-serializable'` | `'return a JSON-safe value; BigInt and cyclic objects are unsupported over JSON-RPC'` |
168
+
169
+ Each `RemoteError` instance carries the structured triple (`.code` / `.expected` / `.hint`) plus an optional bounded `.detail` and an auto-composed `.message` for human stack traces. For `eval-result-not-serializable`, `.detail` contains only `{ code, shape }` where `shape` is `bigint`, `cyclic-object`, or `unsupported`; returned object contents never cross the error boundary. AI users consume via property access — never by parsing `.message`.
170
+
171
+ ```ts
172
+ import { RemoteError, type RemoteErrorCode } from '@forgeax/engine-remote';
173
+
174
+ function recover(code: RemoteErrorCode): string {
175
+ switch (code) {
176
+ case 'script-syntax-error': return 'fix script body syntax and resubmit';
177
+ case 'script-runtime-error': return 'inspect stack trace; verify symbol availability';
178
+ case 'server-startup-failed': return 'pick a different port or free port 5732';
179
+ case 'server-not-running': return 'start demo dev or wire app.remote';
180
+ case 'eval-result-not-serializable': return 'return a JSON-safe eval result';
181
+ }
182
+ }
183
+ ```
184
+
185
+ The SSOT split: the **type alias** `RemoteErrorCode` and **structural interface** `RemoteError` live in `@forgeax/engine-types` (parallel to `ShaderErrorCode`). The **runtime class** (`RemoteError extends Error implements RemoteErrorShape`) lives in `packages/remote/src/errors.ts`.
186
+
187
+ ```mermaid
188
+ stateDiagram-v2
189
+ direction LR
190
+ state "script body has syntax error" as scriptSyntaxError
191
+ state "script threw at runtime" as scriptRuntimeError
192
+ state "server cannot bind port" as serverStartupFailed
193
+ state "no server to connect to" as serverNotRunning
194
+ state "eval result cannot cross JSON-RPC" as evalResultNotSerializable
195
+ ```
196
+
197
+ ## Transport and Security
198
+
199
+ ### Transport Paths
200
+
201
+ ```mermaid
202
+ flowchart TD
203
+ subgraph InProcess["In-Process"]
204
+ A["app.remote → client.eval(script)"] --> E["eval (host realm)"]
205
+ end
206
+ subgraph WS["WebSocket"]
207
+ C["ws://localhost:5732<br/>JSON-RPC 2.0"] --> S["startRemoteServer"] --> E
208
+ end
209
+ E --> W["Live Engine State"]
210
+ ```
211
+
212
+ | Path | Method | Use Case |
213
+ |:--|:--|:--|
214
+ | In-process | `const result = await client.eval('world.inspect().entityCount')` | Host self-inspection; zero network cost |
215
+ | WebSocket | `ws://localhost:5732` send `{"method":"eval","params":{"script":"..."}}` | External AI agents / CLI tools attaching to a running **Node / dawn-node** app |
216
+ | Browser loopback relay (**remote-live**) | `POST http://127.0.0.1:5733/eval {"code":"..."}` → page dials the relay | Driving a **live browser** engine (`pnpm --filter <app> dev`, :5173) where no WS server can bind |
217
+
218
+ > **Browsers cannot host a WS server.** `startServer` uses `ws.WebSocketServer` (a Node listening socket), so it never starts in a browser — `createApp` catches the failure and `app.remote` stays `undefined`. To reach a running browser engine, `createApp` mounts a DEV-only bridge that dials OUT to a loopback relay and runs the ws-free eval core (`@forgeax/engine-remote/execute`) in the page realm. Start it with `node scripts/dev-live.mjs <app>` and drive it with `node skills/forgeax-engine-cli/scripts/remote-live.mjs "<code>"`. On by default in dev; opt out with `VITE_FORGEAX_ENGINE_BRIDGE=0`. Full recipe + security notes: the `forgeax-engine-cli` skill (§remote-live). This path is additive — it does not change the WS-server path or `app.remote` semantics.
219
+
220
+ The wire protocol exposes **two** JSON-RPC methods: `eval` (the single capability above) and `introspect`. Send `{"method":"introspect"}` to get an OpenRPC L2 subset document listing the available methods (`eval` / `introspect`) and the eval-scope live roots — an AI agent can self-describe the surface without reading source. Recoverable failures map to JSON-RPC error codes `-32001..-32005` (the 5-member `RemoteErrorCode` union; see above).
221
+
222
+ ### Security Model
223
+
224
+ > [!IMPORTANT]
225
+ > **The only safety boundary is whether the host starts the server.** Eval is full-access — no code-level interception, no method blacklist, no read-only proxy. Dangerous APIs (`renderer.dispose()` destroys GPU context and crashes the app; `world.despawn` can wipe all entities; `assets.dispose()` etc.) are executable inside eval.
226
+
227
+ | Mode | `app.remote` | Server running? | Safety |
228
+ |:--|:--|:--|:--|
229
+ | Dev (`import.meta.env.DEV`) | `RemoteHandle` (non-undefined, port > 0) | Yes — auto-started by `createApp` | **Developer's responsibility** — do not eval scripts containing destructive API calls |
230
+ | Production | `undefined` | No — `createApp` skips server startup | **Safe by default** — no eval entry point exists |
231
+ | Headless / dawn-node | `undefined` (default) | No — unless `FORGEAX_REMOTE_SERVER=1` opt-in | **Safe by default** — explicit opt-in required |
232
+
233
+ > [!CAUTION]
234
+ > **Dangerous API NOTE** — eval is full-access, read/write. Scripts can call `renderer.dispose()` (destroys GPU context, crashes the app), `world.despawn` (bulk-removes entities), `assets.dispose()`, and other destructive operations. The engine applies no code-level guard. Production safety comes from the server being off by default; dev safety relies on developer discipline. AI users: verify scripts do not contain destructive API calls before eval in dev mode.
235
+
236
+ ## Physical Isolation
237
+
238
+ The engine bundle is physically isolated from the remote package — `@forgeax/engine-remote` never imports `@forgeax/engine-{runtime,ecs,pack,gltf}`, and the engine bundle never references `@forgeax/engine-remote`. Six grep gates enforce this bidirectionally:
239
+
240
+ | Gate Script | Direction | What It Guards |
241
+ |:--|:--|:--|
242
+ | `check-engine-no-console-dep.mjs` | Engine -> Remote | Engine bundle (runtime/*) must not contain `@forgeax/engine-remote` literal or named leaks (`RemoteHandle`, `RemoteError`) |
243
+ | `check-console-not-in-engine-bundle.mjs` | Engine -> Remote | Engine dist bundle must not carry remote package literals |
244
+ | `check-console-not-import-engine.mjs` | Remote -> Engine | Remote package must not import `@forgeax/engine-{runtime,ecs,pack,gltf}` (4 surfaces: deps, peerDeps, src imports, literals) |
245
+ | `check-no-string-sugar.mjs` | Remote internal | No `buildXxxScript` string-sugar identifiers in remote `src/` |
246
+ | `check-no-cli-deps.mjs` | Remote internal | No commander/yargs/cac/sade deps in remote `package.json` |
247
+ | `check-readme-sections.mjs` | Remote internal | This README's 5 H2 section headings are character-exact present |
248
+ ## Injected component schemas
249
+
250
+ Quick start: call the existing `introspect` method, find
251
+ `components.schemas.Visibility`, then use the existing `eval` method with
252
+ `_import('@forgeax/engine-render')` and `_import('@forgeax/engine-ecs')` to
253
+ inspect a live entity.
254
+
255
+ The schema is host data projected from the app's registered ECS components. The
256
+ remote package merges it into OpenRPC `components.schemas` while preserving the
257
+ existing `eval` / `introspect` methods and the closed remote error mapping.
258
+
259
+ | Diagnostic | Meaning | Recovery |
260
+ |:--|:--|:--|
261
+ | Missing `Visibility` schema | The host did not inject post-plugin registry data | Start the app with remote enabled and inspect the host wiring |
262
+ | `current` differs from `effective` | Parent inheritance changed the render decision | Read `resolveVisibility(world).diagnostics` and `source` |
263
+ | Invalid write | ECS rejected a field value | Switch on the returned error `code`, then follow `expected`, `hint`, and `detail` |
264
+ | `visibilityStats` unchanged | No eligible render candidate was counted | Inspect the real entity and renderer path; do not add a remote method |
265
+
266
+ This is a JSON-safe reflection boundary, not a component registry in remote.
267
+ Remote production has no imports from ECS, render, or runtime and adds no RPC,
268
+ CLI, or MCP method. Camera, picking, lifecycle, assets, and VFX shadow policy
269
+ remain out of scope.