Squashed 'packages/cultnet-ts/' content from commit 902f9660
git-subtree-dir: packages/cultnet-ts git-subtree-split: 902f96604b2ae6c8245c3c688f9d80ba6fe42404
This commit is contained in:
commit
b90b5ebce8
47 changed files with 6510 additions and 0 deletions
60
.github/workflows/cultnet-interop.yml
vendored
Normal file
60
.github/workflows/cultnet-interop.yml
vendored
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
name: CultNet Interop
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
interop:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
- name: Check out cultnet-ts
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
path: CultNetTS
|
||||
|
||||
- name: Check out cultnet-rs
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: GameCult/cultnet-rs
|
||||
path: cultnet-rs
|
||||
|
||||
- name: Check out cultcache-rs
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: GameCult/cultcache-rs
|
||||
path: cultcache-rs
|
||||
|
||||
- name: Check out CultLib
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: GameCult/CultLib
|
||||
path: CultLib
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
cache-dependency-path: CultNetTS/package-lock.json
|
||||
|
||||
- name: Set up .NET SDK
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: 10.0.x
|
||||
include-prerelease: true
|
||||
|
||||
- name: Set up Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Install cultnet-ts dependencies
|
||||
working-directory: CultNetTS
|
||||
run: npm ci
|
||||
|
||||
- name: Run cross-runtime interop harness
|
||||
working-directory: CultNetTS
|
||||
run: npm run test:interop
|
||||
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
node_modules/
|
||||
dist/
|
||||
dist-test/
|
||||
*.tgz
|
||||
259
README.md
Normal file
259
README.md
Normal file
|
|
@ -0,0 +1,259 @@
|
|||
# CultNet TS
|
||||
|
||||
`cultnet-ts` is the TypeScript port of the useful shape of GameCult's
|
||||
networking layer: typed MessagePack messages, direct-pipe framing, CultLib-style
|
||||
security/session helpers, and state replication that hands typed values into a
|
||||
`CultCache` instead of making consumer code paw raw database envelopes.
|
||||
|
||||
This is not an HTTP wrapper wearing a fake mustache. It is for runtimes that
|
||||
already trust a direct channel and want a compact shared contract over it.
|
||||
|
||||
## Scope
|
||||
|
||||
The library currently includes:
|
||||
|
||||
- JSON-schema-backed wire contracts for the first CultNet message set
|
||||
- a MessagePack codec plus 4-byte length-prefixed framing for direct pipes
|
||||
- a `CultNetPeer` wrapper over any Node `Duplex`
|
||||
- CultLib-style client/server security options and `Secret` helpers
|
||||
- session-token signing/validation compatible with the C# CultLib semantics
|
||||
- explicit wire-contract selection instead of heuristic payload guessing
|
||||
- `CultCacheTS` replication helpers for document put/delete/snapshot flows
|
||||
- schema discovery catalog messages and a registry for asking what contracts a
|
||||
peer can actually exchange safely
|
||||
- generated TypeScript contracts and runtime verifiers from canonical JSON
|
||||
schemas owned elsewhere in the swarm
|
||||
- an exact mirrored runtime validator and generated TS contract surface for
|
||||
Ghostlight's canonical `ghostlight.agent_state.v0` payload
|
||||
|
||||
## Why This Exists
|
||||
|
||||
We want:
|
||||
|
||||
- one shared agent-state vocabulary across `Ghostlight`, `EpiphanyAgent`,
|
||||
`VoidBot`, and whatever other little laboratory creature appears next
|
||||
- typed persistence through `CultCache`
|
||||
- direct pipes instead of every consumer inventing bespoke JSON fog
|
||||
- authentication and session semantics that match the original CultLib intent
|
||||
|
||||
So the split is:
|
||||
|
||||
- `cultcache-ts`: typed local persistence
|
||||
- `cultnet-ts`: typed transport, auth, and state replication
|
||||
|
||||
Same family. Different organs. Nobody needs a second spine growing out of the
|
||||
transport layer.
|
||||
|
||||
## Contracts
|
||||
|
||||
Wire contracts live under `contracts/` as JSON Schema files.
|
||||
|
||||
Current message families:
|
||||
|
||||
- `cultnet.hello.v0`
|
||||
- `cultnet.login.v0`
|
||||
- `cultnet.register.v0`
|
||||
- `cultnet.verify.v0`
|
||||
- `cultnet.login_success.v0`
|
||||
- `cultnet.error.v0`
|
||||
- `cultnet.document_put.v0`
|
||||
- `cultnet.document_delete.v0`
|
||||
- `cultnet.document_put_raw.v0`
|
||||
- `cultnet.snapshot_request.v0`
|
||||
- `cultnet.snapshot_response.v0`
|
||||
- `cultnet.snapshot_response_raw.v0`
|
||||
- `cultnet.sample.change_name.v0`
|
||||
- `cultnet.sample.chat.v0`
|
||||
|
||||
For shared agent state, the first payload contract is the existing Ghostlight
|
||||
fixture format:
|
||||
|
||||
- payload schema version: `ghostlight.agent_state.v0`
|
||||
- mirrored validator: `contracts/ghostlight.agent-state.schema.json`
|
||||
|
||||
That means `EpiphanyAgent` role dossiers and Ghostlight fixtures can travel over
|
||||
CultNet without inventing a second ontology first.
|
||||
|
||||
## Generated Swarm Contracts
|
||||
|
||||
`cultnet-ts` can consume canonical JSON Schema files and generate:
|
||||
|
||||
- TypeScript contract classes/interfaces
|
||||
- runtime schema verifiers
|
||||
- parse-compatible schema objects that can be handed directly to
|
||||
`CultCacheTS`
|
||||
|
||||
The manifest lives at [contracts/swarm-contracts.manifest.json](contracts/swarm-contracts.manifest.json).
|
||||
Right now it points at Ghostlight's canonical agent-state schema, because
|
||||
Ghostlight owns the swarm's most important mind-shape contract.
|
||||
|
||||
Generate the contract layer with:
|
||||
|
||||
```bash
|
||||
npm run contracts:generate
|
||||
```
|
||||
|
||||
That emits [src/generated/swarm-contracts.generated.ts](src/generated/swarm-contracts.generated.ts),
|
||||
which exports:
|
||||
|
||||
- the generated TS contract shape
|
||||
- named runtime verifier helpers such as
|
||||
`validateGhostlightAgentStateGenerated(...)` and
|
||||
`parseGhostlightAgentStateGenerated(...)`
|
||||
- a runtime `validate(...)` / `parse(...)` contract object via
|
||||
`defineJsonSchemaContract(...)`
|
||||
- a contract object that `CultCacheTS` can persist directly without a second
|
||||
hand-written Zod mirror
|
||||
|
||||
## Wire Contracts
|
||||
|
||||
`cultnet-ts` does not sniff random payloads and pretend that counts as rigor.
|
||||
You choose the contract explicitly.
|
||||
|
||||
Current wire-contract options:
|
||||
|
||||
- `cultnet.schema.v0`
|
||||
- the newer schema-versioned object contract for CultNet-native message
|
||||
families such as hello, document replication, and snapshots
|
||||
- `gamecult.networking.v0`
|
||||
- the legacy C# `GameCult.Networking` MessagePack union contract for
|
||||
login/register/verify/session/error plus the sample `ChangeNameMessage` and
|
||||
`ChatMessage` payloads
|
||||
|
||||
So the transport can stay developer-friendly while the binary stops freelancing
|
||||
away from the C# lineage.
|
||||
|
||||
## Local Fast Lane
|
||||
|
||||
For direct-pipe neighbors that already share the same CultCache formatter
|
||||
contract, `cultnet-ts` now has a raw replication lane:
|
||||
|
||||
- `cultnet.document_put_raw.v0`
|
||||
- `cultnet.snapshot_response_raw.v0`
|
||||
|
||||
Those messages carry the canonical persisted MessagePack payload bytes plus the
|
||||
typed envelope metadata. Paired with `CultCacheTS.putEnvelope(...)`, that means
|
||||
the receiving cache can ingest the exact payload bytes directly instead of
|
||||
decoding them into generic object soup and then re-encoding the same document
|
||||
again.
|
||||
|
||||
This is cheaper. It is not magic:
|
||||
|
||||
- framing still copies
|
||||
- MessagePack decoding still happens once on ingest
|
||||
- ordinary `CultNetPeer` send/receive still materializes messages
|
||||
|
||||
But for local or near-local runtimes sharing the same contract, the fast lane
|
||||
cuts out the dumbest part of the trip.
|
||||
|
||||
## Schema Discovery
|
||||
|
||||
Apps sharing a CultNet space should be able to ask each other what they can
|
||||
exchange without resorting to folklore.
|
||||
|
||||
`cultnet-ts` now includes:
|
||||
|
||||
- `cultnet.schema_catalog_request.v0`
|
||||
- `cultnet.schema_catalog_response.v0`
|
||||
- `CultNetSchemaRegistry`
|
||||
- `cultNetBuiltinSchemaRegistry`
|
||||
|
||||
Descriptors include:
|
||||
|
||||
- canonical `schemaId`
|
||||
- discovery `kind`
|
||||
- optional `schemaVersion`
|
||||
- optional `documentType`
|
||||
- supported `wireContracts`
|
||||
- a SHA-256 `contentHash`
|
||||
- optional inline `schemaJson`
|
||||
|
||||
The inline schema body travels as canonical JSON text, not as a loose object
|
||||
graph. Discovery is supposed to reduce ambiguity, not smuggle in a cute new
|
||||
polymorphic attack surface.
|
||||
|
||||
## Quick Example
|
||||
|
||||
```ts
|
||||
import { CultCache, defineDocumentType } from "cultcache-ts";
|
||||
import {
|
||||
CultNetDocumentRegistry,
|
||||
CultNetPeer,
|
||||
defineCultNetDocumentBinding,
|
||||
ghostlightAgentStateGeneratedContract,
|
||||
} from "cultnet-ts";
|
||||
|
||||
const ghostlightStateDefinition = defineDocumentType({
|
||||
type: "ghostlight.agent-state",
|
||||
schema: ghostlightAgentStateGeneratedContract,
|
||||
});
|
||||
|
||||
const registry = new CultNetDocumentRegistry([
|
||||
defineCultNetDocumentBinding({
|
||||
definition: ghostlightStateDefinition,
|
||||
payloadSchemaVersion: "ghostlight.agent_state.v0",
|
||||
}),
|
||||
]);
|
||||
|
||||
const peer = new CultNetPeer(stream, {
|
||||
wireContract: "cultnet.schema.v0",
|
||||
});
|
||||
```
|
||||
|
||||
## Security Model
|
||||
|
||||
The security helpers intentionally mirror CultLib's shape:
|
||||
|
||||
- shared connection key -> SHA-256 derived AES-GCM key
|
||||
- server-only session signing secret -> HMAC-SHA256 session token signing
|
||||
- 12-byte nonce
|
||||
- authentication tag prefixed onto ciphertext
|
||||
- session token format: `base64url(payload).base64url(signature)`
|
||||
|
||||
That means a TypeScript runtime can follow the same cryptographic and session
|
||||
story as the C# version instead of inventing one more house religion around
|
||||
"trust me, this pipe is probably fine."
|
||||
|
||||
For the legacy `gamecult.networking.v0` contract, `cultnet-ts` normalizes the
|
||||
encrypted binary fields as base64url strings in the ergonomic TS surface and
|
||||
maps them back to the exact C# union payload shape at the wire boundary.
|
||||
|
||||
## Current Limits
|
||||
|
||||
- This repo currently implements the client-side wire contract and pipe
|
||||
ergonomics, not a full account server.
|
||||
- The Ghostlight agent-state mirror is an exact copy of Ghostlight's current
|
||||
canonical schema. If Ghostlight changes the contract, this mirror must be
|
||||
updated in lockstep instead of playing coy with partial validation.
|
||||
- The direct transport is any Node `Duplex`; named-pipe/socket server wrappers
|
||||
can be added without changing the message contract.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run contracts:generate
|
||||
npm run build
|
||||
npm run typecheck
|
||||
npm run test
|
||||
```
|
||||
|
||||
## Interop CI
|
||||
|
||||
The cross-runtime interop harness is meant to run in GitHub Actions on
|
||||
`windows-latest`.
|
||||
|
||||
It expects these sibling checkouts inside the same workspace:
|
||||
|
||||
- `CultNetTS`
|
||||
- `cultnet-rs`
|
||||
- `cultcache-rs`
|
||||
- `CultLib`
|
||||
|
||||
The workflow lives at
|
||||
[.github/workflows/cultnet-interop.yml](.github/workflows/cultnet-interop.yml)
|
||||
and drives the whole ritual through one command:
|
||||
|
||||
```bash
|
||||
npm run test:interop
|
||||
```
|
||||
19
contracts/cultnet.document-delete.schema.json
Normal file
19
contracts/cultnet.document-delete.schema.json
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-delete.schema.json",
|
||||
"title": "CultNet Document Delete Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"messageId",
|
||||
"schemaId",
|
||||
"recordKey"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.document_delete.v0" },
|
||||
"messageId": { "type": "string", "minLength": 1 },
|
||||
"schemaId": { "type": "string", "minLength": 1 },
|
||||
"recordKey": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
40
contracts/cultnet.document-mutation-contract.schema.json
Normal file
40
contracts/cultnet.document-mutation-contract.schema.json
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-mutation-contract.schema.json",
|
||||
"title": "CultNet Document Mutation Contract",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"documentType",
|
||||
"operations",
|
||||
"authority"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"documentType": { "type": "string", "minLength": 1 },
|
||||
"payloadSchemaVersion": { "type": "string", "minLength": 1 },
|
||||
"operations": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["snapshot", "documentPut", "documentDelete", "intentSubmit", "receiptWatch"]
|
||||
}
|
||||
},
|
||||
"authority": {
|
||||
"type": "string",
|
||||
"enum": ["readOnly", "localUser", "coordinator", "runtime", "denied"]
|
||||
},
|
||||
"intentDocumentTypes": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 }
|
||||
},
|
||||
"receiptDocumentTypes": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 }
|
||||
},
|
||||
"notes": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
19
contracts/cultnet.document-put-raw.schema.json
Normal file
19
contracts/cultnet.document-put-raw.schema.json
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-put-raw.schema.json",
|
||||
"title": "CultNet Raw Document Put Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"messageId",
|
||||
"document"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.document_put_raw.v0" },
|
||||
"messageId": { "type": "string", "minLength": 1 },
|
||||
"document": {
|
||||
"$ref": "./cultnet.raw-document-record.schema.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
19
contracts/cultnet.document-put.schema.json
Normal file
19
contracts/cultnet.document-put.schema.json
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-put.schema.json",
|
||||
"title": "CultNet Document Put Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"messageId",
|
||||
"document"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.document_put.v0" },
|
||||
"messageId": { "type": "string", "minLength": 1 },
|
||||
"document": {
|
||||
"$ref": "./cultnet.document-record.schema.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
26
contracts/cultnet.document-record.schema.json
Normal file
26
contracts/cultnet.document-record.schema.json
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-record.schema.json",
|
||||
"title": "CultNet Document Record",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaId",
|
||||
"recordKey",
|
||||
"storedAt",
|
||||
"payload"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaId": { "type": "string", "minLength": 1 },
|
||||
"recordKey": { "type": "string", "minLength": 1 },
|
||||
"storedAt": { "type": "string", "minLength": 1 },
|
||||
"payload": {},
|
||||
"sourceRuntimeId": { "type": "string", "minLength": 1 },
|
||||
"sourceAgentId": { "type": "string", "minLength": 1 },
|
||||
"sourceRole": { "type": "string", "minLength": 1 },
|
||||
"tags": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
15
contracts/cultnet.error.schema.json
Normal file
15
contracts/cultnet.error.schema.json
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.error.schema.json",
|
||||
"title": "CultNet Error Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"error"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.error.v0" },
|
||||
"error": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
35
contracts/cultnet.hello.schema.json
Normal file
35
contracts/cultnet.hello.schema.json
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.hello.schema.json",
|
||||
"title": "CultNet Hello Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"runtimeId",
|
||||
"runtimeKind"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.hello.v0" },
|
||||
"runtimeId": { "type": "string", "minLength": 1 },
|
||||
"runtimeKind": { "type": "string", "minLength": 1 },
|
||||
"agentId": { "type": "string", "minLength": 1 },
|
||||
"role": { "type": "string", "minLength": 1 },
|
||||
"displayName": { "type": "string", "minLength": 1 },
|
||||
"supportedDocumentTypes": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 }
|
||||
},
|
||||
"supportedMutationContracts": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "./cultnet.document-mutation-contract.schema.json"
|
||||
}
|
||||
},
|
||||
"supportedMessageVersions": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 }
|
||||
},
|
||||
"supportsSchemaCatalog": { "type": "boolean" }
|
||||
}
|
||||
}
|
||||
17
contracts/cultnet.login-success.schema.json
Normal file
17
contracts/cultnet.login-success.schema.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.login-success.schema.json",
|
||||
"title": "CultNet Login Success Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"nonce",
|
||||
"session"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.login_success.v0" },
|
||||
"nonce": { "type": "string", "minLength": 1 },
|
||||
"session": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
19
contracts/cultnet.login.schema.json
Normal file
19
contracts/cultnet.login.schema.json
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.login.schema.json",
|
||||
"title": "CultNet Login Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"nonce",
|
||||
"auth",
|
||||
"password"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.login.v0" },
|
||||
"nonce": { "type": "string", "minLength": 1 },
|
||||
"auth": { "type": "string", "minLength": 1 },
|
||||
"password": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
32
contracts/cultnet.raw-document-record.schema.json
Normal file
32
contracts/cultnet.raw-document-record.schema.json
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.raw-document-record.schema.json",
|
||||
"title": "CultNet Raw Document Record",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaId",
|
||||
"recordKey",
|
||||
"storedAt",
|
||||
"payloadEncoding",
|
||||
"payload"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaId": { "type": "string", "minLength": 1 },
|
||||
"recordKey": { "type": "string", "minLength": 1 },
|
||||
"storedAt": { "type": "string", "minLength": 1 },
|
||||
"payloadEncoding": { "const": "messagepack" },
|
||||
"payload": {
|
||||
"type": "string",
|
||||
"contentEncoding": "base64",
|
||||
"x-cult-runtime-type": "bytes"
|
||||
},
|
||||
"sourceRuntimeId": { "type": "string", "minLength": 1 },
|
||||
"sourceAgentId": { "type": "string", "minLength": 1 },
|
||||
"sourceRole": { "type": "string", "minLength": 1 },
|
||||
"tags": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
21
contracts/cultnet.register.schema.json
Normal file
21
contracts/cultnet.register.schema.json
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.register.schema.json",
|
||||
"title": "CultNet Register Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"nonce",
|
||||
"email",
|
||||
"password",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.register.v0" },
|
||||
"nonce": { "type": "string", "minLength": 1 },
|
||||
"email": { "type": "string", "minLength": 1 },
|
||||
"password": { "type": "string", "minLength": 1 },
|
||||
"name": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
15
contracts/cultnet.sample-change-name.schema.json
Normal file
15
contracts/cultnet.sample-change-name.schema.json
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.sample-change-name.schema.json",
|
||||
"title": "CultNet Sample Change Name Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.sample.change_name.v0" },
|
||||
"name": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
15
contracts/cultnet.sample-chat.schema.json
Normal file
15
contracts/cultnet.sample-chat.schema.json
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.sample-chat.schema.json",
|
||||
"title": "CultNet Sample Chat Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"text"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.sample.chat.v0" },
|
||||
"text": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
31
contracts/cultnet.schema-catalog-request.schema.json
Normal file
31
contracts/cultnet.schema-catalog-request.schema.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.schema-catalog-request.schema.json",
|
||||
"title": "CultNet Schema Catalog Request Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"messageId"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.schema_catalog_request.v0" },
|
||||
"messageId": { "type": "string", "minLength": 1 },
|
||||
"includeSchemaJson": { "type": "boolean" },
|
||||
"schemaIds": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 }
|
||||
},
|
||||
"kinds": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"wire_message",
|
||||
"document_payload",
|
||||
"shared_contract"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
22
contracts/cultnet.schema-catalog-response.schema.json
Normal file
22
contracts/cultnet.schema-catalog-response.schema.json
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.schema-catalog-response.schema.json",
|
||||
"title": "CultNet Schema Catalog Response Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"messageId",
|
||||
"schemas"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.schema_catalog_response.v0" },
|
||||
"messageId": { "type": "string", "minLength": 1 },
|
||||
"schemas": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "./cultnet.schema-descriptor.schema.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
39
contracts/cultnet.schema-descriptor.schema.json
Normal file
39
contracts/cultnet.schema-descriptor.schema.json
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.schema-descriptor.schema.json",
|
||||
"title": "CultNet Schema Descriptor",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaId",
|
||||
"kind",
|
||||
"wireContracts",
|
||||
"contentHash"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaId": { "type": "string", "minLength": 1 },
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"wire_message",
|
||||
"document_payload",
|
||||
"shared_contract"
|
||||
]
|
||||
},
|
||||
"schemaVersion": { "type": "string", "minLength": 1 },
|
||||
"documentType": { "type": "string", "minLength": 1 },
|
||||
"title": { "type": "string", "minLength": 1 },
|
||||
"wireContracts": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"cultnet.schema.v0",
|
||||
"gamecult.networking.v0"
|
||||
]
|
||||
}
|
||||
},
|
||||
"contentHash": { "type": "string", "minLength": 1 },
|
||||
"schemaJson": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
23
contracts/cultnet.snapshot-request.schema.json
Normal file
23
contracts/cultnet.snapshot-request.schema.json
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.snapshot-request.schema.json",
|
||||
"title": "CultNet Snapshot Request Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"messageId"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.snapshot_request.v0" },
|
||||
"messageId": { "type": "string", "minLength": 1 },
|
||||
"schemaIds": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 }
|
||||
},
|
||||
"recordKeys": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
22
contracts/cultnet.snapshot-response-raw.schema.json
Normal file
22
contracts/cultnet.snapshot-response-raw.schema.json
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.snapshot-response-raw.schema.json",
|
||||
"title": "CultNet Raw Snapshot Response Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"messageId",
|
||||
"documents"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.snapshot_response_raw.v0" },
|
||||
"messageId": { "type": "string", "minLength": 1 },
|
||||
"documents": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "./cultnet.raw-document-record.schema.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
22
contracts/cultnet.snapshot-response.schema.json
Normal file
22
contracts/cultnet.snapshot-response.schema.json
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.snapshot-response.schema.json",
|
||||
"title": "CultNet Snapshot Response Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"messageId",
|
||||
"documents"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.snapshot_response.v0" },
|
||||
"messageId": { "type": "string", "minLength": 1 },
|
||||
"documents": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "./cultnet.document-record.schema.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
17
contracts/cultnet.verify.schema.json
Normal file
17
contracts/cultnet.verify.schema.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.verify.schema.json",
|
||||
"title": "CultNet Verify Message",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"nonce",
|
||||
"session"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.verify.v0" },
|
||||
"nonce": { "type": "string", "minLength": 1 },
|
||||
"session": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
845
contracts/ghostlight.agent-state.schema.json
Normal file
845
contracts/ghostlight.agent-state.schema.json
Normal file
|
|
@ -0,0 +1,845 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/Ghostlight/schemas/agent-state.schema.json",
|
||||
"title": "Ghostlight Agent State Schema",
|
||||
"description": "First canonical contract for Ghostlight agent, perception, relationship, event, scene, and dialogue-context state.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schema_version",
|
||||
"world",
|
||||
"agents",
|
||||
"relationships",
|
||||
"events",
|
||||
"scenes"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schema_version": {
|
||||
"const": "ghostlight.agent_state.v0"
|
||||
},
|
||||
"world": {
|
||||
"$ref": "#/$defs/world_state"
|
||||
},
|
||||
"agents": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/agent"
|
||||
}
|
||||
},
|
||||
"relationships": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/relationship"
|
||||
}
|
||||
},
|
||||
"events": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/event"
|
||||
}
|
||||
},
|
||||
"scenes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/scene"
|
||||
}
|
||||
}
|
||||
},
|
||||
"$defs": {
|
||||
"world_state": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"world_id",
|
||||
"setting",
|
||||
"time",
|
||||
"canon_context"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"world_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"setting": {
|
||||
"type": "string"
|
||||
},
|
||||
"time": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"label"
|
||||
],
|
||||
"additionalProperties": true,
|
||||
"properties": {
|
||||
"label": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"canon_context": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"ambient_pressures": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/pressure"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"agent": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"agent_id",
|
||||
"identity",
|
||||
"canonical_state",
|
||||
"goals",
|
||||
"memories",
|
||||
"perceived_state_overlays"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"agent_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"identity": {
|
||||
"$ref": "#/$defs/identity"
|
||||
},
|
||||
"canonical_state": {
|
||||
"$ref": "#/$defs/canonical_state"
|
||||
},
|
||||
"goals": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/goal"
|
||||
}
|
||||
},
|
||||
"memories": {
|
||||
"$ref": "#/$defs/memory_bundle"
|
||||
},
|
||||
"perceived_state_overlays": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/perceived_state_overlay"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"identity": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"name",
|
||||
"roles",
|
||||
"origin",
|
||||
"public_description"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"roles": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"origin": {
|
||||
"type": "string"
|
||||
},
|
||||
"public_description": {
|
||||
"type": "string"
|
||||
},
|
||||
"private_notes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"canonical_state": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"underlying_organization",
|
||||
"stable_dispositions",
|
||||
"behavioral_dimensions",
|
||||
"presentation_strategy",
|
||||
"voice_style",
|
||||
"situational_state",
|
||||
"values"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"underlying_organization": {
|
||||
"$ref": "#/$defs/variable_map"
|
||||
},
|
||||
"stable_dispositions": {
|
||||
"$ref": "#/$defs/variable_map"
|
||||
},
|
||||
"behavioral_dimensions": {
|
||||
"$ref": "#/$defs/variable_map"
|
||||
},
|
||||
"presentation_strategy": {
|
||||
"$ref": "#/$defs/variable_map"
|
||||
},
|
||||
"situational_state": {
|
||||
"$ref": "#/$defs/variable_map"
|
||||
},
|
||||
"values": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/value_commitment"
|
||||
}
|
||||
},
|
||||
"voice_style": {
|
||||
"$ref": "#/$defs/variable_map"
|
||||
}
|
||||
}
|
||||
},
|
||||
"variable_map": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"$ref": "#/$defs/state_variable"
|
||||
}
|
||||
},
|
||||
"state_variable": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"mean",
|
||||
"plasticity",
|
||||
"current_activation"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"mean": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"plasticity": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"current_activation": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"evidence": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"value_commitment": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"value_id",
|
||||
"label",
|
||||
"priority",
|
||||
"unforgivable_if_betrayed"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"value_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"label": {
|
||||
"type": "string"
|
||||
},
|
||||
"priority": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"unforgivable_if_betrayed": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
"goal": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"goal_id",
|
||||
"description",
|
||||
"scope",
|
||||
"priority",
|
||||
"emotional_stake",
|
||||
"status"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"goal_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"type": "string"
|
||||
},
|
||||
"scope": {
|
||||
"enum": [
|
||||
"immediate",
|
||||
"scene",
|
||||
"case",
|
||||
"arc",
|
||||
"life"
|
||||
]
|
||||
},
|
||||
"priority": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"emotional_stake": {
|
||||
"type": "string"
|
||||
},
|
||||
"blockers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"status": {
|
||||
"enum": [
|
||||
"active",
|
||||
"blocked",
|
||||
"dormant",
|
||||
"resolved",
|
||||
"abandoned"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"memory_bundle": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"episodic",
|
||||
"semantic",
|
||||
"relationship_summaries"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"episodic": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/memory"
|
||||
}
|
||||
},
|
||||
"semantic": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/memory"
|
||||
}
|
||||
},
|
||||
"relationship_summaries": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/memory"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"memory": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"memory_id",
|
||||
"summary",
|
||||
"salience",
|
||||
"confidence"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"memory_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"summary": {
|
||||
"type": "string"
|
||||
},
|
||||
"salience": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"confidence": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"linked_event_ids": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"linked_relationship_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"perceived_state_overlay": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"observer_agent_id",
|
||||
"target_agent_id",
|
||||
"perceived_dimensions",
|
||||
"beliefs",
|
||||
"distortions"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"observer_agent_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"target_agent_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"perceived_dimensions": {
|
||||
"$ref": "#/$defs/inferred_variable_map"
|
||||
},
|
||||
"beliefs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/belief"
|
||||
}
|
||||
},
|
||||
"distortions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"enum": [
|
||||
"hostile_attribution",
|
||||
"false_reassurance",
|
||||
"overread_warmth",
|
||||
"underread_threat",
|
||||
"false_mask_detection",
|
||||
"missed_mask_detection",
|
||||
"status_injury",
|
||||
"threat_amplification",
|
||||
"institutional_suspicion_transfer",
|
||||
"care_underread",
|
||||
"mask_overfocus"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"belief": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"belief_id",
|
||||
"claim",
|
||||
"confidence"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"belief_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"claim": {
|
||||
"type": "string"
|
||||
},
|
||||
"confidence": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"subject_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"claim_type": {
|
||||
"enum": [
|
||||
"fact",
|
||||
"identity_inference",
|
||||
"motive_inference",
|
||||
"prediction",
|
||||
"norm",
|
||||
"value_read",
|
||||
"relationship_read"
|
||||
]
|
||||
},
|
||||
"evidence_event_ids": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"visibility": {
|
||||
"enum": [
|
||||
"private",
|
||||
"shared",
|
||||
"public",
|
||||
"rumor"
|
||||
]
|
||||
},
|
||||
"emotional_charge": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
}
|
||||
}
|
||||
},
|
||||
"relationship": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"relationship_id",
|
||||
"source_id",
|
||||
"target_id",
|
||||
"stance",
|
||||
"summary"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"relationship_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"source_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"target_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"stance": {
|
||||
"$ref": "#/$defs/variable_map"
|
||||
},
|
||||
"summary": {
|
||||
"type": "string"
|
||||
},
|
||||
"unresolved_incident_ids": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"event": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"event_id",
|
||||
"kind",
|
||||
"summary",
|
||||
"participants",
|
||||
"pressure_tags"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"event_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"kind": {
|
||||
"enum": [
|
||||
"dialogue",
|
||||
"action",
|
||||
"memory",
|
||||
"relationship_shift",
|
||||
"scene_outcome",
|
||||
"author_note"
|
||||
]
|
||||
},
|
||||
"summary": {
|
||||
"type": "string"
|
||||
},
|
||||
"participants": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"pressure_tags": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"observed_exchange": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/event_exchange_turn"
|
||||
}
|
||||
},
|
||||
"private_interpretations": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/event_private_interpretation"
|
||||
}
|
||||
},
|
||||
"event_effects": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/event_effect"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"scene": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"scene_id",
|
||||
"location",
|
||||
"participants",
|
||||
"public_stakes",
|
||||
"hidden_stakes",
|
||||
"dialogue_context_packs"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"scene_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"location": {
|
||||
"type": "string"
|
||||
},
|
||||
"participants": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"public_stakes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"hidden_stakes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"dialogue_context_packs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/dialogue_context_pack"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"dialogue_context_pack": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"speaker_agent_id",
|
||||
"listener_ids",
|
||||
"speaker_local_truth",
|
||||
"speaker_beliefs",
|
||||
"active_memories",
|
||||
"active_goals",
|
||||
"presentation_constraints"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"speaker_agent_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"listener_ids": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"speaker_local_truth": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"speaker_beliefs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"active_memories": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"active_goals": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"presentation_constraints": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"pressure": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"pressure_id",
|
||||
"label",
|
||||
"intensity"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"pressure_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"label": {
|
||||
"type": "string"
|
||||
},
|
||||
"intensity": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
}
|
||||
}
|
||||
},
|
||||
"inferred_variable_map": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"$ref": "#/$defs/inferred_state_variable"
|
||||
}
|
||||
},
|
||||
"inferred_state_variable": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"observed_activation",
|
||||
"attributed_disposition",
|
||||
"confidence"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"observed_activation": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"attributed_disposition": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"confidence": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"evidence": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"event_exchange_turn": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"speaker_id",
|
||||
"utterance_summary",
|
||||
"dialogue_function"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"speaker_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"utterance_summary": {
|
||||
"type": "string"
|
||||
},
|
||||
"dialogue_function": {
|
||||
"type": "string"
|
||||
},
|
||||
"observable_cues": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"event_private_interpretation": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"agent_id",
|
||||
"interpretation",
|
||||
"confidence"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"agent_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"interpretation": {
|
||||
"type": "string"
|
||||
},
|
||||
"attributed_motive": {
|
||||
"type": "string"
|
||||
},
|
||||
"appraisal_tags": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"confidence": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
}
|
||||
}
|
||||
},
|
||||
"event_effect": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"agent_id",
|
||||
"summary"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"agent_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"summary": {
|
||||
"type": "string"
|
||||
},
|
||||
"state_deltas": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/state_delta"
|
||||
}
|
||||
},
|
||||
"new_belief_ids": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"memory_update_ids": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"state_delta": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"path",
|
||||
"delta"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string"
|
||||
},
|
||||
"delta": {
|
||||
"type": "number",
|
||||
"minimum": -1,
|
||||
"maximum": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
11
contracts/swarm-contracts.manifest.json
Normal file
11
contracts/swarm-contracts.manifest.json
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"contracts": [
|
||||
{
|
||||
"schemaPath": "./ghostlight.agent-state.schema.json",
|
||||
"typeName": "GhostlightAgentStateShape",
|
||||
"contractExportName": "ghostlightAgentStateGeneratedContract",
|
||||
"validateExportName": "validateGhostlightAgentStateGenerated",
|
||||
"parseExportName": "parseGhostlightAgentStateGenerated"
|
||||
}
|
||||
]
|
||||
}
|
||||
35
integration/contracts/cultnet.discovery-announce.schema.json
Normal file
35
integration/contracts/cultnet.discovery-announce.schema.json
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.discovery-announce.schema.json",
|
||||
"title": "CultNet Discovery Announce",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"messageId",
|
||||
"runtimeId",
|
||||
"runtimeKind",
|
||||
"displayName",
|
||||
"tcpHost",
|
||||
"tcpPort",
|
||||
"wireContract",
|
||||
"supportedDocumentTypes",
|
||||
"supportsSchemaCatalog"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.discovery_announce.v0" },
|
||||
"messageId": { "type": "string", "minLength": 1 },
|
||||
"runtimeId": { "type": "string", "minLength": 1 },
|
||||
"runtimeKind": { "type": "string", "minLength": 1 },
|
||||
"displayName": { "type": "string", "minLength": 1 },
|
||||
"agentId": { "type": "string", "minLength": 1 },
|
||||
"tcpHost": { "type": "string", "minLength": 1 },
|
||||
"tcpPort": { "type": "integer", "minimum": 1, "maximum": 65535 },
|
||||
"wireContract": { "const": "cultnet.schema.v0" },
|
||||
"supportedDocumentTypes": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 }
|
||||
},
|
||||
"supportsSchemaCatalog": { "type": "boolean" }
|
||||
}
|
||||
}
|
||||
17
integration/contracts/cultnet.discovery-probe.schema.json
Normal file
17
integration/contracts/cultnet.discovery-probe.schema.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.discovery-probe.schema.json",
|
||||
"title": "CultNet Discovery Probe",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"messageId",
|
||||
"requesterRuntimeId"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.discovery_probe.v0" },
|
||||
"messageId": { "type": "string", "minLength": 1 },
|
||||
"requesterRuntimeId": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
26
integration/contracts/cultnet.interop-note.schema.json
Normal file
26
integration/contracts/cultnet.interop-note.schema.json
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-note.schema.json",
|
||||
"title": "CultNet Interop Note",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"documentId",
|
||||
"authorRuntimeId",
|
||||
"title",
|
||||
"body",
|
||||
"tags"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schemaVersion": { "const": "cultnet.interop_note.v0" },
|
||||
"documentId": { "type": "string", "minLength": 1 },
|
||||
"authorRuntimeId": { "type": "string", "minLength": 1 },
|
||||
"title": { "type": "string", "minLength": 1 },
|
||||
"body": { "type": "string", "minLength": 1 },
|
||||
"tags": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
322
package-lock.json
generated
Normal file
322
package-lock.json
generated
Normal file
|
|
@ -0,0 +1,322 @@
|
|||
{
|
||||
"name": "cultnet-ts",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "cultnet-ts",
|
||||
"version": "0.1.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@msgpack/msgpack": "^3.1.3",
|
||||
"ajv": "^8.17.1",
|
||||
"cultcache-ts": "github:GameCult/cultcache-ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.0.0",
|
||||
"json-schema-to-typescript": "^15.0.4",
|
||||
"typescript": "^5.9.0",
|
||||
"zod": "^3.25.76"
|
||||
}
|
||||
},
|
||||
"node_modules/@apidevtools/json-schema-ref-parser": {
|
||||
"version": "11.9.3",
|
||||
"resolved": "https://registry.npmjs.org/@apidevtools/json-schema-ref-parser/-/json-schema-ref-parser-11.9.3.tgz",
|
||||
"integrity": "sha512-60vepv88RwcJtSHrD6MjIL6Ta3SOYbgfnkHb+ppAVK+o9mXprRtulx7VlRl3lN3bbvysAfCS7WMVfhUYemB0IQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jsdevtools/ono": "^7.1.3",
|
||||
"@types/json-schema": "^7.0.15",
|
||||
"js-yaml": "^4.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/philsturgeon"
|
||||
}
|
||||
},
|
||||
"node_modules/@jsdevtools/ono": {
|
||||
"version": "7.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz",
|
||||
"integrity": "sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@msgpack/msgpack": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.3.tgz",
|
||||
"integrity": "sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">= 18"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/json-schema": {
|
||||
"version": "7.0.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
|
||||
"integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/lodash": {
|
||||
"version": "4.17.24",
|
||||
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.24.tgz",
|
||||
"integrity": "sha512-gIW7lQLZbue7lRSWEFql49QJJWThrTFFeIMJdp3eH4tKoxm1OvEPg02rm4wCCSHS0cL3/Fizimb35b7k8atwsQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "24.12.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.2.tgz",
|
||||
"integrity": "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~7.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ajv": {
|
||||
"version": "8.20.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
|
||||
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
"json-schema-traverse": "^1.0.0",
|
||||
"require-from-string": "^2.0.2"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/epoberezkin"
|
||||
}
|
||||
},
|
||||
"node_modules/argparse": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
|
||||
"dev": true,
|
||||
"license": "Python-2.0"
|
||||
},
|
||||
"node_modules/cultcache-ts": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "git+ssh://git@github.com/GameCult/cultcache-ts.git#6c2e1e3691146f99c44c098371cc8c787b4a8d0c",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@msgpack/msgpack": "^3.1.3",
|
||||
"zod": "^3.25.76"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-deep-equal": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-uri": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
|
||||
"integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fastify"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fastify"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/fdir": {
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"picomatch": "^3 || ^4"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"picomatch": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/is-extglob": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-glob": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
|
||||
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"is-extglob": "^2.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
|
||||
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"argparse": "^2.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"js-yaml": "bin/js-yaml.js"
|
||||
}
|
||||
},
|
||||
"node_modules/json-schema-to-typescript": {
|
||||
"version": "15.0.4",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-to-typescript/-/json-schema-to-typescript-15.0.4.tgz",
|
||||
"integrity": "sha512-Su9oK8DR4xCmDsLlyvadkXzX6+GGXJpbhwoLtOGArAG61dvbW4YQmSEno2y66ahpIdmLMg6YUf/QHLgiwvkrHQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@apidevtools/json-schema-ref-parser": "^11.5.5",
|
||||
"@types/json-schema": "^7.0.15",
|
||||
"@types/lodash": "^4.17.7",
|
||||
"is-glob": "^4.0.3",
|
||||
"js-yaml": "^4.1.0",
|
||||
"lodash": "^4.17.21",
|
||||
"minimist": "^1.2.8",
|
||||
"prettier": "^3.2.5",
|
||||
"tinyglobby": "^0.2.9"
|
||||
},
|
||||
"bin": {
|
||||
"json2ts": "dist/src/cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/json-schema-traverse": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
|
||||
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash": {
|
||||
"version": "4.18.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
|
||||
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/minimist": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
|
||||
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/picomatch": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
|
||||
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/prettier": {
|
||||
"version": "3.8.3",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.3.tgz",
|
||||
"integrity": "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"prettier": "bin/prettier.cjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/require-from-string": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
|
||||
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.16",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz",
|
||||
"integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/SuperchupuDev"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "7.16.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
|
||||
"integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "3.25.76",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
|
||||
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
39
package.json
Normal file
39
package.json
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
{
|
||||
"name": "cultnet-ts",
|
||||
"version": "0.1.0",
|
||||
"description": "CultNet-style typed direct-pipe messaging and state replication for TypeScript runtimes.",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist",
|
||||
"contracts"
|
||||
],
|
||||
"scripts": {
|
||||
"contracts:generate": "node tools/generate-swarm-contracts.mjs",
|
||||
"build": "npm run contracts:generate && tsc -p tsconfig.json",
|
||||
"typecheck": "npm run contracts:generate && tsc -p tsconfig.json --pretty false",
|
||||
"test": "npm run build && tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js",
|
||||
"test:interop": "npm run build && tsc -p tsconfig.test.json && node --test dist-test/test/interop/*.test.js"
|
||||
},
|
||||
"keywords": [
|
||||
"messagepack",
|
||||
"networking",
|
||||
"pipes",
|
||||
"cultcache",
|
||||
"gamecult",
|
||||
"typescript"
|
||||
],
|
||||
"author": "metacratic",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@msgpack/msgpack": "^3.1.3",
|
||||
"ajv": "^8.17.1",
|
||||
"cultcache-ts": "github:GameCult/cultcache-ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.0.0",
|
||||
"json-schema-to-typescript": "^15.0.4",
|
||||
"typescript": "^5.9.0",
|
||||
"zod": "^3.25.76"
|
||||
}
|
||||
}
|
||||
970
src/contracts.ts
Normal file
970
src/contracts.ts
Normal file
|
|
@ -0,0 +1,970 @@
|
|||
import Ajv2020, { type ValidateFunction } from "ajv/dist/2020";
|
||||
|
||||
import documentRecordSchema from "../contracts/cultnet.document-record.schema.json";
|
||||
import helloSchema from "../contracts/cultnet.hello.schema.json";
|
||||
import loginSchema from "../contracts/cultnet.login.schema.json";
|
||||
import registerSchema from "../contracts/cultnet.register.schema.json";
|
||||
import verifySchema from "../contracts/cultnet.verify.schema.json";
|
||||
import loginSuccessSchema from "../contracts/cultnet.login-success.schema.json";
|
||||
import errorSchema from "../contracts/cultnet.error.schema.json";
|
||||
import sampleChangeNameSchema from "../contracts/cultnet.sample-change-name.schema.json";
|
||||
import sampleChatSchema from "../contracts/cultnet.sample-chat.schema.json";
|
||||
import documentPutSchema from "../contracts/cultnet.document-put.schema.json";
|
||||
import documentDeleteSchema from "../contracts/cultnet.document-delete.schema.json";
|
||||
import rawDocumentRecordSchema from "../contracts/cultnet.raw-document-record.schema.json";
|
||||
import documentPutRawSchema from "../contracts/cultnet.document-put-raw.schema.json";
|
||||
import documentMutationContractSchema from "../contracts/cultnet.document-mutation-contract.schema.json";
|
||||
import snapshotRequestSchema from "../contracts/cultnet.snapshot-request.schema.json";
|
||||
import snapshotResponseSchema from "../contracts/cultnet.snapshot-response.schema.json";
|
||||
import snapshotResponseRawSchema from "../contracts/cultnet.snapshot-response-raw.schema.json";
|
||||
import schemaDescriptorSchema from "../contracts/cultnet.schema-descriptor.schema.json";
|
||||
import schemaCatalogRequestSchema from "../contracts/cultnet.schema-catalog-request.schema.json";
|
||||
import schemaCatalogResponseSchema from "../contracts/cultnet.schema-catalog-response.schema.json";
|
||||
import ghostlightAgentStateSchema from "../contracts/ghostlight.agent-state.schema.json";
|
||||
|
||||
export type CultNetWireContract = "cultnet.schema.v0" | "gamecult.networking.v0";
|
||||
|
||||
export type CultNetSchemaVersion =
|
||||
| "cultnet.hello.v0"
|
||||
| "cultnet.login.v0"
|
||||
| "cultnet.register.v0"
|
||||
| "cultnet.verify.v0"
|
||||
| "cultnet.login_success.v0"
|
||||
| "cultnet.error.v0"
|
||||
| "cultnet.sample.change_name.v0"
|
||||
| "cultnet.sample.chat.v0"
|
||||
| "cultnet.document_put.v0"
|
||||
| "cultnet.document_delete.v0"
|
||||
| "cultnet.document_put_raw.v0"
|
||||
| "cultnet.snapshot_request.v0"
|
||||
| "cultnet.snapshot_response.v0"
|
||||
| "cultnet.snapshot_response_raw.v0"
|
||||
| "cultnet.schema_catalog_request.v0"
|
||||
| "cultnet.schema_catalog_response.v0";
|
||||
|
||||
export type CultNetSchemaKind = "wire_message" | "document_payload" | "shared_contract";
|
||||
export type CultNetRawPayloadEncoding = "messagepack";
|
||||
|
||||
export interface CultNetDocumentMutationContract {
|
||||
documentType: string;
|
||||
payloadSchemaVersion?: string;
|
||||
operations: string[];
|
||||
authority: "readOnly" | "localUser" | "coordinator" | "runtime" | "denied";
|
||||
intentDocumentTypes?: string[];
|
||||
receiptDocumentTypes?: string[];
|
||||
notes?: string[];
|
||||
}
|
||||
|
||||
export interface CultNetDocumentRecord<TPayload = unknown> {
|
||||
schemaId: string;
|
||||
recordKey: string;
|
||||
storedAt: string;
|
||||
payload: TPayload;
|
||||
sourceRuntimeId?: string;
|
||||
sourceAgentId?: string;
|
||||
sourceRole?: string;
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
export interface CultNetHelloMessage {
|
||||
schemaVersion: "cultnet.hello.v0";
|
||||
runtimeId: string;
|
||||
runtimeKind: string;
|
||||
agentId?: string;
|
||||
role?: string;
|
||||
displayName?: string;
|
||||
supportedDocumentTypes?: string[];
|
||||
supportedMutationContracts?: CultNetDocumentMutationContract[];
|
||||
supportedMessageVersions?: string[];
|
||||
supportsSchemaCatalog?: boolean;
|
||||
}
|
||||
|
||||
export interface CultNetLoginMessage {
|
||||
schemaVersion: "cultnet.login.v0";
|
||||
nonce: string;
|
||||
auth: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface CultNetRegisterMessage {
|
||||
schemaVersion: "cultnet.register.v0";
|
||||
nonce: string;
|
||||
email: string;
|
||||
password: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface CultNetVerifyMessage {
|
||||
schemaVersion: "cultnet.verify.v0";
|
||||
nonce: string;
|
||||
session: string;
|
||||
}
|
||||
|
||||
export interface CultNetLoginSuccessMessage {
|
||||
schemaVersion: "cultnet.login_success.v0";
|
||||
nonce: string;
|
||||
session: string;
|
||||
}
|
||||
|
||||
export interface CultNetErrorMessage {
|
||||
schemaVersion: "cultnet.error.v0";
|
||||
error: string;
|
||||
}
|
||||
|
||||
export interface CultNetSampleChangeNameMessage {
|
||||
schemaVersion: "cultnet.sample.change_name.v0";
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface CultNetSampleChatMessage {
|
||||
schemaVersion: "cultnet.sample.chat.v0";
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface CultNetDocumentPutMessage<TPayload = unknown> {
|
||||
schemaVersion: "cultnet.document_put.v0";
|
||||
messageId: string;
|
||||
document: CultNetDocumentRecord<TPayload>;
|
||||
}
|
||||
|
||||
export interface CultNetDocumentDeleteMessage {
|
||||
schemaVersion: "cultnet.document_delete.v0";
|
||||
messageId: string;
|
||||
schemaId: string;
|
||||
recordKey: string;
|
||||
}
|
||||
|
||||
export interface CultNetRawDocumentRecord {
|
||||
schemaId: string;
|
||||
recordKey: string;
|
||||
storedAt: string;
|
||||
payloadEncoding: CultNetRawPayloadEncoding;
|
||||
payload: Uint8Array;
|
||||
sourceRuntimeId?: string;
|
||||
sourceAgentId?: string;
|
||||
sourceRole?: string;
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
export interface CultNetDocumentPutRawMessage {
|
||||
schemaVersion: "cultnet.document_put_raw.v0";
|
||||
messageId: string;
|
||||
document: CultNetRawDocumentRecord;
|
||||
}
|
||||
|
||||
export interface CultNetSnapshotRequestMessage {
|
||||
schemaVersion: "cultnet.snapshot_request.v0";
|
||||
messageId: string;
|
||||
schemaIds?: string[];
|
||||
recordKeys?: string[];
|
||||
}
|
||||
|
||||
export interface CultNetSnapshotResponseMessage<TPayload = unknown> {
|
||||
schemaVersion: "cultnet.snapshot_response.v0";
|
||||
messageId: string;
|
||||
documents: CultNetDocumentRecord<TPayload>[];
|
||||
}
|
||||
|
||||
export interface CultNetSnapshotResponseRawMessage {
|
||||
schemaVersion: "cultnet.snapshot_response_raw.v0";
|
||||
messageId: string;
|
||||
documents: CultNetRawDocumentRecord[];
|
||||
}
|
||||
|
||||
export interface CultNetSchemaDescriptor {
|
||||
schemaId: string;
|
||||
kind: CultNetSchemaKind;
|
||||
schemaVersion?: string;
|
||||
documentType?: string;
|
||||
title?: string;
|
||||
wireContracts: CultNetWireContract[];
|
||||
contentHash: string;
|
||||
schemaJson?: string;
|
||||
}
|
||||
|
||||
export interface CultNetSchemaCatalogRequestMessage {
|
||||
schemaVersion: "cultnet.schema_catalog_request.v0";
|
||||
messageId: string;
|
||||
includeSchemaJson?: boolean;
|
||||
schemaIds?: string[];
|
||||
kinds?: CultNetSchemaKind[];
|
||||
}
|
||||
|
||||
export interface CultNetSchemaCatalogResponseMessage {
|
||||
schemaVersion: "cultnet.schema_catalog_response.v0";
|
||||
messageId: string;
|
||||
schemas: CultNetSchemaDescriptor[];
|
||||
}
|
||||
|
||||
export interface GhostlightPressure {
|
||||
pressure_id: string;
|
||||
label: string;
|
||||
intensity: number;
|
||||
}
|
||||
|
||||
export interface GhostlightWorldTime {
|
||||
label: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface GhostlightWorldState {
|
||||
world_id: string;
|
||||
setting: string;
|
||||
time: GhostlightWorldTime;
|
||||
canon_context: string[];
|
||||
ambient_pressures?: GhostlightPressure[];
|
||||
}
|
||||
|
||||
export interface GhostlightIdentity {
|
||||
name: string;
|
||||
roles: string[];
|
||||
origin: string;
|
||||
public_description: string;
|
||||
private_notes?: string[];
|
||||
}
|
||||
|
||||
export interface GhostlightStateVariable {
|
||||
mean: number;
|
||||
plasticity: number;
|
||||
current_activation: number;
|
||||
evidence?: string[];
|
||||
}
|
||||
|
||||
export type GhostlightVariableMap = Record<string, GhostlightStateVariable>;
|
||||
|
||||
export interface GhostlightInferredStateVariable {
|
||||
observed_activation: number;
|
||||
attributed_disposition: number;
|
||||
confidence: number;
|
||||
evidence?: string[];
|
||||
}
|
||||
|
||||
export type GhostlightInferredVariableMap = Record<string, GhostlightInferredStateVariable>;
|
||||
|
||||
export interface GhostlightValueCommitment {
|
||||
value_id: string;
|
||||
label: string;
|
||||
priority: number;
|
||||
unforgivable_if_betrayed: boolean;
|
||||
}
|
||||
|
||||
export type GhostlightGoalScope = "immediate" | "scene" | "case" | "arc" | "life";
|
||||
export type GhostlightGoalStatus = "active" | "blocked" | "dormant" | "resolved" | "abandoned";
|
||||
|
||||
export interface GhostlightGoal {
|
||||
goal_id: string;
|
||||
description: string;
|
||||
scope: GhostlightGoalScope;
|
||||
priority: number;
|
||||
emotional_stake: string;
|
||||
blockers?: string[];
|
||||
status: GhostlightGoalStatus;
|
||||
}
|
||||
|
||||
export interface GhostlightMemory {
|
||||
memory_id: string;
|
||||
summary: string;
|
||||
salience: number;
|
||||
confidence: number;
|
||||
linked_event_ids?: string[];
|
||||
linked_relationship_id?: string;
|
||||
}
|
||||
|
||||
export interface GhostlightMemoryBundle {
|
||||
episodic: GhostlightMemory[];
|
||||
semantic: GhostlightMemory[];
|
||||
relationship_summaries: GhostlightMemory[];
|
||||
}
|
||||
|
||||
export interface GhostlightCanonicalState {
|
||||
underlying_organization: GhostlightVariableMap;
|
||||
stable_dispositions: GhostlightVariableMap;
|
||||
behavioral_dimensions: GhostlightVariableMap;
|
||||
presentation_strategy: GhostlightVariableMap;
|
||||
voice_style: GhostlightVariableMap;
|
||||
situational_state: GhostlightVariableMap;
|
||||
values: GhostlightValueCommitment[];
|
||||
}
|
||||
|
||||
export type GhostlightBeliefClaimType =
|
||||
| "fact"
|
||||
| "identity_inference"
|
||||
| "motive_inference"
|
||||
| "prediction"
|
||||
| "norm"
|
||||
| "value_read"
|
||||
| "relationship_read";
|
||||
|
||||
export type GhostlightBeliefVisibility = "private" | "shared" | "public" | "rumor";
|
||||
|
||||
export interface GhostlightBelief {
|
||||
belief_id: string;
|
||||
claim: string;
|
||||
confidence: number;
|
||||
subject_id?: string;
|
||||
claim_type?: GhostlightBeliefClaimType;
|
||||
evidence_event_ids?: string[];
|
||||
visibility?: GhostlightBeliefVisibility;
|
||||
emotional_charge?: number;
|
||||
}
|
||||
|
||||
export type GhostlightPerceivedDistortion =
|
||||
| "hostile_attribution"
|
||||
| "false_reassurance"
|
||||
| "overread_warmth"
|
||||
| "underread_threat"
|
||||
| "false_mask_detection"
|
||||
| "missed_mask_detection"
|
||||
| "status_injury"
|
||||
| "threat_amplification"
|
||||
| "institutional_suspicion_transfer"
|
||||
| "care_underread"
|
||||
| "mask_overfocus";
|
||||
|
||||
export interface GhostlightPerceivedStateOverlay {
|
||||
observer_agent_id: string;
|
||||
target_agent_id: string;
|
||||
perceived_dimensions: GhostlightInferredVariableMap;
|
||||
beliefs: GhostlightBelief[];
|
||||
distortions: GhostlightPerceivedDistortion[];
|
||||
}
|
||||
|
||||
export interface GhostlightAgent {
|
||||
agent_id: string;
|
||||
identity: GhostlightIdentity;
|
||||
canonical_state: GhostlightCanonicalState;
|
||||
goals: GhostlightGoal[];
|
||||
memories: GhostlightMemoryBundle;
|
||||
perceived_state_overlays: GhostlightPerceivedStateOverlay[];
|
||||
}
|
||||
|
||||
export interface GhostlightRelationship {
|
||||
relationship_id: string;
|
||||
source_id: string;
|
||||
target_id: string;
|
||||
stance: GhostlightVariableMap;
|
||||
summary: string;
|
||||
unresolved_incident_ids?: string[];
|
||||
}
|
||||
|
||||
export type GhostlightEventKind =
|
||||
| "dialogue"
|
||||
| "action"
|
||||
| "memory"
|
||||
| "relationship_shift"
|
||||
| "scene_outcome"
|
||||
| "author_note";
|
||||
|
||||
export interface GhostlightEventExchangeTurn {
|
||||
speaker_id: string;
|
||||
utterance_summary: string;
|
||||
dialogue_function: string;
|
||||
observable_cues?: string[];
|
||||
}
|
||||
|
||||
export interface GhostlightEventPrivateInterpretation {
|
||||
agent_id: string;
|
||||
interpretation: string;
|
||||
attributed_motive?: string;
|
||||
appraisal_tags?: string[];
|
||||
confidence: number;
|
||||
}
|
||||
|
||||
export interface GhostlightStateDelta {
|
||||
path: string;
|
||||
delta: number;
|
||||
}
|
||||
|
||||
export interface GhostlightEventEffect {
|
||||
agent_id: string;
|
||||
summary: string;
|
||||
state_deltas?: GhostlightStateDelta[];
|
||||
new_belief_ids?: string[];
|
||||
memory_update_ids?: string[];
|
||||
}
|
||||
|
||||
export interface GhostlightEvent {
|
||||
event_id: string;
|
||||
kind: GhostlightEventKind;
|
||||
summary: string;
|
||||
participants: string[];
|
||||
pressure_tags: string[];
|
||||
observed_exchange?: GhostlightEventExchangeTurn[];
|
||||
private_interpretations?: GhostlightEventPrivateInterpretation[];
|
||||
event_effects?: GhostlightEventEffect[];
|
||||
}
|
||||
|
||||
export interface GhostlightDialogueContextPack {
|
||||
speaker_agent_id: string;
|
||||
listener_ids: string[];
|
||||
speaker_local_truth: string[];
|
||||
speaker_beliefs: string[];
|
||||
active_memories: string[];
|
||||
active_goals: string[];
|
||||
presentation_constraints: string[];
|
||||
}
|
||||
|
||||
export interface GhostlightScene {
|
||||
scene_id: string;
|
||||
location: string;
|
||||
participants: string[];
|
||||
public_stakes: string[];
|
||||
hidden_stakes: string[];
|
||||
dialogue_context_packs: GhostlightDialogueContextPack[];
|
||||
}
|
||||
|
||||
export interface GhostlightAgentStateDocument {
|
||||
schema_version: "ghostlight.agent_state.v0";
|
||||
world: GhostlightWorldState;
|
||||
agents: GhostlightAgent[];
|
||||
relationships: GhostlightRelationship[];
|
||||
events: GhostlightEvent[];
|
||||
scenes: GhostlightScene[];
|
||||
}
|
||||
|
||||
export type CultNetMessage =
|
||||
| CultNetHelloMessage
|
||||
| CultNetLoginMessage
|
||||
| CultNetRegisterMessage
|
||||
| CultNetVerifyMessage
|
||||
| CultNetLoginSuccessMessage
|
||||
| CultNetErrorMessage
|
||||
| CultNetSampleChangeNameMessage
|
||||
| CultNetSampleChatMessage
|
||||
| CultNetDocumentPutMessage
|
||||
| CultNetDocumentDeleteMessage
|
||||
| CultNetDocumentPutRawMessage
|
||||
| CultNetSnapshotRequestMessage
|
||||
| CultNetSnapshotResponseMessage
|
||||
| CultNetSnapshotResponseRawMessage
|
||||
| CultNetSchemaCatalogRequestMessage
|
||||
| CultNetSchemaCatalogResponseMessage;
|
||||
|
||||
const ajv = new Ajv2020({
|
||||
allErrors: true,
|
||||
strict: false,
|
||||
});
|
||||
|
||||
const CULTNET_MESSAGE_SCHEMAS = [
|
||||
helloSchema,
|
||||
loginSchema,
|
||||
registerSchema,
|
||||
verifySchema,
|
||||
loginSuccessSchema,
|
||||
errorSchema,
|
||||
sampleChangeNameSchema,
|
||||
sampleChatSchema,
|
||||
documentPutSchema,
|
||||
documentDeleteSchema,
|
||||
documentPutRawSchema,
|
||||
snapshotRequestSchema,
|
||||
snapshotResponseSchema,
|
||||
snapshotResponseRawSchema,
|
||||
schemaCatalogRequestSchema,
|
||||
schemaCatalogResponseSchema,
|
||||
] as const;
|
||||
|
||||
const cultNetValidators = new Map<CultNetSchemaVersion, ValidateFunction>();
|
||||
for (const schema of [
|
||||
documentRecordSchema,
|
||||
rawDocumentRecordSchema,
|
||||
documentMutationContractSchema,
|
||||
schemaDescriptorSchema,
|
||||
...CULTNET_MESSAGE_SCHEMAS,
|
||||
]) {
|
||||
ajv.addSchema(schema);
|
||||
}
|
||||
|
||||
for (const schema of CULTNET_MESSAGE_SCHEMAS) {
|
||||
const schemaVersion = schema.properties.schemaVersion.const as CultNetSchemaVersion;
|
||||
cultNetValidators.set(schemaVersion, ajv.compile(schema));
|
||||
}
|
||||
|
||||
const ghostlightAgentStateValidator = ajv.compile(ghostlightAgentStateSchema);
|
||||
|
||||
export function parseCultNetMessage(input: unknown, wireContract: CultNetWireContract = "cultnet.schema.v0"): CultNetMessage {
|
||||
if (wireContract === "gamecult.networking.v0") {
|
||||
return parseGameCultNetworkingMessage(input);
|
||||
}
|
||||
|
||||
if (!input || typeof input !== "object") {
|
||||
throw new Error("CultNet message must be an object.");
|
||||
}
|
||||
|
||||
const schemaVersion = (input as { schemaVersion?: string }).schemaVersion as CultNetSchemaVersion | undefined;
|
||||
if (!schemaVersion) {
|
||||
throw new Error("CultNet message is missing schemaVersion.");
|
||||
}
|
||||
|
||||
normalizeCultNetOptionalNulls(input as Record<string, unknown>, schemaVersion);
|
||||
|
||||
const validator = cultNetValidators.get(schemaVersion);
|
||||
if (!validator) {
|
||||
throw new Error(`Unsupported CultNet schemaVersion "${schemaVersion}".`);
|
||||
}
|
||||
|
||||
if (schemaVersion === "cultnet.document_put_raw.v0") {
|
||||
validateDocumentPutRawMessage(input);
|
||||
return input as CultNetDocumentPutRawMessage;
|
||||
}
|
||||
|
||||
if (schemaVersion === "cultnet.snapshot_response_raw.v0") {
|
||||
validateSnapshotResponseRawMessage(input);
|
||||
return input as CultNetSnapshotResponseRawMessage;
|
||||
}
|
||||
|
||||
if (!validator(input)) {
|
||||
throw new Error(renderValidationErrors(schemaVersion, validator));
|
||||
}
|
||||
|
||||
return input as CultNetMessage;
|
||||
}
|
||||
|
||||
export function encodeCultNetMessageForWire(
|
||||
message: CultNetMessage,
|
||||
wireContract: CultNetWireContract = "cultnet.schema.v0",
|
||||
): unknown {
|
||||
if (wireContract === "gamecult.networking.v0") {
|
||||
return encodeGameCultNetworkingMessage(message);
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
export function validateGhostlightAgentState(input: unknown): GhostlightAgentStateDocument {
|
||||
if (!ghostlightAgentStateValidator(input)) {
|
||||
throw new Error(renderValidationErrors("ghostlight.agent_state.v0", ghostlightAgentStateValidator));
|
||||
}
|
||||
|
||||
return input as unknown as GhostlightAgentStateDocument;
|
||||
}
|
||||
|
||||
function renderValidationErrors(schemaVersion: string, validator: ValidateFunction): string {
|
||||
const details = validator.errors?.map((error) => {
|
||||
const location = error.instancePath.length > 0 ? error.instancePath : "/";
|
||||
return `${location}: ${error.message}`;
|
||||
}) ?? ["unknown validation failure"];
|
||||
return `Validation failed for ${schemaVersion}: ${details.join("; ")}`;
|
||||
}
|
||||
|
||||
function parseGameCultNetworkingMessage(input: unknown): CultNetMessage {
|
||||
if (!Array.isArray(input) || input.length !== 2) {
|
||||
throw new Error("gamecult.networking.v0 messages must be a 2-element union array.");
|
||||
}
|
||||
|
||||
const [unionTag, payload] = input;
|
||||
if (!Number.isInteger(unionTag)) {
|
||||
throw new Error("gamecult.networking.v0 message tag must be an integer.");
|
||||
}
|
||||
if (!Array.isArray(payload)) {
|
||||
throw new Error("gamecult.networking.v0 message payload must be an array.");
|
||||
}
|
||||
|
||||
switch (unionTag) {
|
||||
case 0:
|
||||
return {
|
||||
schemaVersion: "cultnet.login.v0",
|
||||
nonce: requireLegacyBytes(payload[0], "LoginMessage.Nonce"),
|
||||
auth: requireLegacyBytes(payload[1], "LoginMessage.Auth"),
|
||||
password: requireLegacyBytes(payload[2], "LoginMessage.Password"),
|
||||
};
|
||||
case 1:
|
||||
return {
|
||||
schemaVersion: "cultnet.register.v0",
|
||||
nonce: requireLegacyBytes(payload[0], "RegisterMessage.Nonce"),
|
||||
email: requireLegacyBytes(payload[1], "RegisterMessage.Email"),
|
||||
password: requireLegacyBytes(payload[2], "RegisterMessage.Password"),
|
||||
name: requireLegacyBytes(payload[3], "RegisterMessage.Name"),
|
||||
};
|
||||
case 2:
|
||||
return {
|
||||
schemaVersion: "cultnet.verify.v0",
|
||||
nonce: requireLegacyBytes(payload[0], "VerifyMessage.Nonce"),
|
||||
session: requireLegacyBytes(payload[1], "VerifyMessage.Session"),
|
||||
};
|
||||
case 3:
|
||||
return {
|
||||
schemaVersion: "cultnet.login_success.v0",
|
||||
nonce: requireLegacyBytes(payload[0], "LoginSuccessMessage.Nonce"),
|
||||
session: requireLegacyBytes(payload[1], "LoginSuccessMessage.Session"),
|
||||
};
|
||||
case 4:
|
||||
return {
|
||||
schemaVersion: "cultnet.error.v0",
|
||||
error: requireLegacyString(payload[0], "ErrorMessage.Error"),
|
||||
};
|
||||
case 5:
|
||||
return {
|
||||
schemaVersion: "cultnet.sample.change_name.v0",
|
||||
name: requireLegacyString(payload[0], "ChangeNameMessage.Name"),
|
||||
};
|
||||
case 6:
|
||||
return {
|
||||
schemaVersion: "cultnet.sample.chat.v0",
|
||||
text: requireLegacyString(payload[0], "ChatMessage.Text"),
|
||||
};
|
||||
case 7:
|
||||
return {
|
||||
schemaVersion: "cultnet.schema_catalog_request.v0",
|
||||
messageId: requireLegacyString(payload[0], "SchemaCatalogRequestMessage.MessageId"),
|
||||
includeSchemaJson: requireLegacyBoolean(payload[1], "SchemaCatalogRequestMessage.IncludeSchemaJson"),
|
||||
schemaIds: requireLegacyOptionalStringArray(payload[2], "SchemaCatalogRequestMessage.SchemaIds"),
|
||||
kinds: requireLegacyOptionalSchemaKindArray(payload[3], "SchemaCatalogRequestMessage.Kinds"),
|
||||
};
|
||||
case 8:
|
||||
return {
|
||||
schemaVersion: "cultnet.schema_catalog_response.v0",
|
||||
messageId: requireLegacyString(payload[0], "SchemaCatalogResponseMessage.MessageId"),
|
||||
schemas: requireLegacySchemaDescriptorArray(payload[1], "SchemaCatalogResponseMessage.Schemas"),
|
||||
};
|
||||
default:
|
||||
throw new Error(`Unsupported gamecult.networking.v0 union tag "${unionTag}".`);
|
||||
}
|
||||
}
|
||||
|
||||
function encodeGameCultNetworkingMessage(message: CultNetMessage): [number, unknown[]] {
|
||||
switch (message.schemaVersion) {
|
||||
case "cultnet.login.v0":
|
||||
return [0, [
|
||||
decodeBase64Url(message.nonce, "LoginMessage.Nonce"),
|
||||
decodeBase64Url(message.auth, "LoginMessage.Auth"),
|
||||
decodeBase64Url(message.password, "LoginMessage.Password"),
|
||||
]];
|
||||
case "cultnet.register.v0":
|
||||
return [1, [
|
||||
decodeBase64Url(message.nonce, "RegisterMessage.Nonce"),
|
||||
decodeBase64Url(message.email, "RegisterMessage.Email"),
|
||||
decodeBase64Url(message.password, "RegisterMessage.Password"),
|
||||
decodeBase64Url(message.name, "RegisterMessage.Name"),
|
||||
]];
|
||||
case "cultnet.verify.v0":
|
||||
return [2, [
|
||||
decodeBase64Url(message.nonce, "VerifyMessage.Nonce"),
|
||||
decodeBase64Url(message.session, "VerifyMessage.Session"),
|
||||
]];
|
||||
case "cultnet.login_success.v0":
|
||||
return [3, [
|
||||
decodeBase64Url(message.nonce, "LoginSuccessMessage.Nonce"),
|
||||
decodeBase64Url(message.session, "LoginSuccessMessage.Session"),
|
||||
]];
|
||||
case "cultnet.error.v0":
|
||||
return [4, [message.error]];
|
||||
case "cultnet.sample.change_name.v0":
|
||||
return [5, [message.name]];
|
||||
case "cultnet.sample.chat.v0":
|
||||
return [6, [message.text]];
|
||||
case "cultnet.schema_catalog_request.v0":
|
||||
return [7, [
|
||||
message.messageId,
|
||||
message.includeSchemaJson ?? false,
|
||||
message.schemaIds ?? null,
|
||||
message.kinds ?? null,
|
||||
]];
|
||||
case "cultnet.schema_catalog_response.v0":
|
||||
return [8, [
|
||||
message.messageId,
|
||||
message.schemas.map((schema) => encodeLegacySchemaDescriptor(schema)),
|
||||
]];
|
||||
case "cultnet.document_put_raw.v0":
|
||||
case "cultnet.snapshot_response_raw.v0":
|
||||
throw new Error(
|
||||
`Message "${message.schemaVersion}" is not defined in the gamecult.networking.v0 contract.`,
|
||||
);
|
||||
default:
|
||||
throw new Error(
|
||||
`Message "${message.schemaVersion}" is not defined in the gamecult.networking.v0 contract.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function requireLegacyBytes(input: unknown, fieldName: string): string {
|
||||
if (!(input instanceof Uint8Array)) {
|
||||
throw new Error(`${fieldName} must be binary data in gamecult.networking.v0.`);
|
||||
}
|
||||
|
||||
return encodeBase64Url(input);
|
||||
}
|
||||
|
||||
function requireLegacyString(input: unknown, fieldName: string): string {
|
||||
if (typeof input !== "string") {
|
||||
throw new Error(`${fieldName} must be a string in gamecult.networking.v0.`);
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
function requireLegacyBoolean(input: unknown, fieldName: string): boolean {
|
||||
if (typeof input !== "boolean") {
|
||||
throw new Error(`${fieldName} must be a boolean in gamecult.networking.v0.`);
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
function requireLegacyOptionalStringArray(input: unknown, fieldName: string): string[] | undefined {
|
||||
if (input === null || typeof input === "undefined") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!Array.isArray(input) || input.some((item) => typeof item !== "string")) {
|
||||
throw new Error(`${fieldName} must be an array of strings in gamecult.networking.v0.`);
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
function requireLegacyOptionalSchemaKindArray(input: unknown, fieldName: string): CultNetSchemaKind[] | undefined {
|
||||
const values = requireLegacyOptionalStringArray(input, fieldName);
|
||||
|
||||
if (!values) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
for (const value of values) {
|
||||
if (value !== "wire_message" && value !== "document_payload" && value !== "shared_contract") {
|
||||
throw new Error(`${fieldName} has unsupported schema kind "${value}".`);
|
||||
}
|
||||
}
|
||||
|
||||
return values as CultNetSchemaKind[];
|
||||
}
|
||||
|
||||
function requireLegacySchemaDescriptorArray(input: unknown, fieldName: string): CultNetSchemaDescriptor[] {
|
||||
if (!Array.isArray(input)) {
|
||||
throw new Error(`${fieldName} must be an array in gamecult.networking.v0.`);
|
||||
}
|
||||
|
||||
return input.map((value, index) => requireLegacySchemaDescriptor(value, `${fieldName}[${index}]`));
|
||||
}
|
||||
|
||||
function requireLegacySchemaDescriptor(input: unknown, fieldName: string): CultNetSchemaDescriptor {
|
||||
if (!input || typeof input !== "object") {
|
||||
throw new Error(`${fieldName} must be an object in gamecult.networking.v0.`);
|
||||
}
|
||||
|
||||
const candidate = input as Record<string, unknown>;
|
||||
const schemaId = requireLegacyString(candidate.schemaId, `${fieldName}.SchemaId`);
|
||||
const kind = requireLegacyString(candidate.kind, `${fieldName}.Kind`);
|
||||
const wireContracts = requireLegacyOptionalStringArray(candidate.wireContracts, `${fieldName}.WireContracts`) ?? [];
|
||||
const contentHash = requireLegacyString(candidate.contentHash, `${fieldName}.ContentHash`);
|
||||
const schemaVersion = requireLegacyOptionalString(candidate.schemaVersion, `${fieldName}.SchemaVersion`);
|
||||
const documentType = requireLegacyOptionalString(candidate.documentType, `${fieldName}.DocumentType`);
|
||||
const title = requireLegacyOptionalString(candidate.title, `${fieldName}.Title`);
|
||||
const schemaJson = requireLegacyOptionalString(candidate.schemaJson, `${fieldName}.SchemaJson`);
|
||||
|
||||
if (kind !== "wire_message" && kind !== "document_payload" && kind !== "shared_contract") {
|
||||
throw new Error(`${fieldName}.Kind has unsupported schema kind "${kind}".`);
|
||||
}
|
||||
|
||||
const normalizedWireContracts = wireContracts.map((value) => {
|
||||
if (value !== "cultnet.schema.v0" && value !== "gamecult.networking.v0") {
|
||||
throw new Error(`${fieldName}.WireContracts contains unsupported wire contract "${value}".`);
|
||||
}
|
||||
|
||||
return value;
|
||||
});
|
||||
|
||||
return {
|
||||
schemaId,
|
||||
kind,
|
||||
schemaVersion,
|
||||
documentType,
|
||||
title,
|
||||
wireContracts: normalizedWireContracts as CultNetWireContract[],
|
||||
contentHash,
|
||||
schemaJson,
|
||||
};
|
||||
}
|
||||
|
||||
function requireLegacyOptionalString(input: unknown, fieldName: string): string | undefined {
|
||||
if (input === null || typeof input === "undefined") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return requireLegacyString(input, fieldName);
|
||||
}
|
||||
|
||||
function encodeLegacySchemaDescriptor(schema: CultNetSchemaDescriptor): Record<string, unknown> {
|
||||
return {
|
||||
schemaId: schema.schemaId,
|
||||
kind: schema.kind,
|
||||
schemaVersion: schema.schemaVersion ?? null,
|
||||
documentType: schema.documentType ?? null,
|
||||
title: schema.title ?? null,
|
||||
wireContracts: schema.wireContracts,
|
||||
contentHash: schema.contentHash,
|
||||
schemaJson: schema.schemaJson ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function encodeBase64Url(input: Uint8Array): string {
|
||||
return Buffer.from(input)
|
||||
.toString("base64")
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/u, "");
|
||||
}
|
||||
|
||||
function decodeBase64Url(input: string, fieldName: string): Uint8Array {
|
||||
if (!input || input.trim().length === 0) {
|
||||
throw new Error(`${fieldName} must be a non-empty base64url string.`);
|
||||
}
|
||||
|
||||
const normalized = input
|
||||
.replace(/-/g, "+")
|
||||
.replace(/_/g, "/");
|
||||
const remainder = normalized.length % 4;
|
||||
const padded = remainder === 0
|
||||
? normalized
|
||||
: normalized + "=".repeat(4 - remainder);
|
||||
|
||||
return Buffer.from(padded, "base64");
|
||||
}
|
||||
|
||||
function validateDocumentPutRawMessage(input: unknown): asserts input is CultNetDocumentPutRawMessage {
|
||||
const candidate = validateBinaryMessageRoot(input, "cultnet.document_put_raw.v0");
|
||||
if (!("document" in candidate)) {
|
||||
throw new Error("Validation failed for cultnet.document_put_raw.v0: /document: is required");
|
||||
}
|
||||
|
||||
validateRawDocumentRecord(candidate.document, "/document");
|
||||
}
|
||||
|
||||
function validateSnapshotResponseRawMessage(
|
||||
input: unknown,
|
||||
): asserts input is CultNetSnapshotResponseRawMessage {
|
||||
const candidate = validateBinaryMessageRoot(input, "cultnet.snapshot_response_raw.v0");
|
||||
if (!("documents" in candidate) || !Array.isArray(candidate.documents)) {
|
||||
throw new Error("Validation failed for cultnet.snapshot_response_raw.v0: /documents: must be an array");
|
||||
}
|
||||
|
||||
candidate.documents.forEach((document, index) => {
|
||||
validateRawDocumentRecord(document, `/documents/${index}`);
|
||||
});
|
||||
}
|
||||
|
||||
function validateBinaryMessageRoot(
|
||||
input: unknown,
|
||||
schemaVersion: "cultnet.document_put_raw.v0" | "cultnet.snapshot_response_raw.v0",
|
||||
): Record<string, unknown> {
|
||||
if (!input || typeof input !== "object") {
|
||||
throw new Error(`Validation failed for ${schemaVersion}: /: must be an object`);
|
||||
}
|
||||
|
||||
const candidate = input as Record<string, unknown>;
|
||||
if (candidate.schemaVersion !== schemaVersion) {
|
||||
throw new Error(`Validation failed for ${schemaVersion}: /schemaVersion: must equal ${schemaVersion}`);
|
||||
}
|
||||
if (typeof candidate.messageId !== "string" || candidate.messageId.trim().length === 0) {
|
||||
throw new Error(`Validation failed for ${schemaVersion}: /messageId: must be a non-empty string`);
|
||||
}
|
||||
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function validateRawDocumentRecord(
|
||||
input: unknown,
|
||||
instancePath: string,
|
||||
): asserts input is CultNetRawDocumentRecord {
|
||||
if (!input || typeof input !== "object") {
|
||||
throw new Error(`Validation failed for raw CultNet document record: ${instancePath}: must be an object`);
|
||||
}
|
||||
|
||||
const candidate = input as Record<string, unknown>;
|
||||
requireNonEmptyString(candidate.schemaId, `${instancePath}/schemaId`);
|
||||
requireNonEmptyString(candidate.recordKey, `${instancePath}/recordKey`);
|
||||
requireNonEmptyString(candidate.storedAt, `${instancePath}/storedAt`);
|
||||
if (candidate.payloadEncoding !== "messagepack") {
|
||||
throw new Error(
|
||||
`Validation failed for raw CultNet document record: ${instancePath}/payloadEncoding: must equal messagepack`,
|
||||
);
|
||||
}
|
||||
if (!(candidate.payload instanceof Uint8Array) || candidate.payload.length === 0) {
|
||||
throw new Error(
|
||||
`Validation failed for raw CultNet document record: ${instancePath}/payload: must be a non-empty Uint8Array`,
|
||||
);
|
||||
}
|
||||
requireOptionalNonEmptyString(candidate.sourceRuntimeId, `${instancePath}/sourceRuntimeId`);
|
||||
requireOptionalNonEmptyString(candidate.sourceAgentId, `${instancePath}/sourceAgentId`);
|
||||
requireOptionalNonEmptyString(candidate.sourceRole, `${instancePath}/sourceRole`);
|
||||
requireOptionalStringArray(candidate.tags, `${instancePath}/tags`);
|
||||
}
|
||||
|
||||
function requireNonEmptyString(input: unknown, instancePath: string): void {
|
||||
if (typeof input !== "string" || input.trim().length === 0) {
|
||||
throw new Error(`Validation failed for raw CultNet document record: ${instancePath}: must be a non-empty string`);
|
||||
}
|
||||
}
|
||||
|
||||
function requireOptionalNonEmptyString(input: unknown, instancePath: string): void {
|
||||
if (typeof input === "undefined" || input === null) {
|
||||
return;
|
||||
}
|
||||
requireNonEmptyString(input, instancePath);
|
||||
}
|
||||
|
||||
function requireOptionalStringArray(input: unknown, instancePath: string): void {
|
||||
if (typeof input === "undefined" || input === null) {
|
||||
return;
|
||||
}
|
||||
if (!Array.isArray(input) || input.some((item) => typeof item !== "string" || item.trim().length === 0)) {
|
||||
throw new Error(`Validation failed for raw CultNet document record: ${instancePath}: must be an array of non-empty strings`);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeCultNetOptionalNulls(
|
||||
candidate: Record<string, unknown>,
|
||||
schemaVersion: CultNetSchemaVersion,
|
||||
): void {
|
||||
switch (schemaVersion) {
|
||||
case "cultnet.hello.v0":
|
||||
stripNullProperties(candidate, [
|
||||
"agentId",
|
||||
"role",
|
||||
"displayName",
|
||||
"supportedDocumentTypes",
|
||||
"supportedMutationContracts",
|
||||
"supportedMessageVersions",
|
||||
]);
|
||||
return;
|
||||
case "cultnet.snapshot_request.v0":
|
||||
stripNullProperties(candidate, ["schemaIds", "recordKeys"]);
|
||||
return;
|
||||
case "cultnet.schema_catalog_request.v0":
|
||||
stripNullProperties(candidate, ["schemaIds", "kinds"]);
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
function stripNullProperties(candidate: Record<string, unknown>, keys: readonly string[]): void {
|
||||
for (const key of keys) {
|
||||
if (candidate[key] === null) {
|
||||
delete candidate[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const cultNetSchemas = {
|
||||
helloSchema,
|
||||
loginSchema,
|
||||
registerSchema,
|
||||
verifySchema,
|
||||
loginSuccessSchema,
|
||||
errorSchema,
|
||||
sampleChangeNameSchema,
|
||||
sampleChatSchema,
|
||||
documentPutSchema,
|
||||
documentDeleteSchema,
|
||||
rawDocumentRecordSchema,
|
||||
documentPutRawSchema,
|
||||
documentMutationContractSchema,
|
||||
snapshotRequestSchema,
|
||||
snapshotResponseSchema,
|
||||
snapshotResponseRawSchema,
|
||||
schemaDescriptorSchema,
|
||||
schemaCatalogRequestSchema,
|
||||
schemaCatalogResponseSchema,
|
||||
ghostlightAgentStateSchema,
|
||||
} as const;
|
||||
30
src/framing.ts
Normal file
30
src/framing.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
const FRAME_HEADER_BYTES = 4;
|
||||
|
||||
export function encodeFrame(payload: Uint8Array): Buffer {
|
||||
const header = Buffer.allocUnsafe(FRAME_HEADER_BYTES);
|
||||
header.writeUInt32BE(payload.length, 0);
|
||||
return Buffer.concat([header, Buffer.from(payload)]);
|
||||
}
|
||||
|
||||
export class LengthPrefixedMessageFramer {
|
||||
#buffer = Buffer.alloc(0);
|
||||
|
||||
push(chunk: Uint8Array): Uint8Array[] {
|
||||
this.#buffer = Buffer.concat([this.#buffer, Buffer.from(chunk)]);
|
||||
const frames: Uint8Array[] = [];
|
||||
|
||||
while (this.#buffer.length >= FRAME_HEADER_BYTES) {
|
||||
const payloadLength = this.#buffer.readUInt32BE(0);
|
||||
const totalLength = FRAME_HEADER_BYTES + payloadLength;
|
||||
|
||||
if (this.#buffer.length < totalLength) {
|
||||
break;
|
||||
}
|
||||
|
||||
frames.push(this.#buffer.subarray(FRAME_HEADER_BYTES, totalLength));
|
||||
this.#buffer = this.#buffer.subarray(totalLength);
|
||||
}
|
||||
|
||||
return frames;
|
||||
}
|
||||
}
|
||||
209
src/generated/swarm-contracts.generated.ts
Normal file
209
src/generated/swarm-contracts.generated.ts
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
import { defineJsonSchemaContract } from "../json-schema-contract";
|
||||
import ghostlightAgentStateGeneratedContractSchema from "../../contracts/ghostlight.agent-state.schema.json";
|
||||
|
||||
// Generated by tools/generate-swarm-contracts.mjs. Do not hand-edit this file unless you enjoy losing arguments with a machine.
|
||||
|
||||
/**
|
||||
* First canonical contract for Ghostlight agent, perception, relationship, event, scene, and dialogue-context state.
|
||||
*/
|
||||
export interface GhostlightAgentStateShape {
|
||||
schema_version: 'ghostlight.agent_state.v0';
|
||||
world: WorldState;
|
||||
agents: Agent[];
|
||||
relationships: Relationship[];
|
||||
events: Event[];
|
||||
scenes: Scene[];
|
||||
}
|
||||
export interface WorldState {
|
||||
world_id: string;
|
||||
setting: string;
|
||||
time: {
|
||||
label: string;
|
||||
[k: string]: unknown;
|
||||
};
|
||||
canon_context: string[];
|
||||
ambient_pressures?: Pressure[];
|
||||
}
|
||||
export interface Pressure {
|
||||
pressure_id: string;
|
||||
label: string;
|
||||
intensity: number;
|
||||
}
|
||||
export interface Agent {
|
||||
agent_id: string;
|
||||
identity: Identity;
|
||||
canonical_state: CanonicalState;
|
||||
goals: Goal[];
|
||||
memories: MemoryBundle;
|
||||
perceived_state_overlays: PerceivedStateOverlay[];
|
||||
}
|
||||
export interface Identity {
|
||||
name: string;
|
||||
roles: string[];
|
||||
origin: string;
|
||||
public_description: string;
|
||||
private_notes?: string[];
|
||||
}
|
||||
export interface CanonicalState {
|
||||
underlying_organization: VariableMap;
|
||||
stable_dispositions: VariableMap;
|
||||
behavioral_dimensions: VariableMap;
|
||||
presentation_strategy: VariableMap;
|
||||
situational_state: VariableMap;
|
||||
values: ValueCommitment[];
|
||||
voice_style: VariableMap;
|
||||
}
|
||||
export interface VariableMap {
|
||||
[k: string]: StateVariable;
|
||||
}
|
||||
export interface StateVariable {
|
||||
mean: number;
|
||||
plasticity: number;
|
||||
current_activation: number;
|
||||
evidence?: string[];
|
||||
}
|
||||
export interface ValueCommitment {
|
||||
value_id: string;
|
||||
label: string;
|
||||
priority: number;
|
||||
unforgivable_if_betrayed: boolean;
|
||||
}
|
||||
export interface Goal {
|
||||
goal_id: string;
|
||||
description: string;
|
||||
scope: 'immediate' | 'scene' | 'case' | 'arc' | 'life';
|
||||
priority: number;
|
||||
emotional_stake: string;
|
||||
blockers?: string[];
|
||||
status: 'active' | 'blocked' | 'dormant' | 'resolved' | 'abandoned';
|
||||
}
|
||||
export interface MemoryBundle {
|
||||
episodic: Memory[];
|
||||
semantic: Memory[];
|
||||
relationship_summaries: Memory[];
|
||||
}
|
||||
export interface Memory {
|
||||
memory_id: string;
|
||||
summary: string;
|
||||
salience: number;
|
||||
confidence: number;
|
||||
linked_event_ids?: string[];
|
||||
linked_relationship_id?: string;
|
||||
}
|
||||
export interface PerceivedStateOverlay {
|
||||
observer_agent_id: string;
|
||||
target_agent_id: string;
|
||||
perceived_dimensions: InferredVariableMap;
|
||||
beliefs: Belief[];
|
||||
distortions: (
|
||||
| 'hostile_attribution'
|
||||
| 'false_reassurance'
|
||||
| 'overread_warmth'
|
||||
| 'underread_threat'
|
||||
| 'false_mask_detection'
|
||||
| 'missed_mask_detection'
|
||||
| 'status_injury'
|
||||
| 'threat_amplification'
|
||||
| 'institutional_suspicion_transfer'
|
||||
| 'care_underread'
|
||||
| 'mask_overfocus'
|
||||
)[];
|
||||
}
|
||||
export interface InferredVariableMap {
|
||||
[k: string]: InferredStateVariable;
|
||||
}
|
||||
export interface InferredStateVariable {
|
||||
observed_activation: number;
|
||||
attributed_disposition: number;
|
||||
confidence: number;
|
||||
evidence?: string[];
|
||||
}
|
||||
export interface Belief {
|
||||
belief_id: string;
|
||||
claim: string;
|
||||
confidence: number;
|
||||
subject_id?: string;
|
||||
claim_type?:
|
||||
| 'fact'
|
||||
| 'identity_inference'
|
||||
| 'motive_inference'
|
||||
| 'prediction'
|
||||
| 'norm'
|
||||
| 'value_read'
|
||||
| 'relationship_read';
|
||||
evidence_event_ids?: string[];
|
||||
visibility?: 'private' | 'shared' | 'public' | 'rumor';
|
||||
emotional_charge?: number;
|
||||
}
|
||||
export interface Relationship {
|
||||
relationship_id: string;
|
||||
source_id: string;
|
||||
target_id: string;
|
||||
stance: VariableMap;
|
||||
summary: string;
|
||||
unresolved_incident_ids?: string[];
|
||||
}
|
||||
export interface Event {
|
||||
event_id: string;
|
||||
kind: 'dialogue' | 'action' | 'memory' | 'relationship_shift' | 'scene_outcome' | 'author_note';
|
||||
summary: string;
|
||||
participants: string[];
|
||||
pressure_tags: string[];
|
||||
observed_exchange?: EventExchangeTurn[];
|
||||
private_interpretations?: EventPrivateInterpretation[];
|
||||
event_effects?: EventEffect[];
|
||||
}
|
||||
export interface EventExchangeTurn {
|
||||
speaker_id: string;
|
||||
utterance_summary: string;
|
||||
dialogue_function: string;
|
||||
observable_cues?: string[];
|
||||
}
|
||||
export interface EventPrivateInterpretation {
|
||||
agent_id: string;
|
||||
interpretation: string;
|
||||
attributed_motive?: string;
|
||||
appraisal_tags?: string[];
|
||||
confidence: number;
|
||||
}
|
||||
export interface EventEffect {
|
||||
agent_id: string;
|
||||
summary: string;
|
||||
state_deltas?: StateDelta[];
|
||||
new_belief_ids?: string[];
|
||||
memory_update_ids?: string[];
|
||||
}
|
||||
export interface StateDelta {
|
||||
path: string;
|
||||
delta: number;
|
||||
}
|
||||
export interface Scene {
|
||||
scene_id: string;
|
||||
location: string;
|
||||
participants: string[];
|
||||
public_stakes: string[];
|
||||
hidden_stakes: string[];
|
||||
dialogue_context_packs: DialogueContextPack[];
|
||||
}
|
||||
export interface DialogueContextPack {
|
||||
speaker_agent_id: string;
|
||||
listener_ids: string[];
|
||||
speaker_local_truth: string[];
|
||||
speaker_beliefs: string[];
|
||||
active_memories: string[];
|
||||
active_goals: string[];
|
||||
presentation_constraints: string[];
|
||||
}
|
||||
|
||||
export const ghostlightAgentStateGeneratedContract = defineJsonSchemaContract<GhostlightAgentStateShape>({
|
||||
schemaId: "https://github.com/GameCult/Ghostlight/schemas/agent-state.schema.json",
|
||||
schema: ghostlightAgentStateGeneratedContractSchema,
|
||||
});
|
||||
|
||||
export function validateGhostlightAgentStateGenerated(value: unknown): value is GhostlightAgentStateShape {
|
||||
return ghostlightAgentStateGeneratedContract.validate(value);
|
||||
}
|
||||
|
||||
export function parseGhostlightAgentStateGenerated(value: unknown): GhostlightAgentStateShape {
|
||||
return ghostlightAgentStateGeneratedContract.parse(value);
|
||||
}
|
||||
28
src/ghostlight.ts
Normal file
28
src/ghostlight.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import type { CultNetDocumentBinding } from "./replication";
|
||||
import { validateGhostlightAgentState, type GhostlightAgentStateDocument } from "./contracts";
|
||||
|
||||
export function validateGhostlightAgentStateDocument(
|
||||
value: unknown,
|
||||
): GhostlightAgentStateDocument {
|
||||
return validateGhostlightAgentState(value);
|
||||
}
|
||||
|
||||
export function resolveGhostlightAgentIds(
|
||||
document: GhostlightAgentStateDocument,
|
||||
): string[] {
|
||||
return document.agents
|
||||
.map((agent) => agent.agent_id)
|
||||
.filter((value): value is string => typeof value === "string" && value.length > 0);
|
||||
}
|
||||
|
||||
export function createGhostlightPayloadSchemaVersionResolver(): (
|
||||
value: GhostlightAgentStateDocument,
|
||||
) => string {
|
||||
return (value) => validateGhostlightAgentState(value).schema_version;
|
||||
}
|
||||
|
||||
export function isGhostlightAgentStateBinding(
|
||||
binding: CultNetDocumentBinding,
|
||||
): boolean {
|
||||
return binding.payloadSchemaVersion === "ghostlight.agent_state.v0";
|
||||
}
|
||||
89
src/index.ts
Normal file
89
src/index.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
export {
|
||||
cultNetSchemas,
|
||||
encodeCultNetMessageForWire,
|
||||
parseCultNetMessage,
|
||||
validateGhostlightAgentState,
|
||||
type CultNetDocumentDeleteMessage,
|
||||
type CultNetDocumentMutationContract,
|
||||
type CultNetDocumentPutMessage,
|
||||
type CultNetDocumentPutRawMessage,
|
||||
type CultNetDocumentRecord,
|
||||
type CultNetRawDocumentRecord,
|
||||
type CultNetRawPayloadEncoding,
|
||||
type CultNetErrorMessage,
|
||||
type CultNetHelloMessage,
|
||||
type CultNetLoginMessage,
|
||||
type CultNetLoginSuccessMessage,
|
||||
type CultNetMessage,
|
||||
type CultNetRegisterMessage,
|
||||
type CultNetSampleChangeNameMessage,
|
||||
type CultNetSampleChatMessage,
|
||||
type CultNetSchemaVersion,
|
||||
type CultNetSchemaCatalogRequestMessage,
|
||||
type CultNetSchemaCatalogResponseMessage,
|
||||
type CultNetSchemaDescriptor,
|
||||
type CultNetSchemaKind,
|
||||
type CultNetSnapshotRequestMessage,
|
||||
type CultNetSnapshotResponseMessage,
|
||||
type CultNetSnapshotResponseRawMessage,
|
||||
type CultNetVerifyMessage,
|
||||
type CultNetWireContract,
|
||||
type GhostlightAgent,
|
||||
type GhostlightAgentStateDocument,
|
||||
type GhostlightBelief,
|
||||
type GhostlightCanonicalState,
|
||||
type GhostlightDialogueContextPack,
|
||||
type GhostlightEvent,
|
||||
type GhostlightEventEffect,
|
||||
type GhostlightEventExchangeTurn,
|
||||
type GhostlightEventPrivateInterpretation,
|
||||
type GhostlightGoal,
|
||||
type GhostlightIdentity,
|
||||
type GhostlightMemory,
|
||||
type GhostlightMemoryBundle,
|
||||
type GhostlightPerceivedStateOverlay,
|
||||
type GhostlightPressure,
|
||||
type GhostlightRelationship,
|
||||
type GhostlightScene,
|
||||
type GhostlightStateDelta,
|
||||
type GhostlightStateVariable,
|
||||
type GhostlightValueCommitment,
|
||||
type GhostlightVariableMap,
|
||||
type GhostlightWorldState,
|
||||
} from "./contracts";
|
||||
export { encodeFrame, LengthPrefixedMessageFramer } from "./framing";
|
||||
export { CultNetPeer, type CultNetPeerEvents } from "./peer";
|
||||
export {
|
||||
defineJsonSchemaContract,
|
||||
type JsonSchemaContract,
|
||||
type JsonSchemaContractDefinition,
|
||||
} from "./json-schema-contract";
|
||||
export {
|
||||
CultNetDocumentRegistry,
|
||||
defineCultNetDocumentBinding,
|
||||
type CultNetDocumentBinding,
|
||||
} from "./replication";
|
||||
export {
|
||||
CultNetSchemaRegistry,
|
||||
cultNetBuiltinSchemaRegistry,
|
||||
type CultNetSchemaCatalogOptions,
|
||||
type CultNetSchemaRegistration,
|
||||
} from "./schema-discovery";
|
||||
export {
|
||||
CultNetClientSecurityOptions,
|
||||
CultNetSecret,
|
||||
CultNetServerSecurityOptions,
|
||||
type ValidatedCultNetSessionToken,
|
||||
} from "./security";
|
||||
export {
|
||||
createGhostlightPayloadSchemaVersionResolver,
|
||||
isGhostlightAgentStateBinding,
|
||||
resolveGhostlightAgentIds,
|
||||
validateGhostlightAgentStateDocument,
|
||||
} from "./ghostlight";
|
||||
export {
|
||||
ghostlightAgentStateGeneratedContract,
|
||||
parseGhostlightAgentStateGenerated,
|
||||
validateGhostlightAgentStateGenerated,
|
||||
type GhostlightAgentStateShape,
|
||||
} from "./generated/swarm-contracts.generated";
|
||||
49
src/json-schema-contract.ts
Normal file
49
src/json-schema-contract.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import Ajv2020, { type ErrorObject, type ValidateFunction } from "ajv/dist/2020";
|
||||
import type { CultCacheSchema } from "cultcache-ts";
|
||||
|
||||
export interface JsonSchemaContract<TValue> extends CultCacheSchema<TValue> {
|
||||
readonly schemaId: string;
|
||||
readonly schema: object;
|
||||
readonly validate: (input: unknown) => input is TValue;
|
||||
}
|
||||
|
||||
export interface JsonSchemaContractDefinition {
|
||||
schemaId: string;
|
||||
schema: object;
|
||||
}
|
||||
|
||||
const ajv = new Ajv2020({
|
||||
allErrors: true,
|
||||
strict: false,
|
||||
});
|
||||
|
||||
export function defineJsonSchemaContract<TValue>(
|
||||
definition: JsonSchemaContractDefinition,
|
||||
): JsonSchemaContract<TValue> {
|
||||
const validator = ajv.compile(definition.schema);
|
||||
|
||||
return Object.freeze({
|
||||
schemaId: definition.schemaId,
|
||||
schema: definition.schema,
|
||||
validate(input: unknown): input is TValue {
|
||||
return validator(input) as boolean;
|
||||
},
|
||||
parse(input: unknown): TValue {
|
||||
if (!validator(input)) {
|
||||
throw new Error(renderValidationErrors(definition.schemaId, validator));
|
||||
}
|
||||
|
||||
return input as TValue;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function renderValidationErrors(schemaId: string, validator: ValidateFunction): string {
|
||||
const details = validator.errors?.map(renderError) ?? ["unknown validation failure"];
|
||||
return `Validation failed for ${schemaId}: ${details.join("; ")}`;
|
||||
}
|
||||
|
||||
function renderError(error: ErrorObject): string {
|
||||
const location = error.instancePath.length > 0 ? error.instancePath : "/";
|
||||
return `${location}: ${error.message}`;
|
||||
}
|
||||
112
src/peer.ts
Normal file
112
src/peer.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
import { EventEmitter } from "node:events";
|
||||
import type { Duplex } from "node:stream";
|
||||
|
||||
import { decode, encode } from "@msgpack/msgpack";
|
||||
|
||||
import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetDocumentDeleteMessage, type CultNetDocumentPutMessage, type CultNetErrorMessage, type CultNetHelloMessage, type CultNetLoginMessage, type CultNetLoginSuccessMessage, type CultNetMessage, type CultNetRegisterMessage, type CultNetSampleChangeNameMessage, type CultNetSampleChatMessage, type CultNetSchemaCatalogRequestMessage, type CultNetSchemaCatalogResponseMessage, type CultNetSnapshotRequestMessage, type CultNetSnapshotResponseMessage, type CultNetVerifyMessage, type CultNetWireContract } from "./contracts";
|
||||
import { encodeFrame, LengthPrefixedMessageFramer } from "./framing";
|
||||
|
||||
export interface CultNetPeerEvents {
|
||||
message: (message: CultNetMessage) => void;
|
||||
invalidMessage: (error: Error) => void;
|
||||
close: () => void;
|
||||
error: (error: Error) => void;
|
||||
}
|
||||
|
||||
export interface CultNetPeerOptions {
|
||||
wireContract: CultNetWireContract;
|
||||
}
|
||||
|
||||
export class CultNetPeer extends EventEmitter {
|
||||
readonly #stream: Duplex;
|
||||
readonly #framer = new LengthPrefixedMessageFramer();
|
||||
readonly #wireContract: CultNetWireContract;
|
||||
|
||||
constructor(stream: Duplex, options: CultNetPeerOptions) {
|
||||
super();
|
||||
if (!options?.wireContract) {
|
||||
throw new Error("CultNetPeer requires an explicit wireContract.");
|
||||
}
|
||||
|
||||
this.#stream = stream;
|
||||
this.#wireContract = options.wireContract;
|
||||
this.#stream.on("data", (chunk: Buffer) => {
|
||||
for (const frame of this.#framer.push(chunk)) {
|
||||
try {
|
||||
const decoded = decode(frame);
|
||||
const message = parseCultNetMessage(decoded, this.#wireContract);
|
||||
this.emit("message", message);
|
||||
} catch (error) {
|
||||
this.emit("invalidMessage", error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
}
|
||||
});
|
||||
this.#stream.on("close", () => this.emit("close"));
|
||||
this.#stream.on("error", (error) => this.emit("error", error instanceof Error ? error : new Error(String(error))));
|
||||
}
|
||||
|
||||
send(message: CultNetMessage): void {
|
||||
const wireValue = encodeCultNetMessageForWire(message, this.#wireContract);
|
||||
this.#stream.write(encodeFrame(encode(wireValue)));
|
||||
}
|
||||
|
||||
sendHello(message: CultNetHelloMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendLogin(message: CultNetLoginMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendRegister(message: CultNetRegisterMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendVerify(message: CultNetVerifyMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendLoginSuccess(message: CultNetLoginSuccessMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendError(message: CultNetErrorMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendSampleChangeName(message: CultNetSampleChangeNameMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendSampleChat(message: CultNetSampleChatMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendDocumentPut(message: CultNetDocumentPutMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendDocumentDelete(message: CultNetDocumentDeleteMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendSnapshotRequest(message: CultNetSnapshotRequestMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendSnapshotResponse(message: CultNetSnapshotResponseMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendSchemaCatalogRequest(message: CultNetSchemaCatalogRequestMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
sendSchemaCatalogResponse(message: CultNetSchemaCatalogResponseMessage): void {
|
||||
this.send(message);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.#stream.end();
|
||||
}
|
||||
}
|
||||
347
src/replication.ts
Normal file
347
src/replication.ts
Normal file
|
|
@ -0,0 +1,347 @@
|
|||
import { decode, encode } from "@msgpack/msgpack";
|
||||
import type {
|
||||
AnyCultCacheDocumentDefinition,
|
||||
CultCache,
|
||||
CultCacheDocumentDefinition,
|
||||
CultCacheDocumentFormatter,
|
||||
CultCacheDocumentValue,
|
||||
CultCacheEnvelope,
|
||||
} from "cultcache-ts";
|
||||
|
||||
import {
|
||||
type CultNetDocumentDeleteMessage,
|
||||
type CultNetDocumentPutMessage,
|
||||
type CultNetDocumentPutRawMessage,
|
||||
type CultNetDocumentRecord,
|
||||
type CultNetRawDocumentRecord,
|
||||
type CultNetSnapshotRequestMessage,
|
||||
type CultNetSnapshotResponseMessage,
|
||||
type CultNetSnapshotResponseRawMessage,
|
||||
} from "./contracts";
|
||||
|
||||
export interface CultNetDocumentBinding<
|
||||
TDefinition extends AnyCultCacheDocumentDefinition = AnyCultCacheDocumentDefinition,
|
||||
> {
|
||||
definition: TDefinition;
|
||||
payloadSchemaVersion?:
|
||||
| string
|
||||
| ((value: CultCacheDocumentValue<TDefinition>) => string | undefined);
|
||||
}
|
||||
|
||||
export function defineCultNetDocumentBinding<
|
||||
TDefinition extends AnyCultCacheDocumentDefinition,
|
||||
>(
|
||||
binding: CultNetDocumentBinding<TDefinition>,
|
||||
): CultNetDocumentBinding<TDefinition> {
|
||||
return Object.freeze({ ...binding });
|
||||
}
|
||||
|
||||
export class CultNetDocumentRegistry {
|
||||
readonly #bindings = new Map<string, CultNetDocumentBinding>();
|
||||
readonly #schemaBindings = new Map<string, CultNetDocumentBinding>();
|
||||
|
||||
constructor(bindings: Iterable<CultNetDocumentBinding> = []) {
|
||||
for (const binding of bindings) {
|
||||
this.register(binding);
|
||||
}
|
||||
}
|
||||
|
||||
register(binding: CultNetDocumentBinding): this {
|
||||
this.#bindings.set(binding.definition.type, binding);
|
||||
this.#schemaBindings.set(schemaIdForBinding(binding), binding);
|
||||
return this;
|
||||
}
|
||||
|
||||
get(documentType: string): CultNetDocumentBinding | undefined {
|
||||
return this.#bindings.get(documentType);
|
||||
}
|
||||
|
||||
getBySchemaId(schemaId: string): CultNetDocumentBinding | undefined {
|
||||
return this.#schemaBindings.get(schemaId);
|
||||
}
|
||||
|
||||
createDocumentPutMessage<TDefinition extends AnyCultCacheDocumentDefinition>(
|
||||
binding: CultNetDocumentBinding<TDefinition>,
|
||||
messageId: string,
|
||||
documentKey: string,
|
||||
value: CultCacheDocumentValue<TDefinition>,
|
||||
options: {
|
||||
storedAt?: string;
|
||||
sourceRuntimeId?: string;
|
||||
sourceAgentId?: string;
|
||||
sourceRole?: string;
|
||||
tags?: string[];
|
||||
} = {},
|
||||
): CultNetDocumentPutMessage<CultCacheDocumentValue<TDefinition>> {
|
||||
const parsed = binding.definition.schema.parse(value);
|
||||
return {
|
||||
schemaVersion: "cultnet.document_put.v0",
|
||||
messageId,
|
||||
document: {
|
||||
schemaId: schemaIdForBinding(binding),
|
||||
recordKey: documentKey,
|
||||
storedAt: options.storedAt ?? new Date().toISOString(),
|
||||
payload: parsed,
|
||||
sourceRuntimeId: options.sourceRuntimeId,
|
||||
sourceAgentId: options.sourceAgentId,
|
||||
sourceRole: options.sourceRole,
|
||||
tags: options.tags,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
createDocumentDeleteMessage(
|
||||
messageId: string,
|
||||
schemaId: string,
|
||||
recordKey: string,
|
||||
): CultNetDocumentDeleteMessage {
|
||||
return {
|
||||
schemaVersion: "cultnet.document_delete.v0",
|
||||
messageId,
|
||||
schemaId,
|
||||
recordKey,
|
||||
};
|
||||
}
|
||||
|
||||
createRawDocumentPutMessageFromEnvelope(
|
||||
messageId: string,
|
||||
envelope: CultCacheEnvelope,
|
||||
): CultNetDocumentPutRawMessage {
|
||||
return {
|
||||
schemaVersion: "cultnet.document_put_raw.v0",
|
||||
messageId,
|
||||
document: this.#createRawDocumentRecord(envelope),
|
||||
};
|
||||
}
|
||||
|
||||
createRawDocumentPutMessage<TDefinition extends AnyCultCacheDocumentDefinition>(
|
||||
binding: CultNetDocumentBinding<TDefinition>,
|
||||
messageId: string,
|
||||
documentKey: string,
|
||||
value: CultCacheDocumentValue<TDefinition>,
|
||||
options: {
|
||||
storedAt?: string;
|
||||
sourceRuntimeId?: string;
|
||||
sourceAgentId?: string;
|
||||
sourceRole?: string;
|
||||
tags?: string[];
|
||||
} = {},
|
||||
): CultNetDocumentPutRawMessage {
|
||||
const parsed = binding.definition.schema.parse(value);
|
||||
const formatter = formatterFor(binding.definition);
|
||||
return {
|
||||
schemaVersion: "cultnet.document_put_raw.v0",
|
||||
messageId,
|
||||
document: {
|
||||
schemaId: schemaIdForBinding(binding),
|
||||
recordKey: documentKey,
|
||||
storedAt: options.storedAt ?? new Date().toISOString(),
|
||||
payloadEncoding: "messagepack",
|
||||
payload: formatter.encode(parsed),
|
||||
sourceRuntimeId: options.sourceRuntimeId,
|
||||
sourceAgentId: options.sourceAgentId,
|
||||
sourceRole: options.sourceRole,
|
||||
tags: options.tags,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
createSnapshotResponse(
|
||||
cache: CultCache,
|
||||
messageId: string,
|
||||
filter?: CultNetSnapshotRequestMessage,
|
||||
): CultNetSnapshotResponseMessage {
|
||||
const requestedSchemaIds = filter?.schemaIds ? new Set(filter.schemaIds) : undefined;
|
||||
const requestedKeys = filter?.recordKeys ? new Set(filter.recordKeys) : undefined;
|
||||
const documents: CultNetDocumentRecord[] = [];
|
||||
|
||||
for (const envelope of cache.snapshot()) {
|
||||
const binding = this.#requireBinding(envelope.type);
|
||||
const schemaId = schemaIdForEnvelope(envelope, binding);
|
||||
|
||||
if (requestedSchemaIds && !requestedSchemaIds.has(schemaId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (requestedKeys && !requestedKeys.has(envelope.key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const payload = decodeDocumentValue(binding.definition, envelope.payload);
|
||||
documents.push({
|
||||
schemaId,
|
||||
recordKey: envelope.key,
|
||||
storedAt: envelope.storedAt,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: "cultnet.snapshot_response.v0",
|
||||
messageId,
|
||||
documents,
|
||||
};
|
||||
}
|
||||
|
||||
createRawSnapshotResponse(
|
||||
cache: CultCache,
|
||||
messageId: string,
|
||||
filter?: CultNetSnapshotRequestMessage,
|
||||
): CultNetSnapshotResponseRawMessage {
|
||||
const requestedSchemaIds = filter?.schemaIds ? new Set(filter.schemaIds) : undefined;
|
||||
const requestedKeys = filter?.recordKeys ? new Set(filter.recordKeys) : undefined;
|
||||
const documents: CultNetRawDocumentRecord[] = [];
|
||||
|
||||
for (const envelope of cache.snapshot()) {
|
||||
const binding = this.#requireBinding(envelope.type);
|
||||
const schemaId = schemaIdForEnvelope(envelope, binding);
|
||||
|
||||
if (requestedSchemaIds && !requestedSchemaIds.has(schemaId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (requestedKeys && !requestedKeys.has(envelope.key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
documents.push(this.#createRawDocumentRecord(envelope));
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: "cultnet.snapshot_response_raw.v0",
|
||||
messageId,
|
||||
documents,
|
||||
};
|
||||
}
|
||||
|
||||
async applyDocumentPutMessage(
|
||||
cache: CultCache,
|
||||
message: CultNetDocumentPutMessage,
|
||||
): Promise<unknown> {
|
||||
const binding = this.#requireSchemaBinding(message.document.schemaId);
|
||||
return cache.put(
|
||||
binding.definition,
|
||||
message.document.recordKey,
|
||||
binding.definition.schema.parse(message.document.payload),
|
||||
);
|
||||
}
|
||||
|
||||
async applyDocumentDeleteMessage(
|
||||
cache: CultCache,
|
||||
message: CultNetDocumentDeleteMessage,
|
||||
): Promise<boolean> {
|
||||
const binding = this.#requireSchemaBinding(message.schemaId);
|
||||
return cache.delete(binding.definition, message.recordKey);
|
||||
}
|
||||
|
||||
async applyRawDocumentPutMessage(
|
||||
cache: CultCache,
|
||||
message: CultNetDocumentPutRawMessage,
|
||||
): Promise<unknown> {
|
||||
const binding = this.#requireSchemaBinding(message.document.schemaId);
|
||||
return cache.putEnvelope(binding.definition, {
|
||||
key: message.document.recordKey,
|
||||
type: binding.definition.type,
|
||||
schemaId: message.document.schemaId,
|
||||
payload: new Uint8Array(message.document.payload),
|
||||
storedAt: message.document.storedAt,
|
||||
});
|
||||
}
|
||||
|
||||
async applySnapshotResponse(
|
||||
cache: CultCache,
|
||||
response: CultNetSnapshotResponseMessage,
|
||||
): Promise<void> {
|
||||
for (const document of response.documents) {
|
||||
await this.applyDocumentPutMessage(cache, {
|
||||
schemaVersion: "cultnet.document_put.v0",
|
||||
messageId: response.messageId,
|
||||
document,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async applyRawSnapshotResponse(
|
||||
cache: CultCache,
|
||||
response: CultNetSnapshotResponseRawMessage,
|
||||
): Promise<void> {
|
||||
for (const document of response.documents) {
|
||||
await this.applyRawDocumentPutMessage(cache, {
|
||||
schemaVersion: "cultnet.document_put_raw.v0",
|
||||
messageId: response.messageId,
|
||||
document,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#requireBinding(documentType: string): CultNetDocumentBinding {
|
||||
const binding = this.get(documentType);
|
||||
if (!binding) {
|
||||
throw new Error(`No CultNet document binding is registered for "${documentType}".`);
|
||||
}
|
||||
|
||||
return binding;
|
||||
}
|
||||
|
||||
#requireSchemaBinding(schemaId: string): CultNetDocumentBinding {
|
||||
const binding = this.getBySchemaId(schemaId);
|
||||
if (!binding) {
|
||||
throw new Error(`No CultNet document binding is registered for schema "${schemaId}".`);
|
||||
}
|
||||
|
||||
return binding;
|
||||
}
|
||||
|
||||
#createRawDocumentRecord(envelope: CultCacheEnvelope): CultNetRawDocumentRecord {
|
||||
const binding = this.#requireBinding(envelope.type);
|
||||
return {
|
||||
schemaId: schemaIdForEnvelope(envelope, binding),
|
||||
recordKey: envelope.key,
|
||||
storedAt: envelope.storedAt,
|
||||
payloadEncoding: "messagepack",
|
||||
payload: new Uint8Array(envelope.payload),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function schemaIdForBinding(binding: CultNetDocumentBinding): string {
|
||||
return binding.definition.schemaId ?? binding.definition.type;
|
||||
}
|
||||
|
||||
function schemaIdForEnvelope(
|
||||
envelope: CultCacheEnvelope,
|
||||
binding: CultNetDocumentBinding,
|
||||
): string {
|
||||
return envelope.schemaId ?? schemaIdForBinding(binding);
|
||||
}
|
||||
|
||||
function resolvePayloadSchemaVersion<TDefinition extends AnyCultCacheDocumentDefinition>(
|
||||
binding: CultNetDocumentBinding<TDefinition>,
|
||||
value: CultCacheDocumentValue<TDefinition>,
|
||||
): string | undefined {
|
||||
if (typeof binding.payloadSchemaVersion === "function") {
|
||||
return binding.payloadSchemaVersion(value);
|
||||
}
|
||||
|
||||
return binding.payloadSchemaVersion;
|
||||
}
|
||||
|
||||
function decodeDocumentValue<TDefinition extends CultCacheDocumentDefinition>(
|
||||
definition: TDefinition,
|
||||
payload: Uint8Array,
|
||||
): CultCacheDocumentValue<TDefinition> {
|
||||
const formatter = formatterFor(definition);
|
||||
const decoded = formatter.decode(payload);
|
||||
return definition.schema.parse(decoded) as CultCacheDocumentValue<TDefinition>;
|
||||
}
|
||||
|
||||
function formatterFor<TDefinition extends CultCacheDocumentDefinition>(
|
||||
definition: TDefinition,
|
||||
): CultCacheDocumentFormatter<CultCacheDocumentValue<TDefinition>> {
|
||||
return (definition.formatter as CultCacheDocumentFormatter<
|
||||
CultCacheDocumentValue<TDefinition>
|
||||
> | undefined) ?? {
|
||||
encode: (value: CultCacheDocumentValue<TDefinition>) => encode(value),
|
||||
decode: (bytes: Uint8Array) => decode(bytes) as CultCacheDocumentValue<TDefinition>,
|
||||
};
|
||||
}
|
||||
276
src/schema-discovery.ts
Normal file
276
src/schema-discovery.ts
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
import { createHash } from "node:crypto";
|
||||
|
||||
import {
|
||||
cultNetSchemas,
|
||||
type CultNetSchemaCatalogRequestMessage,
|
||||
type CultNetSchemaCatalogResponseMessage,
|
||||
type CultNetSchemaDescriptor,
|
||||
type CultNetSchemaKind,
|
||||
type CultNetWireContract,
|
||||
} from "./contracts";
|
||||
|
||||
export interface CultNetSchemaRegistration {
|
||||
schemaId: string;
|
||||
kind: CultNetSchemaKind;
|
||||
schema: object;
|
||||
wireContracts: readonly CultNetWireContract[];
|
||||
schemaVersion?: string;
|
||||
documentType?: string;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
export interface CultNetSchemaCatalogOptions {
|
||||
includeSchemaJson?: boolean;
|
||||
schemaIds?: readonly string[];
|
||||
kinds?: readonly CultNetSchemaKind[];
|
||||
}
|
||||
|
||||
interface CultNetRegisteredSchemaRecord extends CultNetSchemaRegistration {
|
||||
canonicalSchemaJson: string;
|
||||
contentHash: string;
|
||||
}
|
||||
|
||||
export class CultNetSchemaRegistry {
|
||||
readonly #entries = new Map<string, CultNetRegisteredSchemaRecord>();
|
||||
|
||||
constructor(entries: Iterable<CultNetSchemaRegistration> = []) {
|
||||
for (const entry of entries) {
|
||||
this.register(entry);
|
||||
}
|
||||
}
|
||||
|
||||
register(entry: CultNetSchemaRegistration): this {
|
||||
const canonicalSchemaJson = stableStringify(entry.schema);
|
||||
const contentHash = createHash("sha256").update(canonicalSchemaJson).digest("hex");
|
||||
|
||||
this.#entries.set(entry.schemaId, {
|
||||
...entry,
|
||||
canonicalSchemaJson,
|
||||
contentHash,
|
||||
});
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
get(schemaId: string, options: CultNetSchemaCatalogOptions = {}): CultNetSchemaDescriptor | undefined {
|
||||
const entry = this.#entries.get(schemaId);
|
||||
|
||||
if (!entry) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return toSchemaDescriptor(entry, options.includeSchemaJson === true);
|
||||
}
|
||||
|
||||
list(options: CultNetSchemaCatalogOptions = {}): CultNetSchemaDescriptor[] {
|
||||
const requestedSchemaIds = options.schemaIds ? new Set(options.schemaIds) : null;
|
||||
const requestedKinds = options.kinds ? new Set(options.kinds) : null;
|
||||
const includeSchemaJson = options.includeSchemaJson === true;
|
||||
|
||||
return Array.from(this.#entries.values())
|
||||
.filter((entry) => {
|
||||
if (requestedSchemaIds && !requestedSchemaIds.has(entry.schemaId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (requestedKinds && !requestedKinds.has(entry.kind)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
})
|
||||
.map((entry) => toSchemaDescriptor(entry, includeSchemaJson));
|
||||
}
|
||||
|
||||
createCatalogResponse(
|
||||
request: CultNetSchemaCatalogRequestMessage,
|
||||
): CultNetSchemaCatalogResponseMessage {
|
||||
return {
|
||||
schemaVersion: "cultnet.schema_catalog_response.v0",
|
||||
messageId: request.messageId,
|
||||
schemas: this.list({
|
||||
includeSchemaJson: request.includeSchemaJson,
|
||||
schemaIds: request.schemaIds,
|
||||
kinds: request.kinds,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function toSchemaDescriptor(
|
||||
entry: CultNetRegisteredSchemaRecord,
|
||||
includeSchemaJson: boolean,
|
||||
): CultNetSchemaDescriptor {
|
||||
return {
|
||||
schemaId: entry.schemaId,
|
||||
kind: entry.kind,
|
||||
schemaVersion: entry.schemaVersion,
|
||||
documentType: entry.documentType,
|
||||
title: entry.title,
|
||||
wireContracts: [...entry.wireContracts],
|
||||
contentHash: entry.contentHash,
|
||||
schemaJson: includeSchemaJson ? entry.canonicalSchemaJson : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function stableStringify(value: unknown): string {
|
||||
if (Array.isArray(value)) {
|
||||
return `[${value.map((item) => stableStringify(item)).join(",")}]`;
|
||||
}
|
||||
|
||||
if (value && typeof value === "object") {
|
||||
const entries = Object.entries(value as Record<string, unknown>)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, child]) => `${JSON.stringify(key)}:${stableStringify(child)}`);
|
||||
return `{${entries.join(",")}}`;
|
||||
}
|
||||
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
export const cultNetBuiltinSchemaRegistry = new CultNetSchemaRegistry([
|
||||
{
|
||||
schemaId: cultNetSchemas.helloSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.helloSchema,
|
||||
schemaVersion: "cultnet.hello.v0",
|
||||
title: cultNetSchemas.helloSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.loginSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.loginSchema,
|
||||
schemaVersion: "cultnet.login.v0",
|
||||
title: cultNetSchemas.loginSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0", "gamecult.networking.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.registerSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.registerSchema,
|
||||
schemaVersion: "cultnet.register.v0",
|
||||
title: cultNetSchemas.registerSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0", "gamecult.networking.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.verifySchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.verifySchema,
|
||||
schemaVersion: "cultnet.verify.v0",
|
||||
title: cultNetSchemas.verifySchema.title,
|
||||
wireContracts: ["cultnet.schema.v0", "gamecult.networking.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.loginSuccessSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.loginSuccessSchema,
|
||||
schemaVersion: "cultnet.login_success.v0",
|
||||
title: cultNetSchemas.loginSuccessSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0", "gamecult.networking.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.errorSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.errorSchema,
|
||||
schemaVersion: "cultnet.error.v0",
|
||||
title: cultNetSchemas.errorSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0", "gamecult.networking.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.sampleChangeNameSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.sampleChangeNameSchema,
|
||||
schemaVersion: "cultnet.sample.change_name.v0",
|
||||
title: cultNetSchemas.sampleChangeNameSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0", "gamecult.networking.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.sampleChatSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.sampleChatSchema,
|
||||
schemaVersion: "cultnet.sample.chat.v0",
|
||||
title: cultNetSchemas.sampleChatSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0", "gamecult.networking.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.documentPutSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.documentPutSchema,
|
||||
schemaVersion: "cultnet.document_put.v0",
|
||||
title: cultNetSchemas.documentPutSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.documentDeleteSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.documentDeleteSchema,
|
||||
schemaVersion: "cultnet.document_delete.v0",
|
||||
title: cultNetSchemas.documentDeleteSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.rawDocumentRecordSchema.$id,
|
||||
kind: "shared_contract",
|
||||
schema: cultNetSchemas.rawDocumentRecordSchema,
|
||||
title: cultNetSchemas.rawDocumentRecordSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.documentPutRawSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.documentPutRawSchema,
|
||||
schemaVersion: "cultnet.document_put_raw.v0",
|
||||
title: cultNetSchemas.documentPutRawSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.snapshotRequestSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.snapshotRequestSchema,
|
||||
schemaVersion: "cultnet.snapshot_request.v0",
|
||||
title: cultNetSchemas.snapshotRequestSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.snapshotResponseSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.snapshotResponseSchema,
|
||||
schemaVersion: "cultnet.snapshot_response.v0",
|
||||
title: cultNetSchemas.snapshotResponseSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.snapshotResponseRawSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.snapshotResponseRawSchema,
|
||||
schemaVersion: "cultnet.snapshot_response_raw.v0",
|
||||
title: cultNetSchemas.snapshotResponseRawSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.schemaCatalogRequestSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.schemaCatalogRequestSchema,
|
||||
schemaVersion: "cultnet.schema_catalog_request.v0",
|
||||
title: cultNetSchemas.schemaCatalogRequestSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0", "gamecult.networking.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.schemaCatalogResponseSchema.$id,
|
||||
kind: "wire_message",
|
||||
schema: cultNetSchemas.schemaCatalogResponseSchema,
|
||||
schemaVersion: "cultnet.schema_catalog_response.v0",
|
||||
title: cultNetSchemas.schemaCatalogResponseSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0", "gamecult.networking.v0"],
|
||||
},
|
||||
{
|
||||
schemaId: cultNetSchemas.ghostlightAgentStateSchema.$id,
|
||||
kind: "document_payload",
|
||||
schema: cultNetSchemas.ghostlightAgentStateSchema,
|
||||
schemaVersion: "ghostlight.agent_state.v0",
|
||||
documentType: "ghostlight.agent-state",
|
||||
title: cultNetSchemas.ghostlightAgentStateSchema.title,
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
},
|
||||
]);
|
||||
267
src/security.ts
Normal file
267
src/security.ts
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
const NONCE_LENGTH = 12;
|
||||
const TAG_LENGTH = 16;
|
||||
|
||||
export class CultNetClientSecurityOptions {
|
||||
readonly #encryptionKey: Buffer;
|
||||
readonly connectionKey: string;
|
||||
|
||||
constructor(connectionKey: string) {
|
||||
if (!connectionKey || connectionKey.trim().length === 0) {
|
||||
throw new Error("Connection key must be provided.");
|
||||
}
|
||||
|
||||
this.connectionKey = connectionKey;
|
||||
this.#encryptionKey = sha256(Buffer.from(connectionKey, "utf8"));
|
||||
}
|
||||
|
||||
static development(): CultNetClientSecurityOptions {
|
||||
return new CultNetClientSecurityOptions("gamecult-dev-connection-key");
|
||||
}
|
||||
|
||||
getEncryptionKey(): Buffer {
|
||||
return Buffer.from(this.#encryptionKey);
|
||||
}
|
||||
}
|
||||
|
||||
export class CultNetServerSecurityOptions extends CultNetClientSecurityOptions {
|
||||
static readonly CONNECTION_KEY_ENVIRONMENT_VARIABLE = "GAMECULT_CONNECTION_KEY";
|
||||
static readonly SESSION_SIGNING_SECRET_ENVIRONMENT_VARIABLE = "GAMECULT_SESSION_SIGNING_SECRET";
|
||||
|
||||
readonly #sessionSigningKey: Buffer;
|
||||
readonly sessionSigningSecret: string;
|
||||
readonly isDevelopment: boolean;
|
||||
|
||||
constructor(connectionKey: string, sessionSigningSecret: string, isDevelopment = false) {
|
||||
super(connectionKey);
|
||||
|
||||
if (!sessionSigningSecret || sessionSigningSecret.trim().length === 0) {
|
||||
throw new Error("Session signing secret must be provided.");
|
||||
}
|
||||
|
||||
this.sessionSigningSecret = sessionSigningSecret;
|
||||
this.#sessionSigningKey = sha256(Buffer.from(sessionSigningSecret, "utf8"));
|
||||
this.isDevelopment = isDevelopment;
|
||||
}
|
||||
|
||||
static fromEnvironment(
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
allowDevelopmentDefaults = false,
|
||||
): CultNetServerSecurityOptions {
|
||||
const connectionKey = environment[CultNetServerSecurityOptions.CONNECTION_KEY_ENVIRONMENT_VARIABLE];
|
||||
const sessionSigningSecret = environment[CultNetServerSecurityOptions.SESSION_SIGNING_SECRET_ENVIRONMENT_VARIABLE];
|
||||
|
||||
const missingConnectionKey = !connectionKey || connectionKey.trim().length === 0;
|
||||
const missingSessionSigningSecret = !sessionSigningSecret || sessionSigningSecret.trim().length === 0;
|
||||
|
||||
if (missingConnectionKey && missingSessionSigningSecret) {
|
||||
if (allowDevelopmentDefaults) {
|
||||
return CultNetServerSecurityOptions.development();
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
"Server security configuration is not configured. Set GAMECULT_CONNECTION_KEY and GAMECULT_SESSION_SIGNING_SECRET, or explicitly use CultNetServerSecurityOptions.development() for local development.",
|
||||
);
|
||||
}
|
||||
|
||||
if (missingConnectionKey || missingSessionSigningSecret) {
|
||||
const missing = [
|
||||
missingConnectionKey ? CultNetServerSecurityOptions.CONNECTION_KEY_ENVIRONMENT_VARIABLE : undefined,
|
||||
missingSessionSigningSecret ? CultNetServerSecurityOptions.SESSION_SIGNING_SECRET_ENVIRONMENT_VARIABLE : undefined,
|
||||
].filter((value): value is string => Boolean(value));
|
||||
throw new Error(`Server security configuration is partially configured. Missing: ${missing.join(", ")}.`);
|
||||
}
|
||||
|
||||
return new CultNetServerSecurityOptions(connectionKey!, sessionSigningSecret!);
|
||||
}
|
||||
|
||||
static development(): CultNetServerSecurityOptions {
|
||||
return new CultNetServerSecurityOptions(
|
||||
"gamecult-dev-connection-key",
|
||||
"gamecult-dev-session-signing-secret",
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
getSessionSigningKey(): Buffer {
|
||||
return Buffer.from(this.#sessionSigningKey);
|
||||
}
|
||||
|
||||
toClientOptions(): CultNetClientSecurityOptions {
|
||||
return new CultNetClientSecurityOptions(this.connectionKey);
|
||||
}
|
||||
}
|
||||
|
||||
export interface ValidatedCultNetSessionToken {
|
||||
userId: string;
|
||||
expiresAtUtc: Date;
|
||||
}
|
||||
|
||||
export const CultNetSecret = {
|
||||
newNonce(): Uint8Array {
|
||||
return randomBytes(NONCE_LENGTH);
|
||||
},
|
||||
|
||||
encryptString(
|
||||
input: string | null | undefined,
|
||||
nonce: Uint8Array,
|
||||
options: CultNetClientSecurityOptions | CultNetServerSecurityOptions,
|
||||
): Uint8Array | null {
|
||||
if (!input) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.encryptBytes(Buffer.from(input, "utf8"), nonce, options);
|
||||
},
|
||||
|
||||
decryptString(
|
||||
encrypted: Uint8Array | null | undefined,
|
||||
nonce: Uint8Array | null | undefined,
|
||||
options: CultNetClientSecurityOptions | CultNetServerSecurityOptions,
|
||||
): string | null {
|
||||
if (!encrypted || !nonce) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Buffer.from(this.decryptBytes(encrypted, nonce, options)).toString("utf8");
|
||||
},
|
||||
|
||||
encryptBytes(
|
||||
input: Uint8Array,
|
||||
nonce: Uint8Array,
|
||||
options: CultNetClientSecurityOptions | CultNetServerSecurityOptions,
|
||||
): Uint8Array {
|
||||
const nonceBuffer = validateNonce(nonce);
|
||||
const cipher = createCipheriv("aes-256-gcm", options.getEncryptionKey(), nonceBuffer, {
|
||||
authTagLength: TAG_LENGTH,
|
||||
});
|
||||
const ciphertext = Buffer.concat([cipher.update(input), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return Buffer.concat([tag, ciphertext]);
|
||||
},
|
||||
|
||||
decryptBytes(
|
||||
encrypted: Uint8Array,
|
||||
nonce: Uint8Array,
|
||||
options: CultNetClientSecurityOptions | CultNetServerSecurityOptions,
|
||||
): Uint8Array {
|
||||
const nonceBuffer = validateNonce(nonce);
|
||||
const encryptedBuffer = Buffer.from(encrypted);
|
||||
|
||||
if (encryptedBuffer.length < TAG_LENGTH) {
|
||||
throw new Error("Invalid encrypted data.");
|
||||
}
|
||||
|
||||
const tag = encryptedBuffer.subarray(0, TAG_LENGTH);
|
||||
const ciphertext = encryptedBuffer.subarray(TAG_LENGTH);
|
||||
const decipher = createDecipheriv("aes-256-gcm", options.getEncryptionKey(), nonceBuffer, {
|
||||
authTagLength: TAG_LENGTH,
|
||||
});
|
||||
decipher.setAuthTag(tag);
|
||||
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||
},
|
||||
|
||||
createSessionToken(
|
||||
userId: string,
|
||||
expiresAtUtc: Date,
|
||||
options: CultNetServerSecurityOptions,
|
||||
): string {
|
||||
const payload = `${userId}|${Math.floor(expiresAtUtc.getTime() / 1000)}`;
|
||||
const payloadBytes = Buffer.from(payload, "utf8");
|
||||
const signatureBytes = hmacSha256(options.getSessionSigningKey(), payloadBytes);
|
||||
return `${toBase64Url(payloadBytes)}.${toBase64Url(signatureBytes)}`;
|
||||
},
|
||||
|
||||
tryValidateSessionToken(
|
||||
token: string | null | undefined,
|
||||
options: CultNetServerSecurityOptions,
|
||||
): ValidatedCultNetSessionToken | null {
|
||||
if (!token || token.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parts = token.split(".");
|
||||
if (parts.length !== 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const payloadBytes = fromBase64Url(parts[0]);
|
||||
const signatureBytes = fromBase64Url(parts[1]);
|
||||
const expectedSignature = hmacSha256(options.getSessionSigningKey(), payloadBytes);
|
||||
|
||||
if (signatureBytes.length !== expectedSignature.length || !timingSafeEqual(signatureBytes, expectedSignature)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const payload = payloadBytes.toString("utf8");
|
||||
const payloadParts = payload.split("|");
|
||||
if (payloadParts.length !== 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [userId, expiresAtUnix] = payloadParts;
|
||||
const expiresAtSeconds = Number.parseInt(expiresAtUnix, 10);
|
||||
if (!Number.isFinite(expiresAtSeconds)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const expiresAtUtc = new Date(expiresAtSeconds * 1000);
|
||||
if (expiresAtUtc.getTime() <= Date.now()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
userId,
|
||||
expiresAtUtc,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
toBase64Url(input: Uint8Array): string {
|
||||
return toBase64Url(input);
|
||||
},
|
||||
|
||||
fromBase64Url(input: string): Uint8Array {
|
||||
return fromBase64Url(input);
|
||||
},
|
||||
} as const;
|
||||
|
||||
function validateNonce(nonce: Uint8Array): Buffer {
|
||||
const value = Buffer.from(nonce);
|
||||
if (value.length !== NONCE_LENGTH) {
|
||||
throw new Error("Invalid nonce.");
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function sha256(input: Uint8Array): Buffer {
|
||||
return createHash("sha256").update(input).digest();
|
||||
}
|
||||
|
||||
function hmacSha256(key: Uint8Array, input: Uint8Array): Buffer {
|
||||
return createHmac("sha256", key).update(input).digest();
|
||||
}
|
||||
|
||||
function toBase64Url(input: Uint8Array): string {
|
||||
return Buffer.from(input)
|
||||
.toString("base64")
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/u, "");
|
||||
}
|
||||
|
||||
function fromBase64Url(input: string): Buffer {
|
||||
const normalized = input
|
||||
.replace(/-/g, "+")
|
||||
.replace(/_/g, "/");
|
||||
const remainder = normalized.length % 4;
|
||||
const padded = remainder === 0
|
||||
? normalized
|
||||
: normalized + "=".repeat(4 - remainder);
|
||||
return Buffer.from(padded, "base64");
|
||||
}
|
||||
497
test/cultnet.test.ts
Normal file
497
test/cultnet.test.ts
Normal file
|
|
@ -0,0 +1,497 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { Duplex } from "node:stream";
|
||||
import { rmSync, mkdtempSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
import { z } from "zod";
|
||||
import {
|
||||
CultCache,
|
||||
SingleFileMessagePackBackingStore,
|
||||
defineDocumentType,
|
||||
} from "cultcache-ts";
|
||||
|
||||
import {
|
||||
CultNetClientSecurityOptions,
|
||||
CultNetDocumentRegistry,
|
||||
CultNetPeer,
|
||||
CultNetSchemaRegistry,
|
||||
CultNetSecret,
|
||||
CultNetServerSecurityOptions,
|
||||
cultNetSchemas,
|
||||
cultNetBuiltinSchemaRegistry,
|
||||
defineCultNetDocumentBinding,
|
||||
encodeCultNetMessageForWire,
|
||||
ghostlightAgentStateGeneratedContract,
|
||||
parseCultNetMessage,
|
||||
validateGhostlightAgentStateGenerated,
|
||||
validateGhostlightAgentState,
|
||||
type CultNetLoginMessage,
|
||||
type GhostlightAgentStateShape,
|
||||
type GhostlightAgentStateDocument,
|
||||
} from "../src";
|
||||
import {
|
||||
INTEROP_SCHEMA_VERSION,
|
||||
createInteropFormatter,
|
||||
createLegacyInteropNoteFormatter,
|
||||
createMismatchedInteropNoteFormatter,
|
||||
type InteropNote,
|
||||
} from "./interop/cultnet-interop-shared";
|
||||
|
||||
class LinkedDuplex extends Duplex {
|
||||
peer?: LinkedDuplex;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
_read(): void {}
|
||||
|
||||
_write(
|
||||
chunk: Buffer,
|
||||
_encoding: BufferEncoding,
|
||||
callback: (error?: Error | null) => void,
|
||||
): void {
|
||||
this.peer?.push(Buffer.from(chunk));
|
||||
callback();
|
||||
}
|
||||
|
||||
_final(callback: (error?: Error | null) => void): void {
|
||||
this.peer?.push(null);
|
||||
callback();
|
||||
}
|
||||
}
|
||||
|
||||
function createDuplexPair(): { a: Duplex; b: Duplex } {
|
||||
const a = new LinkedDuplex();
|
||||
const b = new LinkedDuplex();
|
||||
a.peer = b;
|
||||
b.peer = a;
|
||||
return { a, b };
|
||||
}
|
||||
|
||||
test("CultNet secret helpers round-trip encrypted strings and validate sessions", () => {
|
||||
const serverSecurity = CultNetServerSecurityOptions.development();
|
||||
const clientSecurity = serverSecurity.toClientOptions();
|
||||
const nonce = CultNetSecret.newNonce();
|
||||
const encrypted = CultNetSecret.encryptString("hello", nonce, clientSecurity);
|
||||
assert.ok(encrypted);
|
||||
assert.equal(CultNetSecret.decryptString(encrypted, nonce, serverSecurity), "hello");
|
||||
|
||||
const token = CultNetSecret.createSessionToken(
|
||||
"runtime-face",
|
||||
new Date(Date.now() + 60_000),
|
||||
serverSecurity,
|
||||
);
|
||||
const validated = CultNetSecret.tryValidateSessionToken(token, serverSecurity);
|
||||
assert.ok(validated);
|
||||
assert.equal(validated?.userId, "runtime-face");
|
||||
});
|
||||
|
||||
test("CultNet peer frames and decodes typed messages over a direct pipe", async () => {
|
||||
const { a, b } = createDuplexPair();
|
||||
const sender = new CultNetPeer(a, { wireContract: "cultnet.schema.v0" });
|
||||
const receiver = new CultNetPeer(b, { wireContract: "cultnet.schema.v0" });
|
||||
|
||||
const message = await new Promise<ReturnType<typeof parseCultNetMessage>>((resolve, reject) => {
|
||||
receiver.once("message", resolve);
|
||||
receiver.once("invalidMessage", reject);
|
||||
sender.sendHello({
|
||||
schemaVersion: "cultnet.hello.v0",
|
||||
runtimeId: "voidbot-main",
|
||||
runtimeKind: "node-worker",
|
||||
agentId: "void",
|
||||
displayName: "Void",
|
||||
supportedDocumentTypes: ["ghostlight.agent-state"],
|
||||
});
|
||||
});
|
||||
|
||||
assert.equal(message.schemaVersion, "cultnet.hello.v0");
|
||||
if (message.schemaVersion === "cultnet.hello.v0") {
|
||||
assert.equal(message.runtimeId, "voidbot-main");
|
||||
assert.equal(message.agentId, "void");
|
||||
}
|
||||
|
||||
sender.close();
|
||||
receiver.close();
|
||||
});
|
||||
|
||||
test("CultNet can round-trip gamecult.networking.v0 auth messages through the explicit legacy contract", () => {
|
||||
const message: CultNetLoginMessage = {
|
||||
schemaVersion: "cultnet.login.v0",
|
||||
nonce: "bm9uY2U",
|
||||
auth: "YXV0aA",
|
||||
password: "cGFzc3dvcmQ",
|
||||
};
|
||||
|
||||
const wireValue = encodeCultNetMessageForWire(message, "gamecult.networking.v0");
|
||||
assert.deepEqual(wireValue, [
|
||||
0,
|
||||
[
|
||||
Buffer.from("nonce", "utf8"),
|
||||
Buffer.from("auth", "utf8"),
|
||||
Buffer.from("password", "utf8"),
|
||||
],
|
||||
]);
|
||||
|
||||
const decoded = parseCultNetMessage(wireValue, "gamecult.networking.v0");
|
||||
assert.deepEqual(decoded, message);
|
||||
});
|
||||
|
||||
test("CultNet schema discovery catalog can advertise canonical schemas without inline bodies by default", () => {
|
||||
const response = cultNetBuiltinSchemaRegistry.createCatalogResponse({
|
||||
schemaVersion: "cultnet.schema_catalog_request.v0",
|
||||
messageId: "catalog-1",
|
||||
});
|
||||
|
||||
const ghostlight = response.schemas.find((schema) => schema.documentType === "ghostlight.agent-state");
|
||||
assert.ok(ghostlight);
|
||||
assert.equal(ghostlight?.kind, "document_payload");
|
||||
assert.equal(ghostlight?.documentType, "ghostlight.agent-state");
|
||||
assert.equal(typeof ghostlight?.contentHash, "string");
|
||||
assert.equal(ghostlight?.schemaJson, undefined);
|
||||
});
|
||||
|
||||
test("CultNet schema discovery can round-trip over the legacy wire contract when schemas are requested inline", () => {
|
||||
const registry = new CultNetSchemaRegistry([
|
||||
{
|
||||
schemaId: "https://example.test/contracts/example.schema.json",
|
||||
kind: "shared_contract",
|
||||
schema: {
|
||||
$schema: "https://json-schema.org/draft/2020-12/schema",
|
||||
$id: "https://example.test/contracts/example.schema.json",
|
||||
type: "object",
|
||||
properties: {
|
||||
value: { type: "string" },
|
||||
},
|
||||
required: ["value"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
title: "Example Schema",
|
||||
wireContracts: ["cultnet.schema.v0", "gamecult.networking.v0"],
|
||||
},
|
||||
]);
|
||||
|
||||
const response = registry.createCatalogResponse({
|
||||
schemaVersion: "cultnet.schema_catalog_request.v0",
|
||||
messageId: "catalog-legacy",
|
||||
includeSchemaJson: true,
|
||||
});
|
||||
|
||||
const wireValue = encodeCultNetMessageForWire(response, "gamecult.networking.v0");
|
||||
const decoded = parseCultNetMessage(wireValue, "gamecult.networking.v0");
|
||||
assert.equal(decoded.schemaVersion, "cultnet.schema_catalog_response.v0");
|
||||
if (decoded.schemaVersion === "cultnet.schema_catalog_response.v0") {
|
||||
assert.equal(decoded.messageId, "catalog-legacy");
|
||||
assert.equal(decoded.schemas[0]?.schemaId, "https://example.test/contracts/example.schema.json");
|
||||
assert.match(decoded.schemas[0]?.schemaJson ?? "", /"value"/u);
|
||||
}
|
||||
});
|
||||
|
||||
test("CultNet document registry builds snapshots and applies document puts through CultCache", async () => {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "cultnetts-"));
|
||||
|
||||
try {
|
||||
const documentDefinition = defineDocumentType({
|
||||
type: "ghostlight.agent-state",
|
||||
schemaId: cultNetSchemas.ghostlightAgentStateSchema.$id,
|
||||
schemaName: "ghostlight.agent-state",
|
||||
schemaVersion: "ghostlight.agent_state.v0",
|
||||
schema: z.custom<GhostlightAgentStateDocument>((value) => {
|
||||
try {
|
||||
validateGhostlightAgentState(value);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
const registry = new CultNetDocumentRegistry([
|
||||
defineCultNetDocumentBinding({
|
||||
definition: documentDefinition,
|
||||
payloadSchemaVersion: "ghostlight.agent_state.v0",
|
||||
}),
|
||||
]);
|
||||
|
||||
const originStore = new SingleFileMessagePackBackingStore(join(tempDir, "origin.msgpack"));
|
||||
const targetStore = new SingleFileMessagePackBackingStore(join(tempDir, "target.msgpack"));
|
||||
const originCache = CultCache.builder()
|
||||
.withDocumentType(documentDefinition)
|
||||
.withGenericStore(originStore)
|
||||
.build();
|
||||
const targetCache = CultCache.builder()
|
||||
.withDocumentType(documentDefinition)
|
||||
.withGenericStore(targetStore)
|
||||
.build();
|
||||
|
||||
const payload = validateGhostlightAgentState({
|
||||
schema_version: "ghostlight.agent_state.v0",
|
||||
world: {
|
||||
world_id: "epiphany-face",
|
||||
setting: "test harness",
|
||||
time: { label: "now" },
|
||||
canon_context: ["test"],
|
||||
},
|
||||
agents: [
|
||||
{
|
||||
agent_id: "epiphany.face",
|
||||
identity: {
|
||||
name: "Face",
|
||||
roles: ["public-surface"],
|
||||
origin: "test",
|
||||
public_description: "test",
|
||||
},
|
||||
canonical_state: {
|
||||
underlying_organization: {},
|
||||
stable_dispositions: {},
|
||||
behavioral_dimensions: {},
|
||||
presentation_strategy: {},
|
||||
voice_style: {},
|
||||
situational_state: {},
|
||||
values: [],
|
||||
},
|
||||
goals: [],
|
||||
memories: {
|
||||
episodic: [],
|
||||
semantic: [],
|
||||
relationship_summaries: [],
|
||||
},
|
||||
perceived_state_overlays: [],
|
||||
},
|
||||
],
|
||||
relationships: [],
|
||||
events: [],
|
||||
scenes: [],
|
||||
});
|
||||
|
||||
await originCache.put(documentDefinition, "epiphany.face", payload);
|
||||
const snapshot = registry.createSnapshotResponse(originCache, "snapshot-1");
|
||||
await registry.applySnapshotResponse(targetCache, snapshot);
|
||||
|
||||
const roundTrip = targetCache.get(documentDefinition, "epiphany.face");
|
||||
assert.ok(roundTrip);
|
||||
assert.equal(roundTrip?.schema_version, "ghostlight.agent_state.v0");
|
||||
assert.equal(roundTrip?.agents[0]?.agent_id, "epiphany.face");
|
||||
} finally {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("CultNet raw replication preserves CultCache payload bytes for bit-compatible neighbors", async () => {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "cultnetts-raw-"));
|
||||
|
||||
try {
|
||||
const documentDefinition = defineDocumentType({
|
||||
type: "ghostlight.agent-state",
|
||||
schemaId: cultNetSchemas.ghostlightAgentStateSchema.$id,
|
||||
schemaName: "ghostlight.agent-state",
|
||||
schemaVersion: "ghostlight.agent_state.v0",
|
||||
schema: z.custom<GhostlightAgentStateDocument>((value) => {
|
||||
try {
|
||||
validateGhostlightAgentState(value);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
const registry = new CultNetDocumentRegistry([
|
||||
defineCultNetDocumentBinding({
|
||||
definition: documentDefinition,
|
||||
payloadSchemaVersion: "ghostlight.agent_state.v0",
|
||||
}),
|
||||
]);
|
||||
|
||||
const originCache = CultCache.builder()
|
||||
.withDocumentType(documentDefinition)
|
||||
.withGenericStore(new SingleFileMessagePackBackingStore(join(tempDir, "origin.msgpack")))
|
||||
.build();
|
||||
const targetCache = CultCache.builder()
|
||||
.withDocumentType(documentDefinition)
|
||||
.withGenericStore(new SingleFileMessagePackBackingStore(join(tempDir, "target.msgpack")))
|
||||
.build();
|
||||
|
||||
const payload = validateGhostlightAgentState({
|
||||
schema_version: "ghostlight.agent_state.v0",
|
||||
world: {
|
||||
world_id: "epiphany-face",
|
||||
setting: "test harness",
|
||||
time: { label: "now" },
|
||||
canon_context: ["test"],
|
||||
},
|
||||
agents: [
|
||||
{
|
||||
agent_id: "epiphany.face",
|
||||
identity: {
|
||||
name: "Face",
|
||||
roles: ["public-surface"],
|
||||
origin: "test",
|
||||
public_description: "test",
|
||||
},
|
||||
canonical_state: {
|
||||
underlying_organization: {},
|
||||
stable_dispositions: {},
|
||||
behavioral_dimensions: {},
|
||||
presentation_strategy: {},
|
||||
voice_style: {},
|
||||
situational_state: {},
|
||||
values: [],
|
||||
},
|
||||
goals: [],
|
||||
memories: {
|
||||
episodic: [],
|
||||
semantic: [],
|
||||
relationship_summaries: [],
|
||||
},
|
||||
perceived_state_overlays: [],
|
||||
},
|
||||
],
|
||||
relationships: [],
|
||||
events: [],
|
||||
scenes: [],
|
||||
});
|
||||
|
||||
await originCache.put(documentDefinition, "epiphany.face", payload);
|
||||
const rawSnapshot = registry.createRawSnapshotResponse(originCache, "raw-snapshot-1");
|
||||
assert.equal(rawSnapshot.documents[0]?.schemaId, cultNetSchemas.ghostlightAgentStateSchema.$id);
|
||||
assert.equal(rawSnapshot.documents[0]?.recordKey, "epiphany.face");
|
||||
await registry.applyRawSnapshotResponse(targetCache, rawSnapshot);
|
||||
|
||||
const sourceEnvelope = originCache.getRequiredEnvelope(documentDefinition, "epiphany.face");
|
||||
const targetEnvelope = targetCache.getRequiredEnvelope(documentDefinition, "epiphany.face");
|
||||
assert.deepEqual(targetEnvelope.payload, sourceEnvelope.payload);
|
||||
assert.equal(targetCache.getRequired(documentDefinition, "epiphany.face").schema_version, "ghostlight.agent_state.v0");
|
||||
} finally {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("CultNet interop slot compatibility defaults missing trailing fields and rejects mismatched slots", () => {
|
||||
const note: InteropNote = {
|
||||
schemaVersion: INTEROP_SCHEMA_VERSION,
|
||||
documentId: "note:compat",
|
||||
authorRuntimeId: "compat-peer",
|
||||
title: "Compatibility",
|
||||
body: "Missing trailing fields are allowed when declared defaults cover them.",
|
||||
tags: ["compat"],
|
||||
};
|
||||
|
||||
assert.deepEqual(createInteropFormatter().decode(createLegacyInteropNoteFormatter().encode(note)), {
|
||||
...note,
|
||||
tags: [],
|
||||
});
|
||||
assert.throws(
|
||||
() => createInteropFormatter().decode(createMismatchedInteropNoteFormatter().encode(note)),
|
||||
/Expected string/u,
|
||||
);
|
||||
});
|
||||
|
||||
test("Ghostlight contract mirror rejects nested payloads that violate the canonical schema", () => {
|
||||
assert.throws(
|
||||
() => validateGhostlightAgentState({
|
||||
schema_version: "ghostlight.agent_state.v0",
|
||||
world: {
|
||||
world_id: "ghostlight-lab",
|
||||
setting: "test",
|
||||
time: { label: "now" },
|
||||
canon_context: ["test"],
|
||||
},
|
||||
agents: [
|
||||
{
|
||||
identity: {
|
||||
name: "Face",
|
||||
roles: ["public-surface"],
|
||||
origin: "test",
|
||||
public_description: "test",
|
||||
},
|
||||
canonical_state: {
|
||||
underlying_organization: {},
|
||||
stable_dispositions: {},
|
||||
behavioral_dimensions: {},
|
||||
presentation_strategy: {},
|
||||
voice_style: {},
|
||||
situational_state: {},
|
||||
values: [],
|
||||
},
|
||||
goals: [],
|
||||
memories: {
|
||||
episodic: [],
|
||||
semantic: [],
|
||||
relationship_summaries: [],
|
||||
},
|
||||
perceived_state_overlays: [],
|
||||
},
|
||||
],
|
||||
relationships: [],
|
||||
events: [],
|
||||
scenes: [],
|
||||
}),
|
||||
/agent_id/u,
|
||||
);
|
||||
});
|
||||
|
||||
test("Generated Ghostlight contracts can feed CultCacheTS directly without a Zod mirror", async () => {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "cultnetts-generated-"));
|
||||
|
||||
try {
|
||||
const documentDefinition = defineDocumentType({
|
||||
type: "ghostlight.agent-state.generated",
|
||||
schema: ghostlightAgentStateGeneratedContract,
|
||||
global: true,
|
||||
});
|
||||
|
||||
const store = new SingleFileMessagePackBackingStore(join(tempDir, "generated.msgpack"));
|
||||
const cache = CultCache.builder()
|
||||
.withDocumentType(documentDefinition)
|
||||
.withGenericStore(store)
|
||||
.build();
|
||||
|
||||
const payload: GhostlightAgentStateShape = {
|
||||
schema_version: "ghostlight.agent_state.v0",
|
||||
world: {
|
||||
world_id: "ghostlight-lab",
|
||||
setting: "test harness",
|
||||
time: { label: "now" },
|
||||
canon_context: ["test"],
|
||||
},
|
||||
agents: [
|
||||
{
|
||||
agent_id: "void",
|
||||
identity: {
|
||||
name: "Void",
|
||||
roles: ["observer"],
|
||||
origin: "test",
|
||||
public_description: "test",
|
||||
},
|
||||
canonical_state: {
|
||||
underlying_organization: {},
|
||||
stable_dispositions: {},
|
||||
behavioral_dimensions: {},
|
||||
presentation_strategy: {},
|
||||
voice_style: {},
|
||||
situational_state: {},
|
||||
values: [],
|
||||
},
|
||||
goals: [],
|
||||
memories: {
|
||||
episodic: [],
|
||||
semantic: [],
|
||||
relationship_summaries: [],
|
||||
},
|
||||
perceived_state_overlays: [],
|
||||
},
|
||||
],
|
||||
relationships: [],
|
||||
events: [],
|
||||
scenes: [],
|
||||
};
|
||||
|
||||
await cache.putGlobal(documentDefinition, payload);
|
||||
const roundTrip = cache.getRequiredGlobal(documentDefinition);
|
||||
assert.equal(validateGhostlightAgentStateGenerated(roundTrip), true);
|
||||
assert.equal(roundTrip.schema_version, "ghostlight.agent_state.v0");
|
||||
assert.equal(roundTrip.agents[0]?.agent_id, "void");
|
||||
} finally {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
767
test/interop/cultnet-interop-peer.ts
Normal file
767
test/interop/cultnet-interop-peer.ts
Normal file
|
|
@ -0,0 +1,767 @@
|
|||
import { createSocket, type RemoteInfo, type Socket as DgramSocket } from "node:dgram";
|
||||
import { connect as connectTcp, createServer, type Server, type Socket as TcpSocket } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import process from "node:process";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
|
||||
import { decode, encode } from "@msgpack/msgpack";
|
||||
import { CultCache, SingleFileMessagePackBackingStore, defineDocumentType, type AnyCultCacheDocumentDefinition } from "cultcache-ts";
|
||||
import {
|
||||
CultNetDocumentRegistry,
|
||||
CultNetPeer,
|
||||
CultNetSchemaRegistry,
|
||||
cultNetBuiltinSchemaRegistry,
|
||||
defineCultNetDocumentBinding,
|
||||
type CultNetDocumentBinding,
|
||||
type CultNetDocumentPutRawMessage,
|
||||
type CultNetMessage,
|
||||
type CultNetSchemaCatalogRequestMessage,
|
||||
type CultNetSchemaCatalogResponseMessage,
|
||||
type CultNetSnapshotRequestMessage,
|
||||
type CultNetSnapshotResponseRawMessage,
|
||||
} from "../../src";
|
||||
import {
|
||||
DISCOVERY_ANNOUNCE_SCHEMA_VERSION,
|
||||
DISCOVERY_PROBE_SCHEMA_VERSION,
|
||||
INTEROP_DOCUMENT_TYPE,
|
||||
INTEROP_FIRE_COMMAND_DOCUMENT_TYPE,
|
||||
INTEROP_FIRE_COMMAND_SCHEMA_ID,
|
||||
INTEROP_FIRE_COMMAND_SCHEMA_VERSION,
|
||||
INTEROP_FIRE_RECEIPT_DOCUMENT_TYPE,
|
||||
INTEROP_FIRE_RECEIPT_SCHEMA_ID,
|
||||
INTEROP_FIRE_RECEIPT_SCHEMA_VERSION,
|
||||
INTEROP_MUTATION_INTENT_DOCUMENT_TYPE,
|
||||
INTEROP_MUTATION_INTENT_SCHEMA_ID,
|
||||
INTEROP_MUTATION_INTENT_SCHEMA_VERSION,
|
||||
INTEROP_MUTATION_RECEIPT_DOCUMENT_TYPE,
|
||||
INTEROP_MUTATION_RECEIPT_SCHEMA_ID,
|
||||
INTEROP_MUTATION_RECEIPT_SCHEMA_VERSION,
|
||||
INTEROP_SCHEMA_VERSION,
|
||||
INTEROP_WIRE_CONTRACT,
|
||||
buildInteropNote,
|
||||
createInteropFireCommandFormatter,
|
||||
createInteropFireReceiptFormatter,
|
||||
createInteropFormatter,
|
||||
createInteropMutationIntentFormatter,
|
||||
createInteropMutationReceiptFormatter,
|
||||
discoveryAnnounceSchema,
|
||||
discoveryProbeSchema,
|
||||
interopFireCommandSchema,
|
||||
interopFireReceiptSchema,
|
||||
interopMutationIntentSchema,
|
||||
interopMutationReceiptSchema,
|
||||
interopNoteSchema,
|
||||
loadInteropSchemaRegistration,
|
||||
optionalIntArg,
|
||||
parseArgs,
|
||||
requireArg,
|
||||
type DiscoveryAnnounce,
|
||||
type DiscoveryProbe,
|
||||
type InteropFireCommand,
|
||||
type InteropFireReceipt,
|
||||
type InteropMutationIntent,
|
||||
type InteropMutationReceipt,
|
||||
type InteropNote,
|
||||
} from "./cultnet-interop-shared";
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const [mode, ...rest] = process.argv.slice(2);
|
||||
if (!mode) {
|
||||
throw new Error("Expected mode: serve | probe | dial");
|
||||
}
|
||||
|
||||
const args = parseArgs(rest);
|
||||
|
||||
switch (mode) {
|
||||
case "serve":
|
||||
await serve(args);
|
||||
return;
|
||||
case "probe":
|
||||
await probe(args);
|
||||
return;
|
||||
case "dial":
|
||||
await dial(args);
|
||||
return;
|
||||
default:
|
||||
throw new Error(`Unknown mode ${mode}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function serve(args: Map<string, string>): Promise<void> {
|
||||
const runtimeId = requireArg(args, "runtime-id");
|
||||
const runtimeKind = requireArg(args, "runtime-kind");
|
||||
const displayName = requireArg(args, "display-name");
|
||||
const agentId = requireArg(args, "agent-id");
|
||||
const advertiseHost = requireArg(args, "advertise-host");
|
||||
const bindHost = args.get("bind-host") ?? "127.0.0.1";
|
||||
const tcpPort = optionalIntArg(args, "tcp-port");
|
||||
const discoveryPort = optionalIntArg(args, "discovery-port");
|
||||
const discoveryGroup = requireArg(args, "discovery-group");
|
||||
const schemaPath = requireArg(args, "schema-path");
|
||||
|
||||
if (!tcpPort || !discoveryPort) {
|
||||
throw new Error("serve mode requires --tcp-port and --discovery-port");
|
||||
}
|
||||
|
||||
const interopSchema = await loadInteropSchemaRegistration(schemaPath);
|
||||
const documents = defineInteropDocuments(interopSchema.schemaId);
|
||||
const cache = CultCache.builder()
|
||||
.withDocumentType(documents.note.definition)
|
||||
.withDocumentType(documents.mutationIntent.definition)
|
||||
.withDocumentType(documents.mutationReceipt.definition)
|
||||
.withDocumentType(documents.fireCommand.definition)
|
||||
.withDocumentType(documents.fireReceipt.definition)
|
||||
.withGenericStore(new SingleFileMessagePackBackingStore(runtimeStorePath(runtimeId)))
|
||||
.build();
|
||||
const documentRegistry = new CultNetDocumentRegistry(Object.values(documents));
|
||||
const customSchemas = new CultNetSchemaRegistry([
|
||||
{
|
||||
schemaId: interopSchema.schemaId,
|
||||
kind: "document_payload",
|
||||
schema: interopSchema.schema,
|
||||
schemaVersion: INTEROP_SCHEMA_VERSION,
|
||||
documentType: INTEROP_DOCUMENT_TYPE,
|
||||
title: interopSchema.title,
|
||||
wireContracts: [INTEROP_WIRE_CONTRACT],
|
||||
},
|
||||
]);
|
||||
|
||||
await cache.put(documents.note.definition, `note:${runtimeId}`, buildInteropNote(runtimeId, displayName));
|
||||
|
||||
const tcpServer = createServer();
|
||||
tcpServer.on("connection", (socket) => {
|
||||
const peer = new CultNetPeer(socket, { wireContract: INTEROP_WIRE_CONTRACT });
|
||||
peer.on("invalidMessage", (error) => writeLog("invalidMessage", { runtimeId, error: error.message }));
|
||||
peer.on("error", (error) => writeLog("tcpError", { runtimeId, error: error.message }));
|
||||
peer.on("message", async (message) => {
|
||||
try {
|
||||
await handleServerMessage({
|
||||
peer,
|
||||
message,
|
||||
runtimeId,
|
||||
runtimeKind,
|
||||
displayName,
|
||||
agentId,
|
||||
cache,
|
||||
documentRegistry,
|
||||
customSchemas,
|
||||
noteSchemaId: interopSchema.schemaId,
|
||||
});
|
||||
} catch (error) {
|
||||
writeLog("serveMessageError", {
|
||||
runtimeId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const udpSocket = createSocket({ type: "udp4", reuseAddr: true });
|
||||
udpSocket.on("error", (error) => writeLog("udpError", { runtimeId, error: error.message }));
|
||||
udpSocket.on("message", (packet, remote) => {
|
||||
try {
|
||||
const probeMessage = discoveryProbeSchema.parse(decode(packet));
|
||||
void respondToProbe({
|
||||
socket: udpSocket,
|
||||
remote,
|
||||
probeMessage,
|
||||
runtimeId,
|
||||
runtimeKind,
|
||||
displayName,
|
||||
agentId,
|
||||
advertiseHost,
|
||||
tcpPort,
|
||||
});
|
||||
} catch {
|
||||
// ignore unrelated multicast noise instead of becoming dramatic about it
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
new Promise<void>((resolve, reject) => {
|
||||
tcpServer.once("error", reject);
|
||||
tcpServer.listen(tcpPort, bindHost, () => resolve());
|
||||
}),
|
||||
new Promise<void>((resolve, reject) => {
|
||||
udpSocket.once("error", reject);
|
||||
udpSocket.bind(discoveryPort, "0.0.0.0", () => {
|
||||
udpSocket.addMembership(discoveryGroup);
|
||||
udpSocket.setMulticastTTL(1);
|
||||
udpSocket.setMulticastLoopback(true);
|
||||
resolve();
|
||||
});
|
||||
}),
|
||||
]);
|
||||
|
||||
writeJsonLine({
|
||||
status: "ready",
|
||||
mode: "serve",
|
||||
runtimeId,
|
||||
runtimeKind,
|
||||
tcpPort,
|
||||
discoveryPort,
|
||||
discoveryGroup,
|
||||
});
|
||||
|
||||
await waitForTermination(async () => {
|
||||
udpSocket.close();
|
||||
await closeServer(tcpServer);
|
||||
});
|
||||
}
|
||||
|
||||
async function handleServerMessage(input: {
|
||||
peer: CultNetPeer;
|
||||
message: CultNetMessage;
|
||||
runtimeId: string;
|
||||
runtimeKind: string;
|
||||
displayName: string;
|
||||
agentId: string;
|
||||
cache: CultCache;
|
||||
documentRegistry: CultNetDocumentRegistry;
|
||||
customSchemas: CultNetSchemaRegistry;
|
||||
noteSchemaId: string;
|
||||
}): Promise<void> {
|
||||
const {
|
||||
peer,
|
||||
message,
|
||||
runtimeId,
|
||||
runtimeKind,
|
||||
displayName,
|
||||
agentId,
|
||||
cache,
|
||||
documentRegistry,
|
||||
customSchemas,
|
||||
noteSchemaId,
|
||||
} = input;
|
||||
|
||||
switch (message.schemaVersion) {
|
||||
case "cultnet.hello.v0":
|
||||
peer.sendHello({
|
||||
schemaVersion: "cultnet.hello.v0",
|
||||
runtimeId,
|
||||
runtimeKind,
|
||||
agentId,
|
||||
displayName,
|
||||
supportedDocumentTypes: [INTEROP_DOCUMENT_TYPE],
|
||||
supportedMutationContracts: [{
|
||||
documentType: INTEROP_DOCUMENT_TYPE,
|
||||
payloadSchemaVersion: INTEROP_SCHEMA_VERSION,
|
||||
operations: ["snapshot", "documentPut", "intentSubmit", "receiptWatch"],
|
||||
authority: "runtime",
|
||||
intentDocumentTypes: [INTEROP_MUTATION_INTENT_DOCUMENT_TYPE, INTEROP_FIRE_COMMAND_DOCUMENT_TYPE],
|
||||
receiptDocumentTypes: [INTEROP_MUTATION_RECEIPT_DOCUMENT_TYPE, INTEROP_FIRE_RECEIPT_DOCUMENT_TYPE],
|
||||
}],
|
||||
supportedMessageVersions: [INTEROP_SCHEMA_VERSION],
|
||||
supportsSchemaCatalog: true,
|
||||
});
|
||||
break;
|
||||
case "cultnet.schema_catalog_request.v0":
|
||||
peer.sendSchemaCatalogResponse(createCatalogResponse(customSchemas, message));
|
||||
break;
|
||||
case "cultnet.snapshot_request.v0":
|
||||
peer.send(documentRegistry.createRawSnapshotResponse(cache, message.messageId, message));
|
||||
break;
|
||||
case "cultnet.document_put_raw.v0":
|
||||
await handleRawPut({
|
||||
peer,
|
||||
message,
|
||||
runtimeId,
|
||||
agentId,
|
||||
cache,
|
||||
documentRegistry,
|
||||
noteSchemaId,
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRawPut(input: {
|
||||
peer: CultNetPeer;
|
||||
message: CultNetDocumentPutRawMessage;
|
||||
runtimeId: string;
|
||||
agentId: string;
|
||||
cache: CultCache;
|
||||
documentRegistry: CultNetDocumentRegistry;
|
||||
noteSchemaId: string;
|
||||
}): Promise<void> {
|
||||
const { peer, message, runtimeId, agentId, cache, documentRegistry, noteSchemaId } = input;
|
||||
const applied = await documentRegistry.applyRawDocumentPutMessage(cache, message);
|
||||
if (message.document.schemaId === INTEROP_MUTATION_INTENT_SCHEMA_ID) {
|
||||
const intent = applied as InteropMutationIntent;
|
||||
const note = cache.getRequired(
|
||||
documentRegistry.getBySchemaId(noteSchemaId)?.definition ?? raise("missing note binding"),
|
||||
intent.targetDocumentId,
|
||||
) as InteropNote;
|
||||
const mutated: InteropNote = {
|
||||
...note,
|
||||
body: `${note.body}${intent.appendBody}`,
|
||||
tags: [...note.tags, intent.appendTag],
|
||||
};
|
||||
await cache.put(documentRegistry.getBySchemaId(noteSchemaId)?.definition ?? raise("missing note binding"), mutated.documentId, mutated);
|
||||
const receipt: InteropMutationReceipt = {
|
||||
schemaVersion: INTEROP_MUTATION_RECEIPT_SCHEMA_VERSION,
|
||||
intentId: intent.intentId,
|
||||
accepted: true,
|
||||
documentId: mutated.documentId,
|
||||
body: mutated.body,
|
||||
tags: mutated.tags,
|
||||
};
|
||||
const receiptBinding = documentRegistry.getBySchemaId(INTEROP_MUTATION_RECEIPT_SCHEMA_ID) ?? raise("missing mutation receipt binding");
|
||||
const noteBinding = documentRegistry.getBySchemaId(noteSchemaId) ?? raise("missing note binding");
|
||||
peer.send(documentRegistry.createRawDocumentPutMessage(receiptBinding, `${runtimeId}-mutation-receipt`, receipt.intentId, receipt, {
|
||||
sourceRuntimeId: runtimeId,
|
||||
sourceAgentId: agentId,
|
||||
sourceRole: "peer",
|
||||
tags: ["mutation", runtimeId],
|
||||
}));
|
||||
peer.send(documentRegistry.createRawDocumentPutMessage(noteBinding, `${runtimeId}-mutated-note`, mutated.documentId, mutated, {
|
||||
sourceRuntimeId: runtimeId,
|
||||
sourceAgentId: agentId,
|
||||
sourceRole: "peer",
|
||||
tags: ["mutation", runtimeId],
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.document.schemaId === INTEROP_FIRE_COMMAND_SCHEMA_ID) {
|
||||
const command = applied as InteropFireCommand;
|
||||
const receipt: InteropFireReceipt = {
|
||||
schemaVersion: INTEROP_FIRE_RECEIPT_SCHEMA_VERSION,
|
||||
commandId: command.commandId,
|
||||
accepted: true,
|
||||
characterId: command.characterId,
|
||||
weaponId: command.weaponId,
|
||||
shotsFired: 1,
|
||||
ammoRemaining: 29,
|
||||
};
|
||||
const receiptBinding = documentRegistry.getBySchemaId(INTEROP_FIRE_RECEIPT_SCHEMA_ID) ?? raise("missing fire receipt binding");
|
||||
peer.send(documentRegistry.createRawDocumentPutMessage(receiptBinding, `${runtimeId}-fire-receipt`, receipt.commandId, receipt, {
|
||||
sourceRuntimeId: runtimeId,
|
||||
sourceAgentId: agentId,
|
||||
sourceRole: "peer",
|
||||
tags: ["side-effect", runtimeId],
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
function createCatalogResponse(
|
||||
customSchemas: CultNetSchemaRegistry,
|
||||
request: CultNetSchemaCatalogRequestMessage,
|
||||
): CultNetSchemaCatalogResponseMessage {
|
||||
const builtIn = cultNetBuiltinSchemaRegistry.list({
|
||||
includeSchemaJson: request.includeSchemaJson,
|
||||
schemaIds: request.schemaIds,
|
||||
kinds: request.kinds,
|
||||
});
|
||||
const custom = customSchemas.list({
|
||||
includeSchemaJson: request.includeSchemaJson,
|
||||
schemaIds: request.schemaIds,
|
||||
kinds: request.kinds,
|
||||
});
|
||||
const schemas = [...builtIn];
|
||||
for (const entry of custom) {
|
||||
if (!schemas.some((candidate) => candidate.schemaId === entry.schemaId)) {
|
||||
schemas.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: "cultnet.schema_catalog_response.v0",
|
||||
messageId: request.messageId,
|
||||
schemas,
|
||||
};
|
||||
}
|
||||
|
||||
async function respondToProbe(input: {
|
||||
socket: DgramSocket;
|
||||
remote: RemoteInfo;
|
||||
probeMessage: DiscoveryProbe;
|
||||
runtimeId: string;
|
||||
runtimeKind: string;
|
||||
displayName: string;
|
||||
agentId: string;
|
||||
advertiseHost: string;
|
||||
tcpPort: number;
|
||||
}): Promise<void> {
|
||||
const {
|
||||
socket,
|
||||
remote,
|
||||
probeMessage,
|
||||
runtimeId,
|
||||
runtimeKind,
|
||||
displayName,
|
||||
agentId,
|
||||
advertiseHost,
|
||||
tcpPort,
|
||||
} = input;
|
||||
|
||||
const announceMessage: DiscoveryAnnounce = {
|
||||
schemaVersion: DISCOVERY_ANNOUNCE_SCHEMA_VERSION,
|
||||
messageId: probeMessage.messageId,
|
||||
runtimeId,
|
||||
runtimeKind,
|
||||
displayName,
|
||||
agentId,
|
||||
tcpHost: advertiseHost,
|
||||
tcpPort,
|
||||
wireContract: INTEROP_WIRE_CONTRACT,
|
||||
supportedDocumentTypes: [INTEROP_DOCUMENT_TYPE],
|
||||
supportsSchemaCatalog: true,
|
||||
};
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.send(encode(announceMessage), remote.port, remote.address, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function probe(args: Map<string, string>): Promise<void> {
|
||||
const runtimeId = requireArg(args, "runtime-id");
|
||||
const discoveryPort = optionalIntArg(args, "discovery-port");
|
||||
const discoveryGroup = requireArg(args, "discovery-group");
|
||||
const timeoutMs = optionalIntArg(args, "timeout-ms", 1500) ?? 1500;
|
||||
|
||||
if (!discoveryPort) {
|
||||
throw new Error("probe mode requires --discovery-port");
|
||||
}
|
||||
|
||||
const socket = createSocket({ type: "udp4", reuseAddr: true });
|
||||
const messageId = `${runtimeId}-${Date.now()}`;
|
||||
const found = new Map<string, DiscoveryAnnounce>();
|
||||
|
||||
socket.on("message", (packet) => {
|
||||
try {
|
||||
const announce = discoveryAnnounceSchema.parse(decode(packet));
|
||||
if (announce.messageId === messageId) {
|
||||
found.set(announce.runtimeId, announce);
|
||||
}
|
||||
} catch {
|
||||
// ignore unrelated packets
|
||||
}
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.once("error", reject);
|
||||
socket.bind(0, "0.0.0.0", () => {
|
||||
socket.setMulticastTTL(1);
|
||||
socket.setMulticastLoopback(true);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
const probeMessage: DiscoveryProbe = {
|
||||
schemaVersion: DISCOVERY_PROBE_SCHEMA_VERSION,
|
||||
messageId,
|
||||
requesterRuntimeId: runtimeId,
|
||||
};
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.send(encode(probeMessage), discoveryPort, discoveryGroup, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
await delay(timeoutMs);
|
||||
socket.close();
|
||||
|
||||
writeJsonLine({
|
||||
mode: "probe",
|
||||
runtimeId,
|
||||
peers: [...found.values()].sort((left, right) => left.runtimeId.localeCompare(right.runtimeId)),
|
||||
});
|
||||
}
|
||||
|
||||
async function dial(args: Map<string, string>): Promise<void> {
|
||||
const runtimeId = requireArg(args, "runtime-id");
|
||||
const runtimeKind = requireArg(args, "runtime-kind");
|
||||
const displayName = requireArg(args, "display-name");
|
||||
const agentId = requireArg(args, "agent-id");
|
||||
const targetHost = requireArg(args, "target-host");
|
||||
const targetPort = optionalIntArg(args, "target-port");
|
||||
const schemaPath = requireArg(args, "schema-path");
|
||||
const timeoutMs = optionalIntArg(args, "timeout-ms", 4000) ?? 4000;
|
||||
|
||||
if (!targetPort) {
|
||||
throw new Error("dial mode requires --target-port");
|
||||
}
|
||||
|
||||
const interopSchema = await loadInteropSchemaRegistration(schemaPath);
|
||||
const documents = defineInteropDocuments(interopSchema.schemaId);
|
||||
const cache = CultCache.builder()
|
||||
.withDocumentType(documents.note.definition)
|
||||
.withDocumentType(documents.mutationIntent.definition)
|
||||
.withDocumentType(documents.mutationReceipt.definition)
|
||||
.withDocumentType(documents.fireCommand.definition)
|
||||
.withDocumentType(documents.fireReceipt.definition)
|
||||
.withGenericStore(new SingleFileMessagePackBackingStore(runtimeStorePath(`${runtimeId}-dial`)))
|
||||
.build();
|
||||
const documentRegistry = new CultNetDocumentRegistry(Object.values(documents));
|
||||
|
||||
const socket = await connectTo(targetHost, targetPort);
|
||||
const peer = new CultNetPeer(socket, { wireContract: INTEROP_WIRE_CONTRACT });
|
||||
|
||||
peer.sendHello({
|
||||
schemaVersion: "cultnet.hello.v0",
|
||||
runtimeId,
|
||||
runtimeKind,
|
||||
agentId,
|
||||
displayName,
|
||||
supportedDocumentTypes: [INTEROP_DOCUMENT_TYPE],
|
||||
supportedMutationContracts: [{
|
||||
documentType: INTEROP_DOCUMENT_TYPE,
|
||||
payloadSchemaVersion: INTEROP_SCHEMA_VERSION,
|
||||
operations: ["snapshot", "documentPut", "intentSubmit", "receiptWatch"],
|
||||
authority: "runtime",
|
||||
intentDocumentTypes: [INTEROP_MUTATION_INTENT_DOCUMENT_TYPE, INTEROP_FIRE_COMMAND_DOCUMENT_TYPE],
|
||||
receiptDocumentTypes: [INTEROP_MUTATION_RECEIPT_DOCUMENT_TYPE, INTEROP_FIRE_RECEIPT_DOCUMENT_TYPE],
|
||||
}],
|
||||
supportedMessageVersions: [INTEROP_SCHEMA_VERSION],
|
||||
supportsSchemaCatalog: true,
|
||||
});
|
||||
const remoteHello = await waitForMessage(peer, (message) => message.schemaVersion === "cultnet.hello.v0", timeoutMs);
|
||||
|
||||
const catalogRequest: CultNetSchemaCatalogRequestMessage = {
|
||||
schemaVersion: "cultnet.schema_catalog_request.v0",
|
||||
messageId: `${runtimeId}-catalog`,
|
||||
includeSchemaJson: true,
|
||||
};
|
||||
peer.sendSchemaCatalogRequest(catalogRequest);
|
||||
const catalogResponse = await waitForMessage(peer, (message) => message.schemaVersion === "cultnet.schema_catalog_response.v0", timeoutMs);
|
||||
|
||||
const snapshotRequest: CultNetSnapshotRequestMessage = {
|
||||
schemaVersion: "cultnet.snapshot_request.v0",
|
||||
messageId: `${runtimeId}-snapshot`,
|
||||
schemaIds: [interopSchema.schemaId],
|
||||
};
|
||||
peer.sendSnapshotRequest(snapshotRequest);
|
||||
const snapshotResponse = await waitForMessage(peer, (message) => message.schemaVersion === "cultnet.snapshot_response_raw.v0", timeoutMs);
|
||||
|
||||
await documentRegistry.applyRawSnapshotResponse(cache, snapshotResponse as CultNetSnapshotResponseRawMessage);
|
||||
const note = cache.getRequired(documents.note.definition, `note:${(remoteHello as { runtimeId: string }).runtimeId}`) as InteropNote;
|
||||
const hasInteropSchema = (catalogResponse as CultNetSchemaCatalogResponseMessage).schemas.some(
|
||||
(schema) => schema.schemaId === interopSchema.schemaId && schema.documentType === INTEROP_DOCUMENT_TYPE,
|
||||
);
|
||||
|
||||
const mutationIntent: InteropMutationIntent = {
|
||||
schemaVersion: INTEROP_MUTATION_INTENT_SCHEMA_VERSION,
|
||||
intentId: `${runtimeId}-decorate`,
|
||||
targetDocumentId: note.documentId,
|
||||
appendBody: ` Decorated by ${runtimeId}.`,
|
||||
appendTag: `decorated:${runtimeId}`,
|
||||
};
|
||||
const mutationReceiptWait = waitForMessage(peer, isRawDocumentPutFor(INTEROP_MUTATION_RECEIPT_SCHEMA_ID), timeoutMs);
|
||||
const mutatedNoteWait = waitForMessage(peer, isRawDocumentPutFor(interopSchema.schemaId), timeoutMs);
|
||||
peer.send(documentRegistry.createRawDocumentPutMessage(
|
||||
documents.mutationIntent,
|
||||
`${runtimeId}-decorate-put`,
|
||||
mutationIntent.intentId,
|
||||
mutationIntent,
|
||||
));
|
||||
const mutationReceiptMessage = await mutationReceiptWait;
|
||||
const mutationReceipt = await documentRegistry.applyRawDocumentPutMessage(cache, mutationReceiptMessage) as InteropMutationReceipt;
|
||||
const mutatedNoteMessage = await mutatedNoteWait;
|
||||
await documentRegistry.applyRawDocumentPutMessage(cache, mutatedNoteMessage);
|
||||
const mutatedNote = cache.getRequired(documents.note.definition, note.documentId) as InteropNote;
|
||||
|
||||
const fireCommand: InteropFireCommand = {
|
||||
schemaVersion: INTEROP_FIRE_COMMAND_SCHEMA_VERSION,
|
||||
commandId: `${runtimeId}-fire`,
|
||||
characterId: remoteHello.runtimeId,
|
||||
weaponId: "interop-rifle",
|
||||
};
|
||||
const fireReceiptWait = waitForMessage(peer, isRawDocumentPutFor(INTEROP_FIRE_RECEIPT_SCHEMA_ID), timeoutMs);
|
||||
peer.send(documentRegistry.createRawDocumentPutMessage(
|
||||
documents.fireCommand,
|
||||
`${runtimeId}-fire-put`,
|
||||
fireCommand.commandId,
|
||||
fireCommand,
|
||||
));
|
||||
const fireReceiptMessage = await fireReceiptWait;
|
||||
const fireReceipt = await documentRegistry.applyRawDocumentPutMessage(cache, fireReceiptMessage) as InteropFireReceipt;
|
||||
|
||||
peer.close();
|
||||
|
||||
writeJsonLine({
|
||||
mode: "dial",
|
||||
runtimeId,
|
||||
targetHost,
|
||||
targetPort,
|
||||
remoteHello,
|
||||
hasInteropSchema,
|
||||
retrievedNote: note,
|
||||
mutatedNote,
|
||||
mutationReceipt,
|
||||
fireReceipt,
|
||||
});
|
||||
}
|
||||
|
||||
function waitForMessage<TMessage extends CultNetMessage>(
|
||||
peer: CultNetPeer,
|
||||
predicate: (message: CultNetMessage) => message is TMessage,
|
||||
timeoutMs: number,
|
||||
): Promise<TMessage> {
|
||||
return new Promise<TMessage>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error(`Timed out waiting for CultNet message after ${timeoutMs}ms.`));
|
||||
}, timeoutMs);
|
||||
|
||||
const onMessage = (message: CultNetMessage) => {
|
||||
if (!predicate(message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
cleanup();
|
||||
resolve(message);
|
||||
};
|
||||
|
||||
const onInvalid = (error: Error) => {
|
||||
cleanup();
|
||||
reject(error);
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timeout);
|
||||
peer.off("message", onMessage);
|
||||
peer.off("invalidMessage", onInvalid);
|
||||
};
|
||||
|
||||
peer.on("message", onMessage);
|
||||
peer.on("invalidMessage", onInvalid);
|
||||
});
|
||||
}
|
||||
|
||||
function isRawDocumentPutFor(schemaId: string): (message: CultNetMessage) => message is CultNetDocumentPutRawMessage {
|
||||
return (message: CultNetMessage): message is CultNetDocumentPutRawMessage =>
|
||||
message.schemaVersion === "cultnet.document_put_raw.v0" && message.document.schemaId === schemaId;
|
||||
}
|
||||
|
||||
function raise(message: string): never {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
function defineInteropDocuments(noteSchemaId: string): Record<string, CultNetDocumentBinding<AnyCultCacheDocumentDefinition>> {
|
||||
const note = defineDocumentType({
|
||||
type: INTEROP_DOCUMENT_TYPE,
|
||||
schemaId: noteSchemaId,
|
||||
schemaName: INTEROP_DOCUMENT_TYPE,
|
||||
schemaVersion: INTEROP_SCHEMA_VERSION,
|
||||
schema: interopNoteSchema,
|
||||
formatter: createInteropFormatter(),
|
||||
});
|
||||
const mutationIntent = defineDocumentType({
|
||||
type: INTEROP_MUTATION_INTENT_DOCUMENT_TYPE,
|
||||
schemaId: INTEROP_MUTATION_INTENT_SCHEMA_ID,
|
||||
schemaName: INTEROP_MUTATION_INTENT_DOCUMENT_TYPE,
|
||||
schemaVersion: INTEROP_MUTATION_INTENT_SCHEMA_VERSION,
|
||||
schema: interopMutationIntentSchema,
|
||||
formatter: createInteropMutationIntentFormatter(),
|
||||
});
|
||||
const mutationReceipt = defineDocumentType({
|
||||
type: INTEROP_MUTATION_RECEIPT_DOCUMENT_TYPE,
|
||||
schemaId: INTEROP_MUTATION_RECEIPT_SCHEMA_ID,
|
||||
schemaName: INTEROP_MUTATION_RECEIPT_DOCUMENT_TYPE,
|
||||
schemaVersion: INTEROP_MUTATION_RECEIPT_SCHEMA_VERSION,
|
||||
schema: interopMutationReceiptSchema,
|
||||
formatter: createInteropMutationReceiptFormatter(),
|
||||
});
|
||||
const fireCommand = defineDocumentType({
|
||||
type: INTEROP_FIRE_COMMAND_DOCUMENT_TYPE,
|
||||
schemaId: INTEROP_FIRE_COMMAND_SCHEMA_ID,
|
||||
schemaName: INTEROP_FIRE_COMMAND_DOCUMENT_TYPE,
|
||||
schemaVersion: INTEROP_FIRE_COMMAND_SCHEMA_VERSION,
|
||||
schema: interopFireCommandSchema,
|
||||
formatter: createInteropFireCommandFormatter(),
|
||||
});
|
||||
const fireReceipt = defineDocumentType({
|
||||
type: INTEROP_FIRE_RECEIPT_DOCUMENT_TYPE,
|
||||
schemaId: INTEROP_FIRE_RECEIPT_SCHEMA_ID,
|
||||
schemaName: INTEROP_FIRE_RECEIPT_DOCUMENT_TYPE,
|
||||
schemaVersion: INTEROP_FIRE_RECEIPT_SCHEMA_VERSION,
|
||||
schema: interopFireReceiptSchema,
|
||||
formatter: createInteropFireReceiptFormatter(),
|
||||
});
|
||||
|
||||
return {
|
||||
note: defineCultNetDocumentBinding({ definition: note, payloadSchemaVersion: INTEROP_SCHEMA_VERSION }),
|
||||
mutationIntent: defineCultNetDocumentBinding({ definition: mutationIntent, payloadSchemaVersion: INTEROP_MUTATION_INTENT_SCHEMA_VERSION }),
|
||||
mutationReceipt: defineCultNetDocumentBinding({ definition: mutationReceipt, payloadSchemaVersion: INTEROP_MUTATION_RECEIPT_SCHEMA_VERSION }),
|
||||
fireCommand: defineCultNetDocumentBinding({ definition: fireCommand, payloadSchemaVersion: INTEROP_FIRE_COMMAND_SCHEMA_VERSION }),
|
||||
fireReceipt: defineCultNetDocumentBinding({ definition: fireReceipt, payloadSchemaVersion: INTEROP_FIRE_RECEIPT_SCHEMA_VERSION }),
|
||||
};
|
||||
}
|
||||
|
||||
async function connectTo(host: string, port: number): Promise<TcpSocket> {
|
||||
return new Promise<TcpSocket>((resolve, reject) => {
|
||||
const socket = connectTcp(port, host);
|
||||
socket.once("connect", () => resolve(socket));
|
||||
socket.once("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
async function closeServer(server: Server): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForTermination(cleanup: () => Promise<void>): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
let closed = false;
|
||||
const finish = async (signal: NodeJS.Signals) => {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
closed = true;
|
||||
try {
|
||||
await cleanup();
|
||||
writeLog("shutdown", { signal });
|
||||
resolve();
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
process.once("SIGTERM", () => void finish("SIGTERM"));
|
||||
process.once("SIGINT", () => void finish("SIGINT"));
|
||||
});
|
||||
}
|
||||
|
||||
function writeJsonLine(value: unknown): void {
|
||||
process.stdout.write(`${JSON.stringify(value)}\n`);
|
||||
}
|
||||
|
||||
function writeLog(event: string, payload: Record<string, unknown>): void {
|
||||
process.stderr.write(`${JSON.stringify({ event, ...payload })}\n`);
|
||||
}
|
||||
|
||||
function runtimeStorePath(runtimeId: string): string {
|
||||
return join(tmpdir(), `cultnet-ts-interop-${runtimeId}.msgpack`);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
writeLog("fatal", { error: error instanceof Error ? error.stack ?? error.message : String(error) });
|
||||
process.exitCode = 1;
|
||||
});
|
||||
330
test/interop/cultnet-interop-shared.ts
Normal file
330
test/interop/cultnet-interop-shared.ts
Normal file
|
|
@ -0,0 +1,330 @@
|
|||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { decode, encode } from "@msgpack/msgpack";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
export const INTEROP_DOCUMENT_TYPE = "cultnet.interop-note";
|
||||
export const INTEROP_SCHEMA_VERSION = "cultnet.interop_note.v0";
|
||||
export const INTEROP_MUTATION_INTENT_DOCUMENT_TYPE = "cultnet.interop-note-mutation-intent";
|
||||
export const INTEROP_MUTATION_INTENT_SCHEMA_ID = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-note-mutation-intent.schema.json";
|
||||
export const INTEROP_MUTATION_INTENT_SCHEMA_VERSION = "cultnet.interop_note_mutation_intent.v0";
|
||||
export const INTEROP_MUTATION_RECEIPT_DOCUMENT_TYPE = "cultnet.interop-note-mutation-receipt";
|
||||
export const INTEROP_MUTATION_RECEIPT_SCHEMA_ID = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-note-mutation-receipt.schema.json";
|
||||
export const INTEROP_MUTATION_RECEIPT_SCHEMA_VERSION = "cultnet.interop_note_mutation_receipt.v0";
|
||||
export const INTEROP_FIRE_COMMAND_DOCUMENT_TYPE = "cultnet.interop-fire-weapon-command";
|
||||
export const INTEROP_FIRE_COMMAND_SCHEMA_ID = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-fire-weapon-command.schema.json";
|
||||
export const INTEROP_FIRE_COMMAND_SCHEMA_VERSION = "cultnet.interop_fire_weapon_command.v0";
|
||||
export const INTEROP_FIRE_RECEIPT_DOCUMENT_TYPE = "cultnet.interop-fire-weapon-receipt";
|
||||
export const INTEROP_FIRE_RECEIPT_SCHEMA_ID = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-fire-weapon-receipt.schema.json";
|
||||
export const INTEROP_FIRE_RECEIPT_SCHEMA_VERSION = "cultnet.interop_fire_weapon_receipt.v0";
|
||||
export const INTEROP_WIRE_CONTRACT = "cultnet.schema.v0" as const;
|
||||
export const DISCOVERY_PROBE_SCHEMA_VERSION = "cultnet.discovery_probe.v0";
|
||||
export const DISCOVERY_ANNOUNCE_SCHEMA_VERSION = "cultnet.discovery_announce.v0";
|
||||
|
||||
export const interopNoteSchema = z.object({
|
||||
schemaVersion: z.literal(INTEROP_SCHEMA_VERSION),
|
||||
documentId: z.string().min(1),
|
||||
authorRuntimeId: z.string().min(1),
|
||||
title: z.string().min(1),
|
||||
body: z.string().min(1),
|
||||
tags: z.array(z.string().min(1)),
|
||||
});
|
||||
|
||||
export type InteropNote = z.infer<typeof interopNoteSchema>;
|
||||
|
||||
export const interopMutationIntentSchema = z.object({
|
||||
schemaVersion: z.literal(INTEROP_MUTATION_INTENT_SCHEMA_VERSION),
|
||||
intentId: z.string().min(1),
|
||||
targetDocumentId: z.string().min(1),
|
||||
appendBody: z.string().min(1),
|
||||
appendTag: z.string().min(1),
|
||||
});
|
||||
|
||||
export type InteropMutationIntent = z.infer<typeof interopMutationIntentSchema>;
|
||||
|
||||
export const interopMutationReceiptSchema = z.object({
|
||||
schemaVersion: z.literal(INTEROP_MUTATION_RECEIPT_SCHEMA_VERSION),
|
||||
intentId: z.string().min(1),
|
||||
accepted: z.boolean(),
|
||||
documentId: z.string().min(1),
|
||||
body: z.string(),
|
||||
tags: z.array(z.string().min(1)),
|
||||
error: z.string().optional(),
|
||||
});
|
||||
|
||||
export type InteropMutationReceipt = z.infer<typeof interopMutationReceiptSchema>;
|
||||
|
||||
export const interopFireCommandSchema = z.object({
|
||||
schemaVersion: z.literal(INTEROP_FIRE_COMMAND_SCHEMA_VERSION),
|
||||
commandId: z.string().min(1),
|
||||
characterId: z.string().min(1),
|
||||
weaponId: z.string().min(1),
|
||||
});
|
||||
|
||||
export type InteropFireCommand = z.infer<typeof interopFireCommandSchema>;
|
||||
|
||||
export const interopFireReceiptSchema = z.object({
|
||||
schemaVersion: z.literal(INTEROP_FIRE_RECEIPT_SCHEMA_VERSION),
|
||||
commandId: z.string().min(1),
|
||||
accepted: z.boolean(),
|
||||
characterId: z.string().min(1),
|
||||
weaponId: z.string().min(1),
|
||||
shotsFired: z.number().int().nonnegative(),
|
||||
ammoRemaining: z.number().int().nonnegative(),
|
||||
error: z.string().optional(),
|
||||
});
|
||||
|
||||
export type InteropFireReceipt = z.infer<typeof interopFireReceiptSchema>;
|
||||
|
||||
export interface SlotFormatter<T> {
|
||||
encode(value: T): Uint8Array;
|
||||
decode(payload: Uint8Array): T;
|
||||
}
|
||||
|
||||
export function createInteropFormatter(): SlotFormatter<InteropNote> {
|
||||
return slotFormatter<InteropNote>("Interop note", 5, (value) => [
|
||||
value.schemaVersion,
|
||||
value.documentId,
|
||||
value.authorRuntimeId,
|
||||
value.title,
|
||||
value.body,
|
||||
value.tags,
|
||||
], ([schemaVersion, documentId, authorRuntimeId, title, body, tags]) => interopNoteSchema.parse({
|
||||
schemaVersion,
|
||||
documentId,
|
||||
authorRuntimeId,
|
||||
title,
|
||||
body,
|
||||
tags: Array.isArray(tags) ? tags : [],
|
||||
}));
|
||||
}
|
||||
|
||||
export function createInteropMutationIntentFormatter(): SlotFormatter<InteropMutationIntent> {
|
||||
return slotFormatter<InteropMutationIntent>("Interop mutation intent", 5, (value) => [
|
||||
value.schemaVersion,
|
||||
value.intentId,
|
||||
value.targetDocumentId,
|
||||
value.appendBody,
|
||||
value.appendTag,
|
||||
], ([schemaVersion, intentId, targetDocumentId, appendBody, appendTag]) => interopMutationIntentSchema.parse({
|
||||
schemaVersion,
|
||||
intentId,
|
||||
targetDocumentId,
|
||||
appendBody,
|
||||
appendTag,
|
||||
}));
|
||||
}
|
||||
|
||||
export function createInteropMutationReceiptFormatter(): SlotFormatter<InteropMutationReceipt> {
|
||||
return slotFormatter<InteropMutationReceipt>("Interop mutation receipt", 6, (value) => [
|
||||
value.schemaVersion,
|
||||
value.intentId,
|
||||
value.accepted,
|
||||
value.documentId,
|
||||
value.body,
|
||||
value.tags,
|
||||
value.error,
|
||||
], ([schemaVersion, intentId, accepted, documentId, body, tags, error]) => interopMutationReceiptSchema.parse({
|
||||
schemaVersion,
|
||||
intentId,
|
||||
accepted,
|
||||
documentId,
|
||||
body,
|
||||
tags: Array.isArray(tags) ? tags : [],
|
||||
error: typeof error === "string" ? error : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
export function createInteropFireCommandFormatter(): SlotFormatter<InteropFireCommand> {
|
||||
return slotFormatter<InteropFireCommand>("Interop fire command", 4, (value) => [
|
||||
value.schemaVersion,
|
||||
value.commandId,
|
||||
value.characterId,
|
||||
value.weaponId,
|
||||
], ([schemaVersion, commandId, characterId, weaponId]) => interopFireCommandSchema.parse({
|
||||
schemaVersion,
|
||||
commandId,
|
||||
characterId,
|
||||
weaponId,
|
||||
}));
|
||||
}
|
||||
|
||||
export function createInteropFireReceiptFormatter(): SlotFormatter<InteropFireReceipt> {
|
||||
return slotFormatter<InteropFireReceipt>("Interop fire receipt", 6, (value) => [
|
||||
value.schemaVersion,
|
||||
value.commandId,
|
||||
value.accepted,
|
||||
value.characterId,
|
||||
value.weaponId,
|
||||
value.shotsFired,
|
||||
value.ammoRemaining,
|
||||
value.error,
|
||||
], ([schemaVersion, commandId, accepted, characterId, weaponId, shotsFired, ammoRemaining, error]) => interopFireReceiptSchema.parse({
|
||||
schemaVersion,
|
||||
commandId,
|
||||
accepted,
|
||||
characterId,
|
||||
weaponId,
|
||||
shotsFired,
|
||||
ammoRemaining,
|
||||
error: typeof error === "string" ? error : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
function slotFormatter<T>(
|
||||
name: string,
|
||||
minimumSlots: number,
|
||||
encodeSlots: (value: T) => unknown[],
|
||||
decodeSlots: (slots: unknown[]) => T,
|
||||
): SlotFormatter<T> {
|
||||
return {
|
||||
encode(value: T): Uint8Array {
|
||||
return encode(encodeSlots(value));
|
||||
},
|
||||
decode(payload: Uint8Array): T {
|
||||
const decoded = decode(payload);
|
||||
if (!Array.isArray(decoded) || decoded.length < minimumSlots) {
|
||||
throw new Error(`${name} payload must be a MessagePack array with at least ${minimumSlots} slots.`);
|
||||
}
|
||||
|
||||
return decodeSlots(decoded);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createLegacyInteropNoteFormatter(): SlotFormatter<InteropNote> {
|
||||
return {
|
||||
encode(value: InteropNote): Uint8Array {
|
||||
return encode([
|
||||
value.schemaVersion,
|
||||
value.documentId,
|
||||
value.authorRuntimeId,
|
||||
value.title,
|
||||
value.body,
|
||||
]);
|
||||
},
|
||||
decode: createInteropFormatter().decode,
|
||||
};
|
||||
}
|
||||
|
||||
export function createMismatchedInteropNoteFormatter(): SlotFormatter<InteropNote> {
|
||||
return {
|
||||
encode(value: InteropNote): Uint8Array {
|
||||
return encode([
|
||||
value.schemaVersion,
|
||||
value.documentId,
|
||||
42,
|
||||
value.title,
|
||||
value.body,
|
||||
value.tags,
|
||||
]);
|
||||
},
|
||||
decode: createInteropFormatter().decode,
|
||||
};
|
||||
}
|
||||
|
||||
export const discoveryProbeSchema = z.object({
|
||||
schemaVersion: z.literal(DISCOVERY_PROBE_SCHEMA_VERSION),
|
||||
messageId: z.string().min(1),
|
||||
requesterRuntimeId: z.string().min(1),
|
||||
});
|
||||
|
||||
export type DiscoveryProbe = z.infer<typeof discoveryProbeSchema>;
|
||||
|
||||
export const discoveryAnnounceSchema = z.object({
|
||||
schemaVersion: z.literal(DISCOVERY_ANNOUNCE_SCHEMA_VERSION),
|
||||
messageId: z.string().min(1),
|
||||
runtimeId: z.string().min(1),
|
||||
runtimeKind: z.string().min(1),
|
||||
displayName: z.string().min(1),
|
||||
agentId: z.string().min(1).optional(),
|
||||
tcpHost: z.string().min(1),
|
||||
tcpPort: z.number().int().positive().max(65535),
|
||||
wireContract: z.literal(INTEROP_WIRE_CONTRACT),
|
||||
supportedDocumentTypes: z.array(z.string().min(1)),
|
||||
supportsSchemaCatalog: z.boolean(),
|
||||
});
|
||||
|
||||
export type DiscoveryAnnounce = z.infer<typeof discoveryAnnounceSchema>;
|
||||
|
||||
export interface LoadedSchemaRegistration {
|
||||
schemaId: string;
|
||||
title?: string;
|
||||
schemaJson: string;
|
||||
schema: object;
|
||||
}
|
||||
|
||||
export async function loadInteropSchemaRegistration(schemaPath: string): Promise<LoadedSchemaRegistration> {
|
||||
const schemaJson = await readFile(schemaPath, "utf8");
|
||||
const parsed = JSON.parse(schemaJson) as {
|
||||
$id?: string;
|
||||
title?: string;
|
||||
};
|
||||
|
||||
if (!parsed.$id) {
|
||||
throw new Error(`Interop schema at ${schemaPath} is missing $id.`);
|
||||
}
|
||||
|
||||
return {
|
||||
schemaId: parsed.$id,
|
||||
title: parsed.title,
|
||||
schemaJson,
|
||||
schema: JSON.parse(schemaJson) as object,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildInteropNote(runtimeId: string, displayName: string): InteropNote {
|
||||
return {
|
||||
schemaVersion: INTEROP_SCHEMA_VERSION,
|
||||
documentId: `note:${runtimeId}`,
|
||||
authorRuntimeId: runtimeId,
|
||||
title: `${displayName} keeps a little note`,
|
||||
body: `${runtimeId} can move CultNet state without begging the gods for translation.`,
|
||||
tags: [runtimeId, "interop", "cultnet"],
|
||||
};
|
||||
}
|
||||
|
||||
export function parseArgs(argv: readonly string[]): Map<string, string> {
|
||||
const args = new Map<string, string>();
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const token = argv[index];
|
||||
if (!token.startsWith("--")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = token.slice(2);
|
||||
const value = argv[index + 1];
|
||||
if (!value || value.startsWith("--")) {
|
||||
throw new Error(`Missing value for --${name}`);
|
||||
}
|
||||
|
||||
args.set(name, value);
|
||||
index += 1;
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
export function requireArg(args: Map<string, string>, name: string): string {
|
||||
const value = args.get(name);
|
||||
if (!value) {
|
||||
throw new Error(`Missing required argument --${name}`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export function optionalIntArg(args: Map<string, string>, name: string, fallback?: number): number | undefined {
|
||||
const raw = args.get(name);
|
||||
if (!raw) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(raw, 10);
|
||||
if (!Number.isInteger(parsed)) {
|
||||
throw new Error(`Argument --${name} must be an integer.`);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
336
test/interop/cultnet-interop.test.ts
Normal file
336
test/interop/cultnet-interop.test.ts
Normal file
|
|
@ -0,0 +1,336 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { execFile, spawn, type ChildProcessByStdio } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import { createServer } from "node:net";
|
||||
import { networkInterfaces } from "node:os";
|
||||
import { resolve } from "node:path";
|
||||
import type { Readable } from "node:stream";
|
||||
import { test } from "node:test";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
const cultNetTsRoot = resolve(__dirname, "../../..");
|
||||
const cultnetRsRoot = resolve(cultNetTsRoot, "..", "cultnet-rs");
|
||||
const cultLibRoot = resolve(cultNetTsRoot, "..", "CultLib");
|
||||
|
||||
const tsPeerScript = resolve(cultNetTsRoot, "dist-test", "test", "interop", "cultnet-interop-peer.js");
|
||||
const interopSchemaPath = resolve(cultNetTsRoot, "integration", "contracts", "cultnet.interop-note.schema.json");
|
||||
const csharpProjectPath = resolve(
|
||||
cultLibRoot,
|
||||
"tests",
|
||||
"GameCult.Networking.InteropPeer",
|
||||
"GameCult.Networking.InteropPeer.csproj",
|
||||
);
|
||||
const csharpDllPath = resolve(
|
||||
cultLibRoot,
|
||||
"bin",
|
||||
"GameCult.Networking.InteropPeer",
|
||||
"Debug",
|
||||
"net10.0",
|
||||
"GameCult.Networking.InteropPeer.dll",
|
||||
);
|
||||
const rustBinaryPath = resolve(
|
||||
cultnetRsRoot,
|
||||
"target",
|
||||
"debug",
|
||||
"examples",
|
||||
process.platform === "win32" ? "cultnet_interop_peer.exe" : "cultnet_interop_peer",
|
||||
);
|
||||
|
||||
const discoveryGroup = "239.77.44.11";
|
||||
|
||||
test("CultNet TS/Rust/C# peers discover each other and exchange raw state over the shared schema-v0 lane", async (t) => {
|
||||
await buildInteropPeers();
|
||||
|
||||
const discoveryPort = await getFreePort();
|
||||
const tsPort = await getFreePort();
|
||||
const rustPort = await getFreePort();
|
||||
const csharpPort = await getFreePort();
|
||||
const advertiseHost = findAdvertiseHost();
|
||||
|
||||
const servers: RunningServeProcess[] = [];
|
||||
servers.push(await spawnServeProcess("rust", {
|
||||
command: rustBinaryPath,
|
||||
args: [
|
||||
"serve",
|
||||
"--runtime-id", "rust-peer",
|
||||
"--runtime-kind", "rust",
|
||||
"--display-name", "Rust Peer",
|
||||
"--agent-id", "rust-agent",
|
||||
"--bind-host", "127.0.0.1",
|
||||
"--advertise-host", advertiseHost,
|
||||
"--tcp-port", String(rustPort),
|
||||
"--discovery-port", String(discoveryPort),
|
||||
"--discovery-group", discoveryGroup,
|
||||
"--schema-path", interopSchemaPath,
|
||||
],
|
||||
cwd: cultnetRsRoot,
|
||||
}));
|
||||
await servers[servers.length - 1].ready;
|
||||
|
||||
servers.push(await spawnServeProcess("ts", {
|
||||
command: process.execPath,
|
||||
args: [
|
||||
tsPeerScript,
|
||||
"serve",
|
||||
"--runtime-id", "ts-peer",
|
||||
"--runtime-kind", "node",
|
||||
"--display-name", "TypeScript Peer",
|
||||
"--agent-id", "ts-agent",
|
||||
"--bind-host", "127.0.0.1",
|
||||
"--advertise-host", advertiseHost,
|
||||
"--tcp-port", String(tsPort),
|
||||
"--discovery-port", String(discoveryPort),
|
||||
"--discovery-group", discoveryGroup,
|
||||
"--schema-path", interopSchemaPath,
|
||||
],
|
||||
cwd: cultNetTsRoot,
|
||||
}));
|
||||
await servers[servers.length - 1].ready;
|
||||
|
||||
servers.push(await spawnServeProcess("csharp", {
|
||||
command: "dotnet",
|
||||
args: [
|
||||
csharpDllPath,
|
||||
"serve",
|
||||
"--runtime-id", "csharp-peer",
|
||||
"--runtime-kind", "dotnet",
|
||||
"--display-name", "CSharp Peer",
|
||||
"--agent-id", "csharp-agent",
|
||||
"--bind-host", "127.0.0.1",
|
||||
"--advertise-host", advertiseHost,
|
||||
"--tcp-port", String(csharpPort),
|
||||
"--discovery-port", String(discoveryPort),
|
||||
"--discovery-group", discoveryGroup,
|
||||
"--schema-path", interopSchemaPath,
|
||||
],
|
||||
cwd: cultLibRoot,
|
||||
}));
|
||||
await servers[servers.length - 1].ready;
|
||||
|
||||
t.after(async () => {
|
||||
await Promise.all(servers.map(stopProcess));
|
||||
});
|
||||
|
||||
const tsDial = await runJsonCommand("ts-dial", process.execPath, [
|
||||
tsPeerScript,
|
||||
"dial",
|
||||
"--runtime-id", "ts-client",
|
||||
"--runtime-kind", "node",
|
||||
"--display-name", "TS Dialer",
|
||||
"--agent-id", "ts-client-agent",
|
||||
"--target-host", "127.0.0.1",
|
||||
"--target-port", String(rustPort),
|
||||
"--schema-path", interopSchemaPath,
|
||||
], cultNetTsRoot);
|
||||
assert.equal(tsDial.remoteHello.runtimeId, "rust-peer");
|
||||
assert.equal(tsDial.hasInteropSchema, true);
|
||||
assert.equal(tsDial.retrievedNote.authorRuntimeId, "rust-peer");
|
||||
assert.ok(tsDial.mutatedNote.tags.includes("decorated:ts-client"));
|
||||
assert.equal(tsDial.mutationReceipt.accepted, true);
|
||||
assert.equal(tsDial.fireReceipt.shotsFired, 1);
|
||||
|
||||
const rustDial = await runJsonCommand("rust-dial", rustBinaryPath, [
|
||||
"dial",
|
||||
"--runtime-id", "rust-client",
|
||||
"--runtime-kind", "rust",
|
||||
"--display-name", "Rust Dialer",
|
||||
"--agent-id", "rust-client-agent",
|
||||
"--target-host", "127.0.0.1",
|
||||
"--target-port", String(csharpPort),
|
||||
"--schema-path", interopSchemaPath,
|
||||
], cultnetRsRoot);
|
||||
assert.equal(rustDial.remoteHello.runtimeId, "csharp-peer");
|
||||
assert.equal(rustDial.hasInteropSchema, true);
|
||||
assert.equal(rustDial.retrievedNote.authorRuntimeId, "csharp-peer");
|
||||
assert.ok(rustDial.mutatedNote.tags.includes("decorated:rust-client"));
|
||||
assert.equal(rustDial.fireReceipt.ammoRemaining, 29);
|
||||
|
||||
const csharpDial = await runJsonCommand("csharp-dial", "dotnet", [
|
||||
csharpDllPath,
|
||||
"dial",
|
||||
"--runtime-id", "csharp-client",
|
||||
"--runtime-kind", "dotnet",
|
||||
"--display-name", "CSharp Dialer",
|
||||
"--agent-id", "csharp-client-agent",
|
||||
"--target-host", "127.0.0.1",
|
||||
"--target-port", String(tsPort),
|
||||
"--schema-path", interopSchemaPath,
|
||||
], cultLibRoot);
|
||||
assert.equal(csharpDial.remoteHello.runtimeId, "ts-peer");
|
||||
assert.equal(csharpDial.hasInteropSchema, true);
|
||||
assert.equal(csharpDial.retrievedNote.authorRuntimeId, "ts-peer");
|
||||
assert.ok(csharpDial.mutatedNote.tags.includes("decorated:csharp-client"));
|
||||
assert.equal(csharpDial.fireReceipt.accepted, true);
|
||||
|
||||
const expectedPeers = ["csharp-peer", "rust-peer", "ts-peer"];
|
||||
|
||||
const tsProbe = await runJsonCommand("ts-probe", process.execPath, [
|
||||
tsPeerScript,
|
||||
"probe",
|
||||
"--runtime-id", "ts-prober",
|
||||
"--discovery-port", String(discoveryPort),
|
||||
"--discovery-group", discoveryGroup,
|
||||
"--timeout-ms", "1500",
|
||||
], cultNetTsRoot);
|
||||
assert.deepEqual(tsProbe.peers.map((peer: { runtimeId: string }) => peer.runtimeId).sort(), expectedPeers);
|
||||
|
||||
const rustProbe = await runJsonCommand("rust-probe", rustBinaryPath, [
|
||||
"probe",
|
||||
"--runtime-id", "rust-prober",
|
||||
"--discovery-port", String(discoveryPort),
|
||||
"--discovery-group", discoveryGroup,
|
||||
"--timeout-ms", "1500",
|
||||
], cultnetRsRoot);
|
||||
assert.deepEqual(rustProbe.peers.map((peer: { runtimeId: string }) => peer.runtimeId).sort(), expectedPeers);
|
||||
|
||||
const csharpProbe = await runJsonCommand("csharp-probe", "dotnet", [
|
||||
csharpDllPath,
|
||||
"probe",
|
||||
"--runtime-id", "csharp-prober",
|
||||
"--discovery-port", String(discoveryPort),
|
||||
"--discovery-group", discoveryGroup,
|
||||
"--timeout-ms", "1500",
|
||||
], cultLibRoot);
|
||||
assert.deepEqual(csharpProbe.peers.map((peer: { runtimeId: string }) => peer.runtimeId).sort(), expectedPeers);
|
||||
});
|
||||
|
||||
async function buildInteropPeers(): Promise<void> {
|
||||
await execFileAsync("cargo", ["build", "--quiet", "--example", "cultnet_interop_peer"], {
|
||||
cwd: cultnetRsRoot,
|
||||
});
|
||||
await execFileAsync("dotnet", ["build", csharpProjectPath, "-nologo"], {
|
||||
cwd: cultLibRoot,
|
||||
});
|
||||
}
|
||||
|
||||
interface ServeCommand {
|
||||
command: string;
|
||||
args: string[];
|
||||
cwd: string;
|
||||
}
|
||||
|
||||
interface RunningServeProcess {
|
||||
name: string;
|
||||
child: ChildProcessByStdio<null, Readable, Readable>;
|
||||
ready: Promise<unknown>;
|
||||
stderr: string[];
|
||||
}
|
||||
|
||||
async function spawnServeProcess(name: string, command: ServeCommand): Promise<RunningServeProcess> {
|
||||
const child = spawn(command.command, command.args, {
|
||||
cwd: command.cwd,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const stderr: string[] = [];
|
||||
let stdoutBuffer = "";
|
||||
|
||||
const ready = new Promise<unknown>((resolve, reject) => {
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => {
|
||||
stdoutBuffer += chunk;
|
||||
while (true) {
|
||||
const newline = stdoutBuffer.indexOf("\n");
|
||||
if (newline === -1) {
|
||||
break;
|
||||
}
|
||||
|
||||
const line = stdoutBuffer.slice(0, newline).trim();
|
||||
stdoutBuffer = stdoutBuffer.slice(newline + 1);
|
||||
if (!line) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(line) as { status?: string };
|
||||
if (parsed.status === "ready") {
|
||||
resolve(parsed);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
reject(new Error(`${name} emitted non-JSON stdout while starting: ${line}`));
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stderr.on("data", (chunk: string) => {
|
||||
stderr.push(chunk);
|
||||
});
|
||||
|
||||
child.once("exit", (code, signal) => {
|
||||
reject(new Error(`${name} serve process exited before becoming ready (code=${code}, signal=${signal}).\n${stderr.join("")}`));
|
||||
});
|
||||
child.once("error", reject);
|
||||
});
|
||||
|
||||
return { name, child, ready, stderr };
|
||||
}
|
||||
|
||||
async function runJsonCommand(
|
||||
name: string,
|
||||
command: string,
|
||||
args: string[],
|
||||
cwd: string,
|
||||
): Promise<any> {
|
||||
const { stdout, stderr } = await execFileAsync(command, args, { cwd, timeout: 30_000 });
|
||||
const trimmed = stdout.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error(`${name} produced no stdout.\n${stderr}`);
|
||||
}
|
||||
|
||||
const lines = trimmed.split(/\r?\n/).filter(Boolean);
|
||||
try {
|
||||
return JSON.parse(lines.at(-1) as string);
|
||||
} catch (error) {
|
||||
throw new Error(`${name} did not end with JSON stdout.\nstdout:\n${stdout}\nstderr:\n${stderr}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function stopProcess(processState: RunningServeProcess): Promise<void> {
|
||||
if (processState.child.killed || processState.child.exitCode !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
processState.child.kill("SIGTERM");
|
||||
await once(processState.child, "exit");
|
||||
}
|
||||
|
||||
async function getFreePort(): Promise<number> {
|
||||
const server = createServer();
|
||||
server.listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
throw new Error("Failed to allocate an ephemeral port.");
|
||||
}
|
||||
|
||||
const { port } = address;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
function findAdvertiseHost(): string {
|
||||
const interfaces = networkInterfaces();
|
||||
for (const entries of Object.values(interfaces)) {
|
||||
for (const entry of entries ?? []) {
|
||||
if (entry.family === "IPv4" && !entry.internal) {
|
||||
return entry.address;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "127.0.0.1";
|
||||
}
|
||||
84
tools/generate-swarm-contracts.mjs
Normal file
84
tools/generate-swarm-contracts.mjs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { compile } from "json-schema-to-typescript";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const repoRoot = path.resolve(__dirname, "..");
|
||||
const manifestPath = path.join(repoRoot, "contracts", "swarm-contracts.manifest.json");
|
||||
const outputPath = path.join(repoRoot, "src", "generated", "swarm-contracts.generated.ts");
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* schemaPath: string;
|
||||
* typeName: string;
|
||||
* contractExportName: string;
|
||||
* validateExportName: string;
|
||||
* parseExportName: string;
|
||||
* }} ContractManifestEntry
|
||||
*/
|
||||
|
||||
/** @type {{ contracts: ContractManifestEntry[] }} */
|
||||
const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
|
||||
|
||||
const importLines = [
|
||||
'import { defineJsonSchemaContract } from "../json-schema-contract";',
|
||||
];
|
||||
const sections = [
|
||||
"// Generated by tools/generate-swarm-contracts.mjs. Do not hand-edit this file unless you enjoy losing arguments with a machine.",
|
||||
];
|
||||
|
||||
for (const entry of manifest.contracts) {
|
||||
const absoluteSchemaPath = path.resolve(path.dirname(manifestPath), entry.schemaPath);
|
||||
const schema = JSON.parse(await readFile(absoluteSchemaPath, "utf8"));
|
||||
const schemaForTypes = structuredClone(schema);
|
||||
delete schemaForTypes.title;
|
||||
const schemaImportName = toIdentifier(`${entry.contractExportName}Schema`);
|
||||
const relativeImportPath = path.relative(path.dirname(outputPath), absoluteSchemaPath).replace(/\\/g, "/");
|
||||
importLines.push(`import ${schemaImportName} from "${ensureRelativeModule(relativeImportPath)}";`);
|
||||
|
||||
const rawTypeSource = await compile(schemaForTypes, entry.typeName, {
|
||||
bannerComment: "",
|
||||
style: {
|
||||
singleQuote: true,
|
||||
semi: true,
|
||||
},
|
||||
});
|
||||
const typeSource = rewriteRootTypeName(rawTypeSource, entry.typeName);
|
||||
|
||||
sections.push(typeSource.trim());
|
||||
sections.push(`
|
||||
export const ${entry.contractExportName} = defineJsonSchemaContract<${entry.typeName}>({
|
||||
schemaId: ${JSON.stringify(schema.$id ?? entry.typeName)},
|
||||
schema: ${schemaImportName},
|
||||
});
|
||||
|
||||
export function ${entry.validateExportName}(value: unknown): value is ${entry.typeName} {
|
||||
return ${entry.contractExportName}.validate(value);
|
||||
}
|
||||
|
||||
export function ${entry.parseExportName}(value: unknown): ${entry.typeName} {
|
||||
return ${entry.contractExportName}.parse(value);
|
||||
}`.trim());
|
||||
}
|
||||
|
||||
const output = `${importLines.join("\n")}\n\n${sections.join("\n\n")}\n`;
|
||||
await mkdir(path.dirname(outputPath), { recursive: true });
|
||||
await writeFile(outputPath, output, "utf8");
|
||||
|
||||
function ensureRelativeModule(value) {
|
||||
return value.startsWith(".") ? value : `./${value}`;
|
||||
}
|
||||
|
||||
function toIdentifier(value) {
|
||||
return value.replace(/[^a-zA-Z0-9_$]/g, "_");
|
||||
}
|
||||
|
||||
function rewriteRootTypeName(typeSource, desiredTypeName) {
|
||||
return typeSource.replace(
|
||||
/export\s+(interface|type)\s+([A-Za-z0-9_$]+)/u,
|
||||
(_match, kind) => `export ${kind} ${desiredTypeName}`,
|
||||
);
|
||||
}
|
||||
20
tsconfig.json
Normal file
20
tsconfig.json
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "CommonJS",
|
||||
"moduleResolution": "Node",
|
||||
"resolveJsonModule": true,
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
]
|
||||
}
|
||||
13
tsconfig.test.json
Normal file
13
tsconfig.test.json
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"outDir": "dist-test",
|
||||
"declaration": false,
|
||||
"declarationMap": false
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.ts",
|
||||
"test/**/*.ts"
|
||||
]
|
||||
}
|
||||
Loading…
Reference in a new issue