avatar-runtime 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. avatar_runtime-0.1.0/LICENSE +201 -0
  2. avatar_runtime-0.1.0/NOTICE +7 -0
  3. avatar_runtime-0.1.0/PKG-INFO +373 -0
  4. avatar_runtime-0.1.0/README.md +336 -0
  5. avatar_runtime-0.1.0/avatar/__init__.py +45 -0
  6. avatar_runtime-0.1.0/avatar/api/__init__.py +10 -0
  7. avatar_runtime-0.1.0/avatar/api/app.py +106 -0
  8. avatar_runtime-0.1.0/avatar/api/ratelimit.py +36 -0
  9. avatar_runtime-0.1.0/avatar/api/routes.py +350 -0
  10. avatar_runtime-0.1.0/avatar/cli.py +194 -0
  11. avatar_runtime-0.1.0/avatar/config.py +119 -0
  12. avatar_runtime-0.1.0/avatar/dashboard/index.html +301 -0
  13. avatar_runtime-0.1.0/avatar/dashboard/landing.html +352 -0
  14. avatar_runtime-0.1.0/avatar/demo.py +168 -0
  15. avatar_runtime-0.1.0/avatar/engine/__init__.py +33 -0
  16. avatar_runtime-0.1.0/avatar/engine/_tool_runner.py +44 -0
  17. avatar_runtime-0.1.0/avatar/engine/budget.py +23 -0
  18. avatar_runtime-0.1.0/avatar/engine/db.py +98 -0
  19. avatar_runtime-0.1.0/avatar/engine/idempotency.py +42 -0
  20. avatar_runtime-0.1.0/avatar/engine/models.py +180 -0
  21. avatar_runtime-0.1.0/avatar/engine/policy.py +42 -0
  22. avatar_runtime-0.1.0/avatar/engine/registry.py +144 -0
  23. avatar_runtime-0.1.0/avatar/engine/replay.py +121 -0
  24. avatar_runtime-0.1.0/avatar/engine/runtime.py +411 -0
  25. avatar_runtime-0.1.0/avatar/engine/schema.sql +75 -0
  26. avatar_runtime-0.1.0/avatar/engine/tools.py +126 -0
  27. avatar_runtime-0.1.0/avatar/engine/worker.py +237 -0
  28. avatar_runtime-0.1.0/avatar/sdk/__init__.py +193 -0
  29. avatar_runtime-0.1.0/avatar_runtime.egg-info/PKG-INFO +373 -0
  30. avatar_runtime-0.1.0/avatar_runtime.egg-info/SOURCES.txt +41 -0
  31. avatar_runtime-0.1.0/avatar_runtime.egg-info/dependency_links.txt +1 -0
  32. avatar_runtime-0.1.0/avatar_runtime.egg-info/entry_points.txt +2 -0
  33. avatar_runtime-0.1.0/avatar_runtime.egg-info/requires.txt +16 -0
  34. avatar_runtime-0.1.0/avatar_runtime.egg-info/top_level.txt +1 -0
  35. avatar_runtime-0.1.0/pyproject.toml +62 -0
  36. avatar_runtime-0.1.0/setup.cfg +4 -0
  37. avatar_runtime-0.1.0/tests/test_api.py +70 -0
  38. avatar_runtime-0.1.0/tests/test_crash_resume.py +102 -0
  39. avatar_runtime-0.1.0/tests/test_engine.py +68 -0
  40. avatar_runtime-0.1.0/tests/test_policy_budget.py +90 -0
  41. avatar_runtime-0.1.0/tests/test_replay.py +83 -0
  42. avatar_runtime-0.1.0/tests/test_schema_drift.py +99 -0
  43. avatar_runtime-0.1.0/tests/test_startup_safety.py +36 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Avatar Runtime Authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,7 @@
1
+ Avatar Engine
2
+ Copyright 2026 Avatar Runtime Authors
3
+
4
+ This product includes software developed by the Avatar Runtime Authors
5
+ (https://github.com/avatar-runtime/avatar-engine).
6
+
7
+ Licensed under the Apache License, Version 2.0. See the LICENSE file.
@@ -0,0 +1,373 @@
1
+ Metadata-Version: 2.4
2
+ Name: avatar-runtime
3
+ Version: 0.1.0
4
+ Summary: Temporal for AI agents — a Postgres-native durable execution engine for AI agent workflows.
5
+ Author: Avatar Runtime Authors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/avatar-runtime/avatar-engine
8
+ Project-URL: Repository, https://github.com/avatar-runtime/avatar-engine
9
+ Project-URL: Documentation, https://github.com/avatar-runtime/avatar-engine/blob/main/docs/AVATAR.md
10
+ Project-URL: Issues, https://github.com/avatar-runtime/avatar-engine/issues
11
+ Keywords: durable-execution,ai-agents,workflow,postgres,idempotency,crash-recovery
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
17
+ Classifier: Topic :: System :: Distributed Computing
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ License-File: NOTICE
22
+ Requires-Dist: fastapi>=0.110
23
+ Requires-Dist: uvicorn[standard]>=0.27
24
+ Requires-Dist: sqlalchemy[asyncio]>=2.0
25
+ Requires-Dist: pydantic>=2.6
26
+ Requires-Dist: httpx>=0.27
27
+ Requires-Dist: aiosqlite>=0.19
28
+ Provides-Extra: postgres
29
+ Requires-Dist: asyncpg>=0.29; extra == "postgres"
30
+ Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
31
+ Provides-Extra: dev
32
+ Requires-Dist: pytest>=8; extra == "dev"
33
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
34
+ Requires-Dist: anyio>=4; extra == "dev"
35
+ Requires-Dist: ruff>=0.6; extra == "dev"
36
+ Dynamic: license-file
37
+
38
+ # Avatar Engine
39
+
40
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
41
+ [![CI](https://github.com/avatar-runtime/avatar-engine/actions/workflows/ci.yml/badge.svg)](https://github.com/avatar-runtime/avatar-engine/actions/workflows/ci.yml)
42
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/)
43
+
44
+ **Temporal for AI agents.** A Postgres-native durable execution engine for AI
45
+ agent workflows — crash-safe, replayable, idempotent. Backed entirely by Postgres.
46
+
47
+ Wrap your existing tool-calling agent loop and get crash-safety, an append-only
48
+ step ledger, idempotent tool dispatch, deterministic replay, and a dashboard to
49
+ watch it all — without writing any of that yourself.
50
+
51
+ ```
52
+ SDK → API → Postgres → Worker → Tools
53
+ ↑ ↓
54
+ Dashboard ← SSE stream
55
+ ```
56
+
57
+ > **The one guarantee:** a worker can die at any point in a run and another
58
+ > resumes from the ledger — no step is lost. **Tool dispatch attempts may repeat,
59
+ > but tool effects cannot duplicate when idempotency is enforced.**
60
+ >
61
+ > Stated precisely: *at-most-once dispatch from Avatar always; exactly-once
62
+ > end-to-end iff the tool honors the idempotency key.* We never claim
63
+ > unconditional exactly-once.
64
+
65
+ ---
66
+
67
+ ## Why
68
+
69
+ LangChain-style frameworks give you the agent loop but no durability. Temporal
70
+ gives you durability but no agent/tool/LLM semantics. Avatar is the only thing
71
+ that is **both agent-native and crash-safe** — and its only infrastructure
72
+ dependency is Postgres. The `runs` table *is* the queue. No Redis, no broker.
73
+
74
+ ## Documentation
75
+
76
+ - **[The Complete Guide](docs/AVATAR.md)** — the comprehensive doc: mental model,
77
+ architecture, execution semantics, the concurrency model as theorems, the
78
+ failure taxonomy, the Guarantees Spec, positioning, adoption metrics, what's
79
+ done, and the roadmap (v1 → v2 Cloud → v3). Start here.
80
+ - **[Deployment](docs/deployment.md)** — production guide (TLS, scaling, backups,
81
+ observability).
82
+ - **[Security](SECURITY.md)** — the auth model, its limits, and production
83
+ must-dos.
84
+
85
+ ## The 30-second proof: a refund that survives a crash
86
+
87
+ ```bash
88
+ git clone https://github.com/avatar-runtime/avatar-engine.git
89
+ cd avatar-engine
90
+ pip install -e . # (PyPI: pip install avatar-runtime — coming soon)
91
+ python -m avatar.cli demo
92
+ ```
93
+
94
+ The demo runs `lookup_order → issue_refund → email_customer`. A worker is killed
95
+ **after `issue_refund` dispatches but before its observation commits** (the
96
+ decisive crash window). A fresh worker re-leases the run, rebuilds from the
97
+ ledger, and finishes it:
98
+
99
+ ```
100
+ ---- timeline ----
101
+ #1 [plan]
102
+ #2 [tool_call] c1
103
+ #3 [observation] c1
104
+ #4 [plan]
105
+ #5 [tool_call] c2
106
+ ▸ resumed by host:6226 (attempt 2) ← worker crashed here; another took over
107
+ #6 [observation] c2
108
+ ...
109
+ #11 [final]
110
+ ------------------
111
+ run status : succeeded
112
+ dispatch attempts : 2 (the tool was physically called twice — crash + resume)
113
+ tool effects : 1 (one actual refund)
114
+
115
+ ✅ "Crashed mid-refund. Restarted. The refund wasn't issued twice."
116
+ Tool dispatch attempts may repeat, but tool effects cannot duplicate
117
+ when idempotency is enforced.
118
+ ```
119
+
120
+ ## Quickstart with `docker compose`
121
+
122
+ ```bash
123
+ docker compose up # Postgres + control API + dashboard + 1 worker
124
+ # scale workers: docker compose up --scale worker=3
125
+ ```
126
+
127
+ Then open the dashboard at **http://localhost:8088** (the compose host port;
128
+ the container serves on 8080), enqueue a run, and watch its live step timeline —
129
+ including the visible *"resumed after crash"* marker.
130
+
131
+ ## Use it from Python
132
+
133
+ ```python
134
+ from avatar import Avatar, tool, Plan, ToolCall
135
+
136
+ app = Avatar(api_url="http://localhost:8080", api_key="dev-key")
137
+
138
+ @tool(timeout=10, retries=2)
139
+ def issue_refund(order_id: str, cents: int) -> dict:
140
+ # Your real side effect. Forward avatar.current_idempotency_key() to the
141
+ # downstream service to get exactly-once end-to-end.
142
+ return {"refunded": True}
143
+
144
+ @app.agent("support-resolver")
145
+ def resolve(state):
146
+ # A model function: read the rebuilt state, return the next Plan.
147
+ if any(m["role"] == "tool" for m in state.messages):
148
+ return Plan(final=True, output={"status": "done"})
149
+ return Plan(tool_calls=[ToolCall(id="c1", name="issue_refund",
150
+ arguments={"order_id": "42", "cents": 500})])
151
+
152
+ run = app.runs.create(agent_ref="support-resolver", input={"ticket_id": 42})
153
+ print(app.runs.wait(run["id"]))
154
+ ```
155
+
156
+ Point the worker at your module with `AVATAR_APP=yourpkg.agents` and run
157
+ `avatar worker`. The engine drives the durable loop; you write only the model
158
+ call and the tools.
159
+
160
+ ### SDK reference
161
+
162
+ **Authoring** (imported by the worker via `AVATAR_APP`):
163
+
164
+ | Symbol | Purpose |
165
+ |---|---|
166
+ | `@tool(timeout=, retries=, idempotent=)` | Register a developer function as a governed tool. |
167
+ | `@app.agent(ref)` / `@agent(ref)` | Register a model function `(State) -> Plan` under `ref`. |
168
+ | `Plan(content=, tool_calls=[], final=, output=, cost_cents=)` | The model's output for one step. A plan with no tool calls is final. |
169
+ | `ToolCall(id, name, arguments)` | One tool invocation. A **stable `id`** keeps idempotency crash-stable. |
170
+ | `State.input` / `State.messages` | The rebuilt-from-ledger view handed to the model each iteration. |
171
+ | `current_idempotency_key()` | Inside a tool: the key to forward to your downstream service. |
172
+
173
+ **Control client** (`app.runs.*`, usable anywhere):
174
+
175
+ | Call | Maps to |
176
+ |---|---|
177
+ | `runs.create(agent_ref=, input=, budget_cap_cents=, idempotency_key=)` | `POST /v1/runs` |
178
+ | `runs.get(id)` · `runs.list(status=, limit=)` · `runs.steps(id)` | `GET /v1/runs…` |
179
+ | `runs.wait(id, timeout=)` | poll until terminal / `approval_wait` |
180
+ | `runs.stream(id)` | SSE generator of step events |
181
+ | `runs.cancel(id)` · `runs.approve(id)` · `runs.reject(id)` | the POST actions |
182
+ | `runs.replay(id, from_seq=)` | `POST /v1/runs/{id}/replay` (fork) |
183
+
184
+ ### Tools, idempotency, and the honest guarantee
185
+
186
+ A tool receives the idempotency key for the in-flight call via
187
+ `current_idempotency_key()`. Forward it to your downstream (e.g. Stripe's
188
+ `Idempotency-Key` header). On a crash between dispatch and observation, Avatar
189
+ re-dispatches with the **same** key, so:
190
+
191
+ - **At-most-once dispatch from Avatar** — always, via the committed intent step.
192
+ - **Exactly-once end-to-end** — iff your tool/downstream honors the key.
193
+
194
+ Tools run in-process by default; set `AVATAR_TOOL_ISOLATION=subprocess` to run
195
+ each in a child process with the wall-clock timeout and output-size cap enforced.
196
+ A crashing in-proc tool can take the worker down, so use `subprocess` for anything
197
+ less than fully trusted. **There is no network/SSRF sandbox** (deliberately cut from
198
+ the wedge) — do not run untrusted third-party agent code yet. See [SECURITY.md](SECURITY.md).
199
+
200
+ **Budgets stop runs, not in-flight calls.** `budget_cap_cents` halts a run *before
201
+ its next step* once the cap is reached; the model/tool call already in flight is not
202
+ cancelled (its provider cost is already incurred). Treat the cap as a circuit
203
+ breaker, not a pre-charge.
204
+
205
+ ## How it works
206
+
207
+ The engine is a state machine over two Postgres tables (`avatar/engine/schema.sql`):
208
+
209
+ - **`runs`** — the durable run record *and* the work queue. Workers atomically
210
+ lease rows with `FOR UPDATE SKIP LOCKED` (Postgres) or a compare-and-swap
211
+ (SQLite), renew a heartbeated lease, and a guarded update means a worker that
212
+ lost its lease can never commit.
213
+ - **`run_steps`** — an append-only, seq-ordered ledger. Steps are never updated
214
+ or deleted; **all run state is a pure fold over this table**, which is what
215
+ makes crash-resume and replay deterministic.
216
+
217
+ The invariant that makes it safe:
218
+
219
+ > Every tool call is preceded by a committed `tool_call` (intent) step, and its
220
+ > result is recorded under `UNIQUE(run_id, idempotency_key)`.
221
+
222
+ So on resume an already-observed call short-circuits to its recorded result, and
223
+ a call dispatched-but-not-observed (the crash window) is re-dispatched with the
224
+ **same** idempotency key — the downstream dedupes it.
225
+
226
+ The execution loop (`avatar/engine/runtime.py`):
227
+
228
+ ```
229
+ rebuild state from the ledger
230
+ loop:
231
+ heartbeat (and confirm we still own the lease)
232
+ if pending tool calls:
233
+ for each: policy check → commit intent → dispatch → commit observation
234
+ else:
235
+ call the model → commit plan (final ⇒ commit final, succeed)
236
+ ```
237
+
238
+ ## Features
239
+
240
+ | | |
241
+ |---|---|
242
+ | **Crash-safe** | Lease + heartbeat + ledger replay. Kill `-9` any worker. |
243
+ | **Idempotent tools** | Crash-stable key per tool call; `UNIQUE(run_id, key)`. |
244
+ | **Policy hook** | `allow` / `deny` / `require_approval` before every dispatch. |
245
+ | **Budget** | Per-run `budget_cap_cents` hard-stop. |
246
+ | **Replay / fork** | Re-run a trace prefix without re-calling the model or re-running tools. |
247
+ | **Control API** | REST + SSE, single static API-key auth. |
248
+ | **Dashboard** | Runs list, step-ledger timeline, live SSE, crash-resume markers, fork. |
249
+
250
+ ## Control API
251
+
252
+ `Authorization: Bearer $AVATAR_API_KEY` on every `/v1` route.
253
+
254
+ | Method | Path | Purpose |
255
+ |---|---|---|
256
+ | POST | `/v1/runs` | Enqueue `{agent_ref, input, budget_cap_cents?, idempotency_key?}` |
257
+ | GET | `/v1/runs` | List / filter (`?status=&limit=`) |
258
+ | GET | `/v1/runs/{id}` | Status + summary |
259
+ | GET | `/v1/runs/{id}/steps` | The append-only ledger |
260
+ | GET | `/v1/runs/{id}/stream` | SSE — live step events |
261
+ | POST | `/v1/runs/{id}/cancel` | Cooperative cancel |
262
+ | POST | `/v1/runs/{id}/approve` · `/reject` | Resolve an `approval_wait` |
263
+ | POST | `/v1/runs/{id}/replay` | Fork from a step: `{from_seq}` |
264
+ | GET | `/healthz` · `/readyz` | Liveness / readiness |
265
+
266
+ ## Dashboard
267
+
268
+ A single-page client of the API (served at `/`, the static API key injected so
269
+ local dev needs no login). Four views:
270
+
271
+ - **Runs** (`#/`) — table of id, agent, status badge, attempt, cost, age;
272
+ auto-refreshing, with a pulse on `running` and red/amber badges for
273
+ `failed`/`dead`/`approval_wait`.
274
+ - **Run detail** (`#/runs/:id`) — the centerpiece. The append-only
275
+ **step-ledger timeline**: each step (`plan / tool_call / observation /
276
+ approval_wait / final / error`) is expandable to its payload JSON, with its
277
+ `tool_call_id`, `idempotency_key`, committing `worker_id`, and `attempt`. A
278
+ **▸ resumed after crash (attempt N)** divider marks where another worker took
279
+ over. Live updates via SSE. **Fork here** on every step, and
280
+ **Approve / Reject / Cancel** when applicable.
281
+ - **Demo** (`#/demo`) — a narrated one-screen view of the crash-resume story,
282
+ surfacing any crash-resumed (`attempt ≥ 2`) refund run.
283
+ - **Health** (`#/health`) — totals, queue depth, status breakdown.
284
+
285
+ ## Configuration
286
+
287
+ Everything is an env var — one infra dependency (Postgres), one auth secret.
288
+ See [`.env.example`](.env.example).
289
+
290
+ | Var | Default | Purpose |
291
+ |---|---|---|
292
+ | `AVATAR_DATABASE_URL` | `sqlite+aiosqlite:///./avatar.db` | Postgres (`postgresql+asyncpg://…`) in production. |
293
+ | `AVATAR_API_KEY` | `dev-key` | The single static Bearer key. **Required & strong in prod** (see below). |
294
+ | `AVATAR_DEV_MODE` | `0` | `1` for local dev only — relaxes the prod key guard, injects the key into the dashboard. |
295
+ | `AVATAR_APP` | — | Module(s) to import so `@agent`/`@tool` register (e.g. `yourpkg.agents`). |
296
+ | `AVATAR_LEASE_SECONDS` | `30` | Lease TTL; a worker silent this long is treated as crashed. |
297
+ | `AVATAR_HEARTBEAT_SECONDS` | `10` | In-loop lease renewal cadence. |
298
+ | `AVATAR_POLL_INTERVAL_MS` | `500` | Worker poll when the queue is empty. |
299
+ | `AVATAR_MAX_STEPS` | `50` | Runaway-plan guard per run. |
300
+ | `AVATAR_MAX_ATTEMPTS` | `5` | Re-leases before a poison run → `dead`. |
301
+ | `AVATAR_TOOL_TIMEOUT_SECONDS` | `30` | Per-tool wall-clock timeout. |
302
+ | `AVATAR_TOOL_ISOLATION` | `inproc` | `inproc` or `subprocess` (use `subprocess` for less-trusted tools). |
303
+ | `AVATAR_RATE_LIMIT_PER_SECOND` / `_BURST` | `50` / `100` | Per-process enqueue throttle. |
304
+ | `AVATAR_MAX_QUEUE_DEPTH` | `10000` | Enqueue returns `429` above this. |
305
+ | `AVATAR_DB_POOL_SIZE` / `_MAX_OVERFLOW` | `10` / `20` | Per-process Postgres connection pool. |
306
+
307
+ > **Production:** the API and worker **refuse to boot** in non-dev mode with an
308
+ > unset or default key. Generate one (`openssl rand -hex 32`), and run behind TLS.
309
+ > The full guide — Caddy/TLS compose, backups/PITR, scaling, observability,
310
+ > tool-isolation caveats — is in **[docs/deployment.md](docs/deployment.md)** and
311
+ > **[SECURITY.md](SECURITY.md)**.
312
+
313
+ ## CLI
314
+
315
+ ```bash
316
+ avatar serve [--host --port] # control API + dashboard
317
+ avatar worker [--max-runs --max-idle] # a stateless durable worker (scale by running more)
318
+ avatar migrate # apply the canonical schema (idempotent)
319
+ avatar demo # the crash-resume killer demo
320
+ ```
321
+
322
+ ## Project layout
323
+
324
+ ```
325
+ avatar/
326
+ engine/ runs+run_steps models, schema.sql, execute_run, worker (lease/
327
+ heartbeat/resume), idempotency, tools, policy, budget, replay
328
+ api/ FastAPI control API (single-key auth) + SSE
329
+ sdk/ @agent / @tool decorators + REST/SSE client
330
+ demo.py the killer-demo agent + idempotent refund tool
331
+ cli.py avatar worker | serve | demo
332
+ config.py env-only settings
333
+ dashboard/ single-page dashboard + landing page (served at /app and /, packaged in the wheel)
334
+ tests/ engine, crash-resume (CRASH-C), idempotency, replay, policy/budget, API
335
+ ```
336
+
337
+ ## Development
338
+
339
+ ```bash
340
+ pip install -e ".[dev]"
341
+ pytest # SQLite (fast)
342
+ AVATAR_DATABASE_URL=postgresql+asyncpg://avatar:avatar@localhost:5432/avatar pytest
343
+ ```
344
+
345
+ The crash/race slice runs against **Postgres** in CI for the true
346
+ `FOR UPDATE SKIP LOCKED` path; SQLite covers the rest.
347
+
348
+ ## Scope
349
+
350
+ This is **single-purpose infrastructure**, not a platform. It is **not** a SaaS,
351
+ not multi-tenant, not a marketplace, not BYOK, not voice/avatars, not multi-agent
352
+ orchestration. Those belong to **Avatar Cloud** — the hosted, commercial control
353
+ plane built on top of this engine — not to the open-source engine. See the
354
+ roadmap in [docs/AVATAR.md](docs/AVATAR.md).
355
+
356
+ ## Versioning & releases
357
+
358
+ Changes are tracked in [CHANGELOG.md](CHANGELOG.md); the project follows
359
+ [SemVer](https://semver.org/) and the API is versioned (`/v1`). A PyPI release is
360
+ planned (`pip install avatar-runtime`); until then install from source
361
+ (`pip install -e .`).
362
+
363
+ ## Contributing & governance
364
+
365
+ Contributions are welcome — see [CONTRIBUTING.md](CONTRIBUTING.md),
366
+ [GOVERNANCE.md](GOVERNANCE.md), and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
367
+ Avatar Engine is company-led OSS and the open foundation of **Avatar Cloud**, the
368
+ hosted multi-tenant control plane built on top of it (the Temporal model).
369
+
370
+ ## License
371
+
372
+ Licensed under the **Apache License, Version 2.0** — see [LICENSE](LICENSE) and
373
+ [NOTICE](NOTICE). Copyright 2026 Avatar Runtime Authors.