> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Call an agent from your service

> Give your backend a service credential, let it call an agent through jaccard.toml, and start sessions over HTTP, alone or on behalf of your own users.

## Before you start

* The agent is deployed and exposed, which is the default.
* Your service has a service credential, and the agent lists it in `callers`: see [Access](/docs/operate/access.md#give-a-service-a-credential).

**1. Get a token**

Your service exchanges its client id and secret for a token at the token URL:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
TOKEN=$(curl -s -X POST "$ACME_WEB_TOKEN_URL" \
  -H "Content-Type: application/json" \
  -d "{\"client_id\":\"$ACME_WEB_CLIENT_ID\",\"client_secret\":\"$ACME_WEB_CLIENT_SECRET\",\"grant_type\":\"client_credentials\"}" \
  | jq -r .access_token)
```

The token lasts an hour. Reuse it until shortly before it expires, then get another.

**2. Start a session**

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
SESSION_ID=$(curl -s -X POST https://my-agent-acme.jaccard.app/eve/v1/session \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"message": "Where is order 1042?"}' \
  | jq -r .sessionId)
```

The agent answers `202` at once and works on the message in the background. The body holds the session id, and `deliveryId` for the message:

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{"ok": true, "sessionId": "wrun_01M6RNT3PHQFHVB2B0HFZHZJQR", "deliveryId": "..."}
```

**3. Read the reply**

The session's stream sends one JSON line per change while the agent works. A line `{at, facts}` holds the events one change produced, in its `facts` array; a line `{progress}` holds one piece of streamed text. This prints the finished reply:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -sN "https://my-agent-acme.jaccard.app/eve/v1/session/$SESSION_ID/stream" \
  -H "Authorization: Bearer $TOKEN" \
  | jq -r '.facts[]? | select(.type == "content.completed" and .data.kind == "text" and .data.phase == "reply") | .data.value'
```

The events you'll use:

| Event | `data` |
| - | - |
| `content.delta` (in `progress`) | `delta`, the next piece of the part `partId`, for showing the reply as it's written |
| `content.completed` | `value`, one finished part. The reply is the part with `kind` `"text"` and `phase` `"reply"`; `"narration"` is text the agent wrote on the way, such as before a tool call. |
| `call.requested`, `call.settled` | The agent called a tool (named in `capability`) and the call ended, with an `outcome` |
| `turn.settled` | The agent has finished with this message. Stop reading here. `outcome` is `"completed"`, `"failed"` or `"cancelled"`. |

A `turn.settled` with `outcome` `"failed"` says why in `error.code` and `error.message`, such as `MODEL_CALL_FAILED` when the model provider refuses the agent's key. One with `"cancelled"` was [stopped](#stop-a-reply). Other events and fields can appear as eve adds them: skip the ones you don't use.

The stream starts from the session's first line every time you open it, so it replays earlier replies too. To read only what's new, pass how many `facts` and `progress` lines you've already read: `/stream?startIndex=16`. Don't count the `{"$eve": ...}` lines, such as heartbeats. The stream stays open after `turn.settled`, and closes after a minute with `{"$eve":"stream.lease-ended"}`: open it again from your count to keep reading. Add `follow=0` to get the lines so far and close at once.

**4. Send the next message**

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -s -X POST "https://my-agent-acme.jaccard.app/eve/v1/session/$SESSION_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"message": "Can you change the delivery address?"}'
```

It answers `202` like the first message. Read the reply from the same stream, with `startIndex` past what you've already read.

## Call it from TypeScript

eve's client does the same steps for you, reads the stream, and gets a new token when the old one expires. Install eve at the version in the agent's `package.json`, such as `npm install eve@1.0.0`. The example reads the credential from the same variables as the `curl` steps, and the agent's URL from `ACME_AGENT_URL`:

```ts agent.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { Client } from "eve/client";

const AGENT_URL = process.env.ACME_AGENT_URL!;

let token: { value: string; expiresAt: number } | undefined;

// Reuse the token until a minute before it expires.
export async function serviceToken(): Promise<string> {
  if (token && token.expiresAt > Date.now() + 60_000) return token.value;
  const res = await fetch(process.env.ACME_WEB_TOKEN_URL!, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      client_id: process.env.ACME_WEB_CLIENT_ID,
      client_secret: process.env.ACME_WEB_CLIENT_SECRET,
      grant_type: "client_credentials",
    }),
  });
  if (!res.ok) throw new Error(`token request failed: ${res.status}`);
  const data = await res.json();
  token = { value: data.access_token, expiresAt: Date.now() + data.expires_in * 1000 };
  return token.value;
}

export const agent = new Client({ baseUrl: AGENT_URL, auth: { bearer: serviceToken } });
```

```ts ask.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { agent } from "./agent";

const { session, delivery } = await agent.sessions.create({ message: "Where is order 1042?" });
console.log((await delivery.result()).reply);

const next = await session.send("Can you change the delivery address?");
console.log((await next.result()).reply);
```

`result()` waits for the reply and returns it as `reply`, with `status` `"completed"`, `"failed"` (and an `error`), `"cancelled"` or `"awaiting-input"`.

## Long-running work

A reply can take hours. Instead of holding the stream open, store the session id and check back later:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -s "https://my-agent-acme.jaccard.app/eve/v1/session/$SESSION_ID/stream?follow=0" \
  -H "Authorization: Bearer $TOKEN"
```

`follow=0` returns the events so far and closes. The reply is ready once they include `turn.settled`. To read only what's new since your last check, add `startIndex` with the number of `facts` and `progress` lines you've already read. Without it, an earlier turn's `turn.settled` matches too.

## Stop a reply

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -s -X POST "https://my-agent-acme.jaccard.app/eve/v1/session/$SESSION_ID/cancel" \
  -H "Authorization: Bearer $TOKEN"
```

The agent stops the turn it's working on, and the stream sends `turn.settled` with `outcome` `"cancelled"`. The session takes the next message as usual.

## Call on behalf of your users

Let your service forward users, as in [Access](/docs/operate/access.md#let-a-service-call-on-behalf-of-its-users). Then send the user as `forwardedPrincipal` with every message, the first and each one after:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -s -X POST https://my-agent-acme.jaccard.app/eve/v1/session \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Where is order 1042?",
    "forwardedPrincipal": {
      "current": {
        "principalId": "customer-1842",
        "principalType": "user",
        "authenticator": "acme-web",
        "issuer": "https://acme.example",
        "attributes": { "tenant": "acme", "email": "sam@example.com" }
      }
    }
  }'
```

From TypeScript, use `fetch` for these calls, since eve's client doesn't send `forwardedPrincipal`:

```ts forward.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { serviceToken } from "./agent";

const AGENT_URL = process.env.ACME_AGENT_URL!;

// eve's client doesn't send forwardedPrincipal, so call the session route directly.
export async function askAs(userId: string, message: string, sessionId?: string) {
  const res = await fetch(`${AGENT_URL}/eve/v1/session${sessionId ? `/${sessionId}` : ""}`, {
    method: "POST",
    headers: { authorization: `Bearer ${await serviceToken()}`, "content-type": "application/json" },
    body: JSON.stringify({
      message,
      forwardedPrincipal: {
        current: {
          principalId: userId,
          principalType: "user",
          authenticator: "acme-web",
          issuer: "https://acme.example",
          attributes: { tenant: process.env.ACME_ORGANIZATION },
        },
      },
    }),
  });
  if (!res.ok) throw new Error(`agent refused: ${res.status} ${await res.text()}`);
  return (await res.json()).sessionId as string;
}

const sessionId = await askAs("customer-1842", "Where is order 1042?");
```

Read the reply from the session's stream, as above. `principalId` is the user's id in your service. `principalType` must be `user`, and the `tenant` attribute must be the agent's organization. Inside the agent, the caller is now that user, with an `eve:forwarded-by` attribute naming your service.

## Troubleshooting

| What you see | What it means | What to do |
| - | - | - |
| `401` | The agent doesn't list your service in `callers`, or the token expired. | Check the subject in `jaccard.toml` and redeploy, or get a new token. |
| `403` "This deployment does not accept a forwarded principal." | The channel file has no `trustedForwarders`. | Add `jaccardForwarders()` as in [Access](/docs/operate/access.md#let-a-service-call-on-behalf-of-its-users), then deploy. |
| `403` "Caller is not authorized to assert a forwarded principal." | Your service isn't in `forwarders`, or the user's `tenant` isn't the agent's organization. | Add it to `forwarders`, or fix the `tenant` attribute. |
| `409` "The session is no longer active." | The session has ended, or the id is wrong. | Start a new session. |
| `400` with a `forwardedPrincipal` | The record has a field the agent doesn't accept, such as a token. | Send only the fields shown above. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.