Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(voice): universal DOM driving + intent-gated tools + chained flows

Adam Eivy2e73f556df73
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 76d01dbf3c..8ee2ce5761 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,6 @@
## Added
+- **Voice agent — universal accessibility-mode DOM driving** — the voice Chief-of-Staff can now navigate to any page and operate any control by voice. New `ui_navigate` tool with a 100+ entry named-page enum ("take me to tasks" / "chief of staff agents" / "calendar" all route correctly instead of defaulting to Daily Log). New accessibility layer: a client-side DOM indexer (`client/src/services/domIndex.js`) walks `<main>` for interactable elements (tabs, buttons, links, inputs, selects, textareas, checkboxes, radios), resolves labels via the standard aria → `<label for>` → wrapping label → text → placeholder → title chain, stamps stable `data-voice-ref` refs, and caps at 200 elements. `useVoiceUiSync` hook (debounced MutationObserver scoped to `<main>`, change-detection via content signature) pushes the index to the server whenever it actually changes. Server stores the index on per-socket state and — for UI-driving user turns (verb-gated by regex to keep the 80% of turns that don't need it cheap) — injects a compact page summary into the LLM's system prompt. New tools: `ui_click` (tab/button/link by label with optional kind hint), `ui_fill` (text inputs + textareas, uses React-safe native value setter so `onChange` fires), `ui_select` (dropdowns with fuzzy option matching), `ui_check` (checkboxes + radios), `ui_list_interactables` (deep-dive fallback). Misses return a helpful `available` list to the LLM so it can self-correct instead of silently failing. **In-turn chained flows**: after a ui_* action fires, the server pauses briefly for the client to push the post-action DOM index, then attaches the fresh summary to the tool result — so multi-step flows like "create a task named Foo with description Bar" can complete in a single turn (ui_click New Task → see the modal → ui_fill Name → ui_fill Description → ui_click Save).
- **Per-peer DNS override on the Instances page** — peer cards now expose an "edit host" control that lets you swap the raw Tailscale IP (`http://100.83.147.46:5555`) for a trusted HTTPS DNS name (`https://void.taile8179.ts.net:5555`). Once set, the server's probe, socket relay, sync orchestrator, and query proxy all route through `https://<host>` instead of `http://<ip>` — so app links in `PeerAppsList` also upgrade to HTTPS automatically. New `GET /api/instances/tailnet-suffix` endpoint shells out to the local `tailscale status --json` and returns the MagicDNS suffix + the full peer map, which the Instances UI uses to auto-suggest DNS names: match by Tailscale IP first (authoritative), fall back to `<peer.hostname>.<suffix>` composition. The UI's "use `<suggested>`" button applies the suggestion in one click. `updatePeer` now accepts an optional `host` field (validated as a DNS name; empty string clears); invalid hosts return 400 instead of silent no-ops. `addPeer` also accepts `host` for direct-DNS registration. Vite dev proxy auto-detects `data/certs/cert.pem` and flips its target to `https://localhost:5555` with `secure: false` when HTTPS is active, fixing "socket hang up" errors in dev mode. 44 tests (3 new) cover valid/invalid/cleared host handling.
- **HTTPS with auto-renewing Let's Encrypt cert via Tailscale (self-signed fallback)** — Chrome refuses `getUserMedia` (mic) access over plain HTTP on a `100.x.x.x` Tailscale IP because the origin isn't a secure context. New `scripts/setup-cert.js` prefers a real Let's Encrypt cert via `tailscale cert <machine>.<tailnet>.ts.net` (Tailscale owns `ts.net` and solves the DNS-01 challenge for you — browsers trust the cert with zero click-through) and drops it into `data/certs/{cert,key}.pem`. If the Tailscale CLI is missing, the machine isn't logged in, or HTTPS Certificates aren't enabled in the tailnet admin, the script falls back to a self-signed cert with SANs for `localhost`, `127.0.0.1`, and every non-internal IPv4 (including the Tailscale IP). `server/index.js` picks `https.createServer` whenever `data/certs/{cert,key}.pem` exist and falls back to HTTP with a warning otherwise. New `server/services/certRenewer.js` runs daily on the server process, calls `tailscale cert` (no-op unless the LE cert is <2/3 lifetime remaining), and hot-swaps the live HTTPS server's `SecureContext` with the renewed cert — no restart needed. `npm start` runs the cert script before PM2 boot so fresh installs come up with HTTPS out of the box; `npm run setup:cert --force` regenerates on demand. Socket.IO auto-upgrades to WSS (same-origin relative paths). Access via `https://<machine>.<tailnet>.ts.net:5555` to get the trusted cert; the Tailscale IP still works but will show a cert mismatch.
- **Blood Pressure tracking in MeatSpace → Body** — feature parity with the MortalLoom iOS/macOS companion app. New Blood Pressure card on the Body tab shows a systolic/diastolic trend chart (with AHA/ACC 2017 guideline reference lines), the latest reading, and its category + estimated life-expectancy impact. Readings are date-upserted so a HealthKit sync on the phone and a manual entry in PortOS on the same day merge into one row. Storage routes through the new `mlUpsertHealthMetricByDate` into MortalLoom's `healthMetrics[]` array when iCloud sync is enabled (same `bloodPressureSystolic`/`bloodPressureDiastolic` keys the Swift app writes), else falls back to `data/meatspace/health-metrics.json`. New endpoints: `GET /api/meatspace/blood-pressure`, `POST /api/meatspace/blood-pressure`. Apple Health XML ingest now maps `HKQuantityTypeIdentifierBloodPressureSystolic`/`Diastolic` → `blood_pressure_systolic`/`diastolic`, and those metrics are registered in the Core Vitals section of the Health tab so exported HK data shows trend lines there too. BP classification (normal / elevated / stage-1 / stage-2 / crisis) is ported from `CardioFitnessEngine.classifyBP` into `client/src/components/meatspace/bpClassification.js` so both sides report identical categories for the same reading.
diff --git a/PLAN.md b/PLAN.md
index 6e09f10a06..aef775d1a3 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -10,12 +10,19 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
## Backlog
-- [ ] **Voice CoS tool expansion** — 14 tools registered in `server/services/voice/tools.js`: `brain_capture`, `brain_search`, `brain_list_recent`, `meatspace_log_drink`, `meatspace_log_nicotine`, `meatspace_log_weight`, `meatspace_summary_today`, `goal_list`, `goal_update_progress`, `goal_log_note`, `pm2_status`, `pm2_restart`, `feeds_digest`, `time_now`. Remaining candidates:
+- [ ] **Voice CoS tool expansion** — tools now include the original domain set plus `ui_navigate`, `ui_list_interactables`, `ui_click`, `ui_fill`, `ui_select`, `ui_check` for accessibility-style page driving. Remaining candidates:
- `calendar_today` / `calendar_next` — surface today's Google Calendar events through the existing Google MCP integration
- `meatspace_log_workout` — wrap `meatspaceHealth.js` workout/activity exports
- `weather_now` — needs an external API choice (OpenWeather / Apple WeatherKit / NWS)
- `timer_set` — set a voice-triggered reminder; likely reuses `agentActionExecutor.js` scheduled actions
- `feeds_mark_read` — pair with `feeds_digest` for "mark that one read"
+
+- [ ] **Voice agent — next power-ups** (follow-ons to the ui_* accessibility layer):
+ - `ui_read` — extract visible page text (not just interactables) so "what does this say?" / "summarize this page" works without hand-navigation. Complements `ui_list_interactables`.
+ - **Destructive-action confirmation gate** — when a `ui_click` target label matches `/delete|remove|discard|reset|clear/i`, pause and require spoken "confirm" / "cancel" before firing. Prevents voice mishaps.
+ - **Vision fallback tool** (`ui_describe_visually`) — screenshot the current tab (or a named canvas/chart element) and send to a vision-capable model so "what's on this chart?" works on non-DOM content (CyberCity, graph views). Depends on whether `portos-ai-toolkit` wires a vision provider.
+ - **Proactive CoS speech** — push-to-talk the other direction: a server event that makes the voice widget speak unprompted ("heads up: 3 things on your briefing" / "time to stretch"). Needs a quiet-hours policy and an interrupt-gracefully contract with the existing barge-in logic.
+ - **Explicit long-term memory routing** — when the user says "remember that …", auto-route to `brain_capture` and inject top-N relevant memories into the voice turn's system prompt via `brain_search`. Some of this is ambiently possible today; make it explicit and self-improving.
- [x] **Test coverage** — cosRunnerClient.js ✅ (37 tests), agentActionExecutor.js ✅ (27 tests), CoS routes ✅ (170 tests across 6 test files, 83-100% route coverage). Remaining gap: cos.js service (~4% coverage)
- [ ] **CyberCity v2** — Transform from decorative scene to living systems dashboard. See [cybercity-v2.md](./docs/features/cybercity-v2.md) for full plan. Top priorities: system health atmosphere, richer billboards, brain inbox pulse, agent activity visualization, chronotype energy overlay.
- [ ] **M50 P9**: CoS Automation & Rules — Automated email classification, rule-based pre-filtering, email-to-task pipeline
diff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsx
index 4fb4655737..8a2daa8bb7 100644
--- a/client/src/components/voice/VoiceWidget.jsx
+++ b/client/src/components/voice/VoiceWidget.jsx
@@ -8,6 +8,8 @@ import {
} from '../../services/voiceClient';
import { getVoiceConfig } from '../../services/apiVoice';
import toast from '../ui/Toast';
+import { useVoiceUiSync, pushUiIndexAfterAction } from '../../hooks/useVoiceUiSync';
+import { doClick, doFill, doSelect, doSetCheckbox } from '../../services/uiInteract';
// Peak below this (0..1) is usually whisper's [BLANK_AUDIO] territory.
const QUIET_MIC_THRESHOLD = 0.02;
@@ -68,6 +70,10 @@ export default function VoiceWidget() {
const scrollRef = useRef(null);
const useWebSpeech = sttEngine === 'web-speech' && webSpeechSupported;
+ // Keep the server's UI index fresh so the LLM knows what's on the page
+ // and can drive it with ui_click / ui_fill / ui_select / ui_check.
+ useVoiceUiSync(enabled);
+
// Disabling voice mode (via Settings or the socket broadcast) must release
// every mic path — MediaRecorder, AudioWorklet VAD, and Web Speech — plus
// drop any queued TTS. Without this, a user who turns voice off while
@@ -176,6 +182,26 @@ export default function VoiceWidget() {
toast(`📓 +"${preview}"`);
}
}),
+ onVoiceEvent('voice:ui:click', (d) => {
+ const res = doClick(d?.target);
+ if (!res.ok) toast.error(`Voice: couldn't click "${d?.target?.label || d?.target?.ref}"`);
+ else pushUiIndexAfterAction();
+ }),
+ onVoiceEvent('voice:ui:fill', (d) => {
+ const res = doFill(d?.target, d?.value);
+ if (!res.ok) toast.error(`Voice: couldn't fill "${d?.target?.label || d?.target?.ref}"`);
+ else pushUiIndexAfterAction();
+ }),
+ onVoiceEvent('voice:ui:select', (d) => {
+ const res = doSelect(d?.target, d?.option);
+ if (!res.ok) toast.error(`Voice: couldn't select "${d?.option}" on "${d?.target?.label}"`);
+ else pushUiIndexAfterAction();
+ }),
+ onVoiceEvent('voice:ui:check', (d) => {
+ const res = doSetCheckbox(d?.target, d?.checked);
+ if (!res.ok) toast.error(`Voice: couldn't toggle "${d?.target?.label}"`);
+ else pushUiIndexAfterAction();
+ }),
];
return () => offs.forEach((off) => off());
}, [enabled, navigate]);
diff --git a/client/src/hooks/useVoiceUiSync.js b/client/src/hooks/useVoiceUiSync.js
new file mode 100644
index 0000000000..5adbf21315
--- /dev/null
+++ b/client/src/hooks/useVoiceUiSync.js
@@ -0,0 +1,104 @@
+// Keeps the voice server's UI index in sync with the current page.
+//
+// Runs only when voice is enabled. Pushes a fresh index:
+// - On route change (useLocation dependency).
+// - On DOM mutations, debounced so burst renders only send one update.
+// - Imperatively via pushUiIndex(delay) — used by ui_* action handlers in
+// VoiceWidget to emit right after a click/fill so the pipeline's in-turn
+// "wait for refresh" can chain the next action.
+//
+// State lives on refs owned by the mounted hook, so StrictMode double-
+// invocation and HMR remounts don't leave stale timers or signature caches.
+// An escape-hatch module-level ref gives the post-action helper a handle
+// without requiring every ui_* handler to thread through React context.
+
+import { useEffect, useRef } from 'react';
+import { useLocation } from 'react-router-dom';
+import socket from '../services/socket.js';
+import { buildIndex, clearRefs } from '../services/domIndex.js';
+
+const DEBOUNCE_MS = 500;
+const INITIAL_DELAY_MS = 250;
+const POST_ACTION_DELAY_MS = 120;
+
+// Reference to the currently-mounted hook's pushUiIndex function. VoiceWidget
+// is a singleton in prod; this handle lets non-React callers (event handlers
+// in VoiceWidget) fire an immediate push after a ui:* side effect.
+let activePush = null;
+
+// Cheap change-detection. Path/title/length rejects most non-mutations; the
+// full per-element body runs only when the quick check matches.
+const quickSig = (idx) => `${idx.path || ''}|${idx.title || ''}|${idx.elements.length}`;
+const fullSig = (idx) => idx.elements
+ .map((e) => `${e.ref}:${e.kind}:${e.label}:${e.active ?? ''}`)
+ .join('|');
+
+export const pushUiIndex = (delay = DEBOUNCE_MS) => activePush?.(delay);
+export const pushUiIndexAfterAction = () => pushUiIndex(POST_ACTION_DELAY_MS);
+
+export const useVoiceUiSync = (enabled) => {
+ const location = useLocation();
+ const timerRef = useRef(null);
+ const quickSigRef = useRef(null);
+ const fullSigRef = useRef(null);
+
+ useEffect(() => {
+ if (!enabled) {
+ clearRefs();
+ if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; }
+ quickSigRef.current = null;
+ fullSigRef.current = null;
+ if (activePush) activePush = null;
+ return undefined;
+ }
+
+ const flush = () => {
+ timerRef.current = null;
+ if (document.hidden) return;
+ const idx = buildIndex();
+ const quick = quickSig(idx);
+ if (quick === quickSigRef.current) {
+ const full = fullSig(idx);
+ if (full === fullSigRef.current) return;
+ fullSigRef.current = full;
+ } else {
+ quickSigRef.current = quick;
+ fullSigRef.current = fullSig(idx);
+ }
+ socket.emit('voice:ui:index', idx);
+ };
+
+ const schedule = (delay) => {
+ if (timerRef.current) clearTimeout(timerRef.current);
+ timerRef.current = setTimeout(flush, delay);
+ };
+
+ activePush = schedule;
+
+ // Reset sigs on route change so the first index for a new page always
+ // emits, even if it happens to hash identically to the previous.
+ quickSigRef.current = null;
+ fullSigRef.current = null;
+ schedule(INITIAL_DELAY_MS);
+
+ // Scope to <main> so the voice widget's own transcript/history updates
+ // don't trigger a re-index on every TTS delta. value/checked are
+ // deliberately excluded from attributeFilter — they fire on every
+ // keystroke into any text field and create a typing-starves-the-index
+ // loop. Interactable SET changes via childList.
+ const target = document.querySelector('main') || document.getElementById('root') || document.body;
+ const observer = new MutationObserver(() => schedule(DEBOUNCE_MS));
+ observer.observe(target, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['aria-selected', 'aria-expanded', 'disabled'],
+ });
+
+ return () => {
+ observer.disconnect();
+ if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; }
+ if (activePush === schedule) activePush = null;
+ };
+ }, [enabled, location.pathname, location.search]);
+};
diff --git a/client/src/services/domIndex.js b/client/src/services/domIndex.js
new file mode 100644
index 0000000000..792f31152a
--- /dev/null
+++ b/client/src/services/domIndex.js
@@ -0,0 +1,206 @@
+// DOM indexer for voice accessibility mode.
+//
+// Walks the visible UI and produces a compact list of interactable elements
+// (tabs, buttons, inputs, selects, etc.) each tagged with a stable ref.
+// The server-side LLM receives this index per turn so it can drive the UI
+// by label ("select the Memory tab", "fill search with 'foo'", etc.) via
+// the ui_click / ui_fill / ui_select tools.
+
+const MAX_ELEMENTS = 200;
+const MAX_LABEL = 80;
+
+const truncate = (s, n = MAX_LABEL) => {
+ if (!s) return '';
+ const trimmed = s.replace(/\s+/g, ' ').trim();
+ return trimmed.length > n ? `${trimmed.slice(0, n - 1)}…` : trimmed;
+};
+
+const isVisible = (el) => {
+ if (!el || !el.isConnected) return false;
+ if (el.hasAttribute('hidden') || el.getAttribute('aria-hidden') === 'true') return false;
+ // Fast-path: offsetParent is null for display:none ancestors and for
+ // elements with display:none themselves. Catches ~80% of hidden cases
+ // without forcing getComputedStyle/getBoundingClientRect layout reads.
+ // Skips for position:fixed (offsetParent is always null) — for those we
+ // fall through to the expensive checks.
+ if (el.offsetParent === null && window.getComputedStyle(el).position !== 'fixed') return false;
+ const style = window.getComputedStyle(el);
+ if (style.visibility === 'hidden' || style.pointerEvents === 'none') return false;
+ const rect = el.getBoundingClientRect();
+ if (rect.width === 0 && rect.height === 0) return false;
+ return true;
+};
+
+const classify = (el) => {
+ const tag = el.tagName.toLowerCase();
+ const role = (el.getAttribute('role') || '').toLowerCase();
+ if (role === 'tab') return 'tab';
+ if (role === 'menuitem') return 'button';
+ if (tag === 'a' && el.href) return 'link';
+ if (tag === 'button' || role === 'button') return 'button';
+ if (tag === 'select') return 'select';
+ if (tag === 'textarea') return 'textarea';
+ if (tag === 'input') {
+ const type = (el.type || 'text').toLowerCase();
+ if (type === 'checkbox') return 'checkbox';
+ if (type === 'radio') return 'radio';
+ if (type === 'submit' || type === 'button' || type === 'reset') return 'button';
+ if (type === 'hidden' || type === 'file') return null;
+ return 'input';
+ }
+ return null;
+};
+
+const extractLabel = (el) => {
+ const aria = el.getAttribute('aria-label');
+ if (aria) return truncate(aria);
+
+ const labelledBy = el.getAttribute('aria-labelledby');
+ if (labelledBy) {
+ const parts = labelledBy.split(/\s+/)
+ .map((id) => document.getElementById(id)?.textContent || '')
+ .filter(Boolean);
+ if (parts.length) return truncate(parts.join(' '));
+ }
+
+ const tag = el.tagName.toLowerCase();
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') {
+ if (el.id) {
+ const lab = document.querySelector(`label[for="${CSS.escape(el.id)}"]`);
+ if (lab?.textContent) return truncate(lab.textContent);
+ }
+ const wrapping = el.closest('label');
+ if (wrapping) {
+ const clone = wrapping.cloneNode(true);
+ clone.querySelectorAll('input, textarea, select').forEach((n) => n.remove());
+ const t = clone.textContent;
+ if (t && t.trim()) return truncate(t);
+ }
+ const placeholder = el.getAttribute('placeholder');
+ if (placeholder) return truncate(placeholder);
+ const name = el.getAttribute('name');
+ if (name) return truncate(name);
+ }
+
+ const text = el.textContent;
+ if (text && text.trim()) return truncate(text);
+
+ const title = el.getAttribute('title');
+ if (title) return truncate(title);
+
+ return null;
+};
+
+const SELECTOR = [
+ 'button',
+ '[role="button"]',
+ '[role="tab"]',
+ '[role="menuitem"]',
+ 'a[href]',
+ 'input',
+ 'select',
+ 'textarea',
+].join(', ');
+
+export const clearRefs = () => {
+ document.querySelectorAll('[data-voice-ref]').forEach((el) => {
+ el.removeAttribute('data-voice-ref');
+ });
+};
+
+const pickRoot = () => (
+ document.querySelector('main')
+ || document.getElementById('root')
+ || document.body
+);
+
+const findTitle = () => {
+ // Prefer a visible page heading over the tab title — it's the name the user
+ // sees and what they'll naturally reference ("the tasks page").
+ const h1 = document.querySelector('main h1, main [role="heading"][aria-level="1"]');
+ if (h1?.textContent) return truncate(h1.textContent, 60);
+ return truncate(document.title, 60);
+};
+
+export const buildIndex = () => {
+ clearRefs();
+ const root = pickRoot();
+ const elements = [];
+ const raw = Array.from(root.querySelectorAll(SELECTOR));
+
+ for (const el of raw) {
+ if (elements.length >= MAX_ELEMENTS) break;
+ const kind = classify(el);
+ if (!kind) continue;
+ if (!isVisible(el)) continue;
+ if (el.disabled) continue;
+
+ const label = extractLabel(el);
+ if (!label) continue;
+
+ const ref = elements.length;
+ el.setAttribute('data-voice-ref', String(ref));
+
+ const entry = { ref, kind, label };
+
+ if (kind === 'tab') {
+ if (el.getAttribute('aria-selected') === 'true') entry.active = true;
+ } else if (kind === 'input' || kind === 'textarea') {
+ entry.type = (el.type || 'text').toLowerCase();
+ if (el.value) entry.value = truncate(el.value, 80);
+ } else if (kind === 'select') {
+ entry.value = el.value;
+ entry.options = Array.from(el.options)
+ .slice(0, 30)
+ .map((o) => o.textContent?.trim() || o.value)
+ .filter(Boolean);
+ } else if (kind === 'checkbox' || kind === 'radio') {
+ entry.checked = !!el.checked;
+ }
+
+ elements.push(entry);
+ }
+
+ return {
+ path: window.location.pathname + window.location.search,
+ title: findTitle(),
+ elements,
+ };
+};
+
+const normalize = (s) => (s || '')
+ .toLowerCase()
+ .replace(/\s+/g, ' ')
+ .trim()
+ .replace(/[.!?:;,"']+$/, '');
+
+export const findByRef = (ref) => {
+ if (ref === undefined || ref === null) return null;
+ return document.querySelector(`[data-voice-ref="${CSS.escape(String(ref))}"]`);
+};
+
+export const findByLabel = (label, kindHint) => {
+ const target = normalize(label);
+ if (!target) return null;
+ const all = Array.from(document.querySelectorAll('[data-voice-ref]'));
+ const candidates = all.map((el) => ({
+ el,
+ kind: classify(el),
+ lab: normalize(extractLabel(el)),
+ })).filter((c) => c.lab && c.kind);
+
+ const withKind = kindHint ? candidates.filter((c) => c.kind === kindHint) : candidates;
+ const pools = [withKind, candidates];
+ const matchers = [
+ (lab) => lab === target,
+ (lab) => lab.startsWith(target),
+ (lab) => lab.includes(target),
+ ];
+ for (const matcher of matchers) {
+ for (const pool of pools) {
+ const hit = pool.find((c) => matcher(c.lab));
+ if (hit) return hit.el;
+ }
+ }
+ return null;
+};
diff --git a/client/src/services/uiInteract.js b/client/src/services/uiInteract.js
new file mode 100644
index 0000000000..1ea7e5915f
--- /dev/null
+++ b/client/src/services/uiInteract.js
@@ -0,0 +1,81 @@
+// Executes voice UI commands (click / fill / select) against the live DOM.
+// Resolves targets via the stable ref assigned by domIndex.js, falling back
+// to label-based lookup when the ref is stale (DOM mutated between the
+// server's last index push and the side-effect dispatch).
+
+import { findByRef, findByLabel } from './domIndex.js';
+
+const resolve = (target, kindHint) => {
+ if (!target) return null;
+ if (target.ref !== undefined && target.ref !== null) {
+ const byRef = findByRef(target.ref);
+ if (byRef) return byRef;
+ }
+ if (target.label) return findByLabel(target.label, kindHint);
+ return null;
+};
+
+export const doClick = (target) => {
+ const el = resolve(target);
+ if (!el) return { ok: false, reason: 'not-found' };
+ el.scrollIntoView?.({ block: 'center', behavior: 'auto' });
+ el.focus?.();
+ el.click();
+ return { ok: true };
+};
+
+// React's controlled inputs ignore `.value = x` because React caches the
+// previous value on the prototype. Use the native setter so React's onChange
+// sees a real change.
+const setNativeValue = (el, value) => {
+ const proto = el.tagName === 'TEXTAREA'
+ ? window.HTMLTextAreaElement.prototype
+ : el.tagName === 'SELECT'
+ ? window.HTMLSelectElement.prototype
+ : window.HTMLInputElement.prototype;
+ const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set;
+ if (setter) setter.call(el, String(value));
+ else el.value = String(value);
+};
+
+export const doFill = (target, value) => {
+ let el = resolve(target, 'input');
+ if (!el) el = resolve(target, 'textarea');
+ if (!el) return { ok: false, reason: 'not-found' };
+ if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA') {
+ return { ok: false, reason: 'not-fillable' };
+ }
+ el.scrollIntoView?.({ block: 'center', behavior: 'auto' });
+ el.focus?.();
+ setNativeValue(el, value ?? '');
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ el.dispatchEvent(new Event('change', { bubbles: true }));
+ return { ok: true };
+};
+
+export const doSelect = (target, option) => {
+ const el = resolve(target, 'select');
+ if (!el) return { ok: false, reason: 'not-found' };
+ if (el.tagName !== 'SELECT') return { ok: false, reason: 'not-selectable' };
+ const wanted = String(option).toLowerCase().trim();
+ const opts = Array.from(el.options);
+ const match = opts.find((o) => (o.value || '').toLowerCase() === wanted)
+ || opts.find((o) => (o.textContent || '').toLowerCase().trim() === wanted)
+ || opts.find((o) => (o.textContent || '').toLowerCase().includes(wanted))
+ || opts.find((o) => (o.value || '').toLowerCase().includes(wanted));
+ if (!match) return { ok: false, reason: 'no-option' };
+ el.scrollIntoView?.({ block: 'center', behavior: 'auto' });
+ setNativeValue(el, match.value);
+ el.dispatchEvent(new Event('change', { bubbles: true }));
+ return { ok: true };
+};
+
+export const doSetCheckbox = (target, checked) => {
+ const el = resolve(target, 'checkbox') || resolve(target, 'radio');
+ if (!el) return { ok: false, reason: 'not-found' };
+ const desired = !!checked;
+ if (el.checked === desired) return { ok: true, noop: true };
+ el.scrollIntoView?.({ block: 'center', behavior: 'auto' });
+ el.click();
+ return { ok: true };
+};
diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.js
index d9f33ff591..cc7373330c 100644
--- a/server/services/voice/pipeline.js
+++ b/server/services/voice/pipeline.js
@@ -10,9 +10,90 @@ import { transcribe } from './stt.js';
import { synthesize } from './tts.js';
import { streamChat } from './llm.js';
import { getVoiceConfig } from './config.js';
-import { getToolSpecs, dispatchTool } from './tools.js';
+import { getToolSpecsForIntent, classifyIntent, dispatchTool, UI_KINDS } from './tools.js';
import { appendJournal, getToday } from '../brainJournal.js';
+// Compact per-page UI summary the LLM uses to drive ui_* tools. Keep it
+// short — every turn pays the token cost. Groups elements by kind and shows
+// label only; full state (values, options) is still available through
+// ui_list_interactables if the LLM needs more detail.
+const UI_SUMMARY_MAX_CHARS = 4000;
+const KIND_HEADINGS = {
+ tab: 'Tabs (* = active)',
+ button: 'Buttons',
+ link: 'Links',
+ input: 'Inputs',
+ textarea: 'Textareas',
+ select: 'Selects',
+ checkbox: 'Checkboxes',
+ radio: 'Radios',
+};
+const summarizeUi = (ui) => {
+ if (!ui || !Array.isArray(ui.elements) || !ui.elements.length) return null;
+ const groups = Object.fromEntries(UI_KINDS.map((k) => [k, []]));
+ for (const e of ui.elements) {
+ const g = groups[e.kind];
+ if (!g) continue;
+ let s = e.label;
+ if (e.kind === 'tab' && e.active) s = `${s}*`;
+ else if (e.kind === 'input' || e.kind === 'textarea') {
+ const type = e.type && e.type !== 'text' ? `:${e.type}` : '';
+ s = `${s}${type}`;
+ } else if (e.kind === 'select' && Array.isArray(e.options)) {
+ const opts = e.options.slice(0, 6).join('|');
+ s = `${s}[${opts}${e.options.length > 6 ? '…' : ''}]`;
+ } else if (e.kind === 'checkbox' || e.kind === 'radio') {
+ s = `${s}${e.checked ? '(✓)' : ''}`;
+ }
+ g.push(s);
+ }
+ const parts = [];
+ if (ui.title) parts.push(`Page: ${ui.title}${ui.path ? ` (${ui.path})` : ''}.`);
+ for (const k of UI_KINDS) {
+ if (groups[k].length) parts.push(`${KIND_HEADINGS[k]}: ${groups[k].slice(0, 40).join(', ')}.`);
+ }
+ const out = parts.join(' ');
+ // Hard cap so a page with hundreds of long labels can't blow past the
+ // LLM's practical context budget.
+ return out.length > UI_SUMMARY_MAX_CHARS ? `${out.slice(0, UI_SUMMARY_MAX_CHARS - 1)}…` : out;
+};
+
+// Only inject the per-turn UI summary when the user is plausibly trying to
+// drive the UI. Most voice turns ("what time", "how am I doing") don't need
+// the 2–4 KB page snapshot, and the LLM can still call ui_list_interactables
+// as an explicit fallback. Takes the pre-computed active group set so the
+// same regex doesn't run twice per turn.
+const shouldIncludeUi = (userText, activeGroups) => !userText || activeGroups?.has('ui');
+
+// After a ui_* side effect fires, pause briefly for the client to push a
+// fresh voice:ui:index so the next LLM iteration sees the post-action DOM
+// (e.g., a modal that just opened). Resolves with the new ui snapshot or
+// null on timeout/abort. Safe to call with no waiter infrastructure in
+// state (e.g., in tests) — just times out.
+const waitForUiRefresh = (state, timeoutMs, signal) => new Promise((resolve) => {
+ if (!state) { resolve(null); return; }
+ if (!Array.isArray(state.uiWaiters)) state.uiWaiters = [];
+ let done = false;
+ const finish = (value) => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ signal?.removeEventListener?.('abort', onAbort);
+ // Remove self from the pending list so timed-out/aborted waiters don't
+ // accumulate across turns. Next voice:ui:index would fire them as
+ // no-ops, but the array grows unbounded without this.
+ const i = state.uiWaiters.indexOf(finish);
+ if (i !== -1) state.uiWaiters.splice(i, 1);
+ resolve(value);
+ };
+ const onAbort = () => finish(null);
+ const timer = setTimeout(() => finish(null), timeoutMs);
+ signal?.addEventListener?.('abort', onAbort, { once: true });
+ state.uiWaiters.push(finish);
+});
+
+export { summarizeUi, shouldIncludeUi };
+
const buildSystemPrompt = (cfg) => {
if (!cfg.llm.usePersonality) return cfg.llm.systemPrompt;
const p = cfg.llm.personality || {};
@@ -36,7 +117,9 @@ const buildSystemPrompt = (cfg) => {
'You MUST call the matching tool whenever the user requests an action — ' +
'never describe the action in words instead of calling the tool. ' +
'Trigger phrases that REQUIRE a tool call: ' +
- '"open"/"go to"/"take me to"/"show me"/"navigate to" → matching navigation tool (e.g., daily_log_open with startDictation=false). ' +
+ '"open"/"go to"/"take me to"/"show me"/"navigate to" X → call ui_navigate with page=X (NOT daily_log_open — that tool is ONLY for the Daily Log / dictation). "Take me to tasks" → ui_navigate page="tasks". "Chief of staff agents" → ui_navigate page="agents". "Open calendar" → ui_navigate page="calendar". Only pick daily_log_open when the user explicitly says "daily log", "log entry", or "journal". ' +
+ '"Select X tab"/"switch to the X tab"/"click X"/"press the X button"/"pick Y from the Z dropdown"/"fill X with Y"/"check/uncheck X" — the LLM receives a compact "Current UI state" summary at the start of UI-driving turns listing Tabs, Buttons, Links, Inputs, Selects, Checkboxes. Use ui_click for tabs/buttons/links, ui_fill for text inputs, ui_select for dropdowns, ui_check for checkboxes. Pass the EXACT label shown in the UI summary. Prefer the `kind` argument when you have it (tab vs button). If the label isn\'t in the current UI summary, call ui_list_interactables OR ui_navigate first — do NOT guess. Active tab is marked with * in the summary; don\'t click it again. ' +
+ 'CHAINED UI FLOWS: after a ui_click / ui_fill / ui_select / ui_check succeeds, its tool result includes a `ui` field with the FRESH page state (a modal may have opened, a tab may have switched, new fields may be visible). Always re-read this `ui` field before choosing the next action — don\'t rely on the original per-turn UI summary after an action has fired. For multi-step flows like "create a task called Foo with description Bar": ui_click New Task → read result.ui → ui_fill Name=Foo → read result.ui → ui_fill Description=Bar → ui_click Save. Do it all in ONE turn, not one action per turn. ' +
'INTENT TO CREATE / WRITE in the daily log — phrases like "let\'s make a daily log", "let\'s make a new daily log", "start a daily log", "I want to make a log entry", "let me log something today", "new daily log", "let me add to my log" → call daily_log_open with startDictation=true. After this single tool call, STOP TALKING and let the user dictate freely — the dictation system handles every following utterance automatically without you. Do NOT say "I\'ll append it" or "what would you like to add" — the user already knows. Just confirm in one short sentence ("Daily log open, dictating now.") and stay quiet. ' +
'When the user is asking you to write something specific into the daily log right now — phrases like "add to my daily log: X", "note in today\'s log that X", "write in my log: X", "log this in my daily log: X", "for my daily log: X" — you MUST call daily_log_append with the exact X text (everything AFTER the leading "add … to my log" / "note that" / "for my log" phrasing). NEVER reply with just a paraphrased "add to my daily log: …" line — that\'s narration; CALL daily_log_append. ' +
'Empty-content intent — phrases that announce the user is about to dictate a note WITHOUT yet providing the note text — "add a note to my daily log" / "add another note to my daily log" / "add this other note to my daily log" / "I want to add to my log" / "let me add a note" — call daily_log_start_dictation (NOT daily_log_append, because there\'s no content to append yet). The user\'s next utterance will be captured by the dictation system. ' +
@@ -206,14 +289,23 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
return { transcript: userText, reply: '' };
}
+ const toolsEnabled = !!cfg.llm.tools?.enabled;
+ const intent = toolsEnabled ? getToolSpecsForIntent(userText) : { specs: undefined, activeGroups: classifyIntent(userText) };
+ const toolSpecs = intent.specs;
+
const messages = [
{ role: 'system', content: buildSystemPrompt(cfg) },
- ...history,
- { role: 'user', content: userText },
];
-
- const toolsEnabled = !!cfg.llm.tools?.enabled;
- const toolSpecs = toolsEnabled ? getToolSpecs() : undefined;
+ if (shouldIncludeUi(userText, intent.activeGroups)) {
+ const uiSummary = summarizeUi(state?.ui);
+ if (uiSummary) {
+ messages.push({
+ role: 'system',
+ content: `Current UI state — use ui_click / ui_fill / ui_select / ui_check to drive these. Names shown are the exact labels; pass them as the "label" argument. ${uiSummary}`,
+ });
+ }
+ }
+ messages.push(...history, { role: 'user', content: userText });
const maxIterations = Math.max(1, cfg.llm.tools?.maxIterations ?? 3);
let pending = '';
@@ -313,7 +405,7 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
const t0 = Date.now();
let result;
let args = {};
- const ctx = { sideEffects: [] };
+ const ctx = { sideEffects: [], state };
try {
args = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
const argSummary = Object.keys(args).length ? Object.entries(args).map(([k, v]) => `${k}=${JSON.stringify(v).slice(0, 40)}`).join(' ') : '—';
@@ -343,6 +435,29 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
emit('voice:dictation', { enabled: state.dictation.enabled, date: state.dictation.date });
} else if (fx.type === 'navigate') {
emit('voice:navigate', { path: fx.path });
+ } else if (fx.type === 'ui:click') {
+ emit('voice:ui:click', { target: fx.target });
+ } else if (fx.type === 'ui:fill') {
+ emit('voice:ui:fill', { target: fx.target, value: fx.value });
+ } else if (fx.type === 'ui:select') {
+ emit('voice:ui:select', { target: fx.target, option: fx.option });
+ } else if (fx.type === 'ui:check') {
+ emit('voice:ui:check', { target: fx.target, checked: fx.checked });
+ }
+ }
+ // If the tool mutated the UI, pause for the client's follow-up index
+ // push and attach the fresh summary to the tool result so the next LLM
+ // iteration can chain the next action against the new page state (e.g.
+ // click New Task → see the modal → fill Name → click Save, all in one
+ // turn). Short timeout so a dropped index doesn't stall voice.
+ const hasUiEffect = ctx.sideEffects.some((fx) => typeof fx.type === 'string' && fx.type.startsWith('ui:'));
+ if (hasUiEffect && !signal?.aborted) {
+ const tRefresh = Date.now();
+ const refreshed = await waitForUiRefresh(state, 800, signal);
+ tlog(`tool.refresh ${tc.function.name} ${refreshed ? 'ok' : 'timeout'} ${Date.now() - tRefresh}ms`);
+ if (refreshed) {
+ const summary = summarizeUi(refreshed);
+ if (summary) result = { ...result, ui: summary };
}
}
emit('voice:tool', { name: tc.function.name, args, result });
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
index 849b8fbea2..f7120c806e 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -14,6 +14,131 @@ import * as journal from '../brainJournal.js';
const DAILY_LOG_PATH = '/brain/daily-log';
+// Named pages the voice agent can navigate to. Keys are spoken-friendly aliases
+// (what the user is likely to say); values are app routes. Keep in sync with
+// Layout.jsx — when you add a nav item the user might ask for by voice, add
+// its alias(es) here.
+const NAV_PAGES = {
+ dashboard: '/',
+ home: '/',
+ apps: '/apps',
+ 'review-hub': '/review',
+ review: '/review',
+ cybercity: '/city',
+ city: '/city',
+ character: '/character',
+ data: '/data',
+ shell: '/shell',
+ browser: '/browser',
+ instances: '/instances',
+ loops: '/loops',
+ openclaw: '/openclaw',
+ 'social-agents': '/agents',
+ // Chief of Staff
+ 'chief-of-staff': '/cos/tasks',
+ cos: '/cos/tasks',
+ tasks: '/cos/tasks',
+ 'cos-tasks': '/cos/tasks',
+ 'cos-agents': '/cos/agents',
+ agents: '/cos/agents',
+ 'cos-briefing': '/cos/briefing',
+ briefing: '/cos/briefing',
+ 'cos-gsd': '/cos/gsd',
+ gsd: '/cos/gsd',
+ 'cos-health': '/cos/health',
+ 'cos-jobs': '/cos/jobs',
+ 'system-tasks': '/cos/jobs',
+ 'cos-schedule': '/cos/schedule',
+ schedule: '/cos/schedule',
+ 'cos-scripts': '/cos/scripts',
+ 'cos-memory': '/cos/memory',
+ 'cos-learning': '/cos/learning',
+ 'cos-productivity': '/cos/productivity',
+ streaks: '/cos/productivity',
+ 'cos-digest': '/cos/digest',
+ 'cos-config': '/cos/config',
+ // Brain
+ brain: '/brain/inbox',
+ 'brain-inbox': '/brain/inbox',
+ inbox: '/brain/inbox',
+ 'daily-log': '/brain/daily-log',
+ 'brain-digest': '/brain/digest',
+ 'brain-graph': '/brain/graph',
+ 'brain-links': '/brain/links',
+ 'brain-memory': '/brain/memory',
+ 'brain-notes': '/brain/notes',
+ notes: '/brain/notes',
+ 'brain-trust': '/brain/trust',
+ // Calendar
+ calendar: '/calendar/agenda',
+ agenda: '/calendar/agenda',
+ 'calendar-day': '/calendar/day',
+ 'calendar-week': '/calendar/week',
+ 'calendar-month': '/calendar/month',
+ 'calendar-lifetime': '/calendar/lifetime',
+ 'calendar-review': '/calendar/review',
+ 'calendar-sync': '/calendar/sync',
+ // Digital Twin
+ 'digital-twin': '/digital-twin/overview',
+ twin: '/digital-twin/overview',
+ 'twin-autobiography': '/digital-twin/autobiography',
+ 'twin-documents': '/digital-twin/documents',
+ 'twin-identity': '/digital-twin/identity',
+ 'twin-interview': '/digital-twin/interview',
+ // Goals & Insights
+ goals: '/goals/list',
+ insights: '/insights/overview',
+ // MeatSpace
+ meatspace: '/meatspace/overview',
+ 'meatspace-health': '/meatspace/health',
+ 'meatspace-body': '/meatspace/body',
+ 'meatspace-alcohol': '/meatspace/alcohol',
+ 'meatspace-nicotine': '/meatspace/nicotine',
+ 'meatspace-age': '/meatspace/age',
+ 'meatspace-blood': '/meatspace/blood',
+ 'meatspace-genome': '/meatspace/genome',
+ 'meatspace-lifestyle': '/meatspace/lifestyle',
+ // Messages
+ messages: '/messages/inbox',
+ drafts: '/messages/drafts',
+ // POST
+ post: '/post/launcher',
+ 'post-launcher': '/post/launcher',
+ 'post-history': '/post/history',
+ 'post-wordplay': '/post/wordplay',
+ // Wiki
+ wiki: '/wiki/overview',
+ 'wiki-browse': '/wiki/browse',
+ 'wiki-graph': '/wiki/graph',
+ 'wiki-search': '/wiki/search',
+ // Dev tools
+ devtools: '/devtools/runs',
+ 'ai-runs': '/devtools/runs',
+ 'ai-agents': '/devtools/agents',
+ 'feature-agents': '/feature-agents',
+ 'devtools-github': '/devtools/github',
+ github: '/devtools/github',
+ 'devtools-jira': '/devtools/jira',
+ jira: '/devtools/jira',
+ 'devtools-datadog': '/devtools/datadog',
+ datadog: '/devtools/datadog',
+ 'devtools-history': '/devtools/history',
+ 'devtools-processes': '/devtools/processes',
+ 'devtools-usage': '/devtools/usage',
+ 'devtools-runner': '/devtools/runner',
+ 'devtools-submodules': '/devtools/submodules',
+ // Settings
+ settings: '/settings/backup',
+ 'settings-voice': '/settings/voice',
+ 'settings-telegram': '/settings/telegram',
+ 'settings-database': '/settings/database',
+ prompts: '/prompts',
+ providers: '/ai',
+ 'ai-providers': '/ai',
+ security: '/security',
+ uploads: '/uploads',
+};
+
// Shorthand presets for voice logging. A user saying "I had a beer" should
// not need to recite oz + ABV — these defaults match typical US servings.
const DRINK_PRESETS = {
@@ -30,6 +155,113 @@ const NICOTINE_PRESETS = {
pouch: { mgPerUnit: 6 },
};
+// Shared with pipeline.js (summarizeUi) and the client's domIndex.classify.
+// Mirror of the client-side kinds; keep in sync.
+export const UI_KINDS = ['tab', 'button', 'link', 'input', 'textarea', 'select', 'checkbox', 'radio'];
+
+// Per-turn tool filtering. Small models (qwen3-4b, granite, etc.) choke when
+// given 25 tools — the schema alone is 10+ KB and routing accuracy tanks.
+// Group each tool by domain; expose only the groups whose intent regex
+// matches the user's utterance, plus the always-on set. "open the tasks
+// page" sees ~8 tools instead of 25; "I had a beer" sees ~8 instead of 25.
+const TOOL_GROUPS = {
+ brain_search: 'brain',
+ brain_list_recent: 'brain',
+ meatspace_log_drink: 'meatspace',
+ meatspace_log_nicotine: 'meatspace',
+ meatspace_summary_today: 'meatspace',
+ meatspace_log_weight: 'meatspace',
+ goal_list: 'goals',
+ goal_update_progress: 'goals',
+ goal_log_note: 'goals',
+ pm2_status: 'system',
+ pm2_restart: 'system',
+ feeds_digest: 'feeds',
+ daily_log_open: 'dailylog',
+ daily_log_start_dictation: 'dailylog',
+ daily_log_stop_dictation: 'dailylog',
+ daily_log_read: 'dailylog',
+ ui_list_interactables: 'ui',
+ ui_click: 'ui',
+ ui_fill: 'ui',
+ ui_select: 'ui',
+ ui_check: 'ui',
+ // UNGROUPED = always-on: time_now, brain_capture, daily_log_append,
+ // ui_navigate. These cover the highest-frequency intents.
+};
+
+// Loose on purpose — false positives are cheap (one extra tool), false
+// negatives are expensive (LLM guesses wrong or can't act).
+export const UI_INTENT_RE = /\b(click|press|tap|hit|open|go to|take me|show me|navigate|select|pick|switch|choose|tab|button|dropdown|field|input|fill|enter|type|write|check|uncheck|toggle|link|option|on (?:this|the) page|what(?:'s)? (?:on|here))\b/i;
+const GROUP_INTENT = {
+ brain: /\b(search|find|look ?up|recall|what did I (?:say|write|note)|brain|inbox|capture)\b/i,
+ meatspace: /\b(drink|drank|beer|wine|whiskey|shot|cocktail|cigarette|vape|pouch|nicotine|weigh|pound|kilo|kg|smoke|smoking|how am I|summary today|log (?:a|my) (?:drink|weight|nicotine))\b/i,
+ goals: /\b(goals?|progress|objective)\b/i,
+ system: /\b(restart|crash(?:ed)?|pm2|process|service|is.*(?:running|down|up)|status)\b/i,
+ feeds: /\b(feeds?|news|unread|article|rss|digest)\b/i,
+ dailylog: /\b(daily ?log|journal|dictat|log entry|log something|to my log|read (?:back )?my log)\b/i,
+ ui: UI_INTENT_RE,
+};
+
+// Fail-fast at import time: any group referenced in TOOL_GROUPS that has no
+// matching GROUP_INTENT entry means a tool silently never reaches the LLM.
+// A typo (`'daily_log'` vs `'dailylog'`) is otherwise invisible until the
+// user tries that group and the LLM has no tool to call.
+for (const [name, group] of Object.entries(TOOL_GROUPS)) {
+ if (!(group in GROUP_INTENT)) {
+ throw new Error(`voice tools: TOOL_GROUPS[${name}] = "${group}" but no GROUP_INTENT.${group} regex defined`);
+ }
+}
+
+const normalizeLabel = (s) => (s || '')
+ .toLowerCase()
+ .replace(/\s+/g, ' ')
+ .trim()
+ .replace(/[.!?:;,"']+$/, '');
+
+// Accepts one kind OR an array of kinds for multi-kind tools like ui_fill
+// (input|textarea) and ui_check (checkbox|radio). The error pool and label
+// come from the union so the LLM sees the correct "available" list.
+const findUiElement = (ctx, label, kindHint) => {
+ const ui = ctx?.state?.ui;
+ if (!ui || !Array.isArray(ui.elements) || !ui.elements.length) {
+ return {
+ entry: null,
+ err: {
+ ok: false,
+ error: 'No UI index available',
+ summary: 'I don\'t see the page contents yet — reload the voice widget and try again.',
+ },
+ };
+ }
+ const kinds = Array.isArray(kindHint) ? kindHint : (kindHint ? [kindHint] : null);
+ const target = normalizeLabel(label);
+ const withKind = kinds ? ui.elements.filter((e) => kinds.includes(e.kind)) : ui.elements;
+ const pools = kinds ? [withKind, ui.elements] : [ui.elements];
+ const matchers = [
+ (lab) => lab === target,
+ (lab) => lab.startsWith(target),
+ (lab) => lab.includes(target),
+ ];
+ for (const matcher of matchers) {
+ for (const pool of pools) {
+ const hit = pool.find((e) => matcher(normalizeLabel(e.label)));
+ if (hit) return { entry: hit, err: null };
+ }
+ }
+ const available = (kinds ? withKind : ui.elements).slice(0, 12).map((e) => e.label);
+ const kindLabel = kinds ? kinds.join('/') : 'element';
+ return {
+ entry: null,
+ err: {
+ ok: false,
+ error: `No ${kindLabel} matching "${label}" on this page`,
+ available,
+ summary: `I don't see "${label}" on this page. Available: ${available.join(', ') || 'none'}.`,
+ },
+ };
+};
+
const resolveDrinkPreset = (name) => {
const key = Object.keys(DRINK_PRESETS).find((k) => name.toLowerCase().includes(k));
return key ? DRINK_PRESETS[key] : DRINK_PRESETS.beer;
@@ -508,7 +740,7 @@ const TOOLS = [
{
name: 'daily_log_open',
description:
- 'Open the Daily Log page in the UI and optionally start voice dictation mode. ' +
+ 'Open the Daily Log page AND (typically) start dictation. ONLY use when the user explicitly mentions "daily log", "log entry", "journal", or dictation — NEVER use this as a generic "take me to a page" tool; for any other destination call ui_navigate instead. ' +
'Use when the user says "open my daily log", "take me to my daily log", "go to daily log", "let\'s make a daily log", "let\'s make a new daily log", "I want to make a log entry", "start my daily log", "new daily log", "let me add to my log". ' +
'Set startDictation=true (DEFAULT for create-intent phrasings) when the user wants to write content right now — i.e., they said any of: "make"/"start"/"new"/"create"/"dictate"/"record"/"talk into"/"log something". ' +
'Set startDictation=false ONLY when the user explicitly just wants to LOOK at the page without writing — i.e., they said "show me", "open"/"go to" without any create/write verb. ' +
@@ -624,6 +856,165 @@ const TOOLS = [
},
},
+ {
+ name: 'ui_navigate',
+ description:
+ 'Navigate the UI to a page. Use for "take me to X" / "open X" / "go to X" EXCEPT Daily Log (use daily_log_open). ' +
+ 'Pass `page` as a short name the user would say: tasks, agents, gsd, briefing, calendar, goals, brain, meatspace, memory, messages, settings, shell, instances, wiki, character, health, body, alcohol, etc. ' +
+ 'Server resolves fuzzy — "chief of staff tasks", "cos tasks", "task page" all map to tasks. If no match, the error lists valid names.',
+ parameters: {
+ type: 'object',
+ properties: {
+ page: {
+ type: 'string',
+ description: 'Short page name the user said (e.g. "tasks", "calendar"). Server fuzzy-matches.',
+ },
+ path: {
+ type: 'string',
+ description: 'Explicit route path starting with / (e.g. "/cos/tasks"). Only when page doesn\'t fit.',
+ },
+ },
+ },
+ execute: async ({ page, path } = {}, ctx = {}) => {
+ let target = null;
+ let resolvedKey = null;
+ if (page && typeof page === 'string') {
+ const norm = normalizeLabel(page).replace(/\s+/g, '-');
+ const keys = Object.keys(NAV_PAGES);
+ // Tiered match: exact → key prefixes norm → norm prefixes key → key
+ // contained in norm (so "chief-of-staff-tasks" finds "tasks") → key
+ // contains norm substring. Last word tried as a standalone key at
+ // the end since voice phrasings often end with the target page.
+ const tail = norm.split('-').filter(Boolean).pop();
+ const picks = [
+ keys.find((k) => k === norm),
+ keys.find((k) => norm.startsWith(k) && k.length >= 3),
+ keys.find((k) => k.startsWith(norm)),
+ keys.find((k) => norm.endsWith(`-${k}`) && k.length >= 3),
+ keys.find((k) => norm.includes(k) && k.length >= 4),
+ keys.find((k) => k.includes(norm)),
+ tail && tail !== norm ? keys.find((k) => k === tail) : null,
+ ];
+ const hit = picks.find(Boolean);
+ if (hit) { target = NAV_PAGES[hit]; resolvedKey = hit; }
+ }
+ if (!target && path && typeof path === 'string' && path.startsWith('/')) target = path;
+ if (!target) {
+ const suggestions = ['tasks', 'agents', 'gsd', 'briefing', 'calendar', 'goals', 'brain', 'meatspace', 'messages', 'settings', 'shell', 'instances'];
+ return {
+ ok: false,
+ error: `Unknown page "${page || path || ''}"`,
+ suggestions,
+ summary: `I don't know that page. Try: ${suggestions.slice(0, 6).join(', ')}.`,
+ };
+ }
+ ctx.sideEffects?.push({ type: 'navigate', path: target });
+ return { ok: true, path: target, summary: `Opened ${resolvedKey || target}.` };
+ },
+ },
+
+ {
+ name: 'ui_list_interactables',
+ description: 'List interactive elements on the current page. Fallback when the per-turn UI summary isn\'t enough.',
+ parameters: {
+ type: 'object',
+ properties: {
+ kind: { type: 'string', enum: UI_KINDS, description: 'Optional kind filter.' },
+ },
+ },
+ execute: async ({ kind } = {}, ctx = {}) => {
+ const ui = ctx.state?.ui;
+ if (!ui || !Array.isArray(ui.elements)) {
+ return { ok: false, error: 'No UI index available. The user may not have the voice widget loaded.' };
+ }
+ const items = kind ? ui.elements.filter((e) => e.kind === kind) : ui.elements;
+ return {
+ ok: true,
+ path: ui.path,
+ title: ui.title,
+ count: items.length,
+ items: items.slice(0, 100),
+ summary: `${items.length} interactive element${items.length === 1 ? '' : 's'} on ${ui.title || ui.path || 'this page'}.`,
+ };
+ },
+ },
+
+ {
+ name: 'ui_click',
+ description: 'Click a tab, button, or link on the current page by visible label. "Select Memory tab" → label="Memory", kind="tab".',
+ parameters: {
+ type: 'object',
+ properties: {
+ label: { type: 'string', description: 'Visible label.' },
+ kind: { type: 'string', enum: ['tab', 'button', 'link'], description: 'Optional kind hint.' },
+ },
+ required: ['label'],
+ },
+ execute: async ({ label, kind } = {}, ctx = {}) => {
+ const hit = findUiElement(ctx, label, kind);
+ if (!hit.entry) return hit.err;
+ ctx.sideEffects?.push({ type: 'ui:click', target: { ref: hit.entry.ref, label: hit.entry.label } });
+ return { ok: true, label: hit.entry.label, kind: hit.entry.kind, summary: `Clicked ${hit.entry.label}.` };
+ },
+ },
+
+ {
+ name: 'ui_fill',
+ description: 'Type text into an input or textarea by its label. Use ui_select for dropdowns, ui_check for checkboxes.',
+ parameters: {
+ type: 'object',
+ properties: {
+ label: { type: 'string', description: 'Visible label of the input.' },
+ value: { type: 'string', description: 'Text to fill in.' },
+ },
+ required: ['label', 'value'],
+ },
+ execute: async ({ label, value } = {}, ctx = {}) => {
+ const hit = findUiElement(ctx, label, ['input', 'textarea']);
+ if (!hit.entry) return hit.err;
+ ctx.sideEffects?.push({ type: 'ui:fill', target: { ref: hit.entry.ref, label: hit.entry.label }, value: String(value ?? '') });
+ return { ok: true, label: hit.entry.label, summary: `Filled ${hit.entry.label}.` };
+ },
+ },
+
+ {
+ name: 'ui_select',
+ description: 'Pick an option from a <select> dropdown by label. "Set status to Active" → label="Status", option="Active".',
+ parameters: {
+ type: 'object',
+ properties: {
+ label: { type: 'string', description: 'Visible label of the select.' },
+ option: { type: 'string', description: 'Option text or value.' },
+ },
+ required: ['label', 'option'],
+ },
+ execute: async ({ label, option } = {}, ctx = {}) => {
+ const hit = findUiElement(ctx, label, 'select');
+ if (!hit.entry) return hit.err;
+ ctx.sideEffects?.push({ type: 'ui:select', target: { ref: hit.entry.ref, label: hit.entry.label }, option: String(option) });
+ return { ok: true, label: hit.entry.label, option, summary: `Selected ${option} on ${hit.entry.label}.` };
+ },
+ },
+
+ {
+ name: 'ui_check',
+ description: 'Toggle a checkbox or radio by label. checked=true to check, false to uncheck.',
+ parameters: {
+ type: 'object',
+ properties: {
+ label: { type: 'string', description: 'Visible label.' },
+ checked: { type: 'boolean', description: 'Desired state.' },
+ },
+ required: ['label', 'checked'],
+ },
+ execute: async ({ label, checked } = {}, ctx = {}) => {
+ const hit = findUiElement(ctx, label, ['checkbox', 'radio']);
+ if (!hit.entry) return hit.err;
+ ctx.sideEffects?.push({ type: 'ui:check', target: { ref: hit.entry.ref, label: hit.entry.label }, checked: !!checked });
+ return { ok: true, label: hit.entry.label, checked: !!checked, summary: `${checked ? 'Checked' : 'Unchecked'} ${hit.entry.label}.` };
+ },
+ },
+
{
name: 'time_now',
description:
@@ -648,10 +1039,38 @@ const TOOLS = [
},
];
-export const getToolSpecs = () => TOOLS.map((t) => ({
+const toSpec = (t) => ({
type: 'function',
function: { name: t.name, description: t.description, parameters: t.parameters },
-}));
+});
+
+export const getToolSpecs = () => TOOLS.map(toSpec);
+
+// Intent-filtered spec list. Pass the user's current utterance; returns the
+// filtered spec array PLUS the set of active groups so downstream consumers
+// (pipeline.js → shouldIncludeUi) don't have to re-run the same regexes.
+// Cuts ~25 tools to ~8–12 per turn so small tool-use models (qwen3-4b etc.)
+// don't choke.
+export const classifyIntent = (userText) => {
+ const active = new Set();
+ if (!userText) return active;
+ for (const [group, re] of Object.entries(GROUP_INTENT)) {
+ if (re.test(userText)) active.add(group);
+ }
+ return active;
+};
+
+export const getToolSpecsForIntent = (userText) => {
+ if (!userText) return { specs: getToolSpecs(), activeGroups: new Set() };
+ const activeGroups = classifyIntent(userText);
+ const specs = TOOLS
+ .filter((t) => {
+ const group = TOOL_GROUPS[t.name];
+ return !group || activeGroups.has(group);
+ })
+ .map(toSpec);
+ return { specs, activeGroups };
+};
export const dispatchTool = async (name, args, ctx) => {
const tool = TOOLS.find((t) => t.name === name);
diff --git a/server/sockets/voice.js b/server/sockets/voice.js
index 632c011e4b..e1f383b87b 100644
--- a/server/sockets/voice.js
+++ b/server/sockets/voice.js
@@ -1,8 +1,9 @@
// Per-socket voice handlers.
// Inbound: voice:turn | voice:text | voice:interrupt | voice:reset
-// | voice:dictation:set
+// | voice:dictation:set | voice:ui:index
// Outbound: voice:transcript | voice:llm:delta | voice:llm:done | voice:tts:audio
// | voice:tool | voice:dictation | voice:navigate
+// | voice:ui:click | voice:ui:fill | voice:ui:select | voice:ui:check
// | voice:dailyLog:appended | voice:error | voice:idle
import { runTurn } from '../services/voice/pipeline.js';
@@ -29,6 +30,12 @@ export const registerVoiceHandlers = (socket) => {
history: [],
ctrl: null,
dictation: { enabled: false, date: null },
+ ui: null, // { path, title, elements:[{ ref, kind, label, ... }], updatedAt }
+ // Promises awaiting the NEXT voice:ui:index arrival — used by the
+ // pipeline to chain ui_* actions within one LLM turn: after firing a
+ // ui:click, wait for the client's fresh index before the next tool
+ // runs so the LLM can see the modal/new content it just opened.
+ uiWaiters: [],
};
const pushHistory = (role, content) => {
@@ -172,7 +179,37 @@ export const registerVoiceHandlers = (socket) => {
socket.emit('voice:dictation', { enabled: state.dictation.enabled, date: state.dictation.date });
});
+ // Client pushes the current page's DOM index whenever voice is enabled
+ // and the user navigates or the DOM mutates. The pipeline injects a
+ // compact summary into each LLM turn so it can drive the UI by label
+ // (ui_click, ui_fill, ui_select, ui_check).
+ socket.on('voice:ui:index', (payload) => {
+ if (!payload || typeof payload !== 'object') return;
+ const { path, title, elements } = payload;
+ if (!Array.isArray(elements)) return;
+ // Cap to avoid prompt bloat from a malicious or runaway client.
+ const MAX = 200;
+ const filtered = elements
+ .filter((e) => e && typeof e === 'object' && typeof e.ref === 'number' && typeof e.label === 'string')
+ .slice(0, MAX);
+ state.ui = {
+ path: typeof path === 'string' ? path.slice(0, 256) : null,
+ title: typeof title === 'string' ? title.slice(0, 120) : null,
+ elements: filtered,
+ updatedAt: Date.now(),
+ };
+ if (state.uiWaiters.length) {
+ const waiters = state.uiWaiters;
+ state.uiWaiters = [];
+ waiters.forEach((resolve) => resolve(state.ui));
+ }
+ });
+
socket.on('disconnect', () => {
state.ctrl?.abort();
+ // Abort any pending UI refresh waiters so their turns don't hang.
+ const waiters = state.uiWaiters;
+ state.uiWaiters = [];
+ waiters.forEach((resolve) => resolve(null));
});
};