Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: expose bounded local Eidoverse scene inspection (#9821)

Adam Eivy9b41d1fddcb7
diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.md
index 2343c11b0a..080c691d01 100644
--- a/docs/features/eidoverse.md
+++ b/docs/features/eidoverse.md
@@ -356,6 +356,86 @@ source. Status requires bounded PortOS read access. Projection, augmentation,
and world chat retain the dedicated Eidoverse-management grant without widening
generic PortOS record-write authority.
+**Bounded local scene inspection.** `eidoverse.inspect-scene` (provider alias
+`eidoverse_inspect_scene`) requires `manageEidoverse` for minds and agents,
+using the same local world-management authority as augmentation. It reads the
+already admitted local connection; it never joins, starts the runtime, projects,
+places objects, visits a peer, or adds a federation channel. If disconnected,
+open/start the existing Eidoverse world through its normal controls first.
+
+Input is exactly `{ anchor: [x, y, z], radius, limit? }`: three finite coordinates
+in `[-10000,10000]`, spherical radius in `(0,100]`, integer limit `1..12`
+(default `8`), no extra keys. Use a new semantic `requestId` for a fresh read;
+replaying one returns its original result under the common dispatch contract.
+
+Output is exactly:
+
+```text
+{
+ availability: "current" | "unavailable" | "incomplete",
+ sequence: integer | null,
+ observedAt: ISO timestamp | null,
+ complete: boolean,
+ truncated: boolean,
+ boundsComplete: boolean,
+ unknownBounds: nonnegative integer,
+ invalidEntities: nonnegative integer,
+ entities: [{
+ id: stable entity id,
+ pos: [x,y,z], yaw: radians, scale: positive number,
+ asset: normalized library model reference | null,
+ portosManaged: boolean,
+ bounds: {min:[x,y,z], max:[x,y,z]} | null,
+ boundsState: "known" | "unknown"
+ }]
+}
+```
+
+`sequence` is the current authored log cut (including the snapshot's already
+folded tail), then advances with contiguous live updates. `observedAt` records
+when the response was assembled after draining received messages. Added, moved
+and removed entities come from those updates, rather than the join handshake.
+Sequence gaps, unknown spatial verbs and world resets invalidate completeness;
+a new valid snapshot restores it. Closed/failed connections and snapshots without
+a verifiable cut are unavailable. This is a point-in-time authored view, not a
+reservation against later movement or construction.
+
+Measured static model bounds become world AABBs by transforming all eight
+corners with the authored position, yaw and scale. Known boxes intersecting the
+sphere are returned even if their origin is outside it; entities with unknown
+bounds are selected by their authored origin. Model summaries must be finite,
+ordered, nondegenerate and within the coordinate range; transforms require a
+finite yaw within ±2000π and scale in `(0,100]`. Malformed transforms and
+parent-relative entities are omitted and counted in `invalidEntities`.
+
+`complete` means every selectable entity in this query was enumerated.
+`boundsComplete` additionally requires no invalid or unknown bounds **anywhere
+in the retained world view**, because an unmeasured object outside the query
+might extend into it. `unknownBounds` is that global count, not just returned
+rows. An empty list with incomplete enumeration or unknown extents never
+certifies an area clear. Even measured bounds describe authored model geometry,
+not terrain, avatars or the full rendered scene. Procedural components, motion,
+attachments, runtime behaviors and deterministic simulation are not evaluated;
+their geometry remains unknown. Unsupported component/dynamic flags stay
+conservative until a replacement spawn or fresh snapshot resolves them.
+
+Inspection retains at most 2000 authored entities (more means `incomplete`),
+fetches at most 16 unique model summaries per call with a shared two-second
+budget, and reads at most 64 KiB per summary. Failed or oversized summaries stay
+unknown. Whole result rows are capped at 3000 serialized characters, below the
+mind's 4000-character semantic envelope budget; count or character clipping sets
+`truncated: true` and `complete: false`. There is no pagination or clearance
+certificate. Use smaller spatial queries to inspect candidate anchors.
+
+Only `eidoverse/assets/models/...glb` library references and content-addressed
+`store/<16..64 lowercase hex>.glb` references can appear as `asset`; all other
+references become `null`. No raw component bags, record contents, chat, tickets,
+actor identities, URLs, filesystem paths, error bodies or credentials are
+exported. `portosManaged` reads only `comp.portos.managedBy === "portos"`;
+keep those existing projected objects intact. A small synthetic workflow uses
+five calls: status → inspect occupied anchor → inspect alternate anchor →
+augment original objects → inspect the result. Inspection itself places nothing.
+
**Proposal vs consequence.** `eidoverse.augment` is a two-phase contract, not a
direct write: a mind's call is a *proposal* (structured verb+args intent), and
only the world's own ack determines the *consequence*. The result's
diff --git a/server/lib/README.md b/server/lib/README.md
index 21859f4e2a..7c43ea58db 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -742,6 +742,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks with `.text()`, `.json()`, and a `headers.get` content-type), `startLoopbackServer(app)`/`closeLoopbackServer(server)`/`waitForAbort(signal)` for tests that need a real socket (raw disconnects, SSE streaming) that `request()`'s run-to-completion fetch harness can't model, plus the source-scan pair `collectServerSources()` / `readServerSource(rel)` (and `SERVER_DIR`) used by the whole-tree guard suites — `spawnCwd.test.js` (#3193) and `cliChildEnv.test.js` (#3194). Those guards overlap deliberately, so they share one definition of "a source file"; change the ignore rules here and both move together. Cross-platform trio: `posixPath(v)` normalizes a RECEIVED path before comparing it to a POSIX-spelled literal (no-op on POSIX — never normalize the expectation, which would hide a genuinely wrong path), and `resolveTestPython()` returns an interpreter that actually runs, probing by execution because Windows ships a `python` Store-alias stub that exists but fails; `null` when there is none, for `describe.skipIf`; `pinPlatform(value)` pins `process.platform` and returns a restore that reinstates the ORIGINAL descriptor (deleting the pin when there was none) — it carries the one hazard every hand-rolled pin had to rediscover: never pin above an import that loads a native addon, which picks its prebuilt binary off the platform at load time (#4085). Python-shelling suites also take their two nested budgets from here: `PY_TEST_TIMEOUT_MS` (vitest per-test, passed as `it()`'s third argument — a real interpreter's wall time tracks machine load, not the assertion, so a ~4s case crosses the tight global 10s `testTimeout` on a contended full-suite worker) and the strictly smaller `PY_SUBPROCESS_TIMEOUT_MS` (every `execFileSync` spawn's own `timeout`, so a hung interpreter trips the spawn guard first and names the command instead of producing a bare vitest timeout; a subprocess allowance ABOVE the vitest budget is dead intent — vitest always wins). |
| `fableLoomShots.js` | Short-shot grouping, spoken-dialogue timing estimates and 5–10 second render validation. |
+| `eidoverseSceneInspection.js` | Typed bounded local scene query, sequence-checked authored geometry view, safe asset references, and conservative world AABBs with explicit completeness and unknown extents. |
| `eidoverseCityLayout.js` | Native halls, rooftop landmark clearance and plinths, curated furniture, visitor chambers, and ordered signal bays for PortOS Commons. |
| `eidoverseCitySurface.js` | Deterministic GLB island scenery, pedestrian paths, gathering terraces, and physical district signs, stored through Eidoverse's content-addressed upload API. |
| `eidoverseIslandLandscape.js` | `appendEidoverseIslandLandscape` appends deterministic coastline, ocean, and distant mountain-island geometry to the Commons asset. |
diff --git a/server/lib/eidoverseSceneInspection.js b/server/lib/eidoverseSceneInspection.js
new file mode 100644
index 0000000000..57814a93f4
--- /dev/null
+++ b/server/lib/eidoverseSceneInspection.js
@@ -0,0 +1,172 @@
+/** Local authored geometry projection, not a renderer or a world-log export. */
+import { z } from 'zod';
+import { eidoverseModelBounds } from './eidoverseCityLayout.js';
+
+const coordinate = z.number().finite().min(-10000).max(10000);
+const vector = z.array(coordinate).length(3);
+export const eidoverseInspectSceneInputSchema = z.object({
+ anchor: vector,
+ radius: z.number().finite().positive().max(100),
+ limit: z.number().int().min(1).max(12).default(8),
+}).strict();
+const boxSchema = z.object({ min: vector, max: vector }).strict();
+export const eidoverseInspectSceneOutputSchema = z.object({
+ availability: z.enum(['current', 'unavailable', 'incomplete']),
+ sequence: z.number().int().min(-1).nullable(),
+ observedAt: z.string().nullable(),
+ complete: z.boolean(), truncated: z.boolean(), boundsComplete: z.boolean(),
+ unknownBounds: z.number().int().nonnegative(), invalidEntities: z.number().int().nonnegative(),
+ entities: z.array(z.object({
+ id: z.string().max(64), pos: vector, yaw: z.number().finite().min(-Math.PI * 2000).max(Math.PI * 2000),
+ scale: z.number().finite().positive().max(100),
+ asset: z.string().max(192).nullable(), portosManaged: z.boolean(),
+ bounds: boxSchema.nullable(), boundsState: z.enum(['known', 'unknown']),
+ }).strict()).max(12),
+}).strict();
+
+export const EIDOVERSE_SCENE_RESULT_MAX_CHARS = 3000;
+const MAX_SCENE_ENTITIES = 2000;
+const idPattern = /^[A-Za-z0-9_-]{1,64}$/;
+const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
+const validVector = (value) => vector.safeParse(value).success;
+
+/** Only library model references and content-addressed store models, never URLs. */
+export function eidoverseSceneAsset(value) {
+ if (typeof value !== 'string') return null;
+ const path = value.replaceAll('\\', '/');
+ if (path.length > 192 || path.split('/').some((part) => !part || part === '.' || part === '..')) return null;
+ return /^(?:eidoverse\/assets\/models\/[A-Za-z0-9_./-]+\.glb|store\/[a-f0-9]{16,64}\.glb)$/.test(path) ? path : null;
+}
+
+const projectEntity = (entity) => ({
+ pos: entity?.pos, yaw: entity?.yaw ?? 0, scale: entity?.scale ?? 1,
+ asset: eidoverseSceneAsset(entity?.lib),
+ portosManaged: entity?.comp?.portos?.managedBy === 'portos',
+ parentId: entity?.parent?.to ?? null,
+ light: entity?.kind === 'light',
+ // Component evaluators and parents can change rendered geometry. Do not
+ // interpret their bags, or claim a static model box covers their effects.
+ unsupported: Boolean(entity?.parent) || Object.keys(entity?.comp || {}).some((key) => !['portos', 'label'].includes(key)),
+});
+
+/** The snapshot state already includes its tail. Validate the cut, never replay it. */
+export function createEidoverseSceneView(snapshot) {
+ const view = { availability: 'unavailable', sequence: null, entities: new Map(), dynamic: false };
+ if (!record(snapshot?.state?.entities) || !Number.isSafeInteger(snapshot.throughSeq)
+ || snapshot.throughSeq < -1 || !Array.isArray(snapshot.entries)) return view;
+ let sequence = snapshot.throughSeq;
+ for (const entry of snapshot.entries) {
+ if (!Number.isSafeInteger(entry?.seq) || entry.seq !== sequence + 1) return view;
+ sequence = entry.seq;
+ }
+ view.sequence = sequence;
+ view.availability = 'current';
+ view.dynamic = Boolean(snapshot.state.epoch) || Object.keys(snapshot.state.behaviors || {}).length > 0;
+ for (const [id, entity] of Object.entries(snapshot.state.entities)) {
+ if (view.entities.size === MAX_SCENE_ENTITIES) { view.availability = 'incomplete'; break; }
+ view.entities.set(id, projectEntity(entity));
+ }
+ return view;
+}
+
+const nonSpatialVerbs = new Set(['genesis', 'say', 'grant', 'ban', 'unban', 'asset', 'terrain', 'grass', 'sky', 'weather', 'attest']);
+/** Fold only the supported authored entity vocabulary; gaps/new dialects fail closed. */
+export function updateEidoverseSceneView(view, entry) {
+ if (view.availability !== 'current') return;
+ if (!Number.isSafeInteger(entry?.seq) || entry.seq !== view.sequence + 1 || typeof entry.verb !== 'string') {
+ view.availability = 'incomplete'; return;
+ }
+ view.sequence = entry.seq;
+ const args = entry.args;
+ if (nonSpatialVerbs.has(entry.verb)) return;
+ if (!record(args)) { view.availability = 'incomplete'; return; }
+ const entity = view.entities.get(args.id);
+ switch (entry.verb) {
+ case 'spawn':
+ if (typeof args.id !== 'string' || !args.lib) { view.availability = 'incomplete'; break; }
+ if (!entity && view.entities.size >= MAX_SCENE_ENTITIES) { view.availability = 'incomplete'; break; }
+ view.entities.set(args.id, projectEntity({ ...args, pos: args.pos ?? [0, 0, 0] }));
+ break;
+ case 'place':
+ if (!entity) break;
+ if (args.pos !== undefined) entity.pos = args.pos;
+ if (args.yaw !== undefined) entity.yaw = args.yaw;
+ if (args.scale !== undefined) entity.scale = args.scale;
+ break;
+ case 'remove':
+ view.entities.delete(args.id);
+ // Attached children require renderer transforms; the view cannot
+ // reconstruct their dismount pose. Keep the enumeration incomplete.
+ for (const row of view.entities.values()) if (row.parentId === args.id) { row.pos = null; row.parentId = null; }
+ break;
+ case 'light':
+ if (!entity && view.entities.size >= MAX_SCENE_ENTITIES) { view.availability = 'incomplete'; break; }
+ view.entities.set(args.id, { ...(entity?.light ? entity : projectEntity({ kind: 'light', pos: [0, 1, 0] })),
+ ...(args.pos !== undefined ? { pos: args.pos } : {}), unsupported: true });
+ break;
+ case 'comp':
+ if (!entity) break;
+ if (args.type === 'portos') entity.portosManaged = args.data?.managedBy === 'portos';
+ else if (args.type !== 'label') entity.unsupported = true;
+ break;
+ case 'motion': case 'mount': case 'dismount':
+ if (entity) {
+ entity.unsupported = true;
+ if (entry.verb === 'mount') entity.parentId = args.to;
+ if (entry.verb === 'dismount') { entity.parentId = null; entity.pos = null; }
+ }
+ break;
+ case 'epoch': case 'behavior': case 'bstate': case 'force': case 'punt':
+ view.dynamic = true;
+ break;
+ default:
+ view.availability = 'incomplete';
+ }
+}
+
+/** Rotate all eight model-box corners into the world frame, then enclose them. */
+function occupiedBounds(entity, value) {
+ if (entity.unsupported) return null;
+ const box = eidoverseModelBounds(value);
+ if (!box || !validVector(box.min) || !validVector(box.max)) return null;
+ const corners = [];
+ for (const x of [box.min[0], box.max[0]]) for (const y of [box.min[1], box.max[1]]) for (const z of [box.min[2], box.max[2]]) {
+ corners.push([entity.pos[0] + entity.scale * (Math.cos(entity.yaw) * x + Math.sin(entity.yaw) * z),
+ entity.pos[1] + entity.scale * y,
+ entity.pos[2] + entity.scale * (-Math.sin(entity.yaw) * x + Math.cos(entity.yaw) * z)]);
+ }
+ const result = { min: [0, 1, 2].map((axis) => Math.min(...corners.map((v) => v[axis]))),
+ max: [0, 1, 2].map((axis) => Math.max(...corners.map((v) => v[axis]))) };
+ return validVector(result.min) && validVector(result.max) ? result : null;
+}
+
+export function buildEidoverseSceneInspection(view, input, { boundsByAsset = new Map(), observedAt = null } = {}) {
+ const { anchor, radius, limit } = eidoverseInspectSceneInputSchema.parse(input);
+ const result = { availability: view?.availability ?? 'unavailable', sequence: view?.sequence ?? null, observedAt,
+ complete: false, truncated: false, boundsComplete: false, unknownBounds: 0, invalidEntities: 0, entities: [] };
+ if (result.availability === 'unavailable') return result;
+ for (const [id, entity] of view.entities) {
+ if (!idPattern.test(id) || entity.parentId || !validVector(entity.pos) || !Number.isFinite(entity.yaw) || Math.abs(entity.yaw) > Math.PI * 2000
+ || !Number.isFinite(entity.scale) || entity.scale <= 0 || entity.scale > 100) {
+ result.invalidEntities++; continue;
+ }
+ const bounds = view.dynamic ? null : occupiedBounds(entity, boundsByAsset.get(entity.asset));
+ if (!bounds) result.unknownBounds++;
+ // Known large objects can overlap the query even when their origin does
+ // not. Unknown extents anywhere in the world preclude a clearance claim.
+ const distanceSquared = anchor.reduce((sum, n, axis) => {
+ const nearest = bounds ? Math.max(bounds.min[axis], Math.min(bounds.max[axis], n)) : entity.pos[axis];
+ return sum + (n - nearest) ** 2;
+ }, 0);
+ if (distanceSquared > radius ** 2) continue;
+ const row = { id, pos: [...entity.pos], yaw: entity.yaw, scale: entity.scale, asset: entity.asset,
+ portosManaged: entity.portosManaged, bounds, boundsState: bounds ? 'known' : 'unknown' };
+ if (result.entities.length >= limit || JSON.stringify({ ...result, entities: [...result.entities, row] }).length > EIDOVERSE_SCENE_RESULT_MAX_CHARS - 100) {
+ result.truncated = true; continue;
+ }
+ result.entities.push(row);
+ }
+ result.complete = result.availability === 'current' && !result.truncated && !result.invalidEntities;
+ result.boundsComplete = result.complete && !result.unknownBounds;
+ return result;
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index fa2a0d6f3b..747ca3f0d0 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -718,6 +718,7 @@ export * from './testHelper.js';
export * from './videoFailure.js';
export * from './eidoverseCityLayout.js';
+export * from './eidoverseSceneInspection.js';
export * from './eidoverseCitySurface.js';
export * from './fableLoomShots.js';
export * from './eidoverseIslandLandscape.js';
diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.js
index 80c6a29321..37a0c349d7 100644
--- a/server/services/cosToolRegistry.js
+++ b/server/services/cosToolRegistry.js
@@ -15,6 +15,7 @@ import { zodToOpenApiSchema } from '../lib/apiContractSchemas.js';
import { canonicalStringify } from '../lib/objects.js';
import { sha256Text } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
+import { eidoverseInspectSceneInputSchema, eidoverseInspectSceneOutputSchema } from '../lib/eidoverseSceneInspection.js';
import {
normalizePersistentMindCapabilities,
persistentMindCleanupRequestSchema,
@@ -382,6 +383,17 @@ const eidoverseProjectTool = Object.freeze({
adapter: { kind: 'eidoverse-world', operation: 'project' },
});
+const eidoverseInspectSceneTool = Object.freeze({
+ type: 'portos_tool', name: 'eidoverse.inspect-scene', version: COS_TOOL_SCHEMA_VERSION,
+ providerName: providerToolName('eidoverse.inspect-scene'), aliases: [providerToolName('eidoverse.inspect-scene')],
+ description: 'Inspect authored entities in this install\'s admitted private world before construction. Input {anchor:[x,y,z],radius,limit?}: coordinates ±10000, radius (0,100], limit 1–12 (default 8). Returns stable ids, authored transforms, safe asset references, PortOS-managed markers and world AABBs where measured. Known boxes intersect the sphere; unknown boxes are selected by origin. complete covers enumeration only; boundsComplete also requires no unknown extents anywhere in the snapshot. Unavailable, incomplete, truncated, invalidEntities>0 or unknownBounds>0 NEVER certifies an area clear. Motion, attachments, procedural components and simulation are not evaluated; terrain, avatars and rendered animation are outside this inspection. No remote inspection, raw components or private record content. Use a new requestId for a fresh read.',
+ input_schema: zodToOpenApiSchema(eidoverseInspectSceneInputSchema),
+ output_schema: zodToOpenApiSchema(eidoverseInspectSceneOutputSchema),
+ policy: { scopes: ['agent', 'mind', 'ui'], requiredCapabilities: ['manageEidoverse'], sideEffect: 'read',
+ idempotent: true, async: false, confirmation: 'capability-grant' },
+ adapter: { kind: 'eidoverse-world', operation: 'inspect-scene' },
+});
+
const eidoverseAugmentTool = Object.freeze({
type: 'portos_tool',
name: 'eidoverse.augment',
@@ -534,7 +546,7 @@ const eidoverseControllerTools = [
idempotent: sideEffect === 'read', async: false, confirmation: 'capability-grant' },
adapter: { kind: 'eidoverse-controllers', operation },
}));
-const eidoverseTools = [eidoverseObserveTool, ...eidoverseTravelTools, ...eidoverseFoundationTools, ...eidoverseCreativeTools, ...eidoverseControllerTools, eidoverseStatusTool, eidoverseProjectTool, eidoverseAugmentTool, eidoverseSayTool];
+const eidoverseTools = [eidoverseObserveTool, ...eidoverseTravelTools, ...eidoverseFoundationTools, ...eidoverseCreativeTools, ...eidoverseControllerTools, eidoverseStatusTool, eidoverseInspectSceneTool, eidoverseProjectTool, eidoverseAugmentTool, eidoverseSayTool];
const thinkingTools = ['mind.thinking-presets', 'mind.request-thinking-preset'].map((name, index) => ({
type: 'portos_tool', name, version: COS_TOOL_SCHEMA_VERSION,
providerName: providerToolName(name), aliases: [],
@@ -1151,6 +1163,7 @@ const executeAdapter = async (tool, args, context, authority) => {
if (tool.adapter.kind === 'eidoverse-world') {
const world = await import('./eidoverseWorld.js');
if (tool.adapter.operation === 'status') return world.getEidoverseWorldStatus({ compact: true });
+ if (tool.adapter.operation === 'inspect-scene') return world.inspectEidoverseScene(args, { signal: context.signal });
if (tool.adapter.operation === 'project') return world.projectEidoverseWorld({ signal: context.signal, compact: true });
if (tool.adapter.operation === 'augment') return world.augmentEidoverseWorld(args.operations, { signal: context.signal });
return world.sayInEidoverseWorld(args.text, { signal: context.signal });
diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.js
index 5dbede6271..58bb254ac1 100644
--- a/server/services/cosToolRegistry.test.js
+++ b/server/services/cosToolRegistry.test.js
@@ -369,6 +369,7 @@ describe('cosToolRegistry', () => {
'eidoverse.arm-controller',
'eidoverse.retire-controller',
'eidoverse.status',
+ 'eidoverse.inspect-scene',
'eidoverse.project',
'eidoverse.augment',
'eidoverse.say',
diff --git a/server/services/eidoverseWorld.js b/server/services/eidoverseWorld.js
index 356a704049..0bb9add55f 100644
--- a/server/services/eidoverseWorld.js
+++ b/server/services/eidoverseWorld.js
@@ -12,6 +12,7 @@ import { eidoverseWorldEvents } from './eidoverseWorldEvents.js';
import { scrubSecretTokens } from '../lib/secretText.js';
import { buildEidoverseCitySurface } from '../lib/eidoverseCitySurface.js';
import { eidoverseModelBounds } from '../lib/eidoverseCityLayout.js';
+import { buildEidoverseSceneInspection, createEidoverseSceneView, eidoverseInspectSceneInputSchema, updateEidoverseSceneView } from '../lib/eidoverseSceneInspection.js';
import { createHash, randomUUID } from 'node:crypto';
import { join } from 'node:path';
import { WebSocket } from 'ws';
@@ -684,6 +685,7 @@ function createWorldConnection({ world, id, avatar, agent = true, guest = false,
let openSettled = false;
let snapshotSettled = false;
let snapshotValue = null;
+ let sceneView = createEidoverseSceneView(null);
const occupiedIdentities = new Set();
let closeTimer = null;
let openTimer = null;
@@ -748,6 +750,7 @@ function createWorldConnection({ world, id, avatar, agent = true, guest = false,
const fail = (error, fallback) => {
const normalized = asConnectionError(error, fallback);
failure ||= normalized;
+ sceneView.availability = 'unavailable';
settleOpen(failure);
settleSnapshot(null, failure);
rejectPending(failure);
@@ -769,14 +772,18 @@ function createWorldConnection({ world, id, avatar, agent = true, guest = false,
try {
message = JSON.parse(String(raw));
} catch {
+ sceneView.availability = 'incomplete';
return;
}
if (message?.type === 'snapshot') {
+ sceneView = createEidoverseSceneView(message);
for (const key of [...Object.keys(message.state?.roles || {}), ...Object.keys(message.state?.entities || {})]) occupiedIdentities.add(key);
settleSnapshot(message);
return;
}
+ if (message?.type === 'world-reset') sceneView.availability = 'incomplete';
+ if (message?.type === 'log') updateEidoverseSceneView(sceneView, message.entry);
if (message?.type === 'error') {
fail(new ServerError(String(message.error || 'Eidoverse rejected the request.'), {
status: 409,
@@ -932,6 +939,11 @@ function createWorldConnection({ world, id, avatar, agent = true, guest = false,
close,
isOpen: () => !closed && socket.readyState === WebSocket.OPEN,
getSnapshot: () => snapshotValue,
+ getSceneView: async () => {
+ await messageTail;
+ return structuredClone({ ...sceneView,
+ availability: closed || failure || socket.readyState !== WebSocket.OPEN ? 'unavailable' : sceneView.availability });
+ },
hasIdentity: (name) => occupiedIdentities.has(name),
readChat: (after = -1) => {
const unread = chat.filter((entry) => entry.seq > after);
@@ -1265,6 +1277,48 @@ export async function ensureEidoverseWorldPresence({ verbIntervalMs } = {}) {
});
}
+// Inspection never joins, starts, grants, projects, or visits a peer. It reads
+// the already admitted LOCAL connection and fetches bounded model summaries.
+export async function inspectEidoverseScene(input, { signal } = {}) {
+ const args = eidoverseInspectSceneInputSchema.parse(input);
+ throwIfAborted(signal);
+ const connection = cosPresence?.connection;
+ if (!connection?.isOpen()) return buildEidoverseSceneInspection(null, args);
+ const view = await connection.getSceneView();
+ if (view.availability !== 'current') return buildEidoverseSceneInspection(view, args);
+ const boundsByAsset = new Map();
+ const assets = [...new Set([...view.entities.values()].map((entity) => entity.asset).filter(Boolean))].slice(0, 16);
+ const geometrySignal = AbortSignal.any([AbortSignal.timeout(2000), ...(signal ? [signal] : [])]);
+ // No reusable cache: a mutable library reference may have changed since
+ // the last inspection. Missing, oversized, or timed-out summaries stay unknown.
+ await Promise.all(assets.map(async (asset) => {
+ try {
+ const response = await fetch(libraryUrl('/geom', { lib: asset }), { signal: geometrySignal, redirect: 'error' });
+ if (!response.ok) { await response.body?.cancel(); return; }
+ const reader = response.body?.getReader();
+ if (!reader) return;
+ const chunks = [];
+ let size = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > 65536) { await reader.cancel(); return; }
+ chunks.push(Buffer.from(value));
+ }
+ } finally { reader.releaseLock(); }
+ const bounds = eidoverseModelBounds(JSON.parse(Buffer.concat(chunks).toString('utf8'))?.bbox);
+ if (bounds) boundsByAsset.set(asset, bounds);
+ } catch {
+ // Never export runtime error bodies, URLs, or credentials as evidence.
+ }
+ }));
+ throwIfAborted(signal);
+ const latest = await connection.getSceneView();
+ return buildEidoverseSceneInspection(latest, args, { boundsByAsset, observedAt: new Date().toISOString() });
+}
+
const libraryUrl = (path, query = null) => {
const url = new URL(path, resolveWorldHttpUrl());
for (const [key, value] of Object.entries(query || {})) url.searchParams.set(key, value);
diff --git a/server/services/eidoverseWorld.runtime.test.js b/server/services/eidoverseWorld.runtime.test.js
index bb890c3fb9..1bbe3ec24c 100644
--- a/server/services/eidoverseWorld.runtime.test.js
+++ b/server/services/eidoverseWorld.runtime.test.js
@@ -85,6 +85,13 @@ vi.mock('./instanceFeatures.js', () => ({
})),
}));
+// Exercise the public semantic dispatcher with the REAL world adapter; these
+// unrelated adapters must never reach live instance data. All-schema grants
+// bypass lease bookkeeping for these calls.
+vi.mock('./voice/tools.js', () => ({ getToolSpecs: () => [], getToolSpecsForIntent: () => ({ specs: [] }), dispatchTool: vi.fn() }));
+vi.mock('./persistentMindTaskCapability.js', () => ({ executePersistentMindTaskRequests: vi.fn() }));
+vi.mock('./persistentMindMaintenance.js', () => ({ cleanupPersistentMind: vi.fn() }));
+
vi.mock('ws', () => {
class FakeWebSocket {
static OPEN = 1;
@@ -124,7 +131,7 @@ vi.mock('ws', () => {
if (message.type === 'join') {
this.identity = message.id;
this.world = message.world;
- const state = mocks.worlds.get(message.world) || { roles: {} };
+ const state = mocks.worlds.get(message.world) || { roles: {}, entities: {} };
if (!Object.keys(state.roles).length) state.roles[message.id] = { role: 'owner' };
else state.roles[message.id] ||= { role: 'visitor' };
mocks.worlds.set(message.world, state);
@@ -133,6 +140,7 @@ vi.mock('ws', () => {
callback?.(null);
this.emit('message', JSON.stringify({
type: 'snapshot',
+ throughSeq: mocks.nextSeq - 1, entries: [],
yourRights: { role: state.roles[message.id].role, gen: false },
state: structuredClone(state),
}));
@@ -223,8 +231,12 @@ const world = new Proxy(rawWorld, {
},
});
const { EIDOVERSE_WORLD_DESIGN_V1 } = await import('../lib/eidoverseWorldDesign.js');
+const { executeCosToolCall, getCosToolCatalog, __testing: semanticTesting } = await import('./cosToolRegistry.js');
+const { eidoverseInspectSceneOutputSchema } = await import('../lib/eidoverseSceneInspection.js');
beforeEach(async () => {
+ semanticTesting.toolCalls.clear();
+ semanticTesting.toolCallFingerprints.clear();
vi.unstubAllEnvs();
await world.__resetEidoverseWorldForTests();
mocks.persistedState = null;
@@ -1320,3 +1332,168 @@ it('reserves names seen in live grants after the resident snapshot and bounds co
const guest = await world.admitEidoverseGuest({ name });
expect(guest.identity.name).toBe(`${name.slice(0, 60)} (2)`);
});
+
+describe('bounded scene inspection through semantic dispatch', () => {
+ const authority = { scope: 'mind', capabilities: { manageEidoverse: true, readPortos: true, toolExposureAllSchemas: true } };
+ let callIndex = 0;
+ const dispatch = (name, args = {}, grants = authority) => executeCosToolCall({
+ call: { requestId: `scene-contract-${++callIndex}`, name, arguments: args }, authority: grants,
+ });
+ const inspect = async (args = { anchor: [0, 0, 0], radius: 5 }) => {
+ const response = await dispatch('eidoverse.inspect-scene', args);
+ expect(response.state).toBe('completed');
+ expect(JSON.stringify(response).length).toBeLessThan(4000);
+ eidoverseInspectSceneOutputSchema.parse(response.result);
+ return response.result;
+ };
+ const seed = async (entities, extra = {}) => {
+ mocks.worlds.set('portos', { roles: {}, entities, ...extra });
+ await world.ensureEidoverseWorldPresence();
+ };
+ const model = (pos = [0, 0, 0], extra = {}) => ({ lib: 'eidoverse/assets/models/example.glb', pos, ...extra });
+ const emit = (verb, args) => {
+ const socket = mocks.sockets.findLast((row) => row.identity === 'portos-cos' && row.readyState === 1);
+ socket.emit('message', JSON.stringify({ type: 'log', entry: { seq: mocks.nextSeq++, actor: 'synthetic-builder', verb, args } }));
+ };
+
+ it('finds an existing structure, selects another anchor and submits an original build in five calls', async () => {
+ await seed({ 'existing-structure': model([0, 0, 0], { comp: { portos: { managedBy: 'portos', privateRecord: 'synthetic-private-record' } } }) });
+ // This is a synthetic workflow only, never a live placement.
+ await dispatch('eidoverse.status');
+ const occupied = await inspect();
+ expect(occupied).toMatchObject({ availability: 'current', complete: true, boundsComplete: true, unknownBounds: 0 });
+ expect(occupied.entities).toEqual([expect.objectContaining({ id: 'existing-structure', portosManaged: true,
+ bounds: { min: [-1, 0, -1], max: [1, 2, 1] }, boundsState: 'known' })]);
+ const anchor = [20, 0, 0];
+ expect((await inspect({ anchor, radius: 3 })).entities).toEqual([]);
+ const submitted = await dispatch('eidoverse.augment', { operations: [{ verb: 'spawn', args: {
+ id: 'original-example', lib: occupied.entities[0].asset, pos: anchor, yaw: 0, scale: 1,
+ } }] });
+ expect(submitted.result.operations[0].outcome).toBe('accepted');
+ expect((await inspect({ anchor, radius: 3 })).entities[0].id).toBe('original-example');
+ });
+
+ it('reflects live added, moved, and removed objects and rotation/scale rather than the handshake', async () => {
+ await seed({});
+ emit('spawn', { id: 'live-model', lib: 'eidoverse/assets/models/example.glb', pos: [10, 0, 0], yaw: Math.PI / 2, scale: 2 });
+ // Origin outside the sphere, measured box overlaps its edge.
+ const added = await inspect({ anchor: [7, 0, 0], radius: 1 });
+ expect(added.entities[0]).toMatchObject({ id: 'live-model', scale: 2 });
+ expect(added.entities[0].bounds.min[0]).toBeCloseTo(8);
+ expect(added.entities[0].bounds.max[1]).toBe(4);
+ emit('place', { id: 'live-model', pos: [30, 0, 0] });
+ expect((await inspect()).entities).toEqual([]);
+ expect((await inspect({ anchor: [30, 0, 0], radius: 2 })).entities).toHaveLength(1);
+ emit('remove', { id: 'live-model' });
+ expect(await inspect({ anchor: [30, 0, 0], radius: 2 })).toMatchObject({ entities: [], complete: true, boundsComplete: true });
+ });
+
+ it('denies missing grants, validates strict bounded inputs, and publishes a typed schema', async () => {
+ await expect(dispatch('eidoverse.inspect-scene', { anchor: [0, 0, 0], radius: 1 }, { scope: 'mind', capabilities: { readPortos: true } }))
+ .rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });
+ for (const args of [
+ { anchor: [0, 0], radius: 1 }, { anchor: [Infinity, 0, 0], radius: 1 }, { anchor: [10001, 0, 0], radius: 1 },
+ { anchor: [0, 0, 0], radius: 0 }, { anchor: [0, 0, 0], radius: 101 }, { anchor: [0, 0, 0], radius: 1, limit: 13 },
+ { anchor: [0, 0, 0], radius: 1, limit: 0 }, { anchor: [0, 0, 0], radius: 1, limit: 1.5 },
+ { anchor: [0, 0, 0], radius: 1, peerId: 'example-peer' },
+ ]) await expect(dispatch('eidoverse.inspect-scene', args)).rejects.toMatchObject({ code: 'TOOL_VALIDATION_ERROR' });
+ expect(mocks.sent).toEqual([]);
+ const tool = getCosToolCatalog({ scope: 'mind', capabilities: authority.capabilities }).tools.find((row) => row.name === 'eidoverse.inspect-scene');
+ expect(tool).toMatchObject({ granted: true, output_schema: { properties: { complete: { type: 'boolean' } } } });
+ });
+
+ it('bounds dense results without exporting components, chat, tickets, credentials or arbitrary paths', async () => {
+ const entities = Object.fromEntries(Array.from({ length: 30 }, (_, n) => [`model-${n}`, model([0, 0, 0], {
+ actor: 'synthetic-private-person', comp: { portos: { managedBy: 'portos', ticket: 'synthetic-private-ticket', token: 'Bearer synthetic-secret' },
+ label: { description: 'synthetic-private-description' } },
+ })]));
+ entities['unsafe-asset'] = model([20, 0, 0], { lib: 'https://example.com/private?token=synthetic-secret' });
+ entities['unsafe-path'] = model([20, 0, 0], { lib: '/private/example/model.glb' });
+ await seed(entities, { recentChat: [{ text: 'synthetic-private-chat' }] });
+ const dense = await inspect({ anchor: [0, 0, 0], radius: 5, limit: 12 });
+ expect(dense).toMatchObject({ complete: false, truncated: true, boundsComplete: false, unknownBounds: 2 });
+ expect(dense.entities.length).toBeLessThanOrEqual(12);
+ expect(JSON.stringify(dense).length).toBeLessThanOrEqual(3000);
+ expect(JSON.stringify(dense)).not.toMatch(/synthetic-private|synthetic-secret|https:|\/private\/|"comp":|recentChat/);
+ expect((await inspect({ anchor: [0, 0, 0], radius: 5, limit: 1 })).entities).toHaveLength(1);
+ const unsafe = await inspect({ anchor: [20, 0, 0], radius: 1 });
+ expect(unsafe.entities).toHaveLength(2);
+ expect(unsafe.entities.every((row) => row.asset === null && row.bounds === null)).toBe(true);
+ });
+
+ it('keeps missing, malformed, procedural, dynamic and out-of-range geometry explicitly unknown', async () => {
+ await seed({
+ missing: model([0, 0, 0], { lib: 'store/aaaaaaaaaaaaaaaa.glb' }),
+ procedural: model([0, 0, 0], { comp: { structure: { privateDescription: 'synthetic-private' } } }),
+ far: model([500, 0, 0], { lib: 'store/bbbbbbbbbbbbbbbb.glb' }),
+ invalid: model([0, 0, 0], { scale: 101 }),
+ mounted: model([0, 0, 0], { parent: { to: 'procedural' } }),
+ });
+ vi.stubGlobal('fetch', vi.fn(async (input) => {
+ const url = new URL(String(input));
+ if (url.searchParams.get('lib')?.startsWith('store/')) return Response.json({ bbox: { min: [2, 0, 0], max: [1, 1, 1] }, secret: 'Bearer synthetic-secret' });
+ return Response.json({ bbox: { min: [-1, 0, -1], max: [1, 2, 1] } });
+ }));
+ const result = await inspect();
+ expect(result).toMatchObject({ complete: false, boundsComplete: false, unknownBounds: 3, invalidEntities: 2 });
+ expect(result.entities.every((row) => row.bounds === null && row.boundsState === 'unknown')).toBe(true);
+ expect(result.entities.find((row) => row.id === 'missing').asset).toBe('store/aaaaaaaaaaaaaaaa.glb');
+ expect(JSON.stringify(result)).not.toContain('synthetic-secret');
+ emit('place', { id: 'missing', pos: [20000, 0, 0] });
+ expect((await inspect()).invalidEntities).toBe(3);
+ });
+
+ it('distinguishes disconnected, sequence gaps, reset and invalid snapshots from empty current geometry', async () => {
+ expect(await inspect()).toMatchObject({ availability: 'unavailable', complete: false, boundsComplete: false, entities: [] });
+ expect(mocks.sent).toEqual([]);
+ await seed({ existing: model() });
+ const socket = mocks.sockets.findLast((row) => row.identity === 'portos-cos');
+ // State includes the tail already: a stale spawn in the tail must NOT undo
+ // a later move reflected in the snapshot state.
+ socket.emit('message', JSON.stringify({ type: 'snapshot', throughSeq: 10,
+ entries: [{ seq: 11, verb: 'spawn', args: { id: 'existing', pos: [0, 0, 0] } }],
+ state: { entities: { existing: model([20, 0, 0]) } } }));
+ expect(await inspect()).toMatchObject({ availability: 'current', sequence: 11, entities: [] });
+ socket.emit('message', JSON.stringify({ type: 'log', entry: { seq: 13, verb: 'remove', args: { id: 'existing' } } }));
+ expect(await inspect()).toMatchObject({ availability: 'incomplete', complete: false, boundsComplete: false });
+ socket.emit('message', JSON.stringify({ type: 'snapshot', throughSeq: 13, entries: [], state: { entities: {} } }));
+ expect((await inspect()).complete).toBe(true);
+ socket.emit('message', JSON.stringify({ type: 'world-reset' }));
+ expect((await inspect()).availability).toBe('incomplete');
+ socket.emit('message', JSON.stringify({ type: 'snapshot', state: { entities: {} } }));
+ expect((await inspect()).availability).toBe('unavailable');
+ socket.emit('message', JSON.stringify({ type: 'snapshot', throughSeq: 13, entries: [], state: {
+ entities: Object.fromEntries(Array.from({ length: 2001 }, (_, n) => [`dense-${n}`, model()])),
+ } }));
+ expect(await inspect({ anchor: [9000, 0, 0], radius: 1 })).toMatchObject({ availability: 'incomplete', complete: false, boundsComplete: false });
+ socket.close();
+ expect((await inspect()).availability).toBe('unavailable');
+ });
+
+ it('caps geometry requests and bodies, and treats renderer motion as unknown', async () => {
+ await seed(Object.fromEntries(Array.from({ length: 20 }, (_, n) => [`asset-${n}`, {
+ lib: `store/${n.toString(16).padStart(16, '0')}.glb`, pos: [0, 0, 0],
+ }])));
+ vi.stubGlobal('fetch', vi.fn(async () => Response.json({ bbox: { min: [-1, 0, -1], max: [1, 2, 1] }, oversized: 'x'.repeat(66000) })));
+ const oversized = await inspect();
+ expect(fetch).toHaveBeenCalledTimes(16);
+ expect(oversized).toMatchObject({ unknownBounds: 20, boundsComplete: false, truncated: true });
+ vi.stubGlobal('fetch', vi.fn(async () => Response.json({ bbox: { min: [-1, 0, -1], max: [1, 2, 1] } })));
+ expect((await inspect()).unknownBounds).toBe(4);
+ emit('motion', { id: 'asset-0', type: 'spin', speed: 1 });
+ expect((await inspect()).entities.find((row) => row.id === 'asset-0').boundsState).toBe('unknown');
+ emit('epoch', { sim: 'example-sim', tickMs: 66 });
+ expect((await inspect()).unknownBounds).toBe(20);
+ });
+
+ it('does not let failed geometry or an update during geometry loading certify old occupancy', async () => {
+ await seed({ existing: model() });
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('Bearer synthetic-secret', { status: 503 })));
+ expect(await inspect()).toMatchObject({ unknownBounds: 1, boundsComplete: false });
+ vi.stubGlobal('fetch', vi.fn(async () => {
+ emit('place', { id: 'existing', pos: [20, 0, 0] });
+ return Response.json({ bbox: { min: [-10001, 0, -1], max: [1, 2, 1] } });
+ }));
+ expect(await inspect()).toMatchObject({ entities: [], unknownBounds: 1, boundsComplete: false });
+ });
+});