Poppy LabTry the live demoLive demo

Build a native client

An app signs in to an agent account with a passkey, keeps a session of its own, and works in the same conversations as the playground. This guide follows an iPhone app; any platform with passkeys and a browser sheet of its own works the same way.

Every request goes to https://poppylab.dev/api/v1 and sends no Origin header: that is what makes it an app's and not a browser's. The examples are requests and answers in the shapes the API gives, shortened where they show …. The reference has every operation and type.

Before you start

The system offers an app passkeys only for a domain that vouches for it. The app needs the Associated Domains entitlement webcredentials:poppylab.dev, and the site must serve /.well-known/apple-app-site-association listing the app as <Team ID>.<bundle ID>. poppylab.dev serves it for the apps set in the site's configuration (APPLE_APP_IDS); another app has to be added there before it can make or use a passkey for poppylab.dev. The requests below are the same for any app it lists. While you develop, add ?mode=developer to the entitlement (webcredentials:poppylab.dev?mode=developer) and turn on Associated Domains Development on the device, so iOS reads the file from the site rather than Apple's cache.

The relying party is poppylab.dev. The clientDataJSON an iOS app sends has the origin https://poppylab.dev, which the API expects.

Create an account

Ask for the options of a new passkey. label is an optional name the person chooses for the account; the account has no email, password or name.

POST /api/v1/accounts/options
Content-Type: application/json

{
  "label": "Home"
}
HTTP/1.1 200
Content-Type: application/json

{
  "ceremony": "DMz80NY0PzjiwanwGamYKA",
  "options": {
    "challenge": "U3l0bkxYSjE4cU9jT2xqVDFPaTNTMUpRbXM2RTdVdU04andPa3d1cC1kbw",
    "rp": {
      "name": "poppylab.dev",
      "id": "poppylab.dev"
    },
    "user": {
      "id": "c0rOAOzr0jtlGGeGpluvjQ",
      "name": "Home",
      "displayName": "Home"
    },
    "pubKeyCredParams": [
      {
        "alg": -7,
        "type": "public-key"
      },
      {
        "alg": -257,
        "type": "public-key"
      }
    ],
    "timeout": 300000,
    "attestation": "none",
    "excludeCredentials": [],
    "authenticatorSelection": {
      "residentKey": "required",
      "userVerification": "required",
      "requireResidentKey": true
    },
    "extensions": {
      "credProps": true
    },
    "hints": []
  }
}

accountOptions in the reference

Pass options.challenge and options.user.id, both base64url, to the platform provider, with user verification required:

let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(
  relyingPartyIdentifier: "poppylab.dev")
let request = provider.createCredentialRegistrationRequest(
  challenge: challenge, name: "Home", userID: userID)
request.userVerificationPreference = .required

Send the result as a RegistrationResponseJSON (id, rawId, type, response.clientDataJSON, response.attestationObject, response.transports) with the ceremony, within five minutes and once. device names the device in its own words. The answer is the account and the device's tokens: keep them in the Keychain.

POST /api/v1/accounts
Content-Type: application/json

{
  "ceremony": "DMz80NY0PzjiwanwGamYKA",
  "credential": {
    "id": "dwA7sfRJQDk5IN4eJgtesA",
    "rawId": "dwA7sfRJQDk5IN4eJgtesA",
    "type": "public-key",
    "response": {
      "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoi…",
      "attestationObject": "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViU…",
      "transports": [
        "internal",
        "hybrid"
      ]
    },
    "clientExtensionResults": {}
  },
  "device": "iPhone"
}
HTTP/1.1 201
Content-Type: application/json

{
  "account": {
    "id": "c0rOAOzr0jtlGGeGpluvjQ",
    "label": "Home",
    "created": 1795772788698,
    "passkeys": [
      {
        "id": "dwA7sfRJQDk5IN4eJgtesA",
        "name": "iPhone",
        "created": 1795772788698,
        "synced": true
      }
    ],
    "channels": [],
    "session": "nsDf4rxOjzq3NFKVJdG2AQ"
  },
  "tokens": {
    "session": "nsDf4rxOjzq3NFKVJdG2AQ",
    "accessToken": "poppy_at.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.KNGQT617OSA3c-i9As0a4HxastNzn0rb3CX977GSDSo",
    "accessTokenExpiresAt": 1795773688698,
    "refreshToken": "poppy_rt.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.65P8qaJ8Pl2zhzDf8eD1JXRCBGpxYiJhI3aokMn9hhE",
    "refreshTokenExpiresAt": 1798364788698
  }
}

createAccount in the reference

Sign in on another device

Ask for sign-in options and pass the challenge to createCredentialAssertionRequest(challenge:) with no allowed credentials, so the system offers every passkey for the site and no username is needed.

POST /api/v1/sessions/options
Content-Type: application/json

{}
HTTP/1.1 200
Content-Type: application/json

{
  "ceremony": "wCo3tWEijhywKSPwr2Ko-g",
  "options": {
    "rpId": "poppylab.dev",
    "challenge": "SEROTUthMEJBYzQ0Qy10aWNhc2Z5OFBkMElHcjB5VGpBOHVaaGtwZlozZw",
    "timeout": 300000,
    "userVerification": "required"
  }
}

signInOptions in the reference

Send the AuthenticationResponseJSON (response.clientDataJSON, response.authenticatorData, response.signature, response.userHandle). The user handle is the account's ID. An answer that proves no account is refused with passkey_not_verified, whatever the reason.

POST /api/v1/sessions
Content-Type: application/json

{
  "ceremony": "wCo3tWEijhywKSPwr2Ko-g",
  "credential": {
    "id": "dwA7sfRJQDk5IN4eJgtesA",
    "rawId": "dwA7sfRJQDk5IN4eJgtesA",
    "type": "public-key",
    "response": {
      "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoi…",
      "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAAAA",
      "signature": "MEUCIQDMwoQt0_I1bv5nZsegi8Rr5lxSIXVLj5vKbUN5x3Du_QIg…",
      "userHandle": "c0rOAOzr0jtlGGeGpluvjQ"
    },
    "clientExtensionResults": {}
  },
  "device": "iPad"
}
HTTP/1.1 201
Content-Type: application/json

{
  "account": {
    "id": "c0rOAOzr0jtlGGeGpluvjQ",
    "label": "Home",
    "created": 1795772788698,
    "passkeys": [
      {
        "id": "dwA7sfRJQDk5IN4eJgtesA",
        "name": "iPhone",
        "created": 1795772788698,
        "synced": true
      }
    ],
    "channels": [],
    "session": "nsDf4rxOjzq3NFKVJdG2AQ"
  },
  "tokens": {
    "session": "nsDf4rxOjzq3NFKVJdG2AQ",
    "accessToken": "poppy_at.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.KNGQT617OSA3c-i9As0a4HxastNzn0rb3CX977GSDSo",
    "accessTokenExpiresAt": 1795773688698,
    "refreshToken": "poppy_rt.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.65P8qaJ8Pl2zhzDf8eD1JXRCBGpxYiJhI3aokMn9hhE",
    "refreshTokenExpiresAt": 1798364788698
  }
}

signIn in the reference

Keep the session

Send Authorization: Bearer with the access token on every request. It lasts 15 minutes. Before accessTokenExpiresAt, or when a request is refused with invalid_token, exchange the refresh token for a new pair and keep both. Refresh one request at a time: a refresh token works once.

POST /api/v1/sessions/refresh
Content-Type: application/json

{
  "refreshToken": "poppy_rt.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.65P8qaJ8Pl2zhzDf8eD1JXRCBGpxYiJhI3aokMn9hhE"
}
HTTP/1.1 200
Content-Type: application/json

{
  "session": "nsDf4rxOjzq3NFKVJdG2AQ",
  "accessToken": "poppy_at.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.naUO0cj7F9IBYr8d8ezzoJiKRwUtyk5VVmN5V1BHADk",
  "accessTokenExpiresAt": 1795774588698,
  "refreshToken": "poppy_rt.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.bo44NTfc5jOxs2-yDukmbRzcI2rgfPBV8j9g8y9FzRc",
  "refreshTokenExpiresAt": 1798364788698
}

refreshSession in the reference

A refresh token sent a second time ends the whole session, on this device and wherever a copy of it is. On session_revoked, sign in again with the passkey.

POST /api/v1/sessions/refresh
Content-Type: application/json

{
  "refreshToken": "poppy_rt.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.65P8qaJ8Pl2zhzDf8eD1JXRCBGpxYiJhI3aokMn9hhE"
}
HTTP/1.1 401
Content-Type: application/json

{
  "code": "session_revoked",
  "error": "This refresh token was used before, so the session was ended on every device that had it. Sign in again with your passkey."
}

refreshSession in the reference

A session unused for 30 days ends, and every session ends after a year. An account keeps at most 25: signing in on one more device ends the one used least recently.

Start a conversation

A conversation starts empty or with one Company, named by its origin, connected signed out. It belongs to the account, so the playground in a browser signed in to it shows the same one.

POST /api/v1/conversations
Authorization: Bearer poppy_at.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.KNGQT617OSA3c-i9As0a4HxastNzn0rb3CX977GSDSo
Content-Type: application/json

{
  "company": "https://food-demo.poppylab.dev"
}
HTTP/1.1 201
Content-Type: application/json

{
  "id": "hKhgaC-veINpeBH3fJQO4-ewBMbIdw9j",
  "active": true,
  "companies": [
    {
      "origin": "https://food-demo.poppylab.dev",
      "name": "Lantern Noodle Bar",
      "url": "https://food-demo.poppylab.dev/",
      "signedIn": false,
      "signingIn": false,
      "consentVersion": 0,
      "accessLost": false,
      "direct": {
        "open": false,
        "invitation": null
      }
    }
  ],
  "removed": [],
  "messages": [],
  "proposals": []
}

startConversation in the reference

Send what the person says. The answer is what the turn added, the person's line first, and the conversation as it is after it. Show each message by its from: user, agent, or company for a Company's own words, which are shown as the Company's and never as the agent's. Without a model a turn runs in demo mode, which runs the scripted examples only.

POST /api/v1/conversations/hKhgaC-veINpeBH3fJQO4-ewBMbIdw9j/messages
Authorization: Bearer poppy_at.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.KNGQT617OSA3c-i9As0a4HxastNzn0rb3CX977GSDSo
Content-Type: application/json

{
  "text": "What can you do?"
}
HTTP/1.1 200
Content-Type: application/json

{
  "conversation": "hKhgaC-veINpeBH3fJQO4-ewBMbIdw9j",
  "messages": [
    {
      "from": "user",
      "text": "What can you do?"
    },
    {
      "from": "agent",
      "text": "Demo mode runs the examples below, without a model. To ask anything in your own words, press “Use your own model”.",
      "spoken": "Demo mode runs the examples below, without a model. To ask anything in your own words, press “Use your own model”.",
      "choices": [
        {
          "label": "What’s on the menu?",
          "answer": {
            "message": "What’s on the menu?"
          }
        }
      ]
    }
  ],
  "replaced": false,
  "state": {
    "id": "hKhgaC-veINpeBH3fJQO4-ewBMbIdw9j",
    "active": true,
    "companies": [
      {
        "origin": "https://food-demo.poppylab.dev",
        "name": "Lantern Noodle Bar",
        "url": "https://food-demo.poppylab.dev/",
        "signedIn": false,
        "signingIn": false,
        "consentVersion": 0,
        "accessLost": false,
        "direct": {
          "open": false,
          "invitation": null
        }
      }
    ],
    "removed": [],
    "messages": [
      "…"
    ],
    "proposals": []
  }
}

sendMessage in the reference

A message can carry choices. Show each label as a button, and when it is pressed send its answer to answers, never the label as a message.

POST /api/v1/conversations/hKhgaC-veINpeBH3fJQO4-ewBMbIdw9j/answers
Authorization: Bearer poppy_at.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.KNGQT617OSA3c-i9As0a4HxastNzn0rb3CX977GSDSo
Content-Type: application/json

{
  "answer": {
    "message": "What’s on the menu?"
  }
}

answerChoice in the reference

Hear the answer as it is written

A model takes seconds to write a whole answer. Send Accept: text/event-stream with the message, or with an answer, and the same request answers each of the agent's sentences as soon as it is written, as a message.delta event: the message's ID, the sentence's index, its text and its spoken form. The last event is turn, with the same result the JSON answer has, in which each of the agent's messages carries as id the ID its sentences came under, or error when the turn failed after it began.

POST /api/v1/conversations/hKhgaC-veINpeBH3fJQO4-ewBMbIdw9j/messages
Authorization: Bearer poppy_at.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.KNGQT617OSA3c-i9As0a4HxastNzn0rb3CX977GSDSo
Accept: text/event-stream
Content-Type: application/json

{
  "text": "What's on the menu tonight?",
  "model": {
    "provider": "free",
    "turnstile": "0.Kx3…"
  }
}
HTTP/1.1 200
Content-Type: text/event-stream

event: message.delta
data: {"type":"message.delta","message":"q7Vb2YxkS1mR0cJtE4uWnA","index":0,"text":"Lantern Noodle Bar has shoyu ramen for $14.00 and salted edamame for $5.50 tonight. ","spoken":"Lantern Noodle Bar has shoyu ramen for 14 dollars and salted edamame for 5 dollars 50 tonight."}

event: message.delta
data: {"type":"message.delta","message":"q7Vb2YxkS1mR0cJtE4uWnA","index":1,"text":"The matcha ice cream is back too. ","spoken":"The matcha ice cream is back too."}

event: message.delta
data: {"type":"message.delta","message":"q7Vb2YxkS1mR0cJtE4uWnA","index":2,"text":"Shall I add anything to your order?\n\n","spoken":"Shall I add anything to your order?"}

event: turn
data: {"type":"turn","result":{"conversation":"hKhgaC-veINpeBH3fJQO4-ewBMbIdw9j","messages":[{"from":"user",…},{"id":"q7Vb2YxkS1mR0cJtE4uWnA","from":"agent","text":"Lantern Noodle Bar has shoyu ramen…",…}],…}}

sendMessage in the reference

A voice client says each sentence's spoken as it arrives, in order, and skips one that is empty (a table row, a link). The sentences are the whole answer, so it does not say the message's own spoken again when turn comes. Demo mode and the agent's own lines, a question about a proposal say, are there at once: they come as sentences too, all together just before turn, so one path speaks everything the agent says. A Company's own words are never sentences of the agent's: they come whole in the result, as the Company's message, to be shown or said as the Company's.

var request = URLRequest(url: messagesURL)
request.httpMethod = "POST"
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
request.httpBody = try JSONEncoder().encode(message)
let (bytes, response) = try await URLSession.shared.bytes(for: request)
// Refused before anything was said: JSON with its status, as without the header.
guard (response as? HTTPURLResponse)?.mimeType == "text/event-stream" else { … }
for try await line in bytes.lines where line.hasPrefix("data: ") {
  let event = try decoder.decode(TurnEvent.self, from: Data(line.dropFirst(6).utf8))
  switch event {
  case .delta(let sentence) where !sentence.spoken.isEmpty:
    synthesizer.speak(AVSpeechUtterance(string: sentence.spoken))
  case .turn(let result): show(result)  // the same TurnResult as the JSON answer
  case .error(let failure): stopSpeaking(); show(failure.error)
  default: break
  }
}

A request refused before anything was said, because another request holds the conversation say, is answered as it would be without the header: its status and an Error. The conversation's event stream carries the agent's message whole, as message, for the account's other devices; the sentences go only to the request that sent it.

Connect a Company

The person signs in on the Company's own page; the agent never sees a password. Ask for a sign-in link with the Company's origin and the access it needs, read or write:

POST /api/v1/conversations/hKhgaC-veINpeBH3fJQO4-ewBMbIdw9j/sign-ins
Authorization: Bearer poppy_at.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.KNGQT617OSA3c-i9As0a4HxastNzn0rb3CX977GSDSo
Content-Type: application/json

{
  "company": "https://food-demo.poppylab.dev",
  "access": "write"
}
HTTP/1.1 200
Content-Type: application/json

{
  "url": "https://poppylab.dev/api/v1/sign-ins/Wq3v0mA4…",
  "expiresAt": 1795772968698,
  "endUrl": "https://poppylab.dev/playground/sign-in/app"
}

startSignIn in the reference

Open url at once, and only once, in an ASWebAuthenticationSession that comes back to endUrl. Send no header with it: the link needs none. It works once, for three minutes, for this account, conversation, Company and access. The agent's page goes straight on to the Company's consent page, which names the agent and says what it asks for.

let session = ASWebAuthenticationSession(
  url: URL(string: signIn.url)!,
  callback: .https(host: "poppylab.dev", path: "/playground/sign-in/app")
) { callbackURL, error in
  // result=done or result=failed: a hint. Read the conversation for the outcome.
}
session.prefersEphemeralWebBrowserSession = true
session.presentationContextProvider = self
session.start()

The .https callback needs iOS 17.4 or later and the same webcredentials:poppylab.dev association as the passkeys. An ephemeral session keeps the Company's cookies out of Safari. There is no custom URL scheme: the agent sends the browser only to its own fixed address. On earlier iOS, start the session with no callback; it ends when the person closes the sheet, and the app reads the conversation then.

Take result=done or result=failed in the callback as a hint, and the outcome from the conversation: signin.completed or signin.failed on the events, or the Company's signedIn in GET /conversations/{id}. A sheet closed early leaves the sign-in waiting until it ends with signin.failed after five minutes; asking for a new link replaces it.

Proposals and decisions

A change a Company would make comes as a proposal, in the conversation's proposals and as proposal.created on the events. Show its summary as the Company's words and its exact terms, with an approve and a decline. Nothing is performed until the person approves, and an approval covers exactly the revision it names: when the Company answers with other terms, the proposal comes back with a new revision, which waits for the person again.

POST /api/v1/conversations/hKhgaC-veINpeBH3fJQO4-ewBMbIdw9j/proposals/op_4UNgDhnV1Y8lgsDmZCAV2pt3/decision
Authorization: Bearer poppy_at.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.KNGQT617OSA3c-i9As0a4HxastNzn0rb3CX977GSDSo
Content-Type: application/json

{
  "company": "https://food-demo.poppylab.dev",
  "revision": "1795772788-peanO34panWBIb-5",
  "decision": "approve"
}
HTTP/1.1 200
Content-Type: application/json

{
  "proposal": {
    "id": "op_4UNgDhnV1Y8lgsDmZCAV2pt3",
    "company": {
      "origin": "https://food-demo.poppylab.dev",
      "name": "Lantern Noodle Bar"
    },
    "revision": "1795772788-peanO34panWBIb-5",
    "summary": "Change order ord_LNB1001 for Elena Maren. Delivery stays Friday 18:30–19:00. New dishes: 2 × Shoyu ramen, 1 × Salted edamame, 1 × Matcha ice cream. New total USD 43.00 (was USD 37.00; USD 6.00 more, charged — simulated, no real payment).",
    "terms": {
      "order_id": "ord_LNB1001",
      "order_version": 1,
      "lines": {
        "shoyu-ramen": 2,
        "edamame": 1,
        "matcha-ice": 1
      },
      "before_total_cents": 3700,
      "new_total_cents": 4300,
      "currency": "USD"
    },
    "state": "succeeded",
    "expiresAt": "2026-11-27T09:56:28.685Z",
    "spoken": "Lantern Noodle Bar wants to change your order, for a new total of 43 dollars, 6 more."
  },
  "state": {
    "id": "hKhgaC-veINpeBH3fJQO4-ewBMbIdw9j",
    "active": true,
    "companies": [
      {
        "origin": "https://food-demo.poppylab.dev",
        "name": "Lantern Noodle Bar",
        "url": "https://food-demo.poppylab.dev/",
        "signedIn": true,
        "scopes": "orders:read orders:write",
        "signingIn": false,
        "consentVersion": 1,
        "accessLost": false,
        "direct": {
          "open": false,
          "invitation": null
        }
      }
    ],
    "removed": [],
    "messages": [
      "…"
    ],
    "proposals": [
      "…"
    ]
  }
}

decideProposal in the reference

Follow the events

Some things happen after a turn has answered: the sign-in in the browser sheet, a proposal that runs out, a Company that writes in a Direct Conversation. Open the event stream while the person is in the conversation.

GET /api/v1/conversations/hKhgaC-veINpeBH3fJQO4-ewBMbIdw9j/events
Authorization: Bearer poppy_at.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.KNGQT617OSA3c-i9As0a4HxastNzn0rb3CX977GSDSo
Accept: text/event-stream
HTTP/1.1 200
Content-Type: text/event-stream

retry: 3000

event: state
data: {"type":"state","state":{"id":"hKhgaC-veINpeBH3fJQO4-ewBMbIdw9j","active":true,…}}

: read

event: signin.completed
data: {"type":"signin.completed","company":{"origin":"https://food-demo.poppylab.dev","name":"Lantern Noodle Bar"}}

event: proposal.created
data: {"type":"proposal.created","proposal":{"id":"op_4UNgDhnV1Y8lgsDmZCAV2pt3",…}}

conversationEvents in the reference

state comes first; every event after it is a change to it. The stream closes after five minutes or when the conversation ends: open it again and start from the new state. It ends with session.ended when the device's sign-in does: refresh and open it again on invalid_token, sign in again on session_revoked. An account keeps at most ten streams open on all its devices. Every event type is in the reference.

Sign out

Signing out ends this device's session only; the account's other devices stay signed in. Remove the tokens from the Keychain.

POST /api/v1/account/sign-out
Authorization: Bearer poppy_at.c0rOAOzr0jtlGGeGpluvjQ.nsDf4rxOjzq3NFKVJdG2AQ.KNGQT617OSA3c-i9As0a4HxastNzn0rb3CX977GSDSo
Content-Type: application/json

{}
HTTP/1.1 200
Content-Type: application/json

{
  "revoked": 1
}

signOut in the reference

What is coming

The API is v1 and still changing until it is frozen. One thing a phone needs is not in it yet: push. Events reach an app only while its stream is open. A device will register for push notifications on its own session, so they stop when the session ends. It will be in the document, and on the reference, when it is in the API.