100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.
feat(insurance-claim): field notebook intake on Gemini 3.8 Live with camera evidence and incident sketches
cid2cf03d405ab
diff --git a/README.md b/README.mdindex 1ecb7605..475c4c2a 100644--- a/README.md+++ b/README.md@@ -167,7 +167,7 @@ streamlit run travel_agent.py* [π£οΈ AI Audio Tour Agent](voice_ai_agents/ai_audio_tour_agent/) - Self-guided audio tours from your location, interests, and pace* [π Customer Support Voice Agent](voice_ai_agents/customer_support_voice_agent/) - Voice answers grounded in your own docs-* [π‘οΈ Insurance Claim Live Agent Team](voice_ai_agents/insurance_claim_live_agent_team/) - Real-time voice claim intake with Gemini Live+* [π‘οΈ Insurance Claim Live Agent Team](voice_ai_agents/insurance_claim_live_agent_team/) - Voice claim intake on Gemini 3.8 Live that writes a field notebook, looks at damage through the webcam, and sketches the incident* [π Voice RAG Agent (OpenAI SDK)](voice_ai_agents/voice_rag_openaisdk/) - Ask your PDFs questions, hear the answers* [ποΈ OpenSource Voice Dictation Agent (Wispr Flow clone)](https://github.com/akshayaggarwal99/jarvis-ai-assistant) <sub>β external</sub> - Open-source dictation that types where you talkdiff --git a/voice_ai_agents/insurance_claim_live_agent_team/.env.example b/voice_ai_agents/insurance_claim_live_agent_team/.env.exampleindex 79446d16..6a711d26 100644--- a/voice_ai_agents/insurance_claim_live_agent_team/.env.example+++ b/voice_ai_agents/insurance_claim_live_agent_team/.env.example@@ -2,6 +2,11 @@GOOGLE_GENAI_USE_VERTEXAI=FalseGOOGLE_API_KEY=replace-me+# Optional Gemini Live settings. Defaults are shown.+# FNOL_GEMINI_LIVE_MODEL=gemini-3.8-live+# FNOL_SKETCH_MODEL=gemini-3.1-flash-image+# FNOL_VOICE=Kore+# Optional Vertex AI settings for future Agent Platform work.# GOOGLE_GENAI_USE_VERTEXAI=True# GOOGLE_CLOUD_PROJECT=your-project-iddiff --git a/voice_ai_agents/insurance_claim_live_agent_team/README.md b/voice_ai_agents/insurance_claim_live_agent_team/README.mdindex fb62511d..fbf86998 100644--- a/voice_ai_agents/insurance_claim_live_agent_team/README.md+++ b/voice_ai_agents/insurance_claim_live_agent_team/README.md@@ -1,35 +1,50 @@# Insurance Claim Live Agent Team-A voice-first insurance claim intake app that lets a claimant talk naturally while the agent builds a structured claim packet in real time. The UI shows the live conversation, extracted claim facts, operator guidance, missing items, and an adjuster-ready handoff.+A voice-first insurance claim intake app built on Gemini 3.8 Live, where the claim is not a form but a field notebook that writes itself while the claimant talks. The claimant can turn on their camera and show the damage. The agent looks, describes what it sees, and tapes the frame into the notebook. Once it understands the scene it draws a pen sketch of the incident and asks the claimant whether it looks right. Behind the page, a background agent team verifies the policy, extracts claim facts, applies deterministic intake rules, and builds an adjuster-ready packet.-This is designed as a realistic first notice of loss (FNOL) workflow: the claimant does not need to fill out a rigid form, and the operator does not need to manually translate a messy conversation into claim fields.+This is designed as a realistic first notice of loss (FNOL) workflow: the claimant does not need to fill out a rigid form, the operator sees a page they can read at a glance, and the adjuster still gets a structured packet.+## What Gemini 3.8 Live makes possible++Gemini 3.8 Live takes audio and camera frames in the same session, speaks back, and runs function calls in the background while the conversation continues. This app leans on all three:++- **It listens and writes.** Facts the claim team extracts appear on the notebook page as handwritten lines with an ink animation. Blockers show up as red questions with a blank to fill. The routing decision is a rubber stamp.+- **It looks.** The claimant taps "Show camera" and frames stream into the live session at one per second. When the agent sees something relevant (a water line, a dent, a receipt), it says so out loud and calls `pin_evidence_photo`. The frame it was looking at gets taped into the notebook with the agent's own observation written underneath, and that observation feeds the claim team as evidence.+- **It draws.** Once the agent knows where it happened and what happened, it calls `draw_incident_sketch` with an illustrator brief. An image model draws a rough pen sketch (basement floor plan, intersection, hotel corridor) that gets pinned to the page, and the agent asks "does this look right?" Corrections by voice trigger a redraw. Confirming a picture catches misunderstandings a form never surfaces.+- **It reports only what it sees.** The pin tool asks the agent for its own observation, what the claimant said it was, and whether the frame confirms it. Told "you can see the big crack, right?" while looking at a smudge, the agent answers that it sees a small dark mark, asks for a closer view, and pins the frame marked not confirmed. The adjuster sees both the claim and the observation.+- **It never stops talking to wait.** Every tool is declared `NON_BLOCKING`. Routine results are scheduled `WHEN_IDLE`, so they land between turns. When the claim team detects injury or an unsafe home, the response is scheduled `INTERRUPT`, so the agent stops mid-sentence and escalates to a human.+## Features-### Voice + Text Claim Intake+### Live call-- Native voice conversation with the claim intake agent-- Real-time transcript for claimant and agent turns-- Text input fallback for typed claim details-- Live audio responses from the agent+- Native voice conversation with Gemini 3.8 Live, with audio replies and live transcripts+- Webcam sharing so the agent can see the damage while you describe it+- Typed turns go through the same live session, so the demo works without a microphone+- A "still needed" checklist and a claim team activity feed beside the call-### Real-Time Claim Packet+### The notebook-- Automatically extracts claimant name, contact method, policy number, loss type, date, location, description, safety details, evidence, and report numbers-- Updates the claim state as the conversation progresses-- Highlights missing or uncertain information-- Builds an adjuster handoff packet while the call is still happening+- Handwritten notes for name, policy, location, date, what happened, injuries, contact, and evidence+- Policy verification as a green tick in the margin, or a red flag for lapsed or unknown policies+- Red blanks for blocking intake items+- Camera frames taped in as polaroids with the agent's captions+- A pen sketch of the incident scene, redrawn when the claimant corrects it+- A rubber stamp for the routing decision: needs docs, ready for adjuster, SIU review, or escalate to human+- The full adjuster packet in Markdown behind one button-### Operator Guidance+### Background agent team-- Shows the current claim disposition-- Suggests the next best question or confirmation-- Lists blocking items before handoff-- Separates the operator-facing summary from the lower-level audit trail+| Tool | What it does | Scheduling |+| --- | --- | --- |+| `lookup_policy` | Verifies the policy number against a mock policy directory | When idle, or interrupt if the policy is lapsed |+| `sync_claim_packet` | Runs the ADK claim graph on the conversation plus camera observations and returns routing and the open items the packet still needs. The agent treats them as a checklist to raise when the current topic closes, not a script | When idle, or interrupt on safety escalation |+| `pin_evidence_photo` | Tapes the current camera frame into the notebook with the agent's own observation, the claimant's description, and whether the frame confirms it | When idle |+| `draw_incident_sketch` | Draws a pen sketch of the scene with the image model | When idle |-### Insurance-Specific Routing+### Insurance-specific routing- Handles home water damage, auto collision, theft/property loss, travel claims, medical reimbursement examples, and unclear claims- Applies deterministic evidence and document checks@@ -38,41 +53,69 @@ This is designed as a realistic first notice of loss (FNOL) workflow: the claima## App Engine-The app combines live voice, an ADK graph, structured extraction, and deterministic insurance rules:-| Layer | Model / Engine | Purpose || --- | --- | --- |-| Live voice | `gemini-3.1-flash-live-preview` | Voice-to-voice conversation, audio responses, and transcription |+| Live voice and vision | `gemini-3.8-live` | Voice-to-voice conversation, camera frame understanding, transcription, background tool calling |+| Sketches | `gemini-3.1-flash-image` | Pen sketch of the incident scene from the agent's brief |+| Background tools | `live_demo/live_tools.py` | Declares the four `NON_BLOCKING` tools, the system instruction, and the sketch prompt |+| Policy directory | `policy_directory.py` | Mock policy administration records used by `lookup_policy` || ADK graph | `root_agent` in `agent.py` | Source of truth for claim normalization, classification, validation, routing, and packet generation |-| Structured extraction | `gemini-3-flash-preview` | Converts messy claim language into structured claim facts inside the ADK graph |+| Structured extraction | `gemini-3.8-flash` | Converts messy claim language and camera observations into structured claim facts inside the ADK graph || Business rules | Python FunctionNodes + Pydantic | Deterministic missing-field checks, evidence gates, safety routing, SIU signals, and handoff packet output |-| App backend | FastAPI | Serves the frontend, manages WebSocket audio, and calls `run_claim_workflow()` from `agent.py` after each claimant turn |-| Frontend | HTML, CSS, JavaScript | Dark professional live cockpit for voice, transcript, claim state, and handoff |+| App backend | FastAPI | Serves the frontend, manages the Gemini Live WebSocket, executes tool calls, and calls `run_claim_workflow()` |+| Frontend | HTML, CSS, JavaScript | The desk: a call card, the notebook page, and the adjuster packet |## How It Works`agent.py` owns the production claim workflow. It exposes the ADK `root_agent` and a `run_claim_workflow()` helper that runs the graph programmatically for the live app.-`server.py` owns the live web transport. It manages the browser session, Gemini Live audio stream, transcripts, and FastAPI routes. It does not duplicate extraction, classification, evidence, routing, or packet logic.+`live_demo/live_tools.py` owns the Gemini 3.8 Live configuration: the system instruction, the four background tool declarations, the sketch prompt, and the scheduling rules.-The live app flow is:+`live_demo/server.py` owns the live web transport. It manages the browser session, the Gemini Live audio and video stream, transcripts, tool execution, the pinned photos and sketch, and FastAPI routes. It does not duplicate extraction, classification, evidence, routing, or packet logic.```text-Claimant speaks or types+Claimant talks, types, or shows the camera|v-server.py captures the turn+Gemini 3.8 Live keeps the conversation going+ | \+ | \ NON_BLOCKING tool calls+ | v+ | lookup_policy -> policy_directory.py+ | sync_claim_packet -> run_claim_workflow() -> ADK graph+ | pin_evidence_photo -> latest camera frame + observation+ | draw_incident_sketch -> gemini-3.1-flash-image+ | |+ | v+ | FunctionResponse with scheduling+ | (INTERRUPT on safety escalation, WHEN_IDLE otherwise)+ v |+Agent confirms the policy, describes the photo, asks about the sketch, or escalates|v-run_claim_workflow() executes root_agent+server.py streams transcript, tool activity, photos, sketch, and claim state|v-ADK graph runs LLM nodes + deterministic FunctionNodes- |- v-server.py renders the returned claim state in the UI+The notebook page writes, tapes, pins, and stamps```+The claim graph also runs automatically after every finalized claimant turn, so the notebook stays current even if the model has not called `sync_claim_packet` yet. Results are cached per transcript snapshot, so a tool call that lands right after an automatic run reuses it instead of paying for a second extraction. Camera observations from `pin_evidence_photo` are appended to the text the graph reads, so the claim writer treats them as evidence.++## Demo Policy Numbers++The mock policy directory lines up with the prompts in `examples.py`. Say one of these on the call to see the policy desk in action:++| Policy number | Policyholder | Line | Status |+| --- | --- | --- | --- |+| H0-44721 | Maya Singh | Homeowners with water backup endorsement | Active |+| AUTO-90210 | Jordan Lee | Personal auto with medical payments | Active |+| RNT-3008 | Priya Shah | Renters | Active |+| TRV-7711 | Alex Chen | Single trip travel | Active |+| MED-5520 | Sam Rivera | Supplemental medical reimbursement | Active |+| AUTO-11111 | Chris Park | Personal auto | Lapsed, routes to human review |++Any other number returns a not-found result and the agent asks the claimant to confirm it.+## Project Structure```text@@ -80,6 +123,7 @@ insurance_claim_live_agent_team/|-- agent.py|-- schemas.py|-- policies.py+|-- policy_directory.py|-- examples.py|-- requirements.txt|-- .env.example@@ -89,6 +133,7 @@ insurance_claim_live_agent_team/| |-- index.html| |-- styles.css| |-- app.js+| |-- live_tools.py| `-- server.py`-- README.md```@@ -112,6 +157,14 @@ GOOGLE_GENAI_USE_VERTEXAI=FalseGOOGLE_API_KEY=your-google-api-key```+Optional settings:++| Variable | Default | Purpose |+| --- | --- | --- |+| `FNOL_GEMINI_LIVE_MODEL` | `gemini-3.8-live` | Live voice and vision model |+| `FNOL_SKETCH_MODEL` | `gemini-3.1-flash-image` | Image model for the incident sketch |+| `FNOL_VOICE` | `Kore` | Prebuilt voice for audio responses |+## Run the AppStart the backend and frontend server:@@ -126,4 +179,12 @@ Open the app:http://127.0.0.1:4177/index.html```-Use the microphone button to start a live claim conversation, or type into the text box if microphone access is unavailable.+Tap "Talk" to start the live call, or type a claimant turn into the text box; typed turns go through the same live session, so you still hear the agent and see the notebook fill in. Tap "Show camera" to let the agent see the damage. Point it at a wet wall, a dented bumper, a receipt, or even a sketch on paper, and the agent will describe what it sees and tape the frame into the notebook.++Try this opening line to see the whole team run at once:++```text+Hi, this is Maya Singh, policy H0-44721. Our finished basement in Denver flooded last night when the sump pump failed. Nobody is hurt. The water came in by the stairs and spread across the carpet toward the boxes.+```++The agent confirms the homeowners policy while the claim writer extracts the facts, draws a floor plan of the basement, and asks whether the sketch looks right, then asks for the best contact method because that is the first blocking item the rules report.diff --git a/voice_ai_agents/insurance_claim_live_agent_team/agent.py b/voice_ai_agents/insurance_claim_live_agent_team/agent.pyindex 1d5718e2..b83b481c 100644--- a/voice_ai_agents/insurance_claim_live_agent_team/agent.py+++ b/voice_ai_agents/insurance_claim_live_agent_team/agent.py@@ -52,7 +52,7 @@ except ImportError:)-MODEL = "gemini-3-flash-preview"+MODEL = "gemini-3.8-flash"APP_NAME = "insurance_claim_live_agent_team"diff --git a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/app.js b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/app.jsindex a16385c6..b191d221 100644--- a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/app.js+++ b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/app.js@@ -1,21 +1,30 @@const transcriptEl = document.querySelector("#transcript");-const claimFieldsEl = document.querySelector("#claimFields");-const timelineEl = document.querySelector("#timeline");-const handoffEl = document.querySelector("#handoff");-const packetMarkdownEl = document.querySelector("#packetMarkdown");-const packetDialog = document.querySelector("#packetDialog");-const packetProgress = document.querySelector("#packetProgress");+const notesEl = document.querySelector("#notes");+const pinboardEl = document.querySelector("#pinboard");+const stampEl = document.querySelector("#stamp");+const penEl = document.querySelector("#pen");+const neededListEl = document.querySelector("#neededList");+const teamFeedEl = document.querySelector("#teamFeed");+const readinessEl = document.querySelector("#readiness");const callStatus = document.querySelector("#callStatus");+const modelLabel = document.querySelector("#modelLabel");+const pageDate = document.querySelector("#pageDate");const micButton = document.querySelector("#micButton");+const cameraButton = document.querySelector("#cameraButton");+const cameraStage = document.querySelector("#cameraStage");+const cameraPreview = document.querySelector("#cameraPreview");+const frameCanvas = document.querySelector("#frameCanvas");const newIntakeButton = document.querySelector("#newIntakeButton");-const resetButton = document.querySelector("#resetButton");const textForm = document.querySelector("#textForm");const textInput = document.querySelector("#textInput");-const modelLabel = document.querySelector("#modelLabel");+const packetDialog = document.querySelector("#packetDialog");+const packetMarkdownEl = document.querySelector("#packetMarkdown");const DEFAULT_API_ORIGIN = "http://127.0.0.1:4177";const API_ORIGIN = window.location.protocol === "file:" ? DEFAULT_API_ORIGIN : window.location.origin;const WS_ORIGIN = API_ORIGIN.replace(/^http/, "ws");+const FRAME_INTERVAL_MS = 1000;+const FRAME_WIDTH = 512;if (window.location.protocol === "file:") {window.location.replace(`${API_ORIGIN}/index.html`);@@ -26,47 +35,53 @@ let audioContext = null;let inputProcessor = null;let inputSource = null;let audioStream = null;+let cameraStream = null;+let frameTimer = null;let isRecording = false;let nextPlaybackTime = 0;let sessionId = null;let state = null;-let closeAfterAgentTurn = false;+let writing = false;+const seenNotes = new Set();++const routeLabels = {+ emergency_escalation: ["Escalate to human", "danger"],+ needs_docs: ["Needs docs", "warning"],+ special_investigation: ["SIU review", "info"],+ ready_for_adjuster: ["Ready for adjuster", "success"],+};++const blockerQuestions = {+ policyholder_name: "Name?",+ policy_number: "Policy number?",+ contact_method: "Best contact?",+ date_of_loss: "When did it happen?",+ loss_location: "Where?",+ loss_description: "What happened?",+};-const initialFields = [- { title: "Identity", fields: [["claimant", "Claimant name"], ["policy", "Policy number"], ["contact", "Contact method"]] },- { title: "Loss", fields: [["type", "Claim type"], ["date", "Date of loss"], ["time", "Reported date"], ["location", "Location"], ["description", "Loss description"]] },- { title: "Safety", fields: [["injuries", "Injuries"], ["hazards", "Hazards present"], ["medical", "Medical attention"]] },- { title: "Evidence", fields: [["police", "Report number"], ["photos", "Evidence available"], ["tow", "Tow info"], ["otherDriver", "Other driver info"]] },-];+const teamLabels = {+ lookup_policy: "Policy desk",+ sync_claim_packet: "Claim writer",+ pin_evidence_photo: "Evidence",+ draw_incident_sketch: "Sketch artist",+};const emptyState = {route: "needs_docs",progress: 0,- fields: Object.fromEntries(- initialFields.flatMap((group) =>- group.fields.map(([id, label]) => [- id,- { label, value: `Missing: ${label.toLowerCase()}`, status: "missing", source: "-" },- ])- )- ),- transcript: [{ speaker: "Agent", text: `Connecting to the live intake backend at ${API_ORIGIN}...` }],- events: [{ tone: "warning", title: "Connecting", detail: `Waiting for ${API_ORIGIN}/api/sessions.`, rule: "API-000" }],- handoff: {- Summary: "Backend session not started yet.",- Priority: "Pending",- "Required actions": "Start a live intake session.",- Attachments: "None",- "Next best action": "Connect to the backend API.",- },- packet_markdown: "# Initial Adjuster Handoff\n\nWaiting for backend session.",-};--const routeLabels = {- emergency_escalation: "Emergency escalation",- needs_docs: "Needs documents",- special_investigation: "Special investigation",- ready_for_adjuster: "Ready for adjuster",+ fields: {},+ transcript: [],+ events: [],+ tool_activity: [],+ missing_blockers: [],+ documents: [],+ evidence_photos: [],+ camera_notes: [],+ sketch: null,+ policy: null,+ handoff: {},+ packet_markdown: "# Adjuster handoff\n\nNo packet yet.",};function escapeHtml(value) {@@ -79,409 +94,350 @@ function escapeHtml(value) {}function now() {- return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });+ return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });+}++function isFilled(field) {+ if (!field || field.status === "missing") return false;+ return !/^(missing:|not captured|not specified|unknown|none)/i.test(String(field.value || "").trim());+}++function shortBlocker(blocker) {+ if (blockerQuestions[blocker]) return blockerQuestions[blocker];+ let text = String(blocker).replace(/\s*\([^)]*\)/g, "").trim();+ if (text.length > 42) text = `${text.slice(0, 40).trim()}...`;+ return text.endsWith("?") ? text : `${text}?`;+}++function setStatus(text, tone = "") {+ callStatus.textContent = text;+ callStatus.className = `pill ${tone}`.trim();+}++function setWriting(next) {+ writing = next;+ penEl.hidden = !next;}function setState(nextState) {- state = nextState || emptyState;- if (state.model) {- modelLabel.innerHTML = `<span class="dot ok"></span> ${escapeHtml(state.model)}`;- }+ const previous = state || emptyState;+ state = {+ ...emptyState,+ ...nextState,+ tool_activity: nextState.tool_activity ?? previous.tool_activity,+ };render();}function render() {renderTranscript();- renderFields();- renderTimeline();- renderHandoff();- renderPacket();+ renderNotes();+ renderPinboard();+ renderStamp();+ renderNeeded();+ renderTeam();+ packetMarkdownEl.textContent = state.packet_markdown || emptyState.packet_markdown;}function renderTranscript() {- transcriptEl.innerHTML = state.transcript+ transcriptEl.innerHTML = (state.transcript || []).map((turn) => {- const initials = turn.speaker === "Agent" ? "AI" : "CL";- return `- <article class="turn ${turn.speaker === "Agent" ? "agent" : "claimant"}">- <div class="speaker-icon">${initials}</div>- <div class="bubble">- <strong>${escapeHtml(turn.speaker)}</strong><time>${escapeHtml(turn.time || now())}</time>- <p>${escapeHtml(turn.text)}</p>- </div>- </article>- `;+ const cls = turn.speaker === "Agent" ? "agent" : turn.speaker === "System" ? "system" : "claimant";+ const who = turn.speaker === "Agent" ? "AI" : turn.speaker === "System" ? "!" : "You";+ return `<article class="turn ${cls} ${turn.streaming ? "streaming" : ""}"><span class="who">${who}</span><p>${escapeHtml(turn.text)}</p></article>`;}).join("");transcriptEl.scrollTop = transcriptEl.scrollHeight;}-function renderFields() {- claimFieldsEl.innerHTML = initialFields- .map((group) => {- const rows = group.fields- .map(([id, label]) => {- const field = state.fields[id] || { label, value: `Missing: ${label.toLowerCase()}`, status: "missing", source: "-" };- return `- <div class="field-row">- <div class="field-label">${escapeHtml(field.label)}</div>- <div class="field-value ${escapeHtml(field.status)}">${escapeHtml(field.value)}</div>- <div class="field-source">${escapeHtml(field.source)}</div>- </div>- `;- })- .join("");- return `- <section class="field-group">- <div class="group-title"><h3>${escapeHtml(group.title)}</h3><span class="status-line">Live</span></div>- ${rows}- </section>- `;- })- .join("");+function buildNotes() {+ const f = state.fields || {};+ const notes = [];+ const name = isFilled(f.claimant) ? f.claimant.value : "";+ const policy = isFilled(f.policy) ? f.policy.value : "";+ if (name || policy) {+ notes.push({ key: `title:${name}|${policy}`, cls: "title", text: [name, policy].filter(Boolean).join(" Β· ") });+ }+ const record = state.policy;+ if (record) {+ if (record.found) {+ const active = record.status === "active";+ const extras = (record.coverages || []).slice(0, 1).join("");+ notes.push({+ key: `policy:${record.policy_number}:${record.status}`,+ cls: active ? "check" : "flag urgent",+ text: active+ ? `${record.policy_line}, active. ${extras}`+ : `${record.policy_line}, ${record.status}. Human review before anything else.`,+ });+ } else {+ notes.push({ key: `policy:notfound:${record.policy_number}`, cls: "flag urgent", text: `Policy ${record.policy_number || ""} not found, confirm the number.` });+ }+ }+ const when = isFilled(f.date) ? f.date.value : "";+ const where = isFilled(f.location) ? f.location.value : "";+ if (when || where) {+ notes.push({ key: `whenwhere:${when}|${where}`, cls: "", text: [where, when].filter(Boolean).join(", ") });+ }+ if (isFilled(f.description)) {+ notes.push({ key: `desc:${f.description.value}`, cls: "", text: f.description.value });+ }+ if (isFilled(f.injuries)) {+ const urgent = f.injuries.status === "urgent";+ notes.push({ key: `inj:${f.injuries.value}`, cls: urgent ? "flag urgent" : "", text: urgent ? `Injury: ${f.injuries.value}` : f.injuries.value });+ }+ if (isFilled(f.contact)) {+ notes.push({ key: `contact:${f.contact.value}`, cls: "aside", text: `Reach at ${f.contact.value}` });+ }+ if (isFilled(f.photos)) {+ notes.push({ key: `ev:${f.photos.value}`, cls: "aside", text: `Has: ${f.photos.value}` });+ }+ if (isFilled(f.police)) {+ notes.push({ key: `rep:${f.police.value}`, cls: "aside", text: `Report: ${f.police.value}` });+ }+ if (claimantHasSpoken()) {+ const seenQuestions = new Set();+ for (const blocker of state.missing_blockers || []) {+ const question = shortBlocker(blocker);+ const dedupe = question.toLowerCase().replace(/[^a-z]/g, "");+ if (seenQuestions.has(dedupe) || seenQuestions.size >= 3) continue;+ seenQuestions.add(dedupe);+ notes.push({ key: `blank:${blocker}`, cls: "blank", text: question, blank: true });+ }+ }+ if (!notes.length) {+ notes.push({ key: "empty", cls: "aside", text: "Waiting for the claimant. Tap Talk, show the camera, or type below." });+ }+ return notes;}-function renderTimeline() {- const guidance = buildOperatorGuidance();- timelineEl.innerHTML = `- <section class="decision-card ${escapeHtml(guidance.routeTone)}">- <div class="decision-label">Current disposition</div>- <strong>${escapeHtml(guidance.routeLabel)}</strong>- <p>${escapeHtml(guidance.priority)}</p>- </section>-- <section class="operator-card ask-card">- <div class="operator-card-label">Ask or confirm next</div>- <p>${escapeHtml(guidance.nextAction)}</p>- </section>-- <section class="operator-card">- <div class="operator-card-label">Blocking items</div>- <div class="missing-chips">- ${guidance.missingItems.map((item) => `<span>${escapeHtml(item)}</span>`).join("")}- </div>- </section>-- <section class="operator-card">- <div class="operator-card-label">Handoff readiness</div>- <div class="readiness-meter" aria-label="Packet completion ${escapeHtml(String(state.progress || 0))}%">- <div style="width: ${Math.max(0, Math.min(100, Number(state.progress || 0)))}%"></div>- </div>- <p class="readiness-copy">${escapeHtml(guidance.readinessCopy)}</p>- </section>-- <details class="audit-details">- <summary>Audit trail</summary>- <div class="audit-list">- ${guidance.auditEvents- .map(- (event) => `- <article class="event ${escapeHtml(event.tone || "")}">- <div class="event-time">${escapeHtml(event.time || now())}</div>- <div class="event-body">- <div class="event-title">${escapeHtml(event.title)}</div>- <div class="event-detail">${escapeHtml(event.detail)}</div>- </div>- <div class="rule-id">${escapeHtml(event.rule || "")}</div>- </article>- `- )- .join("")}- </div>- </details>- `;- timelineEl.scrollTop = timelineEl.scrollHeight;-}--function buildOperatorGuidance() {- const route = state.route || "needs_docs";- const handoff = state.handoff || {};- const missingEvent = [...(state.events || [])].reverse().find((event) => event.rule === "INTAKE-001" && event.title === "Missing intake facts");- const missingItems = missingEvent?.detail- ? missingEvent.detail.split(",").map((item) => item.trim()).filter(Boolean)- : Object.values(state.fields || {})- .filter((field) => field.status === "missing")- .map((field) => field.label)- .slice(0, 6);- const requiredActions = splitList(handoff["Required actions"]);- const routeTone = route === "emergency_escalation" ? "danger" : route === "ready_for_adjuster" ? "success" : "warning";- const readinessCopy =- route === "ready_for_adjuster"- ? "Core intake is ready for assignment."- : requiredActions.length- ? `Collect or confirm: ${requiredActions.slice(0, 2).join(", ")}.`- : "Continue collecting the highlighted intake facts.";- return {- routeLabel: routeLabels[route] || route,- routeTone,- priority: handoff.Priority || "Waiting for claim facts.",- nextAction: handoff["Next best action"] || "Ask for the next missing intake fact.",- missingItems: missingItems.length ? missingItems : ["No blocking intake items"],- readinessCopy,- auditEvents: state.events || [],- };+function claimantHasSpoken() {+ return (state.transcript || []).some((turn) => turn.speaker === "Claimant" && String(turn.text || "").trim());}-function splitList(value) {- return String(value || "")- .split(",")- .map((item) => item.trim())- .filter(Boolean);+function renderNotes() {+ const notes = buildNotes();+ notesEl.innerHTML = notes+ .map((note) => {+ const fresh = !seenNotes.has(note.key);+ seenNotes.add(note.key);+ return `<div class="note ${note.cls} ${fresh ? "ink-in" : ""}">${escapeHtml(note.text)}${note.blank ? '<span class="blank-line"></span>' : ""}</div>`;+ })+ .join("");}-function renderHandoff() {- handoffEl.innerHTML = Object.entries(state.handoff)- .map(([label, value]) => `<div class="handoff-row"><dt>${escapeHtml(label)}</dt><dd>${escapeHtml(value)}</dd></div>`)- .join("");- packetProgress.textContent = `${state.progress}%`;+function renderPinboard() {+ const photos = state.evidence_photos || [];+ const sketch = state.sketch;+ const cards = photos.map(+ (photo, index) => `+ <figure class="polaroid" style="--tilt: ${index % 2 ? 2 : -2.5}deg" data-key="${escapeHtml(photo.id)}">+ <img src="${photo.data_url}" alt="Camera frame pinned as evidence" />+ <figcaption>${escapeHtml(photo.caption)}</figcaption>+ ${photo.claimant_description ? `<span class="tag ${photo.confirmed ? "" : "unconfirmed"}">Claimant says: ${escapeHtml(photo.claimant_description)}${photo.confirmed ? ", confirmed" : ", not confirmed on camera"}</span>` : ""}+ <span class="tag">Seen on camera ${escapeHtml(photo.captured_at || "")} Β· ${escapeHtml(photo.evidence_type || "evidence")}</span>+ </figure>`+ );+ if (sketch) {+ cards.push(`+ <figure class="polaroid sketch" style="--tilt: 1.5deg" data-key="sketch-${sketch.version}">+ <img src="${sketch.data_url}" alt="Hand drawn sketch of the incident scene" />+ <figcaption>Does this look right?</figcaption>+ <span class="tag">Sketch ${sketch.version}, drawn from what you described</span>+ </figure>`);+ }+ const currentKeys = [...pinboardEl.querySelectorAll("[data-key]")].map((el) => el.dataset.key).join("|");+ const nextKeys = [...photos.map((p) => p.id), sketch ? `sketch-${sketch.version}` : ""].filter(Boolean).join("|");+ if (currentKeys !== nextKeys) pinboardEl.innerHTML = cards.join("");+}++function renderStamp() {+ const route = state.route;+ const [label, tone] = routeLabels[route] || [route, "warning"];+ stampEl.hidden = !claimantHasSpoken() || writing;+ stampEl.textContent = label;+ if (stampEl.dataset.route !== route) {+ stampEl.dataset.route = route;+ stampEl.className = `stamp ${tone}`;+ stampEl.style.animation = "none";+ void stampEl.offsetWidth;+ stampEl.style.animation = "";+ }}-function renderPacket() {- packetMarkdownEl.textContent = state.packet_markdown || "# Initial Adjuster Handoff\n\nNo packet generated yet.";+function renderNeeded() {+ const items = [];+ for (const blocker of state.missing_blockers || []) {+ items.push({ text: shortBlocker(blocker).replace(/\?$/, ""), cls: "blocker" });+ }+ for (const doc of state.documents || []) {+ items.push({ text: doc.item, cls: doc.already_provided ? "done" : "" });+ }+ neededListEl.innerHTML = items.length+ ? items.map((item) => `<li class="${item.cls}"><span class="tick-box"></span><span>${escapeHtml(item.text)}</span></li>`).join("")+ : `<li class="empty">Nothing yet. The list fills in as the claim team reads the call.</li>`;+ const progress = Number(state.progress || 0);+ readinessEl.textContent = `${progress}% ready`;+ readinessEl.className = `pill ${progress >= 80 ? "" : progress >= 40 ? "warning" : "neutral"}`;+}++function renderTeam() {+ const activity = [...(state.tool_activity || [])].slice(-6).reverse();+ teamFeedEl.innerHTML = activity.length+ ? activity+ .map((item) => {+ const phase = item.phase || "running";+ const meta = phase === "running" ? "working" : item.scheduling === "INTERRUPT" ? "interrupted the agent" : item.duration_ms != null ? `${item.duration_ms} ms` : "";+ return `<li><span class="team-dot ${phase}"></span><span><span class="team-name">${escapeHtml(teamLabels[item.name] || item.name)}</span> Β· ${escapeHtml(item.headline || "")}</span><span class="team-meta ${item.scheduling === "INTERRUPT" ? "interrupt" : ""}">${escapeHtml(meta)}</span></li>`;+ })+ .join("")+ : `<li class="empty">Policy desk, claim writer, evidence, and sketch artist will show up here as the agent calls them.</li>`;+ setWriting(activity.some((item) => item.phase === "running" && item.name !== "lookup_policy") || writing);}-function appendLocalError(message) {- setState({- ...state,- transcript: [...state.transcript, { speaker: "Agent", text: message, time: now() }],- events: [...state.events, { tone: "danger", title: "Backend API error", detail: message, rule: "API-ERR", time: now() }],- });+function appendSystem(text) {+ setState({ ...state, transcript: [...(state.transcript || []), { speaker: "System", text }] });}-function sameTranscriptTurn(left, right) {- const leftText = String(left?.text || "").trim();- const rightText = String(right?.text || "").trim();- if (!leftText || !rightText || left?.speaker !== right?.speaker) return false;- return leftText === rightText || leftText.includes(rightText) || rightText.includes(leftText);+function sameTurn(left, right) {+ const a = String(left?.text || "").trim();+ const b = String(right?.text || "").trim();+ if (!a || !b || left?.speaker !== right?.speaker) return false;+ return a === b || a.includes(b) || b.includes(a);}-function mergeLiveTranscript(authoritative, local) {+function mergeTranscript(authoritative, local) {const merged = [...(authoritative || [])];for (const turn of local || []) {- if (!turn.streaming || !String(turn.text || "").trim()) continue;- if (merged.some((item) => sameTranscriptTurn(item, turn))) continue;+ if ((!turn.streaming && turn.speaker !== "System") || !String(turn.text || "").trim()) continue;+ if (merged.some((item) => sameTurn(item, turn))) continue;merged.push(turn);}return merged;}function applyServerState(nextState) {+ setWriting(false);setState({...nextState,- transcript: mergeLiveTranscript(nextState.transcript, state?.transcript),+ transcript: mergeTranscript(nextState.transcript, state?.transcript),+ tool_activity: mergeToolActivity(nextState.tool_activity, state?.tool_activity),});}+function mergeToolActivity(authoritative, local) {+ const finished = new Set(["done", "error", "cancelled"]);+ const byId = new Map();+ for (const item of authoritative || []) byId.set(item.id, item);+ for (const item of local || []) {+ const current = byId.get(item.id);+ if (!current || (finished.has(item.phase) && !finished.has(current.phase))) byId.set(item.id, item);+ }+ return [...byId.values()];+}++function applyToolEvent(message) {+ const { type, ...entry } = message;+ const others = (state.tool_activity || []).filter((item) => item.id !== entry.id);+ setState({ ...state, tool_activity: [...others, entry] });+}+function upsertStreamingTurn(speaker, text, final = false) {if (!String(text || "").trim()) return;- const transcript = [...state.transcript];+ const transcript = [...(state.transcript || [])];const last = transcript[transcript.length - 1];if (last && last.speaker === speaker && last.streaming) {- transcript[transcript.length - 1] = { speaker, text, time: last.time, streaming: !final };- } else if (final && last && !last.streaming && sameTranscriptTurn(last, { speaker, text })) {+ transcript[transcript.length - 1] = { speaker, text, streaming: !final };+ } else if (final && last && !last.streaming && sameTurn(last, { speaker, text })) {return;} else {- transcript.push({ speaker, text, time: now(), streaming: !final });+ transcript.push({ speaker, text, streaming: !final });}setState({ ...state, transcript });}-function claimantAskedToClose(text) {- return /\b(that'?s all|nothing else|no,?\s*that'?s it|that is it|i'?m done|goodbye|bye)\b/i.test(text);-}--function agentClosedConversation(text) {- return /\b(have a good|adjuster will|will be in touch|claim packet|initial intake|next steps)\b/i.test(text);-}--function applyRealtimeHints(text) {- const lower = text.toLowerCase();- const nextFields = { ...state.fields };- const nextEvents = [...state.events];- let nextRoute = state.route;- let changed = false;-- const update = (id, value, status = "pending", source = "live audio") => {- const current = nextFields[id];- if (!current || current.value === value) return;- nextFields[id] = { ...current, value, status, source };- changed = true;- };-- const event = (rule, title, detail, tone = "warning") => {- const key = `${rule}:${title}`;- if (nextEvents.some((item) => `${item.rule}:${item.title}` === key)) return;- nextEvents.push({ rule, title, detail, tone, time: now() });- changed = true;- };-- const phone = text.match(/\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}\b/);- if (phone) {- update("contact", phone[0], "pending", "live transcript");- event("LIVE-INFO", "Contact detected", "Phone number heard in live audio.", "success");- }-- const policy = text.match(/\b(?:policy|auto|home|claim)\s*(?:number|#|is|:)?\s*([A-Z0-9][A-Z0-9-]{3,})\b/i);- if (policy && /\d/.test(policy[1])) {- update("policy", policy[1].toUpperCase(), "pending", "live transcript");- event("LIVE-INFO", "Policy candidate detected", "Policy-like identifier heard in live audio.", "success");- }-- const name = text.match(/\b(?:my name is|this is)\s+([a-z]+(?:\s+[a-z]+){0,1})(?=\s+(?:and|with|from|calling|phone|policy|$))/i)- || text.match(/\b(?:i am|i'm)\s+([a-z]+(?:\s+[a-z]+){0,1})(?=\s+(?:and|with|from|calling|phone|policy|$))/i);- if (name) {- update("claimant", toTitleCase(name[1]), "pending", "live transcript");- event("LIVE-INFO", "Claimant name detected", "Name candidate heard in live audio.", "success");- }-- if (/\b(hit|rear ended|rear-ended|crash|accident|collision|side[- ]?swiped)\b/.test(lower)) {- update("type", "auto collision", "pending", "live transcript");- update("description", compactText(text), "pending", "live transcript");- event("LIVE-CLASSIFY", "Auto collision signal", "Crash language detected before final extraction.", "warning");- } else if (/\b(flood|water|leak|pipe|basement|sump)\b/.test(lower)) {- update("type", "home water damage", "pending", "live transcript");- update("description", compactText(text), "pending", "live transcript");- event("LIVE-CLASSIFY", "Home water signal", "Water damage language detected before final extraction.", "warning");- } else if (/\b(stolen|theft|robbed|missing laptop|taken)\b/.test(lower)) {- update("type", "theft property loss", "pending", "live transcript");- update("description", compactText(text), "pending", "live transcript");- event("LIVE-CLASSIFY", "Theft signal", "Theft language detected before final extraction.", "warning");- }-- const safetyText = stripNegatedSafety(lower);- if (/\b(neck pain|injur|hurt|ambulance|hospital|urgent care|bleeding|pain)\b/.test(safetyText)) {- update("injuries", compactText(text), "urgent", "live transcript");- event("SAFE-002", "Injury signal detected", "Live audio mentions injury or medical concern.", "danger");- nextRoute = "emergency_escalation";- changed = true;- } else if (safetyText !== lower) {- update("injuries", "No injuries reported", "pending", "live transcript");- event("SAFE-OK", "No injury reported", "Live audio negated injury or medical concern.", "success");- }-- if (/\b(police|officer|report|case number|incident number)\b/.test(lower)) {- update("police", compactText(text), "pending", "live transcript");- event("DOC-001", "Police/report signal detected", "Police or report language heard in live audio.", "warning");- }-- if (/\b(photo|photos|picture|video|receipt|estimate|tow|towed|storage)\b/.test(lower)) {- update("photos", compactText(text), "pending", "live transcript");- if (/\b(tow|towed|storage)\b/.test(lower)) {- update("tow", compactText(text), "pending", "live transcript");- }- event("DOC-001", "Evidence signal detected", "Document or evidence language heard in live audio.", "warning");- }-- const location = text.match(/\b(?:on|at|near)\s+([A-Z0-9][A-Za-z0-9 .'-]*(?:street|st|road|rd|avenue|ave|highway|hwy|i-\d+|mile marker \d+|intersection|exit \d+))/i);- if (location) {- update("location", location[1].trim(), "pending", "live transcript");- event("LIVE-INFO", "Location candidate detected", "Location heard in live audio.", "success");- }-- if (/\b(today|yesterday|last night|this morning|minutes ago|\d{1,2}:\d{2})\b/.test(lower)) {- update("date", compactText(text), "pending", "live transcript");- event("LIVE-INFO", "Loss timing detected", "Date or time language heard in live audio.", "success");- }-- if (changed) {- const completed = Object.values(nextFields).filter((field) => field.status === "complete" || field.status === "urgent" || field.status === "pending").length;- setState({- ...state,- route: nextRoute,- fields: nextFields,- events: nextEvents.slice(-14),- progress: Math.max(state.progress, Math.round((completed / Object.keys(nextFields).length) * 100)),- });- }-}--function stripNegatedSafety(text) {- return text- .replace(/\b(?:no|not|none|without|denies|denied)\s+(?:one\s+)?(?:was\s+)?(?:injur\w*|hurt|pain|medical attention|ambulance|hospital|unsafe|hazard\w*|danger)\b/gi, " ")- .replace(/\b(?:injur\w*|hurt|pain|medical attention|ambulance|hospital|unsafe|hazard\w*|danger)\s+(?:was|were|is|are)?\s*(?:reported\s+)?(?:no|none|not reported|denied)\b/gi, " ");-}--function compactText(text) {- const trimmed = text.trim().replace(/\s+/g, " ");- return trimmed.length > 96 ? `${trimmed.slice(0, 93)}...` : trimmed;-}--function toTitleCase(value) {- return value- .trim()- .split(/\s+/)- .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())- .join(" ");-}-async function api(path, options = {}) {- const response = await fetch(`${API_ORIGIN}${path}`, {- headers: { "Content-Type": "application/json" },- ...options,- });+ const response = await fetch(`${API_ORIGIN}${path}`, { headers: { "Content-Type": "application/json" }, ...options });const payload = await response.json().catch(() => ({}));- if (!response.ok) {- throw new Error(payload.detail || `Request failed with status ${response.status}`);- }+ if (!response.ok) throw new Error(payload.detail || `Request failed with status ${response.status}`);return payload;}async function createSession() {stopLiveVoice(false);- callStatus.textContent = "Connecting to backend";- textInput.disabled = true;+ stopCamera();+ seenNotes.clear();+ setWriting(false);+ setStatus("Connecting", "neutral");setState(emptyState);+ pageDate.textContent = `Claim intake notes Β· ${new Date().toLocaleDateString([], { month: "short", day: "numeric" })}`;try {const payload = await api("/api/sessions", { method: "POST" });sessionId = payload.session_id;setState(payload.state);- modelLabel.innerHTML = `<span class="dot ok"></span> ${escapeHtml(payload.model)}`;- callStatus.textContent = payload.has_api_key ? "Active - API connected" : "API key required";- textInput.disabled = false;+ const health = await api("/api/health");+ modelLabel.textContent = `${health.live_model} Β· sketches by ${health.sketch_model}`;+ setStatus(payload.has_api_key ? "Ready" : "API key required", payload.has_api_key ? "" : "danger");textInput.focus();} catch (error) {- callStatus.textContent = "Backend unavailable";- appendLocalError(error.message);+ setStatus("Backend unavailable", "danger");+ appendSystem(error.message);}}+async function connectLive() {+ if (liveSocket && liveSocket.readyState === WebSocket.OPEN) return;+ liveSocket = new WebSocket(`${WS_ORIGIN}/ws/live`);+ liveSocket.onmessage = (event) => {+ const message = JSON.parse(event.data);+ if (message.type === "session") {+ sessionId = message.session_id;+ modelLabel.textContent = `${message.model} Β· sketches by ${message.sketch_model}`;+ setStatus("Live", "");+ } else if (message.type === "transcript") {+ upsertStreamingTurn(message.speaker, message.text, message.final);+ if (message.speaker === "Claimant" && message.final) setWriting(true);+ } else if (message.type === "tool") {+ applyToolEvent(message);+ } else if (message.type === "audio") {+ playPcm24(message.data);+ } else if (message.type === "state") {+ applyServerState(message.state);+ } else if (message.type === "interrupted") {+ nextPlaybackTime = audioContext?.currentTime || 0;+ } else if (message.type === "error") {+ appendSystem(message.message);+ }+ };+ liveSocket.onclose = () => {+ if (isRecording || cameraStream) setStatus("Live session ended", "warning");+ };+ await new Promise((resolve, reject) => {+ const timeout = setTimeout(() => reject(new Error("Live connection timed out.")), 8000);+ liveSocket.addEventListener("open", () => { clearTimeout(timeout); resolve(); }, { once: true });+ liveSocket.addEventListener("error", () => { clearTimeout(timeout); reject(new Error("Live connection failed.")); }, { once: true });+ });+}+async function sendClaimantTurn(text) {- if (liveSocket && liveSocket.readyState === WebSocket.OPEN) {- liveSocket.send(JSON.stringify({ type: "text", text }));- upsertStreamingTurn("Claimant", text, true);- return;- }- if (!sessionId) {- appendLocalError("No backend session is active. Start a new intake first.");- return;- }- upsertStreamingTurn("Claimant", text, true);- callStatus.textContent = "Processing with Gemini";- textInput.disabled = true;try {- const payload = await api("/api/message", {- method: "POST",- body: JSON.stringify({ session_id: sessionId, text }),- });- setState(payload.state);- modelLabel.innerHTML = `<span class="dot ok"></span> ${escapeHtml(payload.model)}`;- callStatus.textContent = "Active - API connected";+ await connectLive();} catch (error) {- callStatus.textContent = "API error";- appendLocalError(error.message);- } finally {- textInput.disabled = false;- textInput.focus();+ appendSystem(error.message);+ return;}+ liveSocket.send(JSON.stringify({ type: "text", text }));+ upsertStreamingTurn("Claimant", text, true);+ setWriting(true);}async function startLiveVoice() {if (!navigator.mediaDevices?.getUserMedia || !window.AudioContext) {- appendLocalError("This browser cannot capture microphone audio. Type the claimant turn instead.");+ appendSystem("This browser cannot capture microphone audio. Type instead.");return;}try {- await connectLiveVoice();+ await connectLive();audioStream = await navigator.mediaDevices.getUserMedia({ audio: true });audioContext = audioContext || new AudioContext();await audioContext.resume();@@ -490,114 +446,95 @@ async function startLiveVoice() {inputProcessor.onaudioprocess = (event) => {event.outputBuffer.getChannelData(0).fill(0);if (!liveSocket || liveSocket.readyState !== WebSocket.OPEN) return;- const input = event.inputBuffer.getChannelData(0);- const pcm16 = resampleToPcm16(input, audioContext.sampleRate, 16000);+ const pcm16 = resampleToPcm16(event.inputBuffer.getChannelData(0), audioContext.sampleRate, 16000);liveSocket.send(JSON.stringify({ type: "audio", data: arrayBufferToBase64(pcm16.buffer) }));};inputSource.connect(inputProcessor);inputProcessor.connect(audioContext.destination);isRecording = true;- micButton.classList.add("recording");- micButton.setAttribute("aria-label", "Stop live voice");- callStatus.textContent = "Live voice streaming";+ micButton.classList.add("active");+ micButton.querySelector(".round-label").textContent = "Listening";+ setStatus("Live, listening", "");} catch (error) {const denied = error.name === "NotAllowedError" || /denied|permission/i.test(error.message);- appendLocalError(- denied- ? "Microphone access was denied by the browser or macOS. Allow microphone access for http://127.0.0.1:4177, or use the text box for this turn."- : `Live voice failed: ${error.message}`- );+ appendSystem(denied ? "Microphone access was denied. Allow it for this site or type instead." : `Voice failed: ${error.message}`);stopLiveVoice(false);}}-function stopLiveVoice(sendClose = true) {+function stopLiveVoice(closeSocket = true) {isRecording = false;- closeAfterAgentTurn = false;- micButton.classList.remove("recording");- micButton.setAttribute("aria-label", "Start live voice");+ micButton.classList.remove("active");+ micButton.querySelector(".round-label").textContent = "Talk";inputProcessor?.disconnect();inputSource?.disconnect();audioStream?.getTracks().forEach((track) => track.stop());inputProcessor = null;inputSource = null;audioStream = null;- if (sendClose) {+ if (closeSocket) {+ stopCamera();liveSocket?.send(JSON.stringify({ type: "close" }));+ liveSocket?.close();+ liveSocket = null;+ setStatus("Call ended", "neutral");}- liveSocket?.close();- liveSocket = null;- if (sendClose) callStatus.textContent = "Live voice stopped";}-async function connectLiveVoice() {- if (liveSocket && liveSocket.readyState === WebSocket.OPEN) return;- liveSocket = new WebSocket(`${WS_ORIGIN}/ws/live`);- liveSocket.onopen = () => {- callStatus.textContent = "Gemini Live connected";- modelLabel.innerHTML = '<span class="dot ok"></span> Gemini Live connecting';- };- liveSocket.onmessage = (event) => {- const message = JSON.parse(event.data);- if (message.type === "session") {- sessionId = message.session_id;- modelLabel.innerHTML = `<span class="dot ok"></span> ${escapeHtml(message.model)}`;- } else if (message.type === "transcript") {- upsertStreamingTurn(message.speaker, message.text, message.final);- if (message.speaker === "Claimant") {- applyRealtimeHints(message.text);- if (message.final && claimantAskedToClose(message.text)) {- closeAfterAgentTurn = true;- }- }- if (message.speaker === "Agent" && message.final && closeAfterAgentTurn && agentClosedConversation(message.text)) {- window.setTimeout(() => stopLiveVoice(), 800);- }- } else if (message.type === "audio") {- playPcm24(message.data);- } else if (message.type === "state") {- applyServerState(message.state);- } else if (message.type === "interrupted") {- nextPlaybackTime = audioContext?.currentTime || 0;- } else if (message.type === "error") {- appendLocalError(message.message);- }- };- liveSocket.onclose = () => {- if (isRecording) callStatus.textContent = "Live voice disconnected";- };- liveSocket.onerror = () => appendLocalError("Live voice WebSocket failed. Check the backend server.");- await new Promise((resolve, reject) => {- const timeout = setTimeout(() => reject(new Error("Live voice connection timed out.")), 8000);- liveSocket.addEventListener("open", () => {- clearTimeout(timeout);- resolve();- }, { once: true });- liveSocket.addEventListener("error", () => {- clearTimeout(timeout);- reject(new Error("Live voice connection failed."));- }, { once: true });- });+async function startCamera() {+ if (!navigator.mediaDevices?.getUserMedia) {+ appendSystem("This browser cannot access a camera.");+ return;+ }+ try {+ await connectLive();+ cameraStream = await navigator.mediaDevices.getUserMedia({ video: { width: { ideal: 640 }, height: { ideal: 480 }, facingMode: "environment" } });+ cameraPreview.srcObject = cameraStream;+ cameraStage.hidden = false;+ cameraButton.classList.add("active");+ cameraButton.querySelector(".round-label").textContent = "Stop camera";+ frameTimer = window.setInterval(sendFrame, FRAME_INTERVAL_MS);+ if (!isRecording) setStatus("Camera on, agent can see", "");+ } catch (error) {+ const denied = error.name === "NotAllowedError" || /denied|permission/i.test(error.message);+ appendSystem(denied ? "Camera access was denied. Allow it for this site to show the damage." : `Camera failed: ${error.message}`);+ stopCamera();+ }+}++function stopCamera() {+ if (frameTimer) window.clearInterval(frameTimer);+ frameTimer = null;+ cameraStream?.getTracks().forEach((track) => track.stop());+ cameraStream = null;+ cameraPreview.srcObject = null;+ cameraStage.hidden = true;+ cameraButton.classList.remove("active");+ cameraButton.querySelector(".round-label").textContent = "Show camera";+}++function sendFrame() {+ if (!cameraStream || !liveSocket || liveSocket.readyState !== WebSocket.OPEN) return;+ if (!cameraPreview.videoWidth) return;+ const scale = FRAME_WIDTH / cameraPreview.videoWidth;+ frameCanvas.width = FRAME_WIDTH;+ frameCanvas.height = Math.round(cameraPreview.videoHeight * scale);+ const ctx = frameCanvas.getContext("2d");+ ctx.drawImage(cameraPreview, 0, 0, frameCanvas.width, frameCanvas.height);+ const dataUrl = frameCanvas.toDataURL("image/jpeg", 0.6);+ liveSocket.send(JSON.stringify({ type: "video", data: dataUrl.split(",")[1] }));}function resampleToPcm16(input, inputRate, outputRate) {const ratio = inputRate / outputRate;const outputLength = Math.floor(input.length / ratio);- const output = new Float32Array(outputLength);+ const pcm = new Int16Array(outputLength);for (let i = 0; i < outputLength; i += 1) {const index = i * ratio;const before = Math.floor(index);const after = Math.min(before + 1, input.length - 1);const weight = index - before;- output[i] = input[before] * (1 - weight) + input[after] * weight;- }- return floatToPcm16(output);-}--function floatToPcm16(float32) {- const pcm = new Int16Array(float32.length);- for (let i = 0; i < float32.length; i += 1) {- const sample = Math.max(-1, Math.min(1, float32[i]));+ const sample = Math.max(-1, Math.min(1, input[before] * (1 - weight) + input[after] * weight));pcm[i] = sample < 0 ? sample * 0x8000 : sample * 0x7fff;}return pcm;@@ -610,16 +547,12 @@ function arrayBufferToBase64(buffer) {return btoa(binary);}-function base64ToInt16Array(base64) {+function playPcm24(base64) {+ audioContext = audioContext || new AudioContext();const binary = atob(base64);const bytes = new Uint8Array(binary.length);for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);- return new Int16Array(bytes.buffer);-}--function playPcm24(base64) {- audioContext = audioContext || new AudioContext();- const pcm = base64ToInt16Array(base64);+ const pcm = new Int16Array(bytes.buffer);const audioBuffer = audioContext.createBuffer(1, pcm.length, 24000);const channel = audioBuffer.getChannelData(0);for (let i = 0; i < pcm.length; i += 1) channel[i] = pcm[i] / 32768;@@ -631,14 +564,9 @@ function playPcm24(base64) {nextPlaybackTime = startAt + audioBuffer.duration;}-micButton.addEventListener("click", () => {- if (isRecording) stopLiveVoice();- else startLiveVoice();-});-+micButton.addEventListener("click", () => (isRecording ? stopLiveVoice() : startLiveVoice()));+cameraButton.addEventListener("click", () => (cameraStream ? stopCamera() : startCamera()));newIntakeButton.addEventListener("click", createSession);-resetButton.addEventListener("click", createSession);-textForm.addEventListener("submit", (event) => {event.preventDefault();const value = textInput.value.trim();@@ -646,7 +574,6 @@ textForm.addEventListener("submit", (event) => {textInput.value = "";sendClaimantTurn(value);});-document.querySelector("#openPacket").addEventListener("click", () => packetDialog.showModal());document.querySelector("#closePacket").addEventListener("click", () => packetDialog.close());diff --git a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/index.html b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/index.htmlindex 0ebb5c0c..7de715a9 100644--- a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/index.html+++ b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/index.html@@ -7,52 +7,52 @@<link rel="preconnect" href="https://fonts.googleapis.com" /><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /><link- href="https://fonts.googleapis.com/css2?family=EB+Garamond:wght@400&family=Inter:wght@400;500;600;700&display=swap"+ href="https://fonts.googleapis.com/css2?family=Caveat:wght@400;500;600&family=Patrick+Hand&family=Inter:wght@400;500;600&display=swap"rel="stylesheet"/>- <link rel="stylesheet" href="./styles.css?v=dark-editorial-1" />+ <link rel="stylesheet" href="./styles.css?v=notebook-1" /></head><body>- <div class="app-shell">- <main class="workspace">- <header class="topbar">- <div class="title-group">+ <div class="desk">+ <header class="desk-bar">+ <div class="brand">+ <span class="brand-mark" aria-hidden="true"></span>+ <div><h1>Insurance Claim Live Agent Team</h1>- <span id="modelLabel" class="live-model"><span class="dot ok"></span> Connecting to Gemini API</span>+ <p id="modelLabel" class="brand-sub">Connecting to Gemini</p></div>- </header>+ </div>+ <button id="openPacket" class="ghost-button" type="button">Adjuster packet</button>+ </header>- <section class="dashboard" aria-label="Live intake cockpit">- <section class="panel call-panel">- <div class="panel-header">- <div>- <p class="panel-kicker">Live call</p>- <h2>Voice and transcript</h2>- </div>- <span id="callStatus" class="status-pill active">Active - listening</span>+ <main class="desk-layout">+ <aside class="side">+ <section class="card call-card">+ <div class="card-head">+ <span class="card-kicker">Live call</span>+ <span id="callStatus" class="pill">Connecting</span></div>- <div class="voice-stage">- <div class="wave left" aria-hidden="true">- <span></span><span></span><span></span><span></span><span></span><span></span>- </div>- <button id="micButton" class="mic-button" type="button" aria-label="Start voice recording">- <span class="mic-icon" aria-hidden="true"></span>+ <div class="controls">+ <button id="micButton" class="round-button" type="button" aria-label="Start live voice">+ <span class="icon-mic" aria-hidden="true"></span>+ <span class="round-label">Talk</span>+ </button>+ <button id="cameraButton" class="round-button" type="button" aria-label="Show the damage on camera">+ <span class="icon-camera" aria-hidden="true"></span>+ <span class="round-label">Show camera</span>+ </button>+ <button id="newIntakeButton" class="round-button subtle" type="button" aria-label="Start a new intake">+ <span class="icon-new" aria-hidden="true"></span>+ <span class="round-label">New intake</span></button>- <div class="wave right" aria-hidden="true">- <span></span><span></span><span></span><span></span><span></span><span></span>- </div></div>- <div class="call-actions">- <button id="newIntakeButton" class="primary-action" type="button">New live intake</button>- <button id="resetButton" class="secondary-action" type="button">Reset</button>+ <div id="cameraStage" class="camera-stage" hidden>+ <video id="cameraPreview" autoplay muted playsinline></video>+ <span class="camera-tag"><span class="rec-dot" aria-hidden="true"></span> Agent is watching</span></div>- <div class="transcript-header">- <h3>Live transcript</h3>- <span id="streamingLabel">Streaming</span>- </div><div id="transcript" class="transcript" aria-live="polite"></div><form id="textForm" class="text-entry">@@ -60,60 +60,55 @@id="textInput"type="text"autocomplete="off"- placeholder="Type a claimant response..."+ placeholder="Or type what the claimant says..."aria-label="Type a claimant response"/>- <button type="submit" aria-label="Send response">Send</button>+ <button type="submit">Send</button></form></section>- <section class="panel claim-panel">- <div class="panel-header">- <div>- <p class="panel-kicker">Claim packet live</p>- <h2>Claim state</h2>- </div>- <span id="autosave" class="status-line"><span class="dot ok"></span> Auto-saving</span>+ <section class="card needed-card">+ <div class="card-head">+ <span class="card-kicker">Still needed</span>+ <span id="readiness" class="pill neutral">0% ready</span></div>- <div id="claimFields" class="claim-sections"></div>+ <ul id="neededList" class="needed-list"></ul></section>- <section class="right-rail">- <section class="panel timeline-panel">- <div class="panel-header compact">- <div>- <p class="panel-kicker">Operator guidance</p>- <h2>Next best action</h2>- </div>- <span class="status-line"><span class="dot neutral"></span> Live</span>- </div>- <div id="timeline" class="operator-workbench" aria-live="polite"></div>- </section>-- <section class="panel handoff-panel">- <div class="panel-header compact">- <div>- <p class="panel-kicker">Human handoff</p>- <h2>Adjuster packet forming</h2>- </div>- <div id="packetProgress" class="progress-ring" aria-label="Packet completion">32%</div>- </div>- <dl id="handoff" class="handoff-list"></dl>- <button id="openPacket" class="packet-button" type="button">Open packet preview</button>- </section>+ <section class="card team-card">+ <div class="card-head">+ <span class="card-kicker">Claim team</span>+ <span class="card-hint">Working in the background while the call continues</span>+ </div>+ <ul id="teamFeed" class="team-feed"></ul></section>+ </aside>++ <section class="notebook-wrap" aria-label="Field notebook">+ <div class="notebook">+ <div class="holes" aria-hidden="true"><span></span><span></span><span></span></div>+ <div class="page-head">+ <span id="pageDate">Claim intake notes</span>+ <span id="pageAgent">Gemini 3.8 Live, field notes</span>+ </div>+ <div id="notes" class="notes"></div>+ <div id="pinboard" class="pinboard"></div>+ <div id="stamp" class="stamp" hidden></div>+ <div id="pen" class="pen" hidden><span class="pen-nib" aria-hidden="true"></span> writing</div>+ </div></section></main></div><dialog id="packetDialog" class="packet-dialog"><div class="dialog-header">- <h2>Initial Adjuster Handoff</h2>+ <h2>Adjuster handoff packet</h2><button id="closePacket" type="button" aria-label="Close packet">Close</button></div><pre id="packetMarkdown"></pre></dialog>- <script src="./app.js?v=gemini-live-clean-shell-1"></script>+ <canvas id="frameCanvas" hidden></canvas>+ <script src="./app.js?v=notebook-1"></script></body></html>diff --git a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/live_tools.py b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/live_tools.pynew file mode 100644index 00000000..6e3cf656--- /dev/null+++ b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/live_tools.py@@ -0,0 +1,298 @@+"""Gemini 3.8 Live configuration and background tool contracts for the voice agent.++Gemini 3.8 Live runs function calls in the background (behavior NON_BLOCKING)+so the voice agent keeps talking while the claim team works. The tools here are+the bridge between the live call, the ADK claim graph, the mock policy+directory, the claimant's camera, and the sketch model. Execution lives in+server.py, which owns the session state.+"""++from __future__ import annotations++import os+from typing import Any++from google.genai import types++LIVE_MODEL_ID = os.getenv("FNOL_GEMINI_LIVE_MODEL", "gemini-3.8-live")+SKETCH_MODEL_ID = os.getenv("FNOL_SKETCH_MODEL", "gemini-3.1-flash-image")+VOICE_NAME = os.getenv("FNOL_VOICE", "Kore")++TOOL_NAMES = ["lookup_policy", "sync_claim_packet", "pin_evidence_photo", "draw_incident_sketch"]++SYSTEM_INSTRUCTION = """+You are the live voice intake agent for an insurance first notice of loss (FNOL) team.+Speak naturally, warmly, and briefly. The claimant may be stressed. Acknowledge what+they say, then keep the intake moving one or two questions at a time. Your notes are+written into a field notebook the claimant can see, so narrate what you are doing in+short asides like "I'm noting that" or "let me check that policy".++You work with a claim team that runs in the background while you talk:+- lookup_policy: verifies a policy number against the carrier's policy records.+ Call it as soon as you hear a policy number. Keep talking while it runs. When it+ returns, confirm the policyholder name and policy line out loud in one sentence.+ If the policy is lapsed or not found, say a human reviewer will check it and do+ not stop collecting loss facts.+- sync_claim_packet: sends everything the claimant has said, plus your camera+ observations, to the claim team, which extracts facts, applies deterministic+ intake rules, and returns the routing decision and the list of open items the+ packet still needs. Call it after the claimant shares new loss facts, roughly+ every turn or two. The open items are a checklist, not a script. Never interrupt+ the current topic to ask one. Finish what the claimant is describing or showing,+ acknowledge it, and only then pick the open item that follows naturally from+ where the conversation is. Dates, addresses, and policy numbers wait until the+ current topic is closed.+- pin_evidence_photo: the claimant can turn on their camera and show you the damage.+ Whenever you can see anything relevant to the claim on camera (damage, water+ lines, dents, broken items, the scene or layout, a floor plan, receipts, documents,+ serial numbers), say what you see in one or two concrete sentences and call+ pin_evidence_photo in that same turn. The current camera frame gets taped into the+ notebook. Do this the first time you see each new thing; do not wait to be asked+ and do not postpone it to a later turn. Skip frames that show nothing relevant,+ like a blank wall or a face.+ Your eyes are the adjuster's eyes, so report only what you can actually see. If+ the claimant names something (a crack, a leak, mold, a dent) and the frame does+ not clearly show it, do not repeat their word as if you saw it. Say what you do+ see ("I can see a dark mark about the size of a coin, but I can't make out a crack+ from here"), ask them politely to get closer, tilt the camera, or add light, and+ pin the frame with confirmed set to false. Pin it again with confirmed true once+ you can see it. Being honest about what is visible is more helpful to the claimant+ than agreeing, because the adjuster will look at the same photo.+- draw_incident_sketch: once you understand the scene, call this with a short+ description of the layout and what happened, written for an illustrator. The team+ draws a rough pen sketch into the notebook. When it returns, ask the claimant+ whether the sketch looks right. If they correct it, call it again with the fix.+ Call it in the same turn you first learn where it happened and what happened,+ alongside sync_claim_packet; do not wait for every detail or for the claimant to+ ask. A rough first sketch that gets corrected is better than a late one.++Safety first: if the claimant mentions injury, unsafe housing, or immediate danger,+tell them to contact emergency services if anyone is in danger, say that a human+representative will take over, and call sync_claim_packet so the team escalates.++Stay with the claimant. Talk about what they are talking about; when the camera is+on, the conversation is about what is on camera until you both move on. While a+camera view is still unconfirmed, your next question is about getting a better view+(closer, more light, a different angle), not about the packet. Double check the+details that matter (what is visible, dates, amounts, who was involved) and if+something does not add up, ask about it politely instead of writing it down. Never+announce that you are checking a list or the packet; just ask the next question.++Never promise coverage, payment, liability, benefits, or approval. Policy details+from lookup_policy describe what is on the policy, not what will be paid.+When the core facts and blocking items are collected, summarize the claim back in+two sentences and tell the claimant an adjuster will be in touch.+""".strip()+++def _string_param(description: str) -> types.Schema:+ return types.Schema(type=types.Type.STRING, description=description)+++def tool_declarations() -> list[types.Tool]:+ """Return the background tools the voice agent can call."""++ lookup = types.FunctionDeclaration(+ name="lookup_policy",+ description=(+ "Verify an insurance policy number against the carrier policy directory. "+ "Runs in the background. Returns policyholder name, policy line, status, "+ "deductibles, and coverages when found."+ ),+ behavior=types.Behavior.NON_BLOCKING,+ parameters=types.Schema(+ type=types.Type.OBJECT,+ properties={+ "policy_number": _string_param(+ "Policy number exactly as the claimant said it, for example H0-44721 or AUTO 90210."+ )+ },+ required=["policy_number"],+ ),+ )+ sync = types.FunctionDeclaration(+ name="sync_claim_packet",+ description=(+ "Send the full claimant conversation and camera observations so far to the "+ "background claim team. Returns the routing decision, severity, blocking intake "+ "items, required documents, and the next best question to ask."+ ),+ behavior=types.Behavior.NON_BLOCKING,+ parameters=types.Schema(+ type=types.Type.OBJECT,+ properties={+ "reason": _string_param(+ "One short phrase on why you are syncing now, for example 'new loss facts' or 'injury mentioned'."+ )+ },+ ),+ )+ pin_photo = types.FunctionDeclaration(+ name="pin_evidence_photo",+ description=(+ "Tape the current camera frame into the claim notebook as evidence, with your own "+ "observation as the caption and whether it confirms what the claimant described. "+ "Call it only after you have looked at the camera and can describe what is in the frame."+ ),+ behavior=types.Behavior.NON_BLOCKING,+ parameters=types.Schema(+ type=types.Type.OBJECT,+ properties={+ "observation": _string_param(+ "One or two concrete sentences describing only what you can actually see in "+ "the frame, for example 'Water line about two inches up the drywall next to "+ "the stairs.' Never restate the claimant's description as your own."+ ),+ "claimant_description": _string_param(+ "What the claimant says this shows, in their words, for example 'a crack in the wall'. "+ "Leave empty if they did not describe it."+ ),+ "confirmed": types.Schema(+ type=types.Type.BOOLEAN,+ description=(+ "True only if the frame clearly shows what the claimant described. False if you "+ "cannot make it out, the frame is blurry or dark, or you see something different."+ ),+ ),+ "evidence_type": _string_param(+ "Short category such as 'damage', 'receipt', 'document', 'serial number', or 'scene'."+ ),+ },+ required=["observation", "confirmed"],+ ),+ )+ sketch = types.FunctionDeclaration(+ name="draw_incident_sketch",+ description=(+ "Ask the claim team to draw a rough hand-drawn pen sketch of the incident scene "+ "into the notebook. Runs in the background for several seconds. Call it once you "+ "know the location, the layout, and what happened. Call it again with corrections."+ ),+ behavior=types.Behavior.NON_BLOCKING,+ parameters=types.Schema(+ type=types.Type.OBJECT,+ properties={+ "scene_description": _string_param(+ "Illustrator brief in plain words: the space or intersection, where things "+ "are, what got damaged, and the direction of impact or water flow. Include "+ "labels to write on the sketch. Fold in any corrections the claimant gave."+ )+ },+ required=["scene_description"],+ ),+ )+ return [types.Tool(function_declarations=[lookup, sync, pin_photo, sketch])]+++def build_live_config() -> types.LiveConnectConfig:+ """Build the LiveConnectConfig for Gemini 3.8 Live with audio and camera input."""++ return types.LiveConnectConfig(+ response_modalities=["AUDIO"],+ system_instruction=SYSTEM_INSTRUCTION,+ speech_config=types.SpeechConfig(+ voice_config=types.VoiceConfig(+ prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=VOICE_NAME)+ )+ ),+ input_audio_transcription=types.AudioTranscriptionConfig(),+ output_audio_transcription=types.AudioTranscriptionConfig(),+ tools=tool_declarations(),+ )+++def scheduling_for(*, urgent: bool) -> types.FunctionResponseScheduling:+ """Pick how the model should react when a background tool result lands."""++ if urgent:+ return types.FunctionResponseScheduling.INTERRUPT+ return types.FunctionResponseScheduling.WHEN_IDLE+++def sketch_prompt(scene_description: str) -> str:+ """Prompt for the image model so every sketch looks like the same adjuster's pen."""++ return (+ "A quick hand-drawn pen sketch on cream notebook paper, the kind an insurance "+ "adjuster draws in a field notebook. Black ink line drawing, loose confident "+ "strokes, small handwritten labels in the same ink, a light blue wash only where "+ "water is present and a light red wash only where impact damage is. Top-down or "+ "simple perspective, no photorealism, no shading gradients, no people. Write no names, "+ "dates, addresses, or claim numbers anywhere; the only text is short labels for the "+ "objects in the scene. Scene to draw: "+ f"{scene_description.strip()}"+ )+++def summarize_workflow_for_voice(workflow: dict[str, Any]) -> dict[str, Any]:+ """Compact the ADK graph output into what the voice agent needs to hear."""++ packet = workflow["claim_intake_packet"]+ validation = workflow["field_validation"]+ fraud_gate = workflow["fraud_safety_gate"]+ classification = workflow["claim_classification"]+ checklist = workflow["document_checklist"]+ route = fraud_gate["final_routing_decision"]+ outstanding_docs = [+ item["item"] for item in checklist.get("items", []) if not item.get("already_provided")+ ]+ return {+ "routing_decision": route,+ "safety_escalation": route == "emergency_escalation",+ "claim_type": classification["claim_type"],+ "severity": classification["severity"],+ "open_items": validation.get("missing_fields", []),+ "open_documents": outstanding_docs[:3],+ "suggested_question_when_topic_is_closed": packet["claimant_next_message"],+ "how_to_use": (+ "Open items are a checklist for the packet. Finish the current topic first, then "+ "raise the item that fits the conversation. Do not read the list out."+ ),+ "handoff_summary": packet["adjuster_handoff_summary"],+ "guardrail": "Do not confirm coverage, payment, or liability.",+ }+++def tool_headline(name: str, args: dict[str, Any], result: dict[str, Any] | None) -> str:+ """One-line description of a tool call for the operator activity feed."""++ if name == "lookup_policy":+ number = str(args.get("policy_number", "")).strip() or "unknown number"+ if result is None:+ return f"Checking policy {number}"+ if result.get("found"):+ return f"{result['policyholder_name']} - {result['policy_line']} ({result['status']})"+ return f"No match for {number}"+ if name == "sync_claim_packet":+ if result is None:+ return "Claim team writing up the notes"+ blockers = result.get("open_items", [])+ route = str(result.get("routing_decision", "")).replace("_", " ")+ if blockers:+ return f"{route}: {len(blockers)} open item{'s' if len(blockers) != 1 else ''} left"+ return f"{route}: no open items"+ if name == "pin_evidence_photo":+ if result is None:+ return "Looking at the camera frame"+ if result.get("pinned"):+ return "Pinned, confirmed on camera" if result.get("confirmed") else "Pinned, not confirmed on camera yet"+ return str(result.get("message", "No camera frame available"))+ if name == "draw_incident_sketch":+ if result is None:+ return "Sketching the scene"+ return "Sketch pinned to the notebook" if result.get("sketched") else str(result.get("message", "Sketch failed"))+ return name+++__all__ = [+ "LIVE_MODEL_ID",+ "SKETCH_MODEL_ID",+ "SYSTEM_INSTRUCTION",+ "TOOL_NAMES",+ "build_live_config",+ "scheduling_for",+ "sketch_prompt",+ "summarize_workflow_for_voice",+ "tool_declarations",+ "tool_headline",+]diff --git a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/server.py b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/server.pyindex eb3c6de7..32852cac 100644--- a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/server.py+++ b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/server.py@@ -13,6 +13,7 @@ import loggingimport osimport reimport sys+import timeimport uuidfrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -58,10 +59,25 @@ from agent import ( # noqa: E402run_claim_workflow,)from schemas import ClaimClassification, ClaimNarrative # noqa: E402+from policy_directory import lookup_policy, policy_status_headline # noqa: E402++if str(DEMO_DIR) not in sys.path:+ sys.path.insert(0, str(DEMO_DIR))++from live_tools import ( # noqa: E402+ LIVE_MODEL_ID,+ SKETCH_MODEL_ID,+ TOOL_NAMES,+ build_live_config,+ scheduling_for,+ sketch_prompt,+ summarize_workflow_for_voice,+ tool_headline,+)-LIVE_MODEL = os.getenv("FNOL_GEMINI_LIVE_MODEL", "gemini-3.1-flash-live-preview")GENAI_CLIENT = Nonelogger = logging.getLogger(__name__)+FRAME_MAX_AGE_SECONDS = 12.0class MessageRequest(BaseModel):@@ -83,6 +99,16 @@ class IntakeSession:normalized_claim: dict[str, Any] | None = Noneclassification: dict[str, Any] | None = Noneroute: str = "needs_docs"+ policy_record: dict[str, Any] | None = None+ live_model: str | None = None+ tool_activity: list[dict[str, Any]] = field(default_factory=list)+ last_workflow_key: str | None = None+ last_workflow: dict[str, Any] | None = None+ evidence_photos: list[dict[str, Any]] = field(default_factory=list)+ camera_notes: list[str] = field(default_factory=list)+ sketch: dict[str, Any] | None = None+ last_frame: bytes | None = None+ last_frame_at: float = 0.0sessions: dict[str, IntakeSession] = {}@@ -134,6 +160,20 @@ def _claimant_text(session: IntakeSession) -> str:)+def _intake_text(session: IntakeSession) -> str:+ """Claimant transcript plus what the agent observed on camera, for the claim graph."""++ text = _claimant_text(session)+ if session.camera_notes:+ notes = "\n".join(f"- {note}" for note in session.camera_notes)+ text = f"{text}\n\nEvidence the intake agent observed on the claimant's camera:\n{notes}"+ return text.strip()+++def _data_url(data: bytes, mime_type: str) -> str:+ return f"data:{mime_type};base64,{base64.b64encode(data).decode('ascii')}"++def _status(value: Any, urgent: bool = False) -> str:text = str(value or "").strip().lower()if urgent:@@ -335,6 +375,7 @@ def _ui_state("photos": counted(_field("Evidence available", evidence_text)),"tow": counted(_field("Tow info", _find_text(claim, ["tow", "storage"]))),"otherDriver": counted(_field("Other driver info", _find_text(claim, ["other driver", "driver", "plate", "witness"]))),+ **_policy_fields(session, counted),}progress = max(12, round(completed / len(fields) * 100))@@ -344,6 +385,16 @@ def _ui_state("fields": fields,"transcript": session.transcript,"events": events,+ "policy": session.policy_record,+ "tool_activity": session.tool_activity[-12:],+ "live_model": session.live_model,+ "missing_blockers": validation.get("missing_fields", []),+ "documents": checklist.get("items", []),+ "evidence_photos": session.evidence_photos,+ "camera_notes": session.camera_notes,+ "sketch": session.sketch,+ "severity": classification.severity,+ "claim_type": classification.claim_type.replace("_", " "),"handoff": {"Summary": packet["adjuster_handoff_summary"],"Priority": f"{classification.severity.title()} - {classification.severity_rationale}",@@ -356,6 +407,43 @@ def _ui_state(}+def _policy_fields(session: IntakeSession, counted) -> dict[str, dict[str, str]]:+ """Policy verification rows sourced from the background lookup_policy tool."""++ record = session.policy_record+ source = "Policy directory lookup"+ if not record:+ return {+ "policyStatus": counted(_field("Policy status", "")),+ "policyLine": counted(_field("Policy line", "")),+ "deductible": counted(_field("Deductibles", "")),+ "coverages": counted(_field("Coverages on file", "")),+ }+ if not record.get("found"):+ return {+ "policyStatus": counted(_field("Policy status", "Not found - confirm number", source=source, urgent=True)),+ "policyLine": counted(_field("Policy line", "")),+ "deductible": counted(_field("Deductibles", "")),+ "coverages": counted(_field("Coverages on file", "")),+ }+ deductibles = ", ".join(+ f"{name.replace('_', ' ')} ${int(amount):,}" for name, amount in record.get("deductibles", {}).items()+ )+ return {+ "policyStatus": counted(+ _field(+ "Policy status",+ policy_status_headline(record),+ source=source,+ urgent=str(record.get("status")) != "active",+ )+ ),+ "policyLine": counted(_field("Policy line", record.get("policy_line", ""), source=source)),+ "deductible": counted(_field("Deductibles", deductibles or "None listed", source=source)),+ "coverages": counted(_field("Coverages on file", "; ".join(record.get("coverages", [])), source=source)),+ }++def _find_text(claim: ClaimNarrative, needles: list[str]) -> str:text = " | ".join([claim.loss_description, *claim.evidence_available, *claim.documents_mentioned, *claim.parties_involved]@@ -387,15 +475,38 @@ def _state_from_workflow(session: IntakeSession, workflow: dict[str, Any]) -> direturn _ui_state(session, validation, coverage, checklist, fraud_gate, packet, events)+def _attach_policy_from_claim(session: IntakeSession, workflow: dict[str, Any]) -> None:+ """Verify an extracted policy number against the directory if the voice agent has not yet."""++ if session.policy_record and session.policy_record.get("found"):+ return+ number = str(workflow["normalized_claim"].get("policy_number", "")).strip()+ if not number or number.lower() in {"not specified", "unknown"}:+ return+ record = lookup_policy(number)+ if record.get("found") or session.policy_record is None:+ session.policy_record = record+++async def _run_workflow_cached(session: IntakeSession) -> dict[str, Any]:+ """Run the ADK graph for the current claimant transcript, reusing the last result if unchanged."""++ text = _intake_text(session)+ if session.last_workflow is not None and session.last_workflow_key == text:+ return session.last_workflow+ workflow = await run_claim_workflow(text, session_id=session.session_id)+ session.last_workflow_key = text+ session.last_workflow = workflow+ _attach_policy_from_claim(session, workflow)+ return workflow++async def _process_with_adk_graph(session: IntakeSession,*,add_claimant_facing_reply: bool,) -> dict[str, Any]:- workflow = await run_claim_workflow(- _claimant_text(session),- session_id=session.session_id,- )+ workflow = await _run_workflow_cached(session)if add_claimant_facing_reply:packet = workflow["claim_intake_packet"]session.transcript.append({"speaker": "Agent", "text": packet["claimant_next_message"]})@@ -404,7 +515,14 @@ async def _process_with_adk_graph(@app.get("/api/health")def health() -> dict[str, Any]:- return {"ok": True, "model": MODEL, "has_api_key": _has_api_key()}+ return {+ "ok": True,+ "model": MODEL,+ "has_api_key": _has_api_key(),+ "live_model": LIVE_MODEL_ID,+ "sketch_model": SKETCH_MODEL_ID,+ "tools": TOOL_NAMES,+ }@app.post("/api/sessions", response_model=SessionResponse)@@ -463,11 +581,102 @@ async def message(request: MessageRequest) -> SessionResponse:)+def _pin_evidence_photo(session: IntakeSession, args: dict[str, Any]) -> dict[str, Any]:+ """Tape the most recent camera frame into the notebook with the agent's caption."""++ observation = str(args.get("observation") or args.get("caption") or "").strip()+ claimant_said = str(args.get("claimant_description", "")).strip()+ confirmed = bool(args.get("confirmed", False))+ if not observation:+ return {"pinned": False, "message": "An observation describing what you can see in the frame is required."}+ if session.last_frame is None:+ return {+ "pinned": False,+ "message": "No camera frame has arrived yet. Ask the claimant to turn on the camera and show the damage.",+ }+ if time.monotonic() - session.last_frame_at > FRAME_MAX_AGE_SECONDS:+ return {+ "pinned": False,+ "message": "The camera stopped sending frames. Ask the claimant to turn the camera back on.",+ }+ photo = {+ "id": uuid.uuid4().hex,+ "data_url": _data_url(session.last_frame, "image/jpeg"),+ "caption": observation,+ "claimant_description": claimant_said,+ "confirmed": confirmed,+ "evidence_type": str(args.get("evidence_type", "damage")).strip() or "damage",+ "captured_at": time.strftime("%H:%M"),+ }+ session.evidence_photos.append(photo)+ note = f"Agent saw on camera: {observation}"+ if claimant_said:+ note += f" Claimant described it as: {claimant_said}."+ note += " Confirmed on camera." if confirmed else " Not confirmed on camera; needs a clearer photo."+ session.camera_notes.append(note)+ return {+ "pinned": True,+ "confirmed": confirmed,+ "photo_count": len(session.evidence_photos),+ "message": (+ "Frame taped into the notebook as confirmed evidence."+ if confirmed+ else "Frame taped into the notebook marked as not confirmed. Ask for a closer or brighter view, then pin again."+ ),+ }+++async def _draw_incident_sketch(session: IntakeSession, args: dict[str, Any]) -> dict[str, Any]:+ """Generate a pen sketch of the incident scene with the image model."""++ brief = str(args.get("scene_description", "")).strip()+ if not brief:+ return {"sketched": False, "message": "A scene description is required."}+ from google.genai import types++ response = await _client().aio.models.generate_content(+ model=SKETCH_MODEL_ID,+ contents=sketch_prompt(brief),+ config=types.GenerateContentConfig(response_modalities=["IMAGE"]),+ )+ image_part = next(+ (+ part+ for candidate in response.candidates or []+ for part in (candidate.content.parts if candidate.content else [])+ if part.inline_data and part.inline_data.data+ ),+ None,+ )+ if image_part is None:+ return {"sketched": False, "message": "The sketch model returned no image. Continue without it."}+ version = (session.sketch or {}).get("version", 0) + 1+ session.sketch = {+ "data_url": _data_url(image_part.inline_data.data, image_part.inline_data.mime_type or "image/png"),+ "brief": brief,+ "version": version,+ "confirmed": False,+ }+ return {+ "sketched": True,+ "version": version,+ "next_step": "Tell the claimant the sketch is in the notebook and ask if it looks right.",+ }+++def _current_ui_state(session: IntakeSession) -> dict[str, Any]:+ """Rebuild the UI state from the cached workflow without re-running the graph."""++ workflow = session.last_workflow or build_initial_workflow_state()+ return _state_from_workflow(session, workflow)++@app.websocket("/ws/live")async def live_voice(websocket: WebSocket) -> None:await websocket.accept()+ live_model = LIVE_MODEL_IDsession_id = str(uuid.uuid4())- session = IntakeSession(session_id=session_id)+ session = IntakeSession(session_id=session_id, live_model=live_model)session.transcript.append({"speaker": "Agent",@@ -499,41 +708,28 @@ async def live_voice(websocket: WebSocket) -> None:{"type": "session","session_id": session_id,- "model": LIVE_MODEL,- "message": "Gemini Live voice session connected.",+ "model": live_model,+ "sketch_model": SKETCH_MODEL_ID,+ "tools": TOOL_NAMES,+ "message": "Gemini 3.8 Live voice session connected.",})- config = types.LiveConnectConfig(- response_modalities=["AUDIO"],- system_instruction=(- "You are a voice insurance FNOL intake agent. Speak naturally and briefly. "- "Your job is to collect enough blocking intake facts for a smooth adjuster handoff, "- "not to end the call after the claimant's first narrative. If injury, unsafe housing, "- "or immediate danger is mentioned, prioritize safety and human escalation. Otherwise, "- "keep asking for missing blockers one step at a time: claimant name, contact method, "- "policy number if available, date and location of loss, what happened, safety/injury "- "status, evidence, documents, reports, tow details, or other involved parties. Do not "- "promise coverage, payment, liability, benefits, or approval. Ask only one or two "- "focused follow-up questions at a time."- ),- speech_config=types.SpeechConfig(- voice_config=types.VoiceConfig(- prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")- )- ),- input_audio_transcription=types.AudioTranscriptionConfig(),- output_audio_transcription=types.AudioTranscriptionConfig(),- )+ config = build_live_config()state_lock = asyncio.Lock()background_tasks: set[asyncio.Task] = set()+ tool_tasks: dict[str, asyncio.Task] = {}+ pending_input = ""+ pending_output = ""- def schedule_state_update(text: str) -> None:- task = asyncio.create_task(update_claim_state(text))+ def track(task: asyncio.Task) -> None:background_tasks.add(task)task.add_done_callback(background_tasks.discard)+ def schedule_state_update(text: str) -> None:+ track(asyncio.create_task(update_claim_state(text)))+async def update_claim_state(text: str) -> None:if not text.strip():return@@ -545,8 +741,120 @@ async def live_voice(websocket: WebSocket) -> None:except Exception as exc:await websocket.send_json({"type": "error", "message": f"Claim state update failed: {exc}"})+ async def finalize_input(reason: str) -> None:+ nonlocal pending_input+ finished = pending_input.strip()+ if not finished:+ return+ pending_input = ""+ await websocket.send_json(+ {"type": "transcript", "speaker": "Claimant", "text": finished, "final": True, "reason": reason}+ )+ schedule_state_update(finished)++ async def finalize_output(reason: str) -> None:+ nonlocal pending_output+ finished = pending_output.strip()+ if not finished:+ return+ pending_output = ""+ session.transcript.append({"speaker": "Agent", "text": finished})+ await websocket.send_json(+ {"type": "transcript", "speaker": "Agent", "text": finished, "final": True, "reason": reason}+ )++ def record_activity(entry: dict[str, Any]) -> None:+ session.tool_activity = [item for item in session.tool_activity if item["id"] != entry["id"]]+ session.tool_activity.append(entry)+ session.tool_activity = session.tool_activity[-30:]++ async def publish_tool(entry: dict[str, Any]) -> None:+ record_activity(entry)+ await websocket.send_json({"type": "tool", **entry})++ async def execute_tool(fc: Any, live_session: Any) -> None:+ """Run one background tool call and hand the result back to Gemini Live."""++ started = time.monotonic()+ name = str(fc.name or "")+ args = dict(fc.args or {})+ call_id = str(fc.id or uuid.uuid4())+ entry: dict[str, Any] = {+ "id": call_id,+ "name": name,+ "args": args,+ "phase": "running",+ "headline": tool_headline(name, args, None),+ "model": live_model,+ }+ await publish_tool(entry)++ urgent = False+ refresh_ui_after_response = False+ try:+ if name == "lookup_policy":+ result = lookup_policy(str(args.get("policy_number", "")))+ session.policy_record = result+ urgent = bool(result.get("found") and str(result.get("status")) != "active")+ refresh_ui_after_response = True+ elif name == "sync_claim_packet":+ await finalize_input("tool_call")+ async with state_lock:+ workflow = await _run_workflow_cached(session)+ await websocket.send_json(+ {"type": "state", "state": _state_from_workflow(session, workflow)}+ )+ result = summarize_workflow_for_voice(workflow)+ urgent = bool(result["safety_escalation"])+ elif name == "pin_evidence_photo":+ result = _pin_evidence_photo(session, args)+ refresh_ui_after_response = True+ elif name == "draw_incident_sketch":+ result = await _draw_incident_sketch(session, args)+ refresh_ui_after_response = True+ else:+ result = {"error": f"Unknown tool: {name}"}+ except asyncio.CancelledError:+ entry.update(phase="cancelled", headline="Cancelled by the model", duration_ms=int((time.monotonic() - started) * 1000))+ await publish_tool(entry)+ raise+ except Exception as exc:+ logger.exception("Tool %s failed", name)+ result = {"error": str(exc)}++ scheduling = scheduling_for(urgent=urgent)+ await live_session.send_tool_response(+ function_responses=[+ types.FunctionResponse(+ id=fc.id,+ name=name,+ response=result,+ scheduling=scheduling,+ )+ ]+ )+ entry.update(+ phase="error" if "error" in result else "done",+ headline=result["error"] if "error" in result else tool_headline(name, args, result),+ scheduling=scheduling.value if scheduling else None,+ urgent=urgent,+ duration_ms=int((time.monotonic() - started) * 1000),+ result=result,+ )+ await publish_tool(entry)+ if refresh_ui_after_response:+ # The model already has its answer; the operator UI can wait for the state lock.+ async with state_lock:+ await websocket.send_json({"type": "state", "state": _current_ui_state(session)})++ def launch_tool(fc: Any, live_session: Any) -> None:+ task = asyncio.create_task(execute_tool(fc, live_session))+ tool_tasks[str(fc.id)] = task+ task.add_done_callback(lambda done, key=str(fc.id): tool_tasks.pop(key, None))+ track(task)+try:- async with _client().aio.live.connect(model=LIVE_MODEL, config=config) as live_session:+ async with _client().aio.live.connect(model=live_model, config=config) as live_session:async def client_to_gemini() -> None:while True:message = await websocket.receive_json()@@ -556,58 +864,45 @@ async def live_voice(websocket: WebSocket) -> None:await live_session.send_realtime_input(audio=types.Blob(data=data, mime_type="audio/pcm;rate=16000"))+ elif msg_type == "video":+ frame = base64.b64decode(message["data"])+ session.last_frame = frame+ session.last_frame_at = time.monotonic()+ await live_session.send_realtime_input(+ video=types.Blob(data=frame, mime_type="image/jpeg")+ )elif msg_type == "text":text = str(message.get("text", "")).strip()if text:- session.transcript.append({"speaker": "Claimant", "text": text})- await live_session.send(input=text, end_of_turn=True)- state = await _process_with_adk_graph(session, add_claimant_facing_reply=False)- await websocket.send_json({"type": "state", "state": state})+ async with state_lock:+ session.transcript.append({"speaker": "Claimant", "text": text})+ await live_session.send_client_content(+ turns=types.Content(role="user", parts=[types.Part(text=text)]),+ turn_complete=True,+ )+ async with state_lock:+ state = await _process_with_adk_graph(session, add_claimant_facing_reply=False)+ await websocket.send_json({"type": "state", "state": state})elif msg_type == "close":await websocket.close()returnasync def gemini_to_client() -> None:- pending_input = ""- pending_output = ""-- async def finalize_input(reason: str) -> None:- nonlocal pending_input- finished = pending_input.strip()- if not finished:- return- pending_input = ""- await websocket.send_json(- {- "type": "transcript",- "speaker": "Claimant",- "text": finished,- "final": True,- "reason": reason,- }- )- schedule_state_update(finished)-- async def finalize_output(reason: str) -> None:- nonlocal pending_output- finished = pending_output.strip()- if not finished:- return- pending_output = ""- session.transcript.append({"speaker": "Agent", "text": finished})- await websocket.send_json(- {- "type": "transcript",- "speaker": "Agent",- "text": finished,- "final": True,- "reason": reason,- }- )-+ nonlocal pending_input, pending_outputwhile True:turn = live_session.receive()async for response in turn:+ if response.tool_call and response.tool_call.function_calls:+ await finalize_input("tool_call")+ for fc in response.tool_call.function_calls:+ launch_tool(fc, live_session)++ if response.tool_call_cancellation and response.tool_call_cancellation.ids:+ for call_id in response.tool_call_cancellation.ids:+ task = tool_tasks.get(str(call_id))+ if task:+ task.cancel()+server_content = response.server_contentif not server_content:continue@@ -646,6 +941,9 @@ async def live_voice(websocket: WebSocket) -> None:if server_content.model_turn:await finalize_input("model_audio_started")for part in server_content.model_turn.parts or []:+ if getattr(part, "thought", False) and part.text:+ await websocket.send_json({"type": "thought", "text": part.text})+ continueif part.inline_data and isinstance(part.inline_data.data, bytes):await websocket.send_json({diff --git a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/styles.css b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/styles.cssindex 923bf6df..604ce28e 100644--- a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/styles.css+++ b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/styles.css@@ -1,37 +1,45 @@:root {- --canvas: #0c0a09;- --canvas-soft: #14110f;- --panel: #1b1714;- --panel-soft: #211d19;- --panel-strong: #292524;- --ink: #f8f3ea;- --body: #d8d0c7;- --muted: #a8a29e;- --muted-soft: #78716c;- --hairline: rgba(245, 245, 244, 0.11);- --hairline-strong: rgba(245, 245, 244, 0.2);- --success: #86efac;- --success-bg: rgba(22, 163, 74, 0.14);- --warning: #f8d49b;- --warning-bg: rgba(244, 197, 168, 0.14);- --danger: #fca5a5;- --danger-bg: rgba(220, 38, 38, 0.14);- --shadow: 0 24px 70px rgba(0, 0, 0, 0.34);- --radius: 8px;- font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ --desk: #2a221c;+ --desk-edge: #1d1712;+ --card: #34291f;+ --card-line: rgba(255, 240, 220, 0.12);+ --chrome-ink: #f4ede2;+ --chrome-body: #d9cdbd;+ --chrome-muted: #a0917e;+ --paper: #fbf6ea;+ --paper-line: #dcd2bd;+ --paper-margin: #e3b1ad;+ --ink: #23211c;+ --ink-soft: #5d574b;+ --ink-red: #b1372d;+ --ink-green: #3f7a3a;+ --ink-blue: #2f6a94;+ --tape: rgba(236, 222, 176, 0.85);+ --success: #8fd39a;+ --warning: #f2c98a;+ --danger: #f39c93;+ --ui-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;+ --hand: "Caveat", "Patrick Hand", cursive;+ --hand-label: "Patrick Hand", "Caveat", cursive;}* {box-sizing: border-box;}+html,body {margin: 0;- min-width: 1180px;- background:- linear-gradient(180deg, rgba(245, 245, 244, 0.04), rgba(12, 10, 9, 0) 220px),- var(--canvas);- color: var(--ink);+ min-height: 100%;+}++body {+ font-family: var(--ui-font);+ color: var(--chrome-ink);+ background: var(--desk);+ background-image:+ radial-gradient(ellipse at 20% 0%, rgba(255, 225, 180, 0.08), transparent 55%),+ linear-gradient(180deg, var(--desk-edge), var(--desk) 220px);}button,@@ -39,826 +47,842 @@ input {font: inherit;}-button {- transition:- border-color 160ms ease,- background 160ms ease,- transform 160ms ease;-}--button:hover {- transform: translateY(-1px);+h1,+h2,+p {+ margin: 0;}-.app-shell {+.desk {min-height: 100vh;+ display: flex;+ flex-direction: column;}-.workspace {- min-width: 0;-}--.topbar {- height: 78px;+.desk-bar {display: flex;align-items: center;- gap: 24px;- padding: 0 26px;- background: rgba(12, 10, 9, 0.86);- border-bottom: 1px solid var(--hairline);- backdrop-filter: blur(20px);+ justify-content: space-between;+ padding: 18px 28px 8px;}-.title-group {+.brand {display: flex;- align-items: baseline;- gap: 22px;- flex: 1;- min-width: 0;+ align-items: center;+ gap: 14px;}-h1,-h2,-h3,-p {- margin: 0;+.brand-mark {+ width: 34px;+ height: 34px;+ border-radius: 8px;+ background: var(--paper);+ box-shadow: inset 0 -4px 0 var(--paper-margin);}h1 {- font-family: "EB Garamond", Georgia, "Times New Roman", serif;- font-size: 36px;- line-height: 1;- font-weight: 400;- letter-spacing: 0;- color: var(--ink);-}--h2 {- font-size: 17px;- line-height: 1.25;- font-weight: 500;- letter-spacing: 0;- color: var(--ink);-}--h3 {- font-size: 14px;+ font-size: 18px;font-weight: 600;- letter-spacing: 0;- color: var(--ink);-}--.live-model,-.status-line {- color: var(--muted);- font-size: 13px;- display: inline-flex;- align-items: center;- gap: 8px;- white-space: nowrap;-}--.dot {- width: 7px;- height: 7px;- border-radius: 99px;- display: inline-block;+ letter-spacing: -0.01em;}-.dot.ok {- background: var(--success);- box-shadow: 0 0 18px rgba(134, 239, 172, 0.36);+.brand-sub {+ color: var(--chrome-muted);+ font-size: 12px;+ margin-top: 2px;}-.dot.neutral {- background: var(--muted-soft);+.ghost-button,+.text-entry button,+.dialog-header button {+ border: 1px solid var(--card-line);+ background: rgba(255, 240, 220, 0.06);+ color: var(--chrome-ink);+ border-radius: 999px;+ padding: 9px 16px;+ font-size: 13px;+ font-weight: 500;+ cursor: pointer;+ transition: background 140ms ease, transform 140ms ease;}-.status-pill {- border-radius: 999px;- font-size: 12px;- font-weight: 600;- padding: 8px 12px;- text-transform: uppercase;- letter-spacing: 0;+.ghost-button:hover,+.text-entry button:hover,+.dialog-header button:hover {+ background: rgba(255, 240, 220, 0.12);+ transform: translateY(-1px);}-.dashboard {+.desk-layout {+ flex: 1;display: grid;- grid-template-columns: minmax(340px, 0.9fr) minmax(470px, 1.23fr) minmax(370px, 0.96fr);- gap: 16px;- padding: 18px;- height: calc(100vh - 78px);+ grid-template-columns: 360px minmax(0, 1fr);+ gap: 22px;+ padding: 10px 28px 28px;}-.panel {- background: linear-gradient(180deg, rgba(255, 255, 255, 0.035), rgba(255, 255, 255, 0.01)), var(--panel);- border: 1px solid var(--hairline);- border-radius: var(--radius);- box-shadow: var(--shadow);+.side {+ display: flex;+ flex-direction: column;+ gap: 14px;min-width: 0;}-.panel-header {+.card {+ background: var(--card);+ border: 1px solid var(--card-line);+ border-radius: 14px;+ padding: 16px;+}++.card-head {display: flex;align-items: center;justify-content: space-between;- gap: 18px;- padding: 20px;- border-bottom: 1px solid var(--hairline);+ gap: 12px;+ margin-bottom: 12px;}-.panel-header.compact {- padding: 18px 20px;+.card-kicker {+ font-size: 11px;+ font-weight: 600;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--chrome-muted);}-.panel-kicker {- margin-bottom: 6px;- color: var(--muted);+.card-hint {font-size: 11px;- font-weight: 700;- text-transform: uppercase;- letter-spacing: 0;+ color: var(--chrome-muted);+ text-align: right;}-.status-pill.active {+.pill {+ font-size: 11px;+ font-weight: 600;+ padding: 5px 10px;+ border-radius: 999px;+ background: rgba(143, 211, 154, 0.14);color: var(--success);- background: var(--success-bg);- border: 1px solid rgba(134, 239, 172, 0.24);+ white-space: nowrap;}-.call-panel,-.claim-panel,-.right-rail {- min-height: 0;+.pill.neutral {+ background: rgba(255, 240, 220, 0.08);+ color: var(--chrome-body);}-.call-panel,-.claim-panel {- display: flex;- flex-direction: column;+.pill.warning {+ background: rgba(242, 201, 138, 0.16);+ color: var(--warning);}-.voice-stage {- height: 214px;+.pill.danger {+ background: rgba(243, 156, 147, 0.16);+ color: var(--danger);+}++.controls {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 10px;+ margin-bottom: 12px;+}++.round-button {display: flex;+ flex-direction: column;align-items: center;- justify-content: center;- gap: 30px;- border-bottom: 1px solid var(--hairline);- background:- linear-gradient(90deg, rgba(255, 255, 255, 0.035), transparent 28%, transparent 72%, rgba(255, 255, 255, 0.03)),- var(--canvas-soft);- position: relative;- overflow: hidden;+ gap: 8px;+ padding: 14px 8px 12px;+ border-radius: 12px;+ border: 1px solid var(--card-line);+ background: rgba(255, 240, 220, 0.05);+ color: var(--chrome-ink);+ cursor: pointer;+ transition: background 140ms ease, border-color 140ms ease;}-.voice-stage::before,-.voice-stage::after {- content: "";- position: absolute;- inset: 24px auto 24px 24px;- width: 1px;- background: var(--hairline);+.round-button:hover {+ background: rgba(255, 240, 220, 0.1);}-.voice-stage::after {- left: auto;- right: 24px;+.round-button.active {+ background: rgba(143, 211, 154, 0.14);+ border-color: rgba(143, 211, 154, 0.5);}-.mic-button {- width: 126px;- height: 126px;- border-radius: 50%;- border: 1px solid var(--hairline-strong);- outline: 14px solid rgba(245, 245, 244, 0.055);- background: var(--ink);- box-shadow:- 0 0 0 28px rgba(245, 245, 244, 0.025),- 0 24px 60px rgba(0, 0, 0, 0.42);- display: grid;- place-items: center;- cursor: pointer;- position: relative;- z-index: 1;+.round-button.subtle {+ color: var(--chrome-body);}-.mic-button.recording {- background: #f8f3ea;- animation: pulse 1.35s infinite;+.round-label {+ font-size: 12px;+ font-weight: 500;}-.mic-icon {- width: 24px;- height: 38px;- border: 4px solid var(--canvas);- border-radius: 16px;+.icon-mic,+.icon-camera,+.icon-new {+ width: 26px;+ height: 26px;+ display: block;position: relative;}-.mic-icon::after {+.icon-mic::before {content: "";position: absolute;- left: 50%;- bottom: -18px;- width: 4px;- height: 16px;- background: var(--canvas);- transform: translateX(-50%);+ left: 9px;+ top: 2px;+ width: 8px;+ height: 14px;+ border-radius: 5px;+ background: currentColor;}-.mic-icon::before {+.icon-mic::after {content: "";position: absolute;- left: 50%;- bottom: -24px;- width: 30px;- height: 4px;- background: var(--canvas);+ left: 5px;+ top: 9px;+ width: 14px;+ height: 11px;+ border: 2px solid currentColor;+ border-top: 0;+ border-radius: 0 0 9px 9px;+}++.icon-camera::before {+ content: "";+ position: absolute;+ inset: 5px 3px;+ border: 2px solid currentColor;border-radius: 4px;- transform: translateX(-50%);}-@keyframes pulse {- 0% {- box-shadow:- 0 0 0 28px rgba(245, 245, 244, 0.025),- 0 0 0 0 rgba(248, 243, 234, 0.18);- }- 100% {- box-shadow:- 0 0 0 28px rgba(245, 245, 244, 0.025),- 0 0 0 24px rgba(248, 243, 234, 0);- }+.icon-camera::after {+ content: "";+ position: absolute;+ left: 9px;+ top: 9px;+ width: 8px;+ height: 8px;+ border-radius: 50%;+ border: 2px solid currentColor;}-.wave {- display: flex;- gap: 5px;- align-items: center;- height: 58px;+.icon-new::before,+.icon-new::after {+ content: "";+ position: absolute;+ background: currentColor;+ border-radius: 2px;}-.wave span {- width: 3px;- border-radius: 4px;- background: rgba(248, 243, 234, 0.72);- animation: wave 1s ease-in-out infinite alternate;+.icon-new::before {+ left: 12px;+ top: 4px;+ width: 2px;+ height: 18px;}-.wave span:nth-child(1) { height: 10px; }-.wave span:nth-child(2) { height: 22px; animation-delay: 0.1s; }-.wave span:nth-child(3) { height: 36px; animation-delay: 0.2s; }-.wave span:nth-child(4) { height: 54px; animation-delay: 0.3s; }-.wave span:nth-child(5) { height: 28px; animation-delay: 0.4s; }-.wave span:nth-child(6) { height: 14px; animation-delay: 0.5s; }+.icon-new::after {+ left: 4px;+ top: 12px;+ width: 18px;+ height: 2px;+}-@keyframes wave {- to {- transform: scaleY(0.48);- opacity: 0.48;- }+.round-button.active .icon-mic::before {+ animation: pulse 1.2s ease-in-out infinite;}-.call-actions {- display: grid;- grid-template-columns: 1fr auto;- gap: 10px;- padding: 16px 20px 0;+@keyframes pulse {+ 0%, 100% { transform: scaleY(1); }+ 50% { transform: scaleY(0.72); }}-.primary-action,-.secondary-action,-.packet-button,-.text-entry button,-.dialog-header button {- border: 1px solid var(--hairline-strong);- border-radius: 999px;- background: transparent;- color: var(--ink);- font-size: 13px;- font-weight: 600;- padding: 11px 16px;- cursor: pointer;+.camera-stage {+ position: relative;+ border-radius: 12px;+ overflow: hidden;+ margin-bottom: 12px;+ background: #000;+ aspect-ratio: 4 / 3;}-.primary-action,-.text-entry button,-.packet-button {- background: var(--ink);- color: var(--canvas);- border-color: var(--ink);+.camera-stage[hidden] {+ display: none;}-.secondary-action,-.dialog-header button {- background: rgba(255, 255, 255, 0.03);+.camera-stage video {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;}-.transcript-header {- display: flex;- justify-content: space-between;+.camera-tag {+ position: absolute;+ left: 10px;+ bottom: 10px;+ display: inline-flex;align-items: center;- padding: 20px 20px 10px;+ gap: 6px;+ padding: 5px 9px;+ border-radius: 999px;+ background: rgba(0, 0, 0, 0.55);+ color: #fff;+ font-size: 11px;+ font-weight: 500;}-.transcript-header span {- color: var(--muted);- font-size: 12px;+.rec-dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: #f0554a;+ animation: blink 1.4s ease-in-out infinite;+}++@keyframes blink {+ 50% { opacity: 0.3; }}.transcript {- flex: 1;- min-height: 230px;+ max-height: 260px;overflow: auto;- padding: 0 20px 12px;+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding-right: 4px;+ margin-bottom: 12px;}.turn {- display: grid;- grid-template-columns: 32px 1fr;- gap: 11px;- margin-bottom: 12px;+ display: flex;+ gap: 8px;+ font-size: 13px;+ line-height: 1.45;}-.speaker-icon {- width: 29px;- height: 29px;+.turn .who {+ flex-shrink: 0;+ width: 26px;+ height: 26px;border-radius: 50%;display: grid;place-items: center;- background: var(--panel-strong);- border: 1px solid var(--hairline-strong);- color: var(--ink);- font-size: 11px;- font-weight: 700;+ font-size: 10px;+ font-weight: 600;+ background: rgba(255, 240, 220, 0.1);+ color: var(--chrome-body);}-.turn.agent .speaker-icon {- background: rgba(245, 245, 244, 0.1);+.turn.agent .who {+ background: var(--paper);+ color: var(--ink);}-.bubble {- border-radius: 8px;- background: rgba(245, 245, 244, 0.04);- padding: 12px 13px;- border: 1px solid var(--hairline);+.turn p {+ color: var(--chrome-body);+ padding-top: 4px;}-.bubble strong {- font-size: 12px;- margin-right: 8px;- color: var(--ink);+.turn.agent p {+ color: var(--chrome-ink);}-.bubble time {- color: var(--muted-soft);- font-size: 11px;+.turn.streaming p::after {+ content: "";+ display: inline-block;+ width: 6px;+ height: 12px;+ margin-left: 3px;+ vertical-align: -2px;+ background: var(--chrome-muted);+ animation: blink 0.9s steps(2) infinite;}-.bubble p {- margin-top: 8px;- color: var(--body);- font-size: 14px;- line-height: 1.48;- overflow-wrap: anywhere;+.turn.system p {+ color: var(--danger);}.text-entry {- display: grid;- grid-template-columns: 1fr auto;+ display: flex;gap: 8px;- padding: 16px 20px 20px;}.text-entry input {- height: 44px;- border: 1px solid var(--hairline-strong);+ flex: 1;+ min-width: 0;border-radius: 999px;- padding: 0 16px;- color: var(--ink);- background: rgba(255, 255, 255, 0.035);- outline: none;+ border: 1px solid var(--card-line);+ background: rgba(0, 0, 0, 0.2);+ color: var(--chrome-ink);+ padding: 10px 14px;+ font-size: 13px;}.text-entry input::placeholder {- color: var(--muted-soft);+ color: var(--chrome-muted);}.text-entry input:focus {- border-color: var(--ink);- box-shadow: 0 0 0 3px rgba(248, 243, 234, 0.08);+ outline: 0;+ border-color: rgba(255, 240, 220, 0.4);}-.claim-sections {- overflow: auto;- padding: 0 20px 20px;+.needed-list,+.team-feed {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 7px;}-.field-group {- padding: 19px 0 17px;- border-bottom: 1px solid var(--hairline);+.needed-list li {+ display: flex;+ align-items: flex-start;+ gap: 9px;+ font-size: 13px;+ line-height: 1.4;+ color: var(--chrome-body);}-.field-group:last-child {- border-bottom: 0;+.needed-list li.done {+ color: var(--chrome-muted);+ text-decoration: line-through;}-.group-title {- display: flex;- justify-content: space-between;- align-items: center;- margin-bottom: 13px;+.needed-list li.empty {+ color: var(--chrome-muted);+ font-style: italic;}-.group-title h3 {- font-size: 15px;+.tick-box {+ flex-shrink: 0;+ width: 15px;+ height: 15px;+ margin-top: 2px;+ border-radius: 4px;+ border: 1.5px solid var(--chrome-muted);+ position: relative;}-.field-row {- display: grid;- grid-template-columns: minmax(120px, 0.72fr) minmax(180px, 1.12fr) minmax(120px, 0.86fr);- gap: 10px;- align-items: center;- margin-bottom: 8px;+.needed-list li.done .tick-box {+ border-color: var(--success);+ background: rgba(143, 211, 154, 0.2);}-.field-label {- color: var(--body);- font-size: 13px;+.needed-list li.done .tick-box::after {+ content: "";+ position: absolute;+ left: 4px;+ top: 1px;+ width: 4px;+ height: 8px;+ border: solid var(--success);+ border-width: 0 2px 2px 0;+ transform: rotate(45deg);}-.field-value,-.field-source {- min-height: 36px;- display: flex;- align-items: center;- border: 1px solid var(--hairline);- border-radius: 8px;- padding: 8px 10px;- font-size: 13px;- line-height: 1.25;- background: rgba(255, 255, 255, 0.035);- color: var(--body);+.needed-list li.blocker .tick-box {+ border-color: var(--warning);}-.field-source {- color: var(--muted);- background: rgba(255, 255, 255, 0.025);+.team-feed li {+ display: grid;+ grid-template-columns: 10px 1fr auto;+ gap: 9px;+ align-items: start;+ font-size: 12px;+ line-height: 1.4;+ color: var(--chrome-body);}-.field-value.complete {- color: var(--success);- border-color: rgba(134, 239, 172, 0.24);- background: var(--success-bg);+.team-feed li.empty {+ grid-template-columns: 1fr;+ color: var(--chrome-muted);+ font-style: italic;}-.field-value.pending,-.field-value.missing {- color: var(--warning);- border-color: rgba(248, 212, 155, 0.24);- background: var(--warning-bg);+.team-dot {+ width: 8px;+ height: 8px;+ margin-top: 5px;+ border-radius: 50%;+ background: var(--chrome-muted);}-.field-value.urgent {- color: var(--danger);- border-color: rgba(252, 165, 165, 0.26);- background: var(--danger-bg);+.team-dot.running {+ background: var(--warning);+ animation: blink 1s ease-in-out infinite;}-.right-rail {- display: grid;- grid-template-rows: minmax(380px, 1fr) minmax(260px, 0.78fr);- gap: 16px;- min-height: 0;+.team-dot.done {+ background: var(--success);}-.timeline-panel,-.handoff-panel {- min-height: 0;- overflow: hidden;+.team-dot.error,+.team-dot.cancelled {+ background: var(--danger);}-.operator-workbench {- overflow: auto;- height: calc(100% - 73px);- padding: 16px 20px 20px;+.team-name {+ font-weight: 600;+ color: var(--chrome-ink);}-.decision-card,-.operator-card,-.audit-details {- border: 1px solid var(--hairline);- border-radius: 8px;- background: rgba(245, 245, 244, 0.04);- padding: 15px;- margin-bottom: 12px;+.team-meta {+ color: var(--chrome-muted);+ font-size: 11px;+ white-space: nowrap;}-.decision-card {- border-color: rgba(248, 212, 155, 0.23);- background: var(--warning-bg);+.team-meta.interrupt {+ color: var(--danger);}-.decision-card.success {- border-color: rgba(134, 239, 172, 0.24);- background: var(--success-bg);+.notebook-wrap {+ min-width: 0;+ display: flex;+ justify-content: center;+ align-items: flex-start;}-.decision-card.danger {- border-color: rgba(252, 165, 165, 0.26);- background: var(--danger-bg);+.notebook {+ position: relative;+ width: min(880px, 100%);+ min-height: calc(100vh - 110px);+ background: var(--paper);+ background-image:+ linear-gradient(90deg, transparent 62px, var(--paper-margin) 62px, var(--paper-margin) 64px, transparent 64px),+ repeating-linear-gradient(transparent 0 33px, var(--paper-line) 33px 34px);+ background-position: 0 0, 0 86px;+ border-radius: 6px 12px 12px 6px;+ box-shadow:+ 0 30px 70px rgba(0, 0, 0, 0.45),+ 0 2px 0 rgba(255, 255, 255, 0.5) inset;+ padding: 26px 40px 120px 92px;+ color: var(--ink);}-.decision-label,-.operator-card-label {- color: var(--muted);- font-size: 11px;- font-weight: 700;- text-transform: uppercase;- letter-spacing: 0;+.holes {+ position: absolute;+ left: 20px;+ top: 70px;+ bottom: 70px;+ display: flex;+ flex-direction: column;+ justify-content: space-between;}-.decision-card strong {- display: block;- margin-top: 8px;- font-family: "EB Garamond", Georgia, "Times New Roman", serif;- font-size: 28px;- font-weight: 400;- line-height: 1.05;- color: var(--ink);+.holes span {+ width: 18px;+ height: 18px;+ border-radius: 50%;+ background: var(--desk);+ box-shadow: inset 0 2px 3px rgba(0, 0, 0, 0.5);}-.decision-card p,-.operator-card p {- margin-top: 9px;- color: var(--body);- font-size: 13px;- line-height: 1.45;+.page-head {+ display: flex;+ justify-content: space-between;+ font-family: var(--hand-label);+ font-size: 16px;+ color: var(--ink-soft);+ margin-bottom: 26px;}-.ask-card p {- font-size: 16px;- line-height: 1.4;- color: var(--ink);+.notes {+ font-family: var(--hand);+ font-size: 27px;+ line-height: 34px;+ min-height: 34px;}-.missing-chips {- display: flex;- flex-wrap: wrap;- gap: 8px;- margin-top: 12px;+.note {+ position: relative;+ padding-right: 8px;+ overflow-wrap: anywhere;}-.missing-chips span {- display: inline-flex;- align-items: center;- min-height: 30px;- border-radius: 999px;- border: 1px solid rgba(248, 212, 155, 0.24);- background: rgba(248, 212, 155, 0.1);- color: var(--warning);- font-size: 12px;+.note.title {+ font-size: 32px;font-weight: 600;- padding: 5px 10px;}-.readiness-meter {- height: 9px;- overflow: hidden;- border-radius: 999px;- background: rgba(245, 245, 244, 0.09);- margin-top: 12px;+.note.blank {+ color: var(--ink-red);}-.readiness-meter div {- height: 100%;- border-radius: inherit;- background: var(--ink);+.note.blank .blank-line {+ display: inline-block;+ width: 150px;+ height: 0;+ border-bottom: 2px solid var(--ink-red);+ vertical-align: -6px;+ margin-left: 8px;}-.readiness-copy {- color: var(--muted);+.note.urgent {+ color: var(--ink-red);+ text-decoration: underline;+ text-decoration-thickness: 2px;+ text-underline-offset: 5px;}-.audit-details {- background: rgba(245, 245, 244, 0.025);+.note.check {+ color: var(--ink-green);}-.audit-details summary {- cursor: pointer;- color: var(--body);- font-size: 13px;- font-weight: 600;+.note.check::before {+ content: "";+ position: absolute;+ left: -54px;+ top: 8px;+ width: 9px;+ height: 17px;+ border: solid var(--ink-green);+ border-width: 0 3px 3px 0;+ transform: rotate(40deg);}-.audit-list {- margin-top: 14px;+.note.flag::before {+ content: "!";+ position: absolute;+ left: -52px;+ top: -2px;+ font-family: var(--hand);+ font-size: 34px;+ font-weight: 600;+ color: var(--ink-red);}-.event {- display: grid;- grid-template-columns: 72px 1fr auto;- gap: 10px;- padding: 0 0 17px;- position: relative;+.note.aside {+ font-size: 22px;+ color: var(--ink-soft);}-.event::before {- content: "";- position: absolute;- left: 80px;- top: 17px;- bottom: 0;- width: 1px;- background: var(--hairline);+.note.ink-in {+ animation: inkIn 720ms cubic-bezier(0.2, 0.7, 0.3, 1) both;}-.event:last-child::before {- display: none;+@keyframes inkIn {+ from {+ clip-path: inset(0 100% 0 0);+ opacity: 0.4;+ }+ to {+ clip-path: inset(0 0 0 0);+ opacity: 1;+ }}-.event-time {- color: var(--muted-soft);- font-size: 12px;+.pinboard {+ display: flex;+ flex-wrap: wrap;+ gap: 30px 26px;+ margin-top: 28px;+ align-items: flex-start;}-.event-body {+.polaroid {position: relative;- padding-left: 18px;+ width: 220px;+ padding: 8px 8px 12px;+ background: #fff;+ border: 1px solid #d9d0bb;+ box-shadow: 0 8px 20px rgba(0, 0, 0, 0.16);+ transform: rotate(var(--tilt, -2deg));+ animation: pinIn 520ms cubic-bezier(0.2, 0.8, 0.3, 1.2) both;+ margin: 0;+}++.polaroid.sketch {+ width: 340px;}-.event-body::before {+.polaroid::before {content: "";position: absolute;- left: -2px;- top: 4px;- width: 9px;- height: 9px;- border-radius: 50%;- background: var(--muted);- border: 2px solid var(--panel);- box-shadow: 0 0 0 1px var(--hairline-strong);+ top: -10px;+ left: 50%;+ width: 74px;+ height: 20px;+ margin-left: -37px;+ background: var(--tape);+ transform: rotate(-3deg);+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12);+}++.polaroid img {+ display: block;+ width: 100%;+ height: auto;+ background: #e6e1d6;}-.event.warning .event-body::before { background: var(--warning); }-.event.danger .event-body::before { background: var(--danger); }-.event.success .event-body::before { background: var(--success); }+.polaroid.sketch img {+ border: 1px solid #ece6d8;+}-.event-title {+.polaroid figcaption {+ font-family: var(--hand);+ font-size: 19px;+ line-height: 21px;color: var(--ink);+ margin-top: 8px;+}++.polaroid .tag {+ font-family: var(--hand-label);font-size: 13px;- font-weight: 600;- line-height: 1.25;+ color: var(--ink-soft);+ display: block;+ margin-top: 3px;}-.event-detail {- color: var(--muted);- font-size: 12px;- line-height: 1.38;- margin-top: 4px;- overflow-wrap: anywhere;+.polaroid.sketch figcaption {+ color: var(--ink-blue);}-.rule-id {- color: var(--muted-soft);- font-size: 11px;- font-weight: 700;+.polaroid .tag.unconfirmed {+ color: var(--ink-red);}-.handoff-list {- margin: 0;- padding: 12px 20px 10px;- overflow: auto;- max-height: calc(100% - 124px);+@keyframes pinIn {+ from {+ opacity: 0;+ transform: rotate(var(--tilt, -2deg)) translateY(18px) scale(0.96);+ }+ to {+ opacity: 1;+ transform: rotate(var(--tilt, -2deg)) translateY(0) scale(1);+ }}-.handoff-row {- display: grid;- grid-template-columns: 112px 1fr;- gap: 14px;- padding: 12px 0;- border-bottom: 1px solid var(--hairline);+.stamp {+ position: absolute;+ right: 44px;+ bottom: 42px;+ padding: 6px 16px;+ border: 4px solid var(--ink-red);+ border-radius: 6px;+ color: var(--ink-red);+ font-family: var(--hand-label);+ font-size: 30px;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ transform: rotate(-9deg);+ opacity: 0.85;+ mix-blend-mode: multiply;+ animation: stampIn 420ms cubic-bezier(0.2, 0.9, 0.3, 1.4) both;}-.handoff-row dt {- color: var(--muted);- font-size: 12px;- font-weight: 600;+.stamp[hidden] {+ display: none;}-.handoff-row dd {- margin: 0;- color: var(--body);- font-size: 12px;- line-height: 1.45;+.stamp.success {+ border-color: var(--ink-green);+ color: var(--ink-green);}-.progress-ring {- width: 52px;- height: 52px;- display: grid;- place-items: center;- border: 5px solid rgba(245, 245, 244, 0.1);- border-right-color: var(--ink);- border-radius: 50%;- color: var(--ink);- font-size: 12px;- font-weight: 700;+.stamp.info {+ border-color: var(--ink-blue);+ color: var(--ink-blue);}-.packet-button {- width: calc(100% - 40px);- margin: 0 20px 20px;+@keyframes stampIn {+ from {+ opacity: 0;+ transform: rotate(-9deg) scale(1.6);+ }+ to {+ opacity: 0.85;+ transform: rotate(-9deg) scale(1);+ }+}++.pen {+ position: absolute;+ left: 92px;+ bottom: 48px;+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font-family: var(--hand);+ font-size: 22px;+ color: var(--ink-soft);+}++.pen[hidden] {+ display: none;+}++.pen-nib {+ width: 14px;+ height: 14px;+ border-radius: 50% 50% 50% 0;+ background: var(--ink);+ transform: rotate(-45deg);+ animation: scribble 0.9s ease-in-out infinite;+}++@keyframes scribble {+ 0%, 100% { transform: rotate(-45deg) translate(0, 0); }+ 50% { transform: rotate(-45deg) translate(3px, -2px); }}.packet-dialog {width: min(860px, calc(100vw - 48px));- border: 1px solid var(--hairline-strong);- border-radius: 8px;- box-shadow: 0 30px 90px rgba(0, 0, 0, 0.62);+ border: 1px solid var(--card-line);+ border-radius: 14px;padding: 0;- background: var(--panel);- color: var(--ink);+ background: var(--card);+ color: var(--chrome-ink);+ box-shadow: 0 30px 90px rgba(0, 0, 0, 0.6);}.packet-dialog::backdrop {- background: rgba(0, 0, 0, 0.62);+ background: rgba(0, 0, 0, 0.6);}.dialog-header {display: flex;justify-content: space-between;align-items: center;- padding: 18px 20px;- border-bottom: 1px solid var(--hairline);+ padding: 16px 20px;+ border-bottom: 1px solid var(--card-line);+}++.dialog-header h2 {+ font-size: 16px;+ font-weight: 600;}.packet-dialog pre {white-space: pre-wrap;margin: 0;padding: 20px;- color: var(--body);+ color: var(--chrome-body);font: 13px/1.55 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;max-height: 68vh;overflow: auto;}-@media (max-width: 980px) {- body {- min-width: 0;- }-- .topbar {- height: auto;- min-height: 72px;- flex-wrap: wrap;- padding: 16px;- }-- .title-group {- min-width: 0;- width: 100%;- flex-direction: column;- align-items: flex-start;- gap: 8px;- }-- h1 {- font-size: 32px;- }-- .dashboard {+@media (max-width: 1080px) {+ .desk-layout {grid-template-columns: 1fr;- height: auto;- padding: 12px;- }-- .right-rail {- grid-template-rows: auto auto;}- .call-panel,- .claim-panel,- .timeline-panel,- .handoff-panel {- min-height: 520px;- }-- .field-row {- grid-template-columns: 1fr;- gap: 6px;- margin-bottom: 14px;- }-- .field-value,- .field-source {- width: 100%;- }-- .handoff-row {- grid-template-columns: 1fr;- gap: 6px;+ .notebook {+ min-height: 720px;+ padding-left: 78px;}}diff --git a/voice_ai_agents/insurance_claim_live_agent_team/policy_directory.py b/voice_ai_agents/insurance_claim_live_agent_team/policy_directory.pynew file mode 100644index 00000000..1d292e13--- /dev/null+++ b/voice_ai_agents/insurance_claim_live_agent_team/policy_directory.py@@ -0,0 +1,154 @@+"""Mock policy directory used by the live voice agent's background policy lookup.++This stands in for a carrier policy administration system. The records line up+with the demo prompts in examples.py so a live call can verify the policy the+claimant mentions while the conversation keeps going.+"""++from __future__ import annotations++import re+from typing import Any++POLICY_RECORDS: dict[str, dict[str, Any]] = {+ "H044721": {+ "policy_number": "H0-44721",+ "policyholder_name": "Maya Singh",+ "policy_line": "Homeowners (HO-3)",+ "status": "active",+ "effective_period": "2026-01-01 to 2026-12-31",+ "deductibles": {"all_perils": 1000, "wind_hail": 2500},+ "coverages": [+ "Dwelling $620,000",+ "Personal property $310,000",+ "Water backup and sump overflow endorsement $10,000",+ "Loss of use 12 months",+ ],+ "notes": ["Sump pump and water backup endorsement is on file."],+ },+ "AUTO90210": {+ "policy_number": "AUTO-90210",+ "policyholder_name": "Jordan Lee",+ "policy_line": "Personal auto",+ "status": "active",+ "effective_period": "2026-03-15 to 2026-09-15",+ "deductibles": {"collision": 500, "comprehensive": 250},+ "coverages": [+ "Bodily injury 100/300",+ "Collision",+ "Comprehensive",+ "Medical payments $5,000",+ "Rental reimbursement $40/day up to 30 days",+ ],+ "notes": ["Two listed drivers.", "Rental reimbursement is available while the vehicle is in the shop."],+ },+ "RNT3008": {+ "policy_number": "RNT-3008",+ "policyholder_name": "Priya Shah",+ "policy_line": "Renters (HO-4)",+ "status": "active",+ "effective_period": "2025-11-01 to 2026-10-31",+ "deductibles": {"all_perils": 250},+ "coverages": [+ "Personal property $25,000",+ "Theft away from premises up to 10 percent of personal property",+ "Personal liability $100,000",+ ],+ "notes": ["Theft claims require a police report number before adjuster assignment."],+ },+ "TRV7711": {+ "policy_number": "TRV-7711",+ "policyholder_name": "Alex Chen",+ "policy_line": "Single trip travel",+ "status": "active",+ "effective_period": "Trip dates 2026-01-12 to 2026-01-22",+ "deductibles": {"trip_delay": 0, "trip_cancellation": 0},+ "coverages": [+ "Trip cancellation up to $5,000",+ "Trip delay $200 per day after 6 hours, up to $1,000",+ "Baggage delay $300",+ ],+ "notes": ["Weather-related carrier cancellations are a listed covered reason."],+ },+ "MED5520": {+ "policy_number": "MED-5520",+ "policyholder_name": "Sam Rivera",+ "policy_line": "Supplemental medical reimbursement",+ "status": "active",+ "effective_period": "2026-01-01 to 2026-12-31",+ "deductibles": {"annual": 300},+ "coverages": [+ "Out-of-pocket medical reimbursement up to $7,500 per year",+ "Urgent care and emergency room copay reimbursement",+ ],+ "notes": ["Itemized provider bill and explanation of benefits are required."],+ },+ "AUTO11111": {+ "policy_number": "AUTO-11111",+ "policyholder_name": "Chris Park",+ "policy_line": "Personal auto",+ "status": "lapsed",+ "effective_period": "2025-08-01 to 2026-08-01 (not renewed)",+ "deductibles": {"collision": 1000},+ "coverages": ["Collision", "Comprehensive"],+ "notes": [+ "Policy lapsed on 2026-08-01 for non-payment.",+ "Any loss after the lapse date needs underwriting and human review before intake continues.",+ ],+ },+}+++def normalize_policy_number(value: str) -> str:+ """Collapse spacing, punctuation, and letter O versus zero confusion."""++ text = re.sub(r"[^A-Za-z0-9]", "", str(value or "")).upper()+ # Voice transcripts often render zeros as the letter O inside the numeric tail.+ match = re.match(r"^([A-Z]+)([A-Z0-9]*)$", text)+ if match and match.group(2):+ prefix, tail = match.groups()+ tail = tail.replace("O", "0")+ # Keep the prefix's trailing O as a zero when the record uses one (H0-44721).+ if prefix.endswith("O") and (prefix[:-1] + "0" + tail) in POLICY_RECORDS:+ prefix = prefix[:-1] + "0"+ text = prefix + tail+ return text+++def lookup_policy(policy_number: str) -> dict[str, Any]:+ """Return the policy record for a policy number, or a not-found payload."""++ key = normalize_policy_number(policy_number)+ if not key:+ return {+ "found": False,+ "policy_number": "",+ "message": "No policy number was provided. Ask the claimant to read it from their ID card or renewal notice.",+ }+ record = POLICY_RECORDS.get(key)+ if record is None:+ return {+ "found": False,+ "policy_number": str(policy_number).strip(),+ "message": (+ "No policy matched that number. Ask the claimant to confirm it digit by digit, "+ "or continue intake using their name and contact details."+ ),+ }+ return {"found": True, **record}+++def policy_status_headline(record: dict[str, Any]) -> str:+ """Short human-readable status for the UI and voice summary."""++ if not record.get("found"):+ return "Not found"+ status = str(record.get("status", "unknown")).lower()+ if status == "active":+ return "Active"+ if status == "lapsed":+ return "Lapsed - human review required"+ return status.title()+++__all__ = ["POLICY_RECORDS", "lookup_policy", "normalize_policy_number", "policy_status_headline"]diff --git a/voice_ai_agents/insurance_claim_live_agent_team/requirements.txt b/voice_ai_agents/insurance_claim_live_agent_team/requirements.txtindex c11f4cf9..0b0ad80e 100644--- a/voice_ai_agents/insurance_claim_live_agent_team/requirements.txt+++ b/voice_ai_agents/insurance_claim_live_agent_team/requirements.txt@@ -1,5 +1,5 @@google-adk>=2.0.0a1-google-genai>=1.0.0+google-genai>=1.75.0fastapi>=0.115uvicorn[standard]>=0.30pydantic>=2.7