# Listeners

> Run a small script that watches something no app webhook tells you about, and wake an agent when it changes: every few minutes in a NoClick sandbox, or always on one of your machines.

A **listener** is a small script NoClick runs for an agent. It watches something nothing else tells NoClick about (a mailbox over IMAP IDLE, a price stream, a page, a feed) and wakes the agent when that changes. It's one of the agent's [triggers](https://www.noclick.com/docs/guide/triggers.md): added, listed, paused, changed and removed like a webhook or a schedule.

| | Runs | Paid |
| --- | --- | --- |
| **Recurring** (`every_minutes`) | once every 1 to 30 minutes or 1 to 24 hours, in a NoClick sandbox (Python and Node, the network open), up to `timeout_s` | by the second, at cost, as any [sandbox](https://www.noclick.com/docs/guide/sandboxes.md) |
| **Always on** (`always_on`) | all the time, on one of your [machines](https://www.noclick.com/docs/guide/machines.md), for anything that holds a connection open (IMAP IDLE, a WebSocket, MQTT, a stream) | nothing more than the machine |

## What the script is handed

Its environment holds its secrets' keys (your [secrets](https://www.noclick.com/docs/guide/secrets.md), by name) and three values of NoClick's, nothing else of your account's:

| Variable | What it is |
| --- | --- |
| `NOCLICK_WAKE_URL` | `POST` here, with a JSON body of what changed, to wake the agent |
| `NOCLICK_CURSOR_URL` | `GET` its place (`{"cursor": ...}`, null at first) and `PUT` `{"cursor": ...}` to keep a new one (any JSON, up to 1 MB) |
| `NOCLICK_LISTENER_TOKEN` | the `Authorization: Bearer` token both take; a new one is minted each time it starts |

A wake is delivered as a [webhook's](https://www.noclick.com/docs/guide/triggers.md#wake-it-with-a-webhook) is: the agent reads the body under the listener's name and its `message`, and wakes that come while it's busy ride its next turn. Send a `NoClick-Dedupe-Key` header with something that names the change (a message's id) and a repeat is a no-op (`duplicate`); `NoClick-Conversation` names the conversation, as does a `conversation` template over the body. A listener wakes its agent at most 20 times in 5 minutes unless it says otherwise ([below](https://www.noclick.com/docs/guide/listeners.md#how-often-it-wakes-its-agent)): past that, `429` with `Retry-After`, so a script looping on its URL can't run up your model's bill.

A script that wakes only when something changed keeps its place in its cursor, which NoClick keeps in a [dict](https://www.noclick.com/docs/guide/dicts.md) of the agent's own (`listener-<id>`):

```py
import json, os, urllib.request

def call(method, url, body=None):
    request = urllib.request.Request(url, method=method, data=json.dumps(body).encode() if body is not None else None,
                                     headers={"Authorization": "Bearer " + os.environ["NOCLICK_LISTENER_TOKEN"],
                                              "Content-Type": "application/json"})
    return json.load(urllib.request.urlopen(request))

seen = call("GET", os.environ["NOCLICK_CURSOR_URL"])["cursor"] or 0
hits = json.load(urllib.request.urlopen("https://hn.algolia.com/api/v1/search_by_date?query=acme&tags=story"))["hits"]
new = [h for h in hits if h["created_at_i"] > seen]
if new:
    call("POST", os.environ["NOCLICK_WAKE_URL"], {"posts": [h["title"] for h in new]})
    call("PUT", os.environ["NOCLICK_CURSOR_URL"], {"cursor": max(h["created_at_i"] for h in new)})
```

## How often it wakes its agent

Left out, `wake_limit` is 20 wakes in 5 minutes. A bursty source (a support inbox many visitors write to at once, a market stream) sets its own: `{"wakes": 120, "minutes": 1}`, `wakes` from 1 to 600 and `minutes` from 1 to 60, both whole numbers. Every attempt counts, a duplicate too, and past the limit a wake answers `429` with `Retry-After` (the window's seconds), naming the listener's own numbers. A higher limit refuses fewer wakes but doesn't start as many turns: wakes that come while the agent is busy ride its next turn together. Its trigger's `listener.wake_limit` reads what it is now, the default when it sets none.

```python
support.add_trigger(noclick.Listener("chat", always_on=True, command="python3 chat.py", repo="listeners",
                                     path="chat", wake_limit={"wakes": 120, "minutes": 1},
                                     message="Visitors wrote in. Answer each one."))
```

```ts
import { Listener } from "noclick";

await support.addTrigger(new Listener("chat", {
  alwaysOn: true, command: "python3 chat.py", repo: "listeners", path: "chat",
  wakeLimit: { wakes: 120, minutes: 1 }, message: "Visitors wrote in. Answer each one.",
}));
```

## Run it every few minutes

```python
WATCH = open("watch.py").read()

scout = noclick.Agent.from_name("scout", create_if_missing=True,
                                instructions="You tell the team about posts that mention Acme.")
scout.add_trigger(noclick.Listener("hn", every_minutes=15, command="python3 watch.py", files={"watch.py": WATCH},
                                   message="New posts mention us. Tell the team in one line each."))
```

```ts
import { Agent, Listener } from "noclick";

const WATCH = `...`; // the script above

const scout = Agent.fromName("scout", {
  createIfMissing: true, instructions: "You tell the team about posts that mention Acme.",
});
await scout.addTrigger(new Listener("hn", {
  everyMinutes: 15, command: "python3 watch.py", files: { "watch.py": WATCH },
  message: "New posts mention us. Tell the team in one line each.",
}));
```

Each run makes a sandbox, writes its files to its folder, runs `command` there up to `timeout_s` (120 seconds unless you say), and deletes the sandbox. A tick that comes while the last run still goes is skipped. Its trigger's `listener.last_run` says how the last run went (its exit, how long, how many times it woke the agent) and `listener.lines` its last output when it failed, every value it was handed taken out. Five failed runs in a row stop it until you resume it. A run your account can't pay for leaves it `paused`, and it runs again at its next time once there's money.

## Keep it running on your machines

```python
triage = noclick.Agent.from_name("inbox-triage")
triage.add_trigger(noclick.Listener("inbox", always_on=True, command="python3 idle.py",
                                    repo="listeners", path="inbox", secrets=["imap"],
                                    message="New mail. Sort it, and answer what you can."))
```

```ts
import { Agent, Listener } from "noclick";

const triage = Agent.fromName("inbox-triage");
await triage.addTrigger(new Listener("inbox", {
  alwaysOn: true, command: "python3 idle.py", repo: "listeners", path: "inbox", secrets: ["imap"],
  message: "New mail. Sort it, and answer what you can.",
}));
```

Its code is `files` or a [repo](https://www.noclick.com/docs/guide/repos.md) of yours (the folder `path` in it, at `ref`), read each time it starts. NoClick runs it in a container of its own on the least busy machine of yours that its agent may run on (a user's agent: that user's machines and your machines NoClick runs; your own computers: only your account's own agents), restarts it with backoff when it ends, and keeps its output. Pass `machine` to pin it to one machine, when it needs that box (its home network, a device on it).

When a machine goes away, its listeners don't: deleting a machine moves each one to another machine, and keeps where it moved from, when and why (`listener.moved`); a pinned one stops instead. Deleting your last machine is allowed: its listeners wait for a machine, and start by themselves on the next one you add. A computer of yours that stops answering for 5 minutes moves its listeners the same way (a pinned one waits for it); nothing moves back by itself when it returns. Before you delete a machine, its deletion preview (`POST /v1/delete_previews`) names which listeners go where, and its `impact.effects` says it as data: each listener's `outcome` (`moves`, with the machine it goes `to`; `stops`; `waits`).

## How it stands

```python
for trigger in triage.triggers():
    if trigger.listener:
        print(trigger.spec["name"], trigger.listener.state, trigger.listener.reason)

for item in noclick.listeners(machine=noclick.Machine.from_name("home-pc")):
    print(item.name, item.agent_name, item.status.state, item.status.moved)
```

```ts
import { Machine, listeners } from "noclick";

for (const trigger of await triage.triggers()) {
  if (trigger.listener) console.log(trigger.spec.name, trigger.listener.state, trigger.listener.reason);
}
for (const item of await listeners({ machine: Machine.fromName("home-pc") })) {
  console.log(item.name, item.agentName, item.status.state, item.status.moved);
}
```

| State | Means |
| --- | --- |
| `listening` | running (or between runs); `last_woke_at` says when it last woke its agent |
| `starting` | being placed, or its image fetched |
| `reconnecting` | its script ended and restarts, or its machine stopped answering a moment ago |
| `waiting` | no machine of yours it can run on runs listeners; it starts by itself on the next |
| `paused` | its trigger or agent is paused, its machine is stopped, or your account is out of funds for its runs |
| `stopped` | an error: its `lines` say what, and resuming it starts it again |

## Change it

`update_trigger` takes a new definition of the same name and kind: its code, secrets, schedule, machine and `wake_limit`, all of it (one left out goes back to its default), and starts it again when its code, command, secrets or machine changed. A new `message` or `wake_limit` alone applies from its next wake, the script running on. Pause and resume it as any trigger; removing it stops it where it runs and moves its cursor's dict to the trash.

```python
triage.update_trigger(trigger, listener=noclick.Listener("inbox", always_on=True, command="python3 idle.py",
                                                         repo="listeners", path="inbox", ref="v2", secrets=["imap"]))
```

```ts
import { Listener, type AgentTrigger } from "noclick";
declare const trigger: AgentTrigger;

await triage.updateTrigger(trigger, {
  listener: new Listener("inbox", {
    alwaysOn: true, command: "python3 idle.py", repo: "listeners", path: "inbox", ref: "v2", secrets: ["imap"],
  }),
});
```

Adding a recurring listener takes your key's `sandboxes` scope beside `agents`, an always-on one `machines`, and code from a repo `repos`.
