# Call an opted-in lead from a webhook

Use this Agent Worker when a CRM, form or spreadsheet already knows who asked for a call. The source sends the number, calling authorization and a stable event ID. This workflow needs no CRM access token.

## Prompt

```text
When an opted-in lead requests a demo, have an Agent Worker call the phone number in the event. Show me a test with and without consent before activation.
```

## Set up the Agent Worker

1. Read `get_pricing`. Use `create_worker` with a fresh `idempotency_key` for this definition. Set `worker.name` to `Lead callback`, paste the JavaScript below into `worker.code`, and set `daily_limit_usd` and `max_call_cost_usd` to the owner's limits. The daily limit covers execution. The per-call limit applies to each dial.
2. Run `test_worker` with the returned `worker_id`, a stable test `idempotency_key` and the fixture below as `event`. Expect a simulated `proposed_call`. Change `authorized_to_call` to false and use a fresh test key. Expect `skipped: true`. Tests use prepaid execution time.
3. Once the owner approves the rates and limits, call `set_worker_state` with `state:"active", accept_costs:true`. In the external system, configure the user's chosen event to POST JSON to the returned `webhook_url`. Bind `trigger_secret` from the secret store as the `X-Thoughtly-Trigger` header. Map permission from the source's actual opt-in record.
4. Reuse the same event ID and body for redelivery. The receipt gives a `run_id`. Read `get_worker_run` for its outcome and `get_call` for the resulting call ID. A changed payload with the same event ID returns 409.

```js
export default async function (event, ctx) {
  if (event.type !== "lead.created" || event.authorized_to_call !== true ||
      !/^\+[1-9]\d{1,14}$/.test(event.phone || "")) {
    return { skipped: true };
  }
  return ctx.calls.place({
    to: event.phone,
    prompt: "Introduce yourself and ask how we can help with the requested demo.",
    max_duration_seconds: 60
  });
}
```

```json
{"type":"lead.created","event_id":"lead-fixture-001","record_id":"lead_42","phone":"+12025550147","authorized_to_call":true}
```

For source-specific setup, choose your provider in the [recipe directory](/recipes). To save the call status to the same record, add the [post-call handler](/recipes/post-call-crm.md).
