#!/usr/bin/env node /** * @file ask-client: the box's side of a conversation with the brain, through its ask capability. * usage: ask-client.js URL CONVERSATION < question.txt * prints JSON lines: {"say": "..."} for each thing the brain says meanwhile, * then, if the brain changed the volume, {"louder": N} (percentage points; negative is softer), * then {"reply": "...", "end": false}; end is true when the brain ends the conversation. * usage: ask-client.js URL CONVERSATION end * tells the brain the conversation is over. * The key is in $CREDENTIALS_DIRECTORY/ask-key (systemd LoadCredential), not argv, where ps would show it. */ import { newWebSocketRpcSession } from 'capnweb'; import { readFile } from 'node:fs/promises'; import process from 'node:process'; import { text } from 'node:stream/consumers'; /** * Ask the brain at URL the question on stdin, or tell it the conversation is over. * * @param {object} [io] what it reaches; the process's own, by default * @param {string[]} [io.argv] URL CONVERSATION [end] * @param {Record} [io.env] for CREDENTIALS_DIRECTORY * @param {typeof readFile} [io.read] reads the key * @param {AsyncIterable} [io.stdin] the question * @param {{ write(s: string): unknown }} [io.stdout] the answer goes here, as JSON lines * @param {typeof newWebSocketRpcSession} [io.connect] opens a session with the gate at URL */ const main = async ({ argv = process.argv.slice(2), env = process.env, read = readFile, stdin = process.stdin, stdout = process.stdout, connect = newWebSocketRpcSession, } = {}) => { const [url, conversation, verb] = argv; const key = (await read(`${env.CREDENTIALS_DIRECTORY}/ask-key`, 'utf8')).trim(); /** @param {object} obj */ const line = (obj) => stdout.write(`${JSON.stringify(obj)}\n`); const gate = connect(url); try { const asker = gate.open(key); if (verb === 'end') { await asker.end(conversation); return; } const question = (await text(stdin)).trim(); // Cap'n Web passes the function by reference: the brain calls it back over this session. const { text: reply, end, louder } = await asker.ask(question, conversation, (/** @type {string} */ said) => { line({ say: said }); }); if (louder) line({ louder }); line({ reply, end }); } finally { gate[Symbol.dispose](); } }; main().catch((err) => { console.error(`ask-client: ${err.message ?? err}`); process.exitCode = 1; });