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

# Function and effect declarations

> Declare the TypeScript a call runs, as a pure function or as an effect with explicit capabilities, timeouts and retries.

A `ts function` or `ts effect` declares TypeScript that belongs to the procedure. A declaration is
not a step and never runs by itself. A [`call`](https://docs.canary.effectiveai.app/procedures/reference/nodes/call) runs it once,
addressed as `'@local.<id>'`. A polling [`wait`](https://docs.canary.effectiveai.app/procedures/reference/nodes/wait) can run an
effect repeatedly.

* Use a **function** for deterministic computation over its input: no network, secrets, clock or
  randomness. Running it again always gives the same result.
* Use an **effect** for anything else: reading or writing an outside system, reading a secret,
  calling an Effective API operation, or reading the current time.
* Use a [`value`](https://docs.canary.effectiveai.app/procedures/reference/nodes/value) node instead when you only need to copy
  fields, fill a default or build a string.

Declarations, like schemas and secrets, can appear anywhere in the document, before or after the
calls that use them. Each `call` of `@local.<id>` needs exactly one matching declaration, even
when every test mocks it.

## Syntax

### Function

```ts function id=pro-rata-refund input=refund-input result=refund theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
({ termPremium, termDays, daysInForce }) => {
  const unearnedDays = Math.max(termDays - daysInForce, 0);
  const cents = Math.round((termPremium * unearnedDays * 100) / termDays);
  return { amount: cents / 100 };
};
```

The body is exactly one synchronous arrow function. It takes one argument, the validated input.

### Effect

```ts effect id=cancel-policy input=cancel-request result=cancellation uses=fetch,secrets secrets=pas-token retry=pas-write-retry timeout=1m theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
async ({ policyNumber, effectiveDate }, { fetch, secrets, operation, signal, FatalError }) => {
  const token = await secrets.getText('pas-token');
  const response = await fetch(
    `https://pas.northwind.example/v1/policies/${policyNumber}/cancellations`,
    {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
        'Idempotency-Key': operation.idempotencyKey,
      },
      body: JSON.stringify({ effectiveDate }),
      signal,
    }
  );
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`Cancellation refused (${response.status})`);
  }
  if (!response.ok) throw new Error(`Cancellation failed (${response.status})`);
  const body = await response.json();
  if (typeof body !== 'object' || body === null || !('id' in body) || typeof body.id !== 'string') {
    throw new Error('Cancellation response has no id');
  }
  return { cancellationId: body.id };
};
```

The body is exactly one async arrow function. It takes two arguments: the validated input and the
context.

## Fields

Attributes follow `id` on the fence's info line. Lists are comma-separated, with no spaces, empty
entries or duplicates.

### Function attributes

| Attribute | Type | Required | Default | What it does |
| - | - | - | - | - |
| `input` | schema ID | Yes | None | [Schema](https://docs.canary.effectiveai.app/procedures/reference/nodes/schema.md) of the input object. The input is validated against it before the code runs. |
| `result` | schema ID | Yes | None | Schema of the complete result. The result is validated against it before it's recorded. |
| `retry` | policy ID | No | Default policy | A [`retry`](https://docs.canary.effectiveai.app/procedures/reference/nodes/retry) policy. The default is three attempts. |

### Effect attributes

| Attribute | Type | Required | Default | What it does |
| - | - | - | - | - |
| `input` | schema ID | Yes | None | Schema of the input object. Must be an object schema. |
| `result` | schema ID | Yes | None | Schema of the complete business result. |
| `uses` | list | No | None | Capabilities the effect may use: `fetch`, `secrets` and `effective:<scope>`. See [Capabilities](#capabilities). |
| `secrets` | list | No | None | [Secret slot](https://docs.canary.effectiveai.app/procedures/reference/nodes/secret.md) IDs the effect reads. Requires `uses=secrets`. |
| `retry` | policy ID | No | Default policy | A [`retry`](https://docs.canary.effectiveai.app/procedures/reference/nodes/retry) policy. The default is three attempts. |
| `timeout` | duration | No | `30s` | Longest time one attempt may run. At most `2m`. |

## What the code can use

Both forms use the same TypeScript, with a fixed set of standard objects:

| Object | Available members |
| - | - |
| `Array` | `isArray`; indexing, `length`, `map`, `filter`, `find`, `includes`, `indexOf`, `concat`, `some`, `every`, `reduce`, `reduceRight`, `slice`, `join`, `flat`, `flatMap`, `push`, `reverse`, `sort` |
| `String` | conversion; `length`, `charAt`, `charCodeAt`, `slice`, `trim`, `padStart`, `padEnd`, `toLowerCase`, `toUpperCase`, `startsWith`, `endsWith`, `includes`, `indexOf`, `replace`, `match`, `split` |
| `Number` | `parseInt`, `isFinite`, `isInteger`, `isNaN` |
| `Math` | `abs`, `ceil`, `floor`, `max`, `min`, `round` |
| `Object` | `keys`, `entries`, `fromEntries` |
| `JSON` | `parse`, `stringify` |
| `Boolean`, `RegExp`, `Error` | conversion, regex literals and `new RegExp(pattern, flags)`, `new Error(message)` |
| Binary and text | `ArrayBuffer`; `Uint8Array` with `fromBase64`, `setFromBase64` and `toBase64`; UTF-8 `TextEncoder` and `TextDecoder` |

Members not listed, such as `String.prototype.repeat`, are not available.

Not available in either form: imports of any kind, `eval` and other dynamic code, type assertions
(`as`, `<Type>value` and the non-null `!`), `Intl`, `console`, timers, the filesystem, processes
and environment variables. Write the code you need inside the declaration. Durable sleeps and
polling don't belong in code either; use a [`wait`](https://docs.canary.effectiveai.app/procedures/reference/nodes/wait).

A **function** also has no `Date`, no `Math.random`, no `Promise` and no services. It receives
only its input.

An **effect** also has `Promise.resolve` and `then` for async code, the ambient `Date` for
wall-clock time, and the context below. `Date` can differ between attempts; never use it, or
anything random, as an idempotency key.

Code can't trust outside data. `response.json()` returns `unknown`, so check its shape at run time
before you return it, as the effect above does.

## Effect context

| Name | Needs | What it is |
| - | - | - |
| `operation` | Nothing | `operation.idempotencyKey` is the same for every attempt of the same call. Send it to the systems you write to. `operation.attempt` is the attempt number, for logging only; never base behavior or a key on it. `operation.id` is a deprecated alias of the key. |
| `signal` | Nothing | An `AbortSignal` for the call. Pass it to `fetch` so a cancelled run stops the request. |
| `FatalError` | Nothing | An `Error` subclass. Throw it to fail the step at once, without further attempts. Its message isn't shown on the run; see [On retry and resume](#on-retry-and-resume). |
| `fetch` | `uses=fetch` | Standard Fetch API to the public internet. See [Capabilities](#capabilities). |
| `secrets` | `uses=secrets` | Reads the secret slots listed in `secrets=`. |
| `effective` | `uses=effective:<scope>` | An authenticated Effective API client limited to the declared operations. |

## Capabilities

`uses=` lists everything an effect may do beyond computing. A capability you don't declare
doesn't exist in the effect's context, and the code fails to compile if it uses it.

### fetch

`uses=fetch` grants requests to the public internet. It excludes private networks, loopback and
link-local addresses, cloud metadata services and other tenants' networks. You can't list allowed
hosts per effect.

* Each `fetch` sends one request. It never retries on its own; retries come only from the
  [retry policy](https://docs.canary.effectiveai.app/procedures/reference/nodes/retry.md).
* It follows up to 20 redirects. A redirect to another origin fails if it would forward a header
  or body you set; use `redirect: "manual"` and send the next request yourself.
* It doesn't add an idempotency header. Pass `operation.idempotencyKey` yourself in the header or
  field the receiving system uses.
* It never reaches the Effective API. A relative URL, or a URL on the Effective API's own origin,
  is refused. Use the `effective` client instead.

### secrets

`uses=secrets` with `secrets=<slot>,...` grants the listed slots. Each slot needs a
[`yaml secret`](https://docs.canary.effectiveai.app/procedures/reference/nodes/secret) declaration, and an organization binds the
actual value outside the procedure.

* Read a slot with `secrets.getText('<slot>')`, `secrets.getJson('<slot>')` or
  `secrets.getBytes('<slot>')`. The method must match the slot's declared `format`.
* The slot name must be a string literal. Computed names are invalid.
* The effect must read every slot it lists, and list every slot it reads.

`uses=fetch,secrets` lets your code send secret values to any public host. Review effects that
combine the two with care.

### effective:\<scope>

`uses=effective:<scope>` grants Effective API operations through the `effective` client.
Effective authenticates the call for the run; you don't store an Effective API token.

* Name one operation exactly, such as `uses=effective:api.email.send`, or every read in a group,
  such as `uses=effective:api.chat:read`. Separate several with commas.
* Name each write individually. Group selectors for writes are rejected, so every write is
  visible in the source and when the procedure is reviewed.
* One effect may hold at most 64 operations, so very broad read selectors are too large.
* The operation list is fixed when the procedure is published. A later API addition never widens
  an existing version; republish to use it.
* The call runs with the run's identity, and the API still applies its own permission checks.
* On writes, Effective sends `Idempotency-Key: operation.idempotencyKey` for you. Where the
  operation deduplicates on that key, retries are safe.

The same operations can be called directly from YAML as `'@effective.api.<operation>'` in a
[`call`](https://docs.canary.effectiveai.app/procedures/reference/nodes/call). The effect form is what lets you handle a refusal.

```ts effect id=email-refund-notice input=email-input result=email-receipt uses=effective:api.email.send theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
async ({ to, policyNumber, amount }, { effective }) => {
  await effective.api.email.send({
    template: 'return-premium',
    to,
    subject: `Return premium for policy ${policyNumber}`,
    data: { policyNumber, amount },
  });
  return { sent: true };
};
```

## Branch on a refused Effective API call

A refused `effective.api.*` call throws an error whose message doesn't say why. Inside the effect,
`effective.apiError(error)` tells you:

* It returns `{ status, code, body }` when the API answered with a `4xx`. The call was refused and
  nothing was applied. `body` is the parsed JSON error body, or `null` if it wasn't a JSON object
  or was larger than 16 KiB.
* It returns `null` for a `5xx`, no answer, or any other error. Those may have been applied, so
  rethrow them and let the retry policy apply.

Return the refusals you want to route on as a closed enum in the result, and route on that with a
[`choice`](https://docs.canary.effectiveai.app/procedures/reference/nodes/choice) or [`repeat`](https://docs.canary.effectiveai.app/procedures/reference/nodes/repeat).
Throw `FatalError` for any other refusal, so the run stops instead of retrying a call the API
already refused:

```ts effect id=email-refund-notice input=email-input result=email-receipt uses=effective:api.email.send theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
async ({ to, policyNumber, amount }, { effective, FatalError }) => {
  try {
    await effective.api.email.send({
      template: 'return-premium',
      to,
      subject: `Return premium for policy ${policyNumber}`,
      data: { policyNumber, amount },
    });
    return { outcome: 'sent' };
  } catch (error) {
    const refused = effective.apiError(error);
    if (refused === null) throw error;
    if (refused.status === 422) return { outcome: 'rejected' };
    throw new FatalError(`Email refused (${refused.status}): ${refused.code}`);
  }
};
```

Here `email-receipt` declares `outcome` as `enum: [sent, rejected]`. Which status codes an
operation returns for which refusals depends on the operation.

`effective.apiError` exists only in effects with an `effective:` capability. A YAML `call` of an
`@effective.api.*` operation has no failure routing: a refusal there stops the run with the API's
reason.

## Example

A function works out the pro-rata return premium, then an effect emails the insured:

````markdown return-premium.procedure.md theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
---
kind: procedure@v0
id: return-premium

inputs:
  request: { schema: refund-request }
outputs:
  result: { schema: refund-result }
---

# Return premium

Work out the pro-rata return premium for a cancelled policy, then email the
insured.

## Calculate refund

```yaml call id=calculate-refund
function: '@local.pro-rata-refund'
input:
  termPremium: $inputs.request.termPremium
  termDays: $inputs.request.termDays
  daysInForce: $inputs.request.daysInForce
output: refund
```

## Email insured

```yaml call id=email-insured
function: '@local.email-refund-notice'
input:
  to: $inputs.request.email
  policyNumber: $inputs.request.policyNumber
  amount: $refund.amount
output: email
```

```yaml complete id=done
output: result
value:
  policyNumber: $inputs.request.policyNumber
  refundAmount: $refund.amount
```

## Resources

```yaml schema id=refund-request
type: object
additionalProperties: false
required: [policyNumber, email, termPremium, termDays, daysInForce]
properties:
  policyNumber: { type: string }
  email: { type: string }
  termPremium: { type: number }
  termDays: { type: integer, minimum: 1 }
  daysInForce: { type: integer, minimum: 0 }
```

```yaml schema id=refund-input
type: object
additionalProperties: false
required: [termPremium, termDays, daysInForce]
properties:
  termPremium: { type: number }
  termDays: { type: integer, minimum: 1 }
  daysInForce: { type: integer, minimum: 0 }
```

```yaml schema id=refund
type: object
additionalProperties: false
required: [amount]
properties:
  amount: { type: number }
```

```yaml schema id=email-input
type: object
additionalProperties: false
required: [to, policyNumber, amount]
properties:
  to: { type: string }
  policyNumber: { type: string }
  amount: { type: number }
```

```yaml schema id=email-receipt
type: object
additionalProperties: false
required: [sent]
properties:
  sent: { type: boolean }
```

```yaml schema id=refund-result
type: object
additionalProperties: false
required: [policyNumber, refundAmount]
properties:
  policyNumber: { type: string }
  refundAmount: { type: number }
```

```ts function id=pro-rata-refund input=refund-input result=refund
({ termPremium, termDays, daysInForce }) => {
  const unearnedDays = Math.max(termDays - daysInForce, 0);
  const cents = Math.round((termPremium * unearnedDays * 100) / termDays);
  return { amount: cents / 100 };
};
```

```ts effect id=email-refund-notice input=email-input result=email-receipt uses=effective:api.email.send
async ({ to, policyNumber, amount }, { effective }) => {
  await effective.api.email.send({
    template: 'return-premium',
    to,
    subject: `Return premium for policy ${policyNumber}`,
    data: { policyNumber, amount },
  });
  return { sent: true };
};
```
````

> [!NOTE]
>
> The `return-premium` email template is illustrative. Use a template your organization has set up.

To try it, start it as a draft with your own inputs; see
[Try a draft](https://docs.canary.effectiveai.app/guides/procedures.md#try-a-draft). A draft can't declare secrets, so stub any
effect that needs one while you try it.

## On retry and resume

* **Validated at both ends.** The input is validated before the code runs, and the result is
  validated against `result` before it's recorded.
* **Three attempts by default.** Functions and effects get three attempts: one second before the
  first retry, doubling up to ten seconds. A [`retry`](https://docs.canary.effectiveai.app/procedures/reference/nodes/retry) policy
  replaces this.
* **Effect errors retry; function errors don't.** An uncaught effect error is retried. Throw
  `FatalError` to stop at once. A function error is final, because the function would give the same
  answer again; functions retry only after a timeout or a lost attempt.
* **Thrown messages aren't shown.** A message your code throws, `FatalError` or any other, could
  hold a secret value, so Effective doesn't show it. The run's `failure` names the step and a code
  such as `local-code-failed`, not your message. Return a refusal you need to see as a typed result
  instead, as in [Branch on a refused Effective API call](#branch-on-a-refused-effective-api-call),
  and log the detail in your own system.
* **A finished call doesn't run again.** When a run resumes, a completed call's recorded result is
  used, and the code isn't called again.
* **Effects are not exactly once.** A remote write can commit and its answer still be lost, so a
  retry can send it again. Send `operation.idempotencyKey`, use a natural business key, or select
  a one-attempt policy. Omitting `retry=` keeps the three-attempt default.
* **One write per effect.** An effect may do supporting reads and one business write. Put writes
  that must recover independently in separate effects and separate calls, so each has its own
  result and identity.
* **Polling stops on doubt.** In a polling `wait`, the next poll starts only after the previous one
  finished. If a poll attempt's outcome is unknown, the wait fails for a person to check instead
  of polling again.
* **Pinned with the version.** Publishing seals the code, its schemas and its capabilities into
  the version. Changing any of them needs a new version.

## Common errors

| Code | Cause | Fix |
| - | - | - |
| `PROC-FENCE-006` | Missing, unknown or invalid attribute, for example `ts effect: timeout must be a duration no greater than 2m.` | Use only the attributes above, with valid values. |
| `PROC-FUNCTION-001` | Invalid function attribute or body, or a forbidden name such as `Date` in a function: `Forbidden ambient identifier "Date"`. | Pass the value in as input, or use an effect. |
| `PROC-FUNCTION-002` | The function's `input` or `result` schema doesn't resolve or doesn't fit. | Declare the schema, or fix its ID. |
| `PROC-FUNCTION-004` | The function doesn't type-check, for example `Type 'number[]' must have a '[Symbol.iterator]()' method that returns an iterator.` for array destructuring. | Fix the type error. Read array items by index instead of destructuring. |
| `PROC-EFFECT-002` | The effect's `input` or `result` schema doesn't resolve, or `input` isn't an object schema. | Declare the schema, or fix its ID. |
| `PROC-EFFECT-003` | The effect doesn't type-check or uses something outside its environment, for example `Property 'fetch' does not exist on type 'EffectContext'.` when `uses=fetch` is missing. | Declare the capability, or remove the use. |
| `PROC-EFFECT-004` | Invalid capability, secret slot or API scope, for example a slot listed in `secrets=` that the code never reads. | List exactly the slots and operations the code uses. |
| `PROC-EFFECT-006` | Warning: the code reads the deprecated `operation.id`. | Use `operation.idempotencyKey`. |
| `PROC-EFFECT-007` | The effect may call an Effective API write that doesn't deduplicate retries, and selects no `retry=` policy. | Select a policy, usually with `maximum_attempts: 1`. |
| `PROC-RETRY-002` | `retry=` names a policy that doesn't exist. | Fix the ID, or declare the policy. |
| `PROC-SECRET-003` | The secret read method doesn't match the slot's `format`. | Use `getText`, `getJson` or `getBytes` to match. |

## See also

* [`call` node](https://docs.canary.effectiveai.app/procedures/reference/nodes/call)
* [`retry` policy](https://docs.canary.effectiveai.app/procedures/reference/nodes/retry)
* [`secret` declaration](https://docs.canary.effectiveai.app/procedures/reference/nodes/secret)
* [`schema` declaration](https://docs.canary.effectiveai.app/procedures/reference/nodes/schema)
* [`wait` node](https://docs.canary.effectiveai.app/procedures/reference/nodes/wait)
* [Writes to your systems](https://docs.canary.effectiveai.app/procedures/concepts/writes-to-your-systems.md)


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