kestrelx 0.0.1__py3-none-win_amd64.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.
kestrelx/__init__.py ADDED
@@ -0,0 +1,899 @@
1
+ """Python binding for the Kestrel agent core.
2
+
3
+ Published wheels bundle the native library. Source checkouts can build it with:
4
+
5
+ cargo build -p kestrel-ffi
6
+
7
+ Set KESTREL_FFI_PATH to load a different shared library.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import ctypes
13
+ import asyncio
14
+ import json
15
+ import os
16
+ from pathlib import Path
17
+ from typing import Any, Callable, Optional, Union
18
+
19
+ from ._version import __version__
20
+
21
+
22
+ EventCallback = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_char_p)
23
+ ToolCallback = ctypes.CFUNCTYPE(
24
+ ctypes.c_void_p,
25
+ ctypes.c_void_p,
26
+ ctypes.c_char_p,
27
+ ctypes.c_char_p,
28
+ )
29
+ ModelCallback = ctypes.CFUNCTYPE(
30
+ ctypes.c_void_p,
31
+ ctypes.c_void_p,
32
+ ctypes.c_char_p,
33
+ )
34
+ DeltaEmitter = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_char_p)
35
+ StreamingModelCallback = ctypes.CFUNCTYPE(
36
+ ctypes.c_void_p,
37
+ ctypes.c_void_p,
38
+ ctypes.c_char_p,
39
+ DeltaEmitter,
40
+ ctypes.c_void_p,
41
+ ctypes.POINTER(ctypes.c_void_p),
42
+ )
43
+ SessionLoadCallback = ctypes.CFUNCTYPE(
44
+ ctypes.c_void_p,
45
+ ctypes.c_void_p,
46
+ ctypes.c_char_p,
47
+ ctypes.POINTER(ctypes.c_void_p),
48
+ )
49
+ SessionSaveCallback = ctypes.CFUNCTYPE(
50
+ ctypes.c_int32,
51
+ ctypes.c_void_p,
52
+ ctypes.c_char_p,
53
+ ctypes.POINTER(ctypes.c_void_p),
54
+ )
55
+ SessionDeleteCallback = SessionSaveCallback
56
+ MemoryRecallCallback = SessionLoadCallback
57
+ MemoryRememberCallback = SessionSaveCallback
58
+
59
+
60
+ class KestrelError(RuntimeError):
61
+ """Raised when the native Kestrel library reports an error."""
62
+
63
+
64
+ def _candidate_libraries() -> list[Path]:
65
+ names = (
66
+ "libkestrel_ffi.dylib",
67
+ "libkestrel_ffi.so",
68
+ "kestrel_ffi.dll",
69
+ )
70
+ package = Path(__file__).resolve().parent
71
+ candidates = [
72
+ package / "_native" / name
73
+ for name in names
74
+ ]
75
+ root = package
76
+ for parent in package.parents:
77
+ if (parent / "Cargo.toml").is_file() and (parent / "kestrel-ffi").is_dir():
78
+ root = parent
79
+ break
80
+ candidates.extend(
81
+ root / "target" / profile / name
82
+ for profile in ("debug", "release")
83
+ for name in names
84
+ )
85
+ return candidates
86
+
87
+
88
+ def load_library(path: Optional[str] = None) -> ctypes.CDLL:
89
+ """Loads the shared library and configures exported signatures."""
90
+ candidates = [Path(path)] if path else []
91
+ env_path = os.environ.get("KESTREL_FFI_PATH")
92
+ if env_path:
93
+ candidates.append(Path(env_path))
94
+ candidates.extend(_candidate_libraries())
95
+
96
+ library_path = next((candidate for candidate in candidates if candidate.exists()), None)
97
+ if library_path is None:
98
+ raise KestrelError(
99
+ "kestrel_ffi shared library not found; install a platform wheel "
100
+ "or run `cargo build -p kestrel-ffi`, or set KESTREL_FFI_PATH"
101
+ )
102
+
103
+ library = ctypes.CDLL(str(library_path))
104
+ library.kestrel_version.argtypes = []
105
+ library.kestrel_version.restype = ctypes.c_char_p
106
+ library.kestrel_contract_version.argtypes = []
107
+ library.kestrel_contract_version.restype = ctypes.c_uint32
108
+ library.kestrel_capabilities_json.argtypes = [
109
+ ctypes.POINTER(ctypes.c_void_p),
110
+ ]
111
+ library.kestrel_capabilities_json.restype = ctypes.c_void_p
112
+ library.kestrel_validate_config.argtypes = [
113
+ ctypes.c_char_p,
114
+ ctypes.c_int32,
115
+ ctypes.POINTER(ctypes.c_void_p),
116
+ ]
117
+ library.kestrel_validate_config.restype = ctypes.c_int32
118
+ library.kestrel_string_new.argtypes = [ctypes.c_char_p]
119
+ library.kestrel_string_new.restype = ctypes.c_void_p
120
+ library.kestrel_string_free.argtypes = [ctypes.c_void_p]
121
+ library.kestrel_string_free.restype = None
122
+ library.kestrel_agent_new.argtypes = [
123
+ ctypes.c_char_p,
124
+ ctypes.POINTER(ctypes.c_void_p),
125
+ ]
126
+ library.kestrel_agent_new.restype = ctypes.c_void_p
127
+ library.kestrel_agent_new_with_model.argtypes = [
128
+ ctypes.c_char_p,
129
+ ModelCallback,
130
+ ctypes.c_void_p,
131
+ ctypes.POINTER(ctypes.c_void_p),
132
+ ]
133
+ library.kestrel_agent_new_with_model.restype = ctypes.c_void_p
134
+ library.kestrel_agent_new_with_streaming_model.argtypes = [
135
+ ctypes.c_char_p,
136
+ StreamingModelCallback,
137
+ ctypes.c_void_p,
138
+ ctypes.POINTER(ctypes.c_void_p),
139
+ ]
140
+ library.kestrel_agent_new_with_streaming_model.restype = ctypes.c_void_p
141
+ library.kestrel_agent_builder_new.argtypes = [
142
+ ctypes.c_char_p,
143
+ ctypes.POINTER(ctypes.c_void_p),
144
+ ]
145
+ library.kestrel_agent_builder_new.restype = ctypes.c_void_p
146
+ library.kestrel_agent_builder_new_with_model.argtypes = [
147
+ ctypes.c_char_p,
148
+ ModelCallback,
149
+ ctypes.c_void_p,
150
+ ctypes.POINTER(ctypes.c_void_p),
151
+ ]
152
+ library.kestrel_agent_builder_new_with_model.restype = ctypes.c_void_p
153
+ library.kestrel_agent_builder_new_with_streaming_model.argtypes = [
154
+ ctypes.c_char_p,
155
+ StreamingModelCallback,
156
+ ctypes.c_void_p,
157
+ ctypes.POINTER(ctypes.c_void_p),
158
+ ]
159
+ library.kestrel_agent_builder_new_with_streaming_model.restype = ctypes.c_void_p
160
+ library.kestrel_agent_builder_set_session_store.argtypes = [
161
+ ctypes.c_void_p,
162
+ SessionLoadCallback,
163
+ SessionSaveCallback,
164
+ SessionDeleteCallback,
165
+ ctypes.c_void_p,
166
+ ctypes.POINTER(ctypes.c_void_p),
167
+ ]
168
+ library.kestrel_agent_builder_set_session_store.restype = ctypes.c_int32
169
+ library.kestrel_agent_builder_set_memory.argtypes = [
170
+ ctypes.c_void_p,
171
+ MemoryRecallCallback,
172
+ MemoryRememberCallback,
173
+ ctypes.c_void_p,
174
+ ctypes.POINTER(ctypes.c_void_p),
175
+ ]
176
+ library.kestrel_agent_builder_set_memory.restype = ctypes.c_int32
177
+ library.kestrel_agent_builder_build.argtypes = [
178
+ ctypes.c_void_p,
179
+ ctypes.POINTER(ctypes.c_void_p),
180
+ ]
181
+ library.kestrel_agent_builder_build.restype = ctypes.c_void_p
182
+ library.kestrel_agent_builder_free.argtypes = [ctypes.c_void_p]
183
+ library.kestrel_agent_builder_free.restype = None
184
+ library.kestrel_agent_free.argtypes = [ctypes.c_void_p]
185
+ library.kestrel_agent_free.restype = None
186
+ library.kestrel_agent_set_event_callback.argtypes = [
187
+ ctypes.c_void_p,
188
+ EventCallback,
189
+ ctypes.c_void_p,
190
+ ]
191
+ library.kestrel_agent_set_event_callback.restype = ctypes.c_int32
192
+ library.kestrel_agent_register_tool.argtypes = [
193
+ ctypes.c_void_p,
194
+ ctypes.c_char_p,
195
+ ctypes.c_char_p,
196
+ ctypes.c_char_p,
197
+ ToolCallback,
198
+ ctypes.c_void_p,
199
+ ctypes.POINTER(ctypes.c_void_p),
200
+ ]
201
+ library.kestrel_agent_register_tool.restype = ctypes.c_int32
202
+ library.kestrel_agent_run.argtypes = [
203
+ ctypes.c_void_p,
204
+ ctypes.c_char_p,
205
+ ctypes.POINTER(ctypes.c_void_p),
206
+ ]
207
+ library.kestrel_agent_run.restype = ctypes.c_void_p
208
+ library.kestrel_agent_run_message.argtypes = [
209
+ ctypes.c_void_p,
210
+ ctypes.c_char_p,
211
+ ctypes.POINTER(ctypes.c_void_p),
212
+ ]
213
+ library.kestrel_agent_run_message.restype = ctypes.c_void_p
214
+ library.kestrel_agent_resume.argtypes = [
215
+ ctypes.c_void_p,
216
+ ctypes.c_int32,
217
+ ctypes.POINTER(ctypes.c_void_p),
218
+ ]
219
+ library.kestrel_agent_resume.restype = ctypes.c_void_p
220
+ library.kestrel_agent_start_run.argtypes = [
221
+ ctypes.c_void_p,
222
+ ctypes.c_char_p,
223
+ ctypes.POINTER(ctypes.c_void_p),
224
+ ]
225
+ library.kestrel_agent_start_run.restype = ctypes.c_void_p
226
+ library.kestrel_agent_start_run_message.argtypes = [
227
+ ctypes.c_void_p,
228
+ ctypes.c_char_p,
229
+ ctypes.POINTER(ctypes.c_void_p),
230
+ ]
231
+ library.kestrel_agent_start_run_message.restype = ctypes.c_void_p
232
+ library.kestrel_agent_start_resume.argtypes = [
233
+ ctypes.c_void_p,
234
+ ctypes.c_int32,
235
+ ctypes.POINTER(ctypes.c_void_p),
236
+ ]
237
+ library.kestrel_agent_start_resume.restype = ctypes.c_void_p
238
+ library.kestrel_run_next_event.argtypes = [
239
+ ctypes.c_void_p,
240
+ ctypes.c_int32,
241
+ ctypes.POINTER(ctypes.c_void_p),
242
+ ctypes.POINTER(ctypes.c_void_p),
243
+ ]
244
+ library.kestrel_run_next_event.restype = ctypes.c_int32
245
+ library.kestrel_run_wait.argtypes = [
246
+ ctypes.c_void_p,
247
+ ctypes.c_int32,
248
+ ctypes.POINTER(ctypes.c_void_p),
249
+ ctypes.POINTER(ctypes.c_void_p),
250
+ ]
251
+ library.kestrel_run_wait.restype = ctypes.c_int32
252
+ library.kestrel_run_is_done.argtypes = [ctypes.c_void_p]
253
+ library.kestrel_run_is_done.restype = ctypes.c_int32
254
+ library.kestrel_run_cancel.argtypes = [ctypes.c_void_p]
255
+ library.kestrel_run_cancel.restype = ctypes.c_int32
256
+ library.kestrel_run_free.argtypes = [ctypes.c_void_p]
257
+ library.kestrel_run_free.restype = None
258
+ library.kestrel_agent_cancel.argtypes = [ctypes.c_void_p]
259
+ library.kestrel_agent_cancel.restype = ctypes.c_int32
260
+ library.kestrel_agent_session_json.argtypes = [
261
+ ctypes.c_void_p,
262
+ ctypes.POINTER(ctypes.c_void_p),
263
+ ]
264
+ library.kestrel_agent_session_json.restype = ctypes.c_void_p
265
+ library.kestrel_agent_todos_json.argtypes = [
266
+ ctypes.c_void_p,
267
+ ctypes.POINTER(ctypes.c_void_p),
268
+ ]
269
+ library.kestrel_agent_todos_json.restype = ctypes.c_void_p
270
+ library.kestrel_agent_reset.argtypes = [
271
+ ctypes.c_void_p,
272
+ ctypes.POINTER(ctypes.c_void_p),
273
+ ]
274
+ library.kestrel_agent_reset.restype = ctypes.c_int32
275
+ library.kestrel_agent_delete_session.argtypes = [
276
+ ctypes.c_void_p,
277
+ ctypes.POINTER(ctypes.c_void_p),
278
+ ]
279
+ library.kestrel_agent_delete_session.restype = ctypes.c_int32
280
+ return library
281
+
282
+
283
+ def _take_contract_string(library: ctypes.CDLL, pointer: int) -> str:
284
+ value = ctypes.string_at(pointer).decode()
285
+ library.kestrel_string_free(pointer)
286
+ return value
287
+
288
+
289
+ def _take_contract_error(library: ctypes.CDLL, error: ctypes.c_void_p) -> str:
290
+ if not error:
291
+ return "unknown contract error"
292
+ return _take_contract_string(library, error)
293
+
294
+
295
+ def contract_version(library: Optional[ctypes.CDLL] = None) -> int:
296
+ """Returns the shared configuration schema version."""
297
+ lib = library or load_library()
298
+ return int(lib.kestrel_contract_version())
299
+
300
+
301
+ def capabilities(library: Optional[ctypes.CDLL] = None) -> list[str]:
302
+ """Returns capability names supported by the FFI build."""
303
+ lib = library or load_library()
304
+ error = ctypes.c_void_p()
305
+ pointer = lib.kestrel_capabilities_json(ctypes.byref(error))
306
+ if not pointer:
307
+ raise KestrelError(_take_contract_error(lib, error))
308
+ return json.loads(_take_contract_string(lib, pointer))
309
+
310
+
311
+ def validate_config(
312
+ config: Union[dict[str, Any], str],
313
+ has_custom_model: bool = False,
314
+ library: Optional[ctypes.CDLL] = None,
315
+ ) -> None:
316
+ """Validates config against the shared schema and FFI capabilities."""
317
+ lib = library or load_library()
318
+ config_json = config if isinstance(config, str) else json.dumps(config)
319
+ error = ctypes.c_void_p()
320
+ status = lib.kestrel_validate_config(
321
+ config_json.encode(),
322
+ 1 if has_custom_model else 0,
323
+ ctypes.byref(error),
324
+ )
325
+ if status != 0:
326
+ raise KestrelError(_take_contract_error(lib, error))
327
+
328
+
329
+ class Agent:
330
+ """Owns one native Kestrel agent and keeps callback objects alive."""
331
+
332
+ def __init__(
333
+ self,
334
+ config: Union[dict[str, Any], str],
335
+ *,
336
+ model: Optional[Callable[[dict[str, Any]], dict[str, Any]]] = None,
337
+ stream_model: Optional[
338
+ Callable[[dict[str, Any], Callable[[dict[str, Any]], None]], dict[str, Any]]
339
+ ] = None,
340
+ session_store: Optional[Any] = None,
341
+ memory: Optional[Any] = None,
342
+ library: Optional[ctypes.CDLL] = None,
343
+ ) -> None:
344
+ self._lib = library or load_library()
345
+ self._handle = ctypes.c_void_p()
346
+ self._tool_callbacks: list[Any] = []
347
+ self._service_callbacks: list[Any] = []
348
+ self._runs: list[Any] = []
349
+ self._event_callback: Optional[Any] = None
350
+ self.events: list[dict[str, Any]] = []
351
+ self._event_handler: Optional[Callable[[dict[str, Any]], None]] = None
352
+ config_json = config if isinstance(config, str) else json.dumps(config)
353
+ error = ctypes.c_void_p()
354
+ if model is not None and stream_model is not None:
355
+ raise ValueError("model and stream_model are mutually exclusive")
356
+
357
+ if session_store is not None or memory is not None:
358
+ handle = self._build_with_services(
359
+ config_json,
360
+ model,
361
+ stream_model,
362
+ session_store,
363
+ memory,
364
+ error,
365
+ )
366
+ elif stream_model is not None:
367
+ self._model_callback = StreamingModelCallback(
368
+ self._streaming_model_proxy(stream_model)
369
+ )
370
+ handle = self._lib.kestrel_agent_new_with_streaming_model(
371
+ config_json.encode(),
372
+ self._model_callback,
373
+ None,
374
+ ctypes.byref(error),
375
+ )
376
+ elif model is None:
377
+ self._model_callback = None
378
+ handle = self._lib.kestrel_agent_new(config_json.encode(), ctypes.byref(error))
379
+ else:
380
+ self._model_callback = ModelCallback(self._model_proxy(model))
381
+ handle = self._lib.kestrel_agent_new_with_model(
382
+ config_json.encode(),
383
+ self._model_callback,
384
+ None,
385
+ ctypes.byref(error),
386
+ )
387
+
388
+ if not handle:
389
+ raise KestrelError(self._take_error(error))
390
+ self._handle = ctypes.c_void_p(handle)
391
+
392
+ @property
393
+ def version(self) -> str:
394
+ """Returns the native library version."""
395
+ return self._lib.kestrel_version().decode()
396
+
397
+ def set_event_handler(
398
+ self,
399
+ handler: Optional[Callable[[dict[str, Any]], None]],
400
+ ) -> None:
401
+ """Installs a Python event handler. Callbacks run on a Rust thread."""
402
+ self._event_handler = handler
403
+ if handler is None:
404
+ self._event_callback = None
405
+ self._lib.kestrel_agent_set_event_callback(self._handle, None, None)
406
+ return
407
+
408
+ def event_proxy(_user_data: Any, event_ptr: bytes) -> None:
409
+ event = json.loads(event_ptr.decode())
410
+ self.events.append(event)
411
+ try:
412
+ handler(event)
413
+ except Exception:
414
+ # Exceptions must not unwind through the C ABI.
415
+ pass
416
+
417
+ self._event_callback = EventCallback(event_proxy)
418
+ status = self._lib.kestrel_agent_set_event_callback(
419
+ self._handle,
420
+ self._event_callback,
421
+ None,
422
+ )
423
+ if status != 0:
424
+ raise KestrelError("failed to install event callback")
425
+
426
+ def register_tool(
427
+ self,
428
+ name: str,
429
+ description: str,
430
+ input_schema: dict[str, Any],
431
+ handler: Callable[
432
+ [dict[str, Any], str],
433
+ Union[str, dict[str, Any]],
434
+ ],
435
+ ) -> None:
436
+ """Registers a synchronous Python tool callback."""
437
+ def tool_proxy(
438
+ _user_data: Any,
439
+ call_id_ptr: bytes,
440
+ arguments_ptr: bytes,
441
+ ) -> int:
442
+ try:
443
+ arguments = json.loads(arguments_ptr.decode())
444
+ result = handler(arguments, call_id_ptr.decode())
445
+ text = result if isinstance(result, str) else json.dumps(result)
446
+ except Exception as error:
447
+ text = json.dumps(
448
+ {"content": f"Python tool failed: {error}", "is_error": True}
449
+ )
450
+ return int(self._lib.kestrel_string_new(text.encode()) or 0)
451
+
452
+ callback = ToolCallback(tool_proxy)
453
+ error = ctypes.c_void_p()
454
+ status = self._lib.kestrel_agent_register_tool(
455
+ self._handle,
456
+ name.encode(),
457
+ description.encode(),
458
+ json.dumps(input_schema).encode(),
459
+ callback,
460
+ None,
461
+ ctypes.byref(error),
462
+ )
463
+ if status != 0:
464
+ raise KestrelError(self._take_error(error))
465
+ self._tool_callbacks.append(callback)
466
+
467
+ def run(self, prompt: str) -> dict[str, Any]:
468
+ """Runs one prompt synchronously and returns AgentOutput JSON."""
469
+ return self._run_call(
470
+ self._lib.kestrel_agent_run,
471
+ prompt.encode(),
472
+ )
473
+
474
+ def run_message(self, message: dict[str, Any]) -> dict[str, Any]:
475
+ """Runs one user Message JSON object synchronously."""
476
+ return self._run_call(
477
+ self._lib.kestrel_agent_run_message,
478
+ json.dumps(message).encode(),
479
+ )
480
+
481
+ def resume(self, retry_uncertain_tools: bool = False) -> dict[str, Any]:
482
+ """Resumes the session's interrupted run."""
483
+ error = ctypes.c_void_p()
484
+ pointer = self._lib.kestrel_agent_resume(
485
+ self._handle,
486
+ 1 if retry_uncertain_tools else 0,
487
+ ctypes.byref(error),
488
+ )
489
+ if not pointer:
490
+ raise KestrelError(self._take_error(error))
491
+ return json.loads(self._take_string(pointer))
492
+
493
+ def start_run(self, prompt: str) -> "Run":
494
+ """Starts a nonblocking run and returns a pollable Run handle."""
495
+ return self._start_run_call(
496
+ self._lib.kestrel_agent_start_run,
497
+ prompt.encode(),
498
+ )
499
+
500
+ def start_run_message(self, message: dict[str, Any]) -> "Run":
501
+ """Starts a nonblocking run from a Message JSON object."""
502
+ return self._start_run_call(
503
+ self._lib.kestrel_agent_start_run_message,
504
+ json.dumps(message).encode(),
505
+ )
506
+
507
+ def start_resume(self, retry_uncertain_tools: bool = False) -> "Run":
508
+ """Starts a nonblocking resume and returns a pollable Run handle."""
509
+ error = ctypes.c_void_p()
510
+ pointer = self._lib.kestrel_agent_start_resume(
511
+ self._handle,
512
+ 1 if retry_uncertain_tools else 0,
513
+ ctypes.byref(error),
514
+ )
515
+ if not pointer:
516
+ raise KestrelError(self._take_error(error))
517
+ run = Run(self, pointer)
518
+ self._runs.append(run)
519
+ return run
520
+
521
+ def cancel(self) -> None:
522
+ """Requests cancellation of the active run."""
523
+ if self._handle:
524
+ self._lib.kestrel_agent_cancel(self._handle)
525
+
526
+ def session(self) -> dict[str, Any]:
527
+ """Returns a session snapshot."""
528
+ error = ctypes.c_void_p()
529
+ pointer = self._lib.kestrel_agent_session_json(
530
+ self._handle,
531
+ ctypes.byref(error),
532
+ )
533
+ if not pointer:
534
+ raise KestrelError(self._take_error(error))
535
+ return json.loads(self._take_string(pointer))
536
+
537
+ def todos(self) -> Optional[list[dict[str, Any]]]:
538
+ """Returns todos, or None when todos are disabled for this agent."""
539
+ error = ctypes.c_void_p()
540
+ pointer = self._lib.kestrel_agent_todos_json(
541
+ self._handle,
542
+ ctypes.byref(error),
543
+ )
544
+ if not pointer:
545
+ if not error:
546
+ return None
547
+ raise KestrelError(self._take_error(error))
548
+ return json.loads(self._take_string(pointer))
549
+
550
+ def reset(self) -> None:
551
+ """Clears conversation history while keeping the session ID."""
552
+ error = ctypes.c_void_p()
553
+ status = self._lib.kestrel_agent_reset(
554
+ self._handle,
555
+ ctypes.byref(error),
556
+ )
557
+ if status != 0:
558
+ raise KestrelError(self._take_error(error))
559
+
560
+ def delete_session(self) -> None:
561
+ """Deletes the stored session and clears local history."""
562
+ error = ctypes.c_void_p()
563
+ status = self._lib.kestrel_agent_delete_session(
564
+ self._handle,
565
+ ctypes.byref(error),
566
+ )
567
+ if status != 0:
568
+ raise KestrelError(self._take_error(error))
569
+
570
+ def close(self) -> None:
571
+ """Frees the native agent. Do not call while a run is active."""
572
+ for run in list(self._runs):
573
+ try:
574
+ run.close()
575
+ except Exception:
576
+ pass
577
+ self._runs.clear()
578
+ if self._handle:
579
+ self._lib.kestrel_agent_free(self._handle)
580
+ self._handle = ctypes.c_void_p()
581
+ self._tool_callbacks.clear()
582
+ self._service_callbacks.clear()
583
+ self._event_callback = None
584
+ self._model_callback = None
585
+
586
+ def __enter__(self) -> "Agent":
587
+ return self
588
+
589
+ def __exit__(self, *_exc_info: Any) -> None:
590
+ self.close()
591
+
592
+ def _run_call(self, function: Any, payload: bytes) -> dict[str, Any]:
593
+ error = ctypes.c_void_p()
594
+ pointer = function(self._handle, payload, ctypes.byref(error))
595
+ if not pointer:
596
+ raise KestrelError(self._take_error(error))
597
+ return json.loads(self._take_string(pointer))
598
+
599
+ def _start_run_call(self, function: Any, payload: bytes) -> "Run":
600
+ error = ctypes.c_void_p()
601
+ pointer = function(self._handle, payload, ctypes.byref(error))
602
+ if not pointer:
603
+ raise KestrelError(self._take_error(error))
604
+ run = Run(self, pointer)
605
+ self._runs.append(run)
606
+ return run
607
+
608
+ def _model_proxy(
609
+ self,
610
+ model: Callable[[dict[str, Any]], dict[str, Any]],
611
+ ) -> Callable[[Any, bytes], int]:
612
+ def model_proxy(_user_data: Any, request_ptr: bytes) -> int:
613
+ request = json.loads(request_ptr.decode())
614
+ response = model(request)
615
+ return self._allocate_json(response)
616
+
617
+ return model_proxy
618
+
619
+ def _build_with_services(
620
+ self,
621
+ config_json: str,
622
+ model: Optional[Callable[[dict[str, Any]], dict[str, Any]]],
623
+ stream_model: Optional[
624
+ Callable[[dict[str, Any], Callable[[dict[str, Any]], None]], dict[str, Any]]
625
+ ],
626
+ session_store: Optional[Any],
627
+ memory: Optional[Any],
628
+ error: ctypes.c_void_p,
629
+ ) -> int:
630
+ if stream_model is not None:
631
+ self._model_callback = StreamingModelCallback(
632
+ self._streaming_model_proxy(stream_model)
633
+ )
634
+ builder = self._lib.kestrel_agent_builder_new_with_streaming_model(
635
+ config_json.encode(),
636
+ self._model_callback,
637
+ None,
638
+ ctypes.byref(error),
639
+ )
640
+ elif model is None:
641
+ self._model_callback = None
642
+ builder = self._lib.kestrel_agent_builder_new(
643
+ config_json.encode(),
644
+ ctypes.byref(error),
645
+ )
646
+ else:
647
+ self._model_callback = ModelCallback(self._model_proxy(model))
648
+ builder = self._lib.kestrel_agent_builder_new_with_model(
649
+ config_json.encode(),
650
+ self._model_callback,
651
+ None,
652
+ ctypes.byref(error),
653
+ )
654
+ if not builder:
655
+ raise KestrelError(self._take_error(error))
656
+
657
+ try:
658
+ if session_store is not None:
659
+ self._install_session_store(builder, session_store, error)
660
+ if memory is not None:
661
+ self._install_memory(builder, memory, error)
662
+ handle = self._lib.kestrel_agent_builder_build(
663
+ builder,
664
+ ctypes.byref(error),
665
+ )
666
+ finally:
667
+ self._lib.kestrel_agent_builder_free(builder)
668
+
669
+ if not handle:
670
+ raise KestrelError(self._take_error(error))
671
+ return handle
672
+
673
+ def _streaming_model_proxy(
674
+ self,
675
+ model: Callable[[dict[str, Any], Callable[[dict[str, Any]], None]], dict[str, Any]],
676
+ ) -> Callable[[Any, bytes, Any, Any, Any], int]:
677
+ def model_proxy(
678
+ _user_data: Any,
679
+ request_ptr: bytes,
680
+ emit: Any,
681
+ emit_ctx: Any,
682
+ error_ptr: Any,
683
+ ) -> int:
684
+ try:
685
+ request = json.loads(request_ptr.decode())
686
+
687
+ def emit_delta(delta: dict[str, Any]) -> None:
688
+ emit(emit_ctx, json.dumps(delta).encode())
689
+
690
+ return self._allocate_json(model(request, emit_delta))
691
+ except Exception as callback_error:
692
+ self._set_callback_error(error_ptr, callback_error)
693
+ return 0
694
+
695
+ return model_proxy
696
+
697
+ def _install_session_store(
698
+ self,
699
+ builder: int,
700
+ store: Any,
701
+ error: ctypes.c_void_p,
702
+ ) -> None:
703
+ load_method = getattr(store, "load")
704
+ save_method = getattr(store, "save")
705
+ delete_method = getattr(store, "delete", None)
706
+
707
+ def load_proxy(_user_data: Any, session_id: bytes, error_ptr: Any) -> int:
708
+ try:
709
+ session = load_method(session_id.decode())
710
+ return 0 if session is None else self._allocate_json(session)
711
+ except Exception as callback_error:
712
+ self._set_callback_error(error_ptr, callback_error)
713
+ return 0
714
+
715
+ def save_proxy(_user_data: Any, session_json: bytes, error_ptr: Any) -> int:
716
+ try:
717
+ save_method(json.loads(session_json.decode()))
718
+ return 0
719
+ except Exception as callback_error:
720
+ self._set_callback_error(error_ptr, callback_error)
721
+ return -1
722
+
723
+ load_callback = SessionLoadCallback(load_proxy)
724
+ save_callback = SessionSaveCallback(save_proxy)
725
+ callbacks: list[Any] = [load_callback, save_callback]
726
+ delete_callback = None
727
+ if delete_method is not None:
728
+ def delete_proxy(
729
+ _user_data: Any,
730
+ session_id: bytes,
731
+ error_ptr: Any,
732
+ ) -> int:
733
+ try:
734
+ delete_method(session_id.decode())
735
+ return 0
736
+ except Exception as callback_error:
737
+ self._set_callback_error(error_ptr, callback_error)
738
+ return -1
739
+
740
+ delete_callback = SessionDeleteCallback(delete_proxy)
741
+ callbacks.append(delete_callback)
742
+
743
+ status = self._lib.kestrel_agent_builder_set_session_store(
744
+ builder,
745
+ load_callback,
746
+ save_callback,
747
+ delete_callback,
748
+ None,
749
+ ctypes.byref(error),
750
+ )
751
+ if status != 0:
752
+ raise KestrelError(self._take_error(error))
753
+ self._service_callbacks.extend(callbacks)
754
+
755
+ def _install_memory(
756
+ self,
757
+ builder: int,
758
+ memory: Any,
759
+ error: ctypes.c_void_p,
760
+ ) -> None:
761
+ recall_method = getattr(memory, "recall")
762
+ remember_method = getattr(memory, "remember")
763
+
764
+ def recall_proxy(_user_data: Any, query_json: bytes, error_ptr: Any) -> int:
765
+ try:
766
+ entries = recall_method(json.loads(query_json.decode()))
767
+ return self._allocate_json(entries or [])
768
+ except Exception as callback_error:
769
+ self._set_callback_error(error_ptr, callback_error)
770
+ return 0
771
+
772
+ def remember_proxy(_user_data: Any, entry_json: bytes, error_ptr: Any) -> int:
773
+ try:
774
+ remember_method(json.loads(entry_json.decode()))
775
+ return 0
776
+ except Exception as callback_error:
777
+ self._set_callback_error(error_ptr, callback_error)
778
+ return -1
779
+
780
+ recall_callback = MemoryRecallCallback(recall_proxy)
781
+ remember_callback = MemoryRememberCallback(remember_proxy)
782
+ status = self._lib.kestrel_agent_builder_set_memory(
783
+ builder,
784
+ recall_callback,
785
+ remember_callback,
786
+ None,
787
+ ctypes.byref(error),
788
+ )
789
+ if status != 0:
790
+ raise KestrelError(self._take_error(error))
791
+ self._service_callbacks.extend([recall_callback, remember_callback])
792
+
793
+ def _allocate_json(self, value: Any) -> int:
794
+ encoded = json.dumps(value).encode()
795
+ return int(self._lib.kestrel_string_new(encoded) or 0)
796
+
797
+ def _set_callback_error(self, error_ptr: Any, error: Exception) -> None:
798
+ if error_ptr:
799
+ error_ptr[0] = self._lib.kestrel_string_new(str(error).encode())
800
+
801
+ def _take_string(self, pointer: int) -> str:
802
+ value = ctypes.string_at(pointer).decode()
803
+ self._lib.kestrel_string_free(pointer)
804
+ return value
805
+
806
+ def _take_error(self, error: ctypes.c_void_p) -> str:
807
+ if not error:
808
+ return "unknown Kestrel FFI error"
809
+ value = ctypes.string_at(error).decode()
810
+ self._lib.kestrel_string_free(error)
811
+ return value
812
+
813
+
814
+ class Run:
815
+ """Pollable handle for one asynchronous native run."""
816
+
817
+ def __init__(self, owner: Agent, handle: int) -> None:
818
+ self._owner: Optional[Agent] = owner
819
+ self._lib = owner._lib
820
+ self._handle = ctypes.c_void_p(handle)
821
+ self.ended = False
822
+
823
+ @property
824
+ def is_done(self) -> bool:
825
+ """Returns whether the native run has produced its final outcome."""
826
+ if not self._handle:
827
+ return True
828
+ return self._lib.kestrel_run_is_done(self._handle) == 1
829
+
830
+ def next_event(self, timeout_ms: int = -1) -> Optional[dict[str, Any]]:
831
+ """Returns the next event, None on timeout/end."""
832
+ self._require_handle()
833
+ event = ctypes.c_void_p()
834
+ error = ctypes.c_void_p()
835
+ status = self._lib.kestrel_run_next_event(
836
+ self._handle,
837
+ timeout_ms,
838
+ ctypes.byref(event),
839
+ ctypes.byref(error),
840
+ )
841
+ if status == 1:
842
+ return json.loads(self._owner._take_string(event))
843
+ if status == 0:
844
+ return None
845
+ if status == 2:
846
+ self.ended = True
847
+ return None
848
+ raise KestrelError(self._owner._take_error(error))
849
+
850
+ async def next_event_async(
851
+ self,
852
+ timeout_ms: int = -1,
853
+ ) -> Optional[dict[str, Any]]:
854
+ """Async wrapper around next_event."""
855
+ return await asyncio.to_thread(self.next_event, timeout_ms)
856
+
857
+ def wait(self, timeout_ms: int = -1) -> dict[str, Any]:
858
+ """Waits for the final AgentOutput JSON."""
859
+ self._require_handle()
860
+ output = ctypes.c_void_p()
861
+ error = ctypes.c_void_p()
862
+ status = self._lib.kestrel_run_wait(
863
+ self._handle,
864
+ timeout_ms,
865
+ ctypes.byref(output),
866
+ ctypes.byref(error),
867
+ )
868
+ if status == 1:
869
+ return json.loads(self._owner._take_string(output))
870
+ if status == 0:
871
+ raise TimeoutError("Kestrel run did not finish before timeout")
872
+ raise KestrelError(self._owner._take_error(error))
873
+
874
+ async def wait_async(self, timeout_ms: int = -1) -> dict[str, Any]:
875
+ """Async wrapper around wait."""
876
+ return await asyncio.to_thread(self.wait, timeout_ms)
877
+
878
+ def cancel(self) -> None:
879
+ """Requests cancellation without freeing the run handle."""
880
+ if self._handle:
881
+ self._lib.kestrel_run_cancel(self._handle)
882
+
883
+ def close(self) -> None:
884
+ """Cancels and frees the run, waiting for in-flight callbacks."""
885
+ if self._handle:
886
+ self._lib.kestrel_run_free(self._handle)
887
+ self._handle = ctypes.c_void_p()
888
+ self.ended = True
889
+ self._owner = None
890
+
891
+ def __enter__(self) -> "Run":
892
+ return self
893
+
894
+ def __exit__(self, *_exc_info: Any) -> None:
895
+ self.close()
896
+
897
+ def _require_handle(self) -> None:
898
+ if not self._handle or self._owner is None:
899
+ raise KestrelError("Kestrel run is closed")
Binary file
kestrelx/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
kestrelx/py.typed ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: kestrelx
3
+ Version: 0.0.1
4
+ Summary: Scenario-agnostic agent core for Python, backed by Rust
5
+ Keywords: agents,llm,openai,anthropic,gemini,rust
6
+ Classifier: Development Status :: 3 - Alpha
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3 :: Only
9
+ Classifier: Programming Language :: Rust
10
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ Provides-Extra: dev
14
+ Requires-Dist: build>=1.2; extra == "dev"
15
+ Requires-Dist: twine>=5; extra == "dev"
16
+
17
+ # Kestrel Agent Core for Python
18
+
19
+ Kestrel is a scenario-agnostic agent runtime with a Rust core and a Python
20
+ `ctypes` binding. Published platform wheels include the native library.
21
+
22
+ ```bash
23
+ pip install kestrelx
24
+ ```
25
+
26
+ ```python
27
+ from kestrelx import Agent
28
+
29
+ with Agent({
30
+ "provider": {
31
+ "kind": "anthropic",
32
+ "model": "claude-sonnet-4-5",
33
+ },
34
+ }) as agent:
35
+ print(agent.run("Hello")["text"])
36
+ ```
37
+
38
+ The distribution name and import name are both `kestrelx`.
39
+
40
+ ## Development install
41
+
42
+ From a source checkout, build the native library and put the Python package on
43
+ `PYTHONPATH`:
44
+
45
+ ```bash
46
+ cargo build -p kestrel-ffi
47
+ PYTHONPATH=bindings/python python3 bindings/python/example.py
48
+ ```
49
+
50
+ Set `KESTREL_FFI_PATH` to load a shared library outside the package or workspace
51
+ `target/` directory.
52
+
53
+ The basic example uses a Python model callback and a Python echo tool, so it
54
+ runs offline. For a built-in provider:
55
+
56
+ ```python
57
+ from kestrelx import Agent
58
+
59
+ with Agent({
60
+ "system_prompt": "Be concise.",
61
+ "streaming": True,
62
+ "provider": {"kind": "openai_chat", "model": "gpt-4.1-mini"},
63
+ }) as agent:
64
+ agent.set_event_handler(lambda event: print(event))
65
+ output = agent.run("Hello")
66
+ print(output["text"])
67
+ ```
68
+
69
+ `provider.kind` accepts `openai_chat`, `openai_responses`, `anthropic`, or
70
+ `gemini`. The legacy `openai` section remains supported.
71
+
72
+ The native run is blocking. In an async Python application, call it through
73
+ `asyncio.to_thread` or your framework's equivalent worker mechanism.
74
+
75
+ For native asyncio integration, prefer the nonblocking run handle:
76
+
77
+ ```python
78
+ run = agent.start_run("Hello")
79
+ event = await run.next_event_async(1000)
80
+ output = await run.wait_async()
81
+ run.close()
82
+ ```
83
+
84
+ `Agent.close()` and `Run.close()` wait for active runs and in-flight native
85
+ callbacks. Do not call them from inside an event/tool/model callback; in async
86
+ code, move blocking close/wait operations to `asyncio.to_thread`.
87
+
88
+ `Agent(..., session_store=..., memory=...)` installs host-backed persistence.
89
+ Objects follow the same protocols as the Rust traits:
90
+
91
+ - session store: `load(id) -> dict | None`, `save(session)`, optional `delete(id)`
92
+ - memory: `recall(query) -> list[dict]`, `remember(entry)`
93
+
94
+ Memory queries include `categories`, and entries may include
95
+ `category: {"name": "project", "owner_id": "..."}`.
96
+
97
+ Use `agent.reset()` to clear history while preserving the session ID, or
98
+ `agent.delete_session()` to remove the stored session as well.
99
+
100
+ `agent.resume()` continues an interrupted run. `agent.start_resume()` returns
101
+ the same pollable `Run` handle as `start_run()`. Pass
102
+ `retry_uncertain_tools=True` only when re-running an interrupted tool is safe.
103
+
104
+ See `example_persistence.py` for an in-memory database example.
105
+
106
+ Contract helpers mirror the C ABI:
107
+
108
+ ```python
109
+ import kestrelx as kestrel
110
+
111
+ kestrel.contract_version() # 1
112
+ kestrel.capabilities() # capability names
113
+ kestrel.validate_config(config, has_custom_model=True)
114
+ ```
115
+
116
+ Custom Python models can stream tokens by accepting an `emit` function:
117
+
118
+ ```python
119
+ def stream_model(request, emit):
120
+ emit({"type": "text", "text": "hello "})
121
+ emit({"type": "text", "text": "world"})
122
+ return {...} # complete ModelResponse
123
+
124
+ Agent(config, stream_model=stream_model)
125
+ ```
@@ -0,0 +1,8 @@
1
+ kestrelx/__init__.py,sha256=eKqjgb2htAReST5pGxVDNXjlQHqtLHR499cDnZ3Rpnw,32467
2
+ kestrelx/_version.py,sha256=ry5O5SW74ugwOUMKSV2_LbWjYa8B0IEvUm7S-lHPA2c,23
3
+ kestrelx/py.typed,sha256=frcCV1k9oG9oKj3dpUqdJg1PxRT2RSN_XKdLCPjaYaY,2
4
+ kestrelx/_native/kestrel_ffi.dll,sha256=J20WQeg3Ojby2G6qK3mV0wtwe6EESe0QcpYz0mcQFz4,7250432
5
+ kestrelx-0.0.1.dist-info/METADATA,sha256=RJ0B2kNxgc-v-8wEZlCDJ0cZOoJ2SPkFcEccUtssiW4,3969
6
+ kestrelx-0.0.1.dist-info/WHEEL,sha256=79BCzrXBJOa2YV6ugKrK59dqWifMGjAkgVd_6AQrqbU,98
7
+ kestrelx-0.0.1.dist-info/top_level.txt,sha256=oVWE9puGOdAWH46S1wQiuU1B-wfTJGhTP5Qec1OnAf0,9
8
+ kestrelx-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-win_amd64
5
+
@@ -0,0 +1 @@
1
+ kestrelx