bridge: ask_gm tool, gm answers as tool results, direct apiKey config, line-queue input

This commit is contained in:
2026-11-11 21:33:18 +00:00
parent 9d7273c599
commit f169d92eba
3 changed files with 75 additions and 42 deletions
+64 -35
View File
@@ -72,6 +72,11 @@ const ROLL_TOOL = T('roll',
{ options: { type: 'array', items: { type: 'string' }, minItems: 2, description: 'the options, equal weight' } },
['options']);
const ASK_GM_TOOL = T('ask_gm',
'Talk to the GM out-of-band: points of order, canon questions, proposals (meaningful scope extension — propose before imposing), contradiction flags between canon and play. Ask when a ruling is needed; if the choice is yours to make, make it — do not outsource your judgment. The answer is authoritative.',
{ question: { type: 'string' } },
['question']);
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' } },
@@ -92,7 +97,7 @@ function recordsEnabled() {
return false;
}
}
const TOOLS = [...STATUS_TOOLS, ROLL_TOOL, ...(recordsEnabled() ? RECORD_TOOLS : [])];
const TOOLS = [...STATUS_TOOLS, ROLL_TOOL, ASK_GM_TOOL, ...(recordsEnabled() ? RECORD_TOOLS : [])];
// tool name → clerk argv
const DISPATCH = {
@@ -149,9 +154,10 @@ function assembleSystem() {
+ ' and records work — are available to you as function tools. Prefer the'
+ ' tools over writing the ((...)) lines; tool calls happen between prose'
+ ' 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';
+ ' non-obvious choices — commit to what it returns. When you need the GM'
+ ' — a point of order, a canon question, a proposal, a contradiction'
+ ' flag — call ask_gm; its answer is authoritative. The ((...))'
+ ' convention remains for the GM\'s own messages.\n';
if (!recordsEnabled()) {
sys += 'There are no records tools: this character keeps no files to consult.\n';
}
@@ -174,7 +180,7 @@ async function callModel(cfg, messages, tools) {
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${process.env[cfg.apiKeyEnv ?? 'RP_API_KEY'] ?? ''}`,
authorization: `Bearer ${cfg.apiKey ?? process.env[cfg.apiKeyEnv ?? 'RP_API_KEY'] ?? ''}`,
},
body: JSON.stringify({ model: cfg.model, messages, tools, tool_choice: 'auto' }),
});
@@ -186,31 +192,24 @@ async function callModel(cfg, messages, tools) {
}
// mock model: scripted behavior, proves the loop without a key
// chain: roll → ask_gm → status_set → prose
function mockModel(messages) {
const last = messages[messages.length - 1];
if (last.role === 'tool') {
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.*' };
}
return {
const toolResults = messages.filter((m) => m.role === 'tool').length;
const call = (name, args, id) => ({
role: 'assistant',
content: null,
tool_calls: [{
id: `mock-roll-${messages.length}`,
type: 'function',
function: { name: 'roll', arguments: JSON.stringify({ options: ['press on to the lighthouse', 'go back for Dessa'] }) },
}],
};
tool_calls: [{ id, type: 'function', function: { name, arguments: JSON.stringify(args) } }],
});
if (toolResults === 0) {
return call('roll', { options: ['press on to the lighthouse', 'go back for Dessa'] }, `mock-roll-${messages.length}`);
}
if (toolResults === 1) {
return call('ask_gm', { question: 'From where she stands, is the lighthouse lit?' }, `mock-ask-${messages.length}`);
}
if (toolResults === 2) {
return call('status_set', { key: 'mood', value: 'committed to the ruling' }, `mock-status-${messages.length}`);
}
return { role: 'assistant', content: 'Mock: coin honored, ruling noted. *She moves.*' };
}
// --- session log ---------------------------------------------------------
@@ -223,12 +222,13 @@ 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) {
function pruned(messages, keepIds = new Set()) {
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);
m.role === 'tool' && !keep.has(i) && !keepIds.has(m.tool_call_id)
? { ...m, content: '[elided: earlier tool result]' } : m);
}
// --- the loop ------------------------------------------------------------
@@ -239,22 +239,40 @@ async function main() {
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 pending = [];
let resolveNext = null;
let finished = false;
const finish = (why) => {
if (finished) return;
finished = true;
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)'));
rl.on('line', (line) => {
if (resolveNext) { const r = resolveNext; resolveNext = null; r(line); }
else pending.push(line);
});
rl.on('close', () => {
if (resolveNext) { const r = resolveNext; resolveNext = null; r(undefined); }
finish('session ended (EOF)');
});
const ask = (prompt = 'GM> ') => new Promise((resolve) => {
process.stdout.write(prompt);
if (pending.length) return resolve(pending.shift());
resolveNext = resolve;
});
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');
const askIds = new Set(); // ask_gm answers never elide — rulings must not vanish mid-session
while (true) {
const line = await ask();
if (line === null || line.trim() === '/quit') break;
if (line == null || line.trim() === '/quit') break;
if (!line.trim()) continue;
const user = { role: 'user', content: line };
messages.push(user);
@@ -266,7 +284,7 @@ async function main() {
msg = mockModel(messages);
} else {
try {
msg = await callModel(cfg, pruned(messages), TOOLS);
msg = await callModel(cfg, pruned(messages, askIds), TOOLS);
} catch (e) {
console.error(`bridge: ${e.message}`);
messages.pop();
@@ -280,11 +298,22 @@ async function main() {
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);
let result;
if (call.function.name === 'ask_gm') {
let q = '(no question)';
try { q = JSON.parse(call.function.arguments || '{}').question ?? q; } catch {}
console.log(`\n [ask_gm] ${q}`);
const reply = await ask('GM [ask]> ');
result = (reply ?? '').trim() || '(GM gave no answer)';
askIds.add(call.id);
console.log(' [ask_gm] answered');
} else {
result = runTool(call);
console.log(` [tool] ${call.function.name} → ${result.split('\n')[0]}`);
}
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
}