recall-langgraph 0.1.0__py3-none-any.whl

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,20 @@
1
+ """Recall by Polign for LangGraph.
2
+
3
+ ``RecallResume`` resumes an agent from its own records: its working state,
4
+ pointers to its work, relevant memories and recent turns come back as a
5
+ briefing for the model, and the run's messages are recorded as turns for the
6
+ next resume. ``recall_tools`` gives the model the tools that keep those
7
+ records current. It sits beside your checkpointer; it does not replace it.
8
+ """
9
+
10
+ from .resume import BRIEFING_ID, RecallResume
11
+ from .tools import recall_tools
12
+
13
+ __all__ = ["BRIEFING_ID", "RecallResume", "recall_tools"]
14
+
15
+ try:
16
+ from importlib.metadata import version as _version
17
+
18
+ __version__ = _version("recall-langgraph")
19
+ except Exception: # pragma: no cover - source checkout without metadata
20
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,347 @@
1
+ """One resumed agent, and the hooks that put it into a LangGraph graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hashlib
7
+ import json
8
+ import os
9
+ import threading
10
+ from collections.abc import Mapping, Sequence
11
+ from typing import Any
12
+
13
+ from langchain_core.messages import (
14
+ AIMessage,
15
+ BaseMessage,
16
+ ChatMessage,
17
+ HumanMessage,
18
+ RemoveMessage,
19
+ SystemMessage,
20
+ ToolMessage,
21
+ )
22
+ from langchain_core.runnables import RunnableLambda
23
+ from langgraph.graph.message import REMOVE_ALL_MESSAGES
24
+ from polign_recall import Client, Output, Pointer, ResumeContext, ResumedAgent, WorkingState
25
+
26
+ #: The id of the briefing message ``briefing_node`` adds to the state. The
27
+ #: recorder skips it, so the briefing never becomes a turn of its own.
28
+ BRIEFING_ID = "recall-briefing"
29
+
30
+
31
+ class RecallResume:
32
+ """Resumes one agent from its Recall records and keeps them current.
33
+
34
+ Resuming takes the agent's lease and reads back the context to start
35
+ from: its working state, pointers to its work, relevant memories, and its
36
+ most recent turns, within ``token_budget``. ``briefing`` is that context
37
+ as one text for the model. The first use opens it; call ``open`` (or
38
+ ``aopen``) yourself to resume at a point you choose.
39
+
40
+ Old messages are not replayed into the state: the briefing already
41
+ carries the recent turns as text, and a replayed tool result without its
42
+ matching call would be refused by the model API. Your checkpointer keeps
43
+ working as usual. On a new thread id the resumed run starts from the
44
+ briefing alone; on the old thread id the checkpointer restores the old
45
+ messages too, and nothing is recorded twice: each turn keeps its message
46
+ id, so the first recording after a resume skips every restored message up
47
+ to the last one the records already have.
48
+
49
+ For ``create_react_agent``, pass ``pre_model_hook`` and
50
+ ``post_model_hook``. For your own StateGraph, call ``with_briefing`` on the
51
+ messages you send the model (or add ``briefing_node``), and add
52
+ ``record_node`` where new messages land.
53
+
54
+ ``client`` is a ``polign_recall.Client`` opened with ``agent=True``. When
55
+ it is left out, one is opened with ``local_dir`` and ``env`` and closed on
56
+ release. Release on a clean shutdown (``release``, ``arelease``, or a
57
+ ``with`` block) so the next process can resume at once instead of waiting
58
+ for the lease to expire.
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ agent_id: str,
64
+ *,
65
+ client: Client | None = None,
66
+ token_budget: int | None = None,
67
+ lease_ttl: float | None = None,
68
+ holder: str | None = None,
69
+ output_threshold: int | None = None,
70
+ local_dir: str | os.PathLike[str] | None = None,
71
+ env: Mapping[str, str] | None = None,
72
+ ) -> None:
73
+ if client is not None and (local_dir is not None or env is not None):
74
+ raise ValueError("local_dir and env open a client; do not pass them with client")
75
+ self.agent_id = agent_id
76
+ self._client = client
77
+ self._owns_client = client is None
78
+ self._client_options: dict[str, Any] = {"local_dir": local_dir, "env": env}
79
+ self._resume_options: dict[str, Any] = {
80
+ "token_budget": token_budget,
81
+ "lease_ttl": lease_ttl,
82
+ "holder": holder,
83
+ "output_threshold": output_threshold,
84
+ }
85
+ self._agent: ResumedAgent | None = None
86
+ self._released = False
87
+ self._open_lock = threading.Lock()
88
+ # Serializes recording, so the pre and post hooks of parallel branches
89
+ # cannot record the same message twice.
90
+ self._record_lock = threading.Lock()
91
+ self._recorded: set[str] = set()
92
+ self._seeded = False
93
+
94
+ # Lifecycle.
95
+
96
+ def open(self) -> RecallResume:
97
+ """Resume the agent, once. Raises ``polign_recall.RecallError`` with
98
+ code "lease_held" while another process holds it."""
99
+ with self._open_lock:
100
+ if self._released:
101
+ raise RuntimeError("this resume was released; create a new one to resume again")
102
+ if self._agent is not None:
103
+ return self
104
+ if self._client is None:
105
+ self._client = Client(agent=True, **self._client_options)
106
+ try:
107
+ self._agent = self._client.resume(self.agent_id, **self._resume_options)
108
+ except BaseException:
109
+ if self._owns_client:
110
+ self._client.close()
111
+ self._client = None
112
+ raise
113
+ return self
114
+
115
+ async def aopen(self) -> RecallResume:
116
+ return await asyncio.to_thread(self.open)
117
+
118
+ def release(self) -> None:
119
+ """Hand the lease over and, if this object opened its own client,
120
+ close it. Safe to call more than once."""
121
+ with self._open_lock:
122
+ if self._released:
123
+ return
124
+ self._released = True
125
+ agent, client = self._agent, self._client
126
+ self._agent = None
127
+ try:
128
+ if agent is not None:
129
+ agent.release()
130
+ finally:
131
+ if self._owns_client and client is not None:
132
+ client.close()
133
+
134
+ async def arelease(self) -> None:
135
+ await asyncio.to_thread(self.release)
136
+
137
+ def __enter__(self) -> RecallResume:
138
+ return self.open()
139
+
140
+ def __exit__(self, *exc: object) -> None:
141
+ self.release()
142
+
143
+ async def __aenter__(self) -> RecallResume:
144
+ return await self.aopen()
145
+
146
+ async def __aexit__(self, *exc: object) -> None:
147
+ await self.arelease()
148
+
149
+ @property
150
+ def agent(self) -> ResumedAgent:
151
+ """The resumed agent, for the calls this class does not wrap. Opens it
152
+ on first use."""
153
+ if self._agent is None:
154
+ self.open()
155
+ assert self._agent is not None
156
+ return self._agent
157
+
158
+ @property
159
+ def context(self) -> ResumeContext:
160
+ """What the resume returned."""
161
+ return self.agent.context
162
+
163
+ @property
164
+ def briefing(self) -> str:
165
+ return self.context.briefing
166
+
167
+ # The briefing.
168
+
169
+ def briefing_message(self) -> SystemMessage:
170
+ return SystemMessage(content=self.briefing, id=BRIEFING_ID)
171
+
172
+ def with_briefing(self, messages: Sequence[BaseMessage]) -> list[BaseMessage]:
173
+ """``messages`` with the briefing in front, for the model's input. It
174
+ does not change the graph state. A briefing already there is not
175
+ added twice."""
176
+ messages = list(messages)
177
+ if any(m.id == BRIEFING_ID for m in messages):
178
+ return messages
179
+ return [self.briefing_message(), *messages]
180
+
181
+ def _pre(self, state: Any) -> dict[str, Any]:
182
+ messages = _messages(state)
183
+ self.record(messages)
184
+ return {"llm_input_messages": self.with_briefing(messages)}
185
+
186
+ async def _apre(self, state: Any) -> dict[str, Any]:
187
+ return await asyncio.to_thread(self._pre, state)
188
+
189
+ def _post(self, state: Any) -> dict[str, Any]:
190
+ self.record(_messages(state))
191
+ return {}
192
+
193
+ async def _apost(self, state: Any) -> dict[str, Any]:
194
+ return await asyncio.to_thread(self._post, state)
195
+
196
+ def _briefing_update(self, state: Any) -> dict[str, Any]:
197
+ messages = _messages(state)
198
+ if any(m.id == BRIEFING_ID for m in messages):
199
+ return {}
200
+ # add_messages appends, so putting the briefing first means rewriting
201
+ # the list, the way LangGraph documents for a pre-model hook.
202
+ return {"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES), self.briefing_message(), *messages]}
203
+
204
+ async def _abriefing_update(self, state: Any) -> dict[str, Any]:
205
+ return await asyncio.to_thread(self._briefing_update, state)
206
+
207
+ @property
208
+ def pre_model_hook(self) -> RunnableLambda:
209
+ """For ``create_react_agent(pre_model_hook=...)``. Records the messages
210
+ that arrived since the last model call and hands the model the
211
+ briefing followed by the state's messages, as ``llm_input_messages``,
212
+ so the state itself is unchanged. To combine it with a hook of your
213
+ own (trimming, say), call ``record`` and ``with_briefing`` from it."""
214
+ return RunnableLambda(self._pre, afunc=self._apre, name="recall_pre_model_hook")
215
+
216
+ @property
217
+ def post_model_hook(self) -> RunnableLambda:
218
+ """For ``create_react_agent(post_model_hook=...)``. Records the model's
219
+ reply as soon as it arrives, so a crash during the tool calls that
220
+ follow does not lose it."""
221
+ return RunnableLambda(self._post, afunc=self._apost, name="recall_post_model_hook")
222
+
223
+ @property
224
+ def record_node(self) -> RunnableLambda:
225
+ """A node for your own StateGraph that records every message not
226
+ recorded yet and changes nothing in the state."""
227
+ return RunnableLambda(self._post, afunc=self._apost, name="recall_record")
228
+
229
+ @property
230
+ def briefing_node(self) -> RunnableLambda:
231
+ """A node for your own StateGraph that adds the briefing to the
232
+ ``messages`` state as a SystemMessage, once per thread. Put it first.
233
+ Prefer ``with_briefing`` in your model node when you can: it keeps the
234
+ briefing out of the state."""
235
+ return RunnableLambda(self._briefing_update, afunc=self._abriefing_update, name="recall_briefing")
236
+
237
+ # Recording.
238
+
239
+ def record(self, messages: Sequence[BaseMessage]) -> int:
240
+ """Record each message not recorded yet, in order, as a turn. Returns
241
+ how many were recorded. Messages are told apart by id; the briefing
242
+ and messages without text are skipped."""
243
+ count = 0
244
+ with self._record_lock:
245
+ if not self._seeded:
246
+ self._seed(messages)
247
+ self._seeded = True
248
+ for message in messages:
249
+ key = _key(message)
250
+ if key in self._recorded or message.id == BRIEFING_ID:
251
+ continue
252
+ turn = _turn(message)
253
+ if turn is not None:
254
+ self.agent.record_turn(*turn, message_id=message.id or None)
255
+ count += 1
256
+ self._recorded.add(key)
257
+ return count
258
+
259
+ def _seed(self, messages: Sequence[BaseMessage]) -> None:
260
+ """Mark messages a checkpointer restored as already recorded.
261
+
262
+ The previous process recorded in order, so every message up to the
263
+ last one whose id the records hold was recorded, whether or not its
264
+ own id made it into the recent turns. Anything after that is new: the
265
+ caller's fresh input, or a message the previous process got but died
266
+ before recording, and both should be recorded now."""
267
+ if self.agent.context.turn_seq == 0:
268
+ return
269
+ known = {t.message_id for t in self.agent.recent_turns(200) if t.message_id}
270
+ last = -1
271
+ for i, message in enumerate(messages):
272
+ if message.id and message.id in known:
273
+ last = i
274
+ for message in messages[: last + 1]:
275
+ self._recorded.add(_key(message))
276
+
277
+ async def arecord(self, messages: Sequence[BaseMessage]) -> int:
278
+ return await asyncio.to_thread(self.record, messages)
279
+
280
+ # What the model tools call.
281
+
282
+ def update_working_state(self, **fields: Any) -> WorkingState:
283
+ return self.agent.update_working_state(**fields)
284
+
285
+ def milestone(self, name: str, progress: str | None = None) -> WorkingState:
286
+ return self.agent.milestone(name, progress)
287
+
288
+ def fetch_output(self, ref: str) -> Output:
289
+ return self.agent.fetch_output(ref)
290
+
291
+ def set_pointer(self, name: str, type: str, fields: Mapping[str, str], note: str | None = None) -> Pointer:
292
+ return self.agent.set_pointer(name, type, fields, note)
293
+
294
+
295
+ def _messages(state: Any) -> list[BaseMessage]:
296
+ messages = state.get("messages") if isinstance(state, Mapping) else getattr(state, "messages", None)
297
+ if messages is None:
298
+ raise ValueError("the graph state has no messages")
299
+ return list(messages)
300
+
301
+
302
+ def _key(message: BaseMessage) -> str:
303
+ if message.id:
304
+ return message.id
305
+ # LangGraph's add_messages gives every message an id, so this is only for
306
+ # lists built by hand.
307
+ body = json.dumps([message.type, message.content, getattr(message, "tool_call_id", None)],
308
+ default=str, sort_keys=True)
309
+ return "sha256:" + hashlib.sha256(body.encode()).hexdigest()
310
+
311
+
312
+ def _text(content: Any) -> str:
313
+ """The readable text of a message: a string, or a list of content blocks."""
314
+ if isinstance(content, str):
315
+ return content
316
+ if not isinstance(content, list):
317
+ return ""
318
+ parts = []
319
+ for block in content:
320
+ if isinstance(block, str):
321
+ parts.append(block)
322
+ elif isinstance(block, dict):
323
+ if isinstance(block.get("text"), str):
324
+ parts.append(block["text"])
325
+ elif block.get("type") not in (None, "tool_use", "tool_call"):
326
+ parts.append(f"[{block['type']}]")
327
+ return "\n".join(p for p in parts if p)
328
+
329
+
330
+ def _turn(message: BaseMessage) -> tuple[str, str, str | None] | None:
331
+ """The (role, content, name) turn one message is recorded as."""
332
+ text = _text(message.content)
333
+ if isinstance(message, HumanMessage):
334
+ return ("user", text, None) if text else None
335
+ if isinstance(message, AIMessage):
336
+ calls = [{"name": c["name"], "args": c["args"], "id": c.get("id")} for c in message.tool_calls]
337
+ if calls:
338
+ rendered = json.dumps({"tool_calls": calls}, ensure_ascii=False, default=str)
339
+ text = f"{text}\n{rendered}" if text else rendered
340
+ return ("assistant", text, None) if text else None
341
+ if isinstance(message, ToolMessage):
342
+ return "tool", text or json.dumps(message.content, default=str), message.name
343
+ if isinstance(message, SystemMessage):
344
+ return ("system", text, None) if text else None
345
+ if isinstance(message, ChatMessage) and message.role in ("system", "user", "assistant", "tool"):
346
+ return (message.role, text, None) if text else None
347
+ return ("assistant", text, None) if text else None
@@ -0,0 +1,140 @@
1
+ """LangChain tools that let the model write what its next instance resumes from."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import Callable
7
+ from typing import Any, Literal, TypeVar
8
+
9
+ from langchain_core.tools import BaseTool, StructuredTool, ToolException
10
+ from polign_recall import RecallError
11
+
12
+ from .resume import RecallResume
13
+
14
+ T = TypeVar("T")
15
+
16
+ PointerType = Literal["git_ref", "object", "env", "external", "process"]
17
+
18
+
19
+ def _call(fn: Callable[[], T]) -> T:
20
+ try:
21
+ return fn()
22
+ except RecallError as exc:
23
+ # The model sees this text as the tool's result and can react to it.
24
+ raise ToolException(str(exc)) from exc
25
+
26
+
27
+ def _tool(fn: Callable[..., str]) -> BaseTool:
28
+ async def coroutine(**kwargs: Any) -> str:
29
+ return await asyncio.to_thread(fn, **kwargs)
30
+
31
+ return StructuredTool.from_function(
32
+ func=fn, coroutine=coroutine, parse_docstring=True, handle_tool_error=True
33
+ )
34
+
35
+
36
+ def recall_tools(resume: RecallResume) -> list[BaseTool]:
37
+ """The tools to give the model: ``update_working_state``, ``milestone``,
38
+ ``fetch_output`` and ``set_pointer``. Each works with ``invoke`` and
39
+ ``ainvoke``. A failed call comes back to the model as the tool's text."""
40
+
41
+ def update_working_state(
42
+ goal: str | None = None,
43
+ plan: list[str] | None = None,
44
+ progress: str | None = None,
45
+ focus: str | None = None,
46
+ decisions: list[str] | None = None,
47
+ open_questions: list[str] | None = None,
48
+ notes: str | None = None,
49
+ ) -> str:
50
+ """Save your working state: the note your next instance resumes from if this run stops.
51
+
52
+ Fields you give replace the current ones; fields you leave out are kept. Write it at
53
+ natural boundaries, as a colleague taking over would need it.
54
+
55
+ Args:
56
+ goal: What the whole task is for.
57
+ plan: The remaining steps, in order.
58
+ progress: What is done so far.
59
+ focus: What you are doing right now.
60
+ decisions: Decisions made, each with its reason.
61
+ open_questions: What is still unknown.
62
+ notes: Anything else the next instance needs.
63
+ """
64
+ given = {
65
+ "goal": goal, "plan": plan, "progress": progress, "focus": focus,
66
+ "decisions": decisions, "open_questions": open_questions, "notes": notes,
67
+ }
68
+ state = _call(lambda: resume.update_working_state(**{k: v for k, v in given.items() if v is not None}))
69
+ return f"Working state saved (version {state.version})."
70
+
71
+ def milestone(name: str, progress: str | None = None) -> str:
72
+ """Declare that you reached a durable point, such as tests passing or a section drafted.
73
+
74
+ If this run stops, the next instance loses at most the work since the last milestone.
75
+
76
+ Args:
77
+ name: The milestone reached.
78
+ progress: What is now done.
79
+ """
80
+ _call(lambda: resume.milestone(name, progress))
81
+ return f"Milestone recorded: {name}."
82
+
83
+ def fetch_output(ref: str) -> str:
84
+ """Return a stored output in full, by the ref shown in your context.
85
+
86
+ Args:
87
+ ref: The output's ref.
88
+ """
89
+ return _call(lambda: resume.fetch_output(ref)).content
90
+
91
+ def set_pointer(
92
+ name: str,
93
+ type: PointerType,
94
+ repo: str | None = None,
95
+ branch: str | None = None,
96
+ sha: str | None = None,
97
+ uri: str | None = None,
98
+ image: str | None = None,
99
+ lockfile_hash: str | None = None,
100
+ setup: str | None = None,
101
+ kind: str | None = None,
102
+ id: str | None = None,
103
+ url: str | None = None,
104
+ command: str | None = None,
105
+ port: str | None = None,
106
+ note: str | None = None,
107
+ ) -> str:
108
+ """Record where a piece of your work lives, so your next instance can find it.
109
+
110
+ Replaces any pointer with the same name. Each type needs one of its fields:
111
+ git_ref (repo, branch, sha; needs sha or branch), object (uri), env (image,
112
+ lockfile_hash, setup), external (kind, id, url; needs id or url), process
113
+ (command, port; needs command).
114
+
115
+ Args:
116
+ name: A stable name for this piece of work.
117
+ type: Where it lives.
118
+ repo: git_ref: the repository.
119
+ branch: git_ref: the branch.
120
+ sha: git_ref: the commit.
121
+ uri: object: where the object is stored.
122
+ image: env: the container image.
123
+ lockfile_hash: env: the hash of the dependency lockfile.
124
+ setup: env: how to set the environment up.
125
+ kind: external: what kind of thing it is, such as a ticket.
126
+ id: external: its id.
127
+ url: external: its URL.
128
+ command: process: the command that runs it.
129
+ port: process: the port it listens on.
130
+ note: What it is.
131
+ """
132
+ given = {
133
+ "repo": repo, "branch": branch, "sha": sha, "uri": uri, "image": image,
134
+ "lockfile_hash": lockfile_hash, "setup": setup, "kind": kind, "id": id,
135
+ "url": url, "command": command, "port": port,
136
+ }
137
+ pointer = _call(lambda: resume.set_pointer(name, type, {k: v for k, v in given.items() if v}, note))
138
+ return f"Pointer {pointer.name} saved."
139
+
140
+ return [_tool(f) for f in (update_working_state, milestone, fetch_output, set_pointer)]
@@ -0,0 +1,209 @@
1
+ Metadata-Version: 2.5
2
+ Name: recall-langgraph
3
+ Version: 0.1.0
4
+ Summary: Resume LangGraph agents from their own records, backed by Recall by Polign
5
+ Project-URL: Homepage, https://polign.com
6
+ Project-URL: Documentation, https://polign.com/integrations.html
7
+ Project-URL: Repository, https://github.com/Polign/polign
8
+ Project-URL: Issues, https://github.com/Polign/polign/issues
9
+ Author: Polign
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agent memory,langchain,langgraph,polign,recall,resume
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: langchain-core<2,>=1.0
21
+ Requires-Dist: langgraph<2,>=1.0
22
+ Requires-Dist: polign-recall>=0.4.0
23
+ Description-Content-Type: text/markdown
24
+
25
+ # recall-langgraph
26
+
27
+ Resume [LangGraph](https://github.com/langchain-ai/langgraph) agents from
28
+ their own records, backed by [Recall by Polign](https://polign.com/recall.html).
29
+
30
+ A long-running agent that crashes, gets rescheduled, or moves to another
31
+ machine usually starts over, or restores an exact snapshot of its state. With
32
+ this package it picks up where it left off from what it wrote down instead:
33
+ while it works, it keeps a working state (its goal, plan, progress and
34
+ decisions) and pointers to where its work lives, and every message of the run
35
+ is recorded. The next process that opens the same agent id gets a fresh
36
+ starting context built from those records, sized to a token budget.
37
+
38
+ This sits beside your checkpointer, not in place of it. LangGraph's
39
+ checkpointer still handles threads and interrupts however you configure it.
40
+
41
+ ```bash
42
+ pip install recall-langgraph
43
+ ```
44
+
45
+ pip also brings the [`polign_db`](https://pypi.org/project/polign-db/)
46
+ package with the `polign` CLI and `polign-server` binaries for Linux, macOS
47
+ and Windows, so there is no separate database to download.
48
+
49
+ ## Usage with create_react_agent
50
+
51
+ ```python
52
+ from langchain_openai import ChatOpenAI
53
+ from langgraph.prebuilt import create_react_agent
54
+ from recall_langgraph import RecallResume, recall_tools
55
+
56
+ with RecallResume("billing-migrator", local_dir="./recall-data") as resume:
57
+ agent = create_react_agent(
58
+ ChatOpenAI(model="gpt-4.1"),
59
+ tools=[*your_tools, *recall_tools(resume)],
60
+ prompt=(
61
+ "You move the billing service to the v2 API. Keep your working state "
62
+ "current with update_working_state, and call milestone when a step is done."
63
+ ),
64
+ pre_model_hook=resume.pre_model_hook,
65
+ post_model_hook=resume.post_model_hook,
66
+ )
67
+ agent.invoke({"messages": [("user", "Carry on with the migration.")]})
68
+ ```
69
+
70
+ Run it, stop it halfway, and run it again: the second run starts from the
71
+ working state, pointers and recent turns the first one wrote.
72
+
73
+ What happens:
74
+
75
+ 1. Entering the `with` block resumes the agent. It takes a lease on the id,
76
+ so only one process acts for the agent at a time, and reads back its
77
+ records. The first time an id is used, it starts fresh.
78
+ 2. Before every model call, `pre_model_hook` puts one `SystemMessage` in
79
+ front of the messages, the briefing: the working state, pointers to the
80
+ work, relevant memories, and the most recent turns, within
81
+ `token_budget`. It goes to the model as `llm_input_messages`, so the
82
+ graph's `messages` state never holds it.
83
+ 3. The hooks record each new message once, in order, as a turn: human
84
+ messages before the model call, the model's reply right after it, and tool
85
+ results before the next call. A reply with tool calls is recorded with the
86
+ calls as JSON text. A turn longer than the output threshold is stored whole
87
+ as an output, and the briefing shows a reference the model can pass to
88
+ `fetch_output`.
89
+ 4. The model keeps its working state current through the tools from
90
+ `recall_tools`.
91
+ 5. Leaving the block (or calling `release()`) hands the lease over, so the
92
+ next process can resume at once. A process that dies without releasing
93
+ holds the lease until it expires (60 seconds by default).
94
+
95
+ Recall never replays old messages into the state: the briefing already
96
+ carries the recent turns as text, and a replayed tool result without its
97
+ matching tool call would be refused by the model API. On a new `thread_id`,
98
+ the resumed run starts from the briefing alone. On the old `thread_id`, a
99
+ persistent checkpointer restores the old messages as well, and nothing is
100
+ recorded twice: each turn keeps its message id, so the first recording after
101
+ a resume skips every restored message up to the last one Recall already has.
102
+ Messages after that one, such as the caller's new input or a reply the dead
103
+ process never recorded, are recorded as usual. The model then sees the
104
+ restored history and the briefing both; start a new thread if you would
105
+ rather it saw only the briefing.
106
+
107
+ `create_react_agent` is deprecated in LangGraph 1.0 in favor of
108
+ `langchain.agents.create_agent`, but it still ships in `langgraph.prebuilt`
109
+ and the hooks work with it. Use `version="v2"` (the default), since
110
+ `post_model_hook` needs it.
111
+
112
+ ## Your own StateGraph
113
+
114
+ ```python
115
+ from langgraph.graph import START, MessagesState, StateGraph
116
+
117
+ def call_model(state: MessagesState):
118
+ return {"messages": [model.invoke(resume.with_briefing(state["messages"]))]}
119
+
120
+ builder = StateGraph(MessagesState)
121
+ builder.add_node("model", call_model)
122
+ builder.add_node("record", resume.record_node)
123
+ builder.add_edge(START, "model")
124
+ builder.add_edge("model", "record")
125
+ ```
126
+
127
+ - `with_briefing(messages)` returns the messages with the briefing in front,
128
+ for the model's input, and leaves the state alone.
129
+ - `record_node` records every message not recorded yet and changes nothing.
130
+ Put it after each node that adds messages. `record(messages)` does the same
131
+ from your own code.
132
+ - `briefing_node` adds the briefing to the `messages` state itself, once per
133
+ thread, if you would rather keep it there. Put it first.
134
+
135
+ The hooks and nodes work with `invoke` and `ainvoke`.
136
+
137
+ ## The tools
138
+
139
+ | Tool | What the model uses it for |
140
+ |---|---|
141
+ | `update_working_state` | Save its goal, plan, progress, focus, decisions, open questions and notes. Fields it leaves out are kept. |
142
+ | `milestone` | Declare a durable point, such as tests passing. |
143
+ | `fetch_output` | Read a stored output in full by its ref. |
144
+ | `set_pointer` | Record where a piece of work lives: a git branch or commit, an object, an environment, an external item, or a process. |
145
+
146
+ A failed call comes back to the model as the tool's text. Your own code can
147
+ call `resume.update_working_state`, `resume.milestone`, `resume.fetch_output`
148
+ and `resume.set_pointer`, and `resume.agent` is the underlying
149
+ `polign_recall.ResumedAgent` for everything else (`record_turn`,
150
+ `recent_turns`, `store_output`, `pointers`, `working_state_history`).
151
+ `resume.context` is what the resume returned, and `resume.briefing` its text.
152
+
153
+ ## Options
154
+
155
+ | Option | Default | What it does |
156
+ |---|---|---|
157
+ | `client` | none | A `polign_recall.Client` opened with `agent=True`, to share one subprocess. Without it, `RecallResume` opens its own and closes it on release. |
158
+ | `local_dir` | none | Keep the database in this directory and run its server (only when `RecallResume` opens its own client) |
159
+ | `env` | process environment | `POLIGN_URL`, `POLIGN_API_KEY` and the rest, for a server you run yourself |
160
+ | `token_budget` | 8000 | Bound on the briefing, in tokens |
161
+ | `lease_ttl` | 60 | Seconds each lease epoch lasts; renewed in the background |
162
+ | `holder` | host, pid and a random suffix | Names this process in lease records |
163
+ | `output_threshold` | 2000 | Turns longer than this many tokens are stored as outputs |
164
+
165
+ ## Errors
166
+
167
+ If another process holds the agent, resuming raises
168
+ `polign_recall.RecallError` with code `"lease_held"`. Wait and try again, or
169
+ stop. If another process takes the agent over mid-run, the next record fails
170
+ with code `"lease_lost"`, which stops the graph run; this process should
171
+ stop acting for the agent.
172
+
173
+ Records are append-only. Removing or trimming messages in the graph state
174
+ changes what the model sees, never what was recorded.
175
+
176
+ ## Where the records are stored
177
+
178
+ `local_dir="./recall-data"` keeps the database on this machine; the first
179
+ process to open the directory starts a `polign-server` for it in the
180
+ background, and later ones share it. Agents that move between machines need
181
+ one shared server: run `polign-server` where they can all reach it
182
+ ([Get started](https://polign.com/developers.html) shows how, including
183
+ storing into S3, GCS or Azure) and pass its address through `env` or the
184
+ environment:
185
+
186
+ ```python
187
+ RecallResume(
188
+ "billing-migrator",
189
+ env={"POLIGN_URL": "http://memory.internal:23000", "POLIGN_API_KEY": key},
190
+ )
191
+ ```
192
+
193
+ The agent's records live in their own collection next to the memory
194
+ collection (`<collection>_agents`).
195
+
196
+ ## Development
197
+
198
+ ```bash
199
+ cd python/recall-langgraph
200
+ python -m pip install -e . pytest pytest-asyncio
201
+ pytest tests/unit_tests -q # a fake Recall client, no network
202
+ pytest tests/integration_tests -v # real polign-server and polign CLI
203
+ ```
204
+
205
+ The integration tests locate the binaries like the other packages' tests do
206
+ (`POLIGN_SERVER`, `POLIGN_SOURCE`, `POLIGN_SERVER_VERSION`, or the latest
207
+ release download) and skip when none is found or when the CLI has no
208
+ `polign mcp -agent`. Both suites drive real compiled graphs with a scripted
209
+ chat model, so no model API key is needed.
@@ -0,0 +1,8 @@
1
+ recall_langgraph/__init__.py,sha256=gabHg0Xv5jJXF-Kl13XBrr4gnGpLCMjMXlWeUCIYQ8M,757
2
+ recall_langgraph/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ recall_langgraph/resume.py,sha256=j3dEckPH_OKf_0xALz3F9wbiOEzla-FLYVGz7Va4Aao,14189
4
+ recall_langgraph/tools.py,sha256=BwoO4qdTb9r8OHZlhBKMaYYzorHsSCHw9s4Qmr6jID4,5426
5
+ recall_langgraph-0.1.0.dist-info/METADATA,sha256=o0s94O8MLvsFdnILolKH0DEOWjgIDFBaogV9KmXGMnk,9596
6
+ recall_langgraph-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
7
+ recall_langgraph-0.1.0.dist-info/licenses/LICENSE,sha256=ra9FdQ2xyykGuwkTiZDGe8MaUdF61EbNfS6xW16vQUY,11343
8
+ recall_langgraph-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Polign, Inc.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.