# Routines

A routine is work Adlass runs. Each belongs to one Space, where it is listed,
run and automated; `routines.search` and `routines.create` take the `space_id`
of the current route. `routines.search` returns compact rows to agent clients
(id, slug, name, summary, status); `view: "full"` adds per routine
`runs_30d`, `errors_30d` (FAILED), `last_status`, `recent_statuses` (the last
30 runs in that Space, oldest first, dry runs excluded), `entry_kind`
(`agent`, `script` or `script_agent`), `trigger_kinds` (the active triggers in
that Space: `schedule`, `event`, `webhook`; empty means manual runs only),
`paused` (its automation there is switched off) and `reauth_required` (a bound
connection needs to be reconnected).

A routine runs in one of three ways:

- Agent (no `entry`, or `entry: {"kind": "agent"}`): a model follows
  `instructions`.
- Script only (`entry: {"kind": "script", "alias", "escalate": false}`): one
  pinned script, never a model call; deterministic and cheap.
- Script with the agent as fallback (the same entry with `escalate: true`, the
  default when `escalate` is omitted).

Anything recurring is a routine with triggers (see Automation); a workflow
only chains several routines. A routine has an immutable active version (what
runs) and an optional draft (the working copy); `routines.get` returns both.
`routines.rename` changes the name at once, without a draft; everything else
(summary, instructions, inputs, outputs, scope, integrations, scripts,
settings) goes through the draft.

Instructions the user's own agent follows (a guide, also called a skill) are
not a routine: read_docs("guides").

## Flow

1. `routines.create` opens a draft, empty, with content, or from a template
   found with `routines.search` (`include_templates: true`). Each user holds one unsaved draft per
   `draft_key` (default empty); a call with different content fails with
   `routine_draft_exists`. To build several new routines in parallel (e.g. two
   agents), give each its own `draft_key`, such as the intended slug.
2. `routines.draft.save` replaces the whole working copy. Start from
   `routines.get` and send every field that should remain, changed or not; send
   the current `draft_revision` as `expected_revision`. The response carries
   `issues`, the same list `routines.validate` returns.
3. `routines.validate` checks the draft (or the published version when no draft
   exists) exactly like a publish and returns `valid` plus every issue with
   `path`, `code`, `message`, `hint` and `blocking`. Fix every blocking issue
   with another `routines.draft.save`, then validate again.
4. `routines.integration_bindings.list` with `skill_id` and `space_id` shows the
   integration requirements and which of them the caller has bound; before
   the first publish it reads them from the draft (`source: "draft"`).
5. `routines.save` publishes: it validates again, stores a new immutable
   version, makes it active and clears the draft. MCP clients may call it;
   in the in-app assistant it asks the user for approval. Publish only when
   the user asked for it, never as a follow-up to a rename or a draft save;
   otherwise report that the draft is still unpublished.
6. `routines.integration_bindings.set` binds each requirement to one of the
   caller's own active Space grants. Before the first publish it binds the
   draft's requirements, so the sandbox run can use them.
7. `routines.automation.set` sets the schedule and the run request of the
   routine in a Space (see Automation). Webhooks and platform events reach a
   routine through a queue (`queues.create` with the routine as consumer, then
   `queues.sources.set`; read_docs("queues")).

When changing a published routine the version already exists, so bindings and
automation can be set before the next `routines.save`.

Other operations: `routines.draft.discard` drops the working copy of a routine
that has an active version (a never-published routine is deleted with
`routines.delete` instead). `routines.restore` creates a new active version from
an earlier one and drops the draft; it asks the user for approval.
`routines.versions` lists versions. `routines.scripts.pin` (skill_id, alias or
script_id, version) publishes a new version that changes only one script pin
of the active version, with the same validation and gate as `routines.save`; no
draft round trip, and it refuses while the routine holds an unsaved draft
(`routine_draft_pending`: save or discard it first). `routines.delete` is
irreversible and always succeeds; `routines.delete_preview` tells beforehand
what it will do and what it stops. A routine without real runs is removed with
its sandbox runs and dry script runs (mode hard). A routine with run history,
active runs or queues is hidden instead (mode soft): it disappears from every
list and cannot run, be retried or consume a queue again (`routine_deleted`),
its runs stay readable with `routines.runs.list`/`routines.runs.get` (marked
as deleted) and its slug is free again. Its automations and the queues it
consumes are paused (queues keep holding deliveries until given another
consumer or deleted); active runs finish, or are cancelled with `force: true`.

## Runs

`routines.runs.start` (`skill_id`, `space_id`, `idempotency_key`, `inputs`,
`scope`) starts one run of the active version in a Space; runs cost credits.
`routines.models` lists the AI models a routine may use (`model`,
`reasoning_effort` override the defaults per run).

`inputs` carries exactly the keys of the definition's `inputs`; an unknown key
or a missing input with `required: true` fails with `invalid_run_inputs`
(details `missing` and `unknown` name the keys; a value of the wrong form names
`path` and the `expected` form).

| Input type | Value in `inputs` |
|---|---|
| `text` | a string of at most 4000 characters |
| `document` | exactly `{"document_id": "<uuid>"}`; the document is processed and lies inside the run's scope |

`scope` selects what the run may read: `document_ids`, `folder_ids` (the
processed documents directly in them), `record_type_ids`, or
`include_all_processed_documents: true` (not combined with document or folder
ids). Without a document or folder selection the run takes the definition's
`scope.documentIds` and `scope.folderIds`; `record_type_ids` defaults to
`scope.recordTypeIds` and must stay inside it. A document input therefore
needs its document in `scope.document_ids` or in a selected folder. `items`
(at most 1000 objects) hands data items to the run like a workflow
predecessor; with items, required inputs may be omitted and the scope may be
empty.

Outputs: a run must write every declared output, else it fails with
`model_invalid_output`; a routine may declare none, then its result is the run
summary and its effects come from the tools. Declare only what every run
produces. An `items` output is a JSON array of objects (checked against
`itemsSchema` when set) handed to the next node of a workflow
(read_docs("workflows")); it writes no records, the records tools do.

Dry runs: `dry_run: true` rehearses the active version; `sandbox: true` runs
the draft instead and is always a dry run. In a dry run every tool that writes
or sends (integrations, inbox, folders, files, records) returns a simulated
result marked `dry_run: true` (record upserts and entry appends return a
checked preview) and changes nothing; pages stay unpublished.

Sandbox gate: in the sandbox the agent may write scripts and run them dry, then
reports `sandbox_result`: `outcome` `ready` or `blocked` (its own judgement:
blocked only when a right, a connection or data is missing that a live run
would lack too, never because a simulated call returned no real value or the
draft declares no outputs; simulated side effects go to `would_write`), `blockers`, `scripts` (scripts it wrote, for the
author to adopt), `needed_rights` (integration operations and record types the
draft must still declare) and `would_write`. `routines.save` requires a
SUCCEEDED sandbox run of the same draft with outcome `ready` in which every
script version the agent wrote has a succeeded dry run (issue
`sandbox_run_missing` or `sandbox_run_stale` otherwise). A sandbox run of a
script entry is ready as soon as the script returned its result, exceptions
included (provider responses may be mocked or absent in the rehearsal); a
script that crashed is not. The sandbox of a script entry runs the script with
the parameters of the routine's live consumer in that Space (a queue with that
script entry first, else a schedule), merged over the entry's own
`parameters`; the agent sees them as `entry_script`. For a routine whose entry
is a script, when the definition differs from the active version only in the
versions of pinned scripts (same instructions, capabilities, integrations,
entry, aliases and set of scripts), a succeeded `scripts.runs.dry_run` of each
newly pinned version in a Space of the routine, started by someone who may
edit it, satisfies the gate instead of a sandbox run. Any other change still
needs the sandbox.

Following a run: `routines.runs.get` and `routines.runs.events` (pass the
returned `cursor` back as `cursor`; `after_event_id` is a deprecated alias)
show status, progress and results; both take `wait_seconds` (0-25) to wait
for a final state or new events instead of polling. `routines.runs.cancel`
stops a run. `routines.runs.replay` starts over with the same input and the
same documents, optionally with the current version; integration writes
without business_key run again, and after a crash they are never repeated
automatically. `routines.runs.revert_preview`, then `routines.runs.revert`
take back what a finished run created or changed in Adlass (pages, links,
records); integration calls are only listed for manual follow-up. Only the
most recent runs of a Space can be taken back (`undo_window_exceeded`).

## Agent tools

The run's agent always has `list_scope`, `search_scope`, `read_document`,
`query_facts`, `write_output`, `export_file` and the standard tools `tool__*`
(read_docs("tools")). The definition adds:

| Definition | Tools |
|---|---|
| a `page` output | `create_page`, `update_page` |
| records (see below) | `records_describe`, `records_query`, `records_get`, `records_create`, `records_update`, `records_upsert_many`, `records_archive`, `records_entries_list`, `records_entries_get`, `records_entries_append`; `derivations_preview`, `derivations_run` for derivations whose source and target type lie in the run's record types |
| `inboxAccess` | `send_inbox_message`, `import_reply_attachments`, `import_thread_attachments` |
| `documentActions` | `list_folders`, `move_document`; `create_folder` with `createFolders: true`; `rename_document` with `rename: true` |
| `partnersAccess` | `partners_list_objects`, `partners_get_object`, `partners_list_entries`, `partners_list_obligations`; with `mode: "write"` also `partners_add_entry`, `partners_create_object`, `partners_invite` |
| `settings.webSearchEnabled` | `web_search` |
| `settings.browserEnabled` | `browser_*` (not in dry runs) and `dian_*` |
| bound `integrations` and `emailAccess` | `integration__<key>__<resource>__<operation>` per enabled operation (none for `mode: "direct"`); `wait_for_reply` when one of them can wait for a reply |
| `scripts` | `run_script__<alias>` per pinned script |
| `settings.agentScriptsEnabled` (always in a sandbox) | `scripts_list`, `script_read`, `script_write`, `script_run` |

Script tools, `settings.subagentsEnabled` or input items add the working
directory tools `workspace_list`, `workspace_read`, `workspace_search`,
`workspace_write`.

Records tools exist only when the routine uses records (`records` in
`capabilities` or a non-empty `scope.recordTypeIds`) and the run's scope has
`record_type_ids` (filled from `scope.recordTypeIds`, see Runs); then reading
and writing come together. A run writes at most the record limit of
read_docs("records"), and `routines.runs.revert` takes its record writes back.

## Automation

`routines.automation.set` (`space_id`, `skill_id`, `idempotency_key`,
`schedule`, `run`) holds one schedule per routine and Space (kind `rule`,
`cron` or `once`; `workflows.schedule.preview` shows the next run times) and
the run request `run` (`inputs`, `scope`, `instruction`). A key you omit keeps
what is stored: send only `run` to change the run request, only `schedule` to
keep it. Send `schedule: null` only to delete the schedule. An active schedule
needs a published version; a `run` with scope, inputs or an instruction needs a
schedule, and `run.scope.record_type_ids` needs `records` in the routine's
capabilities. The result is the effective automation (the shape of
`routines.automation.get`) plus `changes` (`{schedule|run: {from, to}}`, empty
when nothing changed) and `removed` (`["schedule"]` when the schedule was
deleted). When an agent or API key deletes a schedule, the routine's creator
and the person the schedule ran as get a notification; the audit row says the
schedule was removed.

The schedule's `entry` `{"kind": "agent"}` (default) starts the routine's
agent with the run request; `{"kind": "script", "alias", "parameters",
"escalate"}` runs one pinned script without a model call. A script entry needs
the caller's own integration bindings.

- `escalate: false`: the agent never runs. A script run that returned its
  result closes the routine run SUCCEEDED even when single items carry
  exceptions (`ctx.exception` or the returned `exceptions`); they stay on the
  script run (`scripts.runs.output`, `exceptions_count`) and in the routine
  run's open points, for the caller to review. Only a script that crashed,
  timed out, was cancelled or was refused by the checker closes the run FAILED.
- `escalate: true` (default): a script that failed or returned exceptions hands
  over to the agent, except after a cancellation or when an external effect
  may already have happened (a pending integration call, a started integration
  write without `business_key`, browser use); the run then fails.

The person who requested a run (for automations the automation's actor) gets
a notification when it fails, at most one per routine, Space and day. When the
agent takes over a failed script, a notification says so at once, and the agent's
summary and open points follow in the same thread when it finishes.

Webhooks (Shopify, Amazon SES over SNS, any sender with a shared secret or an
HMAC signature) and platform events never start a routine directly: they add
items to a queue whose consumer is the routine's agent or one of its pinned
scripts, and the queue runs them in batches with retry and dead letter. See
read_docs("queues").

## Flows that wait for people

A run that must wait for a person (a reply in a chat thread, a file sent
back) waits in one of two ways:

- Agent: the routine's agent sends with an `integration__*` tool and calls
  `wait_for_reply` with that call's `invocation_id`; the run shows WAITING
  and the agent continues with the outcome. Use it when every reply needs
  judgement.
- Script entry (`entry: {"kind": "script", "alias"}`): the pinned script sends,
  calls `ctx.wait_for_reply` and returns; the platform runs it again with
  `ctx.resume` (read_docs("scripts"), example "wait for a reply in a
  thread"). Use it when the steps are fixed: no model call per reply,
  deterministic, cheap. `escalate: true` hands a failed chain to the agent.

The run's inputs (manual values or a workflow node's `input_mapping`) reach
the entry script as `ctx.inputs` (the reserved `_inputs` parameter, never
declared in `input.parameters`); the entry's `parameters` arrive as `params`,
the predecessor's items as `items`. Pin the script with an explicit
`version`; a new version runs only after its dry run, a new pin and
`routines.save`. The routine enables the integration operations the script calls
(`messages.send` under `integrations[].operations`), lists the record types in
`scope.recordTypeIds` and the folders in `documentActions`, and every user who
runs or schedules it binds the integration requirements
(`routines.integration_bindings.set`); unbound requirements block the entry.

## Rules

- `instructions` and `capabilities` are required for a publish.
  `capabilities` is explicit: list every capability the routine uses. Known
  capabilities: browser, email, folders, inbox, integrations, items-output, pages, partners, persistent-output, records, reviewer, sheet-output, web-search.
- Records: a routine that reads or writes records lists `records` in
  `capabilities` and the record type ids in `scope.recordTypeIds`
  (`records.types.list` returns them). Scripts and the agent's records tools
  (see Agent tools) reach only record types in that scope.
- `steps` no longer exists and is rejected; write the order as numbered lines
  in `instructions`.
- The definition model is strict: unknown fields fail on every level. Inputs
  need `key` (lowercase letters, digits, `_`), `type` (`text` or `document`)
  and `label`, optionally `description` and `required` (default false);
  outputs need `key`, `type` (`doc`, `sheet`, `page` or `items`) and
  `nameTemplate`; keys are unique. Integrations need `key`, `providerKey`
  and `operations` of `{resource, operation}`; their optional `mode` is
  `curated` (typed operations become agent tools) or `direct` (only `http.get`
  and `http.request`, usable from scripts alone); without `mode` both kinds
  behave as before. Scripts need `scriptId`, an
  explicit `version` and an `alias`. `entry: {"kind": "script", "alias"}`
  needs that alias under `scripts` and exactly one output, of type `items`;
  any further output is rejected.
- A `page` output is an app page (read_docs("pages")): the run writes
  `{source, manifest}` (an HTML document), checked like saving a page
  version (manifest against the Space, build); no `downloads`, and file
  inputs need `folderId` on the output. `adlass-document:<id>` images need
  the download right of the person who started the run. The page is created,
  already built, when the run succeeds; the team sees it at once. A run never
  shares it: a person releases it when sharing it. A page a person shared
  stays current through its live data, so a recurring routine does not
  create it again.
- Field bindings under `integrations[].operations[].fields` are `fixed`
  (`value`) or `choice` (`values`); they are checked against the provider's
  operation contract.
- Integration requirements are logical: the definition never stores grants
  or connections. Each person binds each requirement to one of their own
  active grants, separately per routine and Space; unbound requirements block
  runs and script entries (`integration_binding_required`). A binding stores
  the requirement's operations: after a publish that changes them, bind again
  (`integration_binding_invalid`).
- A binding to a personal grant (not shared with the Space's members) runs
  only versions the binding's owner published or confirmed. After someone
  else publishes, the owner reviews the version and calls
  `routines.integration_bindings.confirm` (`space_id`, `skill_id`, optional
  `version_id` of the current version); until then that person's runs,
  schedules and queues of the routine fail with
  `integration_binding_unconfirmed`. Sandbox runs need no confirmation.
- `emailAccess` (`read`, default true; `readAttachments`; `lookbackDays` 1-90)
  adds the requirement `email` with provider `imap` (operations
  `messages.search`, `messages.get`, with `readAttachments` also
  `attachments.list`, `attachments.import`); bind it to an IMAP connection.
  `send: true` is rejected.
- `variables` lists up to 20 names of Space variables (uppercase letters,
  digits, `_`; `spaces.variables.list`) that pinned scripts may read with
  `ctx.env.get`. The definition carries only names; each Space sets its own
  values, and a script whose variable is not set there fails at start.
- Integration writes about one business object take `business_key`
  (`<authority:type:id>#<action>`, e.g. `acme.example:invoice:INV-1001#post`).
  Derive it from the object, never from the run: a rerun with the same key
  returns the first result instead of writing again.
- Folder and document ids come from `documents.folders_list` and
  `documents.list`; never invent ids.
- A publish checks: name and summary present, the definition model, field
  bindings, the pinned scripts (they belong to the routine, the version exists,
  the static check passed, slots and operations match the routine's
  integrations, the variables the scripts read are listed under `variables`,
  record types lie in the scope, every `@script:<alias>` in the
  instructions is pinned) and the settings the platform offers
  (`agentScriptsEnabled`, `subagentsEnabled`, `securityReviewEnabled` needs
  the plan feature). An outdated pinned version, a missing dry run and record
  types outside a declared record scope are hints and do not block.
- Importing an automation from another tool (an attached export, JSON, YAML or
  a process description) is information, not a routine to copy: map what the
  draft supports (instructions, inputs, outputs, scope, integration
  requirements, settings); ids, input and output keys, bindings and fields of
  the other system do not transfer. List in the
  answer what was left out.

## Errors and fixes

- `validation_error` from `routines.save`: `details` maps each definition path
  (for example `outputs.0.nameTemplate`, `capabilities`, `scripts.1`) to its
  message. Call `routines.validate` for the full list with hints, fix the draft,
  validate again.
- `script_target_out_of_scope`: a pinned script reads or writes record types
  the routine cannot reach. Blocking when `capabilities` lacks `records` and
  `scope.recordTypeIds` is empty: add both. A hint when the record types are
  only missing from `scope.recordTypeIds`: add their ids.
- `script_variable_unknown`: a pinned script reads variables the routine does
  not list under `variables`. Add the names, or pin a version without them.
- `routine_draft_exists` (409) from `routines.create`: you already hold an
  unsaved draft. Read it with `routines.get(details.skill_id)` and continue it
  with `routines.draft.save`, delete it with `routines.delete`, or call
  `routines.create` again with a distinct `draft_key` for a separate draft.
- `draft_revision_conflict` (409): the draft changed elsewhere. Read it again
  with `routines.get` and retry with the current `draft_revision`.
- `automation_run_scope_requires_trigger`: `run` carries a scope, inputs or
  an instruction, but the schedule is missing. Send a schedule in the same
  call, or send `schedule: null` with `run` of empty inputs and scope to remove
  the automation.
- `routine_not_saved` (409): the operation needs a published version. Call
  `routines.save` first.
- `sandbox_run_missing` / `sandbox_run_stale` (path `sandbox`): start
  `routines.runs.start` with `sandbox: true` on the draft. For a script entry
  where only script versions changed, a succeeded `scripts.runs.dry_run` of
  each new version is enough (see Runs), e.g. through `routines.scripts.pin`.
- `integration_binding_required` / `integration_binding_invalid`
  (`requirement_keys` names them): bind those requirements with
  `routines.integration_bindings.set`.
- `integration_binding_unconfirmed` (409): the binding's owner calls
  `routines.integration_bindings.confirm` (see Rules); paused queues then
  resume on their own.

## Example

A routine that receives Shopify orders by webhook and writes them to records
through a script. The script `orders` was created with `scripts.create`,
tested with a dry run and is pinned in version 3.

```json
{
  "name": "Order sync",
  "summary": "Writes every new Shopify order into the Orders records.",
  "instructions": "1. Run @script:orders with the delivered orders.\n2. When the script reports exceptions, check each order and explain what is missing.",
  "capabilities": ["integrations", "items-output", "records"],
  "scope": {"recordTypeIds": ["<orders record type id>"]},
  "integrations": [
    {
      "key": "shop",
      "providerKey": "shopify",
      "operations": [{"resource": "orders", "operation": "get"}]
    }
  ],
  "outputs": [
    {"key": "orders", "type": "items", "nameTemplate": "Synced orders"}
  ],
  "scripts": [
    {"scriptId": "<script id>", "version": 3, "alias": "orders"}
  ],
  "entry": {"kind": "script", "alias": "orders", "escalate": true}
}
```

Send it as the `draft` of `routines.draft.save`, check it with
`routines.validate`, publish with `routines.save` (the same fields, with name,
summary, categories and tags as separate arguments and the rest as
`definition`), bind `shop` with `routines.integration_bindings.set`, then create
a queue with the script as consumer and the Shopify webhook as source:

```json
{
  "space_id": "<space id>",
  "slug": "shopify-orders",
  "name": "Shopify orders",
  "skill_id": "<routine id>",
  "entry": {"kind": "script", "alias": "orders"},
  "batch_size": 1,
  "max_concurrency": 1
}
```

```json
{
  "queue_id": "<queue id>",
  "webhook": {
    "auth": "integration",
    "integration": {
      "provider_key": "shopify",
      "mode": "subscription",
      "grant_id": "<grant id>",
      "events": ["orders/create"]
    }
  }
}
```

The first is `queues.create`, the second `queues.sources.set`. Each order
arrives as one item; `queues.items.list` shows them and `queues.items.get`
shows a delivery's payload (body is the provider object).

The same routine as a nightly import instead of a webhook: the script lists the
orders itself with `ctx.integrations.call` (the routine's integrations then
include `orders.list`), and the schedule carries the script entry:

```json
{
  "space_id": "<space id>",
  "skill_id": "<routine id>",
  "schedule": {
    "kind": "rule",
    "rule": {"unit": "day", "times": ["06:00"]},
    "timezone": "America/Bogota",
    "active": true,
    "entry": {"kind": "script", "alias": "orders", "escalate": true}
  },
  "run": {"inputs": {}, "scope": {"record_type_ids": ["<orders record type id>"]}}
}
```

Check the schedule with `workflows.schedule.preview` and show the user the
next run times first. No workflow is needed for this.
