Metadata-Version: 2.4
Name: tai42-kit
Version: 22.0.0
Summary: Generic leaf helpers, settings primitives, pooled clients, and LLM/AI factories for the TAI ecosystem.
Author-email: tai42 <oss@tai42.ai>
License-Expression: Apache-2.0
Project-URL: Homepage, https://tai42.ai
Project-URL: Repository, https://github.com/tai42ai/tai42/tree/main/core/kit
Project-URL: Issues, https://github.com/tai42ai/tai42/issues
Project-URL: Changelog, https://github.com/tai42ai/tai42/blob/main/core/kit/CHANGELOG.md
Keywords: llm,langchain,langgraph,mcp,utilities,settings
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Typing :: Typed
Requires-Python: >=3.13
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: tai42-contract<32,>=31.0
Requires-Dist: pydantic>=2.12
Requires-Dist: pydantic-settings>=2.15.0
Requires-Dist: python-dotenv>=1.0
Requires-Dist: fastmcp<4,>=3.4.7
Requires-Dist: mcp>=1
Requires-Dist: anyio>=4
Requires-Dist: httpx>=0.28
Requires-Dist: httpcore>=1
Requires-Dist: ruamel.yaml>=0.18
Requires-Dist: PyYAML>=6
Requires-Dist: jsonschema>=4.19.2
Requires-Dist: referencing>=0.32.0
Requires-Dist: jsonschema-specifications>=2023.03.6
Requires-Dist: prometheus-client>=0.24
Requires-Dist: makefun~=1.16.0
Requires-Dist: click>=8
Requires-Dist: pebble<6,>=5.2.3
Provides-Extra: llm
Requires-Dist: langchain<2,>=1.2; extra == "llm"
Requires-Dist: langchain-core<2,>=1.2; extra == "llm"
Requires-Dist: langchain-openai>=1.6.7; extra == "llm"
Requires-Dist: langgraph<2,>=1.2.12; extra == "llm"
Requires-Dist: langgraph-checkpoint>=4.2.0; extra == "llm"
Requires-Dist: langgraph-checkpoint-redis<0.6,>=0.5.2; extra == "llm"
Requires-Dist: redis>=5; extra == "llm"
Requires-Dist: redisvl<1,>=0.15.0; extra == "llm"
Requires-Dist: orjson<4,>=3.11; extra == "llm"
Provides-Extra: jq
Requires-Dist: jq>=1.10; extra == "jq"
Requires-Dist: orjson>=3.11; extra == "jq"
Provides-Extra: uvicorn
Requires-Dist: uvicorn>=0.52.4; extra == "uvicorn"
Provides-Extra: anthropic
Requires-Dist: tai42-kit[llm]; extra == "anthropic"
Requires-Dist: langchain-anthropic>=1.7.5; extra == "anthropic"
Provides-Extra: mistral
Requires-Dist: tai42-kit[llm]; extra == "mistral"
Requires-Dist: langchain-mistralai>=1.1; extra == "mistral"
Provides-Extra: google
Requires-Dist: tai42-kit[llm]; extra == "google"
Requires-Dist: langchain-google-genai>=4.4.0; extra == "google"
Provides-Extra: xai
Requires-Dist: tai42-kit[llm]; extra == "xai"
Requires-Dist: langchain-xai>=1.2; extra == "xai"
Provides-Extra: ollama
Requires-Dist: tai42-kit[llm]; extra == "ollama"
Requires-Dist: langchain-ollama>=1.0; extra == "ollama"
Provides-Extra: huggingface
Requires-Dist: tai42-kit[llm]; extra == "huggingface"
Requires-Dist: langchain-huggingface>=1.2.3; extra == "huggingface"
Requires-Dist: sentence-transformers>=5.3; extra == "huggingface"
Provides-Extra: typesafe
Requires-Dist: tai42-kit[llm]; extra == "typesafe"
Requires-Dist: langchain-typesafe<0.1,>=0.0.1a3; extra == "typesafe"
Provides-Extra: langgraph-checkpoint-postgres
Requires-Dist: tai42-kit[llm]; extra == "langgraph-checkpoint-postgres"
Requires-Dist: langgraph-checkpoint-postgres>=3.0.5; extra == "langgraph-checkpoint-postgres"
Requires-Dist: psycopg[pool]>=3.3.7; extra == "langgraph-checkpoint-postgres"
Requires-Dist: orjson<4,>=3.11.8; extra == "langgraph-checkpoint-postgres"
Provides-Extra: langgraph-checkpoint-sqlite
Requires-Dist: tai42-kit[llm]; extra == "langgraph-checkpoint-sqlite"
Requires-Dist: langgraph-checkpoint-sqlite>=3.0.3; extra == "langgraph-checkpoint-sqlite"
Requires-Dist: aiosqlite>=0.20; extra == "langgraph-checkpoint-sqlite"
Provides-Extra: monitoring
Requires-Dist: opentelemetry-api<2,>=1.45.1; extra == "monitoring"
Requires-Dist: opentelemetry-sdk<2,>=1.44; extra == "monitoring"
Requires-Dist: opentelemetry-exporter-otlp-proto-http<2,>=1.44; extra == "monitoring"
Requires-Dist: orjson>=3.11; extra == "monitoring"
Provides-Extra: redis
Requires-Dist: redis>=5; extra == "redis"
Provides-Extra: curl
Requires-Dist: curl-cffi>=0.16.3; extra == "curl"
Provides-Extra: postgres
Requires-Dist: psycopg[binary,pool]>=3.3.7; extra == "postgres"
Requires-Dist: orjson<4,>=3.11.8; extra == "postgres"
Provides-Extra: jwt
Requires-Dist: joserfc>=1.7.5; extra == "jwt"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-asyncio>=1.4; extra == "dev"
Requires-Dist: pytest-cov>=5; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: pyright>=1.1.389; extra == "dev"
Requires-Dist: joserfc>=1.7.5; extra == "dev"
Requires-Dist: fakeredis[lua]>=2.21; extra == "dev"
Requires-Dist: redis>=5; extra == "dev"
Requires-Dist: numpy>=2; extra == "dev"
Requires-Dist: uvloop>=0.22; sys_platform != "win32" and extra == "dev"
Requires-Dist: gevent~=26.8.0; extra == "dev"
Requires-Dist: eventlet~=0.41.3; extra == "dev"
Dynamic: license-file

# tai42-kit

[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)

Generic leaf helpers, settings primitives, pooled clients, and LLM/AI factories
for the TAI ecosystem. It provides the reusable building blocks the server is
composed from: data and text transforms, LangChain/FastMCP/MCP tool glue, the
pooled-client facade and concrete drivers (`redis`, `curl`, `mcp`, `postgres`,
`http`), the SSRF URL guard and safe download, MCP client transports over a UDS
socket, the settings machinery, LLM/embedding factories with checkpoint/store
backends, logging setup, and the backend liveness file with its
`tai42-backend-probe` console script. Heavier backends are gated behind extras and
imported lazily. Typed package (`py.typed`).

## Position in the ecosystem

TAI is an open-source runtime for MCP tools, agents, and workflows — the server
that hosts a capability and supplies the operational layer around it (manifest
loading, access control, OAuth connectors, background execution, monitoring,
storage, and human-in-the-loop steps).

Four packages; each depends only on the ones to its left:

```
                     tai42-kit  <--.
                   /  (helpers)     \
tai42-contract  <-+                  +--  tai42-skeleton
  (interfaces)     \                /    (the server)
                     tai42-cli  <--'
               (the remote client)
```

`tai42-kit` obeys the leaf rule: its only tai-* dependency is `tai42-contract`. It
implements the contract's `BaseClient` Protocol and consumes its manifest types;
among tai-* packages it depends on nothing else.

## Install

Requires **Python 3.13+**. Install from PyPI into the environment that runs the
server:

```bash
uv add tai42-kit
```

Or from source — clone this repo and add it as an editable dependency; the
`tai42-*` dependencies resolve in-tree from the workspace.

```bash
git clone https://github.com/tai42ai/tai42   # next to your app checkout
cd /path/to/your/app
uv add --editable ../tai42/core/kit
```

Backends are gated behind extras, so install the ones you need — e.g. the
pooled-client drivers `tai42-kit[redis]`, `tai42-kit[postgres]`, `tai42-kit[curl]`, the
checkpoint/store backends `tai42-kit[langgraph-checkpoint-postgres]`,
`tai42-kit[langgraph-checkpoint-sqlite]`, and LLM-provider backends like
`tai42-kit[anthropic]`, `tai42-kit[google]`, `tai42-kit[mistral]`, `tai42-kit[xai]`,
`tai42-kit[ollama]`, `tai42-kit[huggingface]`.

## Loop-bound resources

The kit keeps its pooled clients and its long-lived async resources (checkpoint
savers, stores) per event loop and per client epoch. `tai42_kit.loop_bound` holds
the registry machinery behind the resources (`ResourceRegistry`,
`LoopRegistryMap`) and the two closes. `release_loop_bound_resources()` is
awaited on the loop by whatever ends the kit's use of it: a loop's end, or an
application's shutdown on a loop that lives on. It closes every epoch's registries
for the loop, then its pooled clients, running each step even when the other fails
and raising every failure. On a loop that lives on, the next lease builds its pool
or registry anew and the next release closes it. `PrivateLoop.close()` marks its
loop closing before it releases (`tai42_kit.loop_closing`): from then on a new
lease of a pooled client, a registry or a registry's resource on that loop raises
a `RuntimeError` naming the loop as closing, as a closed connection pool refuses a
new connection, so nothing is opened that no release would close. A lease held
from before keeps working until it is released, and every other loop leases as
before. A loop that is not marked (one `asyncio.run` ends) refuses nothing: a lease
made on it after its last release opens a resource that stays open, so the code
that ends such a loop leases nothing after that release.
`close_retired_registries(epoch)` closes one retired epoch's registries on the
running loop (the current epoch is refused); the retire of a serving generation
calls it once that generation's work has drained or its drain budget has run out.

A backend whose pool gives each running job an OS thread with no loop running on
it runs the job's coroutine on `tai42_kit.backend.PrivateLoop`, a loop the job's
thread runs itself, one job at a time; the backend makes one per job or keeps one
for job after job. While a job runs, the loop is its thread's current event loop,
and the thread has none after, as with `asyncio.Runner`. An exception raised into
the loop by none of its tasks (a pool's time limit from a signal handler) cancels
the job's task and runs it to its end, its cleanup included, before the job raises
it. The loop's `close()` first marks the loop closing, then releases the
loop-bound resources on it, while the tasks left on it are still alive (a pool whose close awaits its own workers finds
them running), then cancels the tasks on it and runs them to their end, round
after round until none is left (a task one's cleanup starts, one the release left,
work a thread hands the loop), closes the async generators left on it, ends the
tasks their close made, and closes it. A task that leases a pooled client or a
registry once the close has begun gets the closing error, and the close logs it
at ERROR when the task ends with it, as it logs every error a task ends with then.
Its default executor is shut down without waiting for its threads, so a job that
awaited a thread is not held by it once the exception that ends the job has
reached the loop; the thread ends on its own. When that exception reaches a loop
waiting for a thread is the pool's to say: a signal handler's interrupts the wait
at once, while one raised into the job's thread from another thread lands only
once the loop runs Python code again.

A backend whose pool runs its jobs as green threads of the host's OS thread
cannot give a job a loop of its own, since asyncio runs one loop per OS thread:
`tai42_kit.backend.SharedLoop` hands each job's coroutine to the host's running
loop and waits for its result, and the resources bound to that loop stay the
host's, released at its end.

## Backend task branches

`tai42_kit.backend.register_task_branches` registers the three BACKEND tool
extensions every backend offers: `<tool>_sync_task` queues the call and waits for
its result, `<tool>_async_task` queues it and replies with the job's id, and
`<tool>_schedule_task` writes a recurring schedule firing the tool. A backend
supplies only its seams: the contract's `TaskDoor`, which queues a job and waits on
it, and its `ScheduleWriter`, which stores a schedule and says whether it honours a
relative interval. The task options every backend takes are
`tai42_kit.backend.BACKEND_TASK_OPTS` (`countdown`, `eta`, `expires`, `queue`,
`callback_kwargs`); a door adds its own through `task_opts`. A `queue` value is a
label (`tai42_kit.backend.check_queue_label`: letters, digits, `_` and `-`), and the
backend sends the job to `derived_queue(<its queue name>, label)`, its queue name
followed by `.<label>`. A sync wait that runs out raises `TimeoutError` naming the
job, which may still be running; a failed job raises its failure as the backend
retains it.

## Backend tool surface

Every backend offers the same `backend_*` tools (`tai42_kit.backend.BACKEND_TOOLS`),
each with one argument list on every backend. The schedule tools also give one reply
shape on every backend; the task and worker views reply with what the backend reports.
`tai42_kit.backend.register_schedule_tools` registers the ten schedule tools
(`SCHEDULE_TOOLS`: list, get, update, enable, disable, run now, exists, delete,
export, import) over the backend's `ScheduleStore`, and
`register_inspection_tools` registers the twelve task and worker tools
(`INSPECTION_TOOLS`) over its worker inspection, a subclass of
`tai42_kit.backend.BackendInspection`. A backend passes its package name
(`__name__`) as `module`: the tools are registered as tools of that package,
tagged `backend`.

What a backend cannot serve is still registered and raises
`tai42_kit.backend.UnsupportedBackendTool` (a `NotImplementedError`) naming the
backend and the tool: each view `BackendInspection` keeps refuses, a
`worker_name` on a backend whose inspection does not set `addresses_workers`, a
`backend_cancel_task(terminate=True)` on one that does not set `terminates`, a
`backend_cancel_task(terminate=True)` for a task whose worker cannot stop it (the
backend raises it from the worker's own answer), a `backend_cancel_task` without `terminate` for a running task on one that cannot
cancel a running task without stopping it, and a
`backend_disable_schedule` on a store that holds no disabled schedule
(`holds_disabled`), whose `backend_enable_schedule` writes nothing. A schedule
status reply is `{"status", "name"}`. `tai42_kit.backend.check_tool_surface`
certifies a backend's registered tools against the surface.

## Backend liveness

`tai42_kit.liveness` holds the file a backend loop process reports its progress
into (`LivenessFile`), its `TAI_BACKEND_LIVENESS_` settings (`PATH`, `INTERVAL`,
`GRACE`), and the reading of it (`check_liveness`). Each report writes the
process's pid and a horizon: the seconds within which the next pass is
promised, the report's own promise plus `INTERVAL`. The file is rewritten only
when the promise already in it would expire before the next pass, so a steady
loop writes about once per `INTERVAL`. A file holding the pid of another live
process is refused: each process needs its own path. Of two processes claiming
one file at once, the second is refused. A process removes its file when it
exits (a file left by a process that no longer exists is removed too), and a
report after that removal raises instead of writing the file again.

The `tai42-backend-probe` console script reads the file at
`TAI_BACKEND_LIVENESS_PATH` and prints one line: it exits 0 while the file's age
is at most its horizon plus the grace (`--grace`, default
`TAI_BACKEND_LIVENESS_GRACE`), and 1 when the file is stale or missing, so it
serves as an orchestrator's exec liveness probe.

## Compute pool

`tai42_kit.compute` runs CPU-bound work in worker processes, so a job that holds
the interpreter lock for seconds leaves the caller's event loop serving every
other request. `compute_pool()` returns what runs the process's jobs, by the
kind of process, the first of these that applies:

- a process forked, at any remove, from one that shares its pool or from one
  whose pool host had started and was not stopped by it: that pool or host,
  which it never stops or replaces;
- a process started through a process prelude (`TAI_PROCESS_PRELUDE` names
  one), or forked at any remove from one: a pool host of its own, which its
  first job starts;
- any other process: its own `ComputePool`, started on the first call, or on
  the first job of a child it shares the pool with.

`stop_compute_pool()` ends the process's own pool, or the pool host it started
(the skeleton's lifespan does this at shutdown). A process that forks children
which run compute jobs calls `share_compute_pool()` first: each child that keeps
the descriptors it inherited then runs its jobs in the parent's pool (or, when
the parent itself reaches another process's pool, in that one), under the
same timeout and cancellation, and starts no workers of its own. What a job
raises reaches the child as itself; a pool error (`TimeoutError`,
`ComputeWorkerLostError`, `ComputePoolUnavailableError`) reaches it without its
cause. A child that closed its inherited descriptors, or whose pool's process ended or
stopped serving, gets `ComputePoolUnavailableError` on a job. The backend fork
safety, `tai42_kit.backend.fork_safety.guard_forks`, shares in a process whose
threads are OS threads; in a process started through a process prelude, or
forked at any remove from one, `share_compute_pool()` changes nothing: the list above says where its
children's jobs run.
`share_compute_pool()` raises `ComputePoolUnavailableError` where it cannot
start serving (a process at its descriptor limit, or a serving thread that
cannot start or run a loop of its own).

A pool runs only in a process whose threads are OS threads: its threads wait on
its workers, which a process a prelude reshaped does not let them do, so
`ComputePool.start()` there raises `ComputePoolUnavailableError`. Such a process
runs its jobs in a pool host instead: a fresh interpreter, started with the
process's interpreter flags, its environment less `TAI_PROCESS_PRELUDE` and its
module search path, that runs a pool of its own (sized by `COMPUTE_WORKERS`) and
serves the process's jobs over a socket pair, with the same timeout,
cancellation and errors as a shared parent's pool. The first job pays the host's
start (about a second, once per host) and every job one socket hop (under a
millisecond); a process that runs no compute job starts no host. The host ends
when the process stops it, and when the process and every forked descendant of
it that holds the host's end ended, however they ended: its pool's workers end with it. A host that ended fails the
jobs sent to it that had not returned with `ComputePoolUnavailableError`; the
next job starts a fresh host and logs the warning "compute pool host replaced
after it ended". A child forked from the process once its host had started, and before the
process stopped it, keeps reaching that host, and its jobs raise `ComputePoolUnavailableError` once that
host ended; a child forked while the host starts holds none of its sockets (but for an end numbered at or
above a soft descriptor limit lowered below it, which a process prelude that puts off a watched
socket's close keeps in the child until its event loop runs). A
job the serving process (a pool host, or a sharing parent) could not take
because it has no file descriptor free raises `ComputePoolUnavailableError` in
its caller alone; the serving process logs it and keeps serving its other jobs.

`await compute_pool().run(fn, *args,
timeout=...)` runs `fn(*args)` in a worker started with `spawn`: `fn` is a
module-level function and its arguments and result are picklable. The worker
imports `fn`'s module afresh in a process with no app bound, so that module must
import without touching `tai42_app`: no `@tai42_app.tools.tool` registration
beside the job and no module-level `tai42_app.settings` read. A job from a
module that does fails in the worker, and that import error is raised in the
caller like any exception the job raises. The job's own exception is raised in
the caller as itself, with the worker's traceback chained as its cause
(`WorkerTraceback`); an exception that cannot be rebuilt in the caller raises
`ComputeJobFailedError`, which carries its type and message, with the same
cause. Past `timeout` (seconds, counted from the moment a worker takes the job
up) the worker is terminated at once and replaced, and the caller gets
`TimeoutError`; nothing the job itself started (a process, a file) is cleaned
up. Cancelling the caller terminates the worker the same way. The timeout is
kept by the process that runs the pool: when that process is killed, a worker
runs its job to the end before it ends. A pool that is not
started, was stopped or broke raises `ComputePoolUnavailableError`, and a worker
that ends mid-job raises `ComputeWorkerLostError`; both classify as an
unavailable platform transport (`ErrorKind.UNAVAILABLE`, `is_transport_error`
true), and a job never falls back to running on the caller's loop. When the pool
breaks because an idle worker died (for example, killed by the out-of-memory
killer), the next `compute_pool()` call, or the next job of a child the pool is
shared with, stops it, starts a fresh pool and logs
the warning "compute pool replaced after its workers died"; a job that was
running in the broken pool still raises `ComputePoolUnavailableError`. A forked
child's inherited pool state is reset, and the list above picks again. A
pool still running when its process exits is stopped by that exit.

`COMPUTE_WORKERS` (default `2`, at least `1`) sizes each pool; a job
waits for a free worker when every worker is busy. A plugin reaches the pool
through the app as `tai42_app.compute.run(fn, *args, timeout=...)`.

## Development

```bash
uv venv --python 3.13
uv pip install --no-sources --editable ".[dev,llm,jq,uvicorn,redis,curl,postgres]"
uv run --no-sync ruff check .
uv run --no-sync ruff format --check .
uv run --no-sync pyright       # 0 errors; missing optional ML backends report as warnings
uv run --no-sync pytest --cov --cov-report=term-missing        # optional-extra tests skip if their extra is absent
```

See `CONTRIBUTING.md` for the rules.

## Documentation

The whole platform — concepts, guides, and the generated reference — lives in
the unified documentation site:

- Layering & the contract/kit/cli/skeleton split: https://docs.tai42.ai/concepts/layering
- Python SDK reference (this package's public API): https://docs.tai42.ai/reference/python-sdk

## License

Apache-2.0. See `LICENSE` and `NOTICE`.
