bridge: thin player session with native tools, session logging, result elision, mock-tested
This commit is contained in:
@@ -1 +1,2 @@
|
|||||||
runs/*/db/memory.db
|
runs/*/db/memory.db
|
||||||
|
bridge.json
|
||||||
|
|||||||
@@ -98,8 +98,9 @@ Two interleaved stories calibrate the memory system against itself:
|
|||||||
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
|
||||||
the run's `backdrop.md` and `character.md`, then both ring views, then
|
the run's `backdrop.md` and `character.md`, then both ring views, then
|
||||||
the session transcript. Save its manifest to
|
the session transcript — pasted, or the latest
|
||||||
`runs/<story>/manifests/<window>.json`.
|
`runs/<story>/sessions/*.jsonl` when playing through the bridge. Save
|
||||||
|
its manifest to `runs/<story>/manifests/<window>.json`.
|
||||||
6. **Apply:** `node tool/memory.mjs apply runs/<story>/manifests/<window>.json`
|
6. **Apply:** `node tool/memory.mjs apply runs/<story>/manifests/<window>.json`
|
||||||
— the tool validates, applies, handles overflow, writes the run's
|
— the tool validates, applies, handles overflow, writes the run's
|
||||||
`log/<window>.md`, re-renders the views. A rejected manifest changes
|
`log/<window>.md`, re-renders the views. A rejected manifest changes
|
||||||
@@ -260,15 +261,22 @@ as provenance — exactly what the models were sent — and `log/` +
|
|||||||
The housekeeper may be a different model than the player — cheaper, or more
|
The housekeeper may be a different model than the player — cheaper, or more
|
||||||
pedantic, whatever housekeeping needs. The two prompts are independent.
|
pedantic, whatever housekeeping needs. The two prompts are independent.
|
||||||
|
|
||||||
**Substrate note:** the future SPA is a UI and a session runner wrapped
|
**Substrate:** `tool/bridge.mjs` is the thin bridge — a player session with
|
||||||
around exactly these moving parts — the DB, the manifest, `apply`, `render`.
|
native tools, no UI. It assembles the bundle from the run's files (views
|
||||||
Nothing gets redesigned; the SPA just stops the copy-pasting. Player writes
|
refreshed), offers the player tools (status always; records only when the
|
||||||
become native tool calls (her PC *is* the UI). Query results get elided
|
run's gate allows — the tool list is the capability surface), executes
|
||||||
from history — stubbed as `[consulted the files: r1, r4 — sapphire buyers]`
|
model tool calls against the clerk, logs the full exchange to
|
||||||
— so context stays clean while the housekeeping transcript keeps the
|
`runs/<story>/sessions/<stamp>.jsonl` (the housekeeping transcript), and
|
||||||
attention signal. If player-side status maintenance proves too costly for
|
elides old tool results to stubs in the live context (use-and-discard).
|
||||||
the player-model's attention, the fallback is a dedicated status-keeper
|
Config: copy `bridge.example.json` to `bridge.json` — any OpenAI-compatible
|
||||||
agent reading transcripts — same pattern as the housekeeper, smaller job.
|
endpoint, key via the env var it names. `--mock` runs a scripted fake model
|
||||||
|
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
|
||||||
|
tool-calling part is the smallest component, because the provider does the
|
||||||
|
structured emission and the clerk already speaks function-shaped. If
|
||||||
|
player-side status maintenance proves too costly for the player-model's
|
||||||
|
attention, the fallback is a dedicated status-keeper agent reading
|
||||||
|
transcripts — same pattern as the housekeeper, smaller job.
|
||||||
|
|
||||||
## Layout
|
## Layout
|
||||||
|
|
||||||
@@ -281,11 +289,15 @@ tool/
|
|||||||
revive, file, amend, discard, search, unarchive, set, norm,
|
revive, file, amend, discard, search, unarchive, set, norm,
|
||||||
clear, unset, pick, dump, restore, status
|
clear, unset, pick, dump, restore, status
|
||||||
(--run <name>; --gm for GM writes; --force for migrations)
|
(--run <name>; --gm for GM writes; --force for migrations)
|
||||||
|
bridge.mjs the thin bridge: player session with native tools, session
|
||||||
|
logging, tool-result elision; --mock for a scripted model
|
||||||
|
bridge.example.json copy to bridge.json (gitignored) — endpoint + model + key env
|
||||||
db/
|
db/
|
||||||
schema.sql entries, records, status, events journal (shared)
|
schema.sql entries, records, status, events journal (shared)
|
||||||
runs/
|
runs/
|
||||||
prisoners/ one story: backdrop.md, character.md, seed.json, settings.json,
|
prisoners/ one story: backdrop.md, character.md, seed.json, settings.json,
|
||||||
gm.md (GM-private — never in any bundle), db/, dumps/,
|
gm.md (GM-private — never in any bundle), db/, dumps/,
|
||||||
canon/ (status.md, ring-a.md, ring-b.md), log/, manifests/
|
canon/ (status.md, ring-a.md, ring-b.md), log/, manifests/,
|
||||||
|
sessions/ (bridge transcripts)
|
||||||
boutique/ same shape — records enabled (the shopkeep's PC)
|
boutique/ same shape — records enabled (the shopkeep's PC)
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"baseUrl": "https://api.openai.com/v1",
|
||||||
|
"model": "gpt-4o",
|
||||||
|
"apiKeyEnv": "RP_API_KEY"
|
||||||
|
}
|
||||||
@@ -4,4 +4,4 @@
|
|||||||
|
|
||||||
# Status
|
# Status
|
||||||
|
|
||||||
(nothing set — fresh start)
|
- **mood:** testing the bridge
|
||||||
|
|||||||
@@ -51,4 +51,6 @@ 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 status VALUES ('mood','','testing the bridge','2026-11-11');
|
||||||
|
INSERT INTO events VALUES (1,'pc','status','s:mood','mock turn');
|
||||||
COMMIT;
|
COMMIT;
|
||||||
|
|||||||
+282
@@ -0,0 +1,282 @@
|
|||||||
|
#!/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' } }),
|
||||||
|
];
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const TOOLS = [...STATUS_TOOLS, ...(recordsEnabled() ? RECORD_TOOLS : [])];
|
||||||
|
|
||||||
|
// 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],
|
||||||
|
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'
|
||||||
|
+ ' beats without narrating them. The OOC channel remains for talking to'
|
||||||
|
+ ' the GM: points of order, canon questions, proposals.\n';
|
||||||
|
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') {
|
||||||
|
return { role: 'assistant', content: 'Mock: the tool result is noted. *She settles back against the container, watching the light.* ((mock turn complete))' };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
role: 'assistant',
|
||||||
|
content: null,
|
||||||
|
tool_calls: [{
|
||||||
|
id: `mock-${messages.length}`,
|
||||||
|
type: 'function',
|
||||||
|
function: {
|
||||||
|
name: 'status_set',
|
||||||
|
arguments: JSON.stringify({ key: 'mood', value: 'testing the bridge', reason: 'mock turn' }),
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 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();
|
||||||
+4
-2
@@ -63,6 +63,8 @@ const FORCE = argv.includes('--force');
|
|||||||
for (let i = argv.indexOf('--force'); i !== -1; i = argv.indexOf('--force')) argv.splice(i, 1);
|
for (let i = argv.indexOf('--force'); i !== -1; i = argv.indexOf('--force')) argv.splice(i, 1);
|
||||||
const AS_GM = argv.includes('--gm');
|
const AS_GM = argv.includes('--gm');
|
||||||
for (let i = argv.indexOf('--gm'); i !== -1; i = argv.indexOf('--gm')) argv.splice(i, 1);
|
for (let i = argv.indexOf('--gm'); i !== -1; i = argv.indexOf('--gm')) argv.splice(i, 1);
|
||||||
|
const QUIET = argv.includes('--quiet');
|
||||||
|
for (let i = argv.indexOf('--quiet'); i !== -1; i = argv.indexOf('--quiet')) argv.splice(i, 1);
|
||||||
const [cmd, ...args] = argv;
|
const [cmd, ...args] = argv;
|
||||||
|
|
||||||
function resolveRun() {
|
function resolveRun() {
|
||||||
@@ -199,10 +201,10 @@ function renderStatus(db) {
|
|||||||
function renderAll(db) {
|
function renderAll(db) {
|
||||||
for (const ring of RINGS) {
|
for (const ring of RINGS) {
|
||||||
const { file, count } = renderRing(db, ring);
|
const { file, count } = renderRing(db, ring);
|
||||||
console.log(`${rel(file)} — ${count} entries`);
|
if (!QUIET) console.log(`${rel(file)} — ${count} entries`);
|
||||||
}
|
}
|
||||||
const { file, count } = renderStatus(db);
|
const { file, count } = renderStatus(db);
|
||||||
console.log(`${rel(file)} — ${count} keys`);
|
if (!QUIET) console.log(`${rel(file)} — ${count} keys`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// canonical serialization: id-ordered, one row per line, restorable SQL.
|
// canonical serialization: id-ordered, one row per line, restorable SQL.
|
||||||
|
|||||||
Reference in New Issue
Block a user