# Write a station

The [Quickstart](/docs/quickstart) writes a first station. This page covers the rules around it: where its handler lives, what its schema does to the config, what `execute` receives and what it returns. For a station that works through its workpieces, see [Write a station that processes workpieces](/docs/guides/process-workpieces).

## One folder per station

A station's code lives in `src/stations/`, in a folder named like its station file:

```text
src/stations/IN1__check/
├── station.js             the handler: export default defineStation({ code: 'IN1', … })
├── report.md              a template the handler renders
└── totals.js              a helper the handler imports
```

| Part | Rule | Example |
|---|---|---|
| Folder | `{CODE}__{station_name}`, the same name as its station file | `IN1__check/` for `.orchestrator/stations/IN1__check.json` |
| Handler | `station.js` in that folder, whose default export is `defineStation()` | `IN1__check/station.js` |
| Code | The handler's `code` equals the folder's code, case included | `code: 'IN1'` |

The factory session finds handlers with `discoverStations()`: it imports `station.js` from each folder and keys the handler by its code. Other files in the folder (templates, prompts, helpers) are not discovered; `station.js` imports what it needs. The session refuses to start when:

- a `station.js` doesn't default-export `defineStation()`,
- a handler's `code` doesn't match its folder (`code 'IN2' doesn't match its folder 'IN1__check'`), or
- two folders hold a handler with the same code.

A folder without a `station.js` is skipped. A run of a station whose handler the session doesn't have fails at once with `Unknown station: IN1`, without a retry.

### A handler two stations share

When two stations do the same work with different configs, such as one per client, write the handler once in `src/shared/` and give each station a `station.js` that wraps it:

```js
// src/shared/post-invoices.js
import { z } from 'zod';

export const post_invoices_config = z.object({ ledger_account: z.string() });
export async function postInvoices(config, context) { /* … */ }

// src/stations/IN2__post_acme/station.js
import { defineStation } from '@assemblyline/lib-factory';
import { postInvoices, post_invoices_config } from '../../shared/post-invoices.js';

export default defineStation({ code: 'IN2', configSchema: post_invoices_config, execute: postInvoices });
```

Code that isn't a handler, such as a client for an outside system, goes in `src/utils/`.

## The definition

```js
import { defineStation } from '@assemblyline/lib-factory';
import { z } from 'zod';

export default defineStation({
  code: 'IN1',
  configSchema: z.object({
    approval_limit: z.number().default(5000).describe('Invoices above this amount need approval'),
  }),
  execute: async (config, context) => {
    // …
    return { checked: 12, above_limit: 2 };
  },
});
```

| Field | Required | Holds |
|---|---|---|
| `code` | yes | The station's short code; the session finds the handler by it |
| `configSchema` | no | A zod schema for the config. Every factory station has one. |
| `execute(config, context)` | yes | The work. Its return value is the run's output. |

`defineStation()` throws when `code` or `execute` is missing. The station's name, description, line, conveyor, trigger and config live in its [station file](/docs/guides/factory-repo#station-files), not in the code.

## Config: what the schema does to it

When a station runs, it gets the `config` from its station file, with any overrides for that run (`al-orc stations run IN1 --set approval_limit=1000`). Before `execute` runs, the config goes through `configSchema`:

1. **Defaults are filled in.** A setting with `.default()` can be left out of the station file.
2. **Keys the schema doesn't name are dropped.** A misspelt key in a station file is ignored without a word, and the default is used instead.
3. **A config that doesn't fit fails the run** before your code runs, with one line per field:

```text
[IN1] Invalid config:
  - approval_limit: Invalid input: expected number, received string
```

Give every setting with a sensible value a default, so a station file only says what differs, and use `.describe()` to say what a setting means.

To catch a station file and its handler drifting apart, test that the station's config parses: see [Run and test a station](/docs/guides/test-a-station).

### Values from the environment

A station reads every secret, and any value that differs between machines, from the factory's environment in its own code. See [Give stations their credentials](/docs/guides/environment-and-secrets).

## Output: what `execute` returns

What `execute` returns is the run's output. The factory session sends it to the Orchestrator, which stores it on the work record as `output`, next to `config_snapshot`, the config the run was given.

- **It must be JSON.** Return counts and ids, not data: see [Where a station keeps its data](/docs/guides/keep-station-data).
- **Nothing checks its shape.** There is no output schema, so keep the same keys from run to run: people and reports read them.

## What `execute` receives

`config` is the parsed config above. `context` describes the run:

| Field | Use it for |
|---|---|
| `context.work_record.id` | The run's id: `processWorkpiece`, `logEvent` and every attach call take it |
| `context.station.code` | This station's code, for a handler several stations share |
| `context.org_id` | The organisation the run belongs to |

Factory stations take what they need from `context` on the first line:

```js
execute: async (config, context) => {
  const { work_record } = context;
  // …
},
```

In a local run, the ids start with `local-`, and the attach calls write files instead of calling the Orchestrator: see [Run and test a station](/docs/guides/test-a-station).

## When something goes wrong

Throw. Where you throw decides whether one workpiece fails or the whole run does. A run that fails is run again from the start, so a station must be safe to rerun: see [Throw errors from a station](/docs/guides/station-errors).

Every function used here is listed in the [lib-factory README](https://github.com/assemblyline-sh/lib-factory#exports).
