2026-11-14 03:15:53 +00:00
// server/main.mjs — entry + REST spine.
//
2026-11-14 20:01:15 +00:00
// Synchronous JSON over HTTP; the SPA and curl are both just clients.
// Multiuser: bearer-token identity (users.mjs), ownership gating on
// every mutation and model call, fork for everyone else. Boot-rebuild:
// every run whose latest session was not housekept gets its open
// window back from the jsonl — the log is the truth, the context is a
// view.
2026-11-14 03:15:53 +00:00
//
// usage: node server/main.mjs [--mock]
import fs from 'node:fs' ;
import path from 'node:path' ;
import http from 'node:http' ;
import { fileURLToPath } from 'node:url' ;
import { makeProvider } from './provider.mjs' ;
2026-11-14 20:01:15 +00:00
import { clerkRaw , clerkRawJson , clerkJson , clerk } from './clerk.mjs' ;
2026-11-14 03:15:53 +00:00
import * as bundle from './bundle.mjs' ;
import * as session from './session.mjs' ;
import * as housekeeping from './housekeeping.mjs' ;
2026-11-14 09:04:13 +00:00
import { gmTurn , answerAsk , turn0 , HttpError } from './loop.mjs' ;
2026-11-14 20:01:15 +00:00
import * as users from './users.mjs' ;
import { forkRun } from './fork.mjs' ;
2026-11-14 03:15:53 +00:00
const ROOT = path . resolve ( path . dirname ( fileURLToPath ( import . meta . url )), '..' );
const MOCK = process . argv . includes ( '--mock' );
const CONFIG_PATH = path . join ( ROOT , 'server.json' );
if ( ! fs . existsSync ( CONFIG_PATH )) {
console . error ( 'no server.json — copy server.example.json and set your key in it (or via apiKeyEnv)' );
process . exit ( 1 );
}
const cfg = JSON . parse ( fs . readFileSync ( CONFIG_PATH , 'utf8' ));
const provider = makeProvider ( cfg . endpoint ?? {});
const ctx = { mock : MOCK , cfg , provider , sessions : new Map (), jobs : new Map (), runMeta : bundle . runMeta };
2026-11-14 20:01:15 +00:00
// --- the per-run activity lock ---------------------------------------------------
//
// Serializes every async mutation span (turn, ask, turn0, the
// housekeeping job, fork) so a fork can never torn-copy mid-turn and
// two concurrent turns can never interleave across their awaits.
// Sync-only handlers (paper-set, file writes) need no lock: they
// block the event loop and are atomic by construction.
ctx . locks = new Map ();
ctx . enqueue = ( runId , fn ) => {
const prev = ctx . locks . get ( runId ) ?? Promise . resolve ();
const next = prev . then ( fn , fn ); // run regardless of a prior failure
ctx . locks . set ( runId , next . catch (() => {}));
return next ;
};
// --- bootstrap: the fresh-deployment superuser invite ---------------------------
const boot = users . bootstrap ();
if ( boot ? . code ) {
console . log ( `fresh deployment — the superuser invite (also at ${ path . relative ( ROOT , users . bootstrapFile ) } ):` );
console . log ( ` ${ boot . code } ` );
} else if ( boot ? . reused ) {
console . log ( `fresh deployment — the superuser invite waits at ${ path . relative ( ROOT , users . bootstrapFile ) } ` );
}
2026-11-14 03:15:53 +00:00
// --- boot-rebuild ------------------------------------------------------------
if ( fs . existsSync ( path . join ( ROOT , 'runs' ))) {
for ( const d of fs . readdirSync ( path . join ( ROOT , 'runs' ), { withFileTypes : true })) {
2026-11-14 20:01:15 +00:00
if ( ! d . isDirectory () || d . name . startsWith ( '.' )) continue ; // .staging-* is never a run
2026-11-14 03:15:53 +00:00
if ( ! fs . existsSync ( path . join ( ROOT , 'runs' , d . name , 'run.json' ))) continue ;
const latest = session . latestSession ( d . name );
if ( latest && latest !== session . lastHousekept ( d . name )) {
ctx . sessions . set ( d . name , session . loadSession ( d . name , latest ));
}
}
}
// --- http plumbing -----------------------------------------------------------
const send = ( res , status , body ) => {
const data = JSON . stringify ( body );
res . writeHead ( status , { 'content-type' : 'application/json' , 'content-length' : Buffer . byteLength ( data ) });
res . end ( data );
};
const readBody = ( req ) => new Promise (( resolve , reject ) => {
const chunks = [];
let size = 0 ;
req . on ( 'data' , ( c ) => {
size += c . length ;
if ( size > 1024 * 1024 ) { reject ( new HttpError ( 413 , 'body too large' )); req . destroy (); return ; }
chunks . push ( c );
});
req . on ( 'end' , () => {
if ( ! chunks . length ) return resolve ({});
try { resolve ( JSON . parse ( Buffer . concat ( chunks ). toString ( 'utf8' ))); }
catch { reject ( new HttpError ( 400 , 'body is not valid JSON' )); }
});
req . on ( 'error' , reject );
});
const routes = [];
2026-11-14 20:01:15 +00:00
const route = ( method , pattern , handler , opts = {}) =>
routes . push ({ method , segs : pattern . split ( '/' ). filter ( Boolean ), handler , publicRoute : opts . public === true });
2026-11-14 03:15:53 +00:00
const match = ( method , pathname ) => {
const segs = pathname . split ( '/' ). filter ( Boolean );
outer : for ( const r of routes ) {
if ( r . method !== method || r . segs . length !== segs . length ) continue ;
const params = {};
for ( let i = 0 ; i < segs . length ; i ++ ) {
if ( r . segs [ i ]. startsWith ( ':' )) params [ r . segs [ i ]. slice ( 1 )] = decodeURIComponent ( segs [ i ]);
else if ( r . segs [ i ] !== segs [ i ]) continue outer ;
}
2026-11-14 20:01:15 +00:00
return { handler : r . handler , params , publicRoute : r . publicRoute };
2026-11-14 03:15:53 +00:00
}
return null ;
};
// --- static: the SPA in web/ -----------------------------------------------
// The API lives under /api/*; everything else serves web/ (index.html
// at /). Traversal-guarded; the SPA is a client like curl is.
const WEB_DIR = path . join ( ROOT , 'web' );
const MIME = {
'.html' : 'text/html; charset=utf-8' ,
'.js' : 'text/javascript; charset=utf-8' ,
'.mjs' : 'text/javascript; charset=utf-8' ,
'.css' : 'text/css; charset=utf-8' ,
'.svg' : 'image/svg+xml' ,
'.json' : 'application/json' ,
};
function serveStatic ( pathname , res ) {
let rel = decodeURIComponent ( pathname ). replace ( /^\/+/ , '' );
if ( ! rel ) rel = 'index.html' ;
const file = path . resolve ( WEB_DIR , rel );
if ( ! file . startsWith ( WEB_DIR + path . sep ) || ! fs . existsSync ( file ) || ! fs . statSync ( file ). isFile ()) {
2026-11-14 09:04:13 +00:00
// SPA fallback: client-side routes are extensionless paths —
// serve the shell; anything that looks like a file stays a 404
if ( path . extname ( rel )) { send ( res , 404 , { error : `no such file: ${ rel } ` }); return ; }
const shell = fs . readFileSync ( path . join ( WEB_DIR , 'index.html' ));
res . writeHead ( 200 , { 'content-type' : 'text/html; charset=utf-8' , 'content-length' : shell . length });
res . end ( shell );
2026-11-14 03:15:53 +00:00
return ;
}
const data = fs . readFileSync ( file );
res . writeHead ( 200 , { 'content-type' : MIME [ path . extname ( file )] ?? 'application/octet-stream' , 'content-length' : data . length });
res . end ( data );
}
2026-11-14 20:01:15 +00:00
// --- identity: session, claim, invites, users ---------------------------------
//
// Identity is a bearer token (server/users.mjs). Two routes are
// public: reading your own session (null when signed out) and
// claiming an invite. Everything else — reads included — requires a
// signed-in user: the runs and packages of this deployment are shared
// among invitees, not with the world.
route ( 'GET' , '/api/session' , async ({ user }) => ({
user , // null when signed out or the token is stale
fresh : users . userCount () === 0 ,
}), { public : true });
route ( 'POST' , '/api/claim' , async ({ body }) => {
const r = users . claimInvite ( body . code , body . name );
return { token : r . token , user : r . user };
}, { public : true });
// superuser: mint an invite — the code is returned once, never stored
route ( 'POST' , '/api/invites' , async ({ user }) => {
requireSuperuser ( user );
return users . mintInvite ( user . id );
});
// superuser: the invite ledger, hashes only — codes are never listed
route ( 'GET' , '/api/invites' , async ({ user }) => {
requireSuperuser ( user );
const list = users . listInvites (). map (( i ) => ({
id : i . id ,
kind : i . kind ,
created_at : i . created_at ,
state : i . claimed_by == null ? 'unclaimed' : `claimed by ${ users . userName ( i . claimed_by ) ?? i . claimed_by } ` ,
}));
return { invites : list };
});
// superuser: revoke an unclaimed invite (handed to the wrong chat)
route ( 'DELETE' , '/api/invites/:id' , async ({ params , user }) => {
requireSuperuser ( user );
if ( ! users . revokeInvite ( Number ( params . id ))) throw new HttpError ( 409 , 'no such unclaimed invite' );
return { ok : true };
});
route ( 'GET' , '/api/users' , async ({ user }) => {
requireSuperuser ( user );
return { users : users . listUsers () };
});
// revocation destroys the identity: the token dies with the row. Their
// runs and packages stay on disk untouched — the record of ownership
// keeps its dead id, which resolves to ownerless everywhere it is
// read. Only the live map is reconciled: their open windows close.
route ( 'POST' , '/api/users/:id/revoke' , async ({ params , user }) => {
requireSuperuser ( user );
if ( params . id === user . id ) throw new HttpError ( 409 , 'revoking yourself would lock the deployment out of its superuser' );
if ( ! users . revokeUser ( params . id )) throw new HttpError ( 404 , `no such user: ${ params . id } ` );
for ( const id of [... ctx . sessions . keys ()]) {
if ( bundle . runMeta ( id ) ? . owner === params . id ) ctx . sessions . delete ( id );
}
return { ok : true };
});
function requireSuperuser ( user ) {
if ( ! user ? . superuser ) throw new HttpError ( 403 , 'superuser only' );
}
// ownership is resolved, never maintained: run.json keeps the record
// of who owned a run, and a dead owner id (revocation) resolves to
// absent. The API never exposes a dangling id.
const resolveOwner = ( owner ) => ( owner != null && users . exists ( owner ) ? owner : null );
// ownership: every GM action — every mutation, every model call — is
// the owner's alone. Ownerless runs (pre-user or revoked owner) are
// one uniform state: readable by all, forkable, never re-claimed.
function requireOwner ( user , runId ) {
bundle . requireRun ( runId ); // 404 when it doesn't exist
const meta = bundle . runMeta ( runId ) ?? {};
if ( resolveOwner ( meta . owner ) == null ) {
throw new HttpError ( 403 , `run ' ${ runId } ' is ownerless — fork it to make it yours` );
}
if ( meta . owner !== user . id ) {
throw new HttpError ( 403 , `run ' ${ runId } ' is ${ users . userName ( meta . owner ) ?? 'another user' } 's — fork it to continue as yours` );
}
return meta ;
}
2026-11-14 03:15:53 +00:00
// --- routes -------------------------------------------------------------------
2026-11-14 09:04:13 +00:00
route ( 'GET' , '/api' , async () => ({
service : 'rp-test' , mock : MOCK , openWindows : ctx . sessions . size ,
// the live window inventory — debugging state divergence at a glance
windows : [... ctx . sessions . entries ()]. map (([ id , s ]) => ({ run : id , stamp : s . stamp , fresh : s . fresh , pendingAsk : !! s . pendingAsk })),
}));
2026-11-14 03:15:53 +00:00
route ( 'GET' , '/api/models' , async () => ( MOCK ? [ 'mock' ] : await provider . models ()));
2026-11-14 20:01:15 +00:00
route ( 'GET' , '/api/packages' , async () => {
const pkgs = clerkRawJson ( 'packages' );
for ( const p of pkgs ) {
if ( p . origin === 'user' ) {
p . owner = resolveOwner ( p . owner );
p . ownerName = p . owner == null ? null : users . userName ( p . owner );
}
}
return pkgs ;
});
// save a run's craft as a new user package, published to every user
// (gm.md included — saving is the act of publishing). The pc never
// rides: the next create asks for one.
route ( 'POST' , '/api/packages' , async ({ body , user }) => {
const from = String ( body . from ?? '' ). trim ();
const name = String ( body . name ?? '' ). trim ();
if ( ! from ) throw new HttpError ( 400 , 'from (a run id) is required' );
if ( ! name ) throw new HttpError ( 400 , 'name (the new package\'s display name) is required' );
requireOwner ( user , from );
const r = clerk ( from , '--json' , '--owner' , user . id , 'save-package' , name );
if ( r . code !== 0 ) throw new HttpError ( 400 , r . err || r . out || 'save-package failed' );
return { package : JSON . parse ( r . out ) };
});
2026-11-14 03:15:53 +00:00
2026-11-14 09:04:13 +00:00
// the repo-fed prompts, read-only: per-project opening + guards and
// substrate invariants — never copied into a run, so the editor shows
// them as context, not as something to edit
route ( 'GET' , '/api/prompts' , async () => ({
system : fs . readFileSync ( path . join ( ROOT , 'system.md' ), 'utf8' ). trim (),
invariants : fs . readFileSync ( path . join ( ROOT , 'invariants.md' ), 'utf8' ). trim (),
}));
// the clerk's list, enriched with what the server already knows: the
// open window, the pending ask, and the housekeeping bookkeeping. A
// run with no sessions is a draft — created, never started.
route ( 'GET' , '/api/runs' , async () => {
const runs = clerkRawJson ( 'runs' );
for ( const r of runs ) {
const s = ctx . sessions . get ( r . id );
r . open = !! s ;
r . window = s ? . stamp ?? null ;
r . fresh = s ? . fresh ?? false ;
r . pendingAsk = s ? . pendingAsk ? . question ?? null ;
r . lastSession = session . latestSession ( r . id );
r . lastHousekept = session . lastHousekept ( r . id );
2026-11-14 20:01:15 +00:00
r . owner = resolveOwner ( r . owner );
r . ownerName = r . owner == null ? null : users . userName ( r . owner );
2026-11-14 09:04:13 +00:00
}
return runs ;
});
// create: the pc's name is required (unique per package); the
// package display name defaults to the package's own. The id is
// anonymous, generated by the clerk.
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs' , async ({ body , user }) => {
2026-11-14 03:15:53 +00:00
const pkg = String ( body . package ?? '' ). trim ();
2026-11-14 09:04:13 +00:00
const pc = String ( body . pc ?? '' ). trim ();
2026-11-14 03:15:53 +00:00
if ( ! /^[a-z0-9-]+$/ . test ( pkg )) throw new HttpError ( 400 , 'package must be a slug — see GET /api/packages' );
2026-11-14 09:04:13 +00:00
if ( ! pc ) throw new HttpError ( 400 , 'pc is required — the main character\'s name, distinct per package' );
const name = body . name === undefined ? undefined : String ( body . name );
2026-11-14 20:01:15 +00:00
const r = clerkRaw ( '--json' , '--owner' , user . id , 'create' , pkg , pc , ...( name !== undefined ? [ name ] : []), ...( body . model ? [ String ( body . model )] : []));
2026-11-14 03:15:53 +00:00
if ( r . code !== 0 ) throw new HttpError ( 400 , r . err || r . out || 'create failed' );
2026-11-14 09:04:13 +00:00
const run = JSON . parse ( r . out );
return { run , dir : `runs/ ${ run . id } ` };
});
// a name to play as: rolled from the dictionary, unused by any run
route ( 'GET' , '/api/names' , async () => {
const all = fs . readFileSync ( path . join ( ROOT , 'names-female.txt' ), 'utf8' ). split ( '\n' ). map (( l ) => l . trim ()). filter ( Boolean );
const used = new Set ( clerkRawJson ( 'runs' ). flatMap (( r ) => ( r . pc ? [ String ( r . pc ). toLowerCase ()] : [])));
const free = all . filter (( n ) => ! used . has ( n . toLowerCase ()));
const pool = free . length ? free : all ; // a fully-used dictionary still suggests
return { name : pool [ Math . floor ( Math . random () * pool . length )] };
2026-11-14 03:15:53 +00:00
});
route ( 'GET' , '/api/runs/:id' , async ({ params }) => {
const id = params . id ;
bundle . requireRun ( id );
const st = clerkJson ( id , '--json' , 'status' );
const s = ctx . sessions . get ( id );
const meta = bundle . runMeta ( id );
2026-11-14 20:01:15 +00:00
const owner = resolveOwner ( meta ? . owner );
2026-11-14 03:15:53 +00:00
return {
2026-11-14 20:01:15 +00:00
run : {
id ,
package : meta ? . package ?? null ,
created : meta ? . created ?? null ,
forked : meta ? . forked ?? null ,
owner ,
ownerName : owner == null ? null : users . userName ( owner ),
model : meta ? . model ?? null ,
},
2026-11-14 09:04:13 +00:00
display : bundle . runDisplay ( id ),
2026-11-14 03:15:53 +00:00
open : !! s ,
2026-11-14 09:04:13 +00:00
draft : session . latestSession ( id ) === null ,
lastSession : session . latestSession ( id ),
2026-11-14 03:15:53 +00:00
window : s ? . stamp ?? null ,
fresh : s ? . fresh ?? false ,
paper : st . paper ,
records : st . records ,
fill : st . rings ,
events : st . events ,
pendingAsk : s ? . pendingAsk ? . question ?? null ,
usage : s ? . usage ?? null ,
context : s ? . usage ? {
used : s . usage . promptTokens ,
window : cfg . contextWindow ?? null ,
pct : cfg . contextWindow ? Math . round (( 100 * s . usage . promptTokens ) / cfg . contextWindow ) : null ,
} : null ,
};
});
2026-11-14 09:04:13 +00:00
// --- run files: the editor's surface ------------------------------------------
//
// A fixed whitelist, not a path API: state dirs are the clerk's
// alone. Craft files are writable; housekeeper.md is substrate-
// internal (repo-fed at wrap, never copied, not exposed here) and
// gm.md lives only in the notepad endpoints (the play-view pad);
// config is read-only (vars and lineage are easy to break blind).
// JSON writes are validated before landing.
const RUN_FILES = {
'backdrop.md' : 'rw' ,
'character.md' : 'rw' ,
'turn-0.md' : 'rw' ,
'seed.json' : 'rw' ,
'handbook.md' : 'rw' ,
'settings.json' : 'ro' ,
'run.json' : 'ro' ,
};
route ( 'GET' , '/api/runs/:id/files' , async ({ params }) => {
const dir = bundle . requireRun ( params . id );
const files = {};
for ( const [ f , mode ] of Object . entries ( RUN_FILES )) {
const p = path . join ( dir , f );
files [ f ] = fs . existsSync ( p )
? { mode , exists : true , content : fs . readFileSync ( p , 'utf8' ) }
: { mode , exists : false };
}
return { files };
});
2026-11-14 20:01:15 +00:00
route ( 'PUT' , '/api/runs/:id/files/:path' , async ({ params , body , user }) => {
2026-11-14 09:04:13 +00:00
const dir = bundle . requireRun ( params . id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id );
2026-11-14 09:04:13 +00:00
const f = params . path ;
const mode = RUN_FILES [ f ];
if ( ! mode ) throw new HttpError ( 404 , `no such run file in the API surface: ${ f } ` );
if ( mode !== 'rw' ) throw new HttpError ( 403 , ` ${ f } is read-only` );
if ( typeof body . content !== 'string' || ! body . content . trim ()) throw new HttpError ( 400 , 'content (a non-empty string) is required' );
if ( f . endsWith ( '.json' )) {
try { JSON . parse ( body . content ); } catch { throw new HttpError ( 400 , ` ${ f } rejected: not valid JSON` ); }
}
fs . writeFileSync ( path . join ( dir , f ), body . content );
return { ok : true , file : f , bytes : Buffer . byteLength ( body . content ) };
});
// prompt vars: the inputs the prompts themselves declare ($TOKENS
// found in any prompt file). Values live in the run's settings vars.
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/vars' , async ({ params , body , user }) => {
2026-11-14 09:04:13 +00:00
const dir = bundle . requireRun ( params . id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id );
2026-11-14 09:04:13 +00:00
const vars = body . vars ;
if ( typeof vars !== 'object' || vars === null || Array . isArray ( vars )) throw new HttpError ( 400 , 'vars (an object of token -> value) is required' );
for ( const [ k , v ] of Object . entries ( vars )) {
if ( ! /^[A-Za-z][A-Za-z0-9_]*$/ . test ( k )) throw new HttpError ( 400 , `bad var name: ${ JSON . stringify ( k ) } ` );
if ( typeof v !== 'string' ) throw new HttpError ( 400 , `var ${ k } must be a string` );
}
const settings = bundle . readSettings ( params . id );
settings . vars = { ...( settings . vars ?? {}), ... vars };
fs . writeFileSync ( path . join ( dir , 'settings.json' ), JSON . stringify ( settings , null , 2 ) + '\n' );
return { ok : true , vars : settings . vars };
});
// the GM's notepad: the run's gm.md — always editable in the SPA,
// never in any bundle, never sent to any model (no assembly path
// reads it). Seeded from the package at creation, the GM's to keep.
route ( 'GET' , '/api/runs/:id/notes' , async ({ params }) => {
const dir = bundle . requireRun ( params . id );
const file = path . join ( dir , 'gm.md' );
return { content : fs . existsSync ( file ) ? fs . readFileSync ( file , 'utf8' ) : '' };
});
2026-11-14 20:01:15 +00:00
route ( 'PUT' , '/api/runs/:id/notes' , async ({ params , body , user }) => {
2026-11-14 09:04:13 +00:00
const dir = bundle . requireRun ( params . id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id ); // spectators read the pad, the owner writes it
2026-11-14 09:04:13 +00:00
if ( typeof body . content !== 'string' ) throw new HttpError ( 400 , 'content (a string) is required — empty clears the pad' );
fs . writeFileSync ( path . join ( dir , 'gm.md' ), body . content );
return { ok : true };
});
// delete a DRAFT: a run with no sessions holds nothing but its copy,
// so the directory is the whole run and removal is complete. A played
// run is a story — deleting one is a deliberate act that stays by
// hand (Remove-Item runs/<id>), not a button.
2026-11-14 20:01:15 +00:00
route ( 'DELETE' , '/api/runs/:id' , async ({ params , user }) => {
2026-11-14 09:04:13 +00:00
const dir = bundle . requireRun ( params . id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id );
2026-11-14 09:04:13 +00:00
if ( session . latestSession ( params . id ) !== null ) {
throw new HttpError ( 409 , `this run has been played — its sessions and memory stay until deleted by hand: Remove-Item -Recurse ${ path . join ( 'runs' , params . id ) } ` );
}
fs . rmSync ( dir , { recursive : true , force : true });
return { ok : true , deleted : params . id };
});
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/windows' , async ({ params , body , user }) => {
2026-11-14 03:15:53 +00:00
const id = params . id ;
2026-11-14 20:01:15 +00:00
requireOwner ( user , id );
2026-11-14 03:15:53 +00:00
if ( ctx . sessions . has ( id )) throw new HttpError ( 409 , `a window is already open for ' ${ id } ' — one active window per run` );
const s = session . openWindow ( id , body . override === true );
ctx . sessions . set ( id , s );
return {
window : s . stamp ,
fresh : s . fresh ,
notes : s . lines . filter (( e ) => e . t === 'note' ). map (( e ) => ({ kind : e . kind , ok : e . ok , detail : e . detail })),
};
});
route ( 'GET' , '/api/runs/:id/session' , async ({ params }) => {
const s = ctx . sessions . get ( params . id );
if ( ! s ) throw new HttpError ( 404 , `no open window for ' ${ params . id } '` );
return {
run : params . id ,
window : s . stamp ,
entries : s . lines ,
pendingAsk : s . pendingAsk ? . question ?? null ,
usage : s . usage ,
};
});
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/turn' , async ({ params , body , user }) => {
2026-11-14 03:15:53 +00:00
const line = String ( body . line ?? '' ). trim ();
if ( ! line ) throw new HttpError ( 400 , 'line is required' );
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id );
return { ok : true , ...( await ctx . enqueue ( params . id , () => gmTurn ( ctx , params . id , line , user ))) };
2026-11-14 03:15:53 +00:00
});
2026-11-14 09:04:13 +00:00
// the opening beat as its own action: sent as the first GM turn on a
// fresh window — "start" is this right after window-open
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/turn0' , async ({ params , user }) => {
requireOwner ( user , params . id );
return { ok : true , ...( await ctx . enqueue ( params . id , () => turn0 ( ctx , params . id , user ))) };
});
2026-11-14 09:04:13 +00:00
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/ask' , async ({ params , body , user }) => {
2026-11-14 03:15:53 +00:00
const answer = String ( body . answer ?? '' ). trim ();
if ( ! answer ) throw new HttpError ( 400 , 'answer is required' );
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id );
return { ok : true , ...( await ctx . enqueue ( params . id , () => answerAsk ( ctx , params . id , answer , user ))) };
});
// fork: any user, any run — a mechanical atomic copy with the owner
// replaced (server/fork.mjs). The source's activity lock is held, so
// the copy is never taken mid-turn.
route ( 'POST' , '/api/runs/:id/fork' , async ({ params , user }) => {
bundle . requireRun ( params . id );
return ctx . enqueue ( params . id , () => forkRun ( ctx , params . id , user ));
2026-11-14 03:15:53 +00:00
});
route ( 'GET' , '/api/runs/:id/status' , async ({ params }) => {
bundle . requireRun ( params . id );
const s = ctx . sessions . get ( params . id );
return { paper : clerkJson ( params . id , 'paper' ), conflict : s ? . conflict ?? null };
});
2026-11-14 09:04:13 +00:00
// the GM's out-of-band paper override: whole-paper replace via the
// clerk (which journals the prior state). Descriptions never contain
// commas — the transport is comma-separated — so a comma inside an
// item is a 400, not a silent corruption later.
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/paper' , async ({ params , body , user }) => {
2026-11-14 09:04:13 +00:00
const id = params . id ;
bundle . requireRun ( id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , id );
2026-11-14 09:04:13 +00:00
const items = body . items ;
if ( ! Array . isArray ( items )) throw new HttpError ( 400 , 'items (an array of descriptions) is required — an empty array clears the paper' );
for ( const it of items ) {
if ( typeof it !== 'string' || ! it . trim ()) throw new HttpError ( 400 , 'every item must be a non-empty string' );
if ( it . includes ( ',' )) throw new HttpError ( 400 , `descriptions never contain commas (the transport is comma-separated): ${ JSON . stringify ( it ) } ` );
}
const paper = clerkJson ( id , '--gm' , 'paper-set' , ... items );
return { ok : true , paper };
});
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/housekeeping' , async ({ params , user }) => {
2026-11-14 03:15:53 +00:00
// ends the window and kicks the async chain; poll GET for the outcome
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id );
const job = housekeeping . trigger ( ctx , params . id , user );
2026-11-14 03:15:53 +00:00
return { state : job . state , session : job . session };
});
2026-11-14 09:04:13 +00:00
// dry-run the housekeeper over a session log: the same transcript
// assembly the real wrap uses, a real housekeeper call, the manifest
// saved for review — but nothing applied, no window ended, no state
// touched. The way to iterate on housekeeper.md against real data
// without playing more; works on the open window too.
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/housekeeping/replay' , async ({ params , body , user }) => {
2026-11-14 09:04:13 +00:00
const id = params . id ;
bundle . requireRun ( id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , id ); // a replay spends a model call on the shared key
2026-11-14 09:04:13 +00:00
const stamp = String ( body ? . session ?? '' ). trim () || session . latestSession ( id );
if ( ! stamp ) throw new HttpError ( 409 , 'no session to replay — this run has none' );
let lines ;
try {
lines = session . loadSession ( id , stamp ). lines ;
} catch {
throw new HttpError ( 404 , `no such session: ${ stamp } ` );
}
if ( ! lines . some (( e ) => e . t === 'msg' )) throw new HttpError ( 409 , 'that session has no exchange to review' );
const dir = path . join ( bundle . runDir ( id ), 'manifests' );
fs . mkdirSync ( dir , { recursive : true });
const text = ctx . mock
? housekeeping . mockManifest ( stamp )
2026-11-14 20:01:15 +00:00
: await housekeeping . callHousekeeper ( ctx , id , housekeeping . buildMessages ( id , lines , stamp ), user );
2026-11-14 09:04:13 +00:00
let mf ;
try {
mf = housekeeping . parseManifest ( text );
} catch ( e ) {
const raw = path . join ( dir , ` ${ stamp } .replay.raw.md` );
fs . writeFileSync ( raw , String ( text ));
return { ok : true , parsed : false , session : stamp , file : `manifests/ ${ stamp } .replay.raw.md` , reason : e . message };
}
const file = path . join ( dir , ` ${ stamp } .replay.json` );
fs . writeFileSync ( file , JSON . stringify ( mf , null , 2 ) + '\n' );
return { ok : true , parsed : true , session : stamp , file : `manifests/ ${ stamp } .replay.json` , manifest : mf };
});
2026-11-14 03:15:53 +00:00
route ( 'GET' , '/api/runs/:id/housekeeping' , async ({ params }) => housekeeping . jobState ( ctx , params . id ));
route ( 'GET' , '/api/runs/:id/housekeeping/log' , async ({ params }) => housekeeping . latestLog ( params . id ));
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/housekeeping/apply' , async ({ params , body , user }) => {
2026-11-14 03:15:53 +00:00
// the recovery path: apply a (hand-edited) manifest directly — closes
// any open window, marks the latest session housekept, autorestarts
const id = params . id ;
bundle . requireRun ( id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , id );
2026-11-14 03:15:53 +00:00
const file = String ( body . file ?? '' ). trim ();
if ( ! file ) throw new HttpError ( 400 , 'file is required — a manifest path relative to the run dir, e.g. manifests/<window>.json' );
const manifestPath = path . resolve ( path . join ( ROOT , 'runs' , id ), file );
if ( ! manifestPath . startsWith ( path . join ( ROOT , 'runs' , id ))) throw new HttpError ( 400 , 'file must stay inside the run dir' );
if ( ! fs . existsSync ( manifestPath )) throw new HttpError ( 404 , `no such manifest: ${ file } ` );
const latest = session . latestSession ( id );
if ( ! latest ) throw new HttpError ( 409 , 'no session to mark housekept' );
ctx . sessions . delete ( id ); // housekeeping always ends the window
try {
const next = housekeeping . applyAndRestart ( ctx , id , manifestPath , latest );
return { ok : true , housekept : latest , window : next . stamp };
} catch ( e ) {
const job = { state : 'rejected' , session : latest , reason : e . message };
ctx . jobs . set ( id , job );
throw new HttpError ( 422 , e . message );
}
});
// --- dispatch -------------------------------------------------------------------
2026-11-14 20:01:15 +00:00
// bearer-token identity (users.mjs); null when absent or unknown
function authenticate ( req ) {
const m = /^Bearer\s+(.+)$/i . exec ( req . headers . authorization ?? '' );
return m ? users . getUserByToken ( m [ 1 ]. trim ()) : null ;
}
2026-11-14 03:15:53 +00:00
const server = http . createServer ( async ( req , res ) => {
2026-11-14 09:04:13 +00:00
const started = Date . now ();
2026-11-14 20:01:15 +00:00
let user = null ;
2026-11-14 03:15:53 +00:00
try {
const url = new URL ( req . url , 'http://localhost' );
2026-11-14 09:04:13 +00:00
// the request log: one line per API call — reconstruct any session
2026-11-14 20:01:15 +00:00
// from the console output after the fact; the acting user rides
// every line (attribution, #22)
2026-11-14 09:04:13 +00:00
res . on ( 'finish' , () => {
if ( url . pathname . startsWith ( '/api' )) {
2026-11-14 20:01:15 +00:00
console . log ( ` ${ new Date (). toISOString (). slice ( 11 , 19 ) } ${ req . method } ${ url . pathname } ${ res . statusCode } ${ Date . now () - started } ms ${ user ? ` u: ${ user . id } ` : '' } ` );
2026-11-14 09:04:13 +00:00
}
});
2026-11-14 03:15:53 +00:00
if ( ! url . pathname . startsWith ( '/api' )) {
if ( req . method !== 'GET' ) throw new HttpError ( 405 , 'static files are GET-only' );
serveStatic ( url . pathname , res );
return ;
}
const m = match ( req . method , url . pathname );
if ( ! m ) throw new HttpError ( 404 , `no such route: ${ req . method } ${ url . pathname } ` );
const body = ( req . method === 'POST' || req . method === 'PUT' ) ? await readBody ( req ) : {};
2026-11-14 20:01:15 +00:00
user = authenticate ( req );
if ( ! m . publicRoute && ! user ) throw new HttpError ( 401 , 'not signed in — claim an invite first (POST /api/claim)' );
send ( res , 200 , await m . handler ({ params : m . params , body , req , user }));
2026-11-14 03:15:53 +00:00
} catch ( e ) {
const status = e . status ?? 500 ;
if ( status >= 500 ) console . error ( `server: ${ e . stack ?? e . message } ` );
send ( res , status , { error : e . message , ...( e . detail ? { detail : e . detail } : {}) });
}
});
const [ host , port ] = String ( cfg . bind ?? '127.0.0.1:7350' ). split ( ':' );
server . listen ( Number ( port ), host , () => {
console . log ( `rp-test server: http:// ${ host } : ${ port } | ${ MOCK ? 'MOCK model' : cfg . models ? . player } | ${ ctx . sessions . size } window(s) rebuilt` );
});