bridge: ask_gm tool, gm answers as tool results, direct apiKey config, line-queue input
This commit is contained in:
@@ -93,7 +93,9 @@ Two interleaved stories calibrate the memory system against itself:
|
|||||||
record work (`((q:))`, `((file:))`, `((amend:))`, `((discard:))`) to
|
record work (`((q:))`, `((file:))`, `((amend:))`, `((discard:))`) to
|
||||||
`search`/`file`/`amend`/`discard` — `--gm` marks GM-authorized writes.
|
`search`/`file`/`amend`/`discard` — `--gm` marks GM-authorized writes.
|
||||||
The full play protocol — format, one-thing-per-turn, thoughts off the
|
The full play protocol — format, one-thing-per-turn, thoughts off the
|
||||||
page, intent-form, immersion over realism — lives in `system.md`.
|
page, intent-form, immersion over realism — lives in `system.md`. In
|
||||||
|
bridge mode, the model's OOC is the `ask_gm` tool; the GM's own OOC
|
||||||
|
stays `((...))` in their turns.
|
||||||
4. **Close a window:** just stop. No in-band ritual; the player-model has no
|
4. **Close a window:** just stop. No in-band ritual; the player-model has no
|
||||||
end-of-session duties.
|
end-of-session duties.
|
||||||
5. **Housekeep (fresh model, new context):** send `housekeeper.md`, then
|
5. **Housekeep (fresh model, new context):** send `housekeeper.md`, then
|
||||||
@@ -263,14 +265,18 @@ pedantic, whatever housekeeping needs. The two prompts are independent.
|
|||||||
|
|
||||||
**Substrate:** `tool/bridge.mjs` is the thin bridge — a player session with
|
**Substrate:** `tool/bridge.mjs` is the thin bridge — a player session with
|
||||||
native tools, no UI. It assembles the bundle from the run's files (views
|
native tools, no UI. It assembles the bundle from the run's files (views
|
||||||
refreshed), offers the player tools (status and a coin-flip roll always;
|
refreshed), offers the player tools (status, a coin-flip roll, and ask_gm
|
||||||
records only when the run's gate allows — the tool list is the capability
|
always; records only when the run's gate allows — the tool list is the
|
||||||
surface), executes
|
capability surface), executes
|
||||||
model tool calls against the clerk, logs the full exchange to
|
model tool calls against the clerk, logs the full exchange to
|
||||||
`runs/<story>/sessions/<stamp>.jsonl` (the housekeeping transcript), and
|
`runs/<story>/sessions/<stamp>.jsonl` (the housekeeping transcript), and
|
||||||
elides old tool results to stubs in the live context (use-and-discard).
|
elides old tool results to stubs in the live context (use-and-discard).
|
||||||
|
Model-initiated OOC is the `ask_gm` tool: the GM types the reply as the
|
||||||
|
tool result, so the prose channel stays pure fiction — and ask_gm answers
|
||||||
|
are exempt from elision, because a ruling must not vanish mid-session.
|
||||||
Config: copy `bridge.example.json` to `bridge.json` — any OpenAI-compatible
|
Config: copy `bridge.example.json` to `bridge.json` — any OpenAI-compatible
|
||||||
endpoint, key via the env var it names. `--mock` runs a scripted fake model
|
endpoint; put the key in the `apiKey` field (bridge.json is gitignored) or
|
||||||
|
name an env var via `apiKeyEnv`. `--mock` runs a scripted fake model
|
||||||
that proves the loop without a key. The SPA is the bridge plus a
|
that proves the loop without a key. The SPA is the bridge plus a
|
||||||
fiction-first UI, a GM console, and the housekeeping job runner — and the
|
fiction-first UI, a GM console, and the housekeeping job runner — and the
|
||||||
tool-calling part is the smallest component, because the provider does the
|
tool-calling part is the smallest component, because the provider does the
|
||||||
|
|||||||
@@ -51,6 +51,4 @@ CREATE TABLE IF NOT EXISTS events (
|
|||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS events_window ON events (window);
|
CREATE INDEX IF NOT EXISTS events_window ON events (window);
|
||||||
BEGIN TRANSACTION;
|
BEGIN TRANSACTION;
|
||||||
INSERT INTO events VALUES (1,'pc','status','s:mood','excursion declared');
|
|
||||||
INSERT INTO events VALUES (2,'pc','status','s:mood','field dropped');
|
|
||||||
COMMIT;
|
COMMIT;
|
||||||
|
|||||||
+64
-35
@@ -72,6 +72,11 @@ const ROLL_TOOL = T('roll',
|
|||||||
{ options: { type: 'array', items: { type: 'string' }, minItems: 2, description: 'the options, equal weight' } },
|
{ options: { type: 'array', items: { type: 'string' }, minItems: 2, description: 'the options, equal weight' } },
|
||||||
['options']);
|
['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 = [
|
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.',
|
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: { type: 'array', items: { type: 'string' }, description: 'all terms must match' } },
|
||||||
@@ -92,7 +97,7 @@ function recordsEnabled() {
|
|||||||
return false;
|
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
|
// tool name → clerk argv
|
||||||
const DISPATCH = {
|
const DISPATCH = {
|
||||||
@@ -149,9 +154,10 @@ function assembleSystem() {
|
|||||||
+ ' and records work — are available to you as function tools. Prefer the'
|
+ ' and records work — are available to you as function tools. Prefer the'
|
||||||
+ ' tools over writing the ((...)) lines; tool calls happen between prose'
|
+ ' tools over writing the ((...)) lines; tool calls happen between prose'
|
||||||
+ ' beats without narrating them. The roll tool is your coin flip for'
|
+ ' beats without narrating them. The roll tool is your coin flip for'
|
||||||
+ ' non-obvious choices — commit to what it returns. The OOC channel'
|
+ ' non-obvious choices — commit to what it returns. When you need the GM'
|
||||||
+ ' remains for talking to the GM: points of order, canon questions,'
|
+ ' — a point of order, a canon question, a proposal, a contradiction'
|
||||||
+ ' proposals.\n';
|
+ ' flag — call ask_gm; its answer is authoritative. The ((...))'
|
||||||
|
+ ' convention remains for the GM\'s own messages.\n';
|
||||||
if (!recordsEnabled()) {
|
if (!recordsEnabled()) {
|
||||||
sys += 'There are no records tools: this character keeps no files to consult.\n';
|
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',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'content-type': 'application/json',
|
'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' }),
|
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
|
// mock model: scripted behavior, proves the loop without a key
|
||||||
|
// chain: roll → ask_gm → status_set → prose
|
||||||
function mockModel(messages) {
|
function mockModel(messages) {
|
||||||
const last = messages[messages.length - 1];
|
const toolResults = messages.filter((m) => m.role === 'tool').length;
|
||||||
if (last.role === 'tool') {
|
const call = (name, args, id) => ({
|
||||||
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 {
|
|
||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
content: null,
|
content: null,
|
||||||
tool_calls: [{
|
tool_calls: [{ id, type: 'function', function: { name, arguments: JSON.stringify(args) } }],
|
||||||
id: `mock-roll-${messages.length}`,
|
});
|
||||||
type: 'function',
|
if (toolResults === 0) {
|
||||||
function: { name: 'roll', arguments: JSON.stringify({ options: ['press on to the lighthouse', 'go back for Dessa'] }) },
|
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 ---------------------------------------------------------
|
// --- 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,
|
// use-and-discard: old tool results become stubs in the live context,
|
||||||
// while the session log above keeps the full exchange for housekeeping
|
// while the session log above keeps the full exchange for housekeeping
|
||||||
function pruned(messages) {
|
function pruned(messages, keepIds = new Set()) {
|
||||||
const toolIdx = [];
|
const toolIdx = [];
|
||||||
messages.forEach((m, i) => { if (m.role === 'tool') toolIdx.push(i); });
|
messages.forEach((m, i) => { if (m.role === 'tool') toolIdx.push(i); });
|
||||||
const keep = new Set(toolIdx.slice(-4));
|
const keep = new Set(toolIdx.slice(-4));
|
||||||
return messages.map((m, i) =>
|
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 ------------------------------------------------------------
|
// --- the loop ------------------------------------------------------------
|
||||||
@@ -239,22 +239,40 @@ async function main() {
|
|||||||
const messages = [{ role: 'system', content: system }];
|
const messages = [{ role: 'system', content: system }];
|
||||||
|
|
||||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
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) => {
|
const finish = (why) => {
|
||||||
|
if (finished) return;
|
||||||
|
finished = true;
|
||||||
logMsg({ role: 'system-note', content: why });
|
logMsg({ role: 'system-note', content: why });
|
||||||
console.log(`\nsession saved: ${path.relative(ROOT, SESSION_FILE)}`);
|
console.log(`\nsession saved: ${path.relative(ROOT, SESSION_FILE)}`);
|
||||||
process.exit(0);
|
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(`bridge: run '${RUN}' | ${MOCK ? 'MOCK model' : cfg.model}`);
|
||||||
console.log(`tools offered: ${TOOLS.map((t) => t.function.name).join(', ')}`);
|
console.log(`tools offered: ${TOOLS.map((t) => t.function.name).join(', ')}`);
|
||||||
console.log(`session: ${path.relative(ROOT, SESSION_FILE)}`);
|
console.log(`session: ${path.relative(ROOT, SESSION_FILE)}`);
|
||||||
console.log('(/quit to end)\n');
|
console.log('(/quit to end)\n');
|
||||||
|
|
||||||
|
const askIds = new Set(); // ask_gm answers never elide — rulings must not vanish mid-session
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
const line = await ask();
|
const line = await ask();
|
||||||
if (line === null || line.trim() === '/quit') break;
|
if (line == null || line.trim() === '/quit') break;
|
||||||
if (!line.trim()) continue;
|
if (!line.trim()) continue;
|
||||||
const user = { role: 'user', content: line };
|
const user = { role: 'user', content: line };
|
||||||
messages.push(user);
|
messages.push(user);
|
||||||
@@ -266,7 +284,7 @@ async function main() {
|
|||||||
msg = mockModel(messages);
|
msg = mockModel(messages);
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
msg = await callModel(cfg, pruned(messages), TOOLS);
|
msg = await callModel(cfg, pruned(messages, askIds), TOOLS);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(`bridge: ${e.message}`);
|
console.error(`bridge: ${e.message}`);
|
||||||
messages.pop();
|
messages.pop();
|
||||||
@@ -280,11 +298,22 @@ async function main() {
|
|||||||
if (msg.tool_calls?.length) {
|
if (msg.tool_calls?.length) {
|
||||||
if (msg.content) console.log(`\n${msg.content}\n`);
|
if (msg.content) console.log(`\n${msg.content}\n`);
|
||||||
for (const call of msg.tool_calls) {
|
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 };
|
const tm = { role: 'tool', tool_call_id: call.id, content: result };
|
||||||
messages.push(tm);
|
messages.push(tm);
|
||||||
logMsg(tm);
|
logMsg(tm);
|
||||||
console.log(` [tool] ${call.function.name} → ${result.split('\n')[0]}`);
|
|
||||||
}
|
}
|
||||||
continue; // let the model see the results before ending its turn
|
continue; // let the model see the results before ending its turn
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user