Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions pm-stack/voice-line-worker/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Voice line worker — step 1 (#9800)

The basement voice line, first step: talk to the fleet and hear the
answer, end to end, Cloudflare-direct.

- **Push-to-talk WebSocket in a Durable Object** (`src/session.ts`,
one `VoiceSession` per session id). The page at `/` streams PCM16LE
16 kHz mono while the button is held and sends `{"type":"stop"}` on
release.
- **Silence is trimmed before transcription** (`src/vad.ts`):
energy-based VAD cuts head/tail silence and collapses long internal
pauses, and *only the trimmed audio* is submitted — Workers AI
transcription bills per audio minute submitted, pauses included, so
silence is never billed and never transcribed. The transcript event
reports seconds submitted vs seconds recorded.
- **Speech-to-text:** Workers AI Whisper
(`@cf/openai/whisper-large-v3-turbo`) via the `AI` binding.
- **Speech out:** Workers AI MeloTTS (`@cf/myshell-ai/melotts`) speaks
the answer back over the same socket (Drew's 2026-11-14 amendment:
the line must talk back). Outgoing synthesis covers only the answer
text.
- **One read-only intent** (`src/intent.ts`): queue state. The voice
line takes no write actions; anything else gets a spoken explanation
of the one capability. Queue state comes from the newest
`status_snapshots` row, pushed by the fleet via `POST /ingest-status`
(Bearer `STATUS_INGEST_TOKEN`) — a status *input*, not a voice write
action.
- **Session ledger in Turso** (`src/ledger.ts`, libsql HTTP pipeline,
no SDK): every completed utterance writes a `sessions` row — session
id, timestamps, transcript, intent, answer, audio seconds in
(post-trim, as submitted) and out, and the two model ids.
`audio_seconds_out` is estimated from the answer's word count at a
standard speaking rate until MP3 frame parsing is worth it.

The OpenCode pooled/failover version of speech (both directions) is
the companion issue #9801 and is deliberately not built here; the
socket and intent shapes do not preclude it (the DO calls the two
models in exactly two places).

## Run / deploy

```sh
bun install
bun test # VAD + intent suites
bunx tsc --noEmit
bunx wrangler dev # local: AI binding runs remote against the account
```

Deploy needs (account-side, one time):

1. A Turso database for the ledger; set its URL in `wrangler.toml`
(`TURSO_URL` var) — the schema is created idempotently at runtime.
2. `wrangler secret put TURSO_TOKEN` and
`wrangler secret put STATUS_INGEST_TOKEN`.
3. `bun run deploy`, then push a first queue snapshot:
`curl -X POST <worker>/ingest-status -H "Authorization: Bearer $STATUS_INGEST_TOKEN" -d '{"queued":0,"claimed":0,"parked":0,"blocked":0}'`

## Protocol

Client → server: binary PCM16LE frames; text control frames
`{"type":"start"}` (reset buffer) and `{"type":"stop"}` (process).
Server → client: JSON events `ready`, `transcript` (text + seconds
submitted/raw), `answer` (intent + text), then one binary MP3 frame
(the spoken answer), then `done` (session id + ledger seconds), or
`error`.
217 changes: 217 additions & 0 deletions pm-stack/voice-line-worker/bun.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions pm-stack/voice-line-worker/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"description":"Basement voice line step 1 (#9800): push-to-talk WebSocket in a Durable Object, Workers AI Whisper STT + MeloTTS speech out (Cloudflare-direct), silence trim/VAD before transcription, one read-only queue-state intent, Turso session ledger.","devDependencies":{"@cloudflare/workers-types":"^4.20251011.0","typescript":"^5.6.0","wrangler":"4.44.0"},"name":"voice-line-worker","private":true,"scripts":{"deploy":"wrangler deploy","dev":"wrangler dev","test":"bun test","typecheck":"tsc --noEmit"},"type":"module","version":"0.1.0"}
126 changes: 126 additions & 0 deletions pm-stack/voice-line-worker/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// Voice line Worker entry (#9800): serves the push-to-talk page,
// routes WebSocket sessions to the VoiceSession Durable Object, and
// accepts read-only status snapshots the intents answer from.
//
// Routes:
// GET / push-to-talk client page
// GET /ws?session=<id> WebSocket upgrade -> VoiceSession DO
// GET /health { ok, latestQueueSnapshotAt }
// POST /ingest-status Bearer STATUS_INGEST_TOKEN; body is a
// queue-state snapshot {queued, claimed, parked,
// blocked} stored for the queue_state intent.
// This is a status INPUT, not a voice write
// action: the voice line itself stays read-only.

import { TursoClient } from "./ledger";
import type { Env } from "./session";

export { VoiceSession } from "./session";

const PAGE = `<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Voice line — step 1 (#9800)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>body{font-family:system-ui;margin:2rem;max-width:40rem}button{font-size:1.25rem;padding:1rem 2rem}
#log{white-space:pre-wrap;background:#111;color:#eee;padding:1rem;border-radius:.5rem;min-height:8rem}</style>
</head>
<body>
<h1>Voice line — step 1</h1>
<p>Hold the button and ask about the fleet queue, e.g. &ldquo;how many tasks are in the queue?&rdquo;
Your speech is trimmed of silence, transcribed, answered, and spoken back.</p>
<button id="talk" disabled>Connecting…</button>
<div id="log"></div>
<script>
const log = (m) => { document.getElementById('log').textContent += m + '\\n'; };
const sessionId = crypto.randomUUID();
const ws = new WebSocket(location.origin.replace('http', 'ws') + '/ws?session=' + sessionId);
let audioCtx, source, processor, stream, chunks;
ws.binaryType = 'arraybuffer';
ws.onopen = () => { const b = document.getElementById('talk'); b.disabled = false; b.textContent = 'Hold to talk'; };
ws.onmessage = async (ev) => {
if (typeof ev.data !== 'string') {
const ctx = new AudioContext();
const buf = await ctx.decodeAudioData(ev.data);
const src = ctx.createBufferSource(); src.buffer = buf; src.connect(ctx.destination); src.start();
log('🔊 speaking the answer');
return;
}
const msg = JSON.parse(ev.data);
if (msg.type === 'transcript') log('📝 ' + msg.text + ' (' + msg.audioSecondsSubmitted.toFixed(1) + 's submitted of ' + msg.audioSecondsRaw.toFixed(1) + 's recorded)');
else if (msg.type === 'answer') log('💬 ' + msg.text);
else if (msg.type === 'done') log('✅ session ' + msg.sessionId + ' written to the ledger');
else if (msg.type === 'error') log('⚠️ ' + msg.error);
};
async function start() {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
audioCtx = new AudioContext({ sampleRate: 16000 });
source = audioCtx.createMediaStreamSource(stream);
processor = audioCtx.createScriptProcessor(4096, 1, 1);
chunks = [];
processor.onaudioprocess = (e) => {
const f = e.inputBuffer.getChannelData(0);
const pcm = new Int16Array(f.length);
for (let i = 0; i < f.length; i++) pcm[i] = Math.max(-32768, Math.min(32767, Math.round(f[i] * 32767)));
ws.send(pcm.buffer);
};
ws.send(JSON.stringify({ type: 'start' }));
source.connect(processor); processor.connect(audioCtx.destination);
}
async function stop() {
processor.disconnect(); source.disconnect(); stream.getTracks().forEach(t => t.stop());
await audioCtx.close();
ws.send(JSON.stringify({ type: 'stop' }));
}
const btn = document.getElementById('talk');
btn.addEventListener('pointerdown', start);
btn.addEventListener('pointerup', stop);
</script>
</body>
</html>`;

export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);

if (url.pathname === "/") {
return new Response(PAGE, { headers: { "Content-Type": "text/html; charset=utf-8" } });
}

if (url.pathname === "/ws") {
const sessionId = url.searchParams.get("session") ?? crypto.randomUUID();
const stub = env.VOICE_SESSIONS.get(env.VOICE_SESSIONS.idFromName(sessionId));
return stub.fetch(request);
}

if (url.pathname === "/health") {
const turso = new TursoClient(env.TURSO_URL, env.TURSO_TOKEN);
let latest: string | null = null;
try {
latest = (await turso.latestQueueSnapshot())?.at ?? null;
} catch {
latest = null;
}
return Response.json({ ok: true, latestQueueSnapshotAt: latest });
}

if (url.pathname === "/ingest-status" && request.method === "POST") {
const expected = (env as Env & { STATUS_INGEST_TOKEN?: string }).STATUS_INGEST_TOKEN;
if (!expected || request.headers.get("Authorization") !== `Bearer ${expected}`) {
return new Response("unauthorized", { status: 401 });
}
const body = (await request.json()) as Record<string, unknown>;
const snapshot = {
queued: Number(body.queued ?? 0),
claimed: Number(body.claimed ?? 0),
parked: Number(body.parked ?? 0),
blocked: Number(body.blocked ?? 0),
};
const turso = new TursoClient(env.TURSO_URL, env.TURSO_TOKEN);
await turso.ensureSchema();
await turso.putSnapshot("queue_state", snapshot, new Date().toISOString());
return Response.json({ ok: true, stored: snapshot });
}

return new Response("not found", { status: 404 });
},
};
48 changes: 48 additions & 0 deletions pm-stack/voice-line-worker/src/intent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Read-only intent matching for the voice line (#9800).
//
// Step 1 ships exactly ONE intent end to end — queue state — per the
// issue's acceptance. Intents are read-only by design: the voice line
// never takes a write action. Matching is deliberately small and
// deterministic (no model in the loop): a transcript either names the
// queue-state intent or falls back to a spoken explanation of what the
// line can do, which still exercises both speech directions.

export type IntentName = "queue_state" | "unknown";

export interface QueueSnapshot {
queued: number;
claimed: number;
parked: number;
blocked: number;
/** ISO timestamp of the snapshot. */
at: string;
}

const QUEUE_PATTERNS: RegExp[] = [
/\bqueue\b/,
/\btasks?\b.*\b(waiting|queued|left|open)\b/,
/\bhow many\b.*\btasks?\b/,
/\bbacklog\b/,
/\bfleet\b.*\b(state|status)\b/,
];

export function matchIntent(transcript: string): IntentName {
const text = transcript.toLowerCase();
return QUEUE_PATTERNS.some((re) => re.test(text)) ? "queue_state" : "unknown";
}

export function buildAnswer(intent: IntentName, snapshot: QueueSnapshot | null): string {
if (intent === "queue_state") {
if (!snapshot) {
return "I don't have a fresh queue snapshot right now. Ask again in a moment and I should know the queue state.";
}
const parts = [
`The fleet queue has ${snapshot.queued} tasks waiting`,
`${snapshot.claimed} being worked`,
`and ${snapshot.parked} parked`,
];
if (snapshot.blocked > 0) parts.push(`with ${snapshot.blocked} blocked`);
return parts.join(", ") + ".";
}
return "Right now I can only report the fleet queue state. Try asking: how many tasks are in the queue?";
}
129 changes: 129 additions & 0 deletions pm-stack/voice-line-worker/src/ledger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// Turso (libsql) access for the voice line (#9800) over the Turso HTTP
// pipeline API — no SDK, just fetch, so the Worker stays small.
//
// Two tables (created idempotently by `ensureSchema`):
// sessions — the session ledger the issue requires: who asked
// (session id), what intent, what was answered,
// audio seconds in (submitted, post-trim) and out.
// status_snapshots — read-only status inputs for intents; the fleet
// pushes queue-state snapshots via /ingest-status
// and the queue_state intent answers from the
// newest row. kind is the snapshot family
// ("queue_state" for step 1).

import type { QueueSnapshot } from "./intent";

export interface SessionRow {
id: string;
startedAt: string;
endedAt: string;
transcript: string;
intent: string;
answer: string;
audioSecondsIn: number;
audioSecondsOut: number;
sttModel: string;
ttsModel: string;
}

type TursoValue =
| { type: "null" }
| { type: "text"; value: string }
| { type: "float"; value: number }
| { type: "integer"; value: string };

const text = (value: string): TursoValue => ({ type: "text", value });
const float = (value: number): TursoValue => ({ type: "float", value });

interface PipelineResult {
results: Array<{
type: string;
response?: {
type: string;
result?: { cols: unknown[]; rows: Array<{ values: TursoValue[] }> };
};
}>;
}

export class TursoClient {
constructor(
private url: string,
private token: string,
) {}

private async pipeline(statements: Array<{ sql: string; args: TursoValue[] }>): Promise<PipelineResult> {
const res = await fetch(`${this.url.replace(/\/$/, "")}/v2/pipeline`, {
method: "POST",
headers: {
Authorization: `Bearer ${this.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
requests: [
...statements.map((stmt) => ({ type: "execute", stmt })),
{ type: "close" },
],
}),
});
if (!res.ok) throw new Error(`turso pipeline failed: HTTP ${res.status}`);
return (await res.json()) as PipelineResult;
}

async execute(sql: string, args: TursoValue[] = []): Promise<void> {
await this.pipeline([{ sql, args }]);
}

async ensureSchema(): Promise<void> {
await this.pipeline([
{
sql: `CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY, started_at TEXT NOT NULL, ended_at TEXT NOT NULL,
transcript TEXT NOT NULL, intent TEXT NOT NULL, answer TEXT NOT NULL,
audio_seconds_in REAL NOT NULL, audio_seconds_out REAL NOT NULL,
stt_model TEXT NOT NULL, tts_model TEXT NOT NULL)`,
args: [],
},
{
sql: `CREATE TABLE IF NOT EXISTS status_snapshots (
kind TEXT NOT NULL, payload TEXT NOT NULL, at TEXT NOT NULL)`,
args: [],
},
]);
}

async insertSession(row: SessionRow): Promise<void> {
await this.execute(
`INSERT INTO sessions (id, started_at, ended_at, transcript, intent, answer,
audio_seconds_in, audio_seconds_out, stt_model, tts_model)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
text(row.id), text(row.startedAt), text(row.endedAt), text(row.transcript),
text(row.intent), text(row.answer), float(row.audioSecondsIn),
float(row.audioSecondsOut), text(row.sttModel), text(row.ttsModel),
],
);
}

async putSnapshot(kind: string, payload: unknown, at: string): Promise<void> {
await this.execute(
`INSERT INTO status_snapshots (kind, payload, at) VALUES (?, ?, ?)`,
[text(kind), text(JSON.stringify(payload)), text(at)],
);
}

async latestQueueSnapshot(): Promise<QueueSnapshot | null> {
const out = await this.pipeline([
{
sql: `SELECT payload, at FROM status_snapshots WHERE kind = 'queue_state'
ORDER BY at DESC LIMIT 1`,
args: [],
},
]);
const rows = out.results[0]?.response?.result?.rows ?? [];
if (rows.length === 0) return null;
const [payload, at] = rows[0].values;
if (payload.type !== "text" || at.type !== "text") return null;
const parsed = JSON.parse(payload.value) as Omit<QueueSnapshot, "at">;
return { ...parsed, at: at.value };
}
}
Loading