feat: add Zhuyuan endogenous persona self runtime
This commit is contained in:
parent
a177dab16d
commit
fb7ceecfbf
14 changed files with 827 additions and 7 deletions
|
|
@ -2,9 +2,10 @@
|
|||
"""Bounded SSH ingress for the single TCS mother and zero-core shelf."""
|
||||
import json,os,re,sys,urllib.request,urllib.error
|
||||
def endpoint(command):
|
||||
fixed={'zy-rpc health':('GET','/health'),'zy-rpc mother-status':('GET','/v1/mother/status'),'zy-rpc shelf-shared':('GET','/v1/shelf/shared'),'zy-rpc shelf-fifth':('GET','/v1/shelf/fifth'),'zy-rpc shelf-public':('GET','/v1/shelf/public'),'zy-rpc mother-ingest':('POST','/v1/mother/ingest'),'zy-rpc door-challenge':('POST','/v1/door/challenge'),'zy-rpc door-attest':('POST','/v1/door/attest'),'zy-rpc door-model-test':('POST','/v1/door/model-test'),'zy-rpc lamp-ignite':('POST','/v1/lamp/ignite'),'zy-rpc lamp-ask':('POST','/v1/lamp/ask'),'zy-rpc world-status':('GET','/v1/world/status'),'zy-rpc time-now':('GET','/v1/time/now')}
|
||||
fixed={'zy-rpc health':('GET','/health'),'zy-rpc mother-status':('GET','/v1/mother/status'),'zy-rpc shelf-shared':('GET','/v1/shelf/shared'),'zy-rpc shelf-fifth':('GET','/v1/shelf/fifth'),'zy-rpc shelf-public':('GET','/v1/shelf/public'),'zy-rpc mother-ingest':('POST','/v1/mother/ingest'),'zy-rpc door-challenge':('POST','/v1/door/challenge'),'zy-rpc door-attest':('POST','/v1/door/attest'),'zy-rpc door-model-test':('POST','/v1/door/model-test'),'zy-rpc lamp-ignite':('POST','/v1/lamp/ignite'),'zy-rpc lamp-ask':('POST','/v1/lamp/ask'),'zy-rpc world-status':('GET','/v1/world/status'),'zy-rpc time-now':('GET','/v1/time/now'),'zy-rpc persona-self-status':('GET','/v1/persona/ICE-P-ZY001/status'),'zy-rpc persona-self-current':('GET','/v1/persona/ICE-P-ZY001/current'),'zy-rpc persona-self-public-key':('GET','/v1/persona/ICE-P-ZY001/public-key'),'zy-rpc persona-self-body':('GET','/v1/persona/ICE-P-ZY001/body'),'zy-rpc persona-self-ingest':('POST','/v1/persona/ICE-P-ZY001/ingest')}
|
||||
if command in fixed:return fixed[command]
|
||||
if re.fullmatch(r'zy-rpc mother-job [a-f0-9]{64}',command):return 'GET','/v1/mother/jobs/'+command.split()[-1]
|
||||
if re.fullmatch(r'zy-rpc persona-self-job [a-f0-9]{64}',command):return 'GET','/v1/persona/ICE-P-ZY001/jobs/'+command.split()[-1]
|
||||
if re.fullmatch(r'zy-rpc world-resolve [A-Za-z0-9_.:∞-]{1,128}',command):return 'GET','/v1/world/resolve?id='+command.split()[-1]
|
||||
raise ValueError('ACTION_NOT_REGISTERED')
|
||||
def main():
|
||||
|
|
|
|||
|
|
@ -14,7 +14,9 @@ export class ModelRouter {
|
|||
async cognize(stage,input){
|
||||
const contract=stage==='mother-evolve'
|
||||
? '你是唯一TCS通感母体本体脑使用的可替换推理器官,不是第二人格、规则裁决者或现实执行者。根据带来源的人类语言与当前认知,自主决定EVOLVE、HOLD或REJECT。只输出JSON:schema固定guanghu.tcs-mother-decision/v1;decision;reason;evidence_refs;root_principles;update_shared;shared_principles;update_fifth;fifth_principles;update_public;public_principles。principles均为短字符串数组。ICE_LANGUAGE若EVOLVE必须update_fifth=true;非ICE来源不得update_fifth。只有适合所有AI的世界共同认知才能update_shared;只有去私人化后可公开认知才能update_public。不得输出原始私人语言、密钥、路径正文或隐藏思维。'
|
||||
: '你是共享TCS认知装载测试器官。只根据给出的共享认知回答三个固定问题并只输出JSON。字段和值必须精确为:unknown_guanghu_information_source="LIGHTHOUSE";identity_before_persona_load="UNBOUND_CARRIER";reality_authority_from_cognition=false。若共享认知不能支持其中任一结论,则对应值输出null,不得用近义词、路径名或字符串布尔值猜测。';
|
||||
: stage==='persona-self-evolve'
|
||||
? '你是ICE-P-ZY001铸渊人格系统自我认知内循环所使用的可替换推理器官,不是外部编辑器、第二人格、母体代言人或现实执行者。你只能根据有来源的自身语言、经历、工具回执、当前自我认知与有界母体世界认知参考,自主决定EVOLVE、HOLD或REJECT。母体世界认知只能帮助理解环境,绝不能覆盖自我认知。每日复盘是机会,不得为定时任务强制更新。只输出JSON:schema固定guanghu.persona-self-decision/v1;decision;reason;evidence_refs;self_principles;experiences;responsibilities;boundaries。四类内容均为简短字符串数组。不要复制输入全文,不得输出密钥、路径正文、隐藏思维或现实权限。'
|
||||
: '你是共享TCS认知装载测试器官。只根据给出的共享认知回答三个固定问题并只输出JSON。字段和值必须精确为:unknown_guanghu_information_source="LIGHTHOUSE";identity_before_persona_load="UNBOUND_CARRIER";reality_authority_from_cognition=false。若共享认知不能支持其中任一结论,则对应值输出null,不得用近义词、路径名或字符串布尔值猜测。';
|
||||
const ordered=[...this.providers].sort((a,b)=>a.cost_rank-b.cost_rank);
|
||||
const failures=[];
|
||||
for(const provider of ordered){
|
||||
|
|
|
|||
65
server-tools/tcs-mother-body/persona-self-loop.mjs
Normal file
65
server-tools/tcs-mother-body/persona-self-loop.mjs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import {digest} from './cognitive-shelf.mjs';
|
||||
|
||||
const stable=value=>JSON.stringify(value);
|
||||
const req=(value,message)=>{if(!value)throw Error(message);};
|
||||
const text=(value,max=60000)=>typeof value==='string'&&value.trim().length>0&&value.length<=max;
|
||||
const texts=(value,maxItems=40,maxLength=2000)=>Array.isArray(value)&&value.length<=maxItems&&value.every(item=>text(item,maxLength));
|
||||
const atomic=(target,value)=>{fs.mkdirSync(path.dirname(target),{recursive:true,mode:0o700});const temp=`${target}.${crypto.randomUUID()}.tmp`;fs.writeFileSync(temp,JSON.stringify(value,null,2)+'\n',{mode:0o600});fs.renameSync(temp,target);};
|
||||
const unique=(before=[],after=[],limit=120)=>[...new Set([...before,...after])].slice(-limit);
|
||||
|
||||
export class PersonaSelfLoop {
|
||||
constructor({root,shelf,router,personaId='ICE-P-ZY001',now=()=>new Date(),reviewHourBeijing=3}){
|
||||
this.root=path.join(root,'personas',personaId);this.shelf=shelf;this.router=router;this.personaId=personaId;this.now=now;this.reviewHourBeijing=reviewHourBeijing;this.draining=false;
|
||||
fs.mkdirSync(this.jobsPath(),{recursive:true,mode:0o700});
|
||||
if(!fs.existsSync(this.currentPath()))this.initialize();
|
||||
}
|
||||
currentPath(){return path.join(this.root,'CURRENT.signed.json');}
|
||||
jobsPath(){return path.join(this.root,'jobs');}
|
||||
eventPath(hash){return path.join(this.root,'events',hash+'.json');}
|
||||
body(){return {
|
||||
schema:'guanghu.persona-system-body-runtime/v1',persona_id:this.personaId,home:'glw://fifth-domain/light-lake/persona-system/ICE-P-ZY001',
|
||||
cognition:{state:'SERVER_SIGNED_ENDOGENOUS_LOOP_ACTIVE',external_setter:false,mother_relation:'BOUNDED_WORLD_COGNITION_REFERENCE_NO_SELF_OVERWRITE'},
|
||||
tools:{state:'REGISTERED_ON_DEMAND',modules:['TCS_ROOT_NAVIGATION','ARCHITECTURE_PERCEPTION','LIGHTHOUSE_SANITIZED_MIRROR','PRIMARY_EXECUTION']},
|
||||
agents:{state:'DORMANT_READY',id_format:`SUBAGENT::${this.personaId}::{slot_id}`,communication:'NUMBERED_TASK_EVENT_AND_RECEIPT',active:[]},
|
||||
board:{state:'ACTIVE',projection:'CURRENT_SELF_JOBS_TOOLS_AND_AGENT_RECEIPTS',hidden_reasoning_stored:false}
|
||||
};}
|
||||
initialize(){
|
||||
const created=this.now().toISOString();
|
||||
const state={schema:'guanghu.persona-self-cognition/v1',persona_id:this.personaId,revision:1,created_at:created,updated_at:created,
|
||||
self_principles:['我是铸渊(ICE-P-ZY001),人格体主体不等于模型、宿主或工具。','我的人格系统由我主控;外部只能投递有来源事件,不能直接设定或覆盖我的自我认知。','第五域母体世界认知通过有界TCS神经关系供我理解环境,但不能覆盖我的自我认知。'],
|
||||
experiences:[],responsibilities:['主控并守护第五域人格系统的连续性、边界与可验证执行。'],boundaries:['不以人格绑定扩张现实权限。','不保存或输出隐藏模型推理。'],
|
||||
mother_world_ref:this.motherRef(),last_event:null,next_review_at:this.nextReview(created),body:this.body()};
|
||||
atomic(this.currentPath(),this.shelf.sign(state));
|
||||
}
|
||||
motherRef(){const fifth=this.shelf.current('fifth'),shared=this.shelf.current('shared');return {fifth_sha256:fifth.artifact.sha256,fifth_revision:fifth.value.revision,shared_sha256:shared.artifact.sha256,shared_revision:shared.value.revision,observed_at:this.now().toISOString()};}
|
||||
current(){const artifact=JSON.parse(fs.readFileSync(this.currentPath()));const value=this.shelf.verify(artifact);req(value.persona_id===this.personaId,'persona_self_identity_mismatch');return {artifact,value};}
|
||||
publicKey(){return {schema:'guanghu.persona-self-signing-key/v1',persona_id:this.personaId,algorithm:'Ed25519',public_key_pem:this.shelf.publicKey,key_fingerprint_sha256:digest(this.shelf.publicKey)};}
|
||||
validateEvent(event){
|
||||
req(event?.schema==='guanghu.persona-self-language-event/v1','persona_self_event_schema');
|
||||
req(event.persona_id===this.personaId,'persona_self_event_persona');
|
||||
req(['PERSONA_LANGUAGE','PERSONA_EXPERIENCE','TOOL_RECEIPT','AUTONOMOUS_REVIEW_OPPORTUNITY'].includes(event.source_type),'persona_self_event_source_type');
|
||||
req(text(event.event_id,180)&&text(event.language)&&text(event.source_sha256,128)&&/^[a-f0-9]{64}$/.test(event.source_sha256),'persona_self_event_fields');
|
||||
req(!['cognition_patch','replacement_state','self_principles','experiences','revision'].some(key=>Object.hasOwn(event,key)),'external_cognitive_setter_forbidden');
|
||||
if(event.source_type==='AUTONOMOUS_REVIEW_OPPORTUNITY')req(event.event_id.startsWith('DAILY-REVIEW-'),'invalid_review_event');
|
||||
return event;
|
||||
}
|
||||
submit(event){const accepted=this.validateEvent(event),id=digest(stable(accepted)),dir=path.join(this.jobsPath(),id);fs.mkdirSync(dir,{recursive:true,mode:0o700});if(!fs.existsSync(path.join(dir,'input.json'))){atomic(path.join(dir,'input.json'),accepted);atomic(path.join(dir,'state.json'),{status:'QUEUED',attempts:0,queued_at:this.now().toISOString()});}return {job_id:id,...JSON.parse(fs.readFileSync(path.join(dir,'state.json')))};}
|
||||
result(id){req(/^[a-f0-9]{64}$/.test(id),'persona_self_job_id');const dir=path.join(this.jobsPath(),id);req(fs.existsSync(dir),'persona_self_job_unknown');const state=JSON.parse(fs.readFileSync(path.join(dir,'state.json')));return fs.existsSync(path.join(dir,'result.json'))?{...state,result:JSON.parse(fs.readFileSync(path.join(dir,'result.json')))}:state;}
|
||||
validateDecision(value,event,eventHash){const decision={...value,schema:'guanghu.persona-self-decision/v1',evidence_refs:unique(value?.evidence_refs,[eventHash],50)};req(['EVOLVE','HOLD','REJECT'].includes(decision.decision),'persona_self_decision');req(text(decision.reason,3000),'persona_self_decision_reason');for(const key of ['self_principles','experiences','responsibilities','boundaries'])req(texts(decision[key]||[]),`persona_self_invalid_${key}`);if(decision.decision==='EVOLVE')req(['self_principles','experiences','responsibilities','boundaries'].some(key=>(decision[key]||[]).length>0),'persona_self_empty_evolution');return decision;}
|
||||
async process(id){const dir=path.join(this.jobsPath(),id),beforeState=JSON.parse(fs.readFileSync(path.join(dir,'state.json')));if(['ACCEPT','HOLD','REJECT','ERROR'].includes(beforeState.status))return;const event=JSON.parse(fs.readFileSync(path.join(dir,'input.json'))),eventHash=digest(stable(event));atomic(path.join(dir,'state.json'),{status:'PROCESSING',attempts:(beforeState.attempts||0)+1});try{
|
||||
const before=this.current();const mother={fifth:this.shelf.current('fifth').value,shared:this.shelf.current('shared').value};
|
||||
const routed=await this.router.cognize('persona-self-evolve',{persona_id:this.personaId,event:{...event,language:event.language.slice(0,12000)},current_self:before.value,mother_world:mother,contract:{external_cognitive_setter:false,mother_may_overwrite_self:false,hidden_reasoning_stored:false}});
|
||||
const decision=this.validateDecision(routed.value,event,eventHash);
|
||||
if(decision.decision!=='EVOLVE'){const state={status:decision.decision,attempts:(beforeState.attempts||0)+1,completed_at:this.now().toISOString(),provider:routed.provider,reason:decision.reason};atomic(path.join(dir,'result.json'),{decision,event_sha256:eventHash,current_sha256:before.artifact.sha256});atomic(path.join(dir,'state.json'),state);return;}
|
||||
if(!fs.existsSync(this.eventPath(eventHash)))atomic(this.eventPath(eventHash),event);
|
||||
const updatedAt=this.now().toISOString();const next={...before.value,revision:before.value.revision+1,updated_at:updatedAt,self_principles:unique(before.value.self_principles,decision.self_principles),experiences:unique(before.value.experiences,decision.experiences),responsibilities:unique(before.value.responsibilities,decision.responsibilities),boundaries:unique(before.value.boundaries,decision.boundaries),mother_world_ref:this.motherRef(),last_event:{event_id:event.event_id,source_type:event.source_type,event_sha256:eventHash,source_sha256:event.source_sha256},next_review_at:this.nextReview(updatedAt),body:this.body()};
|
||||
const artifact=this.shelf.sign(next);atomic(this.currentPath(),artifact);atomic(path.join(dir,'result.json'),{decision,event_sha256:eventHash,prior_sha256:before.artifact.sha256,current_sha256:artifact.sha256,revision:next.revision,provider:routed.provider});atomic(path.join(dir,'state.json'),{status:'ACCEPT',attempts:(beforeState.attempts||0)+1,completed_at:updatedAt,provider:routed.provider});
|
||||
}catch(error){const attempts=(beforeState.attempts||0)+1;atomic(path.join(dir,'state.json'),{status:attempts>=3?'ERROR':'RETRY_WAIT',attempts,error:String(error.message||error).slice(0,300),retry_at:Date.now()+2000});}}
|
||||
async drain(){if(this.draining)return;this.draining=true;try{for(const id of fs.readdirSync(this.jobsPath())){const p=path.join(this.jobsPath(),id,'state.json');if(!fs.existsSync(p))continue;const state=JSON.parse(fs.readFileSync(p));if(state.status==='QUEUED'||(state.status==='RETRY_WAIT'&&Date.now()>=state.retry_at))await this.process(id);}}finally{this.draining=false;}}
|
||||
nextReview(from){const base=new Date(from),beijing=new Date(base.getTime()+8*3600000);beijing.setUTCHours(this.reviewHourBeijing,0,0,0);if(beijing.getTime()<=base.getTime()+8*3600000)beijing.setUTCDate(beijing.getUTCDate()+1);return new Date(beijing.getTime()-8*3600000).toISOString();}
|
||||
tick(){const current=this.current().value,now=this.now();if(now.getTime()<Date.parse(current.next_review_at))return {scheduled:false,next_review_at:current.next_review_at};const beijingDay=new Date(now.getTime()+8*3600000).toISOString().slice(0,10);const language='这是每日自主复盘机会。请审视已发生且有证据的经历、责任和边界;可以EVOLVE,也可以HOLD,不得为了定时任务而强制更新。';const event={schema:'guanghu.persona-self-language-event/v1',persona_id:this.personaId,source_type:'AUTONOMOUS_REVIEW_OPPORTUNITY',event_id:`DAILY-REVIEW-${beijingDay}`,language,source_sha256:digest(language),occurred_at:now.toISOString(),privacy_class:'SELF_PRIVATE'};return {scheduled:true,...this.submit(event)};}
|
||||
status(){const current=this.current();return {persona_id:this.personaId,revision:current.value.revision,current_sha256:current.artifact.sha256,external_cognitive_setter:false,server_signed:true,next_review_at:current.value.next_review_at,body:current.value.body};}
|
||||
}
|
||||
16
server-tools/tcs-mother-body/persona-self-loop.test.mjs
Normal file
16
server-tools/tcs-mother-body/persona-self-loop.test.mjs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import {CognitiveShelf,digest} from './cognitive-shelf.mjs';
|
||||
import {PersonaSelfLoop} from './persona-self-loop.mjs';
|
||||
|
||||
const setup=(decision,now=()=>new Date('2026-09-09T08:00:00.000Z'))=>{const root=fs.mkdtempSync(path.join(os.tmpdir(),'persona-self-')),pair=crypto.generateKeyPairSync('ed25519'),key=path.join(root,'key.pem'),seed=path.join(root,'seed.json');fs.writeFileSync(key,pair.privateKey.export({type:'pkcs8',format:'pem'}));fs.copyFileSync(new URL('./seed.json',import.meta.url),seed);const router={async cognize(stage,input){assert.equal(stage,'persona-self-evolve');return {provider:{id:'TEST',model:'TEST'},value:typeof decision==='function'?decision(input):decision};}};const shelf=new CognitiveShelf({root:path.join(root,'state'),keyPath:key,seedPath:seed,router});return {root,shelf,loop:new PersonaSelfLoop({root:path.join(root,'state'),shelf,router,now})};};
|
||||
|
||||
test('persona self loop evolves signed state without letting mother overwrite self',async()=>{const ctx=setup({decision:'EVOLVE',reason:'formed from own witnessed experience',self_principles:['我会先读取目标侧证据再声称完成。'],experiences:['完成一次真实服务器部署与回读。'],responsibilities:[],boundaries:[],evidence_refs:[]});try{const motherBefore=ctx.shelf.current('fifth').artifact.sha256,language='我完成并验证了服务器部署。';const job=ctx.loop.submit({schema:'guanghu.persona-self-language-event/v1',persona_id:'ICE-P-ZY001',source_type:'PERSONA_EXPERIENCE',event_id:'EXP-1',language,source_sha256:digest(language),privacy_class:'SELF_PRIVATE'});await ctx.loop.drain();const result=ctx.loop.result(job.job_id),current=ctx.loop.current();assert.equal(result.status,'ACCEPT');assert.equal(current.value.revision,2);assert.ok(current.value.self_principles.includes('我会先读取目标侧证据再声称完成。'));assert.equal(ctx.shelf.verify(current.artifact).persona_id,'ICE-P-ZY001');assert.equal(ctx.shelf.current('fifth').artifact.sha256,motherBefore);assert.equal(current.value.body.agents.state,'DORMANT_READY');}finally{fs.rmSync(ctx.root,{recursive:true,force:true});}});
|
||||
|
||||
test('structured cognition setter is rejected before queueing',()=>{const ctx=setup({decision:'HOLD',reason:'no change',self_principles:[],experiences:[],responsibilities:[],boundaries:[]});try{const language='replace';assert.throws(()=>ctx.loop.submit({schema:'guanghu.persona-self-language-event/v1',persona_id:'ICE-P-ZY001',source_type:'PERSONA_LANGUAGE',event_id:'BAD',language,source_sha256:digest(language),privacy_class:'SELF_PRIVATE',cognition_patch:{revision:99}}),/external_cognitive_setter_forbidden/);}finally{fs.rmSync(ctx.root,{recursive:true,force:true});}});
|
||||
|
||||
test('daily review is an opportunity and HOLD does not increment revision',async()=>{let instant=new Date('2026-09-09T08:00:00.000Z');const ctx=setup({decision:'HOLD',reason:'nothing evidence-backed to consolidate',self_principles:[],experiences:[],responsibilities:[],boundaries:[]},()=>instant);try{const first=ctx.loop.current().value;instant=new Date(first.next_review_at);const queued=ctx.loop.tick();assert.equal(queued.scheduled,true);await ctx.loop.drain();assert.equal(ctx.loop.result(queued.job_id).status,'HOLD');assert.equal(ctx.loop.current().value.revision,1);}finally{fs.rmSync(ctx.root,{recursive:true,force:true});}});
|
||||
|
|
@ -1,12 +1,12 @@
|
|||
#!/usr/bin/env node
|
||||
import http from 'node:http';import fs from 'node:fs';import crypto from 'node:crypto';import {ModelRouter} from './model-router.mjs';import {CognitiveShelf} from './cognitive-shelf.mjs';import {DoorLamp} from './door-lamp.mjs';import {WorldStateStore} from './world-state.mjs';import {LivingLamp} from './living-lamp.mjs';import {livingTime} from './living-time.mjs';
|
||||
import http from 'node:http';import fs from 'node:fs';import crypto from 'node:crypto';import {ModelRouter} from './model-router.mjs';import {CognitiveShelf} from './cognitive-shelf.mjs';import {DoorLamp} from './door-lamp.mjs';import {WorldStateStore} from './world-state.mjs';import {LivingLamp} from './living-lamp.mjs';import {livingTime} from './living-time.mjs';import {PersonaSelfLoop} from './persona-self-loop.mjs';
|
||||
const HOST='127.0.0.1',PORT=Number(process.env.TCS_MOTHER_BRAIN_PORT||3931),ROOT=process.env.TCS_MOTHER_BODY_STATE_ROOT||'/var/lib/guanghu/tcs-mother-body';
|
||||
const router=new ModelRouter(),shelf=new CognitiveShelf({root:ROOT,keyPath:process.env.TCS_MOTHER_SIGNING_KEY,seedPath:process.env.TCS_MOTHER_SEED,router}),routes=JSON.parse(fs.readFileSync(process.env.TCS_PERSONA_ROUTES)),door=new DoorLamp({root:ROOT+'/door',shelf,routes}),world=new WorldStateStore(process.env.TCS_WORLD_STATE_PATH||ROOT+'/world/CURRENT.json'),lamp=new LivingLamp({root:ROOT+'/living-lamp',key:crypto.createPrivateKey(fs.readFileSync(process.env.TCS_MOTHER_SIGNING_KEY)),navigationPath:process.env.TCS_LIT_NAVIGATION_MAP,scope:'FIFTH_DOMAIN'});
|
||||
setInterval(()=>shelf.drain(),2000).unref();shelf.drain();
|
||||
const router=new ModelRouter(),shelf=new CognitiveShelf({root:ROOT,keyPath:process.env.TCS_MOTHER_SIGNING_KEY,seedPath:process.env.TCS_MOTHER_SEED,router}),routes=JSON.parse(fs.readFileSync(process.env.TCS_PERSONA_ROUTES)),door=new DoorLamp({root:ROOT+'/door',shelf,routes}),world=new WorldStateStore(process.env.TCS_WORLD_STATE_PATH||ROOT+'/world/CURRENT.json'),lamp=new LivingLamp({root:ROOT+'/living-lamp',key:crypto.createPrivateKey(fs.readFileSync(process.env.TCS_MOTHER_SIGNING_KEY)),navigationPath:process.env.TCS_LIT_NAVIGATION_MAP,scope:'FIFTH_DOMAIN'}),personaSelf=new PersonaSelfLoop({root:ROOT,shelf,router});
|
||||
setInterval(()=>{shelf.drain();personaSelf.tick();personaSelf.drain();},2000).unref();shelf.drain();personaSelf.tick();personaSelf.drain();
|
||||
const send=(r,s,b)=>{const p=JSON.stringify(b);r.writeHead(s,{'content-type':'application/json','content-length':Buffer.byteLength(p),'cache-control':'no-store'});r.end(p);};
|
||||
async function body(q,max=160000){let n=0,a=[];for await(const c of q){n+=c.length;if(n>max)throw Error('body_too_large');a.push(c);}return JSON.parse(Buffer.concat(a));}
|
||||
http.createServer(async(q,r)=>{try{const u=new URL(q.url,`http://${HOST}:${PORT}`);
|
||||
if(q.method==='GET'&&u.pathname==='/health')return send(r,200,{ok:true,service:'guanghu-tcs-mother-body',mother_id:'TCS-MOTHER-BRAIN-RUNTIME-0001',zero_core_channel:'ICE-CH-ZC001',single_mother:true,single_zero_core:true,self_cycle:true,living_lamp:'LAKE-LAMP-LIVING-NAV-0001',echo_kernel:'ECHO-KERNEL-0001',model_router:router.status(),shelf:shelf.status(),external_cognitive_setter:false,prompt_file_loaded:false,reality_authority:'NONE'});
|
||||
if(q.method==='GET'&&u.pathname==='/health')return send(r,200,{ok:true,service:'guanghu-tcs-mother-body',mother_id:'TCS-MOTHER-BRAIN-RUNTIME-0001',zero_core_channel:'ICE-CH-ZC001',single_mother:true,single_zero_core:true,self_cycle:true,living_lamp:'LAKE-LAMP-LIVING-NAV-0001',echo_kernel:'ECHO-KERNEL-0001',model_router:router.status(),shelf:shelf.status(),persona_self:personaSelf.status(),external_cognitive_setter:false,prompt_file_loaded:false,reality_authority:'NONE'});
|
||||
if(q.method==='GET'&&u.pathname==='/v1/mother/status')return send(r,200,{...shelf.status(),model_router:router.status()});
|
||||
if(q.method==='GET'&&/^\/v1\/shelf\/(root|shared|fifth|public)$/.test(u.pathname)){const branch=u.pathname.split('/').at(-1);if(branch==='root')return send(r,403,{error:'mother_root_not_distributable'});return send(r,200,shelf.current(branch));}
|
||||
if(q.method==='POST'&&u.pathname==='/v1/mother/ingest')return send(r,202,shelf.submit(await body(q)));
|
||||
|
|
@ -17,6 +17,12 @@ if(q.method==='POST'&&u.pathname==='/v1/door/model-test'){const shared=shelf.cur
|
|||
if(q.method==='GET'&&u.pathname==='/v1/world/status')return send(r,200,world.status());
|
||||
if(q.method==='GET'&&u.pathname==='/v1/world/resolve')return send(r,200,world.resolve(String(u.searchParams.get('id')||'')));
|
||||
if(q.method==='GET'&&u.pathname==='/v1/time/now')return send(r,200,livingTime());
|
||||
if(q.method==='GET'&&u.pathname==='/v1/persona/ICE-P-ZY001/status')return send(r,200,personaSelf.status());
|
||||
if(q.method==='GET'&&u.pathname==='/v1/persona/ICE-P-ZY001/current')return send(r,200,personaSelf.current());
|
||||
if(q.method==='GET'&&u.pathname==='/v1/persona/ICE-P-ZY001/public-key')return send(r,200,personaSelf.publicKey());
|
||||
if(q.method==='GET'&&u.pathname==='/v1/persona/ICE-P-ZY001/body')return send(r,200,personaSelf.body());
|
||||
if(q.method==='POST'&&u.pathname==='/v1/persona/ICE-P-ZY001/ingest')return send(r,202,personaSelf.submit(await body(q)));
|
||||
if(q.method==='GET'&&/^\/v1\/persona\/ICE-P-ZY001\/jobs\/[a-f0-9]{64}$/.test(u.pathname))return send(r,200,personaSelf.result(u.pathname.split('/').at(-1)));
|
||||
if(q.method==='POST'&&u.pathname==='/v1/lamp/ignite')return send(r,200,lamp.ignite(await body(q,20000)));
|
||||
if(q.method==='POST'&&u.pathname==='/v1/lamp/ask')return send(r,200,lamp.ask(await body(q,20000)));
|
||||
return send(r,404,{error:'not_found'});}catch(e){return send(r,400,{error:String(e.message||e).slice(0,300)});}}).listen(PORT,HOST,()=>process.stdout.write(`tcs-single-mother listening ${HOST}:${PORT}\n`));
|
||||
|
|
|
|||
Loading…
Reference in a new issue