Triggers

Triggers: what wakes an agent besides a message.

fulfilment = noclick.Agent.from_name(
    "fulfilment", create_if_missing=True, instructions="You confirm new orders with the customer.",
    triggers=[noclick.OnWebhook(name="orders", message="A new order arrived.")],
)

An OnWebhook gives it a URL whose POST body is the turn, an OnEvent subscribes it to a connection's app events, an OnPlatformEvent to NoClick's own events (an operation failing, a connection breaking), and a Cron wakes it on a schedule (an agent with one is an automation), and an OnQueue makes each message on a queue a turn. Mail and calls wake it too, set up where they live (Inbox(agent=), PhoneNumber.answer_with); triggers() lists them as kinds email and call, and while its policy may hold one of its tools for a person, as kind approval: an answered approval wakes it in the held call's conversation.

A webhook, app event or queue trigger takes conversation=, a template over what arrived ("issue-{issue.number}"): deliveries that render the same key continue one conversation, and the turn's operation records the key as input["conversation"].

Cron

noclick.Cron(expr, tz='UTC', message=None)

A schedule: a five-field cron expression (minute, hour, day of month, month, day of week: numbers, *, ranges, steps, lists and month or day names) read in a timezone, so "0 9 * * 1-5" with tz="America/New_York" means 9am New York time on weekdays, daylight saving included. When both day fields are restricted a run must match both. An agent's schedule wakes the agent with message as the turn (each run a conversation of its own); a wake-up's every wakes one conversation at each time, with its note (a routine: agent.wake); a channel's posts message in the room; an app's calls one of its paths. tz="user" reads it in a user's agent's (or channel's) user's timezone, following them when they move (UTC while they have none; an account agent refuses it, having no user); a wake-up reads it in the timezone of the user whose conversation it wakes.

Every agent turn is told the date and time, so a schedule's message can say "last month" or "this week" and mean it.

Parameters
exprstrrequired
tzstr

An IANA timezone, or "user": the agent's user's timezone, followed when they move.

(default 'UTC')
messagestr | None

The turn's text when this schedule wakes an agent; apps ignore it.

(default None)
Usage

Wake an agent every weekday morning:

digest = noclick.Agent.from_name(
    "digest", create_if_missing=True, instructions="You summarize the overnight tickets.",
    triggers=[noclick.Cron("0 8 * * 1-5", tz="Europe/London", message="Post the overnight summary")],
)

Call an app's path every hour:

app = noclick.Project.from_name("booking")
app.schedule(noclick.Cron("0 * * * *"), path="/jobs/reminders")

Brief each user at 8am where they are:

with noclick.as_user("user_42"):
    assistant = noclick.Agent.from_name("assistant")
    assistant.add_trigger(noclick.Cron("0 8 * * *", tz="user", message="Brief me on today's calendar"))
Attributes
exprstr
tzstr

An IANA timezone, or "user": the agent's user's timezone, followed when they move.

messagestr | None

The turn's text when this schedule wakes an agent; apps ignore it.

OnWebhook

noclick.OnWebhook(name, message=None, conversation=None)

A URL that wakes the agent: each POST to it is a turn, its body the message (a JSON body is passed as JSON). The URL is AgentTrigger.url; anyone who has it can wake the agent, so keep it like a key. It stays the same while a trigger of that name stays on the agent. message is what the agent is told with every delivery, above the body.

Parameters
namestrrequired
messagestr | None

Standing instructions sent with each delivery, above its body. A channel can subscribe to one too (channel.subscribe(noclick.OnWebhook(...))), its POSTs posted in the room.

(default None)
conversationstr | None

The conversation a delivery continues: a template over its body, "order-{order.id}"; a NoClick-Conversation header wins.

(default None)
Usage

Let your order system wake an agent:

fulfilment = noclick.Agent.from_name(
    "fulfilment", create_if_missing=True, instructions="You confirm new orders with the customer.",
    triggers=[noclick.OnWebhook(name="orders", message="A new order arrived. Confirm it with the customer.")],
)
[orders] = fulfilment.triggers()
print(orders.url)   # POST your order JSON here

Keep each order in one conversation, keyed by a field of the body:

fulfilment = noclick.Agent.from_name("fulfilment")
fulfilment.add_trigger(noclick.OnWebhook(name="order-updates", conversation="order-{order.id}"))
Attributes
namestr
messagestr | None

Standing instructions sent with each delivery, above its body. A channel can subscribe to one too (channel.subscribe(noclick.OnWebhook(...))), its POSTs posted in the room.

conversationstr | None

The conversation a delivery continues: a template over its body, "order-{order.id}"; a NoClick-Conversation header wins.

OnEvent

noclick.OnEvent(connection, event, *, message=None, conversation=None, **filters)

An app event from one of the agent's connections, such as a Slack message or a new HubSpot contact. connection is a Connection or its name, the agent's own user's (an account agent's may be one connected in the app, credential:<id>); event names one of the integration's app events (channel_message for Slack, contact_created for HubSpot; list them with connection.events()) and each keyword argument narrows it the way the integration takes it, like channel="C0123ABCD" (a Slack channel's id: slack.lookup("channel") lists them). message is what the agent is told with every event, above it. A thread (a Slack thread) stays one conversation, so the agent's replies land in it. conversation keys conversations yourself, a template over the event as the app sent it: "issue-{issue.number}" keeps everything about one issue in one. A channel subscribes to the same events (channel.subscribe(noclick.OnEvent(...))), each posted in the room. The connection needn't be connected yet: the trigger is error until it is.

Parameters
connectionAnyrequired
eventstrrequired
messagestr | Nonedefault None
conversationstr | Nonedefault None
**filtersAny
Usage

Answer every message in a Slack channel:

slack = noclick.Connection.from_name("slack", integration="slack", create_if_missing=True)
support = noclick.Agent.from_name(
    "support", create_if_missing=True, instructions="You answer questions in #support.",
    tools=[slack],
    triggers=[noclick.OnEvent(slack, "channel_message", channel="C0123ABCD")],
)

Or wake a sales agent for each new contact:

sales = noclick.Agent.from_name("sales")
sales.add_trigger(noclick.OnEvent("hubspot", "contact_created", message="Research this contact and draft a first email."))

Pick up GitHub issues when they're labelled, one conversation per issue:

github = noclick.Connection.from_name("github", integration="github", create_if_missing=True)
triage = noclick.Agent.from_name("triage")
triage.add_trigger(noclick.OnEvent(github, "issue_labeled", repository="acme/api", conversation="issue-{issue.number}"))
Attributes
connectionAny
eventstr
filtersdict[str, Any]
messagestr | None
conversationstr | None
connectionAny
eventstr
filters
messagestr | None
conversationstr | None

OnPlatformEvent

noclick.OnPlatformEvent(type, filters=None, message=None, conversation=None)

One of NoClick's own events (the types noclick.Event.types() lists, as your webhooks receive them): an operation failing, a connection breaking, a channel halting, a workflow's run failing, an agent built in the app asking for you, a payment going through. type names one, and * matches the rest of a name ("operation.*"); filters are dotted paths into the event's data and the values they must have. message is what the agent is told with every event, above it; conversation keys conversations by a template over the event ("connection-{data.id}"), else each event is a conversation of its own.

The agent hears its user's events, and an agent of your account's hears every event, your users' included. It never hears what its own turns caused (its turn finishing), and a chain of agents waking each other this way stops five turns deep. A channel subscribes to the same events (channel.subscribe(noclick.OnPlatformEvent(...))).

Parameters
typestrrequired
filtersdict[str, Any] | Nonedefault None
messagestr | Nonedefault None
conversationstr | Nonedefault None
Usage

Have an agent look into every failed job of your coding agents:

triage = noclick.Agent.from_name(
    "triage", create_if_missing=True, instructions="You find out why work failed and say what to do.",
    triggers=[noclick.OnPlatformEvent("operation.failed", filters={"kind": "agent.task"},
                                      message="A job failed. Find out why.")],
)

One conversation per broken connection:

support = noclick.Agent.from_name("support")
support.add_trigger(noclick.OnPlatformEvent("connection.disconnected", conversation="connection-{data.id}",
                                            message="Tell the user how to reconnect it."))

Watch over the workflows built in the app, one conversation per workflow:

ops = noclick.Agent.from_name("ops")
ops.add_trigger(noclick.OnPlatformEvent("workflow.run.failed", conversation="workflow-{data.workflow_id}",
                                        message="A workflow failed. Find out why; pause it if it's useless."))
Attributes
typestr
filtersdict[str, Any] | None
messagestr | None
conversationstr | None

OnQueue

noclick.OnQueue(queue, *, message=None, batch_size=1, conversation=None)

Each message on a queue becomes a turn: the agent reads message (its standing instructions, if any) and then the message's JSON body. With batch_size above 1 (up to 25), one turn takes up to that many waiting messages at once, as a JSON list, for work that's cheaper in bulk. queue is a Queue or its name, the agent's own user's.

Delivery follows the queue's rules: a turn that finishes acks its messages; a turn that fails hands them back for another try (after 30 seconds per attempt they've had), and a message that fails the queue's max_attempts times becomes a dead letter, the turn's error its last_error. Each turn is a conversation of its own, unless conversation keys it from the message (one message a turn only). The agent takes one turn at a time, in order; for more throughput raise batch_size, or put several agents on the queue. While the agent is paused, messages wait.

When the agent's budget, its user's cap or your account's funds run out, the trigger pauses instead of failing turns: messages wait with their attempts unchanged, the trigger's status is error saying why, and it carries on by itself once there's money to spend again (it looks every half minute).

Parameters
queueAnyrequired
messagestr | Nonedefault None
batch_sizeintdefault 1
conversationstr | Nonedefault None
Usage

Let an agent work through a queue your app fills:

invoices = noclick.Queue.from_name("invoices", create_if_missing=True)
support = noclick.Agent.from_name(
    "support-bot", create_if_missing=True, instructions="You chase unpaid invoices by email.",
    tools=["gmail.send_email", "stripe.list_invoices"],
    triggers=[noclick.OnQueue(invoices, message="Chase this unpaid invoice.")],
)
invoices.put({"invoice": "INV-1042", "customer": "acme"})

Ten messages a turn, by the queue's name:

digest = noclick.Agent.from_name("digest")
digest.add_trigger(noclick.OnQueue("webhook-buffer", batch_size=10, message="Summarize these events."))

Each customer's messages in their own conversation:

enrich = noclick.Agent.from_name("enrich")
enrich.add_trigger(noclick.OnQueue("signups", conversation="customer-{customer_id}"))
Attributes
queueAny
messagestr | None
batch_sizeint
conversationstr | None
queueAny
messagestr | None
batch_sizeint
conversationstr | None

Listener

noclick.Listener(
    name, *, command, files=None, repo=None, path=None, ref=None, every_minutes=None,
    always_on=False, machine=None, secrets=None, timeout_s=None, message=None,
    conversation=None, wake_limit=None
)

A script NoClick runs that wakes the agent when something changes: something no app's webhook tells NoClick about (a mailbox, a price stream, a page, a feed). Its code is files (a path in its folder to the file's text) or a repo of yours (the folder path in it, at ref), run with command in its folder.

With every_minutes it's recurring: every 1 to 30 minutes or 1 to 24 hours it runs once in a NoClick sandbox (Python and Node, the network open), up to timeout_s (120 by default), billed by the second as any sandbox. With always_on=True it keeps running on one of your machines (holding a connection open: IMAP IDLE, a WebSocket, MQTT); NoClick picks the least busy one, restarts the script if it dies, and moves it when that machine goes away. machine pins it there (it then never moves, and stops if that machine is removed).

It's handed, in its environment, NOCLICK_WAKE_URL, NOCLICK_CURSOR_URL and NOCLICK_LISTENER_TOKEN, and the keys of its secrets (your secrets, by name or Secret); nothing else of your account's. It wakes the agent with POST $NOCLICK_WAKE_URL (Authorization: Bearer $NOCLICK_LISTENER_TOKEN, a JSON body of what changed; NoClick-Dedupe-Key makes a repeat a no-op), and keeps its place with GET/PUT $NOCLICK_CURSOR_URL ({"cursor": ...}). message and conversation work as an OnWebhook's.

It wakes the agent at most 20 times in 5 minutes (past that a wake answers 429, every attempt counted), unless wake_limit says otherwise for a bursty source: {"wakes": 120, "minutes": 1}, wakes 1 to 600 and minutes 1 to 60. Wakes that come while the agent is busy ride its next turn together, so a higher limit refuses fewer wakes without starting as many turns.

Parameters
namestrrequired
commandstrrequired
filesdict[str, str] | Nonedefault None
repoAnydefault None
pathstr | Nonedefault None
refstr | Nonedefault None
every_minutesint | Nonedefault None
always_onbooldefault False
machineAnydefault None
secretslist[Any] | Nonedefault None
timeout_sint | Nonedefault None
messagestr | Nonedefault None
conversationstr | Nonedefault None
wake_limitdict[str, int] | Nonedefault None
Usage

Check Hacker News for posts about you every 15 minutes, waking the agent only for new ones:

watcher = '''
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 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)})
'''
scout = noclick.Agent.from_name("scout")
scout.add_trigger(noclick.Listener("hn", every_minutes=15, command="python3 watch.py",
                                   files={"watch.py": watcher}, message="New posts mention us."))

Keep a mailbox open on one of your machines, its code in a repo:

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"]))

Let a busy chat widget wake its agent up to 120 times a minute:

support = noclick.Agent.from_name("support")
support.add_trigger(noclick.Listener("chat", always_on=True, command="python3 chat.py",
                                     repo="listeners", path="chat",
                                     wake_limit={"wakes": 120, "minutes": 1}))
Attributes
namestr
commandstr
filesdict[str, str] | None
repoAny
pathstr | None
refstr | None
every_minutesint | None
always_onbool
machineAny
secretslist[Any]
timeout_sint | None
wake_limitdict[str, int] | None

How often its script may wake the agent, {"wakes", "minutes"}; None: 20 in 5 minutes.

messagestr | None
conversationstr | None
secrets
timeout_s
wake_limit

ListenerItem

class ListenerItem

One of your listeners, as noclick.listeners() reads it: its trigger's id, its name, its agent, what it was defined with (spec) and how it stands (status).

Attributes
idstr
namestr
agent_idstr
agent_namestr | None
specdict[str, Any]
statusListenerStatus
created_atAny
rawdict[str, Any]

The response JSON exactly as the API sent it.

ListenerMove

class ListenerMove

Where a listener moved from, when and why (its machine was removed, or stopped answering).

Attributes
from_machine_idstr | None
from_machinestr | None
atAny
whystr | None

ListenerRun

class ListenerRun

A recurring listener's last run: when, its exit (None: it was stopped, or never started), how long, and how many times it woke its agent.

Attributes
atAny
exit_codeint | None
duration_sfloat | None
wokeint

ListenerStatus

class ListenerStatus

A listener as it stands. state is listening (last_woke_at says when it last woke its agent), starting, reconnecting (its script ended and restarts, or its machine stopped answering a moment ago), waiting (for a machine: none of yours it can run on runs listeners; it starts by itself on the next), paused (its trigger or agent is, its machine is stopped, or your account is out of funds for its runs) or stopped (an error, which its lines show); reason says it in words. moved keeps where it last moved from; nothing moves back by itself.

Attributes
runstr
statestr
reasonstr | None
machinedict[str, Any] | None

Where an always-on one runs now ({"id", "name", "status"}; offline: it stopped answering), and the machine it's pinned to.

pinnedbool
pinned_machinedict[str, Any] | None
movedListenerMove | None
last_woke_atAny
every_minutesint | None
timeout_sint | None
next_run_atAny
last_runListenerRun | None
restartsint
lineslist[str] | None

The last lines it printed, whatever its state (at most 20, each cut at 500 characters, every value it was handed taken out): an always-on one's as its machine last reported them, while it runs too; a recurring one's from its last run, whether it went fine or failed. None before its first run or its machine's first report.

started_atAny
dict_idstr | None

The dict its cursor is kept in (made at its first write).

wake_urlstr | None

Where its script wakes its agent and keeps its place (with the token it's handed).

cursor_urlstr | None
rawdict[str, Any]

The response JSON exactly as the API sent it.

wake_limitdict[str, int] | None

How often its script may wake its agent, {"wakes", "minutes"}: its own, else 20 in 5 minutes.

listeners

noclick.listeners(
    *, machine=None, agent=None, user=..., client=None
) -> list[ListenerItem]

Every listener of your agents (a user's own alone, with user=), each with its agent, where it runs and how it stands. machine (a Machine or its id) keeps those placed on it or pinned to it, which is what removing it moves; agent (an Agent or its id) keeps one agent's. A listener is added, changed, paused and removed as its agent's trigger (agent.add_trigger(noclick.Listener(...))).

Parameters
machineAnydefault None
agentAnydefault None
userAny

Who the call acts for. Defaults to the user set by noclick.as_user (none: the account itself).

(defaults to the current user)
clientClient | None

The client to send with; defaults to the module client built from NOCLICK_API_KEY.

(default None)
Returns
list[ListenerItem]

Each listener: its name, agent_name, spec and status (state, reason, machine, moved, last_woke_at, last_run, lines).

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

AgentTrigger

class AgentTrigger

One thing that wakes an agent, as agent.triggers() reads it.

kind is cron, webhook, event, platform, queue, email, call, approval, app, channel or routine; spec is its definition (name for a webhook; connection, event and filters for an app event; type and filters for a NoClick event; message and conversation where they were given; inbox_id and address for email; phone_number_id and number for calls; cron, tz and message for a schedule; queue and batch_size for a queue; tools, the ones policy may hold, for an approval; step, name, type and operation for a trigger wired into the agent in the app, as a step of its workflow, and changed only there; channel_id, name and mode for a channel it sits in; cron, tz, note and conversation for a recurring wake-up, changed through agent.wakeups). An approval trigger is there while your policy may hold one of its tools for a person: an answered approval wakes it in the held call's conversation. state is live, paused (the agent, or the trigger itself: paused says which) or stopped (it can't fire), reason says why in words and fix what makes it live again ({"action": ...}: resume_agent, resume, connect or replace with its connection, or open_in_app). status is the older reading of it: active, paused or error, with error saying why it can't fire (a connection that isn't connected, say, a queue's turns waiting for money, or its turns failing the same way five times in a row, which stops it until it or the agent is resumed). set_by says who set it up ({"kind": "person" | "agent" | "automation", "agent_id": ...}), read_only whether it's changed only where it lives, and actions what it takes here (pause, resume, test, update, remove).

Attributes
idstr
kindstr
specdict[str, Any]
statusstr
urlstr | None

The URL a webhook trigger listens at (None for other kinds).

next_runAny

When a schedule next wakes the agent (None for other kinds, and while paused or in error).

last_fired_atAny
errorstr | None
created_atAny
rawdict[str, Any]

The response JSON exactly as the API sent it.

pausedbool

Paused on its own (agent.pause_trigger), its agent running on.

runningbool

A turn it started is queued or running (for a channel, the agent's turn there).

statestr
reasonstr | None
fixdict[str, Any] | None
next_run_atAny

When a schedule or a recurring wake-up comes round next, paused or not (None for other kinds).

set_bydict[str, Any]
read_onlybool
actionslist[str]
titlestr | None

An app event's in a few words ("Messages to +1 202-555-0101"); None for other kinds.

summarydict[str, Any] | None

What an app event hears through: app, integration, icon (the node type its mark is drawn by), credential_type, account (as Connections names it), number (E.164, a phone's), hears, groups, status (connected, pending, disconnected or missing), and problem and remedy while it isn't linked. None for other kinds.

listenerListenerStatus | None

A listener's: where it runs, its state and why, where it moved from, its last run (None for other kinds).

definedbool

Whether your code defines it (cron, webhook, event, platform, queue); email and call come from an inbox or a phone number and are changed there, approval from your policy, app from the agent's workflow in the app, channel from the channels it sits in and routine from its wake-ups.