# Surfaces

A patient calls to schedule an appointment. During the call, the agent realizes it needs insurance information and a photo of the insurance card. It cannot collect a photo over the phone. Instead of asking the patient to call back or visit a portal, the agent generates a surface - a short data collection form - and texts the patient a secure link before the call ends. The patient fills it out on their phone. The data flows back into the world model, passes through confidence gates and review, and is available for the next interaction.

Surfaces close the gap between "we need this data" and "we have a way to collect it." They work across channels, are generated dynamically by agents based on what they know and what they need, and feed directly into the same data pipeline as every other source.

## How Surfaces Work

<figure><img src="/files/TAcZCOjIgbZ13zmxmVv2" alt="Surface lifecycle: agent reasoning to platform execution to patient to world model"><figcaption></figcaption></figure>

The agent decides what to ask. The platform handles rendering, delivery, and collection. Agents generate surface specs from their understanding of what data is missing, or select from workspace-level form templates that pre-define field layouts and prefill rules for common workflows.

## Mid-Call Surface Tools

Agents have direct access to surfaces during live interactions (voice or text) through four context graph tools. This means an agent can identify missing data during a conversation, create a form, and text the patient a link - all while still on the call or within a text session.

| Tool                     | What It Does                                                                                                                                                                                                                  |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Create surface**       | Agent specifies the entity, title, and fields it needs. Returns a signed URL for patient delivery.                                                                                                                            |
| **Deliver surface**      | Records that the surface was sent to the patient (via SMS or read aloud). Triggers a lifecycle event. Surfaces can be re-delivered if the patient has not yet completed them - useful when a patient loses the original link. |
| **Check status**         | Agent polls whether the patient has opened, partially filled, or completed the surface. Useful for real-time follow-up during the call.                                                                                       |
| **List entity surfaces** | Shows existing surfaces for the entity so the agent avoids sending duplicates. Filterable by status.                                                                                                                          |

A typical mid-call flow: the agent notices the patient's insurance card is missing, creates a two-field surface (front photo + back photo), texts the link to the patient's phone, and checks back moments later to see if the patient has opened it. If completed before the call ends, the agent confirms receipt. If not, the surface stays active and the patient can complete it later.

### Real-Time Surface Observation

The agent does not need to poll for completion. When a patient submits a surface during an active call, the agent is notified automatically and can acknowledge the submission in the conversation. For example: "I can see you just uploaded your insurance card - thank you, let me pull that up."

This works through the same real-time event stream that powers the dashboard. The agent subscribes to workspace events during the interaction and filters for surface submissions matching surfaces it created. The notification is injected into the conversation as guidance, so the agent responds naturally without interrupting the current flow.

These tools are available as context graph actions within any context graph state. Authentication uses the call's session credentials, so surface operations are automatically scoped to the correct workspace.

### Surface Templates and Wait Conditions

Context graph states can also declare surfaces and waiting behavior directly in their definition, without the agent needing to call tools:

* **Surface templates** - A state can include a surface spec template. When the agent enters that state, the platform automatically creates the surface using the template's fields and entity context. This is useful for deterministic workflows where the form is always the same (e.g., "collect insurance card" always needs front and back photo fields).
* **Wait conditions** - A state can declare that the agent should pause and wait for the surface to be submitted before continuing. While waiting, the agent stays in the current state and makes empathetic small-talk rather than advancing through the conversation. The wait clears automatically when the patient submits the form or when a reviewer approves the submission.

These extensions work across both voice and SMS channels. For more details, see [Action State Extensions](/agent/context-graphs.md).

### Form Templates

Workspace administrators can define form templates that standardize common data collection workflows. A template pre-defines the field layout, section structure, and prefill rules - mapping entity state fields to form fields so patients see their known information pre-populated. Templates also support patient-type routing, delivering different field sets based on the entity's characteristics.

Agents access templates through two tools: one to list available templates for the workspace, and one to create a surface from a template with a specific entity. The template system handles field prefill from the entity's world model state, reducing the number of fields the patient needs to fill manually.

Templates are useful when the same form is used repeatedly (intake forms, insurance collection, consent workflows). For one-off or dynamic data collection, agents still generate surface specs directly.

### Calendar Booking

Surfaces can include an appointment booking step where patients select from available time slots and confirm a booking directly within the form. The booking flow queries provider availability, presents a calendar with open slots, and creates the appointment on confirmation - all within the surface, without a separate scheduling system.

This is particularly useful for post-call follow-up surfaces where the agent identified that the patient needs to schedule a visit. The surface collects any missing data (insurance, demographics) and offers appointment booking in a single flow.

## Intake Upload Links

Independent of surfaces, operators can generate shareable upload links that let patients or staff upload files directly without API access. An upload link is a secure, time-limited URL that renders a drag-and-drop upload page. No login, no app, no engineering support required.

| Setting           | Default                                      | What It Controls                                            |
| ----------------- | -------------------------------------------- | ----------------------------------------------------------- |
| **Expiry**        | 7 days                                       | How long the link stays active (configurable up to 30 days) |
| **File types**    | PDF, Word, PowerPoint, images                | Which content types are accepted                            |
| **Size limit**    | 100 MB                                       | Maximum file size per upload                                |
| **Rate limiting** | 30 page loads / 10 uploads per minute per IP | Abuse prevention                                            |

Links are revocable - an operator can deactivate a link at any time, and any subsequent access returns an appropriate status. Each link's upload history is queryable, so operators can see what was uploaded and when.

Upload links are useful for collecting documents outside of a conversation flow - referral letters, prior records, lab results - where a full surface form would be unnecessary overhead. The uploaded files flow into the same intake pipeline as surface-submitted files, including [content validation and duplicate detection](#security).

## Automated Gap Detection

Beyond mid-call surfaces, the platform can proactively identify missing data and create surfaces automatically. A background scanner periodically examines entity state across the workspace, compares it against configurable requirements, and creates surfaces for any gaps it finds.

For example: a workspace can define that every patient with an upcoming appointment must have insurance information, a pharmacy on file, and an emergency contact. The scanner checks all patient entities against these requirements, and for any patient with missing data, creates a surface and delivers it via SMS - days before the appointment, without any human or agent action.

| Setting          | What It Controls                                                                                                                               |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| **Requirements** | Named rules defining which fields must be present for an entity type (e.g., "insurance card required for patients with upcoming appointments") |
| **Trigger**      | When to check - before upcoming appointments or after recent interactions                                                                      |
| **Channel**      | How to deliver the surface (SMS, email, etc.)                                                                                                  |
| **Cooldown**     | How long to wait before re-scanning the same entity (default 7 days, prevents notification fatigue)                                            |
| **Priority**     | Low, normal, or high - controls processing order                                                                                               |

The scanner is rule-based with no LLM involvement. It runs on the [connector runner](/data/connectors-and-ehr.md) as an additional background loop alongside the existing poll, reconciliation, and review loops. It is disabled by default and configured per workspace.

### Auto-Delivery via Text Conversations

When the gap scanner creates an SMS surface and auto-delivery is enabled, it triggers an outbound text conversation rather than sending a bare link. The same context graph-driven agent that handles voice calls conducts a multi-turn SMS exchange with the patient. The surface is delivered inline within the conversation, giving the patient context about why they are being asked and the ability to ask questions.

## Outreach Optimization

Surface analytics feed back into surface creation to prevent fatigue and improve completion rates.

**Agent-side intelligence** - Before creating a new surface during an interaction, the agent can query a patient's surface history: how many are pending, what their completion rate is, and which channel they prefer. If a patient already has three unfinished surfaces, the agent may decide to collect the data verbally instead. If a patient consistently completes SMS surfaces but ignores email, the agent uses SMS.

**Gap scanner fatigue gating** - The automated gap scanner respects per-workspace limits:

| Setting                  | Default | What It Controls                                                                             |
| ------------------------ | ------- | -------------------------------------------------------------------------------------------- |
| **Max pending surfaces** | 3       | Skip entities that already have this many unfinished surfaces                                |
| **Min completion rate**  | 0%      | Skip entities whose historical completion rate is below this threshold                       |
| **Channel optimization** | Off     | When enabled, override the default channel with each entity's historically preferred channel |

These settings prevent the common failure mode of automated outreach systems: sending more messages to patients who do not respond, which decreases engagement and increases opt-out rates.

## Channels

Surfaces reach patients through the channels they already use:

| Channel      | How It Works                                                            | Best For                                  |
| ------------ | ----------------------------------------------------------------------- | ----------------------------------------- |
| **SMS**      | Text message with a secure link                                         | Quick data collection, appointment prep   |
| **WhatsApp** | WhatsApp message with a secure link                                     | Regions where WhatsApp is primary         |
| **iMessage** | iMessage with a secure link                                             | iOS-native delivery                       |
| **Email**    | Email with a branded link via the workspace's configured email provider | Longer forms, document collection         |
| **Voice**    | IVR-style data collection during a live call                            | Simple confirmations, date/time selection |
| **Web**      | Direct link for embedding in portals                                    | Integration with existing patient portals |

The agent selects the channel based on the patient's communication preferences and the nature of the request. A photo upload goes via SMS or email, not voice. A yes/no consent confirmation can happen on the call itself.

## What Surfaces Can Collect

Twelve field types cover the range of healthcare data collection needs:

| Type              | Example Use                                 |
| ----------------- | ------------------------------------------- |
| **Text**          | Name, address, pharmacy name                |
| **Textarea**      | Symptom description, special instructions   |
| **Date**          | Date of birth, preferred appointment date   |
| **Phone**         | Contact number, emergency contact           |
| **Email**         | Patient email for follow-up                 |
| **Number**        | Age, weight, dosage amount                  |
| **Single select** | Preferred provider, insurance type          |
| **Multi select**  | Symptoms from a checklist, available days   |
| **Checkbox**      | Consent confirmation, HIPAA acknowledgment  |
| **Photo**         | Insurance card front/back, wound photo, ID  |
| **Signature**     | Digital consent signature, authorization    |
| **File**          | Referral letter, prior records, lab results |

Fields support prefilling from known data (so patients do not re-enter information the system already has), conditional display (show a field only when another field has a specific value), and PHI flagging for sensitive data handling.

## Form Intelligence

Surfaces include six layers of intelligence that reduce patient effort and improve data quality:

| Capability               | What It Does                                                                                                                                                                                                                                                                                         |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Smart formatting**     | Auto-formats SSNs, ZIP codes, and phone numbers as the patient types. Corrects common email domain typos (gmailcom to gmail.com).                                                                                                                                                                    |
| **Contextual warnings**  | Cross-references fields against each other and the patient's record. If a patient enters a medication that conflicts with an allergy listed elsewhere on the form, a warning appears immediately. Age detection from date of birth triggers minor consent flagging when relevant.                    |
| **Input correction**     | An LLM reviews field values on blur and silently corrects obvious typos and formatting errors. High-confidence corrections (clear typos) apply automatically. Lower-confidence suggestions appear as toasts the patient can accept or dismiss. Sensitive fields receive formatting corrections only. |
| **Healthcare lookups**   | Medication and allergy fields search a standardized drug database in real time. Pharmacy fields search the national provider registry. Insurance carrier fields search a curated list. Results appear as the patient types, reducing free-text entry errors.                                         |
| **OCR prefill**          | For insurance card collection, patients can take a photo with their camera. The platform extracts structured fields (member ID, group number, plan name, dates) from the image and pre-fills the form. The patient reviews and confirms before submission.                                           |
| **Abandonment recovery** | If a patient starts a form but does not finish, the agent can check which fields remain unfilled and generate a shortened follow-up surface containing only the missing fields. The patient picks up where they left off without re-entering completed data.                                         |

## Lifecycle

Each surface progresses through a tracked lifecycle:

<figure><img src="/files/QXL3YyY0kq7AObmIpOC4" alt="Surface state lifecycle: Created, Delivered, Opened, Partial, Completed, Expired"><figcaption></figcaption></figure>

| Status             | What It Means                                                                   |
| ------------------ | ------------------------------------------------------------------------------- |
| **Created**        | Spec generated by agent, stored in world model                                  |
| **Pending Review** | Awaiting review before delivery (when review workflows are configured)          |
| **Delivered**      | Sent to patient via the chosen channel                                          |
| **Opened**         | Patient opened the link                                                         |
| **Partial**        | Some fields submitted (auto-saved as patient progresses)                        |
| **Completed**      | All required fields submitted                                                   |
| **Expired**        | TTL exceeded without completion (default 7 days, configurable 1 hour to 1 year) |

## Data Flow

Surface submissions enter the world model through the same pipeline as every other data source:

* **Source**: `surface` - distinguishable from EHR, voice, or manual imports in analytics and audit trails
* **Confidence**: Initial confidence appropriate for patient-reported data - not automatically trusted at the same level as authoritative EHR data
* **Entity association**: All surface events (creation, delivery, submission) are linked to the specific entity the surface was generated for, so they appear in entity timelines and trigger entity state recomputation

When a patient submits a surface, the platform recomputes the entity's state within the same transaction. Submitted form data flows directly into the entity's demographic and clinical projections - there is no delay or background job between submission and the data being available for the next interaction.

This means surface data passes through the same [confidence gates](/data/connectors-and-ehr.md), [review queues](/data/review-queue.md), and entity resolution as data from any other source. A photo of an insurance card uploaded via a surface goes through the same verification pipeline as insurance data extracted from a phone call.

## Healthcare Examples

| Scenario                   | What the Agent Generates                                                                                          |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| **Pre-visit intake**       | After scheduling, send a surface with insurance card photo, pharmacy name, medication list, and consent signature |
| **Post-call follow-up**    | After a triage call, text a surface with symptom tracker fields and a photo upload for the affected area          |
| **Insurance verification** | During a call where insurance details are unclear, text a surface for front/back photos of the card               |
| **Consent collection**     | Before a referral, email a surface with a consent form, digital signature, and HIPAA acknowledgment               |
| **Appointment prep**       | Day before appointment, send a surface with transportation needs, interpreter request, and current medications    |

## Delivery

When a surface is ready, it can be delivered to the patient via SMS with a single API call. The delivery endpoint sends the surface URL to the patient's phone number, records a lifecycle event, and publishes a real-time notification. Email and WhatsApp delivery follow the same pattern.

### iOS Link Trust

iOS blocks clickable links in SMS messages from unknown senders. To work around this, SMS surface delivery uses a two-step process:

1. **Contact card** - A vCard attachment is sent first, prompting the patient to save the sender as a contact. The vCard includes the workspace's business name and phone number.
2. **Form link** - The surface URL is sent in a second message. Because the patient now has the sender saved as a contact, iOS renders the link as tappable.

If the contact card fails to deliver, the form link is still sent - the vCard step is best-effort. Patients on Android or other platforms receive the link normally regardless.

### Short URLs

Surface links delivered via SMS use short redirect URLs instead of the full cryptographically-signed token URL. The short URL resolves server-side to the full surface page. This keeps SMS messages compact and prevents carriers from truncating or splitting messages that contain long URLs.

### Other Delivery Methods

The agent can also read the URL aloud during a voice call for immediate access, or embed it in a follow-up message through any existing communication channel.

Real-time events (`surface.delivered`, `surface.opened`, `surface.submitted`) are published as they happen, so dashboards and agents can react to patient progress.

## Branding

Patient-facing surfaces adopt the workspace's visual identity automatically. Workspace administrators configure default branding - logo, primary color, background color, and font - through the workspace settings. When a surface renders, the platform applies these defaults so every form is consistent with the organization's brand.

Surface-level branding can override workspace defaults for specific use cases. For example, a workspace might use the standard brand for intake forms but apply partner-specific branding for co-branded outreach. The merge is field-level: surface-level values take precedence, and any unset fields fall back to the workspace default.

Branding changes are audit-logged and take effect on the next surface render - already-opened surfaces are not retroactively updated.

## Multi-Page Forms

Longer data collection needs can be split into sections, creating a step-by-step form experience. Each section groups related fields under its own title and description, so patients work through one page at a time rather than scrolling through a single long form.

The form renders sections as stepped pages with Next and Back navigation buttons. A progress bar at the top shows the current step and overall completion. Each step validates its fields before allowing the patient to advance - required fields, format checks, and conditional logic are enforced per step, so patients catch errors immediately rather than at the end.

Sections are useful for complex intake workflows - for example, separating demographics, insurance information, and consent into distinct steps. Auto-save works across steps, so patients can complete part of the form, leave, and return to where they left off. Forms with a single section or no sections render as a single page, maintaining backward compatibility.

## Patient Experience

Patients access surfaces through a secure link - no login, no app download, no account creation. The link contains a cryptographically signed token that grants access to that specific surface only.

The surface renders as a mobile-first page that works on any device. All twelve field types render natively - photo uploads use the device camera, signatures use touch input, date pickers use the platform default. Fields auto-save as the patient progresses, so no data is lost if they close the browser and return later.

File and document uploads use a dedicated upload page with drag-and-drop support, per-file progress indicators, and streaming upload for large files. The upload page validates files client-side before uploading (file type, size limits) and server-side after upload (content validation, duplicate detection).

### Inline Validation and Accessibility

Forms validate fields inline as the patient fills them out - errors appear immediately when a field loses focus, not after the patient submits the entire form. When submission or step advancement fails validation, the page scrolls to and focuses the first error field automatically.

Long text fields display a live character count that changes color as the limit approaches. The browser prompts before closing a tab with unsaved form progress. All validation messages are linked to their fields via `aria-describedby` for screen reader compatibility.

Rate limiting protects patient-facing endpoints against abuse without affecting the patient experience.

## Security

* **Token-based access** - Patients access surfaces via HMAC-signed URL tokens. No login required. Each token grants access to one specific surface only.
* **Scoped access** - Dedicated `surfaces:read` and `surfaces:write` permissions control who can generate and view surfaces
* **Sensitive fields** - Fields flagged as sensitive receive additional PHI handling throughout the pipeline
* **File content validation** - File and photo uploads are validated by inspecting the file's actual content type (magic bytes), not just the declared MIME type. Files whose content does not match the allowed types are rejected before storage. This prevents disguised file uploads regardless of what the client declares.
* **Duplicate detection** - After a file uploads successfully, the platform checks for existing files with the same content hash in the workspace. Duplicates are flagged in the response but never blocked - healthcare workflows legitimately re-upload the same document, so the platform informs rather than prevents.
* **Expiration** - Surfaces automatically expire after their configured TTL, limiting the exposure window
* **Entity-scoped** - Each surface is associated with a specific entity, maintaining workspace-level data isolation
* **Rate limiting** - Patient-facing endpoints are rate-limited per IP to prevent abuse
* **Audit trail** - Surface creation, delivery, and submission are recorded in the [unified audit trail](/safety-and-compliance/compliance.md#unified-audit-trail)

{% hint style="info" %}
**Developer Guide** - For model schemas, field definitions, and API details, see the [Surfaces](https://docs.amigo.ai/developer-guide/platform-api/platform-api/surfaces) page in the developer guide.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.amigo.ai/channels/surfaces.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
