argon-agents 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,58 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [ main ]
6
+ pull_request:
7
+ branches: [ main ]
8
+
9
+ jobs:
10
+ test:
11
+ name: Test against the engine
12
+ runs-on: ubuntu-latest
13
+
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+
17
+ - uses: actions/checkout@v4
18
+ with:
19
+ repository: argon-lab/argon
20
+ path: engine
21
+
22
+ - name: Set up Go
23
+ uses: actions/setup-go@v5
24
+ with:
25
+ go-version: '1.24'
26
+
27
+ - name: Set up Python
28
+ uses: actions/setup-python@v5
29
+ with:
30
+ python-version: '3.12'
31
+
32
+ - name: Start MongoDB (single-node replica set)
33
+ run: |
34
+ docker run -d --name ci-mongo -p 27017:27017 mongo:7 --replSet rs0 --bind_ip_all
35
+ for i in $(seq 1 30); do
36
+ docker exec ci-mongo mongosh --quiet --eval 'db.runCommand({ping: 1})' && break
37
+ sleep 1
38
+ done
39
+ docker exec ci-mongo mongosh --quiet --eval 'rs.initiate({_id: "rs0", members: [{_id: 0, host: "localhost:27017"}]})'
40
+ for i in $(seq 1 30); do
41
+ [ "$(docker exec ci-mongo mongosh --quiet --eval 'db.hello().isWritablePrimary')" = "true" ] && break
42
+ sleep 1
43
+ done
44
+
45
+ - name: Build and start the API server
46
+ working-directory: engine/api
47
+ run: |
48
+ go build -o /tmp/argon-api .
49
+ /tmp/argon-api &
50
+ for i in $(seq 1 30); do
51
+ curl -sf http://localhost:8080/health && break
52
+ sleep 1
53
+ done
54
+
55
+ - name: Install and test
56
+ run: |
57
+ pip install -e ".[dev]"
58
+ pytest tests/ -v
@@ -0,0 +1,4 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ .pytest_cache/
4
+ dist/
@@ -0,0 +1,23 @@
1
+ LICENSE
2
+
3
+ MIT License
4
+
5
+ Copyright (c) 2025 Jake Wang
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: argon-agents
3
+ Version: 0.1.0
4
+ Summary: Argon adapters for AI agent frameworks: sandboxed, versioned MongoDB for LangGraph and Mem0
5
+ Project-URL: Homepage, https://github.com/argon-lab/argon-agents
6
+ Project-URL: Engine, https://github.com/argon-lab/argon
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: pymongo>=4.6
11
+ Requires-Dist: requests>=2.31
12
+ Provides-Extra: dev
13
+ Requires-Dist: langgraph-checkpoint-mongodb>=0.1; extra == 'dev'
14
+ Requires-Dist: langgraph>=0.2; extra == 'dev'
15
+ Requires-Dist: pytest>=8; extra == 'dev'
16
+ Provides-Extra: langgraph
17
+ Requires-Dist: langgraph-checkpoint-mongodb>=0.1; extra == 'langgraph'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # argon-agents
21
+
22
+ Argon adapters for AI agent frameworks: **sandboxed, versioned MongoDB**
23
+ for LangGraph and Mem0.
24
+
25
+ [Argon](https://github.com/argon-lab/argon) versions MongoDB the way Git
26
+ versions code — branch, time-travel, diff, merge, undo. This package gives
27
+ agent frameworks the two things plain MongoDB can't:
28
+
29
+ 1. **A disposable copy of state to work against.** Fork a sandbox with a
30
+ TTL, point the agent at an ordinary connection string, and production
31
+ data is never at risk.
32
+ 2. **An adopt-or-reject story for what the agent did.** Diff the sandbox,
33
+ merge it back (with conflict strategies), undo any range, or just let
34
+ the TTL reclaim it.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install argon-agents # client + Mem0 factory
40
+ pip install "argon-agents[langgraph]" # + the LangGraph checkpointer
41
+ ```
42
+
43
+ Requires a running [Argon API server](https://github.com/argon-lab/argon)
44
+ (`cd api && go run .`) backed by a MongoDB replica set.
45
+
46
+ ## The client
47
+
48
+ ```python
49
+ from argon_agents import ArgonClient
50
+
51
+ argon = ArgonClient("http://localhost:8080")
52
+ argon.create_project("support-bot")
53
+
54
+ sandbox = argon.create_sandbox("support-bot", ttl_minutes=60)
55
+ db = sandbox.pymongo_database() # plain pymongo, isolated copy
56
+ db.tickets.insert_one({"_id": "t1", "status": "resolved"})
57
+
58
+ print(sandbox.diff()) # what the agent changed
59
+ sandbox.merge() # adopt it — or sandbox.discard()
60
+ ```
61
+
62
+ ## LangGraph
63
+
64
+ ```python
65
+ from argon_agents import ArgonClient, ArgonCheckpointSaver
66
+
67
+ argon = ArgonClient()
68
+ saver = ArgonCheckpointSaver.from_sandbox(argon, "support-bot", ttl_minutes=60)
69
+
70
+ graph = builder.compile(checkpointer=saver) # any LangGraph graph
71
+ graph.invoke(input, {"configurable": {"thread_id": "user-42"}})
72
+
73
+ saver.merge() # keep the run's checkpoints
74
+ # saver.discard() # or reject them
75
+ # saver.fork(argon) # or branch the entire memory state and try both
76
+ ```
77
+
78
+ `ArgonCheckpointSaver` *is* the official `langgraph-checkpoint-mongodb`
79
+ saver — same wire format, same semantics — running on an Argon branch.
80
+ LangGraph's checkpoint ids give step-level rewind within a thread; Argon
81
+ adds branch-level fork/merge/undo/audit across the whole store.
82
+
83
+ ## Mem0
84
+
85
+ Mem0 speaks MongoDB natively; Argon supplies the versioned sandbox:
86
+
87
+ ```python
88
+ from argon_agents import ArgonClient, sandboxed_mem0_config
89
+ from mem0 import Memory
90
+
91
+ argon = ArgonClient()
92
+ config, sandbox = sandboxed_mem0_config(argon, "support-bot")
93
+ memory = Memory.from_config({"vector_store": config})
94
+
95
+ # ... let the agent read/write memories ...
96
+ sandbox.merge() # adopt the new memories, or discard(), or let the TTL run
97
+ ```
98
+
99
+ ## Reproducible evals: dataset pins
100
+
101
+ A pin is a named, immutable reference to a branch state that survives
102
+ garbage collection and resets forever. Pin the eval dataset once; fork a
103
+ fresh sandbox from the pin for every run; every run starts identical:
104
+
105
+ ```python
106
+ argon.create_pin("my-project", "eval-v1", note="golden dataset")
107
+
108
+ run = argon.sandbox_from_pin("my-project", "eval-v1", ttl_minutes=30)
109
+ # ... run the eval against run.connection_string ...
110
+ run.discard() # the pin itself is untouched — fork again anytime
111
+ ```
112
+
113
+ ## Tests
114
+
115
+ ```bash
116
+ pip install -e ".[dev]"
117
+ pytest # skips itself unless an Argon stack is reachable
118
+ ```
119
+
120
+ CI builds the engine from `argon-lab/argon@master`, starts a replica-set
121
+ MongoDB and the API server, and runs the full suite.
@@ -0,0 +1,102 @@
1
+ # argon-agents
2
+
3
+ Argon adapters for AI agent frameworks: **sandboxed, versioned MongoDB**
4
+ for LangGraph and Mem0.
5
+
6
+ [Argon](https://github.com/argon-lab/argon) versions MongoDB the way Git
7
+ versions code — branch, time-travel, diff, merge, undo. This package gives
8
+ agent frameworks the two things plain MongoDB can't:
9
+
10
+ 1. **A disposable copy of state to work against.** Fork a sandbox with a
11
+ TTL, point the agent at an ordinary connection string, and production
12
+ data is never at risk.
13
+ 2. **An adopt-or-reject story for what the agent did.** Diff the sandbox,
14
+ merge it back (with conflict strategies), undo any range, or just let
15
+ the TTL reclaim it.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pip install argon-agents # client + Mem0 factory
21
+ pip install "argon-agents[langgraph]" # + the LangGraph checkpointer
22
+ ```
23
+
24
+ Requires a running [Argon API server](https://github.com/argon-lab/argon)
25
+ (`cd api && go run .`) backed by a MongoDB replica set.
26
+
27
+ ## The client
28
+
29
+ ```python
30
+ from argon_agents import ArgonClient
31
+
32
+ argon = ArgonClient("http://localhost:8080")
33
+ argon.create_project("support-bot")
34
+
35
+ sandbox = argon.create_sandbox("support-bot", ttl_minutes=60)
36
+ db = sandbox.pymongo_database() # plain pymongo, isolated copy
37
+ db.tickets.insert_one({"_id": "t1", "status": "resolved"})
38
+
39
+ print(sandbox.diff()) # what the agent changed
40
+ sandbox.merge() # adopt it — or sandbox.discard()
41
+ ```
42
+
43
+ ## LangGraph
44
+
45
+ ```python
46
+ from argon_agents import ArgonClient, ArgonCheckpointSaver
47
+
48
+ argon = ArgonClient()
49
+ saver = ArgonCheckpointSaver.from_sandbox(argon, "support-bot", ttl_minutes=60)
50
+
51
+ graph = builder.compile(checkpointer=saver) # any LangGraph graph
52
+ graph.invoke(input, {"configurable": {"thread_id": "user-42"}})
53
+
54
+ saver.merge() # keep the run's checkpoints
55
+ # saver.discard() # or reject them
56
+ # saver.fork(argon) # or branch the entire memory state and try both
57
+ ```
58
+
59
+ `ArgonCheckpointSaver` *is* the official `langgraph-checkpoint-mongodb`
60
+ saver — same wire format, same semantics — running on an Argon branch.
61
+ LangGraph's checkpoint ids give step-level rewind within a thread; Argon
62
+ adds branch-level fork/merge/undo/audit across the whole store.
63
+
64
+ ## Mem0
65
+
66
+ Mem0 speaks MongoDB natively; Argon supplies the versioned sandbox:
67
+
68
+ ```python
69
+ from argon_agents import ArgonClient, sandboxed_mem0_config
70
+ from mem0 import Memory
71
+
72
+ argon = ArgonClient()
73
+ config, sandbox = sandboxed_mem0_config(argon, "support-bot")
74
+ memory = Memory.from_config({"vector_store": config})
75
+
76
+ # ... let the agent read/write memories ...
77
+ sandbox.merge() # adopt the new memories, or discard(), or let the TTL run
78
+ ```
79
+
80
+ ## Reproducible evals: dataset pins
81
+
82
+ A pin is a named, immutable reference to a branch state that survives
83
+ garbage collection and resets forever. Pin the eval dataset once; fork a
84
+ fresh sandbox from the pin for every run; every run starts identical:
85
+
86
+ ```python
87
+ argon.create_pin("my-project", "eval-v1", note="golden dataset")
88
+
89
+ run = argon.sandbox_from_pin("my-project", "eval-v1", ttl_minutes=30)
90
+ # ... run the eval against run.connection_string ...
91
+ run.discard() # the pin itself is untouched — fork again anytime
92
+ ```
93
+
94
+ ## Tests
95
+
96
+ ```bash
97
+ pip install -e ".[dev]"
98
+ pytest # skips itself unless an Argon stack is reachable
99
+ ```
100
+
101
+ CI builds the engine from `argon-lab/argon@master`, starts a replica-set
102
+ MongoDB and the API server, and runs the full suite.
@@ -0,0 +1,19 @@
1
+ """Argon adapters for AI agent frameworks.
2
+
3
+ Argon versions MongoDB the way Git versions code. These adapters give
4
+ agent frameworks the two things they are missing: a disposable, isolated
5
+ copy of state to work against (a sandbox with a TTL), and an undo/merge
6
+ story for whatever the agent did to it.
7
+ """
8
+
9
+ from .client import ArgonClient, ArgonError, Sandbox
10
+ from .mem0 import sandboxed_mem0_config
11
+
12
+ __all__ = ["ArgonClient", "ArgonError", "Sandbox", "sandboxed_mem0_config"]
13
+
14
+ try: # langgraph extras are optional
15
+ from .langgraph import ArgonCheckpointSaver # noqa: F401
16
+
17
+ __all__.append("ArgonCheckpointSaver")
18
+ except ImportError: # pragma: no cover
19
+ pass
@@ -0,0 +1,237 @@
1
+ """REST client for the Argon control plane.
2
+
3
+ The control plane (this client) manages projects, branches, sandboxes,
4
+ merges and undos over the Argon API server. The data plane is native
5
+ MongoDB: sandboxes and checked-out branches hand back ordinary connection
6
+ strings, and the API server captures every write into versioned history
7
+ through the branch's change stream.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import datetime
13
+ from dataclasses import dataclass, field
14
+ from typing import Any, Optional
15
+
16
+ import requests
17
+
18
+
19
+ class ArgonError(RuntimeError):
20
+ """An Argon control-plane call failed."""
21
+
22
+ def __init__(self, status: int, message: str):
23
+ super().__init__(f"{message} (HTTP {status})")
24
+ self.status = status
25
+
26
+
27
+ class ArgonClient:
28
+ """Client for the Argon REST API (default http://localhost:8080)."""
29
+
30
+ def __init__(self, api_url: str = "http://localhost:8080", timeout: float = 30.0):
31
+ self.api_url = api_url.rstrip("/")
32
+ self.timeout = timeout
33
+ self._session = requests.Session()
34
+
35
+ # -- plumbing ---------------------------------------------------------
36
+
37
+ def _call(self, method: str, path: str, json: Optional[dict] = None) -> dict:
38
+ response = self._session.request(
39
+ method, f"{self.api_url}/api/v1{path}", json=json or {}, timeout=self.timeout
40
+ )
41
+ body: dict[str, Any] = {}
42
+ if response.content:
43
+ try:
44
+ body = response.json()
45
+ except ValueError:
46
+ pass
47
+ if response.status_code >= 400:
48
+ raise ArgonError(response.status_code, body.get("error", response.text))
49
+ return body
50
+
51
+ # -- projects & branches ----------------------------------------------
52
+
53
+ def create_project(self, name: str) -> dict:
54
+ return self._call("POST", "/projects", {"name": name})
55
+
56
+ def get_or_create_project(self, name: str) -> None:
57
+ try:
58
+ self.create_project(name)
59
+ except ArgonError as exc:
60
+ if exc.status != 409:
61
+ raise
62
+
63
+ def list_branches(self, project: str) -> list[dict]:
64
+ return self._call("GET", f"/projects/{project}/branches")["branches"]
65
+
66
+ def branch_info(self, project: str, branch: str) -> dict:
67
+ return self._call("GET", f"/projects/{project}/branches/{branch}")
68
+
69
+ def create_branch(self, project: str, name: str, from_branch: str = "main") -> dict:
70
+ return self._call(
71
+ "POST", f"/projects/{project}/branches", {"name": name, "from": from_branch}
72
+ )
73
+
74
+ def delete_branch(self, project: str, branch: str) -> None:
75
+ self._call("DELETE", f"/projects/{project}/branches/{branch}")
76
+
77
+ def checkout(self, project: str, branch: str) -> str:
78
+ """Materialize a branch and return its MongoDB connection string."""
79
+ return self._call("POST", f"/projects/{project}/branches/{branch}/checkout")[
80
+ "connection_string"
81
+ ]
82
+
83
+ # -- sandboxes ----------------------------------------------------------
84
+
85
+ def create_sandbox(
86
+ self,
87
+ project: str,
88
+ from_branch: str = "main",
89
+ name: Optional[str] = None,
90
+ ttl_minutes: int = 60,
91
+ ) -> "Sandbox":
92
+ body = {"from": from_branch, "ttl_minutes": ttl_minutes}
93
+ if name:
94
+ body["name"] = name
95
+ resp = self._call("POST", f"/projects/{project}/sandboxes", body)
96
+ return Sandbox(
97
+ _client=self,
98
+ project=project,
99
+ branch=resp["branch"],
100
+ connection_string=resp["connection_string"],
101
+ expires_at=resp["expires_at"],
102
+ forked_from=resp["forked_from"],
103
+ )
104
+
105
+ # -- pins (reproducible eval datasets) -----------------------------------
106
+
107
+ def create_pin(
108
+ self,
109
+ project: str,
110
+ name: str,
111
+ branch: str = "main",
112
+ lsn: Optional[int] = None,
113
+ note: Optional[str] = None,
114
+ ) -> dict:
115
+ """Pin a branch state under a name: a named, immutable dataset
116
+ reference that survives garbage collection and resets forever.
117
+ Defaults to the branch's current head."""
118
+ body: dict[str, Any] = {"name": name, "branch": branch}
119
+ if lsn is not None:
120
+ body["lsn"] = lsn
121
+ if note:
122
+ body["note"] = note
123
+ return self._call("POST", f"/projects/{project}/pins", body)
124
+
125
+ def list_pins(self, project: str) -> list[dict]:
126
+ return self._call("GET", f"/projects/{project}/pins")["pins"]
127
+
128
+ def delete_pin(self, project: str, name: str) -> None:
129
+ self._call("DELETE", f"/projects/{project}/pins/{name}")
130
+
131
+ def sandbox_from_pin(
132
+ self,
133
+ project: str,
134
+ pin: str,
135
+ name: Optional[str] = None,
136
+ ttl_minutes: int = 60,
137
+ ) -> "Sandbox":
138
+ """Fork a TTL sandbox that starts at exactly the pinned state —
139
+ the reproducible-eval workflow: pin the dataset once, fork a fresh
140
+ sandbox from it for every run."""
141
+ body: dict[str, Any] = {"ttl_minutes": ttl_minutes}
142
+ if name:
143
+ body["name"] = name
144
+ resp = self._call("POST", f"/projects/{project}/pins/{pin}/sandboxes", body)
145
+ return Sandbox(
146
+ _client=self,
147
+ project=project,
148
+ branch=resp["branch"],
149
+ connection_string=resp["connection_string"],
150
+ expires_at=resp["expires_at"],
151
+ forked_from=resp["forked_from"],
152
+ )
153
+
154
+ # -- diff / merge / undo ------------------------------------------------
155
+
156
+ def diff(self, project: str, branch: str) -> dict:
157
+ return self._call("GET", f"/projects/{project}/branches/{branch}/diff")
158
+
159
+ def merge_preview(self, project: str, branch: str) -> dict:
160
+ return self._call("POST", f"/projects/{project}/branches/{branch}/merge-preview")
161
+
162
+ def merge_apply(self, plan_id: str, strategy: Optional[str] = None) -> dict:
163
+ body = {"strategy": strategy} if strategy else {}
164
+ return self._call("POST", f"/merge-plans/{plan_id}/apply", body)
165
+
166
+ def merge(self, project: str, branch: str, strategy: Optional[str] = None) -> dict:
167
+ """Preview and apply in one step."""
168
+ plan = self.merge_preview(project, branch)
169
+ return self.merge_apply(plan["id"], strategy)
170
+
171
+ def undo(
172
+ self,
173
+ project: str,
174
+ branch: str,
175
+ from_lsn: int,
176
+ to_lsn: Optional[int] = None,
177
+ actor: Optional[str] = None,
178
+ dry_run: bool = False,
179
+ ) -> dict:
180
+ body: dict[str, Any] = {"from_lsn": from_lsn, "dry_run": dry_run}
181
+ if to_lsn is not None:
182
+ body["to_lsn"] = to_lsn
183
+ if actor:
184
+ body["actor"] = actor
185
+ return self._call("POST", f"/projects/{project}/branches/{branch}/undo", body)
186
+
187
+ def snapshot(self, project: str, branch: str) -> dict:
188
+ return self._call("POST", f"/projects/{project}/branches/{branch}/snapshots")
189
+
190
+ def time_travel_info(self, project: str, branch: str) -> dict:
191
+ return self._call("GET", f"/projects/{project}/branches/{branch}/time-travel")
192
+
193
+
194
+ @dataclass
195
+ class Sandbox:
196
+ """A disposable, versioned copy of a branch, with a TTL.
197
+
198
+ Point any MongoDB client at ``connection_string``; every write becomes
199
+ versioned history. ``merge()`` brings the work back to the parent,
200
+ ``discard()`` throws it away, the TTL reclaims whatever is left.
201
+ """
202
+
203
+ project: str
204
+ branch: str
205
+ connection_string: str
206
+ expires_at: str
207
+ forked_from: str
208
+ _client: ArgonClient = field(repr=False, default=None)
209
+
210
+ @property
211
+ def database_name(self) -> str:
212
+ """The physical database name inside the connection string."""
213
+ path = self.connection_string.split("://", 1)[1]
214
+ db = path.split("/", 1)[1] if "/" in path else ""
215
+ return db.split("?", 1)[0]
216
+
217
+ def pymongo_database(self):
218
+ """A pymongo Database handle for the sandbox (lazy import)."""
219
+ from pymongo import MongoClient
220
+
221
+ return MongoClient(self.connection_string).get_default_database()
222
+
223
+ def diff(self) -> dict:
224
+ return self._client.diff(self.project, self.branch)
225
+
226
+ def merge(self, strategy: Optional[str] = None) -> dict:
227
+ return self._client.merge(self.project, self.branch, strategy)
228
+
229
+ def keep_days_note(self) -> str: # pragma: no cover - convenience only
230
+ return f"expires {self.expires_at}"
231
+
232
+ def discard(self) -> None:
233
+ self._client.delete_branch(self.project, self.branch)
234
+
235
+ @property
236
+ def expires(self) -> datetime.datetime:
237
+ return datetime.datetime.fromisoformat(self.expires_at.replace("Z", "+00:00"))
@@ -0,0 +1,96 @@
1
+ """LangGraph checkpointing on versioned, sandboxed MongoDB.
2
+
3
+ ``ArgonCheckpointSaver`` is the official ``langgraph-checkpoint-mongodb``
4
+ saver pointed at an Argon branch, plus the operations MongoDB alone cannot
5
+ give you:
6
+
7
+ - ``from_sandbox``: fork the whole memory state into a disposable,
8
+ TTL-stamped copy and checkpoint an agent against it — production
9
+ checkpoints are never at risk.
10
+ - ``fork``: branch the entire checkpoint history (every thread) at its
11
+ current state, cheaply, and get an independent saver for the copy.
12
+ - ``merge`` / ``discard`` on the underlying sandbox to adopt or reject
13
+ whatever the agent's run produced.
14
+
15
+ LangGraph's own checkpoint ids give you step-level rewind *within* a
16
+ thread; Argon gives you branch-level fork/undo/audit *across* the whole
17
+ store.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from typing import Optional
23
+
24
+ from langgraph.checkpoint.mongodb import MongoDBSaver
25
+ from pymongo import MongoClient
26
+
27
+ from .client import ArgonClient, Sandbox
28
+
29
+
30
+ class ArgonCheckpointSaver(MongoDBSaver):
31
+ """The official MongoDB checkpointer, running on an Argon branch."""
32
+
33
+ def __init__(self, connection_string: str, *, sandbox: Optional[Sandbox] = None, **kwargs):
34
+ client = MongoClient(connection_string)
35
+ db_name = client.get_default_database().name
36
+ super().__init__(client, db_name=db_name, **kwargs)
37
+ self.sandbox = sandbox
38
+
39
+ # -- constructors -------------------------------------------------------
40
+
41
+ @classmethod
42
+ def from_sandbox(
43
+ cls,
44
+ argon: ArgonClient,
45
+ project: str,
46
+ from_branch: str = "main",
47
+ name: Optional[str] = None,
48
+ ttl_minutes: int = 60,
49
+ **kwargs,
50
+ ) -> "ArgonCheckpointSaver":
51
+ """Fork a sandbox and checkpoint against it.
52
+
53
+ The saver's ``sandbox`` attribute exposes ``merge()`` and
54
+ ``discard()``; the TTL reclaims the sandbox if neither happens.
55
+ """
56
+ sandbox = argon.create_sandbox(
57
+ project, from_branch=from_branch, name=name, ttl_minutes=ttl_minutes
58
+ )
59
+ return cls(sandbox.connection_string, sandbox=sandbox, **kwargs)
60
+
61
+ @classmethod
62
+ def for_branch(cls, argon: ArgonClient, project: str, branch: str = "main", **kwargs):
63
+ """Checkpoint against a (checked-out) long-lived branch."""
64
+ return cls(argon.checkout(project, branch), **kwargs)
65
+
66
+ # -- Argon superpowers ---------------------------------------------------
67
+
68
+ def fork(
69
+ self,
70
+ argon: ArgonClient,
71
+ name: Optional[str] = None,
72
+ ttl_minutes: int = 60,
73
+ ) -> "ArgonCheckpointSaver":
74
+ """Fork the entire checkpoint store (all threads) at its current
75
+ state into a new sandbox and return a saver for the copy."""
76
+ if self.sandbox is None:
77
+ raise ValueError("fork() needs a saver created via from_sandbox()")
78
+ return self.from_sandbox(
79
+ argon,
80
+ self.sandbox.project,
81
+ from_branch=self.sandbox.branch,
82
+ name=name,
83
+ ttl_minutes=ttl_minutes,
84
+ )
85
+
86
+ def merge(self, strategy: Optional[str] = None) -> dict:
87
+ """Adopt the sandboxed checkpoints into the parent branch."""
88
+ if self.sandbox is None:
89
+ raise ValueError("merge() needs a saver created via from_sandbox()")
90
+ return self.sandbox.merge(strategy)
91
+
92
+ def discard(self) -> None:
93
+ """Throw the sandboxed run away and reclaim its storage."""
94
+ if self.sandbox is None:
95
+ raise ValueError("discard() needs a saver created via from_sandbox()")
96
+ self.sandbox.discard()
@@ -0,0 +1,48 @@
1
+ """Sandboxed Mem0 configuration on versioned MongoDB.
2
+
3
+ Mem0 speaks MongoDB natively; what it lacks is a way to experiment on a
4
+ copy of an agent's memory and merge or reject the outcome. This factory
5
+ provisions an Argon sandbox and returns a Mem0 ``config`` dict whose
6
+ MongoDB vector store points at it — plus the sandbox handle for
7
+ ``merge()`` / ``discard()`` and TTL-based cleanup.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Optional, Tuple
13
+
14
+ from .client import ArgonClient, Sandbox
15
+
16
+
17
+ def sandboxed_mem0_config(
18
+ argon: ArgonClient,
19
+ project: str,
20
+ from_branch: str = "main",
21
+ collection_name: str = "mem0",
22
+ embedding_model_dims: int = 1536,
23
+ ttl_minutes: int = 60,
24
+ name: Optional[str] = None,
25
+ ) -> Tuple[dict, Sandbox]:
26
+ """Provision a sandbox and return (mem0_config, sandbox).
27
+
28
+ Usage::
29
+
30
+ config, sandbox = sandboxed_mem0_config(argon, "my-project")
31
+ memory = Memory.from_config({"vector_store": config, ...})
32
+ ... # let the agent read and write memories
33
+ sandbox.merge() # adopt the new memories
34
+ # or sandbox.discard(), or just let the TTL reclaim it
35
+ """
36
+ sandbox = argon.create_sandbox(
37
+ project, from_branch=from_branch, name=name, ttl_minutes=ttl_minutes
38
+ )
39
+ config = {
40
+ "provider": "mongodb",
41
+ "config": {
42
+ "mongo_uri": sandbox.connection_string,
43
+ "db_name": sandbox.database_name,
44
+ "collection_name": collection_name,
45
+ "embedding_model_dims": embedding_model_dims,
46
+ },
47
+ }
48
+ return config, sandbox
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "argon-agents"
7
+ version = "0.1.0"
8
+ description = "Argon adapters for AI agent frameworks: sandboxed, versioned MongoDB for LangGraph and Mem0"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ dependencies = [
13
+ "requests>=2.31",
14
+ "pymongo>=4.6",
15
+ ]
16
+
17
+ [project.optional-dependencies]
18
+ langgraph = ["langgraph-checkpoint-mongodb>=0.1"]
19
+ dev = ["pytest>=8", "langgraph-checkpoint-mongodb>=0.1", "langgraph>=0.2"]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/argon-lab/argon-agents"
23
+ Engine = "https://github.com/argon-lab/argon"
@@ -0,0 +1,191 @@
1
+ """Integration tests against a live Argon stack.
2
+
3
+ Requirements: the Argon API server on ARGON_API_URL (default
4
+ http://localhost:8080) backed by a replica-set MongoDB. Tests skip when the
5
+ stack is unreachable so the suite can run anywhere; CI always provides it.
6
+ """
7
+
8
+ import os
9
+ import time
10
+ import uuid
11
+
12
+ import pytest
13
+ import requests
14
+
15
+ from argon_agents import ArgonClient, ArgonError
16
+
17
+ API_URL = os.environ.get("ARGON_API_URL", "http://localhost:8080")
18
+
19
+
20
+ def _stack_available() -> bool:
21
+ try:
22
+ return requests.get(f"{API_URL}/health", timeout=2).status_code == 200
23
+ except requests.RequestException:
24
+ return False
25
+
26
+
27
+ pytestmark = pytest.mark.skipif(
28
+ not _stack_available(), reason=f"no Argon API server at {API_URL}"
29
+ )
30
+
31
+
32
+ @pytest.fixture()
33
+ def argon() -> ArgonClient:
34
+ return ArgonClient(API_URL)
35
+
36
+
37
+ @pytest.fixture()
38
+ def project(argon: ArgonClient) -> str:
39
+ name = f"agents-test-{uuid.uuid4().hex[:8]}"
40
+ argon.create_project(name)
41
+ return name
42
+
43
+
44
+ def wait_for_diff(sandbox, min_changes: int, timeout: float = 20.0) -> dict:
45
+ """Poll until the sandbox's ingested diff shows the expected changes."""
46
+ deadline = time.time() + timeout
47
+ while True:
48
+ diff = sandbox.diff()
49
+ if len(diff.get("changes") or []) >= min_changes:
50
+ return diff
51
+ assert time.time() < deadline, f"diff never reached {min_changes} changes: {diff}"
52
+ time.sleep(0.3)
53
+
54
+
55
+ def test_sandbox_write_merge_undo(argon: ArgonClient, project: str):
56
+ sandbox = argon.create_sandbox(project, ttl_minutes=15)
57
+ assert sandbox.connection_string.startswith("mongodb://")
58
+ assert sandbox.forked_from == "main"
59
+
60
+ # Data plane: plain pymongo against the sandbox.
61
+ db = sandbox.pymongo_database()
62
+ db.notes.insert_one({"_id": "n1", "text": "hello from the agent"})
63
+ db.notes.insert_one({"_id": "n2", "text": "scratch"})
64
+ db.notes.delete_one({"_id": "n2"})
65
+
66
+ diff = wait_for_diff(sandbox, 1)
67
+ ids = {c["document_id"] for c in diff["changes"]}
68
+ assert "n1" in ids
69
+
70
+ # Merge the surviving work back.
71
+ result = sandbox.merge()
72
+ assert result["applied"] >= 1
73
+
74
+ # It landed on main.
75
+ info = argon.branch_info(project, "main")
76
+ head = info["branch"]["head_lsn"]
77
+ assert head > 0
78
+
79
+ # And main can be dry-run undone over the same API.
80
+ undo = argon.undo(project, "main", from_lsn=head, dry_run=True)
81
+ assert undo["dry_run"] is True
82
+
83
+ sandbox.discard()
84
+ with pytest.raises(ArgonError):
85
+ argon.branch_info(project, sandbox.branch)
86
+
87
+
88
+ def test_merge_conflict_strategies(argon: ArgonClient, project: str):
89
+ # Seed main through a temporary sandbox.
90
+ seed = argon.create_sandbox(project, ttl_minutes=15)
91
+ seed.pymongo_database().cfg.insert_one({"_id": "c", "v": "base"})
92
+ wait_for_diff(seed, 1)
93
+ seed.merge()
94
+ seed.discard()
95
+
96
+ # Two sandboxes contest the same document.
97
+ a = argon.create_sandbox(project, ttl_minutes=15)
98
+ a.pymongo_database().cfg.update_one({"_id": "c"}, {"$set": {"v": "from-a"}})
99
+ wait_for_diff(a, 1)
100
+ a.merge()
101
+ a.discard()
102
+
103
+ b = argon.create_sandbox(project, ttl_minutes=15)
104
+ # b forked before a merged? No — created after, so no conflict... force one:
105
+ # write to the same doc, then merge with strategy after main moved.
106
+ b_db = b.pymongo_database()
107
+ b_db.cfg.update_one({"_id": "c"}, {"$set": {"v": "from-b"}})
108
+ wait_for_diff(b, 1)
109
+ plan = argon.merge_preview(project, b.branch)
110
+ if plan.get("conflicts"):
111
+ with pytest.raises(ArgonError):
112
+ argon.merge_apply(plan["id"])
113
+ result = argon.merge_apply(plan["id"], strategy="theirs")
114
+ assert result["conflicts_resolved"] >= 1
115
+ else:
116
+ assert argon.merge_apply(plan["id"])["applied"] >= 1
117
+ b.discard()
118
+
119
+
120
+ def test_langgraph_checkpointer(argon: ArgonClient, project: str):
121
+ langgraph_mongodb = pytest.importorskip("langgraph.checkpoint.mongodb")
122
+ del langgraph_mongodb
123
+ from langgraph.checkpoint.base import empty_checkpoint
124
+
125
+ from argon_agents import ArgonCheckpointSaver
126
+
127
+ saver = ArgonCheckpointSaver.from_sandbox(argon, project, ttl_minutes=15)
128
+ config = {"configurable": {"thread_id": "t1", "checkpoint_ns": ""}}
129
+
130
+ checkpoint = empty_checkpoint()
131
+ saved_config = saver.put(config, checkpoint, {"source": "input", "step": -1}, {})
132
+ assert saved_config["configurable"]["checkpoint_id"]
133
+
134
+ fetched = saver.get_tuple(config)
135
+ assert fetched is not None
136
+ assert fetched.checkpoint["id"] == checkpoint["id"]
137
+
138
+ # The checkpoints are ordinary versioned data: the diff sees them.
139
+ diff = wait_for_diff(saver.sandbox, 1)
140
+ collections = {c["collection"] for c in diff["changes"]}
141
+ assert any("checkpoint" in c for c in collections)
142
+
143
+ # Fork the whole memory state and verify the copy reads the checkpoint.
144
+ forked = saver.fork(argon, ttl_minutes=15)
145
+ fetched_fork = forked.get_tuple(config)
146
+ assert fetched_fork is not None
147
+ assert fetched_fork.checkpoint["id"] == checkpoint["id"]
148
+
149
+ forked.discard()
150
+ saver.discard()
151
+
152
+
153
+ def test_pinned_eval_dataset(argon: ArgonClient, project: str):
154
+ # Author the dataset through a sandbox and merge it to main.
155
+ seed = argon.create_sandbox(project, ttl_minutes=15)
156
+ seed_db = seed.pymongo_database()
157
+ seed_db.eval_cases.insert_many([{"_id": f"case-{i}", "input": i} for i in range(3)])
158
+ wait_for_diff(seed, 1)
159
+ seed.merge()
160
+ seed.discard()
161
+
162
+ # Pin it.
163
+ pin = argon.create_pin(project, "eval-v1", note="three cases")
164
+ assert pin["lsn"] > 0
165
+ assert any(p["name"] == "eval-v1" for p in argon.list_pins(project))
166
+
167
+ # The dataset moves on after the pin.
168
+ later = argon.create_sandbox(project, ttl_minutes=15)
169
+ later.pymongo_database().eval_cases.insert_one({"_id": "case-99", "input": 99})
170
+ wait_for_diff(later, 1)
171
+ later.merge()
172
+ later.discard()
173
+
174
+ # Every run forked from the pin sees exactly the pinned three cases.
175
+ run = argon.sandbox_from_pin(project, "eval-v1", ttl_minutes=15)
176
+ docs = list(run.pymongo_database().eval_cases.find())
177
+ assert {d["_id"] for d in docs} == {"case-0", "case-1", "case-2"}
178
+ run.discard()
179
+
180
+ argon.delete_pin(project, "eval-v1")
181
+
182
+
183
+ def test_mem0_config_factory(argon: ArgonClient, project: str):
184
+ from argon_agents import sandboxed_mem0_config
185
+
186
+ config, sandbox = sandboxed_mem0_config(argon, project, ttl_minutes=15)
187
+ assert config["provider"] == "mongodb"
188
+ assert config["config"]["mongo_uri"] == sandbox.connection_string
189
+ assert config["config"]["db_name"] == sandbox.database_name
190
+ assert config["config"]["db_name"].startswith("argon_br_")
191
+ sandbox.discard()