> ## 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.

# Build a Play | Agent guide

> Author a durable Deepline Play for custom GTM logic, then validate it before a run or deployment.

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

Build a custom Play for your own routing, provider order, acceptance rules, or
destination writes. Existing Plays and tools can supply its building blocks.
[Choose a prebuilt Play](https://deepline.com/docs/sdk-v2/prebuilt-plays.md) when its contract already fits.

## Before you start

Use an installed Deepline CLI and a project connected to the intended org.
[Installation](https://deepline.com/docs/sdk-v2/coding-agents.md) and [project setup](https://deepline.com/docs/sdk-v2/quickstart.md#1-prepare-a-project)
cover those steps.

This example accepts a CSV with `lead_id` and `linkedin_url` headers. It calls
one scalar email Play per row. Inspect that child's required input, output,
access, and price before composing it:

```bash theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
deepline describe prebuilt/person-linkedin-to-email --json
```

For a provider action, [search and inspect its contract](https://deepline.com/docs/integrations.md) before
adding `deepline.tools.execute`. Keep credentials in org integrations or
[declared Play secrets](https://deepline.com/docs/sdk-v2/sdk-reference.md#deepline-secrets-get-name).

## The authoring contract

A Play is a `.play.ts` file that imports the `deepline` runtime and
default-exports an async function. The file name is its default Play name;
`export const config = { name }` can override it. The function's input type
defines the input contract, and its plain-object return is the result.

Save this as `enrich-lead-file.play.ts`:

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

type Lead = {
  lead_id: string;
  linkedin_url: string;
};

export const config = {
  description: 'Find verified work emails for a CSV of LinkedIn profiles.',
  billing: { maxCreditsPerRun: 25 },
};

export default async function (input: { csv: string }) {
  const leads = await deepline.csv<Lead>(input.csv, {
    required: ['lead_id', 'linkedin_url'],
  });
  const rows = await deepline
    .dataset('lead_email', leads)
    .withColumn('email_result', (lead) =>
      deepline.runPlay(
        'person_email',
        'prebuilt/person-linkedin-to-email',
        { linkedin_url: lead.linkedin_url },
        { description: 'Find a verified work email for this lead.' },
      ),
    )
    .run({
      key: 'lead_id',
      description: 'Find one email for each lead.',
    });

  return { rows };
}
```

The optional `config` object holds the name, description, triggers, runtime,
billing, and other supported settings. Declare it once at module scope with
statically resolvable values. A description helps people understand the saved Play.
The file exports only its Play function and optional `config`.

Use `deepline` inside the Play file. Pass it to helpers as an argument typed
`DeeplinePlayRuntimeContext` when they need runtime operations.

`email_result` holds the child's complete result, including its no-result or
validation evidence. It is not an email-address string. Inspect the child
contract before extracting individual fields.

The returned `rows` dataset contains successful rows. Failed rows and their
errors remain in the saved run. Current edition 11 CSV inputs retain every
source-row occurrence, including repeated keys. Non-CSV datasets and earlier
admitted editions retain their key-based deduplication behavior. Reconcile the
expected input occurrences and failed rows before expanding the file. The
[SDK reference](https://deepline.com/docs/sdk-v2/sdk-reference.md#play-authoring-contract) explains these policies.

## Choose the runtime primitive

| Use | When the work is | What must be stable |
| - | - | - |
| `deepline.dataset(...).withColumn(...).run(...)` | Row-oriented and exportable | The dataset row key |
| `deepline.step(...)` | One scalar action or checkpoint | The step key |
| `deepline.tools.execute(...)` | One provider-backed operation | Call identity and explicit freshness policy |
| `deepline.runPlay(...)` | A statically resolvable scalar child Play | The child-call key |
| `deepline.fetch(...)` | An external HTTP request that should appear in run history | The request id and downstream idempotency key |

Use `deepline.runPlay(...)` for compatible scalar children. A child with its own
dataset, CSV, event wait, or explicit timeout needs a separate top-level run.
Import a local scalar child with `import child from './child.play'` and pass
`child` instead of its name. The [SDK reference](https://deepline.com/docs/sdk-v2/sdk-reference.md) owns the
exact signatures and limits.

For direct tool, step, or HTTP calls, choose `staleAfterSeconds` explicitly.
Use `0` for fresh logical work. A positive integer permits reuse within that
many seconds; `null` permits indefinite reuse. Recovery of the same operation
is separate from this freshness choice.

## Validate before deployment or spend

Check the saved source:

```bash theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
deepline plays check ./enrich-lead-file.play.ts
```

The check does not publish or start provider work. Fix its errors before running
the file. For a short experiment, the CLI also accepts
[inline code with `plays run -e`](https://deepline.com/docs/sdk-v2/calling-plays#run-a-short-snippet-inline).
Prepare a [representative CSV](https://deepline.com/docs/sdk-v2/batch-csv.md), then follow
[Run Plays and view results](https://deepline.com/docs/sdk-v2/calling-plays.md) to run the file and inspect
its saved dataset and errors. Compare accepted results with your business rule.

The example sets `billing.maxCreditsPerRun` to 25 Deepline credits. Choose a cap
for your actual sample before execution. It controls provider-call admission;
already admitted work and compute can remain billable. [Control costs](https://deepline.com/docs/cost-control.md)
explains this limit and the `--max-credits` override.

Publish only after the sample passes review:

```bash theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
deepline plays publish ./enrich-lead-file.play.ts
deepline plays get enrich-lead-file
```

Verify the live version against the publication result. Publishing changes
what callers of that Play name execute. For recurring work, continue with
[Schedule or trigger a Play](https://deepline.com/docs/sdk-v2/webhooks-and-schedules.md).

## Compose an Engine from Plays

Use the [Engine pattern](https://deepline.com/docs/plays/engines.md) when business states must persist
across runs. `/deepline-engine` guides its construction. Keep the orchestrator,
transition Plays, shared types, and state diagram in a versioned project.

1. Define the state matrix: current state, transition Play, allowed next states,
   terminal outcome, and input/output table roles.
2. Inspect existing transition Plays before authoring another. Use only children
   compatible with scalar composition.
3. Persist state through `deepline.customerDb.query(...)` in permitted, schema-qualified
   customer tables. Give each business record a stable key.
4. Define deterministic transition and handoff keys. Use database constraints
   and supported conflict handling, such as `INSERT ... ON CONFLICT`.
5. Recognize completed writes. Repair missing handoffs without duplicating
   completed outputs or next-state inputs.
6. Record unknown states, forbidden moves, child failures, and invalid results.
   Failed transitions must not create a next-state handoff.
7. Check every new Play. Publish compatible children before their callers,
   then verify their live versions.

Test terminal and unknown states, forbidden transitions, child failures,
invalid results, repeated inputs, and interrupted handoffs. If concurrent runs
can advance the same record, test the workflow's conflict policy.

Stable call labels alone do not prevent independent executions. Apply a
provider-free test matrix before a provider-backed pilot. Set the pilot's
per-run credit cap. External writes need destination-supported idempotency or
reconciliation; an Engine does not supply a cross-system transaction.

## Next steps

> [card] [Choose a prebuilt Play](https://deepline.com/docs/sdk-v2/prebuilt-plays.md)
>
> Discover a maintained Play or compose a scalar child Play.

> [card] [SDK reference](https://deepline.com/docs/sdk-v2/sdk-reference.md)
>
> Read the exact `deepline`, dataset, and tool contracts.

## Verify this task

Reconcile input rows, accepted results, explicit misses, and failed rows. Verify
the live revision only after the checked sample meets your acceptance rules.


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