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

# Integrate a Play into your app | Agent guide

> Integrate Deepline plays into a production backend with durable run IDs, resilient polling, callbacks, idempotent writes, and explicit cancellation.

[Human guide: task steps and agent prompt →](https://deepline.com/docs/human/sdk-v2/production-integration.md)

A Deepline play is an asynchronous job. Starting one returns a public run ID
before the work necessarily finishes. Persist that ID, then use it to observe
the same run until Deepline reports a terminal state.

For direct tool calls, use [tool execution recovery](https://deepline.com/docs/sdk-v2/tool-execution-recovery.md).
Its caller-owned key is available before dispatch, so it also covers a lost
initial HTTP response.

![An application starts a play, persists its run ID, lets Deepline run asynchronously, then recovers the terminal result.](https://mintcdn.com/deepline2/HfX7N0vAcXPGNX65/images/production-play-lifecycle.svg?fit=max\&auto=format\&n=HfX7N0vAcXPGNX65\&q=85\&s=2b1a6adf17eac7d7c9f0362844bb7efe)

The run ID is the durable handoff between your application and Deepline.

> [!WARNING]
>
> A timeout in your HTTP client, request handler, worker lease, or polling loop
> does not stop the Deepline run. Do not start the enrichment again only because
> your local wait ended.

## Choose where the result is written

Choose who validates and writes the final result:

| Pattern | Result owner | Infrastructure | Use when |
| - | - | - | - |
| Persist and poll | Your application | Background worker or scheduled job | You want the smallest reliable starting point |
| Custom-play callback | Your application | Authenticated callback endpoint | You want event-driven completion without continuous polling |
| Direct destination write | Deepline play | Scoped destination credentials | The play can own enrichment and the final write |
| Synchronous provider calls | Your application | Your own orchestration | A request path has a strict latency budget |

Start with persisted polling. Use a callback to avoid continuous polling, or
let the Play own an idempotent destination write with scoped credentials.

## Persist and poll

Persist the run ID before waiting. If the process restarts or its local wait
budget ends, a background worker can recover the same run.

```mermaid placement="top-right" theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
sequenceDiagram
    participant App as Your application
    participant Store as Your database
    participant Deepline

    App->>Deepline: Start play
    Deepline-->>App: Return run ID
    App->>Store: Persist run ID

    loop Until Deepline reports a terminal state
        App->>Deepline: Get status for the same run ID
        Deepline-->>App: queued, running, or waiting
    end

    Deepline-->>App: completed, failed, or cancelled
    App->>Store: Write result once, keyed by run ID
```

### Start the run

Record launch intent in your application before submitting. `PlayJob.id` is
the returned public run ID; save it before calling `get()`, `tail()`, or polling.
If the launch response is lost, reconcile that intent before submitting again.

```ts theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
import { Deepline } from 'deepline';

declare const runs: {
  insert(run: { runId: string; status: 'running' }): Promise<void>;
};

const deepline = await Deepline.connect();
const job = await deepline
  .play<{
    domain: string;
    roles: string[];
  }>('prebuilt/company-to-contact')
  .run({
    domain: 'example.com',
    roles: ['VP of Sales'],
  });

await runs.insert({
  runId: job.id,
  status: 'running',
});
```

### Resume the same run

Use `DeeplineClient.getPlayStatus(runId)` when a worker resumes from a stored
run ID.

```ts theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
import { DeeplineClient } from 'deepline';

declare const storedRun: { runId: string };
declare const results: {
  writeOnce(input: { idempotencyKey: string; value: unknown }): Promise<void>;
};

const client = new DeeplineClient();
const status = await client.getPlayStatus(storedRun.runId, { full: true });

if (status.status === 'completed') {
  await results.writeOnce({
    idempotencyKey: storedRun.runId,
    value: status.result,
  });
}
```

Only `completed`, `failed`, and `cancelled` are terminal. Treat `queued`,
`running`, and `waiting` as active work that can be checked again.

The [downloadable caller](https://deepline.com/docs/downloads/sdk-v2/production-integration.ts.txt) combines
submission, saved-run recovery and cancellation. Its in-memory `Map` stores
demonstrate the interfaces; they do not survive a restart. Replace them with
your application's durable store and an atomic result write keyed by run ID.
Persist launch intent there before calling `startEnrichment`.

> [!TIP]
>
> Use the run ID as the idempotency key for the destination write. Repeated
> polls, worker restarts, or duplicate completion delivery then converge on one
> stored result.

## Call your application when a custom play finishes

Use a custom play when you want Deepline to finish the enrichment and then make
a durable outbound request to your application. The custom play owns the
callback step. This is distinct from an inbound webhook that starts a play.

```mermaid placement="top-right" theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
sequenceDiagram
    participant App as Your application
    participant Deepline
    participant Callback as Your callback endpoint
    participant Store as Your database

    App->>Deepline: Start custom play
    Deepline-->>App: Return run ID
    App->>Store: Persist run ID
    Deepline->>Deepline: Complete enrichment
    Deepline->>Callback: POST authenticated result + request ID
    Callback->>Callback: Authenticate and validate payload
    Callback->>Store: Write once by request ID
```

Use `deepline.runPlay(...)` to call a prebuilt play and `deepline.fetch(...)` for the
recorded callback. Keep callback credentials in declared play secrets, require
HTTPS, and reject invalid tokens in your application. Pass a stable application
request ID into the custom play, store its mapping to the Deepline run ID, and
echo it in the callback payload.

Use the maintained [callback Play source](https://deepline.com/docs/downloads/sdk-v2/enrich-and-notify.play.ts.txt).
It shows three recorded callback attempts, bounded waits, bearer authentication,
and a stable `idempotency-key` from the application request. Keep its declared
secret and destination URL aligned with your application.

The application should acknowledge the callback only after it has validated
the payload and committed an idempotent write.

A lost callback response leaves the destination outcome uncertain even when
enrichment completed. Reconcile using the destination's read or idempotency
contract before repeating a mutation. A stable internal call label alone does
not guarantee exactly-once external effects.

## Let the custom play write directly

A custom play can also enrich the record and write the result to the final
destination through a Deepline integration or a recorded `deepline.fetch(...)`
step.

```mermaid placement="top-right" theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
flowchart LR
    App["Your application"] -->|"Start custom play"| Deepline["Deepline"]
    Deepline -->|"Return run ID"| App
    Deepline --> Enrich["Complete enrichment"]
    Enrich --> Write["Write to your destination"]
    Write --> Done["Run completes"]
```

This removes the polling worker and callback service. It also moves final-write
ownership into the play. Use narrowly scoped credentials and make the
destination operation idempotent.

Choose this pattern when:

* the play owns the complete business transaction.
* your application does not need to validate the result first.
* the destination supports a safe upsert or idempotency key.
* you are comfortable storing scoped destination credentials in Deepline.

## Handle local timeouts

A local wait budget and a remote run state are separate.

| What happened | What to do |
| - | - |
| You received a run ID, then polling timed out | Store the state as active and poll the same run later |
| A worker restarted after storing the run ID | Resume with `getPlayStatus(runId)` |
| The run is `queued`, `running`, or `waiting` | Keep the run active; do not create a replacement |
| The run is `completed` | Validate and write the result once |
| The run is `failed` | Store the failure context and apply your retry policy deliberately |
| The run is `cancelled` | Stop polling and record the cancellation |
| The start request failed before returning a run ID | Reconcile application state before deciding whether to submit again |

Keep the final status response when a run fails. Its run ID, progress, and error
context make support and replay decisions much easier.

## Stop a run intentionally

Ending a local request does not cancel a play. Stop the run explicitly when the
user cancels the underlying job or the result is no longer useful.

```ts theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
import { DeeplineClient } from 'deepline';

export async function stopRun(
  runId: string,
): Promise<'stopped' | 'cancelling'> {
  const client = new DeeplineClient();
  const result = await client.stopPlay(runId, {
    reason: 'Request cancelled by the user',
  });
  if (result.stopped) return 'stopped';
  if (result.state === 'cancelling' || result.cancelling) return 'cancelling';
  throw new Error(result.error ?? `Could not confirm stop for ${runId}`);
}
```

From raw HTTP, with `jq` installed for URL encoding:

```bash theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
RUN_ID="<persisted-run-id>"
ENCODED_RUN_ID=$(printf '%s' "$RUN_ID" | jq -sRr @uri)
curl --fail-with-body -X POST "$DEEPLINE_HOST_URL/api/v2/runs/$ENCODED_RUN_ID/stop" \
  -H "Authorization: Bearer $DEEPLINE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"reason":"Request cancelled by the user"}'
```

HTTP `200` confirms `stopped`. HTTP `202` with `state: "cancelling"` accepts the
cancellation while cleanup and the final run update remain pending. Continue
observing the same run until terminal; acceptance is not terminal completion.
A failed or uncertain stop does not prove the run stopped.

Stop for a business reason, such as user cancellation, rather than a short
polling window.

## Design for a latency-sensitive request path

Prebuilt plays can use multiple providers, retries, and fallback paths to
improve coverage and price-performance. That work can outlive an interactive
request.

For a tighter latency budget, choose one of these:

* fork the prebuilt play and keep only the providers or branches that matter to
  the request path.
* return a pending state to the user and finish enrichment in the background.
* call synchronous provider endpoints and own their rate limits, transient
  errors, retries, caching, and observability in your application.

Do not force a broad enrichment waterfall into a synchronous UI deadline.

## Accept and retrieve the result

Validate the business result before applying it. A `completed` lookup may return
no usable candidate; a source failure needs a separate error path. Use the
[dataset and retained-result retrieval paths](https://deepline.com/docs/sdk-v2/calling-plays.md#inspect-and-export-an-existing-run)
for row data rather than expecting all rows in the compact status response.
Use declared getters for supported semantic fields and inspect actual response
shapes before reading provider-specific paths.

Choose one destination owner: either the caller applies accepted results or
the Play does. Independent writes from both can duplicate effects. Read usage
for the saved run separately: empty results and pending charges do not prove
zero usage. See [Cost control](https://deepline.com/docs/cost-control.md).

## Unattended callers

Workers, scheduled agents and CI need authorization in the runtime that
actually executes the task. Bind local working folders with [Choose an org for each project](https://deepline.com/docs/sdk-v2/multi-org.md);
use protected runner credentials for [Deploy with GitHub Actions](https://deepline.com/docs/sdk-v2/github-deployments.md).
A successful interactive session does not prove the background runtime is ready.

Before enabling recurrence:

1. Inspect the published Play and prove one foreground run with reviewed input.
   Follow [Run Plays](https://deepline.com/docs/sdk-v2/calling-plays.md), save its run ID, and inspect row
   outcomes and [scoped usage](https://deepline.com/docs/cost-control.md). An `accounts` array does not imply
   CSV support.
2. Confirm a restarted worker can observe that saved run and apply its accepted
   result through the destination owner chosen above.
3. Choose one owner for timing and retries. Use [Schedule or trigger a Play](https://deepline.com/docs/sdk-v2/webhooks-and-schedules.md)
   for Play-owned triggers, or an external scheduler when the caller owns them.
   Provider [Monitors](https://deepline.com/docs/plays/set-up-a-monitor.md) have their own feed lifecycle;
   an agent watching a folder is custom application logic.
4. Review overlap handling, per-run credit caps and org limits, where
   failures and usage will be visible, and how to pause the recurring trigger
   and stop active work. Activate recurrence only after that review.

For custom Plays, choose `staleAfterSeconds` explicitly on durable calls. Use
`0` for current data; a daily read refresh can use `86_400` only when the tool
permits reuse. The [authoring reference](https://deepline.com/docs/sdk-v2/sdk-reference.md)
defines freshness separately from recovering the same operation.

## Related guides

> [card] [Call Plays](https://deepline.com/docs/sdk-v2/calling-plays.md)
>
> Start plays from TypeScript, the CLI, another play, or raw HTTP.

> [card] [Call Plays from Python or HTTP](https://deepline.com/docs/sdk-v2/http-and-python.md)
>
> Start and poll plays from non-TypeScript systems.

> [card] [API Reference](https://deepline.com/docs/api-reference.md)
>
> Inspect run status, streaming, output, and stop contracts.


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