The stack trace finally showed the truth: the error was in our
own decodeKrpcType, not in protobufjs. The kRPC server omits
the `return_type` field for procedures that have no return value
(e.g. AddStream, RemoveStream, all the setters). protobufjs
decodes missing message fields as null. Our cache then called
`decodeKrpcType(null)`, which did `null.code` and threw.
The null.code error message was a red herring all along — it
looked like protobufjs was looking up an enum descriptor, but it
was actually just our code accessing .code on a null parameter.
The protobufjs fixes (uint32 instead of nested-enum, adding the
game_scenes field) were real and needed — but they weren't the
cause of THIS particular failure mode.
Fix:
- decodeKrpcType accepts null/undefined and returns a NONE type
(code 0) in that case
- Added a regression test in services.test.ts that builds a fake
ServiceCache with a procedure whose returnType is null
The kRPC server's GetServices response includes a `game_scenes`
field on every Procedure message — a repeated GameScene enum
describing which KSP scene the procedure is available in
(SPACE_CENTER, FLIGHT, EDITOR_VAB, etc.). My schema was missing
field 6 entirely, and the field type is a nested enum which hits
the same protobufjs bug we've been chasing.
This is the actual cause of the 'Cannot read properties of null
(reading code)' error that has been blocking the bridge. The
decoder was trying to resolve the GameScene nested-enum
descriptor and throwing.
Fix: add field 6 as repeated uint32 (same nested-enum workaround
as Type.code and ConnectionResponse.status), with the enum values
kept as a nested GameScene for documentation/lookup.
After this fix, the GetServices response should decode cleanly
and the bridge should connect to real KSP.
The real root cause of the 'Cannot read properties of null (reading code)'
error was hiding in two places, not one. The first (ConnectionResponse
status) was fixed in the previous commit. This commit fixes the second:
The KRPC.Type message has a 'code' field of nested-enum type
'Type.TypeCode'. When protobufjs decodes a GetServices response
(which contains MANY Type messages inside Procedure.returnType
fields), it hits the same nested-enum default-value lookup bug
and throws the TypeError.
The fix is identical to the ConnectionResponse.status fix:
change the field type from the nested-enum reference to plain
'uint32'. The wire format is the same (varint), and our code in
services.ts reads raw integers from the typecode field anyway.
This error was happening OUTSIDE my top-level try/catch in
client.connect() — it was in loadServices, called from
adapter.connect(). The bridge's catch caught it, but the error
message was the raw 'Cannot read properties of null (reading code)'
because loadServices didn't wrap the error.
Now:
- The schema fix makes the decode actually succeed
- The adapter wraps any remaining loadServices errors with a
clear 'kRPC loadServices (GetServices decode) failed:' prefix
so the next failure mode is immediately actionable
The schema fix to use uint32 for status was the right call, but
the error persists. The fact that the raw bytes are being printed
means the new code IS running, but the error must be coming from
somewhere outside the inline try/catch blocks. Wrapping the whole
connect() in a safety net so we'll see a stack trace on the next
run and can pinpoint the exact line.
This is the actual root cause of the Windows handshake failure.
The kRPC server sends a minimal ConnectionResponse that omits the
default-value `status` and `message` fields, leaving only the
`clientIdentifier`. Our schema declared the status field as
`type: 'ConnectionResponse.Status'` (a nested enum reference).
When protobufjs decodes the response and the field is absent, it
tries to look up the default value from the nested-enum type
descriptor — but the descriptor resolves to null somewhere in
protobufjs 7.6, and the next thing the code does is
`someDescriptor.code` to look up the default enum value. That
throws the TypeError: 'Cannot read properties of null (reading code)'.
The wire format is identical: status is just a varint. So we model
it as 'uint32' and our code already does `resp.status !== 0`
which works for the happy path (0 = OK). The redundant `!== 'OK'`
check is kept for forward compat — if anyone ever flips the schema
back to nested-enum and protobufjs fixes the bug, the string check
would still work.
Same fix applied to ProcedureResult.error (uses 'Error' which is
the actual top-level Error type, not a nested-enum type).
The raw-bytes diagnostic from the previous commit showed both
handshakes returning 18 bytes:
1a 10 <16 bytes>
which is just field 3 (clientIdentifier), confirming the server is
sending minimal responses. Decoding those 18 bytes as
ConnectionResponse with the old schema triggered the bug; with
uint32 status, it decodes cleanly to {status: 0, message: "",
clientIdentifier: <16 bytes>}, the handshake succeeds, and the
bridge connects to real KSP.
The original fix only wrapped the RPC handshake decode. The user's
symptom is the same error after the RPC handshake succeeds (the kRPC
server registers the client on the RPC side), so the failure must
be in the stream handshake.
Added:
- try/catch around the stream decode (matching the RPC decode)
- KRPC_DEBUG env var that dumps raw bytes from both handshakes
to the console. Set it to 1 when running the bridge to see
exactly what kRPC is sending:
KRPC_DEBUG=1 pnpm start
Output will include lines like:
[krpc-client] rpc handshake raw response (17 bytes): 08001200...
[krpc-client] stream handshake raw response (4 bytes): 08001200
If you see [v2-debug] in the log, you're on the new code. If
you don't, you're still on main and the old error handler is
hiding the real error.
Also hardened the fatal catch handler to never crash on weird
error values.
The bridge was falling back to mock mode with a confusing
'Cannot read properties of null (reading code)' error. The actual
underlying error (ECONNREFUSED, timeout, protocol mismatch) was
being swallowed by our error handler that did `(e as Error).message`
on a value that was sometimes null.
Wrap the kRPC client connect() in per-step try/catch with a
formatErr() helper that handles:
- null / undefined
- strings
- Error with .code (NodeJS.ErrnoException)
- arbitrary objects (JSON.stringify fallback)
Now when the bridge can't reach kRPC you get a real error like
'kRPC RPC TCP connect to 127.0.0.1:50000 failed: code=ECONNREFUSED:
connect ECONNREFUSED 127.0.0.1:50000' instead of the cryptic
null-code message.
Also fixed the bridge's main() error handler to be null-safe.
Discovered while debugging the user's first end-to-end run on
Windows: kRPC was reachable (Test-NetConnection succeeded) but
the bridge couldn't complete the handshake. With this fix we'll
see the real failure mode on the next attempt.
Adds the last piece for real-KSP support:
- packages/krpc-client: types, decoder (primitives/classes/enums/collections), services cache, KrpcServices client (invokes by name with auto-encode/decode)
- apps/tools/ksp-bridge/extract.ts: full SpaceCenter extract (~280 procedure calls per poll for a stock save)
- ksp/README.md: complete setup guide + procedure list + troubleshooting
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.)
- packages/krpc-client: TypeScript kRPC protocol client
- connection.ts: varint encoding/decoding, length-prefix framing,
per-socket read queue (avoids race when multiple read promises
in flight). Uses multiplication not '<<' for varint shift
because JS truncates << to 32 bits.
- schema.ts: hand-written protobufjs schema for kRPC meta-protocol
(ConnectionRequest, Request, Response, StreamUpdate, Status, etc.)
- enough to do connection handshake, single procedure calls, and
stream subscription. Service-specific types (SpaceCenter.Vessel,
Orbit, CelestialBody) need to be loaded from the kRPC mod's
.proto files at runtime.
- client.ts: KRPCClient with connect/invoke/addStream/removeStream/
onStreamUpdate/close. Tested with hand-rolled mock server.
- 10 tests (varint round-trips incl. uint64, wire format with raw
sockets).
- apps/tools/ksp-bridge: bridge that connects KSP to our API
- convert.ts: pure kRPC -> UniverseSnapshot conversion
(situation enum mapping, body id normalization, etc.)
- bridge.ts: main poll loop with retry + backoff
- krpc-adapter.ts: KRPCAdapter class that owns the KRPCClient
- index.ts: entrypoint with MOCK MODE for development (emits
synthetic state when no KSP is available, so you can verify the
HTTP pipeline end-to-end)
- 9 tests (7 conversion + 2 end-to-end bridge)
- ksp/README.md: full setup guide
- CKAN install, KSP server start, env vars
- Hand-rolled KSP calls list (what SpaceCenter methods we need)
- Roadmap for the remaining .proto-loading work
- Protocol deep-dive (for the next dev)
- Bug fixes along the way: protobufjs default import (not namespace),
varint 32-bit truncation, JavaScript bitwise 32-bit limit,
handshake status enum comparison (number vs string).
End-to-end verified: API + bridge in mock mode, 2 bodies + 1 vessel
arriving at /api/v1/state, 500ms polling cadence, automatic recovery
on HTTP failures.
- packages/db: postgres.js + ioredis wrapper, StateStore interface with
InMemory + Postgres implementations, schema migration runner
- apps/api: refactored to use @kerbal-rt/db; live WebSocket hub subscribes
to store changes and broadcasts to all clients
- apps/tools/mock-telemetry: Node script that generates realistic KSP
state and POSTs to /api/v1/ingest at 1Hz (uses same keplerian math
as the live-map renderer)
- apps/hub: new /debug page that connects to /api/v1/live and shows
the live state
- ksp/README.md: documents Phase 1c (real kRPC bridge) and the two
implementation options
- Tests: 17 total (5 kepler math, 5 db store, 5 API health/state,
2 API WebSocket fan-out)
End-to-end verified: mock publisher → API → hub /debug page,
11 snapshots/5s over WebSocket, vessels advancing in mean anomaly.