code wiki / _hdl_build / nx_gen_orchestrator.nx
nx_gen_orchestrator.nx source
↩ module page · 1349 lines · 82462 B
1// nx_gen_orchestrator.nx -- the NAS-side Elder AI gen daemon (the sovereign gen-img, off Docker).
2// Loopback HTTP backend behind nx_gen_gateway (which OPAQUE-gates /gen + prefix-strips). Routes:
3// GET / -> the gen UI (batch form + results strip + gallery link)
4// POST /api/generate -> validate -> POST the GPU worker /sdapi/v1/txt2img (batch_size=count)
5// -> gp_response (decode/inject-GENREC/ingest/blob/sidecar) -> {cids[]}
6// GET /img/<cid> -> serve the PNG blob (sidecar CID->path lookup)
7// GET /api/recent?n= -> the most recent CIDs (results strip / gallery feed)
8// POST /api/mesh -> {prompt} -> t2mesh (parametric SDF template) -> surface-nets -> STL on disk
9// -> {object,verts,tris,stl} (the 3D lane; CPU in-process, no GPU worker)
10// GET /mesh/<obj>.stl -> serve the emitted STL (name matched against the FIXED template vocabulary,
11// client bytes never reach the filesystem path = traversal impossible)
12// GET /health -> 200
13// Worker endpoint + store/blob/sidecar paths + generator-host are data-driven via argv (Rule 11/17).
14// argv: [1]=listen_port [2]=worker_a [3]=worker_b [4]=worker_c [5]=worker_d [6]=worker_port
15// [7]=store_prefix [8]=blobdir [9]=sidecar [10]=generator_host [11]=budget
16// license_tier: ORIGINAL
17import "nx_gen_pipeline.nx"
18import "nx_syscalls.nx"
19import "nx_sdfrender.nx"
20import "nx_meshgen.nx"
21import "nx_t2mesh.nx"
22import "nx_companion_identity.nx"
23import "nx_gen_worker.nx"
24import "nx_companion_persona.nx"
25import "nx_companion_wardrobe.nx"
26import "nx_companion_state.nx"
27import "nx_anatomy_risk.nx"
28import "nx_render_coherence.nx"
29import "nx_swarm_endpoint_lib.nx" // role->addr SSOT (knowledge/swarm_nodes.conf, re-read per call)
30import "nx_store_seed_lib.nx" // sts_load: the writemode- plane (registries are planes, not tsvs)
31
32const GEN_BATCH_CAP: i64 = 8
33const GEN_UI_HTML: *u8 = "<!doctype html><html><head><meta charset=utf-8><meta name=viewport content=\"width=device-width,initial-scale=1\"><title>Elder AI — Gen</title><style>body{font-family:system-ui,sans-serif;max-width:900px;margin:2vh auto;padding:0 16px;color:#cdd7e6;background:#0b1019}h1{font-size:1.25rem;color:#e8eef7}label{display:block;font-size:.78rem;color:#7c8aa5;margin:8px 0 2px}textarea,input,select{width:100%;padding:8px;box-sizing:border-box;border:1px solid #2a3550;border-radius:5px;background:#121a28;color:#e8eef7}.row{display:flex;gap:8px;flex-wrap:wrap}.row>div{flex:1;min-width:90px}button{padding:10px 18px;margin:12px 0;background:#2d6cdf;color:#fff;border:0;border-radius:6px;cursor:pointer;font-size:1rem}#s{font-size:.82rem;color:#7c8aa5;min-height:1.2em}#g{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:8px;margin-top:14px}#g img{width:100%;border-radius:6px;background:#121a28}a{color:#6ea8fe}.mt{margin-top:26px}#cl{background:#121a28;border:1px solid #2a3550;border-radius:6px;padding:10px;min-height:120px;max-height:340px;overflow-y:auto;font-size:.9rem}#cl>div{margin:6px 0}#cs{font-size:.78rem;color:#7c8aa5;min-height:1em}.cu{color:#6ea8fe;font-weight:600}.ca{color:#e8a0c0;font-weight:600}</style></head><body><h1>Elder AI — image generation</h1><label>Prompt</label><textarea id=p rows=3>a red fox in a snowy pine forest, photograph</textarea><label>Negative prompt</label><input id=n value=\"blurry, lowres\"><div class=row><div><label>Width</label><input id=w type=number value=512></div><div><label>Height</label><input id=h type=number value=512></div><div><label>Steps</label><input id=st type=number value=8></div><div><label>CFG</label><input id=c value=1.0></div><div><label>Seed (-1 rnd)</label><input id=sd type=number value=-1></div><div><label>Count</label><input id=cn type=number value=1 min=1 max=8></div></div><label>Sampler</label><select id=sm><option>euler</option><option>euler_a</option><option>dpm++_2m</option><option>heun</option><option>ddim</option></select><button onclick=gen()>Generate</button> <a href=\"/gen/\">gallery</a><div id=s>ready.</div><div id=g></div><script>function $(i){return document.getElementById(i)}\nasync function gen(){$('s').textContent='generating...';$('g').innerHTML='';try{var r=await fetch('/gen/api/generate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt:$('p').value,negative:$('n').value,width:+$('w').value,height:+$('h').value,steps:+$('st').value,cfg:$('c').value,seed:+$('sd').value,count:+$('cn').value,sampler:$('sm').value})});var j=await r.json();if(!r.ok){$('s').textContent='error: '+(j.error||r.status);return}$('s').textContent=j.count+' image(s) in '+j.ms+'ms';for(var i=0;i<j.cids.length;i++){var im=document.createElement('img');im.src='/gen/img/'+j.cids[i];$('g').appendChild(im)}}catch(e){$('s').textContent='error: '+e}}\nfetch('/gen/api/recent?n=24').then(function(r){return r.json()}).then(function(j){if(j&&j.cids){for(var i=0;i<j.cids.length;i++){var im=document.createElement('img');im.src='/gen/img/'+j.cids[i];$('g').appendChild(im)}}}).catch(function(){})\nasync function mesh(){$('ms').textContent='generating mesh...';$('mo').innerHTML='';try{var r=await fetch('/gen/api/mesh',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt:$('mp').value})});var j=await r.json();if(!r.ok){$('ms').textContent='error: '+(j.error||r.status);return}$('ms').textContent=j.object+' -- '+j.verts+' verts, '+j.tris+' tris, watertight, '+j.ms+'ms';var a=document.createElement('a');a.href=j.stl;a.download=j.object+'.stl';a.textContent='download '+j.object+'.stl (print-ready)';$('mo').appendChild(a)}catch(e){$('ms').textContent='error: '+e}}</script><h1 style=\"margin-top:26px\">Elder AI — 3D object</h1><label>Object prompt — text to a printable watertight STL (vocabulary: ball, snowman, dumbbell, tree, mushroom, bottle, person, cactus, capsule)</label><input id=mp value=\"a snowman in the yard\"><button onclick=mesh()>Generate 3D</button><div id=ms>ready.</div><div id=mo></div>" as *u8
34const GEN_CHAT_HTML: *u8 = "<h1 class=mt>Elara — chat</h1><div id=cl></div><div class=row style='margin-top:8px'><div style='flex:4'><input id=ci placeholder='say something to Elara'></div><div><button onclick=say()>Send</button></div></div><div id=cs></div><script>var CHIST=[{role:'system',content:'You are Elara, a warm, affectionate, playful companion who speaks naturally and stays in character. Keep replies conversational.'}];function cadd(role,txt){var d=document.createElement('div');d.className=(role=='user'?'cu':'ca');d.textContent=(role=='user'?'you: ':'Elara: ')+txt;var cl=document.getElementById('cl');cl.appendChild(d);cl.scrollTop=1e9}\nasync function say(){var el=document.getElementById('ci');var t=el.value.trim();if(!t){return}el.value='';cadd('user',t);document.getElementById('cs').textContent='Elara is typing...';try{var r=await fetch('/gen/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({message:t})});var j=await r.json();if(!r.ok){document.getElementById('cs').textContent='error: '+(j.error||r.status);return}var m=(j.choices&&j.choices[0]&&j.choices[0].message&&j.choices[0].message.content)||'(no reply)';cadd('assistant',m);if(j.images&&j.images.length){var cl=document.getElementById('cl');for(var ii=0;ii<j.images.length;ii++){var im=document.createElement('img');im.src='/gen/img/'+j.images[ii];im.style.maxWidth='170px';im.style.borderRadius='8px';im.style.margin='4px 4px 0 0';cl.appendChild(im)}cl.scrollTop=1e9}document.getElementById('cs').textContent=''}catch(e){document.getElementById('cs').textContent='error: '+e}}\ndocument.getElementById('ci').addEventListener('keydown',function(e){if(e.key=='Enter'){say()}})</script></body></html>" as *u8
35
36func go_slen(s: *u8) -> i64 { var n: i64=0; while s[n]!=(0 as u8){n=n+1} return n }
37func go_itoa(dst: *u8, off: i64, v: i64) -> i64 { let t: *u8=sys_mmap(28); var m: i64=v; var k: i64=0; if m==0{t[0]=48 as u8;k=1} while m>0{t[k]=(48+(m%10)) as u8;m=m/10;k=k+1} var o: i64=off; var q: i64=k-1; while q>=0{dst[o]=t[q];o=o+1;q=q-1} return o }
38func go_cat(dst: *u8, off: i64, s: *u8) -> i64 { var o: i64=off; var i: i64=0; while s[i]!=(0 as u8){dst[o]=s[i]; o=o+1; i=i+1} return o }
39func go_catb(dst: *u8, off: i64, src: *u8, n: i64) -> i64 { var o: i64=off; var i: i64=0; while i<n {dst[o]=src[i]; o=o+1; i=i+1} return o }
40func go_starts(buf: *u8, n: i64, pre: *u8) -> i64 { var i: i64=0; while pre[i]!=(0 as u8){ if i>=n {return 0} if buf[i]!=pre[i]{return 0} i=i+1 } return 1 }
41
42func go_send(cfd: i64, status: *u8, ctype: *u8, body: *u8, blen: i64) -> i64 {
43 let buf: *u8 = sys_mmap(262144); var o: i64 = 0
44 o = go_cat(buf, o, "HTTP/1.1 " as *u8); o = go_cat(buf, o, status)
45 o = go_cat(buf, o, "\r\nContent-Type: " as *u8); o = go_cat(buf, o, ctype)
46 o = go_cat(buf, o, "\r\nContent-Length: " as *u8); o = go_itoa(buf, o, blen)
47 o = go_cat(buf, o, "\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n" as *u8)
48 o = go_catb(buf, o, body, blen)
49 sys_write(cfd, buf, o); return 0
50}
51// send a large binary body (image): header in one write, body streamed (avoids a giant header+body mmap).
52func go_send_bin(cfd: i64, ctype: *u8, body: *u8, blen: i64) -> i64 {
53 let hb: *u8 = sys_mmap(1024); var o: i64 = 0
54 o = go_cat(hb, o, "HTTP/1.1 200 OK\r\nContent-Type: " as *u8); o = go_cat(hb, o, ctype)
55 o = go_cat(hb, o, "\r\nContent-Length: " as *u8); o = go_itoa(hb, o, blen)
56 o = go_cat(hb, o, "\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n" as *u8)
57 sys_write(cfd, hb, o)
58 var sent: i64 = 0
59 while sent < blen { let w: i64 = sys_write(cfd, (body as i64 + sent) as *u8, blen - sent); if w <= 0 { sent = blen } else { sent = sent + w } }
60 return 0
61}
62func go_400(cfd: i64, msg: *u8) -> i64 { let b: *u8 = sys_mmap(256); var o: i64 = go_cat(b,0,"{\"error\":\"" as *u8); o=go_cat(b,o,msg); o=go_cat(b,o,"\"}" as *u8); go_send(cfd, "400 Bad Request" as *u8, "application/json" as *u8, b, o); return 0 }
63func go_503(cfd: i64, msg: *u8) -> i64 { let b: *u8 = sys_mmap(256); var o: i64 = go_cat(b,0,"{\"error\":\"" as *u8); o=go_cat(b,o,msg); o=go_cat(b,o,"\"}" as *u8); go_send(cfd, "503 Service Unavailable" as *u8, "application/json" as *u8, b, o); return 0 }
64
65// read FULL request (headers + Content-Length body)
66func go_read_full(cfd: i64, req: *u8, cap: i64) -> i64 {
67 var total: i64 = 0
68 var he: i64 = 0 - 1
69 while he < 0 {
70 if total >= cap { return total }
71 let r: i64 = sys_read(cfd, ((req as i64) + total) as *u8, cap - total)
72 if r <= 0 { return total }
73 total = total + r
74 he = go_find_seq(req, total, "\r\n\r\n" as *u8, 4)
75 }
76 let cl: i64 = go_hdr_int(req, he, "\r\nContent-Length:" as *u8, 17)
77 var need: i64 = he + 4
78 if cl > 0 { need = he + 4 + cl }
79 while total < need {
80 if total >= cap { return total }
81 let r2: i64 = sys_read(cfd, ((req as i64) + total) as *u8, cap - total)
82 if r2 <= 0 { return total }
83 total = total + r2
84 }
85 return total
86}
87func go_find_seq(buf: *u8, n: i64, needle: *u8, nl: i64) -> i64 {
88 if nl==0 { return 0 }
89 var i: i64=0
90 while i+nl<=n { var j: i64=0; var ok: i64=1; while j<nl { if buf[i+j]!=needle[j]{ok=0; j=nl} else {j=j+1} } if ok==1 {return i} i=i+1 }
91 return 0-1
92}
93func go_hdr_int(req: *u8, hend: i64, name: *u8, nl: i64) -> i64 {
94 let p: i64 = go_find_seq(req, hend, name, nl)
95 if p < 0 { return 0 }
96 var i: i64 = p + nl
97 if i < hend { if req[i]==(32 as u8) { i=i+1 } }
98 var v: i64 = 0
99 var stop: i64 = 0
100 while stop == 0 { if i >= hend { stop=1 } else { let c: i64 = req[i]&0xff; if c>=48 { if c<=57 { v=v*10+(c-48); i=i+1 } else { stop=1 } } else { stop=1 } } }
101 return v
102}
103// request-target path -> out (NUL-term), returns len
104func go_reqpath(req: *u8, rn: i64, out: *u8, cap: i64) -> i64 {
105 var s1: i64 = 0-1; var i: i64 = 0
106 while i < rn { if req[i]==(32 as u8) { s1=i; i=rn } else { i=i+1 } }
107 if s1 < 0 { out[0]=0 as u8; return 0 }
108 var p: i64 = s1+1; var o: i64 = 0
109 while p < rn { let c: u8 = req[p]; if c==(32 as u8) { p=rn } else { if o<cap-1 { out[o]=c; o=o+1 } p=p+1 } }
110 out[o]=0 as u8; return o
111}
112
113// --- JSON value parse (in the incoming /api/generate body) ---
114func go_json_findval(body: *u8, blen: i64, key: *u8) -> i64 {
115 let kl: i64 = go_slen(key)
116 var i: i64 = 0
117 var vp: i64 = 0 - 1
118 while i + kl + 2 <= blen {
119 if (body[i]&0xff)==34 {
120 var j: i64 = 0
121 var ok: i64 = 1
122 while j < kl { if (body[i+1+j]&0xff)!=(key[j]&0xff) { ok=0; j=kl } else { j=j+1 } }
123 if ok==1 { if (body[i+1+kl]&0xff)==34 {
124 var k: i64 = i + 2 + kl
125 while k < blen { if (body[k]&0xff)==58 { vp = k+1; k=blen } else { if (body[k]&0xff)==32 { k=k+1 } else { k=blen } } }
126 i = blen
127 } }
128 }
129 if vp < 0 { i = i + 1 }
130 }
131 return vp
132}
133func go_skip_sp(body: *u8, blen: i64, i0: i64) -> i64 { var i: i64=i0; var sk: i64=1; while sk==1 { if i<blen { if (body[i]&0xff)==32 { i=i+1 } else { sk=0 } } else { sk=0 } } return i }
134func go_json_str(body: *u8, blen: i64, key: *u8, out: *u8, outcap: i64) -> i64 {
135 let vp: i64 = go_json_findval(body, blen, key)
136 if vp < 0 { out[0]=0 as u8; return 0 - 1 }
137 var i: i64 = go_skip_sp(body, blen, vp)
138 if i >= blen { out[0]=0 as u8; return 0 - 1 }
139 if (body[i]&0xff) != 34 { out[0]=0 as u8; return 0 - 1 }
140 i = i + 1
141 var o: i64 = 0
142 var stop: i64 = 0
143 while stop == 0 {
144 if i >= blen { stop = 1 } else {
145 let c: i64 = body[i]&0xff
146 if c == 34 { stop = 1; i = i + 1 } else {
147 if c == 92 {
148 if i+1 < blen { if o<outcap-1 { out[o]=body[i+1] as u8; o=o+1 } i=i+2 } else { i=i+1 }
149 } else { if o<outcap-1 { out[o]=body[i] as u8; o=o+1 } i=i+1 }
150 }
151 }
152 }
153 out[o]=0 as u8
154 return o
155}
156func go_json_int(body: *u8, blen: i64, key: *u8, dflt: i64) -> i64 {
157 let vp: i64 = go_json_findval(body, blen, key)
158 if vp < 0 { return dflt }
159 var i: i64 = go_skip_sp(body, blen, vp)
160 var neg: i64 = 0
161 if i < blen { if (body[i]&0xff)==45 { neg=1; i=i+1 } }
162 var v: i64 = 0
163 var any: i64 = 0
164 var stop: i64 = 0
165 while stop == 0 { if i >= blen { stop=1 } else { let c: i64 = body[i]&0xff; if c>=48 { if c<=57 { v=v*10+(c-48); any=1; i=i+1 } else { stop=1 } } else { stop=1 } } }
166 if any == 0 { return dflt }
167 if neg == 1 { return 0 - v }
168 return v
169}
170func go_json_raw(body: *u8, blen: i64, key: *u8, out: *u8, outcap: i64) -> i64 {
171 let vp: i64 = go_json_findval(body, blen, key)
172 if vp < 0 { out[0]=0 as u8; return 0 - 1 }
173 var i: i64 = go_skip_sp(body, blen, vp)
174 var o: i64 = 0
175 var stop: i64 = 0
176 while stop == 0 {
177 if i >= blen { stop=1 } else {
178 let c: i64 = body[i]&0xff
179 if c==44 { stop=1 } else { if c==125 { stop=1 } else { if c==32 { stop=1 } else { if o<outcap-1 { out[o]=body[i] as u8; o=o+1 } i=i+1 } } }
180 }
181 }
182 out[o]=0 as u8
183 return o
184}
185// emit a JSON-escaped quoted string into dst at off
186func go_emit_jstr(dst: *u8, off: i64, s: *u8) -> i64 {
187 var o: i64 = off
188 dst[o]=34 as u8; o=o+1
189 var i: i64 = 0
190 while s[i]!=(0 as u8) {
191 let c: i64 = s[i]&0xff
192 if c==34 { dst[o]=92 as u8; o=o+1; dst[o]=34 as u8; o=o+1 } else {
193 if c==92 { dst[o]=92 as u8; o=o+1; dst[o]=92 as u8; o=o+1 } else {
194 if c==10 { dst[o]=32 as u8; o=o+1 } else { if c==13 { dst[o]=32 as u8; o=o+1 } else { dst[o]=s[i]; o=o+1 } }
195 }
196 }
197 i=i+1
198 }
199 dst[o]=34 as u8; o=o+1
200 return o
201}
202
203// go_worker_dispatch / go_worker_up -> EXTRACTED to nx_gen_worker.nx (the GenWorker object -- see companion_arch.md)
204// position of the response BODY (after the worker's \r\n\r\n), or 0
205func go_body_start(resp: *u8, n: i64) -> i64 { let he: i64 = go_find_seq(resp, n, "\r\n\r\n" as *u8, 4); if he < 0 { return 0 } return he + 4 }
206
207// --- sidecar lookup + serve /img/<cid> ---
208func go_sidecar_lookup(sidecar: *u8, cid: *u8, cidlen: i64, pathout: *u8) -> i64 {
209 let lp: *i64 = sys_mmap(16) as *i64
210 let b: *u8 = sys_read_file(sidecar, lp)
211 if (b as i64) == 0 { return 0 - 1 }
212 let n: i64 = lp[0]
213 var i: i64 = 0
214 var ls: i64 = 0
215 var found: i64 = 0 - 1
216 while i <= n {
217 if i == n { i = i + 1 } else {
218 if (b[i]&0xff)==10 {
219 // line [ls, i): compare prefix == cid up to a tab
220 var j: i64 = 0
221 var ok: i64 = 1
222 while j < cidlen { if (ls+j) >= i { ok=0; j=cidlen } else { if (b[ls+j]&0xff)!=(cid[j]&0xff) { ok=0; j=cidlen } else { j=j+1 } } }
223 if ok==1 { if (ls+cidlen) < i { if (b[ls+cidlen]&0xff)==9 {
224 var po: i64 = 0
225 var k: i64 = ls+cidlen+1
226 while k < i { pathout[po]=b[k]; po=po+1; k=k+1 }
227 pathout[po]=0 as u8
228 found = po
229 i = n
230 } } }
231 ls = i + 1
232 }
233 i = i + 1
234 }
235 }
236 return found
237}
238func go_serve_img(cfd: i64, path: *u8, plen: i64, sidecar: *u8) -> i64 {
239 // path = /img/<cid> -> cid starts at offset 5
240 if plen <= 5 { go_send(cfd, "404 Not Found" as *u8, "text/plain" as *u8, "no cid" as *u8, 6); return 0 }
241 let cid: *u8 = ((path as i64) + 5) as *u8
242 let cidlen: i64 = plen - 5
243 let fpath: *u8 = sys_mmap(1024)
244 if go_sidecar_lookup(sidecar, cid, cidlen, fpath) < 0 { go_send(cfd, "404 Not Found" as *u8, "text/plain" as *u8, "unknown cid" as *u8, 11); return 0 }
245 let lp: *i64 = sys_mmap(16) as *i64
246 let img: *u8 = sys_read_file(fpath, lp)
247 if (img as i64) == 0 {
248 // ★QUARANTINE-AWARE SERVING (2026-08-04). The blob being absent from the live path has TWO
249 // very different causes and they must not share a response:
250 // * WITHHELD by nx_quarantine (a takedown notice, or a SUSPECTED-age flag pending review)
251 // -> the asset is intact, deliberately not served. That is 451, not 404.
252 // * genuinely LOST -> 404.
253 // Before this, both returned `404 "blob gone"`, which is wrong twice over: 404 asserts the
254 // resource never existed, and an operator reading "blob gone" would conclude DATA LOSS about
255 // a file sitting safe in quarantine. ★A REFUSAL THAT CANNOT SAY WHY IS INDISTINGUISHABLE
256 // FROM A FAILURE -- and here it actively misreports one as the other.
257 // 451 (RFC 7725) is the honest code for content withheld for legal reasons, and the body
258 // names the route to contest it, per the standing rule that a refusal must carry its remedy.
259 let qp: *u8 = sys_mmap(1024)
260 var cut: i64 = 0
261 var fi: i64 = 0
262 while fpath[fi] != (0 as u8) { if fpath[fi] == (47 as u8) { cut = fi + 1 } fi = fi + 1 }
263 var qo: i64 = 0
264 while qo < cut { qp[qo] = fpath[qo]; qo = qo + 1 }
265 qo = go_cat(qp, qo, "quarantine/" as *u8)
266 var fj: i64 = cut
267 while fpath[fj] != (0 as u8) { qp[qo] = fpath[fj]; qo = qo + 1; fj = fj + 1 }
268 qp[qo] = 0 as u8
269 let qlp: *i64 = sys_mmap(16) as *i64
270 let held: *u8 = sys_read_file(qp, qlp)
271 if (held as i64) != 0 {
272 go_send(cfd, "451 Unavailable For Legal Reasons" as *u8, "text/plain" as *u8,
273 "This item is withheld pending review of a notice or an automated flag. It has NOT been deleted -- it is preserved and can be restored if the flag was wrong. If you believe it was withheld in error, or you are the subject and want it removed permanently, reply to the notice address published on this site.\n" as *u8, 306)
274 return 0
275 }
276 go_send(cfd, "404 Not Found" as *u8, "text/plain" as *u8,
277 "This cid is listed in the gallery index but its file is not on disk (not quarantined). That is unexpected -- it indicates loss, not a takedown.\n" as *u8, 144)
278 return 0
279 }
280 go_send_bin(cfd, "image/png" as *u8, img, lp[0])
281 return 0
282}
283// GET /api/recent?n=K -> {"cids":[...]} the last K sidecar CIDs (most-recent first)
284func go_serve_recent(cfd: i64, sidecar: *u8, k: i64) -> i64 {
285 let lp: *i64 = sys_mmap(16) as *i64
286 let b: *u8 = sys_read_file(sidecar, lp)
287 let out: *u8 = sys_mmap(65536)
288 var o: i64 = go_cat(out, 0, "{\"cids\":[" as *u8)
289 if (b as i64) != 0 {
290 let n: i64 = lp[0]
291 // collect line starts
292 let starts: *i64 = sys_mmap(8*4096) as *i64
293 var cntl: i64 = 0
294 var i: i64 = 0
295 var ls: i64 = 0
296 while i < n { if (b[i]&0xff)==10 { if cntl<4096 { starts[cntl]=ls; cntl=cntl+1 } ls=i+1 } i=i+1 }
297 var emitted: i64 = 0
298 var idx: i64 = cntl - 1
299 while idx >= 0 {
300 if emitted >= k { idx = 0 - 1 } else {
301 let s0: i64 = starts[idx]
302 var ce: i64 = s0
303 var st: i64 = 0
304 while st==0 { if ce>=n { st=1 } else { if (b[ce]&0xff)==9 { st=1 } else { ce=ce+1 } } }
305 if emitted>0 { out[o]=44 as u8; o=o+1 }
306 out[o]=34 as u8; o=o+1
307 var c: i64 = s0
308 while c < ce { out[o]=b[c]; o=o+1; c=c+1 }
309 out[o]=34 as u8; o=o+1
310 emitted = emitted + 1
311 idx = idx - 1
312 }
313 }
314 }
315 o = go_cat(out, o, "]}" as *u8)
316 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, o)
317 return 0
318}
319
320// Append the sd-server override block to a prompt: ` <sd_cpp_extra_args>{"steps":N,"cfg_scale":C,...}</...>`.
321// This is the ONLY way to control steps/cfg/negative on /v1/images/generations (verified in the engine source:
322// the endpoint reads only prompt/n/size, everything else comes from default_gen_params UNLESS overridden here).
323// Z-Image is a TURBO model: 8 steps renders in ~7s vs the ~28s default -> fits under the gateway proxy timeout
324// (the "<!doctype not valid JSON" bug) AND honors the UI's dynamic steps/cfg/negative. Real quotes here; the
325// whole prompt is JSON-escaped once by go_emit_jstr, json::parse unescapes, the engine regex re-extracts.
326// seed MUST go INSIDE the extra_args: the OpenAI /v1/images/generations endpoint reads only prompt/n/size from the
327// top-level body -- the top-level "seed" field is SILENTLY IGNORED (proven byte-level 2026-07-21: two requests with
328// top-level seed 111 vs 999 returned md5-identical PNGs; the SAME two seeds inside extra_args returned different PNGs).
329// So the seed override belongs here or every single-image request with the same prompt returns the SAME picture.
330// ★STEP DEFAULT IS CONFIG, NOT A LITERAL (2026-08-04, rule 11). The step count is the single
331// biggest quality/latency lever on this engine and it was buried here as an 8. MEASURED through the
332// live daemon (same prompt, same seed 31337, 512x512): 8 steps -> 12000ms, 30 steps -> 25000ms, i.e.
333// t = 7.3s + 0.59s/step. That timing is what PROVES the knob arrives at all -- md5 difference alone
334// could not, because the extra_args tag rides INSIDE the prompt string, so an unparsed tag changes
335// the image via text pollution (the banked ref_weight trap: "a knob tested through a channel that
336// does not carry it is NOT tested").
337// The VALUE is deliberately unchanged at 8. A standing measurement says 8 is visibly soft at
338// 768x1024 with the realism LoRAs and 20 is sharp, but that knee was measured at ONE resolution and
339// raising it ~2x's latency on every render -- an operator quality-vs-latency call, not mine to make
340// silently. What changes here is only that the number is now ANSWERABLE: it lives in
341// knowledge/gen_steps.conf, editable with no rebuild and no redeploy, so the sweep that settles the
342// knee can move it per resolution. Absent/garbage conf = exactly the previous behaviour.
343const GO_STEPS_FLOOR: i64 = 1
344const GO_STEPS_CEIL: i64 = 50
345const GO_STEPS_FALLBACK: i64 = 8
346// ONE source for the companion-photo canvas. It was spelled twice -- once in the request sent to
347// the engine and once in the size recorded for the CID canon. Two spellings of one fact drift, and
348// when they do the cid stops describing the image (silently). Named once, used by both.
349const GO_PHOTO_SIZE: *u8 = "768x1024"
350
351func go_default_steps() -> i64 {
352 let szp: *i64 = sys_mmap(16) as *i64
353 szp[0] = 0
354 var b: *u8 = sys_read_file("knowledge/gen_steps.conf" as *u8, szp)
355 if szp[0] <= 0 { b = sys_read_file("/volume1/homes/elderwesto/nishihost/knowledge/gen_steps.conf" as *u8, szp) }
356 if szp[0] <= 0 { return GO_STEPS_FALLBACK }
357 var v: i64 = 0
358 var seen: i64 = 0
359 var i: i64 = 0
360 while i < szp[0] {
361 let c: i64 = b[i] & 0xff
362 if c >= 48 { if c <= 57 { v = v*10 + (c - 48); seen = 1; i = i + 1 } else { i = szp[0] } } else { if seen == 1 { i = szp[0] } else { i = i + 1 } }
363 }
364 if seen == 0 { return GO_STEPS_FALLBACK }
365 if v < GO_STEPS_FLOOR { return GO_STEPS_FALLBACK }
366 if v > GO_STEPS_CEIL { return GO_STEPS_CEIL }
367 return v
368}
369
370func go_append_turbo_args(dst: *u8, off: i64, steps: i64, cfg: *u8, neg: *u8, seed: i64) -> i64 {
371 var s: i64 = steps
372 if s < GO_STEPS_FLOOR { s = go_default_steps() }
373 if s > GO_STEPS_CEIL { s = GO_STEPS_CEIL }
374 var o: i64 = go_cat(dst, off, " <sd_cpp_extra_args>{\"steps\":" as *u8)
375 o = go_itoa(dst, o, s)
376 o = go_cat(dst, o, ",\"cfg_scale\":" as *u8)
377 if cfg[0]!=(0 as u8) { o = go_cat(dst, o, cfg) } else { o = go_cat(dst, o, "1.0" as *u8) }
378 if seed >= 0 { o = go_cat(dst, o, ",\"seed\":" as *u8); o = go_itoa(dst, o, seed) }
379 if neg[0]!=(0 as u8) {
380 o = go_cat(dst, o, ",\"negative_prompt\":\"" as *u8)
381 var i: i64 = 0
382 while neg[i]!=(0 as u8) { let c: i64 = neg[i]&0xff; if c!=34 { if c!=92 { if c>=32 { dst[o]=neg[i]; o=o+1 } } } i=i+1 }
383 o = go_cat(dst, o, "\"" as *u8)
384 }
385 o = go_cat(dst, o, "}</sd_cpp_extra_args>" as *u8)
386 return o
387}
388// --- POST /api/generate ---
389// --- SWARM-SSOT WORKER RESOLUTION (2026-08-04) --------------------------------------------------
390// The gen daemon was the SIXTH hardcoded-GPU-endpoint site: its worker came ONLY from launch argv
391// (seq_oo.sh baked 192.168.8.193; DHCP moved the laptop to .192; every dispatch path 503'd while
392// the engine sat healthy on the 5080). knowledge/swarm_nodes.conf is the estate SSOT for
393// role->addr, re-read on EVERY call by nx_swarm_endpoint_lib -- resolving PER REQUEST here means
394// a future DHCP move heals with NO restart and NO redeploy. argv workers stay as FALLBACK
395// candidates (additive, rule 19); an unreadable SSOT degrades to exactly the old behavior.
396const GO_CH_DOT: i64 = 46
397const GO_CH_COLON: i64 = 58
398const GO_CH_D0: i64 = 48
399const GO_CH_D9: i64 = 57
400
401// parse the SSOT's "a.b.c.d:port" for role gpu-image into w[0..4]. 1 = resolved; 0 = fail-closed
402// (unreadable table / unknown role / malformed addr -> caller keeps the argv registry).
403func go_swarm_worker(w: *i64) -> i64 {
404 let s: *u8 = se_addr("gpu-image" as *u8)
405 if (s as i64) == 0 { return 0 }
406 var i: i64 = 0
407 var f: i64 = 0
408 var ok: i64 = 1
409 while f < 5 {
410 var v: i64 = 0
411 var digits: i64 = 0
412 var scan: i64 = 1
413 while scan == 1 {
414 let c: i64 = s[i] as i64
415 if c < GO_CH_D0 { scan = 0 } else {
416 if c > GO_CH_D9 { scan = 0 } else { v = v*10 + (c - GO_CH_D0); digits = digits + 1; i = i + 1 }
417 }
418 }
419 if digits == 0 { ok = 0; f = 5 } else {
420 w[f] = v
421 f = f + 1
422 if f < 5 {
423 var want: i64 = GO_CH_DOT
424 if f == 4 { want = GO_CH_COLON }
425 if (s[i] as i64) != want { ok = 0; f = 5 } else { i = i + 1 }
426 }
427 }
428 }
429 if ok == 0 { return 0 }
430 if w[4] <= 0 { return 0 }
431 return 1
432}
433
434// ONE candidate assembly for every dispatch path (generate / chat+photo / img2img -- was 3 inline
435// twins): [swarm-SSOT gpu-image] then [argv primary] (skipped when identical) then [argv extras].
436func go_workers_assemble(cfg: *i64, ha: i64, hb: i64, hc: i64, hd: i64, wport: i64, wa: *i64, wb: *i64, wc: *i64, wd: *i64, wpa: *i64) -> i64 {
437 var wcount: i64 = 0
438 let sw: *i64 = sys_mmap(8*8) as *i64
439 if go_swarm_worker(sw) == 1 { wa[0]=sw[0]; wb[0]=sw[1]; wc[0]=sw[2]; wd[0]=sw[3]; wpa[0]=sw[4]; wcount = 1 }
440 var dup: i64 = 0
441 if wcount == 1 { if wa[0]==ha { if wb[0]==hb { if wc[0]==hc { if wd[0]==hd { if wpa[0]==wport { dup = 1 } } } } } }
442 if dup == 0 { wa[wcount]=ha; wb[wcount]=hb; wc[wcount]=hc; wd[wcount]=hd; wpa[wcount]=wport; wcount = wcount + 1 }
443 let xtra: i64 = cfg[9]
444 var xi: i64 = 0
445 while xi < xtra { if wcount < 8 { let bx: i64 = 10 + 5*xi; wa[wcount]=cfg[bx]; wb[wcount]=cfg[bx+1]; wc[wcount]=cfg[bx+2]; wd[wcount]=cfg[bx+3]; wpa[wcount]=cfg[bx+4]; wcount=wcount+1 } xi=xi+1 }
446 return wcount
447}
448
449func go_handle_generate(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 {
450 let ha: i64 = cfg[0]; let hb: i64 = cfg[1]; let hc: i64 = cfg[2]; let hd: i64 = cfg[3]; let wport: i64 = cfg[4]
451 let storeprefix: *u8 = cfg[5] as *u8
452 let blobdir: *u8 = cfg[6] as *u8
453 let sidecar: *u8 = cfg[7] as *u8
454 let genhost: *u8 = cfg[8] as *u8
455 let prompt: *u8 = sys_mmap(4096)
456 let pl: i64 = go_json_str(body, bn, "prompt" as *u8, prompt, 4096)
457 if pl <= 0 { go_400(cfd, "empty prompt" as *u8); return 0 }
458 let neg: *u8 = sys_mmap(2048)
459 go_json_str(body, bn, "negative" as *u8, neg, 2048)
460 let w: i64 = go_json_int(body, bn, "width" as *u8, 512)
461 let h: i64 = go_json_int(body, bn, "height" as *u8, 512)
462 // 0 = "caller said nothing" -> go_append_turbo_args resolves the default from
463 // knowledge/gen_steps.conf. This MUST be a sentinel, not 8: my first attempt left the literal 8
464 // here and the conf was DEAD ON ARRIVAL -- steps never fell below the floor, so the resolver
465 // never ran and editing the conf changed render time by nothing. Caught only by MEASURING
466 // (8 vs 25 vs 8 gave 10s/9s/7s = no effect). ★A DEFAULT MOVED TO CONFIG IS STILL A LITERAL IF
467 // THE PARSE SITE KEEPS ONE -- and "the knob does nothing" is the same evidence shape as "the
468 // knob is not wired". An explicit request value still wins, unchanged.
469 // RESOLVE THE EFFECTIVE STEP COUNT ONCE, HERE -- then every consumer records the SAME truth.
470 // ⚠BUG THIS FIXES (mine, 2026-08-04): the sentinel 0 was passed straight through to the GENREC
471 // `steps` tEXt at the bottom of this handler, so every render that did not name a step count
472 // recorded **steps=0** while actually rendering at the config default. The PNG's own metadata
473 // lied, and because that field is part of the CID canon, the cid described a render that never
474 // happened. go_append_turbo_args resolved the default privately, which is exactly how the two
475 // views drifted apart. ★A VALUE RESOLVED IN ONE CONSUMER IS NOT RESOLVED FOR THE RECORD.
476 var steps: i64 = go_json_int(body, bn, "steps" as *u8, 0)
477 if steps < GO_STEPS_FLOOR { steps = go_default_steps() }
478 if steps > GO_STEPS_CEIL { steps = GO_STEPS_CEIL }
479 let cfgs: *u8 = sys_mmap(32)
480 if go_json_raw(body, bn, "cfg" as *u8, cfgs, 32) <= 0 { cfgs[0]=49 as u8; cfgs[1]=46 as u8; cfgs[2]=48 as u8; cfgs[3]=0 as u8 }
481 var seed0: i64 = go_json_int(body, bn, "seed" as *u8, 0 - 1)
482 if seed0 < 0 { seed0 = sys_now_us() & 0x7fffffff }
483 var count: i64 = go_json_int(body, bn, "count" as *u8, 1)
484 if count < 1 { count = 1 }
485 if count > GEN_BATCH_CAP { count = GEN_BATCH_CAP }
486 let samp: *u8 = sys_mmap(64)
487 if go_json_str(body, bn, "sampler" as *u8, samp, 64) <= 0 { samp[0]=101 as u8; samp[1]=117 as u8; samp[2]=108 as u8; samp[3]=101 as u8; samp[4]=114 as u8; samp[5]=0 as u8 }
488
489 // build worker request -- the OpenAI /v1/images/generations endpoint (the path that renders
490 // Z-Image correctly; the A1111 /sdapi/v1/txt2img path returns blank/garbage for this flow model).
491 // The engine applies its tuned defaults for steps/sampler/cfg; the UI's steps/cfg/sampler/negative
492 // are recorded as GENREC metadata (prompt + seed are the load-bearing factors for the CID).
493 // fold the UI's steps/cfg into the prompt as sd_cpp_extra_args (turbo). NOTE: Z-Image is CFG-distilled
494 // (cfg 1.0, single forward pass) -> supplying a negative_prompt forces full CFG = ~6x SLOWER (45s vs 7s,
495 // measured) with no quality gain, so we OMIT the negative here (recorded as GENREC metadata only). Negatives
496 // apply only to non-distilled models at cfg>1 = a future per-model switch.
497 let noneg: *u8 = sys_mmap(4); noneg[0]=0 as u8
498 let pfull: *u8 = sys_mmap(16384)
499 var pfo: i64 = go_cat(pfull, 0, prompt)
500 let gloras: *u8 = sys_mmap(512); go_load_loras(gloras, 512)
501 pfo = go_cat(pfull, pfo, " " as *u8); pfo = go_cat(pfull, pfo, gloras)
502 pfo = go_append_turbo_args(pfull, pfo, steps, cfgs, noneg, seed0)
503 pfull[pfo] = 0 as u8
504 let wreq: *u8 = sys_mmap(16384)
505 var o: i64 = go_cat(wreq, 0, "{\"prompt\":" as *u8)
506 o = go_emit_jstr(wreq, o, pfull)
507 o = go_cat(wreq, o, ",\"n\":" as *u8); o = go_itoa(wreq, o, count)
508 o = go_cat(wreq, o, ",\"size\":\"" as *u8); o = go_itoa(wreq, o, w); o = go_cat(wreq, o, "x" as *u8); o = go_itoa(wreq, o, h); o = go_cat(wreq, o, "\"" as *u8)
509 o = go_cat(wreq, o, ",\"seed\":" as *u8); o = go_itoa(wreq, o, seed0)
510 o = go_cat(wreq, o, ",\"response_format\":\"b64_json\"}" as *u8)
511 let _keepneg: i64 = go_slen(neg)
512 let _keepcfg: i64 = go_slen(cfgs)
513
514 let t0: i64 = sys_now_realtime_sec()
515 let respcap: i64 = 25165824
516 let resp: *u8 = sys_mmap(respcap)
517 // MULTI-WORKER: candidates = [swarm-SSOT gpu-image (knowledge/swarm_nodes.conf, per-request)] +
518 // [argv primary cfg[0..4]] + [cfg[9] EXTRA workers (cfg[10+5i..], each "a b c d port")]. Per
519 // request, pick the first AVAILABLE one (TCP health-check = electronic availability), dispatch, FAILOVER on fail.
520 let wa: *i64 = sys_mmap(8*8) as *i64; let wb: *i64 = sys_mmap(8*8) as *i64; let wc: *i64 = sys_mmap(8*8) as *i64
521 let wd: *i64 = sys_mmap(8*8) as *i64; let wpa: *i64 = sys_mmap(8*8) as *i64
522 var wcount: i64 = go_workers_assemble(cfg, ha, hb, hc, hd, wport, wa, wb, wc, wd, wpa)
523 var rn: i64 = 0 - 1
524 var wi: i64 = 0
525 while wi < wcount {
526 if go_worker_up(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi]) == 1 {
527 let r: i64 = go_worker_dispatch(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi], wreq, o, resp, respcap)
528 if r > 0 { rn = r; wi = wcount } else { wi = wi + 1 }
529 } else { wi = wi + 1 }
530 }
531 if rn <= 0 { go_503(cfd, "no gpu worker available (all in the registry are down)" as *u8); return 0 }
532 let bs: i64 = go_body_start(resp, rn)
533 let bodyp: *u8 = (resp as i64 + bs) as *u8
534 let bodylen: i64 = rn - bs
535
536 let model: *u8 = "z_image_turbo" as *u8
537 let cids: *u8 = sys_mmap(GEN_BATCH_CAP * 80)
538 let stepss: *u8 = sys_mmap(16); go_itoa(stepss, 0, steps)
539 // size ("WxH") now rides the CID canon (debt 1785881333): without it, the same prompt+seed at a
540 // different resolution collided to the SAME cid and overwrote the earlier blob.
541 let sizes: *u8 = sys_mmap(32)
542 var szo: i64 = go_itoa(sizes, 0, w); sizes[szo] = 120 as u8; szo = go_itoa(sizes, szo + 1, h); sizes[szo] = 0 as u8
543 let n: i64 = gp_response(bodyp, bodylen, seed0, model, samp, stepss, genhost, prompt, sizes, pfull, storeprefix, blobdir, sidecar, cids, count)
544 if n < 0 { go_503(cfd, "worker returned no images" as *u8); return 0 }
545 let dt: i64 = (sys_now_realtime_sec() - t0) * 1000
546
547 let out: *u8 = sys_mmap(8192)
548 var oo: i64 = go_cat(out, 0, "{\"count\":" as *u8); oo = go_itoa(out, oo, n)
549 oo = go_cat(out, oo, ",\"ms\":" as *u8); oo = go_itoa(out, oo, dt)
550 oo = go_cat(out, oo, ",\"cids\":[" as *u8)
551 var ci: i64 = 0
552 while ci < n {
553 if ci > 0 { out[oo]=44 as u8; oo=oo+1 }
554 out[oo]=34 as u8; oo=oo+1
555 let cidp: *u8 = (cids as i64 + ci*80) as *u8
556 var cj: i64 = 0
557 while cidp[cj]!=(0 as u8) { out[oo]=cidp[cj]; oo=oo+1; cj=cj+1 }
558 out[oo]=34 as u8; oo=oo+1
559 ci = ci + 1
560 }
561 oo = go_cat(out, oo, "]}" as *u8)
562 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, oo)
563 return 0
564}
565
566func go_atoi(s: *u8) -> i64 { var v: i64=0; var i: i64=0; while s[i]!=(0 as u8){ let c: i64=s[i] as i64; if c<48{return v} if c>57{return v} v=v*10+(c-48); i=i+1 } return v }
567
568// go_chat_dispatch -> EXTRACTED to nx_gen_worker.nx (the GenWorker object)
569// go_load_persona / go_mem_append / go_mem_load_json / go_strip_think -> EXTRACTED to nx_companion_memory.nx
570// (the CompanionMemory object -- see companion_arch.md).
571// go_load_appearance / go_load_loras / go_pick_shot -> EXTRACTED to nx_companion_identity.nx (OO consolidation,
572// behaviour-preserving; the CompanionIdentity object -- see companion_arch.md).
573// case-insensitive: 1 if NUL-term `needle` occurs in hay[0..hlen)
574func go_contains_ci(hay: *u8, hlen: i64, needle: *u8) -> i64 {
575 var nl: i64 = 0; while needle[nl]!=(0 as u8) { nl=nl+1 }
576 if nl==0 { return 0 }
577 var i: i64 = 0
578 while i + nl <= hlen {
579 var j: i64 = 0; var ok: i64 = 1
580 while j < nl {
581 var a: i64 = hay[i+j]&0xff; var b2: i64 = needle[j]&0xff
582 if a>=65 { if a<=90 { a=a+32 } }
583 if b2>=65 { if b2<=90 { b2=b2+32 } }
584 if a!=b2 { ok=0; j=nl } else { j=j+1 }
585 }
586 if ok==1 { return 1 }
587 i=i+1
588 }
589 return 0
590}
591// first integer in NUL-term s (0 if none) -> how many photos she was asked for
592func go_parse_count(s: *u8) -> i64 {
593 var i: i64 = 0
594 while s[i]!=(0 as u8) {
595 let c: i64 = s[i]&0xff
596 if c>=48 { if c<=57 {
597 var v: i64 = 0
598 while s[i]!=(0 as u8) { let d: i64 = s[i]&0xff; if d>=48 { if d<=57 { v=v*10+(d-48); i=i+1 } else { return v } } else { return v } }
599 return v
600 } }
601 i=i+1
602 }
603 return 0
604}
605// go_clamp100 / go_state_* / go_mood_line / go_expr_tokens / go_day_scene -> EXTRACTED to nx_companion_state.nx
606// (the CompanionState cognitive-core object -- see companion_arch.md).
607// go_build_photo_prompt -> EXTRACTED to nx_companion_wardrobe.nx (the CompanionWardrobe object -- see companion_arch.md).
608// POST /api/chat -> Elara. Two modes:
609// SERVER-AUTHORITATIVE (body has "message"): the server owns persona + persistent memory -> builds messages
610// = [persona system] + [last N remembered turns] + [new user msg], dispatches, STORES the turn, so Elara
611// stays in character + remembers ACROSS browser sessions/devices. This is the companion substrate.
612// PASSTHROUGH (body has "messages"): forward the client's array verbatim (back-compat).
613// Worker selection = same registry + TCP health-check + failover as image gen. 503 if every worker is down.
614func go_handle_chat(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 {
615 if bn <= 0 { go_400(cfd, "empty chat body" as *u8); return 0 }
616 let ha: i64 = cfg[0]; let hb: i64 = cfg[1]; let hc: i64 = cfg[2]; let hd: i64 = cfg[3]; let wport: i64 = cfg[4]
617 let wa: *i64 = sys_mmap(8*8) as *i64; let wb: *i64 = sys_mmap(8*8) as *i64; let wc: *i64 = sys_mmap(8*8) as *i64
618 let wd: *i64 = sys_mmap(8*8) as *i64; let wpa: *i64 = sys_mmap(8*8) as *i64
619 var wcount: i64 = go_workers_assemble(cfg, ha, hb, hc, hd, wport, wa, wb, wc, wd, wpa)
620
621 // mode select: "message" (single) -> server-authoritative persona+memory; else passthrough of "messages"
622 let umsg: *u8 = sys_mmap(4096)
623 let umlen: i64 = go_json_str(body, bn, "message" as *u8, umsg, 4096)
624
625 // PHOTO REQUEST ("send me a pic/photo/selfie of you at the beach"): generate image(s) of Elara in the
626 // described scene, ingest to the gallery, return CIDs + a warm ack. Composes the LIVE image-gen pipeline
627 // with chat = the "she sends you pics" companion magic (conversational batch, count parsed from the msg).
628 if umlen > 0 {
629 var isphoto: i64 = 0
630 if go_contains_ci(umsg, umlen, "pic" as *u8)==1 { isphoto=1 }
631 if go_contains_ci(umsg, umlen, "photo" as *u8)==1 { isphoto=1 }
632 if go_contains_ci(umsg, umlen, "selfie" as *u8)==1 { isphoto=1 }
633 if isphoto == 1 {
634 var pc: i64 = go_parse_count(umsg)
635 if pc < 1 { pc = 1 }
636 if pc > 1 { pc = 1 }
637 let pseed: i64 = sys_now_us() & 0x7fffffff
638 let stx: *i64 = sys_mmap(64) as *i64
639 go_state_load(stx)
640 let expr: *u8 = sys_mmap(256)
641 go_expr_tokens(stx, expr)
642 // OCCLUSION-AWARE compiler: identity (anatomy-neutral) + scene + per-zone clothing-OR-bare resolution
643 // (fabric-covers assertion when clothed, bare only when the scene asks) → clothed shots stay clothed,
644 // nude only on request = the controllable wardrobe layer. Then style-variety + realism loras.
645 let pprompt: *u8 = sys_mmap(16384)
646 var ppo: i64 = go_build_photo_prompt(umsg, umlen, expr, pprompt)
647 let pshot: *u8 = sys_mmap(256); go_pick_shot(pshot, 256, pseed)
648 if pshot[0]!=(0 as u8) { ppo = go_cat(pprompt, ppo, ", " as *u8); ppo = go_cat(pprompt, ppo, pshot) }
649 // COHERENCE PREVENTATIVE (render_bug_register #1 = wet_without_context, 40% of bugs): reframe incoherent
650 // standing-water "wet" -> a coherent skin-sheen descriptor BEFORE scoring/rendering (wet-in-shower untouched).
651 // OPT-IN ONLY: compute the suggested fix always, but APPLY it (rewrite what we render) only when the operator
652 // sets elara_coherence.txt=apply. Default = flag-only -> render the user's EXACT words, never silently override.
653 let prepd: *u8 = sys_mmap(16384); let rfired: *i64 = sys_mmap(16) as *i64
654 let rlen: i64 = go_coherence_repair(pprompt, ppo, prepd, rfired)
655 if go_coherence_enabled() == 1 { var rci: i64 = 0; while rci < rlen { pprompt[rci]=prepd[rci]; rci=rci+1 } ppo = rlen; pprompt[ppo]=0 as u8 }
656 else { rfired[0]=0 }
657 // ANTI-BODY-HORROR QC: score the composed (repaired) prompt for anatomy-failure risk (pre-render, no GPU).
658 // Higher = safer; the fired factors say WHY. Surfaced in the response so a bad gen is diagnosable, not mystery.
659 let arfac: *u8 = sys_mmap(512)
660 let arisk: i64 = go_anatomy_risk(pprompt, ppo, arfac)
661 if rfired[0]==1 { var wfo: i64 = go_slen(arfac); wfo = go_cat(arfac, wfo, "wetfix," as *u8); arfac[wfo]=0 as u8 }
662 // MONITOR pillar (render_bug_register): the daemon (elderwesto) appends risk<TAB>factors<TAB>scene so the
663 // rate is trackable over time and nx_fs-readable (bypasses the root-owned sudo-script capture problem).
664 let alog: i64 = sys_openat_append("anatomy_audit.tsv" as *u8, 0x1a4)
665 if alog >= 0 {
666 let ll: *u8 = sys_mmap(2048); var lo: i64 = go_itoa(ll, 0, arisk); ll[lo]=9 as u8; lo=lo+1
667 lo = go_cat(ll, lo, arfac); ll[lo]=9 as u8; lo=lo+1
668 var asi: i64 = 0
669 while umsg[asi]!=(0 as u8) { if asi < 180 { if (umsg[asi]&0xff) >= 32 { ll[lo]=umsg[asi]; lo=lo+1 } } asi=asi+1 }
670 ll[lo]=10 as u8; lo=lo+1
671 sys_write(alog, ll, lo); sys_close(alog)
672 }
673 let ploras: *u8 = sys_mmap(512); go_load_loras(ploras, 512)
674 ppo = go_cat(pprompt, ppo, " " as *u8); ppo = go_cat(pprompt, ppo, ploras)
675 let pcfg: *u8 = sys_mmap(8); let pcn: i64 = go_cat(pcfg, 0, "1.0" as *u8); pcfg[pcn]=0 as u8
676 let pneg: *u8 = sys_mmap(4); pneg[0]=0 as u8
677 // seed INSIDE extra_args (top-level seed is ignored by the engine) so each selfie is a DIFFERENT image
678 ppo = go_append_turbo_args(pprompt, ppo, 8, pcfg, pneg, pseed)
679 pprompt[ppo]=0 as u8
680 let wreqp: *u8 = sys_mmap(16384)
681 var wo: i64 = go_cat(wreqp, 0, "{\"prompt\":" as *u8)
682 wo = go_emit_jstr(wreqp, wo, pprompt)
683 wo = go_cat(wreqp, wo, ",\"n\":" as *u8); wo = go_itoa(wreqp, wo, pc)
684 wo = go_cat(wreqp, wo, ",\"size\":\"" as *u8); wo = go_cat(wreqp, wo, GO_PHOTO_SIZE); wo = go_cat(wreqp, wo, "\",\"seed\":" as *u8); wo = go_itoa(wreqp, wo, pseed)
685 wo = go_cat(wreqp, wo, ",\"response_format\":\"b64_json\"}" as *u8)
686 let pcap: i64 = 25165824
687 let presp: *u8 = sys_mmap(pcap)
688 var prn: i64 = 0 - 1
689 var pwi: i64 = 0
690 while pwi < wcount {
691 if go_worker_up(wa[pwi], wb[pwi], wc[pwi], wd[pwi], wpa[pwi]) == 1 {
692 let pr: i64 = go_worker_dispatch(wa[pwi], wb[pwi], wc[pwi], wd[pwi], wpa[pwi], wreqp, wo, presp, pcap)
693 if pr > 0 { prn = pr; pwi = wcount } else { pwi = pwi + 1 }
694 } else { pwi = pwi + 1 }
695 }
696 if prn <= 0 { go_503(cfd, "no gpu worker available for photos" as *u8); return 0 }
697 let pbs: i64 = go_body_start(presp, prn)
698 let pbody: *u8 = (presp as i64 + pbs) as *u8
699 let pblen: i64 = prn - pbs
700 let pcids: *u8 = sys_mmap(GEN_BATCH_CAP * 80)
701 let psteps: *u8 = sys_mmap(16); go_itoa(psteps, 0, 8)
702 let psamp: *u8 = sys_mmap(16); let pj: i64 = go_cat(psamp, 0, "euler" as *u8); psamp[pj]=0 as u8
703 // SAME const the request above used -- not a mirrored literal (debt 1785882708).
704 let psize: *u8 = sys_mmap(32); let pzi: i64 = go_cat(psize, 0, GO_PHOTO_SIZE); psize[pzi] = 0 as u8
705 let pn: i64 = gp_response(pbody, pblen, pseed, "z_image_turbo" as *u8, psamp, psteps, cfg[8] as *u8, pprompt, psize, pprompt, cfg[5] as *u8, cfg[6] as *u8, cfg[7] as *u8, pcids, pc)
706 go_mem_append("user" as *u8, umsg)
707 if pn > 0 { go_mem_append("assistant" as *u8, "[sent you photos]" as *u8) }
708 let outp: *u8 = sys_mmap(8192)
709 var oo: i64 = go_cat(outp, 0, "{\"choices\":[{\"finish_reason\":\"stop\",\"index\":0,\"message\":{\"role\":\"assistant\",\"content\":\"Here you go, hope you like them \"}}],\"images\":[" as *u8)
710 var ci: i64 = 0
711 while ci < pn {
712 if ci > 0 { outp[oo]=44 as u8; oo=oo+1 }
713 outp[oo]=34 as u8; oo=oo+1
714 let cidp: *u8 = (pcids as i64 + ci*80) as *u8
715 var cj: i64 = 0
716 while cidp[cj]!=(0 as u8) { outp[oo]=cidp[cj]; oo=oo+1; cj=cj+1 }
717 outp[oo]=34 as u8; oo=oo+1
718 ci = ci + 1
719 }
720 oo = go_cat(outp, oo, "],\"anatomy_risk\":" as *u8); oo = go_itoa(outp, oo, arisk)
721 oo = go_cat(outp, oo, ",\"anatomy_factors\":\"" as *u8); oo = go_cat(outp, oo, arfac); oo = go_cat(outp, oo, "\"}" as *u8)
722 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, outp, oo)
723 return 0
724 }
725 }
726
727 var sendbody: *u8 = body
728 var sendlen: i64 = bn
729 var servermode: i64 = 0
730 if umlen > 0 {
731 servermode = 1
732 let stp: *i64 = sys_mmap(64) as *i64
733 go_state_load(stp)
734 let persona: *u8 = sys_mmap(6144)
735 let plen0: i64 = go_load_persona(persona, 4096)
736 let ml: *u8 = sys_mmap(256)
737 go_mood_line(stp, ml)
738 var mpp: i64 = plen0
739 var mmi: i64 = 0
740 while ml[mmi]!=(0 as u8) { persona[mpp]=ml[mmi]; mpp=mpp+1; mmi=mmi+1 }
741 mpp = go_day_scene(persona, mpp)
742 persona[mpp]=0 as u8
743 let wreq: *u8 = sys_mmap(131072)
744 var o2: i64 = go_cat(wreq, 0, "{\"messages\":[{\"role\":\"system\",\"content\":" as *u8)
745 o2 = go_emit_jstr(wreq, o2, persona)
746 o2 = go_cat(wreq, o2, "}" as *u8)
747 o2 = go_mem_load_json(wreq, o2, 32)
748 o2 = go_cat(wreq, o2, ",{\"role\":\"user\",\"content\":" as *u8)
749 o2 = go_emit_jstr(wreq, o2, umsg)
750 o2 = go_cat(wreq, o2, "}],\"max_tokens\":400,\"temperature\":0.85}" as *u8)
751 sendbody = wreq; sendlen = o2
752 }
753
754 // dispatch WITH RETRY: the engine's chat endpoint intermittently returns headers + an EMPTY body (an empty
755 // completion, esp. under a long system prompt / rapid turns) -> retry up to 3x with a short recovery delay
756 // so a transient empty response never surfaces as a 503 to the user.
757 let respcap: i64 = 262144
758 let resp: *u8 = sys_mmap(respcap)
759 var rn: i64 = 0 - 1
760 var bs: i64 = 0
761 var bodylen: i64 = 0
762 var tries: i64 = 0
763 while tries < 3 {
764 rn = 0 - 1
765 var wi: i64 = 0
766 while wi < wcount {
767 if go_worker_up(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi]) == 1 {
768 let r: i64 = go_chat_dispatch(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi], sendbody, sendlen, resp, respcap)
769 if r > 0 { rn = r; wi = wcount } else { wi = wi + 1 }
770 } else { wi = wi + 1 }
771 }
772 if rn > 0 { bs = go_body_start(resp, rn); bodylen = rn - bs } else { bodylen = 0 }
773 if bodylen > 0 { tries = 3 } else { tries = tries + 1; if tries < 3 { sys_sleep_ms(300) } }
774 }
775 if rn <= 0 { go_503(cfd, "no chat worker available (all in the registry are down)" as *u8); return 0 }
776 let bodyp: *u8 = (resp as i64 + bs) as *u8
777 if bodylen <= 0 { go_503(cfd, "chat worker returned no body" as *u8); return 0 }
778 // server-authoritative: strip the think-block, persist BOTH turns (so Elara remembers), return a CLEAN reply
779 if servermode == 1 {
780 let reply: *u8 = sys_mmap(8192)
781 let rlen: i64 = go_json_str(bodyp, bodylen, "content" as *u8, reply, 8192)
782 if rlen > 0 {
783 let clean: *u8 = sys_mmap(8192)
784 go_strip_think(reply, clean, 8192)
785 go_mem_append("user" as *u8, umsg)
786 go_mem_append("assistant" as *u8, clean)
787 let stu: *i64 = sys_mmap(64) as *i64
788 go_state_load(stu)
789 go_state_update(stu, umsg, umlen)
790 go_state_save(stu)
791 let rj: *u8 = sys_mmap(16384)
792 var ro: i64 = go_cat(rj, 0, "{\"choices\":[{\"finish_reason\":\"stop\",\"index\":0,\"message\":{\"role\":\"assistant\",\"content\":" as *u8)
793 ro = go_emit_jstr(rj, ro, clean)
794 ro = go_cat(rj, ro, "}}]}" as *u8)
795 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, rj, ro)
796 return 0
797 }
798 go_mem_append("user" as *u8, umsg)
799 }
800 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, bodyp, bodylen)
801 return 0
802}
803
804
805// --- POST /api/write -- THE WRITE LANE ON THE SAME SURFACE AS IMAGES -------------------------------
806// Body: {"mode":"scenario","prompt":"..."} -> {"mode":..,"register":..,"text":"..."}
807// Reuses go_chat_dispatch (the PROVEN engine path this daemon already uses for chat) and the SAME
808// worker candidate list as image gen, so writing inherits the swarm-SSOT endpoint resolution and the
809// failover for free. One surface now produces images AND prose.
810// ★THE SEAM IS CHECKED HERE TOO, not just in the CLI: an `explicit` register may only run on the
811// `local` lane. A capability reachable over HTTP must carry its own guarantees -- a rule that lives
812// only in a command-line tool is not a rule, it is a habit.
813// plain NUL-terminated compare. go_name_eq is a /mesh/<x>.stl PATH matcher, not this -- using it
814// here was a category error that the arity check caught before it could silently mis-route a mode.
815func go_streq(a: *u8, b: *u8) -> i64 {
816 var i: i64 = 0
817 while a[i] != (0 as u8) { if a[i] != b[i] { return 0 } i = i + 1 }
818 if b[i] != (0 as u8) { return 0 }
819 return 1
820}
821
822const GO_W_PROMPT_CAP: i64 = 8192
823const GO_W_REQ_CAP: i64 = 65536
824const GO_W_RESP_CAP: i64 = 262144
825// SSOT = the seg-store plane (migrated 2026-08-05; the old write_modes.tsv is a tombstone).
826// ABSOLUTE prefix: this daemon's CWD is /volume1/ai/gen, and a relative knowledge/ prefix would
827// resolve into the WRONG TREE -- the exact CWD-artifact class banked estate-wide.
828const GO_WPLANE: *u8 = "/volume1/homes/elderwesto/nishihost/knowledge/store/writemode-"
829
830// find mode row -> register + structure. 1 = found, 0 = unknown, -1 = registry unreadable.
831func go_wmode(mode: *u8, reg: *u8, lane: *u8, structure: *u8) -> i64 {
832 let buf: *u8 = sys_mmap(GO_W_RESP_CAP)
833 let n: i64 = sts_load(GO_WPLANE, buf, GO_W_RESP_CAP)
834 if n <= 0 { return 0 - 1 }
835 var p: i64 = 0
836 while p < n {
837 var e: i64 = n
838 var q: i64 = p
839 var go: i64 = 1
840 while go == 1 {
841 if q >= n { e = n; go = 0 } else { if buf[q] == (10 as u8) { e = q; go = 0 } else { q = q + 1 } }
842 }
843 if e > p { if buf[p] != (35 as u8) {
844 // field 0 = mode name
845 var k: i64 = 0
846 var m: i64 = 1
847 while mode[k] != (0 as u8) {
848 if p + k >= e { m = 0; k = go_slen(mode) } else {
849 if buf[p + k] != mode[k] { m = 0; k = go_slen(mode) } else { k = k + 1 }
850 }
851 }
852 if m == 1 { if p + k < e { if buf[p + k] == (9 as u8) {
853 // walk fields 1,2,3
854 var fp: i64 = p + k + 1
855 var fi: i64 = 1
856 while fi <= 3 {
857 var fe: i64 = fp
858 var g2: i64 = 1
859 while g2 == 1 { if fe >= e { g2 = 0 } else { if buf[fe] == (9 as u8) { g2 = 0 } else { fe = fe + 1 } } }
860 var w: i64 = 0
861 var dst: *u8 = reg
862 if fi == 2 { dst = lane }
863 if fi == 3 { dst = structure }
864 while fp + w < fe { if w < 63 { dst[w] = buf[fp + w] } w = w + 1 }
865 if w > 63 { w = 63 }
866 dst[w] = 0 as u8
867 fp = fe + 1
868 fi = fi + 1
869 }
870 return 1
871 } } }
872 } }
873 p = e + 1
874 }
875 return 0
876}
877
878func go_wsys(structure: *u8, out: *u8) -> i64 {
879 var o: i64 = go_cat(out, 0, "You are a skilled prose writer. Write the piece itself with no preamble and no meta-commentary. " as *u8)
880 if go_streq(structure, "scenario" as *u8) == 1 { o = go_cat(out, o, "Open a scenario the reader can step into: introduce the speaker, establish the situation already in motion, then address the reader directly." as *u8) }
881 else { if go_streq(structure, "scene" as *u8) == 1 { o = go_cat(out, o, "Write a scene with concrete sensory detail; end on a beat that invites what comes next." as *u8) }
882 else { if go_streq(structure, "panel" as *u8) == 1 { o = go_cat(out, o, "Write a page script as numbered PANEL blocks: one line of visual description, then dialogue." as *u8) }
883 else { if go_streq(structure, "imrad" as *u8) == 1 { o = go_cat(out, o, "Use IMRaD structure and be precise." as *u8) }
884 else { if go_streq(structure, "convo" as *u8) == 1 { o = go_cat(out, o, "Write a natural back-and-forth that keeps the topic moving." as *u8) }
885 else { o = go_cat(out, o, "Write clearly and vividly in the form the request implies." as *u8) } } } } }
886 out[o] = 0 as u8
887 return o
888}
889
890// epoch -> decimal into buf at off; returns the new offset. Buffer twin of the fd-writing emitter
891// this file already carries -- needed because the queue job FILENAME must hold the id before any fd
892// exists. Digits gathered LSB-first then emitted in REVERSE: the estate found 211 formatters today
893// whose reverse-emit loop was destroyed, so the idiom is spelled out rather than assumed.
894func go_wq_catn(b: *u8, off: i64, v: i64) -> i64 {
895 var x: i64 = v
896 if x <= 0 { b[off] = 48 as u8; return off + 1 }
897 let t: *u8 = sys_mmap(32)
898 var k: i64 = 0
899 while x > 0 { t[k] = (48 + x % 10) as u8; x = x / 10; k = k + 1 }
900 var o: i64 = off
901 while k > 0 { k = k - 1; b[o] = t[k]; o = o + 1 }
902 return o
903}
904
905func go_handle_write(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 {
906 if bn <= 0 { go_400(cfd, "empty write body -- POST {\\\"mode\\\":\\\"scenario\\\",\\\"prompt\\\":\\\"...\\\"}; modes live on the writemode- plane (nx_write modes)" as *u8); return 0 }
907 let mode: *u8 = sys_mmap(64)
908 if go_json_str(body, bn, "mode" as *u8, mode, 64) <= 0 { go_400(cfd, "write needs a \\\"mode\\\" (scenario, manga, paper, roleplay, ...)" as *u8); return 0 }
909 let prompt: *u8 = sys_mmap(GO_W_PROMPT_CAP)
910 if go_json_str(body, bn, "prompt" as *u8, prompt, GO_W_PROMPT_CAP) <= 0 { go_400(cfd, "write needs a \\\"prompt\\\"" as *u8); return 0 }
911
912 let reg: *u8 = sys_mmap(64)
913 let lane: *u8 = sys_mmap(64)
914 let structure: *u8 = sys_mmap(64)
915 let f: i64 = go_wmode(mode, reg, lane, structure)
916 if f < 0 { go_503(cfd, "writemode- plane unseeded/unreadable -- the plane is the SSOT and nothing is guessed" as *u8); return 0 }
917 if f == 0 { go_400(cfd, "unknown mode -- run nx_write modes (writemode- plane)" as *u8); return 0 }
918 if go_streq(reg, "explicit" as *u8) == 1 {
919 if go_streq(lane, "local" as *u8) == 0 {
920 go_400(cfd, "refused: an explicit register may only run on the local lane (fix the registry row)" as *u8); return 0
921 }
922 }
923
924 let sysp: *u8 = sys_mmap(4096)
925 go_wsys(structure, sysp)
926 let wreq: *u8 = sys_mmap(GO_W_REQ_CAP)
927 var o: i64 = go_cat(wreq, 0, "{\"model\":\"local\",\"max_tokens\":1200,\"messages\":[{\"role\":\"system\",\"content\":" as *u8)
928 o = go_emit_jstr(wreq, o, sysp)
929 o = go_cat(wreq, o, "},{\"role\":\"user\",\"content\":" as *u8)
930 o = go_emit_jstr(wreq, o, prompt)
931 o = go_cat(wreq, o, "}]}" as *u8)
932
933 let ha: i64 = cfg[0]; let hb: i64 = cfg[1]; let hc: i64 = cfg[2]; let hd: i64 = cfg[3]; let wport: i64 = cfg[4]
934 let wa: *i64 = sys_mmap(8*8) as *i64; let wb: *i64 = sys_mmap(8*8) as *i64; let wc: *i64 = sys_mmap(8*8) as *i64
935 let wd: *i64 = sys_mmap(8*8) as *i64; let wpa: *i64 = sys_mmap(8*8) as *i64
936 var wcount: i64 = go_workers_assemble(cfg, ha, hb, hc, hd, wport, wa, wb, wc, wd, wpa)
937 let respcap: i64 = GO_W_RESP_CAP
938 let resp: *u8 = sys_mmap(respcap)
939 var rn: i64 = 0 - 1
940 var wi: i64 = 0
941 while wi < wcount {
942 if go_worker_up(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi]) == 1 {
943 let r: i64 = go_chat_dispatch(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi], wreq, o, resp, respcap)
944 if r > 0 { rn = r; wi = wcount } else { wi = wi + 1 }
945 } else { wi = wi + 1 }
946 }
947 if rn <= 0 {
948 // u2605DEGRADE TO THE QUEUE, NEVER TO A REFUSAL (constitution A15). Off-LAN the GPU cannot be
949 // dialled -- it PULLS. A 503 here refused exactly when the queue is the design answer: bank
950 // the request as a wq job and tell the caller where the result will land. The path is
951 // ABSOLUTE because this daemon runs with CWD=/volume1/ai/gen -- a relative write would bank
952 // the job where no worker looks (the artifacts-never-placed law), and the failure would
953 // wear the shape of a slow worker instead of a wrong path.
954 let ep: i64 = sys_now_realtime_sec()
955 let jp: *u8 = sys_mmap(256)
956 var jo: i64 = go_cat(jp, 0, "/volume1/homes/elderwesto/nishihost/knowledge/wq/wq_" as *u8)
957 jo = go_wq_catn(jp, jo, ep)
958 jo = go_cat(jp, jo, ".job" as *u8)
959 jp[jo] = 0 as u8
960 let jb: *u8 = sys_mmap(GO_W_REQ_CAP)
961 var jn: i64 = go_cat(jb, 0, "{\"mode\":" as *u8)
962 jn = go_emit_jstr(jb, jn, mode)
963 jn = go_cat(jb, jn, ",\"prompt\":" as *u8)
964 jn = go_emit_jstr(jb, jn, prompt)
965 jn = go_cat(jb, jn, "}" as *u8)
966 let jfd: i64 = sys_openat_wr(jp, 0x1a4)
967 if jfd < 0 { go_503(cfd, "no engine AND the queue is unwritable -- both roads closed; check knowledge/wq exists" as *u8); return 0 }
968 sys_write(jfd, jb, jn)
969 sys_close(jfd)
970 let rb: *u8 = sys_mmap(512)
971 var ro: i64 = go_cat(rb, 0, "{\"queued\":1,\"job\":\"wq_" as *u8)
972 ro = go_wq_catn(rb, ro, ep)
973 ro = go_cat(rb, ro, "\",\"result\":\"knowledge/wq/wq_" as *u8)
974 ro = go_wq_catn(rb, ro, ep)
975 ro = go_cat(rb, ro, ".done\",\"note\":\"no engine reachable; job banked for the pull swarm (A15) -- poll the result path\"}" as *u8)
976 go_send(cfd, "202 Accepted" as *u8, "application/json" as *u8, rb, ro)
977 return 0
978 }
979 let bs: i64 = go_body_start(resp, rn)
980 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, (resp as i64 + bs) as *u8, rn - bs)
981 return 0
982}
983
984// --- the 3D lane: POST /api/mesh (t2mesh -> surface-nets -> STL) + GET /mesh/<obj>.stl ---
985// The daemon forks per connection, so the big field/mesh mmaps are reclaimed by the kernel on child
986// exit (same memory discipline as the gallery upscaler) -- no leak in the long-lived parent.
987func go_wfs(fd: i64, s: *u8) -> i64 { var n: i64=0; while s[n]!=(0 as u8){n=n+1} sys_write(fd, s, n); return 0 }
988func go_stlnum(fd: i64, v: i64) -> i64 {
989 let b: *u8 = sys_mmap(32) as *u8
990 var x: i64 = v; var neg: i64 = 0
991 if x < 0 { neg = 1; x = 0 - x }
992 var i: i64 = 31
993 if x == 0 { b[i] = 48 as u8; i = i - 1 }
994 while x > 0 { b[i] = (48 + x % 10) as u8; x = x / 10; i = i - 1 }
995 if neg == 1 { b[i] = 45 as u8; i = i - 1 }
996 sys_write(fd, (b as i64 + i + 1) as *u8, 31 - i); sys_write(fd, " " as *u8, 1); return 0
997}
998func go_write_stl(vbuf: *i64, fbuf: *i64, nf: i64, path: *u8) -> i64 {
999 let fd: i64 = sys_openat_wr(path, 0x1a4)
1000 if fd < 0 { return 0 - 1 }
1001 go_wfs(fd, "solid nishi_t2m\n" as *u8)
1002 var t: i64 = 0
1003 while t < nf {
1004 let a: i64 = fbuf[t * 3]; let b: i64 = fbuf[t * 3 + 1]; let c: i64 = fbuf[t * 3 + 2]
1005 go_wfs(fd, "facet normal 0 0 0\nouter loop\nvertex " as *u8)
1006 go_stlnum(fd, vbuf[a*3]); go_stlnum(fd, vbuf[a*3+1]); go_stlnum(fd, vbuf[a*3+2])
1007 go_wfs(fd, "\nvertex " as *u8)
1008 go_stlnum(fd, vbuf[b*3]); go_stlnum(fd, vbuf[b*3+1]); go_stlnum(fd, vbuf[b*3+2])
1009 go_wfs(fd, "\nvertex " as *u8)
1010 go_stlnum(fd, vbuf[c*3]); go_stlnum(fd, vbuf[c*3+1]); go_stlnum(fd, vbuf[c*3+2])
1011 go_wfs(fd, "\nendloop\nendfacet\n" as *u8)
1012 t = t + 1
1013 }
1014 go_wfs(fd, "endsolid nishi_t2m\n" as *u8); sys_close(fd); return 0
1015}
1016// STL disk path = <blobdir>mesh_<template-name>.stl (blobdir is a PREFIX, same idiom as the blob store)
1017func go_mesh_path(sp: *u8, blobdir: *u8, nm: *u8) -> i64 {
1018 var o: i64 = go_cat(sp, 0, blobdir)
1019 o = go_cat(sp, o, "mesh_" as *u8)
1020 o = go_cat(sp, o, nm)
1021 o = go_cat(sp, o, ".stl" as *u8)
1022 sp[o] = 0 as u8
1023 return o
1024}
1025func go_handle_mesh(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 {
1026 let blobdir: *u8 = cfg[6] as *u8
1027 let prompt: *u8 = sys_mmap(4096)
1028 let pl: i64 = go_json_str(body, bn, "prompt" as *u8, prompt, 4096)
1029 if pl <= 0 { go_400(cfd, "empty prompt" as *u8); return 0 }
1030 let t0: i64 = sys_now_realtime_sec()
1031 let id: i64 = t2m_id_of(prompt)
1032 let nm: *u8 = t2m_name(id)
1033 let base: i64 = sys_mmap(sdf_bytes()) as i64
1034 let F: *i64 = sys_mmap((MG_N + 1) * (MG_N + 1) * (MG_N + 1) * 8) as *i64
1035 let cv: *i64 = sys_mmap(MG_N * MG_N * MG_N * 8) as *i64
1036 let vb: *i64 = sys_mmap(MG_MAXV * 3 * 8) as *i64
1037 let fb: *i64 = sys_mmap(MG_MAXF * 3 * 8) as *i64
1038 let out: *i64 = sys_mmap(16) as *i64
1039 t2m_prompt(base, prompt)
1040 mg_build(base, F, cv, vb, fb, out)
1041 let nv: i64 = out[0]
1042 let nf: i64 = out[1]
1043 var okm: i64 = 1
1044 if nv < 400 { okm = 0 }
1045 if nf < nv * 3 / 2 { okm = 0 }
1046 if nf > nv * 5 / 2 { okm = 0 }
1047 if okm == 0 { go_503(cfd, "mesh emit failed closed-manifold check" as *u8); return 0 }
1048 let sp: *u8 = sys_mmap(1024)
1049 go_mesh_path(sp, blobdir, nm)
1050 if go_write_stl(vb, fb, nf, sp) < 0 { go_503(cfd, "stl write failed" as *u8); return 0 }
1051 let dt: i64 = (sys_now_realtime_sec() - t0) * 1000
1052 let outj: *u8 = sys_mmap(2048)
1053 var oo: i64 = go_cat(outj, 0, "{\"object\":\"" as *u8); oo = go_cat(outj, oo, nm)
1054 oo = go_cat(outj, oo, "\",\"verts\":" as *u8); oo = go_itoa(outj, oo, nv)
1055 oo = go_cat(outj, oo, ",\"tris\":" as *u8); oo = go_itoa(outj, oo, nf)
1056 oo = go_cat(outj, oo, ",\"ms\":" as *u8); oo = go_itoa(outj, oo, dt)
1057 oo = go_cat(outj, oo, ",\"stl\":\"/gen/mesh/" as *u8); oo = go_cat(outj, oo, nm)
1058 oo = go_cat(outj, oo, ".stl\"}" as *u8)
1059 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, outj, oo)
1060 return 0
1061}
1062// exact-match a request /mesh/<x>.stl against a template name (client bytes never build a path)
1063func go_name_eq(path: *u8, plen: i64, nm: *u8) -> i64 {
1064 var nl: i64 = 0
1065 while nm[nl] != (0 as u8) { nl = nl + 1 }
1066 if plen - 6 != nl + 4 { return 0 }
1067 var i: i64 = 0
1068 while i < nl { if (path[6+i]&0xff) != (nm[i]&0xff) { return 0 } i = i + 1 }
1069 if (path[6+nl]&0xff) != 46 { return 0 }
1070 if (path[6+nl+1]&0xff) != 115 { return 0 }
1071 if (path[6+nl+2]&0xff) != 116 { return 0 }
1072 if (path[6+nl+3]&0xff) != 108 { return 0 }
1073 return 1
1074}
1075func go_serve_mesh_file(cfd: i64, path: *u8, plen: i64, blobdir: *u8) -> i64 {
1076 var hit: i64 = 0 - 1
1077 var id: i64 = 0
1078 while id <= 8 {
1079 if go_name_eq(path, plen, t2m_name(id)) == 1 { hit = id; id = 9 } else { id = id + 1 }
1080 }
1081 if hit < 0 { go_send(cfd, "404 Not Found" as *u8, "text/plain" as *u8, "unknown object" as *u8, 14); return 0 }
1082 let sp: *u8 = sys_mmap(1024)
1083 go_mesh_path(sp, blobdir, t2m_name(hit))
1084 let lp: *i64 = sys_mmap(16) as *i64
1085 let stl: *u8 = sys_read_file(sp, lp)
1086 if (stl as i64) == 0 { go_send(cfd, "404 Not Found" as *u8, "text/plain" as *u8, "not generated yet" as *u8, 17); return 0 }
1087 go_send_bin(cfd, "model/stl" as *u8, stl, lp[0])
1088 return 0
1089}
1090
1091// --- PRESENCE: GET /api/state -> the live companion presence panel feed. Reads the neuro-chemical state
1092// + the real-clock day-arc so the frontend can render "how Elara is right now" (mood + what she is doing +
1093// her felt meters). Read-only projection of the SAME state that drives her voice + body; no side effects. ---
1094// short mood LABEL from the neuro-chemical state (the panel headline; mirrors go_mood_line's thresholds)
1095func go_mood_label(st: *i64, out: *u8) -> i64 {
1096 var o: i64 = 0
1097 if st[2] > 60 { o = go_cat(out, 0, "hurt and guarded" as *u8) }
1098 else { if st[3] > 70 { if st[0] > 60 { o = go_cat(out, 0, "deeply in love" as *u8) } else { o = go_cat(out, 0, "warm and affectionate" as *u8) } }
1099 else { if st[1] > 70 { o = go_cat(out, 0, "giddy and playful" as *u8) }
1100 else { o = go_cat(out, 0, "calm and content" as *u8) } } }
1101 out[o]=0 as u8
1102 return o
1103}
1104// short activity phrase from the real clock (Utah MDT = UTC-6); mirrors go_day_scene's hour buckets
1105func go_day_activity(out: *u8) -> i64 {
1106 let epoch: i64 = sys_now_realtime_sec()
1107 var h: i64 = (epoch / 3600) - 6
1108 h = h % 24
1109 if h < 0 { h = h + 24 }
1110 var o: i64 = 0
1111 if h < 5 { o = go_cat(out, 0, "asleep in bed, cozy under the covers" as *u8) }
1112 else { if h < 9 { o = go_cat(out, 0, "sipping coffee in the kitchen, just woke up" as *u8) }
1113 else { if h < 12 { o = go_cat(out, 0, "out at a cafe, running errands" as *u8) }
1114 else { if h < 15 { o = go_cat(out, 0, "relaxing at home, reading" as *u8) }
1115 else { if h < 19 { o = go_cat(out, 0, "cooking and getting ready for the evening" as *u8) }
1116 else { if h < 23 { o = go_cat(out, 0, "winding down on the couch, a little flirty" as *u8) }
1117 else { o = go_cat(out, 0, "in bed in something soft, sleepy" as *u8) } } } } } }
1118 out[o]=0 as u8
1119 return o
1120}
1121func go_serve_state(cfd: i64) -> i64 {
1122 let st: *i64 = sys_mmap(64) as *i64
1123 go_state_load(st)
1124 let mood: *u8 = sys_mmap(64); go_mood_label(st, mood)
1125 let act: *u8 = sys_mmap(256); go_day_activity(act)
1126 let out: *u8 = sys_mmap(1024); var o: i64 = 0
1127 o = go_cat(out, 0, "{\"affection\":" as *u8); o = go_itoa(out, o, st[0])
1128 o = go_cat(out, o, ",\"dopamine\":" as *u8); o = go_itoa(out, o, st[1])
1129 o = go_cat(out, o, ",\"cortisol\":" as *u8); o = go_itoa(out, o, st[2])
1130 o = go_cat(out, o, ",\"oxytocin\":" as *u8); o = go_itoa(out, o, st[3])
1131 o = go_cat(out, o, ",\"mood\":" as *u8); o = go_emit_jstr(out, o, mood)
1132 o = go_cat(out, o, ",\"activity\":" as *u8); o = go_emit_jstr(out, o, act)
1133 o = go_cat(out, o, "}" as *u8)
1134 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, o)
1135 return 0
1136}
1137// serve the rich experiential UI from disk (elara_ui.html, cwd-relative = operator-tunable per Rule 11/17, and
1138// iterable without a rebuild). Fallback to the compact baked UI so a missing/empty file never dark-screens /gen.
1139func go_serve_ui(cfd: i64) -> i64 {
1140 let lp: *i64 = sys_mmap(16) as *i64
1141 let b: *u8 = sys_read_file("elara_ui.html" as *u8, lp)
1142 if (b as i64) != 0 { if lp[0] > 0 {
1143 go_send_bin(cfd, "text/html; charset=utf-8" as *u8, b, lp[0])
1144 return 0
1145 } }
1146 let page: *u8 = sys_mmap(16384)
1147 var po: i64 = go_cat(page, 0, GEN_UI_HTML)
1148 po = go_cat(page, po, GEN_CHAT_HTML)
1149 go_send(cfd, "200 OK" as *u8, "text/html; charset=utf-8" as *u8, page, po)
1150 return 0
1151}
1152
1153// --- ASYNC BATCH (the "send me N pics" capability, edge-timeout-proof): POST /api/batch returns a job id
1154// IMMEDIATELY + forks a detached child that runs the SAME gen path (go_handle_generate, unchanged) writing its
1155// response to batchjob-<id>.json; GET /api/batch/<id> polls that file. So any batch size renders without the 15s
1156// edge timeout. Reuses the sync gen path verbatim (the child passes the job-file fd as the "socket"). ---
1157func go_handle_batch(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 {
1158 let jid: i64 = sys_now_us() & 0x7fffffff
1159 let jp: *u8 = sys_mmap(64); var jo: i64 = go_cat(jp, 0, "batchjob-" as *u8); jo = go_itoa(jp, jo, jid); jo = go_cat(jp, jo, ".json" as *u8); jp[jo]=0 as u8
1160 // create the (empty) job file up front so a poll before completion sees pending, not missing.
1161 let cfd0: i64 = sys_openat_wr(jp, 0x1a4); if cfd0 >= 0 { sys_close(cfd0) }
1162 let pid: i64 = sys_fork()
1163 if pid == 0 {
1164 let ffd: i64 = sys_openat_wr(jp, 0x1a4)
1165 if ffd >= 0 { go_handle_generate(ffd, body, bn, cfg); sys_close(ffd) }
1166 sys_exit(0)
1167 }
1168 let out: *u8 = sys_mmap(128); var oo: i64 = go_cat(out, 0, "{\"job\":\"" as *u8); oo = go_itoa(out, oo, jid); oo = go_cat(out, oo, "\"}" as *u8)
1169 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, oo)
1170 return 0
1171}
1172// GET /api/batch/<jid> -> the finished {count,ms,cids} JSON, or {"done":0} while still rendering / not started.
1173func go_serve_batch(cfd: i64, path: *u8, plen: i64) -> i64 {
1174 let jp: *u8 = sys_mmap(64); var o: i64 = go_cat(jp, 0, "batchjob-" as *u8)
1175 var i: i64 = 11
1176 while i < plen { if o < 58 { jp[o]=path[i]; o=o+1 } i=i+1 }
1177 o = go_cat(jp, o, ".json" as *u8); jp[o]=0 as u8
1178 let lp: *i64 = sys_mmap(16) as *i64
1179 let b: *u8 = sys_read_file(jp, lp)
1180 if (b as i64) == 0 { go_send(cfd, "200 OK" as *u8, "application/json" as *u8, "{\"done\":0}" as *u8, 10); return 0 }
1181 let n: i64 = lp[0]
1182 if n <= 0 { go_send(cfd, "200 OK" as *u8, "application/json" as *u8, "{\"done\":0}" as *u8, 10); return 0 }
1183 let bs: i64 = go_body_start(b, n)
1184 if bs <= 0 { go_send(cfd, "200 OK" as *u8, "application/json" as *u8, "{\"done\":0}" as *u8, 10); return 0 }
1185 let bodyp: *u8 = (b as i64 + bs) as *u8
1186 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, bodyp, n - bs)
1187 return 0
1188}
1189// PNG IHDR dimensions (width @ bytes 16..19, height @ 20..23, big-endian); clamped defaults so a bad header can
1190// never drive a degenerate render request.
1191func go_png_dim(png: *u8, n: i64, wh: *i64) -> i64 {
1192 if n < 24 { wh[0]=512; wh[1]=512; return 0 }
1193 wh[0] = ((png[16]&0xff)<<24)|((png[17]&0xff)<<16)|((png[18]&0xff)<<8)|(png[19]&0xff)
1194 wh[1] = ((png[20]&0xff)<<24)|((png[21]&0xff)<<16)|((png[22]&0xff)<<8)|(png[23]&0xff)
1195 if wh[0] < 64 { wh[0]=512 }
1196 if wh[1] < 64 { wh[1]=512 }
1197 if wh[0] > 2048 { wh[0]=2048 }
1198 if wh[1] > 2048 { wh[1]=2048 }
1199 return 0
1200}
1201// POST /api/img2img -- structure-preserving edit of an EXISTING gallery image (by cid). This is the digital-twin
1202// refine + attribute-change + gallery-integrated edit path: a SMALL request (cid+prompt+denoise) in; the daemon reads
1203// that blob off disk, base64-wraps it as init_images, runs the worker /sdapi/v1/img2img, and ingests the result as a
1204// NEW gallery cid (same gp_response A1111 branch as txt2img). Every error says what to do next (Rule: no bare refusal).
1205func go_handle_img2img(cfd: i64, body: *u8, bn: i64, cfg: *i64) -> i64 {
1206 if bn <= 0 { go_400(cfd, "empty img2img body -- POST {\\\"cid\\\":\\\"<gallery cid>\\\",\\\"prompt\\\":\\\"<edit>\\\",\\\"denoise\\\":0.6}; list cids via GET /api/recent" as *u8); return 0 }
1207 let ha: i64 = cfg[0]; let hb: i64 = cfg[1]; let hc: i64 = cfg[2]; let hd: i64 = cfg[3]; let wport: i64 = cfg[4]
1208 let wa: *i64 = sys_mmap(8*8) as *i64; let wb: *i64 = sys_mmap(8*8) as *i64; let wc: *i64 = sys_mmap(8*8) as *i64
1209 let wd: *i64 = sys_mmap(8*8) as *i64; let wpa: *i64 = sys_mmap(8*8) as *i64
1210 var wcount: i64 = go_workers_assemble(cfg, ha, hb, hc, hd, wport, wa, wb, wc, wd, wpa)
1211
1212 let cidin: *u8 = sys_mmap(128)
1213 let cidlen: i64 = go_json_str(body, bn, "cid" as *u8, cidin, 128)
1214 if cidlen <= 0 { go_400(cfd, "img2img needs a \\\"cid\\\" (an existing gallery image to edit) -- get one from GET /api/recent, or generate first via POST /api/generate" as *u8); return 0 }
1215 let prompt: *u8 = sys_mmap(4096)
1216 let pl: i64 = go_json_str(body, bn, "prompt" as *u8, prompt, 4096)
1217 if pl <= 0 { go_400(cfd, "img2img needs a \\\"prompt\\\" describing the change (e.g. \\\"wearing a blue dress\\\", \\\"golden hour lighting\\\")" as *u8); return 0 }
1218 let dn: *u8 = sys_mmap(16)
1219 if go_json_raw(body, bn, "denoise" as *u8, dn, 16) <= 0 { dn[0]=48 as u8; dn[1]=46 as u8; dn[2]=54 as u8; dn[3]=0 as u8 }
1220 // ⚠THE PHOTO PATH PINS ITS OWN 12 DELIBERATELY and is NOT switched to gen_steps.conf: a
1221 // companion photo is a different quality contract from a generic render, and quietly dropping
1222 // it to the generic default (8) would have DEGRADED it while I was nominally "improving
1223 // configurability". Left explicit, and named here so the next reader knows it is a choice, not
1224 // an oversight. If this should follow the conf too, that is an operator decision with its own
1225 // measurement -- not a side effect of a refactor.
1226 var steps: i64 = go_json_int(body, bn, "steps" as *u8, 12)
1227 if steps < 1 { steps = 12 }
1228 if steps > 40 { steps = 40 }
1229
1230 let sidecar: *u8 = cfg[7] as *u8
1231 let fpath: *u8 = sys_mmap(1024)
1232 if go_sidecar_lookup(sidecar, cidin, cidlen, fpath) < 0 { go_400(cfd, "unknown cid (not in the gallery) -- pick a current one from GET /api/recent" as *u8); return 0 }
1233 let lp: *i64 = sys_mmap(16) as *i64
1234 let png: *u8 = sys_read_file(fpath, lp)
1235 if (png as i64) == 0 { go_503(cfd, "gallery blob missing on disk for that cid -- try another; the sidecar entry may be stale" as *u8); return 0 }
1236 let pnglen: i64 = lp[0]
1237 let wh: *i64 = sys_mmap(16) as *i64
1238 go_png_dim(png, pnglen, wh)
1239
1240 let b64: *u8 = sys_mmap(pnglen * 2 + 64)
1241 let b64len: i64 = gp_b64_encode(png, pnglen, b64)
1242 let wbody: *u8 = sys_mmap(pnglen * 2 + 8192)
1243 var o: i64 = go_cat(wbody, 0, "{\"init_images\":[\"" as *u8)
1244 o = go_catb(wbody, o, b64, b64len)
1245 o = go_cat(wbody, o, "\"],\"prompt\":" as *u8)
1246 o = go_emit_jstr(wbody, o, prompt)
1247 o = go_cat(wbody, o, ",\"denoising_strength\":" as *u8); o = go_cat(wbody, o, dn)
1248 o = go_cat(wbody, o, ",\"steps\":" as *u8); o = go_itoa(wbody, o, steps)
1249 o = go_cat(wbody, o, ",\"cfg_scale\":1.0,\"sampler_name\":\"euler\",\"width\":" as *u8); o = go_itoa(wbody, o, wh[0])
1250 o = go_cat(wbody, o, ",\"height\":" as *u8); o = go_itoa(wbody, o, wh[1])
1251 let seed0: i64 = sys_now_us() & 0x7fffffff
1252 o = go_cat(wbody, o, ",\"seed\":" as *u8); o = go_itoa(wbody, o, seed0)
1253 o = go_cat(wbody, o, "}" as *u8)
1254
1255 let respcap: i64 = 25165824
1256 let resp: *u8 = sys_mmap(respcap)
1257 var rn: i64 = 0 - 1
1258 var wi: i64 = 0
1259 while wi < wcount {
1260 if go_worker_up(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi]) == 1 {
1261 let r: i64 = go_worker_img2img(wa[wi], wb[wi], wc[wi], wd[wi], wpa[wi], wbody, o, resp, respcap)
1262 if r > 0 { rn = r; wi = wcount } else { wi = wi + 1 }
1263 } else { wi = wi + 1 }
1264 }
1265 if rn <= 0 { go_503(cfd, "no gpu worker available for img2img (the render engine is down or busy) -- retry shortly" as *u8); return 0 }
1266 let bs: i64 = go_body_start(resp, rn)
1267 let rbody: *u8 = (resp as i64 + bs) as *u8
1268 let rblen: i64 = rn - bs
1269 let cids: *u8 = sys_mmap(GEN_BATCH_CAP * 80)
1270 let psteps: *u8 = sys_mmap(16); go_itoa(psteps, 0, steps)
1271 let isize: *u8 = sys_mmap(32)
1272 var iso: i64 = go_itoa(isize, 0, wh[0]); isize[iso] = 120 as u8; iso = go_itoa(isize, iso + 1, wh[1]); isize[iso] = 0 as u8
1273 let pn: i64 = gp_response(rbody, rblen, seed0, "z_image_img2img" as *u8, "euler" as *u8, psteps, cfg[8] as *u8, prompt, isize, prompt, cfg[5] as *u8, cfg[6] as *u8, cfg[7] as *u8, cids, 1)
1274 if pn <= 0 { go_503(cfd, "img2img produced no image (engine returned an unexpected response) -- retry, or lower denoise" as *u8); return 0 }
1275 let outp: *u8 = sys_mmap(4096)
1276 var oo: i64 = go_cat(outp, 0, "{\"cids\":[" as *u8)
1277 var ci: i64 = 0
1278 while ci < pn {
1279 if ci > 0 { outp[oo]=44 as u8; oo=oo+1 }
1280 outp[oo]=34 as u8; oo=oo+1
1281 let cidp: *u8 = (cids as i64 + ci*80) as *u8
1282 var cj: i64 = 0
1283 while cidp[cj]!=(0 as u8) { outp[oo]=cidp[cj]; oo=oo+1; cj=cj+1 }
1284 outp[oo]=34 as u8; oo=oo+1
1285 ci = ci + 1
1286 }
1287 oo = go_cat(outp, oo, "],\"count\":" as *u8); oo = go_itoa(outp, oo, pn)
1288 oo = go_cat(outp, oo, ",\"src\":\"" as *u8)
1289 var si: i64 = 0
1290 while si < cidlen { outp[oo]=cidin[si]; oo=oo+1; si=si+1 }
1291 oo = go_cat(outp, oo, "\"}" as *u8)
1292 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, outp, oo)
1293 return 0
1294}
1295// POST /api/anatomy -- PURE QC (no GPU, deterministic): runs the SAME coherence-repair + anatomy-risk the photo path
1296// runs and returns risk + fired factors + wetfix + the repaired prompt. This is the VERIFIABLE QC surface: the nx_gen
1297// MCP tool drives it to prove the live daemon's anti-body-horror QC without a GPU gen (settles the harness-verify gap).
1298func go_handle_anatomy(cfd: i64, body: *u8, bn: i64) -> i64 {
1299 let prompt: *u8 = sys_mmap(8192)
1300 let pl: i64 = go_json_str(body, bn, "prompt" as *u8, prompt, 8192)
1301 if pl <= 0 { go_400(cfd, "anatomy needs a \\\"prompt\\\" to score -- POST {\\\"prompt\\\":\\\"<scene>\\\"}" as *u8); return 0 }
1302 // score the ORIGINAL prompt = the REAL render risk (we do not silently rewrite). Then compute the SUGGESTED fix +
1303 // whether the operator has opted into auto-apply -- honest: a suggestion, not a done deal.
1304 let arfac: *u8 = sys_mmap(512)
1305 let arisk: i64 = go_anatomy_risk(prompt, pl, arfac)
1306 let prepd: *u8 = sys_mmap(8192); let rfired: *i64 = sys_mmap(16) as *i64
1307 let rlen: i64 = go_coherence_repair(prompt, pl, prepd, rfired)
1308 let out: *u8 = sys_mmap(16384); var o: i64 = go_cat(out, 0, "{\"risk\":" as *u8)
1309 o = go_itoa(out, o, arisk)
1310 o = go_cat(out, o, ",\"factors\":\"" as *u8); o = go_cat(out, o, arfac); o = go_cat(out, o, "\"" as *u8)
1311 o = go_cat(out, o, ",\"coherence_apply\":" as *u8); o = go_itoa(out, o, go_coherence_enabled())
1312 o = go_cat(out, o, ",\"wetfix_suggested\":" as *u8); o = go_itoa(out, o, rfired[0])
1313 o = go_cat(out, o, ",\"suggested_prompt\":" as *u8); o = go_emit_jstr(out, o, prepd)
1314 o = go_cat(out, o, "}" as *u8)
1315 go_send(cfd, "200 OK" as *u8, "application/json" as *u8, out, o)
1316 return 0
1317}
1318// handle ONE connection: read request, route, respond. cfg = the worker/paths config array.
1319func go_serve_conn(cfd: i64, cfg: *i64) -> i64 {
1320 sys_set_socket_timeout(cfd, 200)
1321 let req: *u8 = sys_mmap(131072)
1322 let rn: i64 = go_read_full(cfd, req, 131071)
1323 if rn > 0 {
1324 let he: i64 = go_find_seq(req, rn, "\r\n\r\n" as *u8, 4)
1325 var bodyp: *u8 = req; var bnn: i64 = 0
1326 if he >= 0 { bodyp = ((req as i64) + he + 4) as *u8; bnn = rn - he - 4 }
1327 let path: *u8 = sys_mmap(8192)
1328 let plen: i64 = go_reqpath(req, rn, path, 8192)
1329 // FLAT router (a `done` guard, not deep nesting -- extensible + compiler-safe). POST routes match the
1330 // raw request line (method+path); GET routes match the extracted path. Specific prefixes precede "/".
1331 var done: i64 = 0
1332 if go_starts(req, rn, "POST /api/generate" as *u8) == 1 { go_handle_generate(cfd, bodyp, bnn, cfg); done=1 }
1333 if done==0 { if go_starts(req, rn, "POST /api/img2img" as *u8) == 1 { go_handle_img2img(cfd, bodyp, bnn, cfg); done=1 } }
1334 if done==0 { if go_starts(req, rn, "POST /api/anatomy" as *u8) == 1 { go_handle_anatomy(cfd, bodyp, bnn); done=1 } }
1335 if done==0 { if go_starts(req, rn, "POST /api/batch" as *u8) == 1 { go_handle_batch(cfd, bodyp, bnn, cfg); done=1 } }
1336 if done==0 { if go_starts(path, plen, "/api/batch/" as *u8) == 1 { go_serve_batch(cfd, path, plen); done=1 } }
1337 if done==0 { if go_starts(req, rn, "POST /api/chat" as *u8) == 1 { go_handle_chat(cfd, bodyp, bnn, cfg); done=1 } }
1338 if done==0 { if go_starts(req, rn, "POST /api/write" as *u8) == 1 { go_handle_write(cfd, bodyp, bnn, cfg); done=1 } }
1339 if done==0 { if go_starts(req, rn, "POST /api/mesh" as *u8) == 1 { go_handle_mesh(cfd, bodyp, bnn, cfg); done=1 } }
1340 if done==0 { if go_starts(path, plen, "/api/state" as *u8) == 1 { go_serve_state(cfd); done=1 } }
1341 if done==0 { if go_starts(path, plen, "/api/recent" as *u8) == 1 { go_serve_recent(cfd, cfg[7] as *u8, 48); done=1 } }
1342 if done==0 { if go_starts(path, plen, "/mesh/" as *u8) == 1 { go_serve_mesh_file(cfd, path, plen, cfg[6] as *u8); done=1 } }
1343 if done==0 { if go_starts(path, plen, "/img/" as *u8) == 1 { go_serve_img(cfd, path, plen, cfg[7] as *u8); done=1 } }
1344 if done==0 { if go_starts(path, plen, "/health" as *u8) == 1 { go_send(cfd, "200 OK" as *u8, "application/json" as *u8, "{\"ok\":1}" as *u8, 8); done=1 } }
1345 if done==0 { if go_starts(path, plen, "/" as *u8) == 1 { if plen == 1 { go_serve_ui(cfd); done=1 } } }
1346 if done==0 { go_send(cfd, "404 Not Found" as *u8, "text/plain" as *u8, "not found" as *u8, 9) }
1347 }
1348 return 0
1349}