2026-06-11 21:07:48 +01:00
#!/usr/bin/env node
import Module from "node:module" ;
2026-06-23 22:54:54 +01:00
import { existsSync , readFileSync , readdirSync , statSync } from "node:fs" ;
2026-06-11 21:07:48 +01:00
import { mkdir , readdir , rm , writeFile } from "node:fs/promises" ;
import { basename , delimiter , dirname , extname , resolve } from "node:path" ;
import { fileURLToPath } from "node:url" ;
const repoRoot = resolve ( dirname ( fileURLToPath ( import . meta . url ) ) , ".." ) ;
2026-06-16 05:18:26 +01:00
configureCultLibModulePath ( ) ;
const require = Module . createRequire ( import . meta . url ) ;
const {
createIdunnRudpHealthPublisher ,
publishIdunnRudpHealth ,
} = require ( "./idunn-rudp-health.cjs" ) ;
2026-06-23 22:54:54 +01:00
const {
CULTNET _RUDP _PROTOCOL _ID ,
WEKSA _MIMO _VOICEDESIGN _COMMAND _SCHEMA _ID ,
createWeksaRudpCommandServer ,
sendWeksaMimoVoiceDesignCommand ,
formatRudpEndpoint ,
} = require ( "./weksa-rudp-command.cjs" ) ;
2026-06-11 21:07:48 +01:00
const options = parseArgs ( process . argv . slice ( 2 ) ) ;
const port = Number ( options . port ? ? process . env . WEKSA _DAEMON _PORT ? ? 8813 ) ;
const host = options . host ? ? process . env . WEKSA _DAEMON _HOST ? ? "127.0.0.1" ;
const stateRoot = resolve ( repoRoot , options . stateRoot ? ? process . env . WEKSA _STATE _ROOT ? ? ".weksa" ) ;
const cultMeshStorePath = resolve ( stateRoot , "provider-advertisement-store.cc" ) ;
const pidPath = resolve ( stateRoot , "weksa-daemon.pid" ) ;
const logPath = resolve ( stateRoot , "weksa-daemon.log" ) ;
const mimoApiKeyPath = options . mimoApiKeyPath ? ? process . env . WEKSA _MIMO _API _KEY _FILE ? ? "E:/Projects/gamecult-ops/mimo-api-Weksa.txt" ;
2026-06-16 05:18:26 +01:00
const idunnHealthPublisher = createIdunnRudpHealthPublisher ( {
endpoint : options . idunnRudpHealth ? ? process . env . WEKSA _IDUNN _RUDP _HEALTH ,
daemonId : options . idunnDaemon ? ? process . env . WEKSA _IDUNN _DAEMON ? ? "weksa" ,
healthContract : options . idunnHealthContract ? ? process . env . WEKSA _IDUNN _HEALTH _CONTRACT ? ? "weksa.cultnet-rudp-provider-health" ,
} ) ;
2026-06-23 22:54:54 +01:00
const odinCultMeshRudp = options . odinCultMeshRudp ? ? process . env . WEKSA _ODIN _CULTMESH _RUDP ;
2026-06-11 21:07:48 +01:00
const startedAt = new Date ( ) . toISOString ( ) ;
let tick = 0 ;
let lastPublishedAt = "" ;
let lastError = undefined ;
let cachedSnapshot = undefined ;
2026-06-16 05:18:26 +01:00
let witnessRefreshRunning = false ;
let lastRudpHealthSuccessMs = 0 ;
2026-06-11 21:07:48 +01:00
if ( options . health ) {
await runHealthCheck ( ) ;
process . exit ( 0 ) ;
}
2026-06-23 22:54:54 +01:00
if ( options . mimoCommandJson ) {
const command = JSON . parse ( readFileSync ( resolve ( repoRoot , options . mimoCommandJson ) , "utf8" ) ) ;
const receipt = await sendWeksaMimoVoiceDesignCommand ( {
endpoint : formatRudpEndpoint ( host , port ) ,
command ,
runtimeId : "weksa-cli" ,
localHost : host . includes ( ":" ) ? "::" : "0.0.0.0" ,
} ) ;
process . stdout . write ( ` ${ JSON . stringify ( receipt , null , 2 ) } \n ` ) ;
process . exit ( 0 ) ;
}
2026-06-11 21:07:48 +01:00
await mkdir ( stateRoot , { recursive : true } ) ;
await writeFile ( pidPath , ` ${ process . pid } \n ` , "ascii" ) ;
await appendLog ( ` started pid= ${ process . pid } host= ${ host } port= ${ port } ` ) ;
2026-06-23 22:54:54 +01:00
const startupSnapshot = await refreshWitnesses ( "startup" ) ;
await publishOdinStartupRespect ( startupSnapshot ) ;
const commandServer = await createWeksaRudpCommandServer ( {
host ,
port ,
runtimeId : "weksa-daemon" ,
onCommand : async ( command ) => {
const receipt = await handleMimoVoiceDesign ( command ) ;
await refreshWitnesses ( "mimo-voicedesign-command" ) ;
return receipt ;
} ,
onError : async ( error ) => {
2026-06-11 21:07:48 +01:00
lastError = String ( error ? . stack ? ? error ) ;
2026-06-23 22:54:54 +01:00
await appendLog ( ` rudp command error: ${ lastError } ` ) ;
} ,
2026-06-11 21:07:48 +01:00
} ) ;
2026-06-23 22:54:54 +01:00
await appendLog ( ` listening ${ commandServer . uri } ` ) ;
2026-06-11 21:07:48 +01:00
const interval = setInterval ( ( ) => {
2026-06-16 05:18:26 +01:00
refreshWitnesses ( "interval" ) . catch ( async ( error ) => {
2026-06-11 21:07:48 +01:00
lastError = String ( error ? . stack ? ? error ) ;
await appendLog ( ` publish error: ${ lastError } ` ) ;
2026-06-16 05:18:26 +01:00
await publishWeksaRudpHealth ( "failed" , ` Weksa witness refresh failed: ${ String ( error ? . message ? ? error ) } ` ) ;
2026-06-11 21:07:48 +01:00
} ) ;
} , 30_000 ) ;
process . on ( "SIGINT" , ( ) => shutdown ( 0 ) ) ;
process . on ( "SIGTERM" , ( ) => shutdown ( 0 ) ) ;
async function shutdown ( code ) {
clearInterval ( interval ) ;
await appendLog ( ` stopping pid= ${ process . pid } ` ) ;
2026-06-23 22:54:54 +01:00
commandServer . close ( ) ;
process . exit ( code ) ;
2026-06-11 21:07:48 +01:00
}
async function runHealthCheck ( ) {
2026-06-23 22:54:54 +01:00
const operatorStatePath = resolve ( stateRoot , "operator-state.cc" ) ;
const commandBoundaryPath = resolve ( stateRoot , "command-boundary.cc" ) ;
const transportProfilePath = resolve ( stateRoot , "transport-profile.cc" ) ;
if ( ! existsSync ( pidPath ) ) {
throw new Error ( ` Weksa daemon PID file is missing: ${ pidPath } ` ) ;
}
if ( ! existsSync ( operatorStatePath ) ) {
throw new Error ( ` Weksa operator-state witness is missing: ${ operatorStatePath } ` ) ;
}
if ( ! existsSync ( commandBoundaryPath ) ) {
throw new Error ( ` Weksa command-boundary witness is missing: ${ commandBoundaryPath } ` ) ;
}
if ( ! existsSync ( transportProfilePath ) ) {
throw new Error ( ` Weksa transport-profile witness is missing: ${ transportProfilePath } ` ) ;
}
const pidText = readFileSync ( pidPath , "utf8" ) . trim ( ) ;
if ( ! /^\d+$/ . test ( pidText ) ) {
throw new Error ( ` Weksa daemon PID file is invalid: ${ pidText } ` ) ;
}
const pid = Number ( pidText ) ;
try {
process . kill ( pid , 0 ) ;
} catch {
throw new Error ( ` Weksa daemon PID ${ pid } is not running. ` ) ;
}
const operatorStateText = readFileSync ( operatorStatePath , "utf8" ) ;
const commandBoundaryText = readFileSync ( commandBoundaryPath , "utf8" ) ;
const transportProfileText = readFileSync ( transportProfilePath , "utf8" ) ;
const ages = [ operatorStatePath , commandBoundaryPath , transportProfilePath ]
. map ( ( path ) => Math . floor ( ( Date . now ( ) - statSync ( path ) . mtimeMs ) / 1000 ) ) ;
const ageSeconds = Math . max ( ... ages ) ;
if ( ageSeconds > 180 ) {
throw new Error ( ` Weksa daemon witnesses are stale ( ${ ageSeconds } s old at oldest required path). ` ) ;
}
if ( ! operatorStateText . includes ( "command_ingress: cultnet_rudp_document_mimo_voicedesign" ) ) {
throw new Error ( "Weksa operator-state witness does not report RUDP command ingress." ) ;
}
if ( ! commandBoundaryText . includes ( ` ingress: ${ CULTNET _RUDP _PROTOCOL _ID } ` ) ) {
throw new Error ( "Weksa command-boundary witness does not report CultNet/RUDP ingress." ) ;
}
if ( ! commandBoundaryText . includes ( ` input_schema: ${ WEKSA _MIMO _VOICEDESIGN _COMMAND _SCHEMA _ID } ` ) ) {
throw new Error ( "Weksa command-boundary witness does not report the MiMo command document schema." ) ;
}
if ( ! transportProfileText . includes ( ` command_transport: ${ CULTNET _RUDP _PROTOCOL _ID } ` ) ) {
throw new Error ( "Weksa transport-profile witness does not report CultNet/RUDP command transport." ) ;
}
process . stdout . write ( ` ${ JSON . stringify ( {
ok : true ,
service : "weksa.intent.service" ,
state : "healthy" ,
pid ,
ageSeconds ,
commandEndpoint : formatRudpEndpoint ( host , port ) ,
} , null , 2 ) } \ n ` );
2026-06-11 21:07:48 +01:00
}
async function publishWitnesses ( ) {
const snapshot = await buildSnapshot ( ) ;
await writeWitness ( "provider-advertisement.cc" , snapshot . providerAdvertisement ) ;
await writeWitness ( "operator-state.cc" , snapshot . operatorState ) ;
2026-06-16 11:30:32 +01:00
await writeWitness ( "command-boundary.cc" , snapshot . commandBoundary ) ;
await writeWitness ( "transport-profile.cc" , snapshot . transportProfile ) ;
2026-06-11 21:07:48 +01:00
await writeWitness ( "cultmesh-publications.cc" , snapshot . cultMeshPublications ) ;
await writeCultMeshStore ( snapshot ) ;
await writeJson ( resolve ( stateRoot , "provider-advertisement.json" ) , snapshot . providerAdvertisement ) ;
await writeJson ( resolve ( stateRoot , "operator-state.json" ) , snapshot . operatorState ) ;
2026-06-16 11:30:32 +01:00
await writeJson ( resolve ( stateRoot , "command-boundary.json" ) , snapshot . commandBoundary ) ;
await writeJson ( resolve ( stateRoot , "transport-profile.json" ) , snapshot . transportProfile ) ;
2026-06-11 21:07:48 +01:00
await writeJson ( resolve ( stateRoot , "cultmesh-publications.json" ) , snapshot . cultMeshPublications ) ;
cachedSnapshot = snapshot ;
lastPublishedAt = snapshot . operatorState . updated _at ;
tick += 1 ;
2026-06-16 05:18:26 +01:00
return snapshot ;
2026-06-11 21:07:48 +01:00
}
2026-06-16 05:18:26 +01:00
async function refreshWitnesses ( reason ) {
if ( witnessRefreshRunning ) {
await appendLog ( ` skipped overlapping witness refresh reason= ${ reason } ` ) ;
return cachedSnapshot ;
}
witnessRefreshRunning = true ;
try {
const snapshot = await publishWitnesses ( ) ;
await publishWeksaRudpHealth (
"healthy" ,
` Weksa refreshed witnesses reason= ${ reason } tick= ${ tick } provider= ${ snapshot . providerAdvertisement . providerId } ` ,
snapshot . operatorState . updated _at ,
) ;
return snapshot ;
} finally {
witnessRefreshRunning = false ;
}
}
async function publishWeksaRudpHealth ( state , detail , observedAt = new Date ( ) . toISOString ( ) ) {
if ( ! idunnHealthPublisher ) return ;
try {
await publishIdunnRudpHealth ( idunnHealthPublisher , { state , detail , observedAt } ) ;
lastRudpHealthSuccessMs = Date . now ( ) ;
} catch ( error ) {
const hasRecentSuccess = lastRudpHealthSuccessMs > 0 && Date . now ( ) - lastRudpHealthSuccessMs < 300_000 ;
if ( ! hasRecentSuccess ) {
await appendLog ( ` Idunn RUDP health publish failed: ${ String ( error ? . message ? ? error ) } ` ) ;
}
}
}
2026-06-23 22:54:54 +01:00
async function publishOdinStartupRespect ( snapshot ) {
if ( ! odinCultMeshRudp || ! snapshot ? . providerAdvertisement ) return ;
const runtime = loadCultRuntime ( ) ;
if ( runtime . error ) {
await appendLog ( ` Odin startup respect skipped: ${ runtime . error . message } ` ) ;
return ;
}
try {
const { providerAdvertisementDefinition } = defineCultMeshDocuments ( runtime . defineDocumentType ) ;
await runtime . CultMesh . publishRudpDocumentOnce (
idunnHealthPublisher ? . daemonId ? ? "weksa" ,
0x0d1d0002 ,
normalizeRudpEndpoint ( odinCultMeshRudp ) ,
runtime . defineCultNetDocumentBinding ( { definition : providerAdvertisementDefinition } ) ,
snapshot . providerAdvertisement . providerId ,
snapshot . providerAdvertisement ,
{
sourceRole : "weksa.provider" ,
tags : [ "startup-respect" , "odin-verse-discovery" ] ,
} ,
) ;
await appendLog ( ` Odin startup respect published to ${ odinCultMeshRudp } ` ) ;
} catch ( error ) {
await appendLog ( ` Odin startup respect failed: ${ String ( error ? . message ? ? error ) } ` ) ;
}
}
2026-06-11 21:07:48 +01:00
async function buildSnapshot ( ) {
const updatedAt = new Date ( ) . toISOString ( ) ;
const providerAdvertisement = loadProviderAdvertisement ( updatedAt ) ;
const tuning = loadLatestAffectTuning ( ) ;
const cultureCatalog = await inspectCultureCatalog ( ) ;
const operatorState = {
schema : "weksa.operator_state.v0" ,
service _id : "weksa.intent.service" ,
provider _id : providerAdvertisement . providerId ,
verse _id : "asgard.starfire.weksa" ,
state : "healthy" ,
mode : "daemon" ,
pid : process . pid ,
host ,
port ,
started _at : startedAt ,
updated _at : updatedAt ,
last _error : lastError ,
witnesses : {
provider _advertisement : ".weksa/provider-advertisement.cc" ,
provider _advertisement _store : ".weksa/provider-advertisement-store.cc" ,
operator _state : ".weksa/operator-state.cc" ,
cultmesh _publications : ".weksa/cultmesh-publications.cc" ,
} ,
readiness : {
affect _aware _lowering : tuning ? "tuned" : "no_tuning_artifact_seen" ,
cultural _ontology _profiles : cultureCatalog . profile _count ,
target _language _profiles : cultureCatalog . target _language _profile _count ,
accepts _commands : true ,
2026-06-23 22:54:54 +01:00
command _ingress : "cultnet_rudp_document_mimo_voicedesign" ,
2026-06-11 21:07:48 +01:00
mimo _voicedesign : existsSync ( mimoApiKeyPath ) ? "api_key_file_seen" : "missing_api_key_file" ,
} ,
latest _affect _tuning : tuning ,
} ;
2026-06-16 11:30:32 +01:00
const commandBoundary = buildCommandBoundary ( updatedAt ) ;
const transportProfile = buildTransportProfile ( updatedAt ) ;
2026-06-11 21:07:48 +01:00
const cultMeshPublications = {
schema : "weksa.cultmesh_publications.v0" ,
service _id : "weksa.intent.service" ,
updated _at : updatedAt ,
transport : {
cultmesh _store : ".weksa/provider-advertisement-store.cc" ,
2026-06-23 22:54:54 +01:00
native _cultnet _peer : formatRudpEndpoint ( host , port ) ,
2026-06-16 05:18:26 +01:00
idunn _rudp _health : idunnHealthPublisher ? ` ${ idunnHealthPublisher . endpoint . host } : ${ idunnHealthPublisher . endpoint . port } ` : "unconfigured" ,
2026-06-11 21:07:48 +01:00
} ,
publications : [
2026-06-23 22:54:54 +01:00
publication ( "weksa.service/provider-advertisement" , "gamecult.eve.provider_advertisement.v1" , ".weksa/provider-advertisement-store.cc" , ".weksa/provider-advertisement-store.cc" ) ,
publication ( "weksa.operator/status" , "weksa.operator_state.v0" , ".weksa/operator-state.cc" , ".weksa/operator-state.cc" ) ,
2026-06-16 11:30:32 +01:00
publication ( "weksa.command-boundary" , "weksa.command_boundary.v1" , ".weksa/command-boundary.cc" , null ) ,
publication ( "weksa.transport-profile" , "weksa.transport_profile.v1" , ".weksa/transport-profile.cc" , null ) ,
2026-06-23 22:54:54 +01:00
publication ( "weksa.cultmesh/publications" , "weksa.cultmesh_publications.v0" , ".weksa/cultmesh-publications.cc" , ".weksa/cultmesh-publications.cc" ) ,
publication ( "weksa.speech-provider/mimo/voicedesign" , WEKSA _MIMO _VOICEDESIGN _COMMAND _SCHEMA _ID , ".weksa/speech-provider/mimo/{requestId}/command.cc" , formatRudpEndpoint ( host , port ) ) ,
2026-06-11 21:07:48 +01:00
] ,
} ;
2026-10-22 20:13:36 +02:00
return { providerAdvertisement , operatorState , commandBoundary , transportProfile , cultMeshPublications } ;
2026-06-11 21:07:48 +01:00
}
async function writeCultMeshStore ( snapshot ) {
const runtime = loadCultRuntime ( ) ;
if ( runtime . error ) {
await appendLog ( ` CultMesh store write skipped: ${ runtime . error . message } ` ) ;
return ;
}
2026-06-16 11:30:32 +01:00
const {
providerAdvertisementDefinition ,
operatorStateDefinition ,
commandBoundaryDefinition ,
transportProfileDefinition ,
} = defineCultMeshDocuments ( runtime . defineDocumentType ) ;
const documents = [
providerAdvertisementDefinition ,
operatorStateDefinition ,
commandBoundaryDefinition ,
transportProfileDefinition ,
] ;
2026-06-11 21:07:48 +01:00
await rm ( cultMeshStorePath , { force : true } ) ;
const node = await createCultMeshNodeWithOwnedStoreReset ( runtime . CultMesh , cultMeshStorePath , documents ) ;
await node . put ( providerAdvertisementDefinition , snapshot . providerAdvertisement . providerId , snapshot . providerAdvertisement ) ;
2026-06-16 11:30:32 +01:00
await node . put ( operatorStateDefinition , "weksa" , snapshot . operatorState ) ;
await node . put ( commandBoundaryDefinition , "weksa" , snapshot . commandBoundary ) ;
await node . put ( transportProfileDefinition , "weksa" , snapshot . transportProfile ) ;
2026-06-11 21:07:48 +01:00
await node . flush ? . ( true ) ;
}
async function createCultMeshNodeWithOwnedStoreReset ( CultMesh , storePath , documents ) {
try {
return await CultMesh . createNode ( storePath , { documents } ) ;
} catch ( error ) {
await appendLog ( ` CultMesh store reset after decode failure: ${ error . message } ` ) ;
await rm ( storePath , { force : true } ) ;
return await CultMesh . createNode ( storePath , { documents } ) ;
}
}
function loadCultRuntime ( ) {
try {
2026-06-16 05:18:26 +01:00
configureCultLibModulePath ( ) ;
2026-06-11 21:07:48 +01:00
const { CultMesh } = require ( "cultmesh-ts" ) ;
const { defineDocumentType } = require ( "cultcache-ts" ) ;
2026-06-23 22:54:54 +01:00
const { defineCultNetDocumentBinding } = require ( "cultnet-ts" ) ;
return { CultMesh , defineDocumentType , defineCultNetDocumentBinding , error : null } ;
2026-06-11 21:07:48 +01:00
} catch ( error ) {
2026-06-23 22:54:54 +01:00
return { CultMesh : null , defineDocumentType : null , defineCultNetDocumentBinding : null , error } ;
}
}
function normalizeRudpEndpoint ( endpoint ) {
const text = String ( endpoint || "" ) . trim ( ) ;
if ( ! text ) {
throw new Error ( "Odin CultMesh/RUDP endpoint must be non-empty." ) ;
2026-06-11 21:07:48 +01:00
}
2026-06-23 22:54:54 +01:00
return text . toLowerCase ( ) . startsWith ( "rudp://" ) ? text : ` rudp:// ${ text } ` ;
2026-06-11 21:07:48 +01:00
}
2026-06-16 05:18:26 +01:00
function configureCultLibModulePath ( ) {
process . env . NODE _PATH = [
resolve ( repoRoot , ".." , "CultLib" , "packages" ) ,
process . env . NODE _PATH || "" ,
] . filter ( Boolean ) . join ( delimiter ) ;
Module . _initPaths ( ) ;
}
2026-06-11 21:07:48 +01:00
function defineCultMeshDocuments ( defineDocumentType ) {
const providerAdvertisementDefinition = defineDocumentType ( {
type : "gamecult.eve.provider_advertisement" ,
schemaName : "gamecult.eve.provider_advertisement" ,
schemaId : "gamecult.eve.provider_advertisement.v1" ,
schemaVersion : "gamecult.eve.provider_advertisement.v1" ,
global : false ,
name : ( value ) => value ? . providerId || "provider" ,
schema : { parse : ( value ) => value } ,
} ) ;
2026-06-16 11:30:32 +01:00
const operatorStateDefinition = defineDocumentType ( {
type : "weksa.operator_state" ,
schemaName : "weksa.operator_state" ,
schemaId : "weksa.operator_state.v0" ,
schemaVersion : "weksa.operator_state.v0" ,
global : false ,
name : ( value ) => value ? . daemon _id || value ? . provider _id || "weksa" ,
schema : { parse : ( value ) => value } ,
} ) ;
const commandBoundaryDefinition = defineDocumentType ( {
type : "weksa.command_boundary" ,
schemaName : "weksa.command_boundary" ,
schemaId : "weksa.command_boundary.v1" ,
schemaVersion : "weksa.command_boundary.v1" ,
global : false ,
name : ( value ) => value ? . boundary _id || value ? . daemon _id || "weksa" ,
schema : { parse : ( value ) => value } ,
} ) ;
const transportProfileDefinition = defineDocumentType ( {
type : "weksa.transport_profile" ,
schemaName : "weksa.transport_profile" ,
schemaId : "weksa.transport_profile.v1" ,
schemaVersion : "weksa.transport_profile.v1" ,
global : false ,
name : ( value ) => value ? . profile _id || value ? . daemon _id || "weksa" ,
schema : { parse : ( value ) => value } ,
} ) ;
return {
providerAdvertisementDefinition ,
operatorStateDefinition ,
commandBoundaryDefinition ,
transportProfileDefinition ,
} ;
2026-06-11 21:07:48 +01:00
}
function loadProviderAdvertisement ( updatedAt ) {
const fixturePath = resolve ( repoRoot , "docs/fixtures/weksa-provider-advertisement.json" ) ;
const fixture = JSON . parse ( readFileSync ( fixturePath , "utf8" ) ) ;
return {
... fixture ,
mode : "daemon-live" ,
status : "active" ,
2026-06-16 11:30:32 +01:00
daemonId : "weksa" ,
2026-06-11 21:07:48 +01:00
updatedAt ,
canonicalService : "asgard.weksa" ,
locatedService : "asgard.starfire.weksa" ,
2026-10-22 20:13:36 +02:00
cultMeshAddress : "asgard.starfire.weksa/operator" ,
2026-06-11 21:07:48 +01:00
serviceVerse : {
... fixture . serviceVerse ,
semanticAddress : "asgard.starfire.weksa" ,
cultMeshKey : "weksa.service/provider-advertisement" ,
} ,
endpoints : [
{ transport : "cultmesh-store" , address : ".weksa/provider-advertisement-store.cc" } ,
2026-06-23 22:54:54 +01:00
{ transport : CULTNET _RUDP _PROTOCOL _ID , address : formatRudpEndpoint ( host , port ) } ,
2026-06-11 21:07:48 +01:00
] ,
routes : [
{ transport : "cultmesh-store" , address : ".weksa/provider-advertisement-store.cc" } ,
2026-06-23 22:54:54 +01:00
{ transport : CULTNET _RUDP _PROTOCOL _ID , address : formatRudpEndpoint ( host , port ) } ,
2026-06-11 21:07:48 +01:00
] ,
health : {
state : "healthy" ,
2026-06-23 22:54:54 +01:00
endpoint : idunnHealthPublisher ? ` ${ CULTNET _RUDP _PROTOCOL _ID } :idunn-health ` : "unconfigured" ,
2026-06-11 21:07:48 +01:00
witness : ".weksa/operator-state.cc" ,
checkedBy : "idunn.desired_daemon.v1" ,
} ,
} ;
}
2026-06-16 11:30:32 +01:00
function buildCommandBoundary ( updatedAt ) {
return {
schema : "weksa.command_boundary.v1" ,
boundary _id : "weksa" ,
daemon _id : "weksa" ,
provider _id : "weksa.intent.service" ,
service _id : "weksa.intent.service" ,
updated _at : updatedAt ,
owner : "Weksa daemon" ,
lifecycle _authority : "idunn.local-command" ,
health _publication : {
contract : "weksa.cultnet-rudp-provider-health" ,
transport : CULTNET _RUDP _PROTOCOL _ID ,
publication _source : "daemon-published" ,
state _owner : "Weksa daemon" ,
} ,
commands : [
{
command : "speech_provider.mimo.voicedesign" ,
2026-06-23 22:54:54 +01:00
ingress : CULTNET _RUDP _PROTOCOL _ID ,
endpoint : formatRudpEndpoint ( host , port ) ,
2026-06-16 11:30:32 +01:00
owner : "Weksa daemon" ,
2026-06-23 22:54:54 +01:00
input _schema : WEKSA _MIMO _VOICEDESIGN _COMMAND _SCHEMA _ID ,
2026-06-16 11:30:32 +01:00
output _schema : "weksa.mimo_voicedesign_receipt.v0" ,
authority : "Weksa accepts the request, commits typed witnesses, and treats MiMo as an external renderer." ,
} ,
] ,
forbidden _writers : [
2026-06-23 22:54:54 +01:00
"RUDP command senders may request commands but do not own Weksa intent state." ,
2026-06-16 11:30:32 +01:00
"Odin, Eve, and renderers may lower Weksa surfaces but do not mutate command authority." ,
] ,
compatibility : {
2026-06-23 22:54:54 +01:00
http : null ,
status : "no-http-command-lane" ,
cut _line : "The HTTP command route is deleted; Weksa accepts speech_provider.mimo.voicedesign over CultNet/RUDP command documents and keeps typed witnesses as truth." ,
2026-06-16 11:30:32 +01:00
} ,
} ;
}
function buildTransportProfile ( updatedAt ) {
return {
schema : "weksa.transport_profile.v1" ,
profile _id : "weksa" ,
daemon _id : "weksa" ,
provider _id : "weksa.intent.service" ,
updated _at : updatedAt ,
target _transport : CULTNET _RUDP _PROTOCOL _ID ,
current _transport : idunnHealthPublisher
2026-06-23 22:54:54 +01:00
? "rudp-health-and-cultmesh-store-and-rudp-command"
: "cultmesh-store-and-rudp-command" ,
health _transport : idunnHealthPublisher ? CULTNET _RUDP _PROTOCOL _ID : "unconfigured" ,
2026-06-16 11:30:32 +01:00
state _transport : "cultmesh-store" ,
2026-06-23 22:54:54 +01:00
command _transport : CULTNET _RUDP _PROTOCOL _ID ,
2026-06-16 11:30:32 +01:00
compatibility : {
2026-06-23 22:54:54 +01:00
http : null ,
endpoints _are _lowerings : false ,
2026-06-16 11:30:32 +01:00
} ,
2026-06-23 22:54:54 +01:00
cut _line : "Weksa health, provider state, and MiMo VoiceDesign command ingress are daemon-owned typed records over CultNet/RUDP plus CultMesh store; HTTP is no longer in the daemon stack." ,
2026-06-16 11:30:32 +01:00
} ;
}
2026-06-11 21:07:48 +01:00
function loadLatestAffectTuning ( ) {
const root = resolve ( repoRoot , ".weksa-runs/metame-affect-tuning" ) ;
if ( ! existsSync ( root ) ) {
return undefined ;
}
const runs = readdirSyncSafe ( root )
. map ( ( name ) => ( { name , path : resolve ( root , name , "status.json" ) } ) )
. filter ( ( entry ) => existsSync ( entry . path ) )
. map ( ( entry ) => {
try {
const status = JSON . parse ( readFileSync ( entry . path , "utf8" ) ) ;
return { entry , status } ;
} catch {
return undefined ;
}
} )
. filter ( Boolean )
. sort ( ( left , right ) => String ( right . status . completed _at ? ? right . status . started _at ? ? "" ) . localeCompare ( String ( left . status . completed _at ? ? left . status . started _at ? ? "" ) ) ) ;
const latest = runs [ 0 ] ? . status ;
if ( ! latest ) {
return undefined ;
}
const observations = Array . isArray ( latest . observations ) ? latest . observations : [ ] ;
const visible = observations . filter ( ( entry ) => entry ? . evaluation ? . verdict === "affect_contrast_visible" ) . length ;
const needsTuning = observations . filter ( ( entry ) => entry ? . evaluation ? . verdict === "needs_tuning" ) . length ;
return {
run _id : latest . run _id ,
status : latest . status ,
pass _count : latest . pass _count ,
completed _at : latest . completed _at ,
current _prompt _state : latest . current _prompt _state ,
affect _contrast _visible : visible ,
needs _tuning : needsTuning ,
} ;
}
async function inspectCultureCatalog ( ) {
const culturalRoot = resolve ( repoRoot , "data/cultural-ontology" ) ;
const targetRoot = resolve ( repoRoot , "data/target-language-ontology" ) ;
const culturalProfiles = await collectFiles ( culturalRoot , ".yaml" ) ;
const targetProfiles = await collectFiles ( targetRoot , ".yaml" ) ;
return {
profile _count : culturalProfiles . length ,
target _language _profile _count : targetProfiles . length ,
cultural _root : "data/cultural-ontology" ,
target _language _root : "data/target-language-ontology" ,
} ;
}
async function handleMimoVoiceDesign ( body ) {
const command = validateMimoCommand ( body ) ;
const requestId = command . request _id || ` mimo- ${ new Date ( ) . toISOString ( ) . replace ( /[-:.TZ]/g , "" ) } - ${ Math . random ( ) . toString ( 36 ) . slice ( 2 , 8 ) } ` ;
const outputRoot = resolve ( stateRoot , "speech-provider" , "mimo" , requestId ) ;
await mkdir ( outputRoot , { recursive : true } ) ;
2026-06-23 22:54:54 +01:00
const commandDocument = {
... command ,
schema _version : WEKSA _MIMO _VOICEDESIGN _COMMAND _SCHEMA _ID ,
request _id : requestId ,
} ;
2026-06-11 21:07:48 +01:00
2026-06-23 22:54:54 +01:00
const personaEvidence = inspectPersonaState ( commandDocument . persona _state _path ) ;
const interlinguaPacket = commandDocument . interlingua _packet
? normalizeInterlinguaPacket ( commandDocument . interlingua _packet , requestId )
: decomposeThoughtIntoInterlingua ( commandDocument . thought _text , requestId , personaEvidence , commandDocument ) ;
const targetRealization = lowerInterlinguaToSpeechText ( interlinguaPacket , personaEvidence , commandDocument ) ;
const mimoRequest = buildMimoVoiceDesignRequest ( { requestId , command : commandDocument , personaEvidence , interlinguaPacket , targetRealization } ) ;
2026-06-11 21:07:48 +01:00
const providerResponse = await callMimoVoiceDesign ( mimoRequest ) ;
const audioPath = resolve ( outputRoot , ` ${ requestId } .wav ` ) ;
await writeFile ( audioPath , providerResponse . audioBytes ) ;
const receipt = {
schema _version : "weksa.mimo_voicedesign_receipt.v0" ,
request _id : requestId ,
2026-06-23 22:54:54 +01:00
generated _at : new Date ( ) . toISOString ( ) ,
2026-06-11 21:07:48 +01:00
ok : true ,
provider : "xiaomi-mimo" ,
model : "mimo-v2.5-tts-voicedesign" ,
persona _state _ref : personaEvidence . path ,
2026-06-23 22:54:54 +01:00
source _kind : commandDocument . interlingua _packet ? "interlingua_packet" : "thought_text_decomposed_to_interlingua" ,
2026-06-11 21:07:48 +01:00
target _language : targetRealization . target _language ,
performance _register : targetRealization . performance _register ,
artifacts : {
2026-06-23 22:54:54 +01:00
command : ` .weksa/speech-provider/mimo/ ${ requestId } /command.cc ` ,
2026-06-11 21:07:48 +01:00
interlingua _packet : ` .weksa/speech-provider/mimo/ ${ requestId } /interlingua.cc ` ,
mimo _request : ` .weksa/speech-provider/mimo/ ${ requestId } /mimo-request.cc ` ,
receipt : ` .weksa/speech-provider/mimo/ ${ requestId } /receipt.cc ` ,
audio : ` .weksa/speech-provider/mimo/ ${ requestId } / ${ requestId } .wav ` ,
} ,
provider _response : {
id : providerResponse . id ,
created : providerResponse . created ,
audio _bytes : providerResponse . audioBytes . length ,
} ,
trace : {
authority : "Weksa created or accepted interlingua, projected delivery controls, and exported a MiMo VoiceDesign request. MiMo rendered audio only." ,
persona _state _read : personaEvidence . read _status ,
persona _delivery _hints : personaEvidence . delivery _hints ,
text _preview _optimization : false ,
notes : targetRealization . trace . notes ,
} ,
} ;
2026-06-23 22:54:54 +01:00
await writeWitness ( ` speech-provider/mimo/ ${ requestId } /command.cc ` , commandDocument ) ;
2026-06-11 21:07:48 +01:00
await writeWitness ( ` speech-provider/mimo/ ${ requestId } /interlingua.cc ` , interlinguaPacket ) ;
await writeWitness ( ` speech-provider/mimo/ ${ requestId } /mimo-request.cc ` , mimoRequest ) ;
await writeWitness ( ` speech-provider/mimo/ ${ requestId } /receipt.cc ` , receipt ) ;
2026-06-23 22:54:54 +01:00
await writeJson ( resolve ( outputRoot , "command.json" ) , commandDocument ) ;
2026-06-11 21:07:48 +01:00
await writeJson ( resolve ( outputRoot , "interlingua.json" ) , interlinguaPacket ) ;
await writeJson ( resolve ( outputRoot , "mimo-request.json" ) , mimoRequest ) ;
await writeJson ( resolve ( outputRoot , "receipt.json" ) , receipt ) ;
await appendLog ( ` mimo voicedesign request_id= ${ requestId } audio_bytes= ${ providerResponse . audioBytes . length } ` ) ;
return receipt ;
}
function validateMimoCommand ( body ) {
if ( ! body || typeof body !== "object" || Array . isArray ( body ) ) {
throw httpError ( 400 , "request body must be a JSON object" ) ;
}
if ( ! body . persona _state _path || typeof body . persona _state _path !== "string" ) {
throw httpError ( 400 , "persona_state_path is required" ) ;
}
if ( ! body . interlingua _packet && ! body . thought _text ) {
throw httpError ( 400 , "provide interlingua_packet or thought_text" ) ;
}
if ( body . interlingua _packet && body . thought _text ) {
throw httpError ( 400 , "provide either interlingua_packet or thought_text, not both" ) ;
}
if ( body . thought _text && typeof body . thought _text !== "string" ) {
throw httpError ( 400 , "thought_text must be a string" ) ;
}
return body ;
}
function inspectPersonaState ( personaStatePath ) {
const absolutePath = resolve ( repoRoot , personaStatePath ) ;
if ( ! existsSync ( absolutePath ) ) {
throw httpError ( 400 , ` persona_state_path does not exist: ${ personaStatePath } ` ) ;
}
const bytes = readFileSync ( absolutePath ) ;
const printable = Array . from ( bytes . subarray ( 0 , Math . min ( bytes . length , 4096 ) ) ) . filter ( ( byte ) => byte === 9 || byte === 10 || byte === 13 || ( byte >= 32 && byte <= 126 ) ) . length ;
const printableRatio = bytes . length ? printable / Math . min ( bytes . length , 4096 ) : 0 ;
const textPreview = printableRatio > 0.75 ? bytes . toString ( "utf8" , 0 , Math . min ( bytes . length , 4096 ) ) : "" ;
const extractedStrings = extractPersonaStrings ( bytes ) ;
const deliveryHints = derivePersonaDeliveryHints ( extractedStrings , basename ( absolutePath , extname ( absolutePath ) ) ) ;
return {
path : absolutePath ,
basename : basename ( absolutePath , extname ( absolutePath ) ) ,
byte _length : bytes . length ,
read _status : extractedStrings . length ? "string_evidence_extracted" : ( printableRatio > 0.75 ? "text_preview_available" : "binary_or_compact_state_reference_only" ) ,
text _preview : textPreview ,
delivery _hints : deliveryHints ,
} ;
}
function extractPersonaStrings ( bytes ) {
const strings = [ ] ;
let current = "" ;
for ( const byte of bytes ) {
if ( byte >= 32 && byte <= 126 ) {
current += String . fromCharCode ( byte ) ;
} else {
if ( current . length >= 8 ) strings . push ( current ) ;
current = "" ;
}
}
if ( current . length >= 8 ) strings . push ( current ) ;
return strings
2026-06-11 22:01:56 +01:00
. filter ( ( text ) => / voice | style | presentation | affect | persona | pronoun | she \ / her | feminine | woman | female | ship | companion | anime | loli | waifu | sharp | abrasive | technical | bright | cute | hostile | cruel | contempt | protect | dependency | leverage / i . test ( text ) )
2026-06-11 21:07:48 +01:00
. slice ( 0 , 24 ) ;
}
function derivePersonaDeliveryHints ( strings , personaId ) {
const joined = strings . join ( "\n" ) . toLowerCase ( ) ;
const hints = [ ] ;
const addIfSeen = ( pattern , hint ) => {
if ( pattern . test ( joined ) && ! hints . includes ( hint ) ) hints . push ( hint ) ;
} ;
addIfSeen ( /loli|waifu|companion-shaped|companion product|companion shell/ , "youth-coded/loli-coded companion-product presentation as non-sexual product residue" ) ;
2026-06-11 22:01:56 +01:00
addIfSeen ( /she\/her|pronoun guidance|feminine|female|woman/ , "explicitly feminine she/her voice; do not default masculine" ) ;
2026-06-11 21:07:48 +01:00
addIfSeen ( /anime|visual novel/ , "anime / visual-novel heroine performance register" ) ;
addIfSeen ( /ship mind|ship ai|ship-self|embodied ship|cockpit/ , "embodied ship intelligence speaking through ship audio" ) ;
addIfSeen ( /abrasive|cutting|bite|cruel|sadistic/ , "abrasive, cutting delivery with aim rather than random cruelty" ) ;
addIfSeen ( /technical|precision|engineering|mechanism/ , "technical precision inside character performance" ) ;
addIfSeen ( /bright/ , "bright sharp timbre" ) ;
addIfSeen ( /dependency|leverage|life support|bargain/ , "dependency covered by contempt and leverage" ) ;
addIfSeen ( /protect|warning|useful/ , "irritated protection rather than soft affection" ) ;
if ( ! hints . length ) hints . push ( ` ${ personaId } projected Persona voice ` ) ;
return hints . slice ( 0 , 10 ) ;
}
function normalizeInterlinguaPacket ( packet , requestId ) {
if ( typeof packet === "string" ) {
try {
return { ... JSON . parse ( packet ) , packet _id : requestId } ;
} catch {
return {
interlingua _version : "0.1-daemon-provisional" ,
packet _id : requestId ,
kind : "dialogue_line" ,
provenance : { source _type : "opaque_interlingua_text" , confidence : 0.45 } ,
discourse : { speech _act : "verbalize" , intent : packet . slice ( 0 , 240 ) , tone : "unspecified" } ,
trace : { notes : [ "Interlingua arrived as opaque text; daemon preserved it as intent text rather than parsing YAML in the hot path." ] } ,
} ;
}
}
return {
interlingua _version : packet . interlingua _version ? ? "0.1-daemon-provisional" ,
packet _id : packet . packet _id ? ? requestId ,
kind : packet . kind ? ? "dialogue_line" ,
... packet ,
} ;
}
function decomposeThoughtIntoInterlingua ( thoughtText , requestId , personaEvidence , command ) {
const trimmed = thoughtText . trim ( ) ;
return {
interlingua _version : "0.1-daemon-provisional" ,
packet _id : requestId ,
kind : "dialogue_line" ,
provenance : {
source _type : "thought_text" ,
confidence : 0.55 ,
warning : "Heuristic daemon decomposition; review before promoting as canonical interlingua." ,
} ,
context : {
medium : "spoken verbalization" ,
scene : command . scene ? ? "unspecified" ,
} ,
discourse : {
speech _act : command . speech _act ? ? inferSpeechAct ( trimmed ) ,
intent : command . intent ? ? trimmed ,
tone : command . tone ? ? "persona_projected" ,
addressee : command . addressee ? ? "listener" ,
} ,
referents : [
{ id : "speaker" , kind : "person" , label : personaEvidence . basename , salience : "high" } ,
{ id : "listener" , kind : "person" , label : command . addressee ? ? "listener" , salience : "medium" } ,
] ,
predications : [
{
id : "verbalized-thought" ,
predicate : "express" ,
frame : "thought_to_speech" ,
roles : { agent : "speaker" , content : "thought_text" , addressee : "listener" } ,
} ,
] ,
constraints : {
preserve _text _intent : true ,
required _outputs : [ "spoken_text" ] ,
deterministic : false ,
} ,
extensions : {
"weksa.raw_thought" : {
text : trimmed ,
} ,
} ,
trace : {
notes : [
"Raw thought was converted into provisional interlingua by Weksa daemon command ingress." ,
"This path is for verbalization service use; a reviewer or authoring model should promote durable interlingua if the line becomes canon." ,
] ,
} ,
} ;
}
function inferSpeechAct ( text ) {
if ( /^(do not|don't|stop|never|take your hand off|hands off|get away from)\b/i . test ( text ) ) return "warning" ;
if ( /\?$/ . test ( text ) ) return "question" ;
if ( /^(please|could|can you)\b/i . test ( text ) ) return "request" ;
return "statement" ;
}
function lowerInterlinguaToSpeechText ( interlinguaPacket , personaEvidence , command ) {
const targetLanguage = {
code : command . target _language ? . code ? ? "en" ,
locale : command . target _language ? . locale ? ? "en-US" ,
script : command . target _language ? . script ? ? "Latn" ,
register : command . target _language ? . register ? ? "persona-shaped spoken" ,
cultural _ontology _refs : command . target _language ? . cultural _ontology _refs ? ? [ "data/target-language-ontology/en-US.yaml" ] ,
} ;
const performanceRegister = {
label : command . performance _register ? . label ? ? "persona verbalization" ,
medium : command . performance _register ? . medium ? ? "spoken character voiceover" ,
delivery _archetype : command . performance _register ? . delivery _archetype ? ? ` ${ personaEvidence . basename } verbalizes projected intent ` ,
} ;
const spokenText = command . spoken _text
? ? interlinguaPacket . outputs ? . spoken _text
? ? interlinguaPacket . extensions ? . weksa ? . spoken _text
? ? interlinguaPacket . extensions ? . [ "weksa.raw_thought" ] ? . text
? ? interlinguaPacket . discourse ? . intent
? ? "" ;
if ( ! spokenText . trim ( ) ) {
throw httpError ( 400 , "could not derive spoken text from command or interlingua packet" ) ;
}
return {
realization _id : ` ${ interlinguaPacket . packet _id ? ? "packet" } - ${ targetLanguage . locale } -mimo ` ,
target _language : targetLanguage ,
performance _register : performanceRegister ,
outputs : {
spoken _text : spokenText . trim ( ) ,
private _interpretation : command . private _interpretation ? ? "Speaker verbalizes the supplied intent through projected Persona context." ,
intended _effect : command . intended _effect ? ? "Make the supplied intent audible in the speaker's voice." ,
} ,
trace : {
notes : [
"Daemon lowering preserved supplied spoken_text when present; otherwise it used raw thought or interlingua discourse intent." ,
"Target-language register stays separate from provider-facing performance register." ,
] ,
} ,
} ;
}
function buildMimoVoiceDesignRequest ( { requestId , command , personaEvidence , interlinguaPacket , targetRealization } ) {
const voiceDesignInstruction = command . voice _design _prompt
? ? buildVoiceDesignPrompt ( { command , personaEvidence , targetRealization } ) ;
const sourceControls = [
... personaEvidence . delivery _hints ,
... ( Array . isArray ( command . delivery _controls ) ? command . delivery _controls : [ ] ) ,
] . filter ( ( value , index , array ) => value && array . indexOf ( value ) === index ) ;
return {
schema _version : "weksa.mimo_tts_request.v0" ,
request _id : requestId ,
source _realization _ref : ` ${ interlinguaPacket . packet _id ? ? requestId } # ${ targetRealization . realization _id } ` ,
speaker _agent _id : command . speaker _agent _id ? ? personaEvidence . basename ,
persona _state _ref : personaEvidence . path ,
provider : {
id : "xiaomi-mimo" ,
model : "mimo-v2.5-tts-voicedesign" ,
} ,
target _language : targetRealization . target _language ,
performance _register : targetRealization . performance _register ,
voice _design : {
description : voiceDesignInstruction ,
source _controls : sourceControls ,
projected _context _refs : [ personaEvidence . path ] ,
forbidden _traits : command . forbidden _traits ? ? [ "generic assistant voice" , "provider rewriting source meaning" ] ,
} ,
messages : {
user _voice _design _instruction : voiceDesignInstruction ,
assistant _spoken _content : command . provider _tags
? ` ${ command . provider _tags } ${ targetRealization . outputs . spoken _text } `
: targetRealization . outputs . spoken _text ,
} ,
audio : {
format : "wav" ,
optimize _text _preview : false ,
streaming : false ,
} ,
trace : {
source _fields : command . interlingua _packet ? [ "interlingua_packet" ] : [ "thought_text" , "provisional_interlingua" ] ,
delivery _controls _used : sourceControls ,
provider _tags _used : command . provider _tags ? [ command . provider _tags ] : [ ] ,
uncertainties : [
"VoiceDesign prompt is a lossy provider projection from Weksa-owned delivery intent." ,
] ,
} ,
} ;
}
function buildVoiceDesignPrompt ( { command , personaEvidence , targetRealization } ) {
const combinedControls = [
... personaEvidence . delivery _hints ,
... ( Array . isArray ( command . delivery _controls ) ? command . delivery _controls : [ ] ) ,
] . filter ( ( value , index , array ) => value && array . indexOf ( value ) === index ) ;
const controls = combinedControls . length
? combinedControls . join ( ", " )
: "projected Persona voice, clear character delivery, preserve source intent" ;
const forbidden = Array . isArray ( command . forbidden _traits ) && command . forbidden _traits . length
? ` Avoid ${ command . forbidden _traits . join ( ", " ) } . `
: " Avoid generic assistant voice and do not rewrite the spoken text." ;
return ` ${ personaEvidence . basename } voice for ${ targetRealization . performance _register . label } : ${ controls } . ${ forbidden } ` ;
}
async function callMimoVoiceDesign ( mimoRequest ) {
2026-06-23 22:54:54 +01:00
if ( options . mimoDryRun ) {
return {
id : "weksa-mimo-dry-run" ,
created : new Date ( ) . toISOString ( ) ,
audioBytes : Buffer . from ( "RIFF0000WAVEfmt " , "ascii" ) ,
} ;
}
2026-06-11 21:07:48 +01:00
if ( ! existsSync ( mimoApiKeyPath ) ) {
throw httpError ( 500 , ` MiMo API key file is missing: ${ mimoApiKeyPath } ` ) ;
}
const apiKey = readFileSync ( mimoApiKeyPath , "utf8" ) . trim ( ) ;
const providerBody = {
model : "mimo-v2.5-tts-voicedesign" ,
messages : [
{ role : "user" , content : mimoRequest . messages . user _voice _design _instruction } ,
{ role : "assistant" , content : mimoRequest . messages . assistant _spoken _content } ,
] ,
audio : {
format : "wav" ,
optimize _text _preview : false ,
} ,
} ;
const providerResponse = await fetch ( "https://api.xiaomimimo.com/v1/chat/completions" , {
method : "POST" ,
headers : {
"api-key" : apiKey ,
"Content-Type" : "application/json" ,
} ,
body : JSON . stringify ( providerBody ) ,
} ) ;
const text = await providerResponse . text ( ) ;
if ( ! providerResponse . ok ) {
throw httpError ( 502 , ` MiMo VoiceDesign failed with HTTP ${ providerResponse . status } : ${ redactProviderError ( text ) } ` ) ;
}
const json = JSON . parse ( text ) ;
const audioData = json . choices ? . [ 0 ] ? . message ? . audio ? . data ;
if ( ! audioData ) {
throw httpError ( 502 , "MiMo VoiceDesign response did not include audio data" ) ;
}
return {
id : json . id ? ? null ,
created : json . created ? ? null ,
audioBytes : Buffer . from ( audioData , "base64" ) ,
} ;
}
function publication ( key , schema , witness , endpoint ) {
return {
key ,
schema ,
witness ,
2026-06-23 22:54:54 +01:00
endpoint ,
2026-06-11 21:07:48 +01:00
authority : "Weksa daemon" ,
} ;
}
async function writeWitness ( name , value ) {
const path = resolve ( stateRoot , name ) ;
await mkdir ( dirname ( path ) , { recursive : true } ) ;
await writeFile ( path , ` ${ toCultCacheText ( value ) } \n ` , "utf8" ) ;
}
function toCultCacheText ( value ) {
return renderYaml ( value ) . trim ( ) ;
}
function renderYaml ( value , indent = 0 ) {
const pad = " " . repeat ( indent ) ;
if ( Array . isArray ( value ) ) {
if ( ! value . length ) return "[]" ;
return value . map ( ( item ) => {
if ( item && typeof item === "object" ) {
return ` ${ pad } - \n ${ renderYaml ( item , indent + 2 ) } ` ;
}
return ` ${ pad } - ${ yamlScalar ( item ) } ` ;
} ) . join ( "\n" ) ;
}
if ( value && typeof value === "object" ) {
return Object . entries ( value )
. filter ( ( [ , entryValue ] ) => entryValue !== undefined )
. map ( ( [ key , entryValue ] ) => {
if ( entryValue && typeof entryValue === "object" ) {
return ` ${ pad } ${ key } : \n ${ renderYaml ( entryValue , indent + 2 ) } ` ;
}
return ` ${ pad } ${ key } : ${ yamlScalar ( entryValue ) } ` ;
} )
. join ( "\n" ) ;
}
return ` ${ pad } ${ yamlScalar ( value ) } ` ;
}
function yamlScalar ( value ) {
if ( value === null ) return "null" ;
if ( typeof value === "number" || typeof value === "boolean" ) return String ( value ) ;
const text = String ( value ) ;
if ( ! text || /[:#\n\r\t{}[\],&*?|-]|^\s|\s$/ . test ( text ) ) {
return JSON . stringify ( text ) ;
}
return text ;
}
async function collectFiles ( root , extension ) {
if ( ! existsSync ( root ) ) {
return [ ] ;
}
const entries = await readdir ( root , { withFileTypes : true } ) ;
const results = [ ] ;
for ( const entry of entries ) {
const child = resolve ( root , entry . name ) ;
if ( entry . isDirectory ( ) ) {
results . push ( ... await collectFiles ( child , extension ) ) ;
} else if ( entry . name . endsWith ( extension ) ) {
results . push ( child ) ;
}
}
return results ;
}
function readdirSyncSafe ( path ) {
try {
return existsSync ( path ) ? readdirSync ( path ) : [ ] ;
} catch {
return [ ] ;
}
}
async function writeJson ( path , value ) {
await mkdir ( dirname ( path ) , { recursive : true } ) ;
await writeFile ( path , ` ${ JSON . stringify ( value , null , 2 ) } \n ` , "utf8" ) ;
}
function httpError ( statusCode , message ) {
const error = new Error ( message ) ;
error . statusCode = statusCode ;
return error ;
}
function redactProviderError ( text ) {
return String ( text ) . replace ( /[A-Za-z0-9_-]{32,}/g , "[redacted]" ) ;
}
async function appendLog ( line ) {
await mkdir ( dirname ( logPath ) , { recursive : true } ) ;
const previous = existsSync ( logPath ) ? readFileSync ( logPath , "utf8" ) : "" ;
await writeFile ( logPath , ` ${ previous } [ ${ new Date ( ) . toISOString ( ) } ] ${ line } \n ` , "utf8" ) ;
}
function parseArgs ( args ) {
const parsed = { } ;
for ( let index = 0 ; index < args . length ; index += 1 ) {
const arg = args [ index ] ;
switch ( arg ) {
case "--host" :
parsed . host = args [ index + 1 ] ;
index += 1 ;
break ;
case "--port" :
parsed . port = args [ index + 1 ] ;
index += 1 ;
break ;
case "--state-root" :
parsed . stateRoot = args [ index + 1 ] ;
index += 1 ;
break ;
case "--mimo-api-key-path" :
parsed . mimoApiKeyPath = args [ index + 1 ] ;
index += 1 ;
break ;
2026-06-16 05:18:26 +01:00
case "--idunn-rudp-health" :
parsed . idunnRudpHealth = args [ index + 1 ] ;
index += 1 ;
break ;
case "--idunn-daemon" :
parsed . idunnDaemon = args [ index + 1 ] ;
index += 1 ;
break ;
case "--idunn-health-contract" :
parsed . idunnHealthContract = args [ index + 1 ] ;
index += 1 ;
break ;
2026-06-23 22:54:54 +01:00
case "--odin-cultmesh-rudp" :
parsed . odinCultMeshRudp = args [ index + 1 ] ;
index += 1 ;
break ;
2026-06-11 21:07:48 +01:00
case "--health" :
parsed . health = true ;
break ;
2026-06-23 22:54:54 +01:00
case "--mimo-command-json" :
parsed . mimoCommandJson = args [ index + 1 ] ;
index += 1 ;
break ;
case "--mimo-dry-run" :
parsed . mimoDryRun = true ;
break ;
2026-06-11 21:07:48 +01:00
default :
throw new Error ( ` Unknown argument: ${ arg } ` ) ;
}
}
return parsed ;
}