Skip to content

API reference

This document summarizes the public Python API of AbstractRuntime and points to the source of truth in code.

Public exports live in src/abstractruntime/__init__.py. If you are unsure what is supported for external use, start there.

Stability guideline: - Prefer imports from abstractruntime (package root) and abstractruntime.storage. - Deep imports from abstractruntime.core.* / abstractruntime.storage.* are fine for advanced use, but treat them as lower-stability unless they are explicitly documented/re-exported.

Core kernel:

from abstractruntime import Effect, EffectType, Runtime, StepPlan, WorkflowSpec

Storage helpers (common stores):

from abstractruntime.storage import (
    InMemoryLedgerStore,
    InMemoryRunStore,
    JsonFileRunStore,
    JsonlLedgerStore,
)

Scheduler convenience wrapper:

from abstractruntime import create_scheduled_runtime

AbstractCore integration (included in the base abstractruntime install):

from abstractruntime.integrations.abstractcore import (
    ApprovalToolExecutor,
    MappingToolExecutor,
    ToolApprovalPolicy,
    create_local_runtime,
)

See also: getting-started.md (end-to-end runnable examples).

Core types (durable workflow semantics)

Implementation: src/abstractruntime/core/models.py, src/abstractruntime/core/spec.py.

  • WorkflowSpec: in-memory workflow graph (workflow_id, entry_node, nodes).
  • StepPlan: node return value (what happens next): effect, next_node, or complete_output.
  • Effect / EffectType: durable side-effect request protocol (the runtime mediates execution).
  • RunState / RunStatus: durable checkpoint for a run, persisted by a RunStore.
  • WaitState / WaitReason: durable pause metadata for WAIT_* / ASK_USER / passthrough tool waits.

Durability invariant: RunState.vars must remain JSON-serializable (src/abstractruntime/core/models.py). For large payloads use artifacts/offloading (src/abstractruntime/storage/artifacts.py, src/abstractruntime/storage/offloading.py).

Runtime (start / tick / resume)

Implementation: src/abstractruntime/core/runtime.py.

  • Runtime.start(workflow, vars=..., actor_id=..., session_id=..., parent_run_id=..., run_id=...) -> run_id
  • creates and persists a new RunState
  • run_id starts the run under an id you choose ([A-Za-z0-9_-]+). The run is created only if that id is free; starting it again with the same identity (workflow, session, parent, vars._meta.occurrence, vars._meta.creation_digest) returns the existing run untouched, and a different identity raises RunIdentityConflict (a ValueError, reason_code = "identity_conflict"). The store must support create_if_absent (otherwise NotImplementedError). START_SUBWORKFLOW accepts the same explicit id as payload.run_id, and payload.resolve_vars (a list of top-level var names) resolves the artifact refs in those vars for the child only, strictly (a missing artifact fails the start), so the parent's records keep the refs
  • a root run that names a session is checked against the session's attribution: in a discussion session it gets the discussion's workspace setup (its own writable workspace and the read-only mount) and provenance, and when the attribution cannot be read (an invalid discussion root, or a store without a run index) the start raises SessionAttributionError (see automations.md)
  • Runtime.tick(workflow, run_id, max_steps=..., step_gate=None) -> RunState
  • executes node handlers and effects until the run becomes WAITING, COMPLETED, FAILED, or CANCELLED
  • optional step_gate() is consulted at every step boundary; when it returns False the tick returns the persisted state and the run stays RUNNING (a later tick continues where it stopped)
  • Runtime.resume(workflow, run_id, wait_key, payload, max_steps=...) -> RunState
  • validates the wait_key, writes payload to WaitState.result_key (if set), and continues from WaitState.resume_to_node
  • a wait is resumed at most once: a resume of a run that is no longer waiting, or that waits on another key, raises StaleResumeError (a ValueError); replies to recognized conversational questions are instead retained without answering or resuming another question (below)
  • the check and the commit run under a per-run lock, and tools approved with {"approved": true} execute while that lock is held, so a long tool delays a competing resume of the same run, which is then refused
  • run_mutation_lock(run_id) (package root): the per-run, per-process, re-entrant lock that tick holds for the whole tick and resume for its commit; take it around your own read-modify-save of a run so a tick cannot overwrite your change
  • Runtime.get_state(run_id) -> RunState and Runtime.get_ledger(run_id) -> list[dict]
  • host-facing read APIs for checkpoints and the append-only ledger
  • Runtime.cancel_run(run_id, reason=None, cancelled_by="api") -> RunState

Cancellation publishes a detached snapshot. Runtime writers in the same writer process arbitrate short state commits separately from effect execution, so a stale tick cannot overwrite cancellation. The publication lock is independent of provider execution. Completion evidence and state publication share that boundary; an already completed run stays completed. Direct store writers must follow the store's synchronization contract.

  • persists CANCELLED, then signals every effect of that run (and its in-flight descendants) executing in this process; the running attempt is recorded as cancelled (StepStatus.CANCELLED, never retried) with cancelled_by and reason, and no further effect starts
  • Runtime.set_default_provider_model(provider=..., model=...)
  • re-points the default provider/model seeded into new runs; pair it with the pooled client's set_default_provider_model(...) so both agree
  • Runtime.set_event_inbox(inbox), Runtime.set_trigger_connection_store(store) and Runtime.set_schedule_run_handler(handler): the host seams of event-triggered automations, trigger connections and wakes (see automations.md and automations.md)
  • Runtime.set_live_delta_sink(sink) where sink(event: dict) -> None, or None to remove it
  • receives live token deltas (llm.delta, llm.delta_end) for LLM calls of runs started with _runtime.stream: true (a boolean; start refuses any other value); nothing is written to the ledger. See Live token streaming

Effect cancellation helpers (src/abstractruntime/core/effect_cancellation.py): - inflight_effects(run_ids=None) lists executing effects (run, step, provider, model, elapsed time) - request_model_effects_cancel(provider, model, cancelled_by="model_eject") stops the effects using a model before it is unloaded; local unload_model_residency calls it for you - kill_inflight_effect(step_id, killed_by=...) is an in-process hard stop for a call that ignores its cancel event (it cannot interrupt a thread blocked inside one native call)

Conversational questions and deadlines

ASK_USER retains its indefinite legacy behavior when payload.question is absent. For a conversational question, add exactly one of these policies alongside the existing prompt, choices and allow_free_text fields:

{"importance": "essential"}
{"importance": "clarification", "timeout_s": 120, "fallback": "Compare both options before choosing."}

Essential questions have no deadline or fallback. Clarifications require a numeric duration from 120 through 300 seconds and a nonempty, predeclared safe fallback. Extra policy fields are refused. Time passing never grants tool approval or permission to perform an action. Flows may supply the same object through the AskUser question input or effectConfig.question.

Every logical issuance has a fresh wait_key (question:<id>). Its persisted waiting.details.question contains id, purpose: "conversation", importance, published_at, deadline and fallback (the last two are null for essential questions). The existing waiting.prompt remains the question text. Resume with the exact key and {"response": "the person's words"}. Empty responses and approval payloads are refused.

The server arbitrates at commit time: a response before the deadline wins; at or after it, expiry wins even if the due scan has not run. An answer result carries question: {id, outcome: "answered"}. Expiry produces {timed_out: true, fallback: "...", question: {id, outcome: "expired"}} with no response. Hosts and actors must present this as a host-authored continuation, never as human speech. Cancellation records a cancelled outcome and does not continue the workflow.

Explicit pause suppresses timeout continuation. The original deadline survives pause and restart; after explicit resume, an overdue question resolves before further work. A reply to a paused, expired or already resolved recognized question is retained in the ledger, with its reason, and does not answer a newer question. The small outcome index retains 64 entries; full outcomes and retained replies remain in the ledger. Outcome receipts are authoritative across a crash before the following checkpoint save.

Memory, JSON and SQLite run stores index these USER deadlines through their existing due-wait queries. The existing scheduler/host runner advances them; Runtime does not install a timer service. Resolution uses process-local locks and the existing single-writer authority for the store; it is not a distributed multi-writer transaction. Legacy EVENT deadlines and tool-approval waits retain their own contracts.

Public conversation and accepted guidance

An opt-in actor may inherit _runtime.conversation: {enabled: true} through native child workflows and VisualFlow Agent nodes. This flag does not create an extra inference call. Public updates enter replay only through an explicit completed EMIT_EVENT named public_update, with payload id, text, run_id, optional session_id, iteration, source_call_ids and optional kind ("progress" or "finding", replayed as the message's update_kind). The event's owner must match run_id; private diary/thinking fences are excluded. See replay.md.

Actors may attach public_action to a proposed TOOL_CALLS payload with text, update_id, run_id, positive integer iteration and call_ids. The text is the actor's public stated purpose (nonblank, at most 600 characters), not execution proof. The adapter owns its binding to an accepted public update and unchanged proposed calls. Runtime checks the owning run and exact effect call IDs, then narrows the metadata to the actual calls requiring approval. Mismatched targets, unknown or duplicate IDs, malformed metadata and private fences withhold the explanation without changing the approval policy. Valid context appears at waiting.details.public_action and the canonical replay interaction's details. Clients verify its run and exact pending IDs before presenting it. An absent explanation must not be replaced with private reasoning or a guessed purpose. Hosts with an earlier approval boundary can share abstractruntime.integrations.abstractcore.effect_handlers.approval_public_action(run, payload, host_calls, waiting_calls). Pass the original effect payload and host calls plus the exact gated subset. The return value is validated narrowed metadata or None; compute it before replacing a delegated payload's tool_calls, and carry only that returned context forward. This helper grants no permission and changes no approval policy.

For human input during work, Runtime.steer(run_id, message, display_text=words, speaker=...) keeps the existing durable guidance path and adds a public acceptance receipt only when display_text is explicitly supplied. message may contain quoted context; display_text preserves the person's exact original words (nonblank, at most 65,536 characters). Operational steering without this field does not become public human history. Hosts may supply client_message_id for correlation; it is preserved on the reserved receipt and replay message, independently of the sidecar sequence and message id. An accepted receipt means the words were durably queued; the actor's later response is the evidence that it considered or adopted them. It does not undo an action already performed.

If the sidecar append succeeds and the public-receipt append fails, admission still succeeds: the exact words remain in the sidecar and the host logs a repair warning. Delivery repairs the receipt before acknowledging that source. A terminal run does not promise another actor boundary; its retained sidecar remains recoverable rather than being reported as refused. Entity visits use the narrower participant-checked visit door and fresh attributed recall, described in entity-runtime.md.

Tool scope: an explicit allowed_tools list in run.vars["_runtime"], in a child run's _runtime, or in a TOOL_CALLS payload is a ceiling intersected across the run tree (src/abstractruntime/core/tool_scope.py). Approval policy can remove a prompt but can never grant a tool outside it; a missing key means unrestricted and an empty list denies every tool.

For the execution model (ledger records, effect outcomes, waits), see architecture.md.

Scheduler convenience API

Implementation: src/abstractruntime/scheduler/*.

Use create_scheduled_runtime() for a zero-config wrapper that bundles Runtime + an in-process polling Scheduler: - ScheduledRuntime.run(workflow, vars=..., actor_id=..., max_steps=...) -> (run_id, state) (src/abstractruntime/scheduler/convenience.py) - ScheduledRuntime.respond(run_id, payload) -> RunState (resumes a waiting run using its stored wait_key) - ScheduledRuntime.stop() (stops the scheduler thread/loop)

For time-based waits, the scheduler polls due runs via QueryableRunStore.list_due_wait_until(...) (src/abstractruntime/storage/base.py, src/abstractruntime/scheduler/scheduler.py).

Storage layer (durability backends)

Interfaces: RunStore, LedgerStore, and QueryableRunStore are defined in src/abstractruntime/storage/base.py.

Included backends: - In-memory (tests/dev): InMemoryRunStore, InMemoryLedgerStore (src/abstractruntime/storage/in_memory.py) - Filesystem: - checkpoints: JsonFileRunStore (src/abstractruntime/storage/json_files.py) - append-only ledger: JsonlLedgerStore (src/abstractruntime/storage/json_files.py) - SQLite: - SqliteRunStore, SqliteLedgerStore (src/abstractruntime/storage/sqlite.py)

Notes: - abstractruntime.storage intentionally exports only the most common store types. SQLite types are available via: - from abstractruntime import SqliteRunStore, SqliteLedgerStore, or - from abstractruntime.storage.sqlite import SqliteRunStore, SqliteLedgerStore

Run index and creation (all built-in run stores, including the offloading wrapper): - create_if_absent(run) -> (run, created): creates a run only if its id is free and never overwrites an existing one; store_supports_create_if_absent(store) / require_create_if_absent(store) check a store first. Process-crash safe; power-loss durability is not claimed - list_run_index(status=, workflow_id=, session_id=, root_only=, limit=, oldest_first=, automation_id=, role=, session_kind=): lightweight rows carrying automation_id, role, occurrence_index, session_kind and workspace_root (the run's top-level vars["workspace_root"] as stored, stripped; None when absent); the three attribution filters take a value, a comma-separated string or a list; root_only=True returns turn roots (parent-less runs except automation controllers, plus automation occurrences) - session_kinds(session_id) -> frozenset and latest_occurrence_row(automation_id): indexed lookups used by session attribution and automation listings - MailboxQueryableRunStore (in-memory, file, SQLite and offloading stores): list_mailbox_runs(names=[...], limit=10_000) returns every running or waiting run whose events_mailbox names one of the names (newest first; the file store keeps a mailbox index maintained on save and delete and re-verifies each hit on disk), and next_wait_deadline() the earliest wait deadline over all waiting runs (WAIT_UNTIL, or WAIT_EVENT with a deadline), or None. Hosts use them to fan durable events out and to schedule wakes without reading a window of the newest runs - JsonFileRunStore.warm_session_index() builds the session and children indexes at host startup. Store objects and processes sharing one JSON run folder see each other's created and deleted runs through the creation journal .runs_created.log; v1 supports one writer process per store - JsonFileRunStore answers list_runs / list_run_index for status=running or status=waiting (without session_id) from an in-memory active index: the set of active run ids, built from one directory scan (at host boot through warm_session_index(), else on the first such listing) and kept current by save, create_if_absent, delete and the creation journal. Every candidate is re-verified against its file at listing time, so a run that ended or vanished is never listed. Rows, order (file mtime, then file name, then the final updated_at sort), filters and limits are the same as the directory scan's; a listing of a 10,000-run store costs milliseconds instead of a full scan. JsonFileRunStore(..., use_active_index=False) keeps the plain scan. rescan_active_index() reconciles the index with the directory in the caller's thread; a background rescan runs at most every JsonFileRunStore.ACTIVE_INDEX_RESCAN_S (60 s) to pick up writers that bypass the store. list_due_wait_until (the scheduler's due-wait poll) takes its candidates from the index too. Other listings (a terminal status, no status, a session scope) scan as before. - Trusted run index (JsonFileRunStore(..., trust_index=True), the default): every listing the active index does not answer (no status or a finished status, no session_id: list_run_index, list_runs, latest_occurrence_row) is answered from memory once one complete pass (the active-index build, at host boot through warm_session_index()) has read every run file: ranked by file mtime then file name, same filters, rows and limits as the directory scan, with no glob and no stat of a run file (11,500 files: about 1-20 ms instead of a 0.25 s scan that waits for the interpreter lock under contention). It is kept current by the store's own saves, creates and deletes, the creation journal (including =<run_id>), and a re-read of its RUNNING/WAITING entries when the folder's mtime moved (another process ticking a run writes no journal line). A background reconciliation (the active-index rescan, a daemon thread, never on a caller's path) re-reads the folder at most every ACTIVE_INDEX_RESCAN_S (60 s) when the folder or the journal moved, and at least every RUN_INDEX_FULL_RECONCILE_S (600 s); a difference it finds (a writer that bypassed the journal) is repaired and logged as a warning. The risk is a stale row until then, never a lost run: load() reads disk. trust_index=False (verify, the shadow mode) answers every such listing with the directory scan, as before, and compares it with the in-memory answer. run_index_stats() (forwarded by OffloadingRunStore) returns mode, complete, entries, active_entries, trusted_listings, scanned_listings, shadow_compared, shadow_mismatches (verify mode: stable comparisons whose answers differed; 0 means the index would have answered every listing the same), shadow_unstable (a write overlapped the comparison: no verdict), last_mismatch, reconciles, reconcile_repairs and last_reconcile; each mismatch and each repair is also logged as a JsonFileRunStore: warning. reconcile_run_index() runs the reconciliation in the caller's thread. Needs the active index (use_active_index=False is the plain scan, without shadow). - The creation journal (.runs_created.log in the run folder) carries one line per change another store object or process must learn about: +<run_id> created, -<run_id> deleted, ~<run_id> became active again (resumed, re-opened, first save after a restart, or saved after another writer touched the file). Lines are written before the file change they announce; readers apply the lines they have not seen at their next lookup, and a line whose file has not landed yet (or does not read active yet) is re-checked until it does. Readers from AbstractRuntime 0.10.0 ignore ~ lines, and writers from 0.10.0 never write them: a re-open made by such a writer reaches other store objects through the periodic rescan. =<run_id>: a run that is not active changed its file (it finished, or a finished run was re-saved), written AFTER the file is published; older readers ignore it, and a change made by an older writer reaches the trusted run index through the reconciliation. - JsonFileRunStore event-wait and mailbox indexes (list_event_waiters, list_event_waiters_by_prefix, list_mailbox_runs) see what another process saved on the same folder (a split gateway: API process + runner process). Before each lookup the store reads its change signal (the creation log's size and the folder's mtime): when either moved, or at least every EVENT_INDEX_REFRESH_S (2 s), it stats each running or waiting run and re-reads the ones whose file changed since it last filed them. An idle store pays two stats per lookup; its own saves are never re-read. event_index_stats() returns {refreshes, refiled, tracked}. - JsonFileRunStore.change_token() answers "did any run of this folder change?" with one stat: (creation-log size, active-index counter). Every save, create and delete through the store moves the counter; another process's create, delete or became-active line moves the log size. Not seen: another process re-saving a run that stays active (one ticking process per folder); ending a run, or re-saving a finished one, writes =<run_id>. changed_run_ids(token) names the runs this store changed since token, or None when that is unknown (the log moved, or more than 8,192 changes ago). ObservableLedgerStore.change_token() / changed_run_ids(token) do the same for ledger appends (process-local). The gateway runner's scan gate and its mail notification check compare these tokens instead of reading the directory.

The durable cursor (ADR 0010): - Every ledger store numbers a run's records 1, 2, 3, … and list() returns each record with its seq. JsonlLedgerStore writes it on each line, allocated under an advisory file lock that spans the head read and the write, so another process appending to the same run never takes the same number. A line written before the field existed is numbered by its position. append() returns the seq. - LedgerStore.list_after(*, run_id, after, limit=1000) -> (records, last_seq): the records after a seq. SQLite does an indexed read; JSONL seeks to the byte offset where the previous read ended; the default implementation filters list(). The decorators (observable, hash-chained, offloading) delegate it. - ObservableLedgerStore hands subscribers the record with its seq. - SqliteLedgerStore.import_records(run_id, records) copies a run's ledger in, keeping each seq. A migration from files to SQLite therefore keeps every cursor valid. It refuses a run that already has records.

Common decorators: - ObservableLedgerStore for subscriptions (src/abstractruntime/storage/observable.py) - HashChainedLedgerStore + verify_ledger_chain(...) for tamper-evidence (src/abstractruntime/storage/ledger_chain.py) - OffloadingRunStore / OffloadingLedgerStore to store large values by artifact reference (src/abstractruntime/storage/offloading.py)

Commands (durable control-plane inbox)

AbstractRuntime ships append-only, idempotent command inbox primitives designed for gateways/workers that must accept retries safely: - models + interfaces: CommandRecord, CommandStore, CommandCursorStore (src/abstractruntime/storage/commands.py) - backends: in-memory + JSONL (src/abstractruntime/storage/commands.py), SQLite (src/abstractruntime/storage/sqlite.py)

These APIs are exported at the package root (see src/abstractruntime/__init__.py).

Artifacts (store by reference)

Implementation: src/abstractruntime/storage/artifacts.py. Deep dive: artifacts.md.

Key types: - ArtifactStore (interface), InMemoryArtifactStore, FileArtifactStore - helpers: artifact_ref(...), resolve_artifact(...), is_artifact_ref(...)

The store keeps payload bytes out of run state and persists structured metadata: - ArtifactDescriptor is the Runtime-owned descriptor used by Gateway and Observer. It separates semantic_kind such as voice, music, sound, or image from render_kind such as audio, markdown, html, or json, and can carry workflow/node/turn links, media facts, generation/provenance data, source refs, security, and action links. - ArtifactAccessStats records explicit metadata/content/preview/download/export actions when HTTP or UI layers call record_access(...). Plain load(...) and get_metadata(...) remain side-effect free. - search(...), count(...), facet_counts(...), and stats(...) provide metadata queries for host control planes. FileArtifactStore serves these from a repairable SQLite catalog when possible, including exact total, total_bytes, and requested facet counts without forcing Gateway/Observer to load every matching artifact.

Artifacts are used by: - offloading wrappers (src/abstractruntime/storage/offloading.py) - evidence capture (docs/evidence.md, src/abstractruntime/evidence/recorder.py) - AbstractCore media integration: input artifact refs can be materialized for LLM calls, and generated image/video/voice/music/audio outputs are stored as artifact refs

Snapshots / bookmarks

Implementation: src/abstractruntime/storage/snapshots.py.

  • SnapshotStore interface + InMemorySnapshotStore, JsonSnapshotStore
  • Snapshot model (a named bookmark of run state)

Docs: snapshots.md.

Effect policies (retries + idempotency)

Implementation: src/abstractruntime/core/policy.py.

  • EffectPolicy protocol and implementations: DefaultEffectPolicy, RetryPolicy, NoRetryPolicy
  • compute_idempotency_key(...) helper

The AbstractCore runtime factories default to three total LLM attempts and one tool attempt, with exponential backoff starting at one second and capped at 30 seconds. Supply effect_policy=NoRetryPolicy() to disable Runtime retries; the provider may have its own retry policy. Deterministic structured-request and serialization refusals are nonretryable. Inspect a returned run's status and error even when tick(...) itself returns normally.

Docs: architecture.md (reliability section).

WorkflowBundles (.flow) and VisualFlow distribution

Implementation: - bundles: src/abstractruntime/workflow_bundle/* - compiler: src/abstractruntime/visualflow_compiler/*

VisualFlow compiler helpers are available from abstractruntime.visualflow_compiler: - load_visualflow_json(...) normalizes VisualFlow JSON into the stdlib model. - visual_to_flow(...) lowers VisualFlow into the internal Flow IR. - compile_visualflow(...) and compile_visualflow_tree(...) compile VisualFlow JSON into executable WorkflowSpec objects.

VisualFlow authoring note (media and document nodes): - Runtime recognizes first-class VisualFlow media nodes such as generate_image, edit_image, image_to_image, upscale_image, image_upscale, generate_video, text_to_video, image_to_video, generate_voice, generate_music, decide, transcribe_audio, and listen_voice. - Generated-media and transcription nodes lower to a durable EffectType.LLM_CALL with an output selector (for example {"modality":"music","task":"music_generation"}), while listen_voice lowers to WAIT_EVENT. The decide node asks ONE question about a state (inputs state, question, question_type = choice | noul | score, options for a choice, levels for a score, provider, model, truncate) and fills the typed output pins of that type (answer plus choice/confidence/probabilities, noul/verdict, or score/level/confidence/probabilities, with model and success); a wired questions object (several System One questions) replaces the single question and fills answers. It lowers to the same LLM_CALL with {"modality":"decision","questions":{...}} and the state as the prompt; see decisions. Hosts should persist the authoring node type rather than pre-lowering to llm_call. - Runtime also recognizes file/document nodes. read_file and write_file handle UTF-8 text/JSON workspace paths. In Gateway-hosted runs, those paths follow the shared canonical contract: rel/path for the main workspace root and mount_alias/rel/path for approved mounts. read_pdf extracts text and metadata from PDF paths with pypdf; write_pdf renders text or Markdown-style content to real PDF bytes with reportlab; write_docx renders Markdown-style content to real .docx bytes with the standard library; list_folder_files enumerates workspace-scoped folders with family/extension filters; import_workspace_file snapshots a workspace file into a durable artifact; read_artifact projects saved file content back out as text/JSON/bounded binary metadata; and export_artifact writes a durable artifact back to a workspace path. PDF/DOCX bytes are written to the workspace path and only JSON-safe metadata/path values are stored in run state. In local Runtime-only runs with no workspace scope, relative file-node paths still fall back to the process working directory.

Public bundle APIs are exported from src/abstractruntime/workflow_bundle/__init__.py and re-exported in src/abstractruntime/__init__.py: - open: open_workflow_bundle(...) - registry: WorkflowBundleRegistry - pack/unpack: pack_workflow_bundle(...), unpack_workflow_bundle(...)

Docs: workflow-bundles.md.

Automations

Implementation: src/abstractruntime/automations/*, src/abstractruntime/triggers/*, src/abstractruntime/automation_queries.py. Deep dive: automations.md.

from abstractruntime.automations import (
    apply_automation_command,   # pause / resume / run_now / revise / stop_current / archive / unarchive
    create_automation,          # -> (automation_id, revision)
    drive_automation,           # standalone run loop
    get_automation,
    list_attention,
    list_occurrences,
    pending_waits,
    register_controller_bundle,
    start_discussion,
)
from abstractruntime.automation_queries import latest_occurrence, list_automations
from abstractruntime.triggers import get_trigger_adapter, trigger_sources
  • create_automation(runtime, request, *, now=None, actor_id=None): creates the controller root run (the automation) with a deterministic id; raises AutomationError (invalid_definition, unsupported_feature, unknown_trigger_source, identity_conflict)
  • apply_automation_command(runtime, *, automation_id, command_id, type, payload=None, actor=None, expected_revision=None): the only writer of automation state; returns {status: "applied" | "rejected", error?, duplicate}; idempotent per command_id
  • record_automation_command_result(...): records a host-side failure of a command as a rejected result
  • reads: get_automation(run_store, id), list_occurrences(runtime, id, cursor=, limit=), list_attention(ledger_store, id, after_seq=, cursor=, limit=), pending_waits(run_store, id, limit=) with typed waits (ask_user, tool_approval, event) and ANSWER_PAYLOADS; list_automations(run_store, status=, cursor=, limit=, index_rows=), automation_summary(run), latest_occurrence(run_store, id) (the index row); from abstractruntime.automations: latest_occurrence(runtime, id, user_turn=) (the newest occurrence row, read from the ledger's end), pending_waits_by_automation(run_store, limit=) (one read for a whole listing), automation_generation(runtime_or_store) (the change counter a host keys its cached listings on) and the active-consumers index (active_consumers_index, invalidate_active_consumers; see automations.md#trigger-connections)
  • start_discussion(runtime, *, automation_id, occurrence_index, request_id, prompt, workspace_root, actor_id=None): a separate conversation forked at any occurrence N, seeded with the automation's whole timeline 1..N, working in its own writable workspace_root with the automation's workspace mounted read-only
  • controller bundle: register_controller_bundle(registry), controller_workflow_spec(), controller_bundle_path(); CONTROLLER_WORKFLOW_ID is abstractframework.automation-controller@1.0.0:controller
  • trigger sources: trigger_sources(), get_trigger_adapter(id, version), built-ins schedule@1, schedule@2 (daily/weekly/monthly rules in an IANA time zone; validate_time_zone, time_zone_names), manual@1, email.received@1, feed.item@1 and webhook.received@1, third-party sources through the abstractruntime.trigger_sources entry-point group
  • trigger connections (abstractruntime.triggers.connections): TriggerConnectionStore(plane_dir, *, sealing_key_file=None) (per-principal CRUD, sealed secrets), connection_principal(tenant, user), connection_stream(id) (trigger:<id>), append_connection_event(...), test_fire(store, inbox, id, principal=), validate_binding_connection(principal, binding, store), wake_connection_automations(runtime, id), Runtime.set_trigger_connection_store(store); create_automation(..., principal=) and apply_automation_command(..., principal=) check a binding's config.connection_id
  • run origin (abstractruntime.core.run_origin): origin_for(kind, *, actor=, client=, automation_id=, occurrence_index=, event_id=, source=, origin_run_id=, session_id=, bridge=) builds _meta.origin (person | trigger | agent | system), stamp_origin(vars, origin), origin_of(vars); occurrences carry it from the controller
  • CloudEvents envelope (abstractruntime.triggers.cloudevents): to_cloudevent(envelope), from_cloudevent(event), with_cloudevent_attributes(...), event_type(source_id, version), CLOUDEVENT_JSON_SCHEMA; occurrences receive input_data.event
  • feed source feed.item@1 (abstractruntime.triggers.feed): parse_feed(bytes), FeedPoller(store, inbox, fetch=), poll_feed_connections(runtime, store, fetch=None, now=None) (the host's poll step), urllib_fetch (conditional GET)
  • webhook source webhook.received@1 (abstractruntime.triggers.webhook): verify_standard_webhook(secret, headers, body, now, tolerance_s=300), append_webhook_event(inbox, connection, body, headers, *, secret=None, store=None, now=None), sign_standard_webhook(...), new_webhook_secret(), webhook_event_data(...)
  • wakes (abstractruntime.automations.wakes): EffectType.SCHEDULE_RUN, Runtime.set_schedule_run_handler(handler) (handler(run, plan) -> {automation_id}), plan_schedule_run(run, payload, *, now, run_store=None, request_id=None), create_scheduled_run(runtime, plan, *, target, tenant, user, workspace_root, notify=None), wake_scheduled_event, wake_cancelled_event; creation requests accept session_id (growing only), origin_run_id, one_shot, untrusted_origin
  • sample inputs (abstractruntime.automations.samples): sample_occurrence_inputs(runtime, source_id, source_version, config, *, count=100, principal=None, email_context=None, fetch=None) -> {inputs, resolve_vars, truncated, source, count} (the named inputs + event with abstracttest: true, from real data, read only), resolved_sample_inputs(sample, artifact_store=), SampleError
  • mail verbs for flows (abstractruntime.mail_verbs): fixed verbs mail.search, mail.get, mail.mark, mail.label, mail.move, mail.delete, mail.send, mail.reply, mail.forward, mail.attachment run by the TOOL_INVOKE handler (node types mail_*); run_mail_verb(run, name, arguments), mail_verb_outcome(...), MailVerbError; the Email record triggers.email_received.email_record(message, mailbox=), email_id, parse_email_id, thread_id_of. See email.md
  • publish to channel (abstractruntime.core.publish): EffectType.PUBLISH_EVENT (node type publish_event), payload {channel, type?, title, body?, subject?, data?, alert?, recipient? = "me", channels? (tray|watch|phone|email|console; absent = all)}, validate_publish(payload), normalize_channels(value), strip_visual_envelope(payload), DELIVERY_CHANNELS, Runtime.set_publish_event_handler(handler) with handler(run, payload, step_id) -> {event_id, sequence, alerted}. See automations.md
  • definition v2: policy.email_allowed_recipients (default ["self"]), policy.untrusted_input_tools (default []) and notify.channels (default ["console"]); attention items carry channels

Email

Implementation: src/abstractruntime/email/*, src/abstractruntime/triggers/email_received.py. Deep dive: email.md.

from abstractruntime.email import (
    EmailBinding, bind_email_account, strip_client_email_keys, binding_of,   # run-scoped binding
    JsonFileEventInbox, InMemoryEventInbox,                                  # durable event inbox
    EmailInboxFeeder, PollReport, email_event_id,                            # mailbox -> inbox
    email_trigger_consumers, wake_email_automations, prune_email_inbox,      # watcher helpers
    EventInboxRetention,                                                     # inbox retention (90 days / 10,000 events)
    EMAIL_USE_AGENT_TOOL, EMAIL_USE_ACTION, email_use_for_workflow,          # who is sending
    email_action_target, register_email_action_workflow, validate_email_action, render_email_template,
)
  • Runtime.set_email_context_resolver(fn): fn(binding, *, use) -> EmailContext | None (use is "agent_tool" or "action"; fn(binding) also accepted), per runtime, memory only
  • Runtime.set_email_binding(binding | None) / Runtime.email_binding: the account occurrences are bound to
  • Runtime.set_occurrence_input_resolver(fn | None) / Runtime.occurrence_input_resolver: fn(definition, input_data) -> input_data, called at each automation occurrence's admission (its run start) and frozen with the occurrence's inputs (a replayed dispatch stays identical); a non-dict answer fails the admission. The gateway re-resolves an automation's "Use my default" workspaces here. None (default): the definition's inputs as stored
  • Runtime.set_event_inbox(inbox) / Runtime.event_inbox: required by email.received@1
  • EmailInboxFeeder(inbox, account_ref=...).poll(ctx, *, now=None, force=False) -> PollReport and .status()
  • toolsets: get_default_toolsets(..., email_enabled=True) (also list_default_tool_specs, build_default_tool_map, list_tool_catalog); no env flag; list_tool_catalog(email_enabled=False, email_off_reason="not_connected" | "admin_disabled" | "not_available" | "agent_tools_off")
  • mail library for hosts: abstractruntime.integrations.abstractcore.email_facade re-exports abstractcore.comms.email (its __all__ plus the legacy module; GATEWAY_NAMES lists the names hosts use)
  • approval: the send_email_recipient@v2 refiner (tool-approval.md)
  • adopt_legacy_schedule_projection(run): read-only summary of a legacy gateway scheduled:* root
  • read-only mounts: _runtime.workspace_read_only_paths (absolute folders; file write tools and VisualFlow writers refused inside, reads and command/code tools allowed); helpers read_only_paths(vars), path_is_read_only(vars, path) and READ_ONLY_PATHS_KEY in abstractruntime.utils.workspace_paths
  • writable exceptions inside read-only roots: workspace_writable_paths (top-level or _runtime; absolute folders). A path is read-only when a read-only root contains it and no writable path inside that root contains it, so the more specific rule wins (a host sets / read-only plus the run's folder and its read & write folders for a read-only default). Child runs and VisualFlow file nodes get the parent's exceptions exactly; a child never adds one. Helpers: writable_paths(vars), is_read_only_target(path, read_only_roots, writable_roots), WRITABLE_PATHS_KEY.
  • read-only workspaces: run vars workspace_read_only: true (or _runtime.workspace_read_only: true); abstractruntime.integrations.abstractcore.tool_effects.TOOL_EFFECT_CLASSES classifies every exposable tool as read, write, exec, delegate, comms or memory-write

Sessions and history

Implementation: src/abstractruntime/session_turns.py, src/abstractruntime/session_history.py, src/abstractruntime/core/run_attribution.py.

  • select_session_turns(run_store, session_id, *, include_occurrences=True, until_ms=None, automation_id=None, through_occurrence=None, include_drafts=False, limit=50) (package root): a session's turns, oldest first. Turns are parent-less runs except automation controllers, plus automation occurrences (a retried occurrence counts once, as its newest attempt); child runs, runtime-internal runs, legacy scheduled wrappers and draft-test runs are left out
  • session_chat_messages(run_store=, ledger_store=, artifact_store=, session_id=, max_tokens=HISTORY_REPLAY_MAX_TOKENS, until_ms=None, exclude_run_ids=None, automation_id=None, through_occurrence=None, strict=False) (package root): the session's completed turns as user/assistant message pairs; in a discussion session the discussion's seed comes first. Returns a ReplayedHistory (a list of messages) whose .report says what was replayed and dropped. strict=True raises SessionHistoryError (reason_code = "history_unavailable") instead of returning a partial history. max_messages, max_total_chars and max_chars_per_message (keyword-only, default None) are the caps retired in 0.7.0: they are accepted so hosts built against 0.6 (AbstractGateway 0.6.0) still get their history, and ignored. Passing any of them logs one warning and names them in report["ignored_inputs"]
  • The history window: HISTORY_REPLAY_MAX_TOKENS = 50_000 (package root). Replay keeps the most recent turns that fit 50,000 estimated tokens, newest first, as whole messages. There is no message-count cap and no character cap, and no message is ever cut. The fold stops at the first older turn that does not fit, so the window has no gaps. A total of exactly 50,000 tokens fits. One exception: when the newest turn alone is larger than the window, it is kept whole (oversize_turn_kept: true), because cutting it would lose content and dropping it would replay nothing. The model can use the rest of its context window; if a turn is too large for the model, the provider reports the error. Tokens are counted with abstractruntime.memory.token_budget.estimate_message_tokens: for a content-part list it counts the text parts' text plus MEDIA_PART_TOKEN_ESTIMATE (512) for each media part (MEDIA_PART_TYPES: image, audio, file), never the part's base64; any other part (a tool result, a thinking block) counts by its text (0.7.1). max_tokens must be a positive int
  • ReplayedHistory.report: {policy: "most_recent_whole_turns", max_tokens, token_estimator, replayed_messages, replayed_tokens, dropped_messages, dropped_tokens, dropped_counts_complete, oversize_turn_kept}. Replay stops reading once the window is full, so in a long session dropped_counts_complete is false and the dropped counts cover only the turns it read. When turns were dropped, the oldest replayed message starts with a [#TRUNCATION: N earlier message(s) ... were dropped from replay by the history window ...] line (ADR-0026). Hosts record the report in the run as vars._runtime.session_history
  • fold_history_window(pairs, *, max_tokens=HISTORY_REPLAY_MAX_TOKENS) (package root): the window itself, applied to chronological turns (lists of whole messages); returns (kept, report)
  • announce_dropped(messages, report, *, stamp_metadata=True) (package root): writes the window's [#TRUNCATION: ...] notice at the start of the oldest kept message, in place, when report says turns were dropped. Use it after your own fold_history_window call (for example on client-sent history) so the notice matches session replay. stamp_metadata=True also adds metadata.replay_truncated and metadata.history_window to that message; pass False for plain role/content messages. When the message's content is a content-part list ([{"type": "text", ...}, {"type": "image_url", ...}]), the notice is added as one {"type": "text"} part and every other part is left as it is, so images stay images (0.7.1); a stamped head keeps its <runtime_metadata> envelope first. Content of any other type is left untouched and a warning is logged. _announce_dropped is kept as an alias of the pre-0.7.0 private name
  • window_transcript(messages, *, max_tokens=HISTORY_REPLAY_MAX_TOKENS, current_turn_start=None) (package root): the same window over a transcript you already hold (a turn is a user message and the messages after it). current_turn_start is the index of the message that opened the turn in progress: from there on everything is one turn, the newest, always kept whole (oversize_turn_kept when it alone exceeds the window), whatever user-role messages a loop adds inside it; an index out of range raises ValueError. Returns a ReplayedHistory of copies with the notice written by announce_dropped(..., stamp_metadata=False). The entity chat driver and the entity visit workflow use it for their prompts. The visit records the report in vars._runtime.session_history; the chat driver puts it on TurnReport.history_window. On the react visit arm, BRIDGE sets _runtime.history_window_tokens (50,000) and _runtime.history_window_turn_start (the visitor's message) and the AbstractAgent react loop (0.3.17 or newer) sends window_transcript(context.messages) on each call and records the report; the stored transcript stays whole. The report carries window_applied: true; with an older AbstractAgent that records no window the turn still completes, a warning is logged and the report is {"window_applied": false, "reason": "agent_too_old", ...} (the whole transcript was sent). When the oldest kept message carries a <runtime_metadata> envelope, the notice is written after it
  • session_attribution(run_store, session_id) (abstractruntime.core.run_attribution): None or {"kind": "chat" | "automation" | "occurrence" | "discussion", ...}; a discussion adds its validated root, automation, occurrence and workspace. Raises SessionAttributionError when the lookup cannot be completed
  • is_draft_lifecycle(run_lifecycle) (package root): whether a run's lifecycle value marks a draft test run

History bundles (export_run_history_bundle) and session replay use the same turn selection, so automation occurrences appear as turns (kind occurrence, with automation_id and occurrence_index) in both.

Implementation: src/abstractruntime/conversation_search.py.

  • ConversationSearch(db_path, *, run_store, ledger_store, artifact_store=None, kinds=None): the keyword search index of one runtime plane. db_path is its own SQLite file in that plane's data folder (one index per plane, so a principal's search can only ever read the plane it was opened on; the file is disposable and is rebuilt when the schema changes). Each turn root (a question and its answer, as the session replay builds them) is one row, together with the turn's media: the artifacts its run generated (image, voice, video, music, by their generation prompt) and the attachments it was sent with (by their file name), each with its kind. Read-aloud audio, media saved without a prompt and internal artifacts are not indexed. kinds defaults to INDEXED_KINDS (chat, discussion): automation sessions are not indexed
  • sync(*, budget_s=3.0) -> SyncReport: indexes what changed since the last call (turn roots whose updated_at moved, re-read by session, newest sessions first) within the time budget. SyncReport: {indexed_turns, reindexed_sessions, pending_sessions, total_turns, seconds, complete, errors}; complete is False while older conversations are still waiting, so a first search on a large plane can say it is still indexing
  • search(query, *, limit=20, sessions=None, exclude=None, session_kinds=None) -> list[SearchHit]: one hit per session, best first. Text is indexed and queried lowercased and without accents (normalize) with the FTS5 trigram tokenizer: every query word of three or more characters must appear in the turn, as a word or part of one ("surviv" finds "overall survival"); words of one or two characters are matched as whole words; ranked by bm25, the question weighing more than the answer. When exact matches are fewer than limit, a fuzzy pass keeps turns holding at least FUZZY_MIN (60%) of each word's trigrams, so a typo still finds its turn (fuzzy: true on those hits). sessions, exclude and session_kinds filter inside the query, so a filter never empties a page that had matches further down. limit is clamped to 1–100
  • SearchHit (as_dict()): session_id, run_id (the best turn), prompt, snippet (around the first match), matched_in (question, answer or artifact), highlights ([start, length] pairs in the snippet), score, created_at, updated_at, session_kind, fuzzy, and artifact when the match is an artifact: {artifact_id, run_id, kind, content_type, name, prompt}, run_id being the run that owns it (a host's artifact content route is scoped to that run)
  • Without the trigram tokenizer (SQLite before 3.34) the index falls back to whole words with prefix matching. Tool usage, tool outputs and intermediate thinking are not indexed: backlog 0849

Run history bundle export (portable replay artifact)

Implementation: src/abstractruntime/history_bundle.py.

  • export_run_history_bundle(...)
  • persist_workflow_snapshot(...)

This produces a portable record of a run’s state + ledger + artifacts suitable for debugging/review. When available, it also includes resolved_actions: bounded capability/action summaries derived from Core route resolution and persisted from LLM_CALL results.

Voice transport is never part of a conversation turn: the recording of a spoken question and the read-aloud audio synthesized from an answer are left out of each session turn's attachments and artifacts. is_voice_transport(tags) (in abstractruntime.history_bundle) recognizes them: purpose voice_playback or voice_dictation, artifact_space voice, or a voice/ or client:voice/ path. The bundle's own artifacts section stays complete, and conversation search applies the same rule.

Replay view (one reconstruction of a run, every client)

Implementation: src/abstractruntime/replay/ (ADR 0010). Guide: replay.md.

  • replay(records_by_run, runs_by_id=None, *, root_run_id=None) -> ReplayView: folds a run tree's ledger records ({run_id: [records in ledger order]}) and durable snapshots (RunState or dicts) into a view. Pure and deterministic.
  • ReplayView.apply(records, *, runs_by_id=None) -> delta: folds newer records and snapshots. The same delta is kept as view.last_delta. apply(view, records) is the module-level form.
  • ReplayView.to_json(): the view, replay_view_v1 (status, interaction, open_waits, runs, messages, activities, artifacts, usage, workflow, cursor, warnings). Other reads: cursor, run_ids, last_seq(run_id), status(), run_statuses() and is_terminal().
  • apply_delta(view_json, delta), diff_views(old, new) and parse_cursor_token(token): the client side of a delta, the delta between two views, and a cursor token as {run id prefix: seq}.
  • wait_kind(wait), workflow_ref(workflow_id), PERSON_FACING_KINDS, TERMINAL_STATUSES, REPLAY_VIEW_VERSION.

Runtime-owned integrations

AbstractCore (LLM + tools)

Requires: pip install abstractruntime (AbstractCore 2.35.2 or newer is part of the base install).

Implementation: src/abstractruntime/integrations/abstractcore/*.

Entry points: - create_local_runtime(...), create_remote_runtime(...), create_hybrid_runtime(...) (src/abstractruntime/integrations/abstractcore/factory.py) - public discovery facade: AbstractCoreDiscoveryFacade, get_abstractcore_discovery_facade(...) (src/abstractruntime/integrations/abstractcore/discovery_facade.py) - model errors a host tells apart, AbstractCore's own classes: from abstractruntime.integrations.abstractcore.discovery_facade import ModelNotDownloadedError, ModelNotFoundError (ModelNotDownloadedError is a ModelNotFoundError whose model and provider name what to download); a host never imports abstractcore for them - public host facade: AbstractCoreHostFacade, get_abstractcore_host_facade(...) (src/abstractruntime/integrations/abstractcore/host_facade.py) - public voice library facade: AbstractCoreVoiceFacade, get_abstractcore_voice_facade(...), VoiceLibraryError (src/abstractruntime/integrations/abstractcore/voice_facade.py): languages, cloned voices (list by language, read, rename or replace the transcript, delete), cloning from a recording, voice design, the capability catalog; local in process, remote over the AbstractCore server's /v1 voice routes (see Voice library) - email facade: email_facade (AbstractCore's mail library for hosts; see Email) - public Telegram host wrappers: TelegramTdlibNotAvailable, bootstrap_telegram_auth_from_env(...), get_global_telegram_client(...), stop_global_telegram_client(), send_telegram_message(...) (src/abstractruntime/integrations/abstractcore/telegram_facade.py) - public durable run facade: AbstractCoreRunFacade, get_abstractcore_run_facade(...) (src/abstractruntime/integrations/abstractcore/run_facade.py); inline_run_active(run_id) is true while the facade executes a child run in this process (its workflow exists only inside that call), so a host runner that scans RUNNING runs skips it - effect handler wiring: build_effect_handlers(...) (src/abstractruntime/integrations/abstractcore/effect_handlers.py) - tool executors: MappingToolExecutor, AbstractCoreToolExecutor, PassthroughToolExecutor, ApprovalToolExecutor, ToolApprovalPolicy (src/abstractruntime/integrations/abstractcore/tool_executor.py) - discovery-facade delegation is implemented by the configured AbstractCore LLM clients in src/abstractruntime/integrations/abstractcore/llm_client.py (list_providers, list_provider_models, get_voice_catalog (with language=), list_tts_models, list_stt_models, list_music_providers, list_music_models, list_vision_provider_models, list_cached_vision_models, list_vision_adapters) - the host's OpenAI credential for AbstractVoice's openai engines, voice_openai_api_key, travels two ways. For discovery, pass it to get_voice_catalog, list_tts_models or list_stt_models; the local clients hand it to the voice plugin's config, and a remote client never sends it (a remote AbstractCore server uses its own voice configuration). For execution, put it in create_local_runtime(llm_kwargs={"voice_openai_api_key": ...}). Constructor kwargs become the provider's config, which is also the capability-plugin config. Providers read only the keys they name, so a voice_* key changes no text request (tests tests/test_voice_openai_api_key_path.py) - host-facade client delegation is implemented by the configured AbstractCore LLM clients in src/abstractruntime/integrations/abstractcore/llm_client.py (get_prompt_cache_capabilities, get_prompt_cache_stats, prompt_cache_set, prompt_cache_update, prompt_cache_fork, prompt_cache_clear, prompt_cache_prepare_modules, upsert_text_bloc, get_bloc_record, list_blocs, get_bloc_kv_manifest, ensure_bloc_kv_artifact, load_bloc_kv_artifact, list_bloc_kv_artifacts, delete_bloc_kv_artifact, prune_bloc_kv_artifacts, delete_bloc, get_model_residency_capabilities, list_model_residency, load_model_residency, unload_model_residency, get_memory_snapshot, list_session_prompt_caches, clear_session_prompt_caches, lock_model_residency, unlock_model_residency, get_context_estimate); the last six are optional in the client contract, and the facade returns {"ok": false, "supported": false, ...} when the configured client does not implement one - integrations.abstractcore.llm_client.set_default_model_warmup(enabled) (process-wide, no environment variable): whether a new MultiLocalAbstractCoreLLMClient builds (for a local model: loads) its default model at construction and on a default switch. Default on. A process that serves no model turns it off once at boot (the gateway's serve --no-runner); the default client is then built at its first call. default_model_warmup() reads the setting (see integrations/abstractcore.md#unloading-and-switching-models) - switching the default model (set_default_provider_model on the pooled client) unloads the previous in-process model unless an owner in the process still uses it; list_model_residency diagnostics report pending_ejects and last_switch_ejects, and unload_model_residency(runtime_id=...) accepts any listed local:<task>:<provider>:<model> id, including local:embedding:<provider>:<model> rows (see integrations/abstractcore.md#unloading-and-switching-models) - lock_model_residency, unlock_model_residency, and get_context_estimate accept an optional payload mapping and/or keyword arguments (keyword arguments win on conflicts); a lock requires provider-verified residency — locking a non-resident pair refuses with a structured model_not_resident payload (load with lock: true instead; remotely the Core server's HTTP 409 refusal is converted to the same payload), while unlock never requires residency so a locked-but-evicted pair is always releasable; a locked model refuses unload_model_residency with a structured model_locked payload — locally as a client-side per-(provider, model) lock, remotely by converting the Core server's HTTP 409 refusal — and unloads only with force=true, releasing the lock only after the unload succeeds - the MODEL_RESIDENCY effect supports list_loaded, load, unload, lock, and unlock operations with the same soft-fail semantics; on unload, force is forwarded only when authored in the effect payload - local list_model_residency merges AbstractCore's host-wide loaded-model sweep into text-generation listings (sweep-only rows carry source: "provider_server" and no task label), and residency rows normalize provider size extras to size_bytes / size_vram_bytes while keeping the originals; local text rows also carry registry-declared modalities (omitted on a registry miss), host identity (host_id / host_name), and runtime-owned lock truth (locked / lockable, with pinned a truthful alias of locked — never the default-identity flag, which default alone carries), while remote listings keep the Core server's row identity - host-local prompt-cache export/import admin also lives on the host facade and client delegation layer (list_prompt_cache_exports, prompt_cache_export, prompt_cache_import) and is intentionally local-only - host-facade email helpers (list_email_accounts, list_emails, read_email, send_email) use the process's own AbstractCore account (single-user installs) - run-facade helpers create and resume durable child runs for existing runs (execute_llm_call, execute_tool_calls, resume_tool_calls, generate_image, edit_image, upscale_image, generate_video, image_to_video, generate_voice, generate_music, decide, transcribe_audio, send_email, send_telegram_message) - task-specific image/video helpers preserve batch and adapter controls such as count/n, seeds, ordered lora_adapters, and video flow_shift; local subprocess isolation stays within the same public contract.

Execution controls and cancellation: - params.thinking (bool or reasoning level) and params.speculation (False, True, or a Core speculation object such as {"mode": "native_mtp", "num_draft_tokens": 2}) are forwarded locally and remotely; run.vars["_runtime"]["speculation"] sets a run-wide preference inherited by subworkflows, Agent loops and delegated calls, and False stays Off across every boundary (see integrations/abstractcore.md#execution-controls-and-local-concurrency) - get_abstractcore_discovery_facade(...).get_execution_capabilities(model_name=None, provider=None) asks the actual execution host (local or remote) what it supports, without loading a model - the LLM_CALL handler hands the effect's cancel event to AbstractCore (generate(..., cancel_event=...)); remote clients close the request to the AbstractCore server on Stop, which the server treats as a cancel - every LLM_CALL is offered a progress callback; providers that report text phases (prefill / generate / complete) produce abstract.progress ledger events with kind: "llm" - abstractruntime.turn_grounding.stamp_user_turn_grounding(messages, grounding=...) writes the grounding envelope once into the stored user turn, so the prompt sent to the model stays a byte prefix of the next turn's prompt

LLM_CALL payloads are JSON-safe effect payloads. Common fields: - prompt, messages, system_prompt, and convenience text - media: a media path, artifact ref ({"$artifact": "..."} or {"artifact_id": "..."}), media dict, or list of those - output: AbstractCore output selector; top-level outputs is accepted as a runtime alias - params: provider/model routing, generation controls, prompt-cache keys or prompt_cache_binding, structured-output schema options, and tracing metadata - response_schema / response_schema_name: JSON schema data and name for a structured result at result.data; local execution creates the validator at the provider boundary. Structured calls do not stream tokens. Remote/hybrid clients forward an OpenAI JSON-schema response format; Python validator classes cannot cross HTTP. See structured responses.

Multimodal support: - common remote-light AbstractCore media, vision, voice, audio, and music dependencies are part of the base Runtime install - local clients call AbstractCore's unified generate(..., media=..., output=...) - remote and hybrid clients support AbstractCore Server chat media content arrays plus image generation, image edits, image upscaling, text-to-video, image-to-video, speech, music generation, transcription, and decision (POST /v1/decisions) endpoints; pass an output-specific model for remote media provider routing, otherwise the server endpoint can use its configured capability default - remote transcription requires one audio media item that resolves to a local file path or artifact-backed temporary file - a transcription result's metadata carries language (what the engine was told; None = it detected the language) and detected_language (the ISO 639-1 code the engine reported, None when it reports none) — the remote client copies them from the Core server's answer, the in-process client keeps them in the text's own metadata (text.metadata) - generated image/video/voice/music/audio bytes require a runtime ArtifactStore; the result contains artifact_id / artifact_ref instead of inline bytes - a decision (output: {"modality": "decision", "questions": {...}}, the state as the prompt) is typed answers, not bytes: no ArtifactStore is needed, and the result carries content (the answers as JSON), decision (model, answers, usage, latency_ms, optional truncated), answers, and the provider / model of the decision model; the resolved action id is decision. Without a model the call uses the output.decision capability default, so a text runtime on any provider can answer decisions once that default is set (see decisions) - streamed TTS playback artifacts carry purpose=voice_playback, artifact_space=voice and a logical voice/tts-<id>.wav path in their tags; hosts can separate read-aloud recordings from user attachments while retaining their artifact refs and provenance - with the pooled local client (MultiLocalAbstractCoreLLMClient), a request whose outputs are all non-text (image, video, voice, music, transcription, decision) and that carries no tools never builds the text client: it runs on AbstractCore's capability host (CapabilityHostProvider, no text model), and so does streaming TTS. A text default that cannot be built (an engine not installed) therefore never blocks speech or image generation - media-only normalized results expose runtime_provider / runtime_model separately from media_provider / media_model - local image/video generation runs in a one-shot subprocess (execution_mode="local_one_shot_subprocess") unless every requested media model is resident (explicitly loaded with load_model_residency), in which case it runs in-process on the loaded pipeline (execution_mode="resident_in_process", resident_load_ids) - a media spec whose provider is an endpoint profile (endpoint:<id>) never uses the one-shot subprocess: it is an HTTP call to that endpoint, and the host's endpoint-profile resolver (set_provider_endpoint_profile_resolver) exists only in this process - the LLM_CALL handler resolves only the call's own provider (endpoint:<id> on the effect payload) into Core routing params (_provider, base_url, provider_api_key); an endpoint profile named on an output spec stays on the spec, and the media plugin resolves it through the resolver the host attached to the client. Every client the pooled client builds carries that resolver: the text clients, the per-call override clients and the media host that serves media-only calls - optional local media residency failures complete with status_hint="warning" and degraded=true; local media warmup that no capability plugin can serve (image_generation, image_upscale, video_generation, text_to_video, image_to_video, tts, stt, music_generation) reports requires_long_lived_server=true, and image/video tasks also report execution_mode="local_one_shot_subprocess" - Gateway/hosts remain responsible for explicit Core server URLs, Core server auth headers, provider/model defaults, selected local-inference profiles, and translation of Gateway-owned env/config into explicit Runtime inputs; Runtime persists only JSON-safe routing metadata and artifact refs

Prompt cache / cached sessions: - LLM clients expose cache control methods listed above for host-side preparation and inspection - LLM_CALL.params.prompt_cache_key selects a cache key for a call; runtime can also derive a session-scoped key from run.vars["_runtime"]["prompt_cache"] or the Runtime-owned ABSTRACTRUNTIME_PROMPT_CACHE process default - LLM_CALL.params.prompt_cache_binding is the durable exact-reuse input for bloc-backed prompt caching; if a binding includes key, Runtime adopts it as the effective prompt-cache key and refuses mismatches before provider execution - Runtime only auto-derives session prompt-cache keys for text/chat calls; non-text output selectors such as image, voice, music, decision, and transcription keep explicit prompt_cache_binding support but do not receive an inferred cache key - when Runtime injects the derived session key, the client stamps session attribution (session_id, run_id, workflow_id, node_id, namespace) into the cache entry's metadata after each generate; caller-supplied prompt_cache_keys and binding keys are never stamped, so session-scoped clearing cannot destroy caches shared across sessions - get_abstractcore_host_facade(...) exposes get_memory_snapshot(), list_session_prompt_caches(session_id=None), and clear_session_prompt_caches(session_id); session caches persist until a host clears them, the owning model is unloaded, or the provider evicts them — completing a run does not clear them - get_abstractcore_host_facade(...) also exposes durable bloc helpers (upsert_text_bloc, get_bloc_record, list_blocs, get_bloc_kv_manifest, ensure_bloc_kv_artifact, load_bloc_kv_artifact, list_bloc_kv_artifacts, delete_bloc_kv_artifact, prune_bloc_kv_artifacts, delete_bloc) - local Runtime owns the bloc root policy: ~/.abstractruntime/blocs by default, <base_dir>/blocs for create_local_file_runtime(...), and explicit bloc_root_dir=... overrides when needed - provider cache/session handles are not durable runtime state and should not be stored in RunState.vars

Workspace scope: - run vars workspace_root, workspace_access_mode, workspace_allowed_paths, workspace_ignored_paths, and the host-only workspace_builtin_deny_prefixes / workspace_builtin_allow scope file and shell tools; child runs inherit them (see integrations/abstractcore.md#workspace-scoped-tools)

Attachment registration limits: - TOOL_CALLS.payload.max_attachment_bytes, run.vars["_runtime"]["max_attachment_bytes"], or ABSTRACTRUNTIME_MAX_ATTACHMENT_BYTES bound the bytes Runtime stores when local read_file outputs are captured as session attachments

Docs: integrations/abstractcore.md.

AbstractMemory bridge (KG effects)

Implementation: src/abstractruntime/integrations/abstractmemory/effect_handlers.py.

This provides handlers for MEMORY_KG_* effects and MEMORY_REVISE (opt-in wiring layer): build_memory_kg_effect_handlers(store=, run_store=, now_iso=, journal=None). MEMORY_REVISE applies one revision of a mind (assert / close / narrow ops) through abstractmemory.graph.MemoryGraph, stamped with the step that applied it; VisualFlow node type memory_revise. Payload and result: MEMORY_REVISE.

AbstractMemory facade (host surface)

abstractruntime.integrations.abstractmemory.memory_facade is the only way a host reaches AbstractMemory (ADR 0011; AbstractMemory 0.5.2+):

  • MemoryFacade.open_mind(path, *, embedder=None, **stores); MemoryFacade(graph=, ledger_store=, run_store=, artifact_store=, diary_store=, event_inbox=, runtime_id=); .graph, .store, .journal
  • stamp(provenance, *, run_id, seq=None, step_id=None, artifact_ids=(), runtime_id=None) -> dict and stamp_current_step(provenance, *, run_id, artifact_ids=()): add step / run / artifact SourceRefs, never for a synthetic run id (is_real_run), never a guessed seq
  • reconstruct_source(ref) -> {"status": "ok" | "source_gone" | "unsupported", ...}; never raises for a missing source
  • history(memory_id), sources_of(memory_id), derived_from_source(ref), apply_revision(revision)
  • GATEWAY_NAMES: AbstractMemory names re-exported unchanged (memory_facade.X is abstractmemory.X), resolved lazily

Ledger row address: LedgerStore.get_record(run_id, seq) (slim markers resolved, offloaded leaves rehydrated), list() records carry "seq", append() returns it. Step context: abstractruntime.core.step_context.current_step_context(run_id) inside an effect handler. Details: integrations/abstractmemory.md.

Utilities (host UX)

  • Rendering helpers: abstractruntime.rendering.stringify_json(...) and abstractruntime.rendering.render_agent_trace_markdown(...) (src/abstractruntime/rendering/*)
  • Active-context helpers (what is sent to the LLM): ActiveContextPolicy, TimeRange (src/abstractruntime/memory/active_context.py, exports in src/abstractruntime/memory/__init__.py)

See also

  • ../README.md — install + quick start
  • getting-started.md — first durable workflow
  • architecture.md — component map + durability invariants
  • faq.md — common questions and gotchas
  • integrations/abstractcore.md — LLM_CALL / TOOL_CALLS wiring
  • integrations/abstractmemory.md — memory facade, provenance stamping, MEMORY_REVISE

Host ASGI serving

abstractruntime.integrations.abstractcore.server_facade.start_core_server(*, host=None, port=None) starts Core's optional listener in the calling execution process. It returns a Core-owned handle with url, is_running, status() and stop(). Core owns configuration, credentials and HTTP request handling; stopping the listener does not unload resident providers. Omitted bind arguments use Core server settings; explicit port 0 selects an ephemeral port. Startup errors raise to the caller. Importing the facade starts nothing. See host-managed serving.

abstractruntime.integrations.abstractcore.server_facade.serve_core_request(scope, receive, send, *, token: str, allow_unauthenticated: bool = False) delegates host-admitted ASGI requests with request-scoped Core authentication. See host-managed serving for network and credential responsibilities.

Structured-output checks

abstractruntime.integrations.abstractcore.structured_facade.parse_response_format(raw) -> (kind, schema, name) checks an OpenAI response_format and raises ResponseFormatError (AbstractCore's own class, with .param) for an unusable one. Both are also exported flat from abstractruntime.integrations.abstractcore. Requires AbstractCore 2.25.0 or newer. See structured-output checks for hosts.

Diary resolution projections

DIARY_WRITE projects resolves, the recorded resolves_status, and an available resolved_record_id onto the memory of the act. A public target's resolved_title is omitted when either entry is private. A replay uses the stored diary entry and the chain prefix before it, preserving its original verdict. Failed target reads or projection writes retain the diary act and return labelled warnings; replay can retry the deferred projection. Upgrading does not backfill existing graph assertions.

Selected Hugging Face repository details

config_facade.model_catalog(..., hub=True, detail_repo="org/repo", extended=True) forwards one explicit repository detail request to Core. Ordinary searches use summary pages and a shared quota cooldown. A Core without this detail operation raises AbstractCoreTooOld; missing sizes are not silently filled by per-result lookups.