@@ -160,12 +160,15 @@ async def get_items(
160160 self ,
161161 limit : int | None = None ,
162162 branch_id : str | None = None ,
163+ offset : int = 0 ,
163164 ) -> list [TResponseInputItem ]:
164165 """Get items from current or specified branch.
165166
166167 Args:
167168 limit: Maximum number of items to return. If None, uses session_settings.limit.
168169 branch_id: Branch to get items from. If None, uses current branch.
170+ offset: Number of most-recent items to skip before applying the limit.
171+ Defaults to 0. Use with limit to paginate backwards through history.
169172
170173 Returns:
171174 List of conversation items from the specified branch.
@@ -180,7 +183,7 @@ def _get_all_items_sync():
180183 """Synchronous helper to get all items for a branch."""
181184 with self ._locked_connection () as conn :
182185 with closing (conn .cursor ()) as cursor :
183- if session_limit is None :
186+ if session_limit is None and offset == 0 :
184187 cursor .execute (
185188 f"""
186189 SELECT m.message_data
@@ -192,20 +195,21 @@ def _get_all_items_sync():
192195 (self .session_id , branch_id ),
193196 )
194197 else :
198+ sql_limit = session_limit if session_limit is not None else - 1
195199 cursor .execute (
196200 f"""
197201 SELECT m.message_data
198202 FROM { self .messages_table } m
199203 JOIN message_structure s ON m.id = s.message_id
200204 WHERE m.session_id = ? AND s.branch_id = ?
201205 ORDER BY s.sequence_number DESC
202- LIMIT ?
206+ LIMIT ? OFFSET ?
203207 """ ,
204- (self .session_id , branch_id , session_limit ),
208+ (self .session_id , branch_id , sql_limit , offset ),
205209 )
206210
207211 rows = cursor .fetchall ()
208- if session_limit is not None :
212+ if session_limit is not None or offset > 0 :
209213 rows = list (reversed (rows ))
210214
211215 items = []
@@ -224,7 +228,7 @@ def _get_items_sync():
224228 with self ._locked_connection () as conn :
225229 with closing (conn .cursor ()) as cursor :
226230 # Get message IDs in correct order for this branch
227- if session_limit is None :
231+ if session_limit is None and offset == 0 :
228232 cursor .execute (
229233 f"""
230234 SELECT m.message_data
@@ -236,20 +240,21 @@ def _get_items_sync():
236240 (self .session_id , branch_id ),
237241 )
238242 else :
243+ sql_limit = session_limit if session_limit is not None else - 1
239244 cursor .execute (
240245 f"""
241246 SELECT m.message_data
242247 FROM { self .messages_table } m
243248 JOIN message_structure s ON m.id = s.message_id
244249 WHERE m.session_id = ? AND s.branch_id = ?
245250 ORDER BY s.sequence_number DESC
246- LIMIT ?
251+ LIMIT ? OFFSET ?
247252 """ ,
248- (self .session_id , branch_id , session_limit ),
253+ (self .session_id , branch_id , sql_limit , offset ),
249254 )
250255
251256 rows = cursor .fetchall ()
252- if session_limit is not None :
257+ if session_limit is not None or offset > 0 :
253258 rows = list (reversed (rows ))
254259
255260 items = []
0 commit comments