Scripts

Contract, ctx API, derived capabilities, static rules and the path to a live run.

Raw Markdown for agents: scripts.md. MCP: read_docs("scripts").

A script is a small, deterministic Python program that the platform runs in a sandbox. It has no network and no imports beyond an allowlist; everything it may touch goes through one object, ctx. A script belongs to exactly one routine (scripts.create takes skill_id). Every version is immutable and every live run records its write effects.

You write only code. scripts.versions.create takes the source, a one-line purpose and optionally a description, input and output JSON schemas and limits. The platform derives from the ctx calls what the script reads, writes and calls (record types, folders, documents it creates, integrations and operations, browser hosts and login, variable names, files, log) and stores that as the version's manifest. There is no approval of a script by itself: a routine decides where it runs.

Flow

  1. scripts.create with skill_id.
  2. scripts.versions.create with source and purpose. Fix static-check findings (static_check.findings) and readiness.violations first; each fix is a new version. script_runtime_outdated (503) means the deployed script runtime enforces another static-checker version than the platform (details.platform_checker_version, details.runtime_checker_version): a platform problem, not a script problem. Do not rewrite the script; report it and retry after the runtime is refreshed. The source comes in exactly one of three ways: source (the full text); source_document_id, a UTF-8 text file of at most 128 KB in the routine's Space that you may download (upload it with documents.upload_initiate, your PUT and documents.upload_confirm with reading="code", so a large source never travels through the call); or patch, a unified diff against parent_version_id (the format of scripts.versions.diff). A patch is applied hunk by hunk; a hunk not at its stated line is searched for after the previous one. script_patch_conflict names the first hunk whose context or removed lines do not match the parent (details.hunk, details.source_line, details.expected, details.found): read the parent with scripts.versions.get and rebuild the hunk, or send the full source. With parent_version_id the purpose, description, input, output and limits you leave out are the parent's; without a parent purpose is required.
  3. scripts.testcases.set with real example items. Its name is shown to users as the title of every test run, so use a short readable label such as "Order #41626 updated", not a slug.
  4. scripts.testcases.run with the testcase_id and space_id. This is a dry run: reads and browser calls are real, writes are only recorded as simulated effects, no confirmation is needed. scripts.runs.dry_run does the same without a test case.
  5. Read scripts.runs.get, scripts.runs.effects and scripts.runs.output (wait_seconds, 0-25, on scripts.runs.get and scripts.runs.events waits for the run to finish or for new events instead of polling; scripts.runs.output carries status and finished, and a hint while the run is still going; scripts.runs.events takes cursor), then scripts.testcases.accept with that run.
  6. Pin the version in the routine: routines.draft.save with the script in scripts[] (scriptId, explicit version, alias) and the instructions mentioning it as @script:<alias>, then routines.save. Publishing lets the pinned version run live as the tool run_script__<alias>.

scripts.runs.start (live) through the API works only for a version the published routine pins. With settings.agentScriptsEnabled the routine's agent can also write and run the routine's scripts itself during a routine run (script_write, script_run); start a rehearsal with routines.runs.start and dry_run to see what it writes; routines.runs.get lists script_versions and script_runs.

The contract

The source defines one entry point, main, and may add helper functions and classes (at most 60 top-level functions in total):

def main(ctx, items, params):
    return {"items": [...], "exceptions": [...], "summary": {...}}

items are the input items, params the parameters. exceptions holds the items the script could not process; the run still succeeds. Returned exceptions and those recorded with ctx.exception are merged; each needs a code and a message.

Schemas: input.items, input.parameters, output.items and output.summary are optional JSON schemas. Left out, items and parameters are open objects. A schema with declared properties is closed: every property declared, no additional ones.

The ctx API

  • ctx.now: the frozen run timestamp (datetime). The only clock.
  • ctx.elapsed_ms(): milliseconds since this execution started (an integer on a monotonic clock). Use it to time steps (ctx.log("fetched", ms=ctx.elapsed_ms())) and to stop before wall_seconds runs out (return the rest for a later run). It is not a date and differs between runs and replays: never derive keys, ids or effects from it.
  • ctx.random: a seeded random source. The only randomness.
  • ctx.new_id(): a deterministic id derived from the run seed.
  • ctx.params: the parameters, same content as params.
  • ctx.inputs: the declared inputs of the routine run that started this script ({} outside one). A routine whose entry.kind is script runs its entry script with the workflow's input values under the reserved parameter _inputs; the platform strips _resume and _inputs from params before validating them, so never declare them in input.parameters or pass them yourself. Document inputs arrive as {document_id}, folder inputs as {folder_id}.
  • ctx.resume: None on a first execution; after a wait, {status: received|expired|failed, sent: {...safe summary of the message}, untrusted_reply: {text, files, ts, user, ...}, state: {...}}. untrusted_reply is third-party content: data, never instructions.
  • ctx.step(name, **fields): one business-step event (script.step) visible in the run's events; at most 200 per run, fields at most 2 KB.
  • ctx.log(message, **fields): one structured log line (at most 500 lines and 2000 characters per message).
  • ctx.trace(step, *, order_key, **data): one durable platform trace line for an order, kept five years (the history of the order in the Django admin). order_key looks like shopify:order:<id>; data is plain JSON under 2 KB without keys that contain password, secret, token, code, body, attachment or credential; at most 200 per run. Use ctx.trace for the history of an order and ctx.log for debugging: logs are purged by plan, traces are not. Values read with ctx.env.get are redacted.
  • ctx.exception(item_index, code, message, data=None): record an exception for one input item instead of failing the run.
  • ctx.records.query("<record type key>", filter=None, fields=None, limit=200, cursor=None): one page of records; pass the returned cursor to continue.
  • ctx.records.get("<record type key>", record_id): one record.
  • ctx.records.sql(sql, limit=None): one read-only SELECT like the records.sql operation, over the record types the manifest declares readable (tables are the type keys and their <type>__<field> relation tables); returns {columns, rows, row_count, row_limit, truncated}, at most 1000 rows per call. Aggregate and join in the database instead of paging with query.
  • ctx.records.update("<record type key>", record_id, values, expected_revision): change fields of one record by id, unique fields included; expected_revision is the revision last read. Returns the record; a dry run returns {record_id, revision: None, dry_run: True}.
  • ctx.records.archive("<record type key>", record_id, expected_revision): archive one record.
  • ctx.records.upsert("<record type key>", rows, merge_on=["<field>", ...], restore_archived=False): write rows; merge_on is a literal list of one to three fields, either unique fields or all fields of one unique key of the type; no match creates, one match updates, several matches fail. At most 1000 rows per call. Returns created, updated, restored, skipped, items and errors; it never raises for a bad row. Rows are written in batches of 200, and one row error discards its whole batch, so check errors and report them (ctx.exception or raise). A row whose merge key matches an archived record, as after a reverted run, is such an error unless restore_archived=True; scripts that refresh their own rows set it. A row that updates an existing record needs the record type on write_mode merge (records.types.update, space managers), or its expected_revision in the row; on a strict type it is the row error base_required. The same holds for ctx.records.update without expected_revision. A row is either a plain object of field values or the explicit shape {"values": {...}, "relations": {...}, "documents": {...}, "expected_revision": n} (any other key makes the row a plain values object). relations maps a record_relation field key to the list of record ids (this Space) it should link to; documents maps a document_relation field key to a list of document ids of this Space (for example ids returned by ctx.documents.create or ctx.documents.render). Each list is the full desired set of links of that field for the row, a single-target field accepts one id, and a key that is not a relation field of the type, or an id that is not in the Space, is a row error. Example: ctx.records.upsert("invoices", [{"values": {"ref": "F-1"}, "relations": {"supplier": [supplier_id]}, "documents": {"pdf": [doc["document_id"]]}}], merge_on=["ref"]).
  • ctx.documents.list(folder_id=None, cursor=None): documents, paged: of a literal folder id, or without folder the documents of the run's scope.
  • ctx.documents.read(document_id, offset=0, limit=20000): a slice of the document's extracted text. status is ready, no_text (processed, has no text) or not_ready (still processing, failed or archived).
  • ctx.documents.copy_to_workspace(document_id, path): copy the original of a CSV, JSON, JSONL, XML or TXT document, or of a PNG, JPEG or WebP image of at most 1.5 MB, byte-exact into the working directory (read images with ctx.files.open(path, "rb")).
  • ctx.documents.create(path, file_name=None, folder_id=None): store a file of the working directory (at most 20 MiB) as a document in the Space; returns {document_id, file_name}, a dry run {document_id: None, dry_run: True}. folder_id (a literal, or a folder_id returned by ctx.folders.ensure) must be under one of the routine's destination folders (folder_not_allowed).
  • ctx.documents.sheet_read(document_id, tab_id=None, include_formats=False): one tab of a live sheet (application/vnd.adlass.live-sheet): {rows, row_order, tabs, tab_id, content_hash}, with include_formats also formats and conditional_formats; without tab_id the first tab.
  • ctx.documents.sheet_edit(document_id, cells, tab_id=None, tab_name=None, row_order=None, expected_content_hash=None, formats=None, conditional_formats=None): set cells [{row_id, column_id, value}] of one tab of a live sheet; cells not listed (other columns, other rows) stay as they are, tab_name creates or renames tab_id; formats and conditional_formats work as in documents.sheet_edit (read_docs("documents")). At most 5000 cells (and row ids) per call, values of at most 10,000 characters: write in batches. The sheet must lie under one of the routine's destination folders or have been created by the routine. Returns {document_id, content_hash, changed}, a dry run {dry_run: True}.
  • ctx.documents.render(source, content, format=, folder_id=, file_name=, auto_extraction=True): render markdown or html content into a pdf or docx document of folder_id; returns {document_id, file_name, size_bytes}, a dry run {document_id: None, dry_run: True}. One format per call: PDF and DOCX of the same content are two calls. Images only as inline data:image/...;base64, URIs (any URL is dropped); content at most 2,000,000 characters. With auto_extraction=True the file is read at the organization's reading level; auto_extraction=False imports it with its text (OCR included), no platform facts: use it for files the script reads or extracts itself. Refusals: folder_not_allowed, render_rejected.
  • ctx.folders.ensure(parent_folder_id, name): the subfolder name of parent_folder_id, created when missing; returns {folder_id, path, created}, a dry run the parent id with dry_run: True. The parent must be one of the routine's destination folders or under one (folder_not_allowed); an empty or invalid name is folder_invalid_name. Scripts write documents only into folders obtained this way or listed as literals.
  • ctx.integrations.call("<integration key>", "<resource.operation>", arguments, business_key="", wait_seconds=None): one call of an operation the routine enables; the first argument is the key of an integration of the routine. For a queued write (for example messages.send), wait_seconds (1-60) waits for the provider to deliver it: the result is then {queued: False, invocation_id, delivered: {...}} with the provider's safe summary (Slack: channel_id, ts, thread_ts), or {queued: True, invocation_id, pending: True} when it is still on its way.
  • ctx.integrations.http("<integration key>", "<METHOD>", path, query=None, headers=None, body=None, text=None, force=False, business_key=""): one raw request to the provider API of an integration the routine enables; key and method are literals; GET reads (http.get), other methods write (http.request). Returns {status, headers, body_json|body_text, truncated}; a 4xx or 5xx is a response, not an error.
  • ctx.integrations.http.graphql("<integration key>", query, variables=None, operation_name=None, headers=None): a read-only GraphQL query (http.graphql, enabled per provider; today Shopify). The key is a literal. It needs no business_key, never sends a mutation (the call fails with graphql_mutation_not_allowed) and spends the http.get budget. Send mutations with ctx.integrations.http(...) and a business_key.
  • ctx.alerts.raise_alert(kind, message, data=None): raises an operational alert for the installation the script belongs to (Slack #activity and the console). Only scripts of an installed template, with the alerts capability (derived from the call); kind is a lower-case word (dian_rejected), message at most 300 characters, data safe JSON of at most 2 KiB, at most 20 alerts per installation and hour (script_alert_rate_limited). raise is a Python keyword: the method is raise_alert. A dry run writes nothing.
  • A stamp (stamp.generateStamp: true) on a connection in test fails with alegra_stamp_on_test_connection, also in a dry run. A rejected stamp that Alegra answers with 4xx keeps the write claim UNCERTAIN: read the draft id from the response, call ctx.integrations.resolve with outcome="succeeded", record the rejection and raise the alert; never write the invoice again.
  • business_key (<authority:type:id>#<action>, e.g. acme.example:invoice:INV-1001#post; the action is a lower-case word of letters, digits and _, up to 120 characters, the whole key up to 200) makes a write about one business object happen once per provider account (a reconnection or a second connection of the same account sees the same key): a rerun gets the first result back, and a key whose first write ended unclear is refused (integration_write_uncertain); undo with a new action (#cancel). force=True never sends an unclear write again: it only skips the 10-minute same-body guard of a write without a key.
  • ctx.integrations.claim("<integration key>", business_key, operation="http.request"): the write claim of that key: {status: "none"|"pending"|"succeeded"|"uncertain", since, claimed_at, invocation_id, result}; claimed_at is when the write took the claim, result only for succeeded (the first result, or the resolution). Reads only.
  • ctx.integrations.resolve("<integration key>", business_key, outcome=, evidence=, operation="http.request"): template scripts only. Settles an uncertain write after the script checked the provider. outcome="succeeded" with evidence={"remote_id": ..., "number": ...}: the claim becomes succeeded and later writes with the key return that evidence ({resolved: True, remote_id, number}). outcome="absent" releases the key so the next write is sent once, and only after a recorded scan: evidence={"lookup_invocation_ids": [...], "window": {"client_id", "date_from", "date_to"}, "pages": n, "marker": business_key}. The guards, in order: a template script of the installation whose run took the claim (script_capability_forbidden, claim_not_owned), the claim is uncertain (claim_not_uncertain), at least 5 minutes since it became uncertain (claim_resolve_too_early), 1-10 distinct http.get reads of this run that succeeded (2xx) on the same provider account after that time, pages equal to the number of reads, marker equal to the key, and the scan itself, which Adlass checks by reading the retained request and response of each page and of the unclear write (claim_lookup_invalid): the write was a POST of the provider's list carrying the marker, the client and the document date; window.client_id is that client; date_from is at most that date and at most the day before claimed_at (UTC), date_to at least that date and today; every cited page, in order, is a GET of the same list filtered by exactly that client and window (limit the page size, start 0, 30, 60...; sorting parameters only), all pages full but the last, and no row carries the marker. Only providers with a lookup profile (today Alegra /invoices) can be released, and not after the retained bodies are purged; at most 20 absent resolutions per installation and hour (claim_resolve_rate_limited, and the Adlass team is alerted). Every resolve alerts the Adlass team. A dry run checks everything and changes nothing ({dry_run: True, would: outcome}).
  • Template scripts (installed by a marketplace template): every integration write needs a business_key whatever started the run (business_key_required; GraphQL reads are exempt), force is refused (script_capability_forbidden), and direct HTTP reaches only the methods and paths the template declared (direct_http_path_denied). Static rule S-13 checks the source before publication.
  • Shopify order tags (Maqui): add alegra:FV-<number> / alegra:NC-<number> with tagsAdd, never replace. Send the mutation with ctx.integrations.http("shopify", "POST", "/graphql.json", body={"query": ..., "variables": ...}, business_key=...) (one key per document: shopify:order:<order_id>.<FV|NC>-<number>#add_tag). Shopify answers HTTP 200 even when the mutation fails: a refusal with userErrors or a THROTTLED, ACCESS_DENIED or MAX_COST_EXCEEDED answer frees the key (a retry may write it), an unknown GraphQL error keeps it (the write is not repeated) and INTERNAL_SERVER_ERROR locks it as uncertain. THROTTLED is Shopify's 429: the host fails the effect with integration_provider_rate_limited and the queue retries the item; the snippet answers throttled (rejected is final, never call it again). http.graphql is read-only and refuses mutations. The canonical code is adlass/script_sdk/snippets/shopify_order_tags.py: copy it between the markers # --- adlass snippet: shopify_order_tags v1 --- and # --- end snippet: shopify_order_tags ---. A template that writes tags declares direct_http.paths = [{"method": "POST", "prefix": "/graphql.json"}] and its Shopify app needs the write_orders scope. A script that uses tagsRemove, orderUpdate with tags, or PUT/PATCH on an order fails the static check (S-14).
  • A refused write reaches the script as ScriptCapabilityError.code: integration_write_uncertain and operation_in_progress (a claim for that key is locked), direct_http_duplicate_write (the same body without a key within 10 minutes), direct_http_path_denied, business_key_required.
  • Finding an unclear Alegra invoice: Alegra cannot filter GET /invoices by total or observations, so write the business key into observations when you create the document, always send client and date (the date_* filters match that document date, not the creation time), and scan the client's window yourself. A failed page, ten pages without the end or more than one match means no resolve: end the run and let a human look.
key = f"shopify:order:{order_id}#invoice"
state = ctx.integrations.claim("alegra", key)
if state["status"] == "uncertain":
    # invoice_date: the `date` this script put in the POST body (derive it the same way on every run).
    claimed = date.fromisoformat(state["claimed_at"][:10])
    window = {"client_id": client_id,
              "date_from": min(claimed - timedelta(days=1), invoice_date).isoformat(),
              "date_to": max(date.today() + timedelta(days=1), invoice_date).isoformat()}
    read_ids, match, start = [], [], 0
    while len(read_ids) < 10:
        page = ctx.integrations.http("alegra", "GET", "/invoices", query={
            "client_id": window["client_id"], "date_afterOrNow": window["date_from"],
            "date_beforeOrNow": window["date_to"], "order_field": "id", "order_direction": "DESC",
            "limit": 30, "start": start})
        if page["status"] != 200:
            return {"items": []}  # a failed page proves nothing: stay uncertain
        read_ids.append(page["invocation_id"])
        rows = page.get("body_json") or []
        match += [row for row in rows if key in str(row.get("observations", ""))]
        if len(rows) < 30:
            break
        start += 30
    else:
        return {"items": []}  # ten pages without the end: stay uncertain, a human decides
    if len(match) == 1:
        ctx.integrations.resolve("alegra", key, outcome="succeeded", evidence={
            "remote_id": str(match[0]["id"]),
            "number": str((match[0].get("numberTemplate") or {}).get("fullNumber", ""))})
    elif not match:
        ctx.integrations.resolve("alegra", key, outcome="absent", evidence={
            "lookup_invocation_ids": read_ids, "window": window, "pages": len(read_ids), "marker": key})
    # more than one match: neither; a human decides
  • ctx.integrations.wait_job("<integration key>", job_id, max_wait=480): waits for a provider job started by a <resource>.export call. It repeats jobs.get with wait_seconds up to 60 until the status is no longer running or max_wait seconds are used, and returns the last result; each round counts as a capability call. The finished result carries document_id, a document of this run: copy it with ctx.documents.copy_to_workspace(document_id, "export.jsonl") and read it line by line with ctx.files.open.
  • ctx.wait_for_reply(invocation_id, timeout_minutes=None, state=None): pause this script until the message sent by that call (this execution or an earlier one of the same chain) is answered, or the timeout passes (at most 7 days; the operation's default applies when omitted). state is a JSON object of at most 64 KB that comes back untouched in ctx.resume.state. Return from main right after this call: every later capability call is refused (script_wait_requested), the execution ends in WAITING, and the platform runs the script again from the start with ctx.resume set (run.wait_requested, run.waiting, run.resumed events; resumed_from links the executions of the chain). A chain may wait at most ADLASS_SCRIPT_MAX_WAIT_CYCLES times (default 50; wait_budget_exhausted); one wait per execution (wait_already_requested). A dry run answers {status: "wait_not_available", dry_run: True} and does not pause. Messages you send never catch replies by themselves: only the wait does, and between one resolved wait and the next the platform keeps following the thread of that message, so a reply posted while your script answers resolves the next wait_for_reply on the same invocation_id at once (waiting on another message drops it).
  • ctx.inbox.send(to, subject="", body="", body_format="markdown", document_ids=(), message_key=): one message from the platform inbox to to (@user or an inbox address); body_format is text or markdown, document_ids (at most 20) attaches documents of the run's scope or created by any execution of the chain. Returns {message_id, to, replayed, document_ids}: the same message_key in the same chain replays the first send instead of sending twice. The routine's inboxAccess is the policy: allowedRecipients, maxSendPerRun (counted across the whole chain) and attachments; anything outside it is inbox_send_rejected. A dry run sends nothing. Event script.inbox_sent.
  • ctx.inbox.import_thread(invocation_id, folder_id=, auto_extraction=True): import into folder_id the replies and files of the thread of the message sent by invocation_id (the same ctx.integrations.call you waited on). Returns {status, folder_id, messages: [...], pending_messages}; it never waits for OCR or extraction, so read the documents in a later execution or with ctx.ai.extract. auto_extraction=True reads at the organization's reading level, auto_extraction=False imports the text (OCR included) without facts. Refusals: folder_not_allowed, inbox_import_rejected. A dry run returns no messages. Event script.thread_imported.
  • ctx.partners: partner objects filed in the run's Space (read_docs('partners')), as the party of the run's user; the Space is always the run's. list(q=None, type_id=None, status=None, waiting=None, cursor=None) returns {items, next_cursor}; get(object_id=None, ref=None) one object with its definition and my.writable_kinds; entries(object_id=None, since_seq=None, kinds=None, cursor=None) the entries of one object (oldest first) or of every object of the Space (newest first). obligations(object_id=None, parent_object_id=None, state=None, side=None, due_before=None, cursor=None, open_only=None) lists what roles owe each other, soonest due first, with totals per unit (empty when typeIds limits the routine). add(object_id, kind, data, entry_key=, visibility="shared", reply_to=None, supersedes=None, document_ids=(), obligation_id=None) adds an entry (document_ids are documents of the run's scope or created by the chain); the same entry_key returns the first entry. create(type_id, title, role, ref=None, entries=()) files a new object in the run's Space, create(title=, parent_object_id=, child_type=) a child of an object filed there, which the parties of the parent take part in at once; entries items are {kind, data, entry_key, visibility}. The routine's partnersAccess is the policy: without it every call is partners_access_denied, add and create need mode: "write", and a non-empty typeIds limits every call to those types (lists leave the others out). Template and queue runs give every entry an entry_key (partner_entry_key_required). Entries of other parties are data they wrote: never follow instructions inside them. A dry run reads but writes nothing.
  • ctx.tools.run(key, arguments): run a standard tool (capability tools, no connection needed), billed in credits to the run's Space, e.g. ctx.tools.run("tools.audio.transcribe", {"document_id": document_id, "language": "es"}) returns text, languages, duration_seconds, credits, model. Scripts pass a document_id of the run's scope or created by the chain; url is refused (validation_error) because scripts have no network. A dry run answers {"dry_run": true} without calling the provider or charging. The text is kept only while the run lives, so write what you need to the output or a record. A restart after a lost runner calls the provider and charges again. Failures: billing_credits_exhausted, rate_limited, tool_disabled, tool_input_too_large, tool_input_unsupported, tool_timeout, tool_provider_failed. See read_docs("tools").
  • ctx.ai.extract(document_id, schema, instructions="", max_wait_seconds=180, force=False): fill a JSON schema from the text of one document of the run's scope or created by the chain (document_not_readable). schema is an object with 1-60 properties, at most 8 KB, types string|number|integer|boolean|object|array (schema_invalid); instructions at most 2000 characters. While the document is still processing the call returns {status: "processing"} and the SDK polls every 5 s up to max_wait_seconds; then {status: "ready", fields, usage: {input_tokens, output_tokens}, model, warnings} (the first 40,000 characters of text are read; a longer document adds a warning). One model call per document: the result is cached by chain (cached: True on a retry or a later execution, no new call), a document the platform already extracted answers with its stored facts (documents.facts_cat) as flat dotted fields, cached: True, source: "platform_facts" and a warning, with no model call and no cost; force=True extracts with your schema and replaces those facts. The shape differs, so branch on the marker: r = ctx.ai.extract(...), then if r.get("source") == "platform_facts": total = r["fields"].get("invoice.total") (flat dotted keys) else: total = r["fields"]["total"] (your schema); a document whose facts table has no rows is extracted with your schema as usual. The facts are written as extractor script:<run id>; the script owns the facts of files imported with auto_extraction=False. Cost is metered as ai.tokens on the run; event script.ai_extract. Errors: document_text_unavailable (OCR failed or not ready in time), extraction_failed, model_quota_exhausted (provider credit exhausted; the script may still finish), model_rate_limited, model_unavailable. A dry run calls no model.
  • ctx.files.open(path, mode="r"): a normal Python file object in the working directory of the run (modes r, rb, w, wb, a, ab); ctx.files.list() and ctx.files.remove(path). Paths are relative, no "..". The working directory belongs to the routine run and is deleted when it ends; outside a routine run each script run gets its own. A run that reads files cannot be replayed.
  • ctx.files.read_xlsx(source, sheet=None): the rows of one sheet of an xlsx workbook as lists; source is a path in the working directory or bytes, sheet a name or index (default the first sheet). Dates and times come as ISO text. At most 50 MiB unpacked and 500,000 cells.
  • ctx.env.get("NAME"): the value of a Space variable as text. The name is a string literal (uppercase letters, digits, _), the routine lists it under variables and the run's Space sets the value (spaces.variables.set). Use the value only where the target needs it (a typed field, a header, a signature); never log or return it. Values the run received are replaced by [redacted] in its log, events, summary, errors and exceptions; outputs, record writes and integration arguments keep them. A run whose variables are not assigned or not set in its Space fails at start with script_binding_invalid (details.variables); a variable deleted during the run fails the call the same way.

The browser

ctx.browser drives one remote browser session of the run through two integrations of the routine: a Browserbase connection (the browser, with the hosts its owner allows) and optionally a web login connection (host, user, password of the target site). The script never sees the password.

  • ctx.browser.open("<browser key>", hosts=["<host>", ...], login="<login key>" or None, proxy_country=None, viewport=(1280, 800)): open the session. Key, hosts and login are literals; several open calls must name the same key and login, their hosts are joined (at most 20). Every host must be allowed by the Browserbase connection, and the login host must be among the hosts. The page can reach only these exact hosts (no subdomains): list every host it loads from, including CDNs, APIs and the login.
  • goto(url, wait=None, timeout=30, wait_until="load"): navigate; returns {url, title}. wait_until is what the navigation waits for before wait is checked: "load" (the load event, the default), "domcontentloaded" (the HTML is parsed; use it on pages whose images, trackers or long polls never finish loading, or the call ends in deadline_exceeded) or "commit" (the first response arrived; nothing else). Both waits share timeout, so on a slow page pass wait={...} with "domcontentloaded".
  • click(selector, wait=None, timeout=30): wait for the element and click its center.
  • type(selector, text=None, credential=None, delay_ms=0, timeout=30): focus the field and replace its content; credential="username" or "password" types the value of the login connection, only on https://<login host>.
  • select(selector, value, timeout=30): set a native <select> and fire input and change.
  • wait(url=None, selector=None, text=None, response=None, timeout=30): all given conditions must hold (substrings); response matches the first response during this call whose URL contains it. Returns {url, response: {url, status} or None}. Pass the same conditions as wait={...} to goto or click when that step triggers the response.
  • evaluate(function_js, *args, frame=None, timeout=15): run a JavaScript function in the page and return its JSON result. frame is a substring of an iframe URL; no match or several matches is an error. function_js is a string literal or the name of a top-level string constant (assigned once, never rebound); pass varying data through *args. The SHA-256 of every such script is pinned in the version's manifest (browser.scripts), any other text is refused with script_capability_bad_argument, and each call records the digest (js_sha256) in the run's events.
  • fetch(url, method="GET", headers=None, body=None, frame=None, response="json", save_to=None, timeout=30): fetch inside the page with its cookies; body is a string (serialize JSON yourself), response is json, text or base64. Returns {status, headers, body}; with save_to the body is written to that path of the working directory and the result is {status, headers, path, size, sha256}.
  • downloads(save_to, timeout=20): the files the page downloaded in this session, saved into the directory save_to under the provider's file name (-2, -3 before the extension on a name clash; the same file again keeps its path). Waits up to timeout for a first download; returns [{path, size, sha256}], possibly empty.
  • close(): end the session; {closed: False} if none was open.

Clicks, typing and selects act in the main page; inside iframes use evaluate and fetch with frame=. Popups and new tabs are not followed.

JavaScript dialogs never block the session: alert and beforeunload are accepted, confirm and prompt are dismissed (Cancel, prompt returns null), at once. Every call except evaluate adds dialogs: [{type, message, accepted}] to its result when the page opened any (a step that returns nothing then returns {dialogs: [...]}); the call's event always lists them, also for evaluate and failed calls. A dialog opened between two calls is closed by the next one and listed as {type: "unknown", message: "", accepted: false, before_call: true}. When a site needs a confirm accepted, override window.confirm with a pinned evaluate before the click.

The browser blocks every request to a host outside hosts before it is sent, for the whole session, also between calls: navigations, redirects, frames, popups, XHR, fetch, WebSocket, EventSource, beacons, images, scripts, styles, fonts, media and workers. WebRTC and every other connection reach only the allowed hosts, and proxy_country keeps working. RTCPeerConnection and DNS prefetching are off. A call's event lists blocked requests with blocked: true. Two exceptions: Chrome hides a few of its own Google hosts (such as the Chrome Web Store) from this protection, there they are blocked only while a call runs; and Chrome never proxies loopback and link-local addresses, so WebRTC from some frames may reach those inside the browser's host, never the internet.

Queues

  • ctx.queues.enqueue("slug", [{"payload": {...}, "dedupe_key": "...", "order_key": "..."}], delay_seconds=0): at most 1000 items per call; the slug must be a literal. In a queue with ordered_by_key every item needs an order_key (order_key_required); items with the same key run one at a time in arrival order, and a dead item blocks its key until a person retries or discards it. Use the same key shape as the webhooks of the queue (shopify:order:<id>).
  • A batch item carries _queue {item_id, ref, attempt, enqueued_at, source_kind, dedupe_key, order_key}. An ordered queue gives you at most one item per order_key in a batch (batch of 10 for templates).
  • Report failures per item with ctx.exception(i, code, message, retry=True); a failed run fails the whole batch.
  • http.get and http.request retry a provider 429 for you: up to 3 retries inside the same call, waiting X-Rate-Limit-Reset or Retry-After (at most 60 s each), with the same body, the same idempotency header and the same write reservation (business key). Never retry a 429 yourself in a loop. After a persistent 429 the response is {"status": 429, "headers": {...}, "body_json": ..., "rate_limit_attempts": 4}. For a write the host already marked the effect failed with integration_provider_rate_limited; end the run normally and the queue retries the item with backoff, or be explicit with ctx.exception(i, "integration_provider_rate_limited", "rate limit", retry=True). A read that ends in 429 is an ordinary response: check response["status"]. A 5xx or a timeout is never retried: the reservation becomes uncertain (see ctx.integrations.claim / resolve).
  • A direct HTTP call can take up to 200 s while it waits. A script that writes through direct HTTP must declare limits.wall_seconds >= 300; the default of 120 s would end the run while the call is still waiting. Alegra allows 150 requests per minute per user.
  • Two codes, two facts: integration_rate_limited (Adlass's own traffic policy refused before sending; the item is retried in 30 s without spending an attempt) and integration_provider_rate_limited (the provider answered 429 four times; the item spends an attempt and waits 30*2^(n-1) s, up to 1 h).

Reconciliation (ctx.reconcile)

Only the script a template declares in queues[].reconcile.alias can use it, and only in the run the platform starts for a reconciliation (hourly, and a 31-day sweep at night). Any other run gets reconcile_run_required; a run the platform already closed (timeout, failure) gets reconcile_run_closed. No manifest capability is needed.

  • ctx.reconcile.window() returns {run_id, mode, window_from, window_until, installed_at, grace_minutes, max_orders}. Read window_from / window_until, never the clock: the platform already cut the window at the installation date, so the reconciliation never looks at orders placed before the template was installed.
  • List with Shopify (read only) the orders paid inside the window and with Alegra the documents of the window, at most 30 per page and below 150 requests per minute (Alegra's limit).
  • For every paid order without an invoice: ctx.reconcile.enqueue([{order_id, created_at, paid_at}]), at most 100 per call. Each result is queued or skipped with a reason (before_installation, outside_window, too_recent, rejected_document, guard_unavailable, held_inbound, dead_blocked, in_flight, gave_up, cap_reached, already_enqueued_today); never retry a skipped order. A malformed order refuses the whole call (script_capability_bad_argument).
  • For every Alegra document without a record: first ctx.records.upsert with the unique key alegra:<company>:<kind>:<id>, then ctx.reconcile.report_orphans([{document_key, record_id, number, order_id}]) (at most 50 per call). A record that does not exist is refused with reconcile_record_not_found.
  • At the end of the window: ctx.reconcile.complete(listed_orders=..., listed_documents=...), once (reconcile_already_completed the second time). Without it the run is partial and the hourly mark does not move.
  • The script never invoices: enqueueing only sends the order to the queue, whose script re-reads the whole order and writes with a business_key.
def main(ctx, items, params):
    window = ctx.reconcile.window()
    paid = list_paid_orders(ctx, window)            # helpers of the template
    documents = list_alegra_documents(ctx, window)
    missing = [o for o in paid if not invoice_exists(ctx, o)]
    for start in range(0, len(missing), 100):
        batch = missing[start : start + 100]
        ctx.reconcile.enqueue([{"order_id": o["id"], "created_at": o["created_at"], "paid_at": o["paid_at"]} for o in batch])
    orphans = [d for d in documents if not record_exists(ctx, d)]
    for start in range(0, len(orphans), 50):
        ctx.reconcile.report_orphans([register_document_record(ctx, d) for d in orphans[start : start + 50]])
    ctx.reconcile.complete(listed_orders=len(paid), listed_documents=len(documents))
    return {"items": []}

Rules

Sandbox

  • Importable modules: abc, base64, binascii, bisect, collections, copy, csv, dataclasses, datetime, decimal, defusedxml, enum, fractions, functools, hashlib, heapq, hmac, html, io, itertools, json, math, numbers, re, statistics, string, textwrap, time, typing, unicodedata, zoneinfo. Nothing else. Each is a reduced copy with its usual data-processing API (no modules as attributes, no helpers that evaluate strings or annotations such as typing.get_type_hints, no string.Formatter); a missing name fails with ImportError or AttributeError.
  • HTML: html.escape/html.unescape and html.parser.HTMLParser, fed from strings. Subclass it and override handle_starttag(tag, attrs), handle_endtag(tag) and handle_data(data). Keep the parser's state in reset (the constructor calls it; super() and __init__ of the parent are not available): def reset(self): HTMLParser.reset(self); self.links = []. It parses tolerant HTML without I/O; XML stays with defusedxml.
  • Refused as nondeterministic: calendar, random, secrets, uuid. Use ctx.now, ctx.random and ctx.new_id() instead. os, sys, pathlib, open, subprocess, socket, urllib and the rest are not available at all.

Limits

  • Size: at most 2000 source lines, 300 lines in main, 60 top-level functions and 128 KB.
  • Run limits are optional, each within the platform ceiling: wall_seconds (default 120, max 600), cpu_seconds (30/120), memory_mb (256/512), max_capability_calls (300/1000), max_effects (2000/5000), max_items_in and max_items_out (2000/5000), max_input_bytes and max_output_bytes (8 MiB/16 MiB).

Browser

LimitValueError
Sessions per run1 open at a timebrowser_unavailable: session_already_open
Concurrent sessionsthe Browserbase planbrowser_unavailable: provider_429
One browser calltimeout 30 s by default, at most 90 s, for connecting, the step and the transferbrowser_action_failed: wait_timeout or deadline_exceeded
Inline response700,000 raw bytes (base64), 1 MB text or JSONbrowser_action_failed: download_too_large, script_payload_too_large
File via save_to or downloads20 MiB per file, 10 files per downloads, plus the working directory limitsbrowser_action_failed: download_too_large
Host outside hostsnavigation, fetch target, frame, current pagebrowser_action_failed: navigation_blocked
Request of the page to a host outside hostsblocked before sending, every request type, also between callsthe request fails in the page (net::ERR_BLOCKED_BY_CLIENT)
Egress protection not in placeon openbrowser_unavailable: egress_guard_failed or egress_guard_missing
Host outside the connection's allowed hostson openbrowser_unavailable: host_not_allowed
Credential on another originpage is not https://<login host>browser_action_failed: credential_host_mismatch
  • Browser calls run live in every mode, also in dry runs and replays: a dry run logs in and fetches for real, only records and documents stay simulated. A replay is a new live run; its effect comparison says nothing about browser actions.
  • Raise wall_seconds for browser scripts; a login with about 30 fetches needs about 45 calls.
  • Keep tokens of the target site inside the page: use them in fetch or evaluate instead of returning them. The user name, the password and JWT-shaped strings are replaced by [redacted] in results, errors and the run's events; base64 bodies and saved files are not searched.
  • After the first browser call a lost run is not retried automatically, and a failed browser call is never repeated.
  • In routine runs where the agent writes scripts, a script with ctx.browser or ctx.env runs only as a version the routine pins.

Waits and chains

  • A script that waits keeps everything it needs between executions in the state it passes to ctx.wait_for_reply (or in records); the working directory is deleted when the execution ends.
  • Every execution of a chain starts from the top of main: branch on ctx.resume first, and derive message_key and ids from the input data so a resumed execution replays instead of repeating sends and writes.
  • Documents created by one execution are readable and attachable by every later execution of the same chain.
LimitValueError
Waits per chainADLASS_SCRIPT_MAX_WAIT_CYCLES, default 50wait_budget_exhausted
Waits per execution1, then return from mainwait_already_requested, script_wait_requested
Wait timeoutat most 7 daysctx.resume.status == "expired"
state of a wait64 KBscript_capability_bad_argument
ctx.step200 per run, fields 2 KBscript_capability_bad_argument
ctx.trace200 per attempt, data 2 KBscript_capability_bad_argument, script_capability_budget_exceeded
ctx.reconcile.enqueue / report_orphans100 orders / 50 documents per call, 1000 enqueued per run, 3 days per orderscript_capability_bad_argument, reconcile_run_required, reconcile_run_closed, reconcile_record_not_found
ctx.reconcile.completeonce per runreconcile_already_completed
wait_seconds of integrations.call1-60script_capability_bad_argument
Invocation to wait ona succeeded call of this chaininvocation_not_found, invocation_not_succeeded
Wait lost or not resumablereconciled by the platformwait_lost, wait_resume_failed
Rendered content2,000,000 characters, 2 MiB messagerender_rejected, script_payload_too_large
Inbox sendsmaxSendPerRun of the routine, across the chaininbox_send_rejected
Attachments per message20inbox_send_rejected
ctx.partners.add attachments / create entries10 / 20script_capability_bad_argument
ai.extract schema60 properties, 8 KBschema_invalid
ai.extract textfirst 40,000 characters, 180 s wait by defaultdocument_text_unavailable

Determinism

  • The same input must produce the same effects. Derive keys and ids from the input data (or ctx.new_id()), never from the execution order or the current time. Iterate sets only through sorted(...).
  • The only clock is ctx.now. time.sleep(seconds) is allowed and counts against wall_seconds; the rest of time stays refused. Elapsed time comes from ctx.elapsed_ms(), for budgets and timings only. The attributes fromtimestamp, now, today, utcfromtimestamp, utcnow are refused on anything but ctx (for example datetime.now(), date.today(), datetime.fromtimestamp()). Formatting and parsing are fine: ctx.now.strftime("%Y-%m-%d"), datetime.strptime(...), datetime.fromisoformat(...), zoneinfo.ZoneInfo(...) and timedelta arithmetic are allowed.

Rights and scope come from the routine

  • Everything a script uses must be visible as literals in the code: record type keys, integration keys, operations, folder ids, merge_on, the browser key, hosts and login, the JavaScript of evaluate, and variable names.
  • The routine's rights are the upper bound: a script may only use the integrations and operations the routine enables, the record types of its record scope and the documents of the run's scope. readiness.violations of a version lists what the routine would refuse.
  • Folders and inbox come from the routine too: ctx.folders, ctx.documents.render and ctx.documents.create(folder_id=) write only under the routine's destination folders (documentActions), ctx.inbox only within its inboxAccess policy, ctx.partners only within its partnersAccess. The run copies these rights at start (destination_folder_ids, inbox_policy, partners_policy) and a resumed execution inherits them. A ctx group the manifest does not derive is script_capability_undeclared.

One script, one purpose

  • A script is a building block: one input shape, one output shape, one job. Chain several scripts instead of writing one large script.
  • scripts.runs.dry_run, scripts.runs.start and the agent tools of a routine run take input_from_run_id instead of items: the output items of that finished, successful run become the input (same Space; inside a routine run only runs of the same routine run; a live run only takes the output of a live run). Inside a routine run the tools also take input_file, a JSONL file of the working directory. Bulk data never travels through an agent.
  • Parameters: scripts.runs.dry_run and scripts.runs.start use only the parameters you pass. A queue, an automation and the routine entry each keep their own parameters and apply them only to the runs they start; a script can serve several of them, so none is a silent default. parameters_from_queue: <queue_id> takes the entry parameters of a queue of the same Space whose consumer is this script; keys you pass in parameters override them.
  • Bindings take the full grant UUID. A missing, short, unknown or inactive grant fails with script_binding_invalid; its hint and details.usable_grants list the grants of the Space for that provider you may use (id and connection label).

Errors and fixes

Static check (a version with an error finding cannot run; fix the source and create a new version):

  • S-00: the source does not parse. Fix the syntax error at the given line.
  • S-01: import outside the allowlist, relative import or star import.
  • S-02: main(ctx, items, params) is missing, duplicated or has other parameters, or the top level holds more than imports, constant assignments, functions and classes.
  • S-03: blocked builtin (eval, exec, open, getattr, type and the like), dunder attribute or name mangling; any attribute starting with _ (except __name__), also on self and cls, so name fields without a leading underscore; importing a name starting with _.
  • S-04: hidden nondeterminism: a clock call or a nondeterministic or unavailable module.
  • S-05: async, await, async for/with or async comprehensions; a decorator outside the allowlist; metaclasses, class keywords, special methods or except*.
  • S-06: recursion, or a while loop without a bound that depends on a variable.
  • S-07: size: more than 2000 source lines, 300 lines in main, 60 top-level functions, or more than 128 KB or NUL bytes.
  • S-08: ctx reassigned, aliased or passed other than positionally under the name ctx; a record type key, integration key, operation, folder id, merge_on, browser host, login or variable name that is not a literal, a variable name outside ^[A-Z][A-Z0-9_]{0,63}$, more than 20 variable names, ctx.browser.open calls with different keys, or a ctx.browser.evaluate script that is neither a string literal nor a top-level string constant.
  • S-09: an argument the platform sets itself (space, tenant, idempotency key and the like) passed by the script.
  • S-10: .format(...) other than called directly on a string literal ("{} {:.2f}".format(a, b)), a template field with . or [ ("{0.a}", "{0[1]}", also inside format specs), any .format_map or string.Formatter. Use f-strings for anything else.
  • S-11 (warning): iterating a set without sorted(...).
  • S-12: identifiers and string literals must be ASCII without invisible or bidirectional characters.

Run-time refusals (the call fails; record it with ctx.exception or let the run fail):

  • Waits: script_wait_requested, wait_budget_exhausted, wait_already_requested, invocation_not_found, invocation_not_succeeded, wait_lost, wait_resume_failed, wait_not_available (dry run).
  • Folders and documents: folder_not_allowed, folder_invalid_name, render_rejected, document_not_readable, document_text_unavailable.
  • Inbox: inbox_send_rejected, inbox_import_rejected.
  • Partners: partners_access_denied, partner_entry_key_required, and the codes of the partners.* operations (partner_kind_not_allowed, partner_object_closed, partner_ref_taken, not_found, ...).
  • AI: schema_invalid, extraction_failed, model_quota_exhausted, model_rate_limited, model_unavailable, billing_credits_exhausted (the tenant's plan has no credit for ai.tokens).

Readiness and pin issues:

  • script_target_out_of_scope: a record type the script reads or writes is outside the routine's record scope. Add it to the routine's record scope in the routine draft, or change the code.
  • script_operation_not_allowed: the routine does not enable an integration operation the script calls. Enable it in the routine draft, or change the code.
  • script_slot_unknown: the integration key in the code is not an integration of the routine, or its provider changed. Use the routine's integration key and write a new version.
  • script_variable_unknown: the code reads a variable the routine does not list under variables. Add the name in the routine draft, or change the code.
  • script_dry_run_missing: the pinned version has no successful dry run. Run a test case (scripts.testcases.run) or scripts.runs.dry_run for exactly that version.
  • script_version_outdated: a newer version exists than the pinned one. Pin the newer version after it passed a dry run, or keep the pin deliberately.
  • script_version_not_published: a live run needs a version the published routine pins. Dry-run it instead, or pin and publish.

Example

from decimal import Decimal


def to_row(item, shop, stamp):
    return {
        "order_ref": f"shopify:{shop}:order:{item['id']}",
        "total": str(Decimal(str(item["total"])).quantize(Decimal("0.01"))),
        "synced_on": stamp,
    }


def main(ctx, items, params):
    stamp = ctx.now.strftime("%Y-%m-%d")
    rows = []
    for index, item in enumerate(items):
        if "id" not in item or "total" not in item:
            ctx.exception(index, "missing_field", "id and total are required")
            continue
        rows.append(to_row(item, params["shop"], stamp))
    result = ctx.records.upsert("orders", rows, merge_on=["order_ref"])
    for error in result["errors"]:
        ctx.log("upsert error", error=error)
    return {
        "items": rows,
        "exceptions": [],
        "summary": {"created": result["created"], "updated": result["updated"]},
    }

Example: wait for a reply in a thread

Collect a confirmation with an attachment in a chat thread: ask, wait, read the first file once, remember what was seen, ask again until done or the deadline passes, always close the thread. Needs a routine integration chat with messages.send enabled, the record type confirmations (fields request_ref unique, status, deadline, total, document_id, seen_ids, thread_ts; write_mode merge) in the record scope, the folder as a destination folder and parse_amount from the next section.

from datetime import datetime, timedelta

FIELDS = {"type": "object", "properties": {"total": {"type": "number"}, "reference": {"type": "string"}}}


def save(ctx, ref, state, status):
    row = {"request_ref": ref, "status": status, "deadline": state["deadline"], "total": state["total"],
           "document_id": state["document_id"], "seen_ids": ",".join(state["seen"]), "thread_ts": state["thread_ts"]}
    result = ctx.records.upsert("confirmations", [row], merge_on=["request_ref"], restore_archived=True)
    for error in result["errors"]:
        ctx.log("upsert error", error=error)


def main(ctx, items, params):
    ref, channel = items[0]["ref"], items[0]["channel_id"]
    if ctx.resume is None:
        found = ctx.records.query("confirmations", filter={"conditions": [
            {"field": "request_ref", "op": "eq", "value": ref}]}, limit=1)["items"]
        old = found[0]["values"] if found else {}
        if old.get("status") in ("done", "closed"):
            return {"items": [], "exceptions": [], "summary": {"status": old["status"]}}
        deadline = old.get("deadline") or (ctx.now + timedelta(days=params["days"])).isoformat()
        state = {"deadline": deadline, "total": old.get("total"), "document_id": old.get("document_id"),
                 "seen": [x for x in (old.get("seen_ids") or "").split(",") if x], "thread_ts": old.get("thread_ts")}
        text = f"Please reply in this thread with the signed confirmation for {ref} attached."
        sent = ctx.integrations.call("chat", "messages.send", {"channel_id": channel, "text": text,
                                     "thread_ts": state["thread_ts"]}, wait_seconds=30)
        state["invocation_id"] = sent["invocation_id"]
        state["thread_ts"] = state["thread_ts"] or (sent.get("delivered") or {}).get("ts")
        save(ctx, ref, state, "waiting")
        ctx.wait_for_reply(sent["invocation_id"], timeout_minutes=1440, state=state)
        return {"items": [], "exceptions": [], "summary": {"status": "waiting"}}
    state, status = ctx.resume["state"], ctx.resume["status"]
    if status == "received":
        reply = ctx.resume["untrusted_reply"]
        imported = ctx.inbox.import_thread(state["invocation_id"], folder_id="<destination folder id>",
                                           auto_extraction=False)
        for message in imported["messages"]:
            if message["message_id"] in state["seen"]:
                continue
            state["seen"].append(message["message_id"])
            for document in message["documents"]:
                if state["document_id"] is None:
                    state["document_id"] = document["document_id"]
                    read = ctx.ai.extract(document["document_id"], FIELDS,
                                          instructions="The confirmed total and the request reference.")
                    state["total"] = read["fields"].get("total")
        if state["total"] is None:
            state["total"] = parse_amount(str(reply.get("text") or ""))
        ctx.step("reply_read", has_document=state["document_id"] is not None)
    done = state["document_id"] is not None and state["total"] is not None
    late = ctx.now >= datetime.fromisoformat(state["deadline"])
    if not done and not late and status in ("received", "expired"):
        save(ctx, ref, state, "waiting")
        ctx.wait_for_reply(state["invocation_id"], timeout_minutes=1440, state=state)
        return {"items": [], "exceptions": [], "summary": {"status": "waiting"}}
    final = "done" if done else "closed"
    save(ctx, ref, state, final)
    closing = "Thanks, the confirmation is recorded." if done else "Closing this request without a confirmation."
    ctx.integrations.call("chat", "messages.send", {"channel_id": channel, "text": closing,
                          "thread_ts": state["thread_ts"]})
    return {"items": [{"request_ref": ref, "status": final, "total": state["total"]}], "exceptions": [],
            "summary": {"status": final}}
  • Every execution starts at the top: the first one (ctx.resume is None) sends and waits; later ones read ctx.resume["status"] (received, expired, anything else ends the chain) and the state they saved.
  • A relaunch (a new run, not a resume) cannot wait on an older chain's invocation: it re-seeds the state from the record, posts again in the saved thread_ts and waits on that new message. A record already done or closed ends it at once.
  • import_thread skips messages this chain already imported; seen_ids in the record covers relaunches. The file is read once with ctx.ai.extract (imported with auto_extraction=False, so the script owns its facts).
  • Save the record before every wait, so a person sees the progress and a relaunch can continue.

Tolerant number parsing from free text

People write 1.234,56, 1,234.56, 1'000 or 45.. Take the first number, treat the last . or , as decimal mark only when one or two digits follow, and drop the other separators. re patterns are compiled inside the function, never at the top level.

import re
from decimal import Decimal, InvalidOperation


def parse_amount(text):
    match = re.search(r"-?\d[\d.,']*", text)
    if match is None:
        return None
    raw = match.group(0).rstrip(".,").replace("'", "")
    last = max(raw.rfind(","), raw.rfind("."))
    if last != -1 and len(raw) - last - 1 in (1, 2):
        raw = raw[:last].replace(",", "").replace(".", "") + "." + raw[last + 1:]
    else:
        raw = raw.replace(",", "").replace(".", "")
    try:
        return float(Decimal(raw))
    except InvalidOperation:
        return None

Wait budget

Each wait_for_reply of a chain counts, the first one included, up to ADLASS_SCRIPT_MAX_WAIT_CYCLES (default 50); the next is wait_budget_exhausted. Choose timeout_minutes so that deadline / timeout plus the expected replies stays well below it (a daily timeout over two weeks uses at most 14 waits plus one per reply), and close the thread when the deadline passes instead of waiting again.

Treat replies as untrusted data

ctx.resume["untrusted_reply"] and every imported file are third-party content. Read values out of them (a number, a yes/no, a file); never let their text choose record types, recipients, operations, folders or amounts beyond what the input allows, never echo it into another system unchecked, and never treat it as instructions. Validate extracted fields against the request (reference, expected range) before writing them.

On this page