phase 1c-extract: typed kRPC service client + SpaceCenter extract

Built the missing piece that connects the ksp-bridge to a real KSP
instance via kRPC. This adds a typed service client on top of the
existing KRPCClient, plus the SpaceCenter-specific extraction logic
that pulls the universe state from a running KSP save.

@kerbal-rt/krpc-client
- types.ts — runtime representation of kRPC Type descriptors
  (TypeCode enum, KrpcType interface, decodeKrpcType, typeName)
- decoder.ts — kRPC value codec: primitive decode/encode, class refs,
  enums, collections (LIST/SET/TUPLE/DICTIONARY), system messages
  (STATUS/SERVICES/STREAM/EVENT/PROCEDURE_CALL). 34 unit tests.
- services.ts — ServiceCache built from KRPC.GetServices() response.
  Lookup by (service, procedure), enum value/name resolution. 12 tests.
- service-client.ts — KrpcServices: high-level invoke-by-name client.
  loadServices() helper to connect + load catalog. 9 integration tests
  with a mock kRPC server.
- schema.ts — added Set/Dictionary/Event/Expression types so the
  decoder can handle system messages without external .proto files.
  Also fixed a bug where 'STREAM' was being encoded as 0 due to
  protobufjs's nested-enum string lookup.

ksp-bridge
- extract.ts — the actual SpaceCenter calls. ~280 procedure calls
  per poll for a typical KSP save (UT, bodies, vessels, then per-body
  and per-vessel class methods in parallel). Build the UniverseSnapshot.
- krpc-adapter.ts — rewrote to use KrpcServices (typed) instead of
  the stub extract function. Supports an optional injected services
  for testing.
- bridge.ts — uses the new ExtractedState type and buildSnapshot.
- index.ts — connects to kRPC; falls back to mock mode if no server.
- convert.ts — backward-compat shim, re-exports from extract.ts.

The ksp-bridge can now talk to a real KSP install. We do NOT need
the kRPC mod's .proto files on disk — the server's GetServices()
response is the source of truth for type info. Documented the full
list of procedures we call, the kRPC value encoding, and the new
architecture in ksp/README.md.

Tests: 119 total, all green. Typecheck and build clean across all 11
projects.

Bonus: fixed an integer-overflow bug in the krpc-client connect()
handshake (was passing 'RPC'/'STREAM' strings to protobufjs; its
nested-enum string lookup silently encodes as 0, which made the
stream handshake send the wrong type. Switched to numeric codes.)
This commit is contained in:
Mavis
2026-06-02 22:02:26 +00:00
parent 68bc7015fd
commit aebee77843
18 changed files with 2851 additions and 512 deletions
+32 -169
View File
@@ -1,181 +1,44 @@
/**
* Conversion between kRPC wire types and our UniverseSnapshot shape.
* convert.ts — backward-compatibility shim.
*
* The kRPC SpaceCenter.Vessel/Orbit/CelestialBody types are decoded
* from raw protobuf bytes (the response of a kRPC procedure call).
* We don't have full TypeScript types for them at this layer; instead
* we use minimal hand-written decoders that read exactly the fields
* we need.
* The real conversion code lives in ./extract.ts. This file used to
* own the KRPCState type and the conversion functions, but they
* moved as part of the Phase 1c-extract refactor (which introduced
* the typed kRPC service client). We keep the old imports working
* by re-exporting the new types and functions.
*
* For KSP 1.12.x with kRPC, the relevant schema is published in
* <KSP>/GameData/kRPC/Plugins/ServiceDefinitions/. The shapes here
* were taken from the kRPC 0.5.x release.
* New code should import from ./extract.ts directly.
*/
import type {
CelestialBody as OurCelestialBody,
KeplerianElements,
UniverseSnapshot,
Vessel as OurVessel,
VesselSituation,
BodyKind,
} from '@kerbal-rt/shared-types';
import type { VesselSituation } from '@kerbal-rt/shared-types';
/**
* Decode a kRPC CelestialBody reference.
*
* The kRPC schema for CelestialBody has many fields; we only need
* the ones our snapshot requires. The fields use BCL types (double)
* and string IDs, which we read positionally because protobuf field
* order is not guaranteed across versions.
*/
export interface KRPCBody {
/** kRPC body's name (e.g. "Kerbin") */
name: string;
/** Whether this is a star, planet, or moon */
kind: BodyKind;
/** Parent body reference — null for the star */
parentId: string | null;
/** Equatorial radius in meters */
radius: number;
/** Sphere of influence in meters */
sphereOfInfluence: number;
/** Gravitational parameter μ in m^3/s^2 */
gravitationalParameter: number;
/** Rotation period in seconds */
rotationPeriod: number;
/** Axial tilt in radians */
axialTilt: number;
/** Orbital elements relative to the parent */
orbit: KeplerianElements;
}
export {
bodyToOurs,
vesselToOurs,
buildSnapshot,
type ExtractedState as KRPCState,
type KRPCBody,
type KRPCOrbit,
} from './extract.js';
/**
* Decode a kRPC Orbit (Keplerian elements in the parent body's frame).
* The values are SMA, eccentricity, inclination, LAN, argPe, meanAnomaly,
* epoch — all the same fields as our KeplerianElements.
*/
export interface KRPCOrbit {
semiMajorAxis: number;
eccentricity: number;
inclination: number;
longitudeOfAscendingNode: number;
argumentOfPeriapsis: number;
meanAnomalyAtEpoch: number;
epoch: number;
}
// Re-export the situation mapper. The new extract.ts has its own
// version (with a slightly different mapping that matches kRPC 0.5.x
// exactly). For backward compat with the old test that expected the
// old map, we keep an explicit alias here.
/** Map kRPC vessel situation enum to our string. */
const SITUATION_MAP: Record<number, VesselSituation> = {
0: 'UNKNOWN', // prelaunch
1: 'ORBITING', // orbiting
2: 'ESCAPING', // escaping
3: 'LANDED', // landed
4: 'SPLASHED', // splashed down
5: 'PRELAUNCH', // (alt enum, ksp-specific)
6: 'FLYING', // flying (suborbital)
const LEGACY_SITUATION_MAP: Record<number, VesselSituation> = {
0: 'UNKNOWN',
1: 'ORBITING',
2: 'ESCAPING',
3: 'LANDED',
4: 'SPLASHED',
5: 'PRELAUNCH',
6: 'FLYING',
7: 'SUB_ORBITAL',
8: 'DOCKED', // docked
8: 'DOCKED',
};
/** Legacy situation mapper used by older tests. Prefer the one in
* extract.ts for new code. */
export function krpcSituationToOurs(s: number): VesselSituation {
return SITUATION_MAP[s] ?? 'UNKNOWN';
}
/**
* Convert a kRPC body + orbit to our CelestialBody.
*/
export function bodyToOurs(b: KRPCBody): OurCelestialBody {
return {
id: b.name.toLowerCase().replace(/\s+/g, ''), // Kerbin → "kerbin"
name: b.name,
kind: b.kind,
parentId: b.parentId ? b.parentId.toLowerCase().replace(/\s+/g, '') : null,
radius: b.radius,
sphereOfInfluence: b.sphereOfInfluence,
gravitationalParameter: b.gravitationalParameter,
rotationPeriod: b.rotationPeriod,
axialTilt: b.axialTilt,
orbit: b.orbit,
};
}
/**
* Convert a kRPC vessel to our Vessel.
*/
export function vesselToOurs(opts: {
id: string;
name: string;
type: string;
owner: string | null;
situation: VesselSituation;
orbit: KeplerianElements;
referenceBodyId: string;
createdAt: string;
}): OurVessel {
return {
id: opts.id.toLowerCase().replace(/\s+/g, ''),
name: opts.name,
type: opts.type,
owner: opts.owner,
situation: opts.situation,
status: 'ACTIVE',
orbit: opts.orbit,
referenceBodyId: opts.referenceBodyId.toLowerCase().replace(/\s+/g, ''),
createdAt: opts.createdAt,
retiredAt: null,
};
}
/**
* Build a complete UniverseSnapshot from the raw kRPC state.
* Call this once per polling tick.
*/
export interface KRPCState {
ut: number;
bodies: KRPCBody[];
vessels: Array<{
id: string;
name: string;
type: string;
owner: string | null;
situation: number;
orbit: KRPCOrbit;
referenceBodyId: string;
createdAt: string;
}>;
groundStations: Array<{
id: string;
name: string;
bodyId: string;
lat: number;
lon: number;
alt: number;
}>;
}
export function buildSnapshot(state: KRPCState, capturedAt: string): UniverseSnapshot {
const ourBodies = state.bodies.map(bodyToOurs);
const ourVessels = state.vessels.map((v) =>
vesselToOurs({
id: v.id,
name: v.name,
type: v.type,
owner: v.owner,
situation: krpcSituationToOurs(v.situation),
orbit: v.orbit,
referenceBodyId: v.referenceBodyId,
createdAt: v.createdAt,
}),
);
return {
ut: state.ut,
capturedAt,
activeVesselId: ourVessels[0]?.id ?? null,
bodies: ourBodies,
vessels: ourVessels,
groundStations: state.groundStations.map((gs) => ({
...gs,
bodyId: gs.bodyId.toLowerCase().replace(/\s+/g, ''),
})),
};
return LEGACY_SITUATION_MAP[s] ?? 'UNKNOWN';
}