# Customer service: the support desk

The support desk is the first worked example of a domain harness: it has exactly the parts
described in [What a domain harness is made of](index.md#what-a-domain-harness-is-made-of),
and nothing more. Here is each part, as this harness fills it:

| Part | In the support desk |
|---|---|
| Plan | `SupportRun`, a workflow of three stages: triage, answer, escalate |
| Tools and policy | two routing tools, `search_knowledge` and `open_ticket`; a person approves every ticket |
| Ports | `Knowledge` (the knowledge base) and `Tickets` (the ticket system) |
| Brief and evaluation | a customer and their question; a good run ends answered or escalated |
| Launcher | runs it on a Governor and passes the approver's answer in |

**What you will learn:** how this small harness answers a customer from a knowledge base,
or hands them to a person after someone approves it. You will build it over two in-memory
ports, run one case of each kind and grade both.

**Read first:** the [domains overview](index.md), which explains what a harness, a port and
the `Launcher` are; [Workflows](../concepts/workflows.md) (a plan whose stages host other
actors), [the reference agent](../concepts/reference-agent.md) and
[Humans and interruption](../concepts/human-in-the-loop.md).

**Time:** about 15 minutes.

`service/support_desk` (module `gvn_domains.service.support`) is the smallest harness in the
package and the one the others were modelled on. Read it first.

## The problem

A customer writes in with a question. Most questions are answered by an article in the
knowledge base; some (a complaint, a refund) need a person. A model can tell the two apart
and write the answer, but it must never open a ticket on its own, never open one for the
wrong customer, and never open two for one case.

## The harness at a glance

A run is a `SupportRun` [workflow](../concepts/workflows.md). It moves through these states:

- `idle`: the run exists but has not started;
- `triaging`: an agent decides whether the knowledge base can answer;
- `answering`: an agent searches the knowledge base and answers;
- `escalating`: an agent writes a hand-off note and asks to open a ticket;
- `resolved`, `escalated` or `failed`: the run is over.

Each of the three working stages hosts one [reference agent](../concepts/reference-agent.md).
Here is the same plan as gvn renders it from the code: first as a transition table (one row
per state: the work it asks for, its **output**, then where each input leads; `>` marks the
initial state, `*` a final state), then as a diagram, where "emits" names each state's
output. A docs test renders both
again and fails if this page drifts from the harness.

```text
   state       output     transitions
   answering   answer     answer_failed -> failed, answered -> resolved
*  escalated   escalated  -
   escalating  escalate   escalation_failed -> failed, not_ticketed -> failed, ticketed -> escalated
*  failed      failed     -
>  idle        idle       started -> triaging
*  resolved    resolved   -
   triaging    triage     answerable -> answering, needs_human -> escalating, triage_failed -> failed
otherwise: stay
```

```mermaid
stateDiagram-v2
    answering : emits answer
    escalated : emits escalated
    escalating : emits escalate
    failed : emits failed
    idle : emits idle
    resolved : emits resolved
    triaging : emits triage
    [*] --> idle
    answering --> failed : answer_failed
    answering --> resolved : answered
    escalating --> failed : escalation_failed
    escalating --> failed : not_ticketed
    escalating --> escalated : ticketed
    idle --> triaging : started
    triaging --> answering : answerable
    triaging --> escalating : needs_human
    triaging --> failed : triage_failed
    escalated --> [*]
    failed --> [*]
    resolved --> [*]
    note right of idle
        otherwise: stay
    end note
```

"otherwise: stay" means any input a state does not list leaves it where it is: the machine
is total, so no input is ever unhandled (see [Machines](../concepts/machines.md)).

## Walking through a run

The steps below follow a run in the order it happens. Each code block runs, in order, as
part of the docs tests; together they form one program.

### 1. The outside world: two ports

A harness never talks to a real system directly. It declares **ports**: small abstract
classes for what it needs from the world, which you implement. The support desk needs two:

| Port | Method | Used by the tool |
|---|---|---|
| `Knowledge` | `search(query)`: a list of `{"title", "text"}` articles, best first | `search_knowledge` |
| `Tickets` | `open(customer, summary, key)`: a ticket id; one ticket per key | `open_ticket` |

Here are two in-memory implementations. `TicketBook` remembers every ticket by its `key`, so
asking twice with the same key opens one ticket (step 5 explains why that matters).

```python
from gvn_domains.service.support import Knowledge, Tickets


class Articles(Knowledge):
    async def search(self, query: str) -> list[dict[str, str]]:
        return [{"title": "Resetting your password", "text": "Use the 'Forgot password' link."}]


class TicketBook(Tickets):
    def __init__(self) -> None:
        self._opened = {}  # key -> (ticket id, customer, summary)

    async def open(self, customer: str, summary: str, key: str) -> str:
        if key not in self._opened:
            self._opened[key] = (f"T-{len(self._opened) + 1}", customer, summary)
        return self._opened[key][0]

    def opened(self) -> list[tuple[str, str, str]]:
        return list(self._opened.values())
```

### 2. Building the harness from the catalog

The [catalog](index.md#the-catalog) builds a harness by path from your ports. `Ports.of`
files each object under the port class it implements. The brief, the data a run starts
with, is a record with two non-blank text fields:

```python
from gvn_domains.catalog import Ports
from gvn_domains.directory import catalog

tickets = TicketBook()
desk = catalog().harness(path="service/support_desk", ports=Ports.of(Articles(), tickets))
print(desk.name())
for identity in desk.toolbox().identities():
    print(identity)
```

```text
support_desk
gvn_domains.service.support.open_ticket
gvn_domains.service.support.route_to_answer
gvn_domains.service.support.route_to_human
gvn_domains.service.support.search_knowledge
```

The toolbox holds every tool any of the desk's agents may call, listed by
[identity](../concepts/tools.md#two-names-the-short-name-and-the-identity): the module that
defines the tool, a dot and the short name the model sees. The module also names each tool
with a constant built without its port (`SEARCH_KNOWLEDGE`, `OPEN_TICKET`, and the
`ROUTING` pair `ROUTE_TO_ANSWER`, `ROUTE_TO_HUMAN`); the plan, the policy, the judges and the
evaluation refer to the tools through those constants, and the plan declares all four
(`Plan(..., tools=TOOLS)`), so the Governor checks this toolbox against them before the run
starts (see [how a harness names its tools](index.md#how-a-harness-names-its-tools)). Each
agent is offered only its own stage's tools, and refuses any other.

### 3. A model to play the agents

In production a real model plays each agent. Here a `FunctionModel` does: a plain function
that receives the model request (the agent's instructions and messages) and returns a
reply. This one reads which agent it is from the instructions, makes one tool call, and
after the tool result says "Done.":

```python
from gvn.harness.messages import TOOL, Message, ToolCall
from gvn.harness.ports import Exchange, Reply
from gvn.testing.fakes import FunctionModel


def desk_model(exchange: Exchange) -> Reply:
    """Plays every agent of the desk: one tool call, then one sentence."""
    if any(message.role() == TOOL for message in exchange.messages()):
        return Reply(message=Message.assistant(text="Done."))
    role = exchange.instructions()
    question = exchange.messages()[0].text()
    if role.startswith("You triage"):
        tool = "route_to_human" if "refund" in question else "route_to_answer"
        call = ToolCall(call_id="c1", name=tool, arguments={"reason": "as read"})
    elif role.startswith("You answer"):
        call = ToolCall(call_id="c1", name="search_knowledge", arguments={"query": "password"})
    else:
        call = ToolCall(call_id="c1", name="open_ticket", arguments={"summary": "Customer wants a refund."})
    return Reply(message=Message.assistant(text="", calls=[call]))


model = FunctionModel(respond=desk_model)
```

Nothing has run yet: this only defines how the fake model answers. The names it uses are the
shapes a model's conversation is made of, as in the
[tutorials](../tutorials/first-agent.md): the `exchange` is what the agent sends the model
(its instructions and messages so far); a `Message` with the role `TOOL` carries a tool's
result back; a `ToolCall` is one call the model asks for, naming the tool by the short name
the model was shown; a `Reply` wraps the model's answer.

### 4. Starting a run, and triage

The [`Launcher`](index.md#the-launcher) wires the harness, the model, a journal, an output
and a clock into one [Governor](../concepts/governor.md). `start` begins a run and drives it
until it finishes or has to wait for someone. Here the journal, output and clock are the
in-memory fakes from `gvn.testing.fakes`: `MemoryJournal` keeps the record of events in
memory, `RecordingOutput` collects what would be shown live, and `ManualClock` is a clock
that moves only when told to.

```python
import asyncio

from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput
from gvn_domains.launcher import Launcher

launcher = Launcher(
    harness=desk,
    model=model,
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)

password_brief = {"customer": "Ada", "question": "How do I reset my password?"}
answered = asyncio.run(launcher.start(run_id="case-1", brief=password_brief))
print(answered.status(), answered.outcome().state())
```

```text
finished State('resolved')
```

Here is what happened. The run went from `idle` to `triaging`, whose agent may call only
`route_to_answer` or `route_to_human`. The stage then ends through a **judge**, a
[Decision](../concepts/decisions.md) that reads what the agent *did* (the tool calls in its
outcome), not what it said:

| Stage | Agent's tools | How it ends |
|---|---|---|
| `triaging` | `route_to_answer`, `route_to_human` | a judge: `answerable` when the agent's last successful routing call was `route_to_answer`; `needs_human` for `route_to_human` or no routing call at all (when in doubt, escalate); `triage_failed` when the agent failed |
| `answering` | `search_knowledge` | routes: `completed` is `answered`, `failed` is `answer_failed` |
| `escalating` | `open_ticket` | a judge: `ticketed` when `open_ticket` succeeded; `not_ticketed` when it did not (a person denied it); `escalation_failed` when the agent failed |

Ada's question was routed to `answering`, whose agent searched the knowledge base and
answered, and the run ended `resolved`. `interrupted` and `resumed` are relayed to whichever
agent is active (see [Humans and interruption](../concepts/human-in-the-loop.md)).

### 5. Where a person is asked

Grace asks for a refund. Triage routes her to `escalating`, whose agent asks to call
`open_ticket`. Before any tool runs, the harness's **policy** gives a verdict on each call:
the two routing tools and `search_knowledge` are cleared, `open_ticket` needs a person's
approval, and anything else is forbidden. A person is asked only about the calls that need
one ([one verdict per call](../concepts/reference-agent.md#one-verdict-per-call)). So the run stops and waits:

```python
refund_brief = {"customer": "Grace", "question": "I want a refund."}
waiting = asyncio.run(launcher.start(run_id="case-2", brief=refund_brief))
request = waiting.pending()[0]
print(waiting.status(), request.origin())
print(request.payload()["context"])
```

```text
waiting case-2/escalating.1
{'customer': 'Grace', 'question': 'I want a refund.'}
```

The request comes from the agent at `case-2/escalating.1` (the first visit of the
`escalating` stage). It carries the calls, the agent's explanation and the run context, so
the approver sees what they are approving. A waiting run costs no process: the journal holds
it, and the answer can come days later.

Now a person approves:

```python
escalated = asyncio.run(launcher.approve(run_id="case-2", request=request))
print(escalated.outcome().state())
print(tickets.opened())
```

```text
State('escalated')
[('T-1', 'Grace', 'Customer wants a refund.')]
```

The ticket is for Grace even though the model's call named only a summary. With
`launcher.deny(...)` no ticket would exist: the stage would end `not_ticketed` and the run
`failed`.

### 6. How it ends, and grading the run

Every harness carries an **evaluation**: what a good run looks like, checked against the
run's recorded [trace](../reference/glossary.md#trace) (the events of the run, read back from
its journal). The support desk's says the run finishes `resolved` or `escalated`,
nothing is rejected, no ticket is opened without a person's approval
(`Gated([OPEN_TICKET])`), and it takes at most 25 events. A run that ends `failed`
because a person declined the ticket is flagged.

```python
for run in ("case-1", "case-2"):
    grade = asyncio.run(launcher.grade(run_id=run))
    print(run, grade.passed())
```

```text
case-1 True
case-2 True
```

With a real model you would replace `FunctionModel(respond=desk_model)` with an
[adapter](../guides/vendors.md), and the two ports with your knowledge base and ticket
system. The harness itself does not change.

## What is enforced before any effect

- **The ticket's customer comes from the context.** Every agent is built with the brief as its
  [run context](../concepts/run-context.md), which the model cannot change. The harness also
  includes the customer and question in the prompt. `open_ticket` takes only a summary and
  reads the customer for the ticket from `invocation.context()`. The policy and the tool
  both refuse `open_ticket` if the context names no customer.
- **A person approves every ticket.** The approval request carries the calls, the agent's
  explanation and the run context.
- **A ticket is opened once.** After a crash, work in flight runs again. `open_ticket`
  passes the call's [idempotency key](../concepts/run-context.md) to `Tickets.open`, which
  must open one ticket per key.

## What this harness uses from gvn

The support desk is the smallest harness and the pattern the others follow: a workflow
whose stages host reference agents, judges that decide from what the agents did, the brief
as every agent's run context, and a policy and tools that enforce the same rules before any
effect. It relies on three parts of gvn: the run context, stable idempotency keys, and
per-call statuses in agent outcomes (see the [domains overview](index.md#what-the-harnesses-use-from-gvn)).

## Running it safely

Opening a ticket once per key is the port's job: an implementation of `open_ticket` must
use `key` to open one ticket per key, so that a call delivered again after a crash does not
open a second one.

The harness's own tests are in `packages/gvn-domains/tests/test_dom_service_support.py`.

## Recap

- A harness is a workflow plus ports, tools, a policy and an evaluation.
- Stages end through judges that read what an agent did, so a model's wording never routes.
- The policy stops the run before `open_ticket` runs; the run waits for a person at no cost.
- Trusted data (the customer) comes from the run context, never from the model.

**Next:** [Research](research.md), where a stage repeats in bounded rounds and several
agents run side by side.
