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

# Build a warehouse station

> A Node device with a scanner, scale, stock lookup, receipt printer, and gate, plus a low-stock trigger handled on the platform

You'll build a [device](https://docs.heylua.ai/concepts/devices.md) for a packing station: the agent can scan a barcode, read the scale, look up stock, print a receipt, and open a dock gate after confirmation, and the station wakes the agent when stock runs low. The hardware is simulated so the example runs anywhere with Node 18 and an agent created with `lua init`.

*Verified against lua-cli 3.45.0.*

## What you'll build

* A Node device `warehouse-station-01` with five commands.
* A `low_stock_alert` trigger fired by the station and handled by a `defineDeviceTrigger` on the agent.
* Persona guidance so the model confirms before opening a gate.

**1. Create the credential**

From the agent project, issue a [device credential](https://docs.heylua.ai/devices/credentials.md) for device name `warehouse-station-01`; the default operations, `commands` and `triggers`, are what the station needs. Then load it in the folder where the device will run and install the client.

```bash theme={null}
mkdir -p ../warehouse-station
lua devices credential --device-name warehouse-station-01 --out ../warehouse-station/.env.device
cd ../warehouse-station
set -a; . ./.env.device; set +a
npm init -y && npm install @lua-ai-global/device-client && npm install -D tsx
```

**2. Write the device**

Each handler talks to simulated hardware; replace the stubs with your drivers. The station checks stock every minute and fires `low_stock_alert` for each SKU under its threshold.

```ts device.ts expandable theme={null}
import { DeviceClient } from '@lua-ai-global/device-client';

type Item = { name: string; quantity: number; threshold: number };
const inventory: Record<string, Item> = {
  'SKU-2024-0847': { name: 'Widget A', quantity: 8, threshold: 10 },
  'SKU-2024-0312': { name: 'Bracket B', quantity: 142, threshold: 20 },
};

const device = new DeviceClient({
  agentId: process.env.LUA_AGENT_ID!,
  deviceCredential: process.env.LUA_DEVICE_CREDENTIAL!,
  deviceName: 'warehouse-station-01',
  commands: [
    { name: 'scan_barcode', description: 'Activate the scanner and return the barcode it reads', timeoutMs: 10000 },
    { name: 'read_weight', description: 'Read the shipping scale in kilograms' },
    {
      name: 'check_stock_level',
      description: 'Return the stock level and reorder threshold for a SKU',
      inputSchema: { type: 'object', properties: { sku: { type: 'string' } }, required: ['sku'] },
    },
    {
      name: 'print_receipt',
      description: 'Print lines of text on the station receipt printer',
      inputSchema: {
        type: 'object',
        properties: { lines: { type: 'array', items: { type: 'string' }, maxItems: 40 } },
        required: ['lines'],
      },
      timeoutMs: 15000,
    },
    {
      name: 'open_gate',
      description: 'Open a dock gate. Ask the worker to confirm before calling this.',
      inputSchema: { type: 'object', properties: { gate: { type: 'string', enum: ['dock-a', 'dock-b'] } }, required: ['gate'] },
      timeoutMs: 15000,
    },
  ],
});

device.onCommand('scan_barcode', async () => ({ barcode: 'SKU-2024-0847', format: 'CODE128' }));
device.onCommand('read_weight', async () => ({ weight: 12.4, unit: 'kg' }));

device.onCommand('check_stock_level', async (payload) => {
  const item = inventory[String(payload.sku)];
  if (!item) return { found: false, sku: payload.sku };
  return { found: true, sku: payload.sku, ...item, low: item.quantity <= item.threshold };
});

device.onCommand('print_receipt', async (payload) => {
  const lines: string[] = payload.lines.map((line: unknown) => String(line).slice(0, 48));
  console.log(['--- RECEIPT ---', ...lines, '--- END ---'].join('\n'));
  return { printed: lines.length };
});

device.onCommand('open_gate', async (payload) => ({ gate: payload.gate, opened: true, at: new Date().toISOString() }));

async function main() {
  await device.connect();
  console.log('warehouse-station-01 connected');
  setInterval(async () => {
    for (const [sku, item] of Object.entries(inventory)) {
      if (item.quantity > item.threshold) continue;
      await device
        .trigger('low_stock_alert', { sku, name: item.name, quantity: item.quantity, threshold: item.threshold })
        .catch((err: Error) => console.error(err.message));
    }
  }, 60_000);
}

main().catch((err: Error) => {
  console.error(err.message);
  process.exit(1);
});
```

**3. Handle the trigger on the agent**

In the agent project, a standalone trigger stores the alert and hands it to the model. The name matches the device's string exactly.

```ts src/devices/LowStockAlert.ts theme={null}
import { Agents, Data, defineDeviceTrigger } from 'lua-cli';
import { z } from 'zod';

// From lua.skill.yaml; env() is empty inside device-trigger handlers.
const AGENT_ID = 'agent_abc123';

export const lowStockAlert = defineDeviceTrigger({
  name: 'low_stock_alert',
  description: 'A station reports a SKU at or below its reorder threshold',
  payloadSchema: z.object({ sku: z.string(), name: z.string(), quantity: z.number(), threshold: z.number() }),
  async execute(payload, { device }) {
    await Data.create('stock-alerts', { device: device.name, ...payload, at: Date.now() });
    await Agents.invoke(
      AGENT_ID,
      `${device.name} reports ${payload.name} (${payload.sku}) at ${payload.quantity}, threshold ${payload.threshold}. Draft a reorder.`
    );
  },
});
```

**4. Register and publish**

Register the trigger, give the model its rules in the persona, then push the trigger live.

```ts src/index.ts highlight={8} theme={null}
import { LuaAgent } from 'lua-cli';
import { lowStockAlert } from './devices/LowStockAlert';

export default new LuaAgent({
  name: 'warehouse-agent',
  persona:
    'You assist packing-station workers. After scanning a barcode, check its stock level. Never call open_gate without an explicit confirmation in this conversation.',
  deviceTriggers: [lowStockAlert],
});
```

```bash theme={null}
lua push device-trigger --name low_stock_alert --auto-deploy
```

**5. Run and talk to it**

Start the station, then ask the agent from the project.

```bash theme={null}
npx tsx device.ts
lua chat -m "Scan the item on warehouse-station-01 and tell me whether we need to reorder"
```

The model calls `device__warehouse_station_01__scan_barcode`, then `check_stock_level`, and reports Widget A as low.

**6. Verify the trigger**

Within a minute the station fires `low_stock_alert` for Widget A. Read the handler's run.

```bash theme={null}
lua logs --type device-trigger --limit 10
```

Stop the script: `lua devices status --device-name warehouse-station-01 --ci` prints `offline` and the five tools are gone on the agent's next turn. If the connection drops while the script runs, each minute's `trigger()` call rejects with `Not connected to device gateway` and the loop logs it until the client reconnects.

## What you learned

* Timeouts per command (`timeoutMs`) cover slow hardware such as a printer. See [Expose device commands as tools](https://docs.heylua.ai/devices/commands-and-tools.md).
* Confirmation rules belong in the persona and the command description; the device can't see the conversation.
* A trigger is queued and acknowledged before its handler runs, and the handler is published with `lua push device-trigger --auto-deploy`. See [Handle device triggers](https://docs.heylua.ai/devices/triggers.md).

## Next steps

> [card] [Smart office](https://docs.heylua.ai/devices/examples/smart-office.md)
>
> Several devices in a group with one fan-out tool.

> [card] [defineDevice and defineDeviceTrigger](https://docs.heylua.ai/reference/sdk/device-definition.md)
>
> Every handler field.


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