agentstateprotocol 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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 AgentStateProtocol Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentstateprotocol
3
+ Version: 0.1.0
4
+ Summary: Checkpointing and recovery protocol for AI agents
5
+ Author: AgentStateProtocol Contributors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/ekessh/agentstateprotocol
8
+ Project-URL: Documentation, https://agentstateprotocol.readthedocs.io
9
+ Project-URL: Repository, https://github.com/ekessh/agentstateprotocol
10
+ Project-URL: Issues, https://github.com/ekessh/agentstateprotocol/issues
11
+ Keywords: ai,agents,checkpointing,recovery,state-management,llm,reasoning,rollback,branching
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=7.0; extra == "dev"
27
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # AgentStateProtocol
31
+
32
+ Checkpointing and recovery protocol for AI agents.
33
+
34
+ `AgentStateProtocol` lets an agent save state at each reasoning step, branch into alternatives, and roll back safely after failures.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install agentstateprotocol
40
+ ```
41
+
42
+ ## Quick Start
43
+
44
+ ```python
45
+ from agentstateprotocol import AgentStateProtocol
46
+
47
+ agent = AgentStateProtocol("my-agent")
48
+
49
+ agent.checkpoint(
50
+ state={"task": "summarize quarterly report", "stage": "parsed"},
51
+ metadata={"confidence": 0.91},
52
+ description="Initial parse",
53
+ logic_step="parse_input",
54
+ )
55
+
56
+ agent.checkpoint(
57
+ state={"task": "summarize quarterly report", "stage": "drafted"},
58
+ metadata={"confidence": 0.86},
59
+ description="Draft generated",
60
+ logic_step="draft_summary",
61
+ )
62
+
63
+ # Roll back one step if needed
64
+ agent.rollback()
65
+ ```
66
+
67
+ ## Core Operations
68
+
69
+ - `agent.checkpoint(...)`: save a state snapshot
70
+ - `agent.rollback(...)`: restore a previous checkpoint
71
+ - `agent.branch(name)`: start an alternate reasoning path
72
+ - `agent.switch_branch(name)`: move between branches
73
+ - `agent.merge(source_branch)`: merge branch outcomes
74
+ - `agent.history()`: inspect checkpoint timeline
75
+ - `agent.visualize_tree()`: show decision tree
76
+
77
+ ## Decorators
78
+
79
+ ```python
80
+ from agentstateprotocol.decorators import agentstateprotocol_step
81
+
82
+ @agentstateprotocol_step("analyze")
83
+ def analyze(state):
84
+ return {"result": "ok", **state}
85
+ ```
86
+
87
+ ## Storage
88
+
89
+ ```python
90
+ from agentstateprotocol.storage import FileSystemStorage, SQLiteStorage
91
+
92
+ file_storage = FileSystemStorage(".agentstateprotocol")
93
+ sqlite_storage = SQLiteStorage(".agentstateprotocol/agentstateprotocol.db")
94
+ ```
95
+
96
+ ## CLI
97
+
98
+ ```bash
99
+ agentstateprotocol demo
100
+ agentstateprotocol log
101
+ agentstateprotocol tree
102
+ agentstateprotocol branches
103
+ agentstateprotocol diff <checkpoint_a> <checkpoint_b>
104
+ agentstateprotocol metrics
105
+ ```
106
+
107
+ ## Project
108
+
109
+ - Repository: https://github.com/ekessh/agentstateprotocol
110
+ - License: MIT
@@ -0,0 +1,81 @@
1
+ # AgentStateProtocol
2
+
3
+ Checkpointing and recovery protocol for AI agents.
4
+
5
+ `AgentStateProtocol` lets an agent save state at each reasoning step, branch into alternatives, and roll back safely after failures.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install agentstateprotocol
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```python
16
+ from agentstateprotocol import AgentStateProtocol
17
+
18
+ agent = AgentStateProtocol("my-agent")
19
+
20
+ agent.checkpoint(
21
+ state={"task": "summarize quarterly report", "stage": "parsed"},
22
+ metadata={"confidence": 0.91},
23
+ description="Initial parse",
24
+ logic_step="parse_input",
25
+ )
26
+
27
+ agent.checkpoint(
28
+ state={"task": "summarize quarterly report", "stage": "drafted"},
29
+ metadata={"confidence": 0.86},
30
+ description="Draft generated",
31
+ logic_step="draft_summary",
32
+ )
33
+
34
+ # Roll back one step if needed
35
+ agent.rollback()
36
+ ```
37
+
38
+ ## Core Operations
39
+
40
+ - `agent.checkpoint(...)`: save a state snapshot
41
+ - `agent.rollback(...)`: restore a previous checkpoint
42
+ - `agent.branch(name)`: start an alternate reasoning path
43
+ - `agent.switch_branch(name)`: move between branches
44
+ - `agent.merge(source_branch)`: merge branch outcomes
45
+ - `agent.history()`: inspect checkpoint timeline
46
+ - `agent.visualize_tree()`: show decision tree
47
+
48
+ ## Decorators
49
+
50
+ ```python
51
+ from agentstateprotocol.decorators import agentstateprotocol_step
52
+
53
+ @agentstateprotocol_step("analyze")
54
+ def analyze(state):
55
+ return {"result": "ok", **state}
56
+ ```
57
+
58
+ ## Storage
59
+
60
+ ```python
61
+ from agentstateprotocol.storage import FileSystemStorage, SQLiteStorage
62
+
63
+ file_storage = FileSystemStorage(".agentstateprotocol")
64
+ sqlite_storage = SQLiteStorage(".agentstateprotocol/agentstateprotocol.db")
65
+ ```
66
+
67
+ ## CLI
68
+
69
+ ```bash
70
+ agentstateprotocol demo
71
+ agentstateprotocol log
72
+ agentstateprotocol tree
73
+ agentstateprotocol branches
74
+ agentstateprotocol diff <checkpoint_a> <checkpoint_b>
75
+ agentstateprotocol metrics
76
+ ```
77
+
78
+ ## Project
79
+
80
+ - Repository: https://github.com/ekessh/agentstateprotocol
81
+ - License: MIT
@@ -0,0 +1,29 @@
1
+ """
2
+ AgentStateProtocol package.
3
+
4
+ Checkpointing and recovery protocol for AI agents.
5
+ """
6
+
7
+ __version__ = "0.1.0"
8
+ __author__ = "AgentStateProtocol Contributors"
9
+
10
+ from .engine import AgentStateProtocol, Checkpoint, Branch, LogicTree
11
+ from .strategies import RecoveryStrategy, RetryWithBackoff, AlternativePathStrategy
12
+ from .serializers import StateSerializer, JSONSerializer, PickleSerializer
13
+ from .storage import StorageBackend, FileSystemStorage, SQLiteStorage
14
+
15
+ __all__ = [
16
+ "AgentStateProtocol",
17
+ "Checkpoint",
18
+ "Branch",
19
+ "LogicTree",
20
+ "RecoveryStrategy",
21
+ "RetryWithBackoff",
22
+ "AlternativePathStrategy",
23
+ "StateSerializer",
24
+ "JSONSerializer",
25
+ "PickleSerializer",
26
+ "StorageBackend",
27
+ "FileSystemStorage",
28
+ "SQLiteStorage",
29
+ ]
@@ -0,0 +1,318 @@
1
+ """
2
+ agentstateprotocol CLI — Command-line interface for inspecting agent state.
3
+
4
+ Usage:
5
+ python -m agentstateprotocol log # View checkpoint history
6
+ python -m agentstateprotocol tree # Visualize logic tree
7
+ python -m agentstateprotocol branches # List branches
8
+ python -m agentstateprotocol diff <id1> <id2> # Compare checkpoints
9
+ python -m agentstateprotocol inspect <checkpoint> # View checkpoint details
10
+ python -m agentstateprotocol metrics # Show agent metrics
11
+ python -m agentstateprotocol demo # Run interactive demo
12
+ """
13
+
14
+ import argparse
15
+ import json
16
+ import sys
17
+ import time
18
+ import random
19
+
20
+ from .engine import AgentStateProtocol
21
+ from .strategies import RetryWithBackoff, AlternativePathStrategy, DegradeGracefully
22
+ from .storage import FileSystemStorage
23
+
24
+
25
+ def create_parser() -> argparse.ArgumentParser:
26
+ parser = argparse.ArgumentParser(
27
+ prog="agentstateprotocol",
28
+ description="🧠 agentstateprotocol — Git for AI Thoughts",
29
+ )
30
+
31
+ subparsers = parser.add_subparsers(dest="command", help="Available commands")
32
+
33
+ # Log
34
+ log_parser = subparsers.add_parser("log", help="View checkpoint history")
35
+ log_parser.add_argument("--branch", default=None, help="Filter by branch")
36
+ log_parser.add_argument("--limit", type=int, default=20, help="Max entries")
37
+
38
+ # Tree
39
+ subparsers.add_parser("tree", help="Visualize logic tree")
40
+
41
+ # Branches
42
+ subparsers.add_parser("branches", help="List all branches")
43
+
44
+ # Diff
45
+ diff_parser = subparsers.add_parser("diff", help="Compare two checkpoints")
46
+ diff_parser.add_argument("checkpoint_a", help="First checkpoint ID")
47
+ diff_parser.add_argument("checkpoint_b", help="Second checkpoint ID")
48
+
49
+ # Inspect
50
+ inspect_parser = subparsers.add_parser("inspect", help="Inspect a checkpoint")
51
+ inspect_parser.add_argument("checkpoint_id", help="Checkpoint ID")
52
+
53
+ # Metrics
54
+ subparsers.add_parser("metrics", help="Show agent metrics")
55
+
56
+ # Demo
57
+ subparsers.add_parser("demo", help="Run interactive demonstration")
58
+
59
+ return parser
60
+
61
+
62
+ def run_demo():
63
+ """
64
+ Interactive demonstration of AgentStateProtocol capabilities.
65
+
66
+ Simulates an AI agent that:
67
+ 1. Receives a task
68
+ 2. Tries to solve it step by step
69
+ 3. Hits an error
70
+ 4. Rolls back and tries a different approach
71
+ 5. Branches to explore alternatives
72
+ 6. Merges the best result
73
+ """
74
+ print("\n" + "=" * 60)
75
+ print("🧠 AgentStateProtocol Demo — Git for AI Thoughts")
76
+ print("=" * 60)
77
+
78
+ # Initialize
79
+ agent = AgentStateProtocol(
80
+ "demo-agent",
81
+ recovery_strategies=[
82
+ RetryWithBackoff(base_delay=0.1, max_delay=1.0),
83
+ DegradeGracefully(),
84
+ ],
85
+ )
86
+
87
+ # Step 1: Receive task
88
+ print("\nšŸ“‹ Step 1: Agent receives a task")
89
+ print(" Task: 'Summarize the latest quarterly earnings report'")
90
+
91
+ cp1 = agent.checkpoint(
92
+ state={
93
+ "task": "Summarize quarterly earnings",
94
+ "status": "received",
95
+ "context": {"source": "user_request", "priority": "high"},
96
+ },
97
+ metadata={"confidence": 1.0, "tokens_used": 0},
98
+ description="Task received",
99
+ logic_step="task_intake",
100
+ )
101
+ print(f" āœ… Checkpoint saved: {cp1.id} (hash: {cp1.hash})")
102
+
103
+ # Step 2: Parse and plan
104
+ print("\nšŸ” Step 2: Agent parses the task and creates a plan")
105
+
106
+ cp2 = agent.checkpoint(
107
+ state={
108
+ "task": "Summarize quarterly earnings",
109
+ "plan": [
110
+ "1. Retrieve earnings document",
111
+ "2. Extract key financial metrics",
112
+ "3. Identify trends vs previous quarter",
113
+ "4. Generate executive summary",
114
+ ],
115
+ "current_step": 1,
116
+ },
117
+ metadata={"confidence": 0.9, "tokens_used": 150},
118
+ description="Plan created",
119
+ logic_step="planning",
120
+ )
121
+ print(f" āœ… Checkpoint saved: {cp2.id}")
122
+ print(f" šŸ“ Plan: 4 steps identified")
123
+
124
+ # Step 3: Execute step 1 — document retrieval (FAILS!)
125
+ print("\n⚔ Step 3: Agent tries to retrieve the document...")
126
+ print(" šŸ’„ ERROR: Document API returned 503 (Service Unavailable)")
127
+
128
+ cp3 = agent.checkpoint(
129
+ state={
130
+ "task": "Summarize quarterly earnings",
131
+ "current_step": 1,
132
+ "error": "API 503 - Service Unavailable",
133
+ },
134
+ metadata={"confidence": 0.3, "tokens_used": 200, "error": True},
135
+ description="Document retrieval failed",
136
+ logic_step="retrieve_doc:failed",
137
+ )
138
+ print(f" āŒ Error checkpoint: {cp3.id}")
139
+
140
+ # Step 4: Roll back!
141
+ print("\nāŖ Step 4: Rolling back to the planning stage...")
142
+
143
+ rolled_back = agent.rollback(to_checkpoint_id=cp2.id)
144
+ print(f" āœ… Rolled back to: {rolled_back.id}")
145
+ print(f" šŸ“Š State restored: plan is intact, step 1 error discarded")
146
+
147
+ # Step 5: Branch to try alternative approach
148
+ print("\n🌿 Step 5: Creating a branch for alternative approach...")
149
+
150
+ agent.branch("cached-data-approach")
151
+ print(f" āœ… Branch 'cached-data-approach' created")
152
+
153
+ cp_alt = agent.checkpoint(
154
+ state={
155
+ "task": "Summarize quarterly earnings",
156
+ "approach": "Use cached data instead of live API",
157
+ "data_source": "local_cache",
158
+ "cached_metrics": {
159
+ "revenue": "$12.4B",
160
+ "net_income": "$3.1B",
161
+ "yoy_growth": "15%",
162
+ },
163
+ },
164
+ metadata={"confidence": 0.75, "tokens_used": 100},
165
+ description="Using cached data",
166
+ logic_step="use_cached_data",
167
+ )
168
+ print(f" āœ… Alternative checkpoint: {cp_alt.id}")
169
+
170
+ # Step 6: Also try main branch with retry
171
+ print("\nšŸ”„ Step 6: Back on main branch, retrying with backoff...")
172
+
173
+ agent.switch_branch("main")
174
+
175
+ cp_retry = agent.checkpoint(
176
+ state={
177
+ "task": "Summarize quarterly earnings",
178
+ "current_step": 1,
179
+ "retry_attempt": 2,
180
+ "data": {
181
+ "revenue": "$12.5B",
182
+ "net_income": "$3.2B",
183
+ "yoy_growth": "16%",
184
+ "eps": "$2.45",
185
+ },
186
+ },
187
+ metadata={"confidence": 0.95, "tokens_used": 350},
188
+ description="Document retrieved on retry",
189
+ logic_step="retrieve_doc:success",
190
+ )
191
+ print(f" āœ… Retry succeeded! Checkpoint: {cp_retry.id}")
192
+
193
+ # Step 7: Merge branches
194
+ print("\nšŸ”€ Step 7: Merging cached approach (as validation)...")
195
+
196
+ merged = agent.merge("cached-data-approach", strategy="prefer_higher_confidence")
197
+ print(f" āœ… Merged! Final checkpoint: {merged.id}")
198
+
199
+ # Step 8: Generate summary
200
+ print("\nšŸ“„ Step 8: Generating final summary...")
201
+
202
+ final = agent.checkpoint(
203
+ state={
204
+ "task": "Summarize quarterly earnings",
205
+ "status": "completed",
206
+ "summary": (
207
+ "Q4 revenue reached $12.5B, up 16% YoY. "
208
+ "Net income of $3.2B with EPS of $2.45."
209
+ ),
210
+ },
211
+ metadata={"confidence": 0.95, "tokens_used": 500},
212
+ description="Summary generated",
213
+ logic_step="generate_summary",
214
+ )
215
+ print(f" āœ… Final checkpoint: {final.id}")
216
+
217
+ # Show results
218
+ print("\n" + "=" * 60)
219
+ print("šŸ“Š SESSION SUMMARY")
220
+ print("=" * 60)
221
+
222
+ metrics = agent.metrics
223
+ print(f"\n Agent: {agent.agent_name}")
224
+ print(f" Total Checkpoints: {metrics['total_checkpoints']}")
225
+ print(f" Total Rollbacks: {metrics['total_rollbacks']}")
226
+ print(f" Total Branches: {metrics['total_branches']}")
227
+ print(f" Branches: {', '.join(metrics['branches'])}")
228
+
229
+ print("\nšŸ“œ HISTORY (main branch):")
230
+ for entry in agent.history(limit=10):
231
+ status_icon = {
232
+ "active": "🟢", "committed": "šŸ“¦",
233
+ "rolled_back": "āŖ", "recovered": "ā™»ļø",
234
+ }.get(entry["status"], "⬜")
235
+ print(f" {status_icon} [{entry['id']}] {entry['status']:12s} | {entry['logic_path']}")
236
+
237
+ print("\n🌳 LOGIC TREE:")
238
+ tree_viz = agent.visualize_tree()
239
+ for line in tree_viz.split("\n"):
240
+ print(f" {line}")
241
+
242
+ print("\n🌿 BRANCHES:")
243
+ for b in agent.list_branches():
244
+ marker = " ← current" if b["is_current"] else ""
245
+ print(f" {'*' if b['is_current'] else ' '} {b['name']} ({b['checkpoint_count']} checkpoints){marker}")
246
+
247
+ # Diff
248
+ print(f"\nšŸ“Š DIFF between first and last checkpoint:")
249
+ diff = agent.diff(cp1.id, final.id)
250
+ if diff["added"]:
251
+ for key in list(diff["added"].keys())[:3]:
252
+ print(f" + {key}: {str(diff['added'][key])[:60]}")
253
+ if diff["modified"]:
254
+ for key in list(diff["modified"].keys())[:3]:
255
+ print(f" ~ {key}: {str(diff['modified'][key]['before'])[:30]} → {str(diff['modified'][key]['after'])[:30]}")
256
+
257
+ print("\n" + "=" * 60)
258
+ print("✨ Demo complete! AgentStateProtocol protected the agent through:")
259
+ print(" • 1 API failure (caught & recovered)")
260
+ print(" • 1 rollback (restored clean state)")
261
+ print(" • 1 branch (explored alternative path)")
262
+ print(" • 1 merge (combined best results)")
263
+ print(" • Full reasoning tree preserved for audit")
264
+ print("=" * 60 + "\n")
265
+
266
+ return agent
267
+
268
+
269
+ def main():
270
+ parser = create_parser()
271
+ args = parser.parse_args()
272
+
273
+ if args.command == "demo":
274
+ run_demo()
275
+ elif args.command is None:
276
+ parser.print_help()
277
+ else:
278
+ # For other commands, try to load from filesystem storage
279
+ storage = FileSystemStorage()
280
+ session = storage.load_session()
281
+
282
+ if not session:
283
+ print("No agentstateprotocol session found. Run 'agentstateprotocol demo' to create one.")
284
+ sys.exit(1)
285
+
286
+ agent = AgentStateProtocol.import_session(session)
287
+
288
+ if args.command == "log":
289
+ for entry in agent.history(branch_name=args.branch, limit=args.limit):
290
+ print(json.dumps(entry, indent=2))
291
+
292
+ elif args.command == "tree":
293
+ print(agent.visualize_tree())
294
+
295
+ elif args.command == "branches":
296
+ for b in agent.list_branches():
297
+ marker = "*" if b["is_current"] else " "
298
+ print(f" {marker} {b['name']} ({b['checkpoint_count']} checkpoints)")
299
+
300
+ elif args.command == "metrics":
301
+ print(json.dumps(agent.metrics, indent=2))
302
+
303
+ elif args.command == "diff":
304
+ diff = agent.diff(args.checkpoint_a, args.checkpoint_b)
305
+ print(json.dumps(diff, indent=2, default=str))
306
+
307
+ elif args.command == "inspect":
308
+ for entry in agent.history():
309
+ if entry["id"] == args.checkpoint_id:
310
+ print(json.dumps(entry, indent=2))
311
+ break
312
+ else:
313
+ print(f"Checkpoint {args.checkpoint_id} not found.")
314
+
315
+
316
+ if __name__ == "__main__":
317
+ main()
318
+