2026-11-11 21:14:50 +00:00
#!/usr/bin/env node
// tool/bridge.mjs — the thin bridge: a player session with native tools.
//
// The model never runs anything. The provider returns structured tool-call
// *requests*; this loop executes them against the clerk (memory.mjs) and
// returns the results as messages. Judgment stays prompt-side; caps and
// gates stay in the tool; the loop is plumbing.
//
// usage:
// node tool/bridge.mjs --run <name> needs bridge.json + api key
// node tool/bridge.mjs --run <name> --mock scripted fake model, no key
//
// config: bridge.json (see bridge.example.json) — any OpenAI-compatible
// endpoint. Sessions are logged to runs/<story>/sessions/<stamp>.jsonl —
// that file is the housekeeping transcript.
import fs from 'node:fs' ;
import path from 'node:path' ;
import { fileURLToPath } from 'node:url' ;
import readline from 'node:readline' ;
import { spawnSync } from 'node:child_process' ;
const ROOT = path . resolve ( path . dirname ( fileURLToPath ( import . meta . url )), '..' );
// --- run resolution (same rule as memory.mjs) --------------------------------
const argv = process . argv . slice ( 2 );
const runIdx = argv . indexOf ( '--run' );
const RUN = runIdx !== - 1 ? argv [ runIdx + 1 ] : null ;
if ( ! RUN || ! /^[a-z0-9-]+$/ . test ( RUN )) {
console . error ( 'usage: node tool/bridge.mjs --run <name> [--mock]' );
process . exit ( 1 );
}
const MOCK = argv . includes ( '--mock' );
const RUN_ROOT = path . join ( ROOT , 'runs' , RUN );
// every clerk call goes through the CLI — the clerk stays the one truth
const clerk = (... args ) => {
const res = spawnSync ( 'node' , [ path . join ( ROOT , 'tool' , 'memory.mjs' ), '--run' , RUN , '--quiet' , ... args ], { encoding : 'utf8' });
return {
code : res . status ,
out : ( res . stdout || '' ). trim (),
err : ( res . stderr || '' ). split ( '\n' ). filter (( l ) => ! l . includes ( 'ExperimentalWarning' ) && ! l . includes ( 'trace-warnings' )). join ( '\n' ). trim (),
};
};
// --- the tool manifest: the OOC verbs, transcribed ---------------------------
const T = ( name , description , properties , required ) => ({
type : 'function' ,
function : {
name ,
description ,
parameters : { type : 'object' , properties , required : required ?? Object . keys ( properties ) },
},
});
const STATUS_TOOLS = [
T ( 'status_set' , 'Declare a status excursion — a value leaving its baseline. Ride natural pauses, not every turn.' ,
{ key : { type : 'string' }, value : { type : 'string' }, reason : { type : 'string' , description : 'optional one-line context' } },
[ 'key' , 'value' ]),
T ( 'status_norm' , 'Adopt or shift a baseline. Baseline shifts are character growth.' ,
{ key : { type : 'string' }, baseline : { type : 'string' } }),
T ( 'status_clear' , 'An excursion ends — the value returns to its baseline.' ,
{ key : { type : 'string' } }),
T ( 'status_drop' , 'Remove a field from her paper entirely.' ,
{ key : { type : 'string' } }),
];
2026-11-11 21:26:26 +00:00
const ROLL_TOOL = T ( 'roll' ,
'Flip a coin: pick one of the options at random. For genuinely non-obvious choices, or in-fiction chance she herself controls (a tossed coin, a drawn straw). Randomizes choices, never outcomes — whether an attempt succeeds is the GM\'s to resolve. Commit to the result; do not re-roll.' ,
{ options : { type : 'array' , items : { type : 'string' }, minItems : 2 , description : 'the options, equal weight' } },
[ 'options' ]);
2026-11-11 21:14:50 +00:00
const RECORD_TOOLS = [
T ( 'records_search' , 'Consult her files. Narrow terms — what this beat needs. The result is capped at 10. A miss is a miss: do not rephrase, broaden, or retry this scene.' ,
{ terms : { type : 'array' , items : { type : 'string' }, description : 'all terms must match' } },
[ 'terms' ]),
T ( 'records_file' , 'File a new record at her desk.' ,
{ kind : { type : 'string' }, label : { type : 'string' }, detail : { type : 'string' } }),
T ( 'records_amend' , 'Amend an existing record.' ,
{ rid : { type : 'string' , description : 'record id like r12' }, detail : { type : 'string' } }),
T ( 'records_discard' , 'Discard a record — she throws the card away.' ,
{ rid : { type : 'string' }, reason : { type : 'string' } },
[ 'rid' ]),
];
function recordsEnabled () {
try {
return JSON . parse ( fs . readFileSync ( path . join ( RUN_ROOT , 'settings.json' ), 'utf8' )). records === true ;
} catch {
return false ;
}
}
2026-11-11 21:26:26 +00:00
const TOOLS = [... STATUS_TOOLS , ROLL_TOOL , ...( recordsEnabled () ? RECORD_TOOLS : [])];
2026-11-11 21:14:50 +00:00
// tool name → clerk argv
const DISPATCH = {
status_set : ( a ) => [ 'set' , a . key , a . value , ...( a . reason ? [ a . reason ] : [])],
status_norm : ( a ) => [ 'norm' , a . key , a . baseline ],
status_clear : ( a ) => [ 'clear' , a . key ],
status_drop : ( a ) => [ 'unset' , a . key ],
2026-11-11 21:26:26 +00:00
roll : ( a ) => [ 'pick' , ... a . options ],
2026-11-11 21:14:50 +00:00
records_search : ( a ) => [ 'search' , ... a . terms ],
records_file : ( a ) => [ 'file' , a . kind , a . label , a . detail ?? '' ],
records_amend : ( a ) => [ 'amend' , a . rid , a . detail ],
records_discard : ( a ) => [ 'discard' , a . rid , ...( a . reason ? [ a . reason ] : [])],
};
function runTool ( call ) {
const fn = DISPATCH [ call . function . name ];
if ( ! fn ) return `error: no such tool: ${ call . function . name } ` ;
let args ;
try {
args = JSON . parse ( call . function . arguments || '{}' );
} catch {
return 'error: malformed tool arguments' ;
}
const r = clerk (... fn ( args ));
return r . code === 0 ? ( r . out || '(done)' ) : ( r . err || r . out || 'error: tool failed' );
}
// --- the bundle: assembled from the run's files, views refreshed -------------
function assembleSystem () {
const render = clerk ( 'render' );
if ( render . code !== 0 ) {
console . error ( render . err || 'render failed — is the run initialized?' );
process . exit ( 1 );
}
const parts = [
path . join ( ROOT , 'system.md' ),
path . join ( RUN_ROOT , 'backdrop.md' ),
path . join ( RUN_ROOT , 'character.md' ),
path . join ( RUN_ROOT , 'canon' , 'status.md' ),
path . join ( RUN_ROOT , 'canon' , 'ring-a.md' ),
path . join ( RUN_ROOT , 'canon' , 'ring-b.md' ),
];
let sys = '' ;
for ( const p of parts ) {
if ( ! fs . existsSync ( p )) {
console . error ( `missing bundle file: ${ path . relative ( ROOT , p ) } ` );
process . exit ( 1 );
}
sys += fs . readFileSync ( p , 'utf8' ). trim () + '\n\n' ;
}
sys += '---\n'
+ 'Tool mode: the mechanical verbs described above — status declarations'
+ ' and records work — are available to you as function tools. Prefer the'
+ ' tools over writing the ((...)) lines; tool calls happen between prose'
2026-11-11 21:26:26 +00:00
+ ' beats without narrating them. The roll tool is your coin flip for'
+ ' non-obvious choices — commit to what it returns. The OOC channel'
+ ' remains for talking to the GM: points of order, canon questions,'
+ ' proposals.\n' ;
2026-11-11 21:14:50 +00:00
if ( ! recordsEnabled ()) {
sys += 'There are no records tools: this character keeps no files to consult.\n' ;
}
return sys ;
}
// --- providers ---------------------------------------------------------------
function loadConfig () {
const p = path . join ( ROOT , 'bridge.json' );
if ( ! fs . existsSync ( p )) {
console . error ( 'no bridge.json — copy bridge.example.json and set your key in the env var it names' );
process . exit ( 1 );
}
return JSON . parse ( fs . readFileSync ( p , 'utf8' ));
}
async function callModel ( cfg , messages , tools ) {
const res = await fetch ( ` ${ cfg . baseUrl . replace ( /\/+$/ , '' ) } /chat/completions` , {
method : 'POST' ,
headers : {
'content-type' : 'application/json' ,
authorization : `Bearer ${ process . env [ cfg . apiKeyEnv ?? 'RP_API_KEY' ] ?? '' } ` ,
},
body : JSON . stringify ({ model : cfg . model , messages , tools , tool_choice : 'auto' }),
});
if ( ! res . ok ) {
throw new Error ( `API ${ res . status } : ${ ( await res . text ()). slice ( 0 , 300 ) } ` );
}
const data = await res . json ();
return data . choices [ 0 ]. message ;
}
// mock model: scripted behavior, proves the loop without a key
function mockModel ( messages ) {
const last = messages [ messages . length - 1 ];
if ( last . role === 'tool' ) {
2026-11-11 21:26:26 +00:00
if ( last . content . startsWith ( 'picked:' )) {
return {
role : 'assistant' ,
content : null ,
tool_calls : [{
id : `mock-status- ${ messages . length } ` ,
type : 'function' ,
function : { name : 'status_set' , arguments : JSON . stringify ({ key : 'mood' , value : 'committed to the roll' }) },
}],
};
}
return { role : 'assistant' , content : 'Mock: noted. *She commits to the path the coin chose.*' };
2026-11-11 21:14:50 +00:00
}
return {
role : 'assistant' ,
content : null ,
tool_calls : [{
2026-11-11 21:26:26 +00:00
id : `mock-roll- ${ messages . length } ` ,
2026-11-11 21:14:50 +00:00
type : 'function' ,
2026-11-11 21:26:26 +00:00
function : { name : 'roll' , arguments : JSON . stringify ({ options : [ 'press on to the lighthouse' , 'go back for Dessa' ] }) },
2026-11-11 21:14:50 +00:00
}],
};
}
// --- session log ---------------------------------------------------------
const SESSIONS = path . join ( RUN_ROOT , 'sessions' );
fs . mkdirSync ( SESSIONS , { recursive : true });
const stamp = new Date (). toISOString (). replace ( /[:.]/g , '-' ). slice ( 0 , 19 );
const SESSION_FILE = path . join ( SESSIONS , ` ${ stamp } .jsonl` );
const logMsg = ( m ) => fs . appendFileSync ( SESSION_FILE , JSON . stringify ( m ) + '\n' );
// use-and-discard: old tool results become stubs in the live context,
// while the session log above keeps the full exchange for housekeeping
function pruned ( messages ) {
const toolIdx = [];
messages . forEach (( m , i ) => { if ( m . role === 'tool' ) toolIdx . push ( i ); });
const keep = new Set ( toolIdx . slice ( - 4 ));
return messages . map (( m , i ) =>
m . role === 'tool' && ! keep . has ( i ) ? { ... m , content : '[elided: earlier tool result]' } : m );
}
// --- the loop ------------------------------------------------------------
async function main () {
const cfg = MOCK ? null : loadConfig ();
const system = assembleSystem ();
const messages = [{ role : 'system' , content : system }];
const rl = readline . createInterface ({ input : process . stdin , output : process . stdout });
const ask = () => new Promise (( resolve ) => rl . question ( 'GM> ' , resolve ));
const finish = ( why ) => {
logMsg ({ role : 'system-note' , content : why });
console . log ( `\nsession saved: ${ path . relative ( ROOT , SESSION_FILE ) } ` );
process . exit ( 0 );
};
rl . on ( 'close' , () => finish ( 'session ended (EOF)' ));
console . log ( `bridge: run ' ${ RUN } ' | ${ MOCK ? 'MOCK model' : cfg . model } ` );
console . log ( `tools offered: ${ TOOLS . map (( t ) => t . function . name ). join ( ', ' ) } ` );
console . log ( `session: ${ path . relative ( ROOT , SESSION_FILE ) } ` );
console . log ( '(/quit to end)\n' );
while ( true ) {
const line = await ask ();
if ( line === null || line . trim () === '/quit' ) break ;
if ( ! line . trim ()) continue ;
const user = { role : 'user' , content : line };
messages . push ( user );
logMsg ( user );
while ( true ) {
let msg ;
if ( MOCK ) {
msg = mockModel ( messages );
} else {
try {
msg = await callModel ( cfg , pruned ( messages ), TOOLS );
} catch ( e ) {
console . error ( `bridge: ${ e . message } ` );
messages . pop ();
logMsg ({ role : 'system-note' , content : `error: ${ e . message } ` });
break ;
}
}
messages . push ( msg );
logMsg ( msg );
if ( msg . tool_calls ? . length ) {
if ( msg . content ) console . log ( `\n ${ msg . content } \n` );
for ( const call of msg . tool_calls ) {
const result = runTool ( call );
const tm = { role : 'tool' , tool_call_id : call . id , content : result };
messages . push ( tm );
logMsg ( tm );
console . log ( ` [tool] ${ call . function . name } → ${ result . split ( '\n' )[ 0 ] } ` );
}
continue ; // let the model see the results before ending its turn
}
console . log ( `\n ${ msg . content ?? '(no content)' } \n` );
break ;
}
}
finish ( 'session ended' );
}
main ();