Files
Tommi Kyntola 1ea27f1eec Dictate op: one recording aimed at one pane
Driving, with the airc viewer on the car screen: an agent's input box is
visible and what you want to give it is a PROMPT, a sentence, not a keypress.
airc's buttons cover keypresses well and the Android app has IME dictation, but
the car browser has no dictation at all — so today a prompt means the laptop
keyboard. dais already transcribes locally and pastes into a tmux pane; what
was missing is a way to say "record now, and deliver it to the pane I am
looking at" without touching the laptop.

    {"op":"dictate","action":"toggle","pane":"%19"}

start | stop | discard | toggle, the last resolved against the CURRENT mode so
a client that missed a poll — or a latch someone started at the desk — cannot
be inverted by a stale button. stop TRANSCRIBES and discard throws the
recording away, which is the existing latch-vs-voice-off rule and what makes a
remote ✕ useful: a misheard prompt can be dropped instead of typed. Omit the
pane and it is F10 over the socket.

The pane is an ephemeral override (:dictate-target), never a slot. transition!
persists on any :targets/:active-slot change, so writing a slot would churn
targets.edn and the digits addressed by voice; a reserved slot is worse, since
load-targets honors the overlay only while (get targets active-slot) is truthy
and a dangling active-slot silently discards every persisted target on the next
start. save-targets! writes only :targets/:active-slot, so nothing a car-side
tap aims at can survive a restart — asserted by a test rather than by new code.

Two orderings are load-bearing, and both are the opposite of the obvious one:

- The override is set in the same transition as the mode change and AFTER it.
  Every mic OPEN drops a pending override (drop-override), which is exactly
  what keeps a forgotten one from stealing a later utterance — so setting the
  aim first would erase it.
- It is consumed after dispatch, not before, and only when the plan actually
  DELIVERED. :armed is cleared before dispatch for the opposite reason; copying
  that placement here would deliver to the slot instead. An utterance the
  confidence gate refused ("say again?") keeps its aim, or the repeat lands in
  the wrong pane.

No TTL. The plan sketched one; the rule set turned out not to need a clock,
because a mic open, a voice-off and any explicit target op all drop the aim,
and the only utterance that can reach a pending override is the one it was set
for. Dropping the TTL also removes the failure mode where an aim expires
mid-sentence.

state gains the precedence split the feature needs: active-target is where an
UTTERANCE goes (override, else slot) and is the single point everything the
router produces reads through; slot-target is the active slot ignoring any
override, and the desk-side router-bypassing paths now use it — the keystroke
bridge behind dais-top's passthrough lock and F11/esc are keys typed by
someone sitting at the machine, aimed at the slot they can see, and must not
follow a recording someone made from the car.

The ear's transcribe-vs-discard decision moves from a hardcoded via string to
ear/transcribing-stops, so the next caller that latches has one obvious place
to register — miss it and recordings vanish silently, which is a bad way to
find out.

The dictation run is now keyed on the delivery LABEL rather than the slot: an
override, a re-pointed slot and two slots naming one pane all have to answer
"same cursor?" correctly, and only the label does.

parse-target-value accepts a bare pane id ("%23"). tmux takes one anywhere a
target-pane goes, it is how airc reports panes, and it is the one spec form
immune to the pane_index renumbering trap — so `dais-ctl target set 3 %19`
starts working as a side effect.

Reporting: dictate_target rides along in state.json, the status query, the
state_changed broadcast and the target-list reply (a UI that missed an event
self-heals on the poll it already runs), and dais-top shows the override on the
target line so the cockpit never claims the slot while speech goes elsewhere.
tools/dais-ctl gains `dictate` with completion, which makes the whole feature
hand-testable without airc.

Also drops the last references to FABLE_PLAN.md, GOAL.md and CODEX_PLAN.md,
deleted in 9353d85: the README reading order, one code comment, and AGENTS.md's
claim that a missing file is normative.
2026-08-17 16:46:42 +03:00

263 lines
9.7 KiB
JavaScript
Executable File

#!/usr/bin/env node
// dais-ctl — thin client for the dais daemon socket. Dependency-free.
//
// Usage:
// dais-ctl status
// dais-ctl inject <text...> feed a fake transcript into the router
// dais-ctl send <text...> raw text straight to the target, router
// bypassed and nothing logged (the keystroke
// bridge behind dais-top's passthrough lock)
// dais-ctl send --keys <chord…> raw key chords, e.g. C-c Enter S-Tab
// dais-ctl brief [--full] deliver the voice-input briefing to the
// target: a pointer to BRIEF.md (default)
// or its full text (--full)
// dais-ctl dictate <start|stop|discard|toggle> [pane]
// latch a recording aimed at ONE pane (what
// airc's mic button sends); stop transcribes,
// discard throws it away. Omit the pane for a
// plain latch on the active slot.
// dais-ctl vad toggle the VAD session (F9)
// dais-ctl rec toggle the manual latch (F10)
// dais-ctl esc send Escape to the target (F11)
// dais-ctl off force voice off
// dais-ctl arm next utterance must be a command
// dais-ctl mute | unmute warm pause: drop utterances until unmute
// dais-ctl dry-run toggle dry-run (route & plan, don't deliver)
// dais-ctl target set <slot> <session:window.pane|focus|current>
// dais-ctl target use <slot>
// dais-ctl target release <slot> forget a slot, freeing the digit for reuse
// (refuses the last remaining slot)
// dais-ctl target next | prev cycle to the next/previous slot
// dais-ctl target next-live next deliverable slot (skips dead targets)
// dais-ctl target list
// dais-ctl target panes list all tmux panes (annotated)
// dais-ctl target pick [slot] fzf-pick a pane into a slot
// (default: the active slot)
// dais-ctl set enter-mode <no-enter|enter-auto|enter-always>
// dais-ctl set strategy <whole-match|prefix|key-armed>
// dais-ctl set language <en|fi|...|auto> transcription language
// (needs a multilingual model for non-en/auto)
// session-only; config wins on restart
// dais-ctl events [n]
// dais-ctl replay <trace_id>
// dais-ctl shutdown
//
// Socket: $DAIS_SOCKET, else $XDG_RUNTIME_DIR/dais/control.sock
const net = require("node:net");
const { spawn } = require("node:child_process");
const { randomUUID } = require("node:crypto");
const SOCKET =
process.env.DAIS_SOCKET ??
`${process.env.XDG_RUNTIME_DIR ?? "/tmp"}/dais/control.sock`;
function usage(code = 1) {
const lines = require("node:fs")
.readFileSync(__filename, "utf8")
.split("\n")
.filter((l) => l.startsWith("// "))
.map((l) => l.slice(3));
console.error(lines.join("\n"));
process.exit(code);
}
// ---------- socket helper (multiple requests per connection) ----------
function connectSock() {
return new Promise((resolve, reject) => {
const sock = net.createConnection({ path: SOCKET });
sock.setEncoding("utf8");
const pending = [];
let buf = "";
sock.on("data", (chunk) => {
buf += chunk;
let nl;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl);
buf = buf.slice(nl + 1);
const cb = pending.shift();
if (cb && line.trim()) {
try { cb(JSON.parse(line)); } catch { cb(null); }
}
}
});
sock.on("connect", () =>
resolve({
request: (req) =>
new Promise((res) => {
pending.push(res);
sock.write(JSON.stringify(req) + "\n");
}),
end: () => sock.end(),
}));
sock.on("error", (err) => reject(err));
});
}
function finish(resp) {
console.log(JSON.stringify(resp, null, 2));
process.exit(resp && resp.ok ? 0 : 1);
}
// ---------- interactive pane picker ----------
function fzf(lines, header) {
return new Promise((resolve) => {
const p = spawn("fzf",
["--height=40%", "--reverse", "--delimiter=\t", `--header=${header}`],
{ stdio: ["pipe", "pipe", "inherit"] });
let out = "";
p.stdout.on("data", (d) => (out += d));
p.on("close", () => resolve(out.trim() || null));
p.on("error", () => {
console.error("dais-ctl: fzf not available");
resolve(null);
});
p.stdin.end(lines.join("\n") + "\n");
});
}
async function pickFlow(slotArg) {
const sock = await connectSock();
const resp = await sock.request({ op: "target", action: "panes" });
if (!resp?.ok) finish(resp ?? { ok: false, error: "no response" });
const home = process.env.HOME;
const lines = resp.panes.map((p) => {
const tags = [
p.agent ? "★ agent" : null,
p.slot != null ? `= slot ${p.slot}` : null,
].filter(Boolean).join(", ");
const raw = p.path ?? "";
const path = home && raw.startsWith(home) ? "~" + raw.slice(home.length) : raw;
return `${p.pane}\t[${p.command}]\t${path}${tags ? `\t(${tags})` : ""}`;
});
const slot = slotArg ? Number(slotArg) : resp.active_slot;
const sel = await fzf(lines, `pick pane for target slot ${slot}`);
if (!sel) process.exit(1);
const pane = sel.split("\t")[0];
finish(await sock.request({ op: "target", action: "set", slot, pane }));
}
// ---------- request builder (single-shot verbs) ----------
function buildRequest(argv) {
const [cmd, ...rest] = argv;
switch (cmd) {
case "status":
return { op: "query", query: "status" };
case "inject": {
if (rest.length === 0) usage();
return {
op: "publish",
event: {
schema: "dais.event.v1",
id: randomUUID(),
time: new Date().toISOString(),
type: "voice.transcript",
source: { module: "dais-ctl", provider: "inject" },
payload: { text: rest.join(" ") },
},
};
}
case "send": {
if (rest.length === 0) usage();
return rest[0] === "--keys"
? { op: "send", keys: rest.slice(1) }
: { op: "send", text: rest.join(" ") };
}
case "brief": {
const fs = require("node:fs");
const path = require("node:path");
const briefPath = path.resolve(__dirname, "..", "BRIEF.md");
const text =
rest[0] === "--full"
? fs.readFileSync(briefPath, "utf8")
: `Voice input notice: parts of my input arrive via speech-to-text and may ` +
`contain recognition errors or noise. Read ${briefPath} for how to cope ` +
`(verify unclear intent, match dictated identifiers against the repo, ` +
`ignore noise fragments, prefer numbered options).`;
return {
op: "publish",
event: {
schema: "dais.event.v1",
id: randomUUID(),
time: new Date().toISOString(),
type: "voice.transcript",
source: { module: "dais-ctl", provider: "brief" },
payload: { text },
},
};
}
case "dictate": {
const [action, pane] = rest;
if (!["start", "stop", "discard", "toggle"].includes(action)) usage();
return pane ? { op: "dictate", action, pane } : { op: "dictate", action };
}
case "vad":
return { op: "control", action: "toggle-vad" };
case "rec":
return { op: "control", action: "toggle-record" };
case "esc":
return { op: "control", action: "esc" };
case "off":
return { op: "control", action: "voice-off" };
case "arm":
return { op: "control", action: "arm" };
case "mute":
return { op: "control", action: "mute" };
case "unmute":
return { op: "control", action: "unmute" };
case "dry-run":
return { op: "control", action: "toggle-dry-run" };
case "shutdown":
return { op: "control", action: "shutdown" };
case "target": {
const [action, slot, value] = rest;
if (action === "set" && slot && value)
return { op: "target", action: "set", slot: Number(slot), pane: value };
if (action === "use" && slot)
return { op: "target", action: "use", slot: Number(slot) };
if (action === "release" && slot)
return { op: "target", action: "release", slot: Number(slot) };
if (action === "next" || action === "prev")
return { op: "target", action };
if (action === "next-live") return { op: "target", action: "next-live" };
if (action === "list") return { op: "target", action: "list" };
if (action === "panes") return { op: "target", action: "panes" };
usage();
break;
}
case "set": {
const [key, value] = rest;
if (key === "enter-mode" && value) return { op: "settings", enter_mode: value };
if (key === "strategy" && value) return { op: "settings", strategy: value };
if (key === "language" && value) return { op: "settings", language: value };
usage();
break;
}
case "events":
return { op: "events", last: rest[0] ? Number(rest[0]) : 20 };
case "replay":
if (!rest[0]) usage();
return { op: "replay", trace_id: rest[0] };
default:
usage(cmd === "--help" || cmd === "-h" ? 0 : 1);
}
}
async function main() {
const argv = process.argv.slice(2);
try {
if (argv[0] === "target" && argv[1] === "pick") {
await pickFlow(argv[2]);
return;
}
const req = buildRequest(argv);
const sock = await connectSock();
finish(await sock.request(req));
} catch (err) {
console.error(`dais-ctl: ${err.message} (socket: ${SOCKET} — daemon running?)`);
process.exit(1);
}
}
main();