Skip to main content Switch to mobile version prism-ai-harness 0.5.4 Durable agent sessions for Python — threads, session state and store drivers.
pip install prism-ai-harness==0.5.4 Copy PIP instructions
Durable agent sessions — threads, session state and store drivers. The Python port of particle-academy/prism-harness.
Zero runtime dependencies. Python 3.10+.
pip install prism-ai-harness from prism_harness import FileSessionStore, MemorySessionStore, Participant, PrismHarness harness = PrismHarness( drivers={ "memory": MemorySessionStore, "files": lambda: FileSessionStore("./storage/harness"), }, stores={"ephemeral": "memory", "durable": "files"}, ) session = harness.for_(Participant("User", 7)).session("support") session.using_mode("plan").using_model("claude-sonnet-4-5") def advance(live): live.begin_run("run-1", "plan", "anthropic", "claude-sonnet-4-5") session.lock(advance) # whatever must not happen twice for is a Python keyword, so the method is for_ — forced rather than chosen, like Media.as_ in prism-ai-core.
Choose a stable id in trusted application code, using [a-z][a-z0-9_-]{0,63}. Calls without an agent keep their existing addresses. Named agents have separate tools, providers, modes, session state, threads and default task lists.
from prism_harness import AgentRuntime, LlmResponse, ModeRegistry, ToolRegistry class Lookup: name = "lookup" def handle(self, args: dict[str, object]) -> str: return "found" tools, modes = ToolRegistry(), ModeRegistry() tools.for_agent("support").register(Lookup(), "app.support") modes.for_agent("support").register("reply", {"tools": ["lookup"]}, "app.support").set_default( "reply" ) runtime = AgentRuntime( client=lambda _: LlmResponse(text="done", finish_reason="stop"), tools=tools, modes=modes, ) # Replace the synthetic client when connecting a model. session = harness.for_agent("support").for_(Participant("User", 7)).session("case:42") descriptors = runtime.effective_tools(session, "reply") A harness constructed with runtime also offers for_agent(...).effective_tools(mode, participant, scope). The descriptors contain name, owner and source from the model offer resolver. Inspection creates no session, thread or index entry, invokes no handler and makes no model/provider request or logical state change. Reads may physically purge expired entries, exactly as an ordinary store read does. Explicit state writes during resolution refuse.
The mode list is the ceiling for named and legacy sessions. Caller-supplied names narrow it; omitting names uses the mode's full list, and an explicit empty list offers no tools. A requested * selects the mode's ceiling. Other names outside it fail before the model is called.
Legacy callers that intentionally need the previous replacement behavior can set AgentRuntime(..., allow_legacy_tool_list_widening=True). This permits widening only in the legacy namespace; the configured authorizer still filters the offer and tool calls. This opt-out also preserves the old empty-list fallback. Named agents always retain their ceiling. Remove an old explicit narrow_requested_tools=False: it now raises a migration error. Explicit True remains supported, and conflicts with the widening opt-out. Named agents inherit no legacy authority. Builtins require explicit registration and mode selection. A named-agent repeated registration fails even for the same owner; replace(replacement, predecessor_owner, owner) makes intended replacement explicit. Mode replacement likewise names its predecessor.
Legacy registries retain duplicate overwrite and existing cross-kind precedence. Use ToolRegistry(refuse_duplicates=True) and ModeRegistry(..., refuse_duplicates=True) to refuse legacy duplicates. Named session addresses are immutable and validated; legacy participant/scope values retain their existing mutable behavior.
AgentRuntime's agents map supports provider/model, max_steps_ceiling, max_output_tokens_per_call and lock_ttl/lock_wait. Unset scalars use config's fallback; explicit None clears nullable defaults. Caps narrow the existing RunContext ledger and output budget. ToolAuthorizer's agents map supplies enabled/offer/call overrides with invocation-time rechecks. PrismHarness's agents map separately controls ttl_seconds, default_scope and default_task_list. ParticipantRef requires a registered ParticipantAdapters actor resolver; child construction retains its parent's bound actor. Plain Participant values continue to work.
A server handles a request and moves on, so a session cannot be an object kept in memory the way a single-process agent's is. Every call rebuilds one from a store, which is what makes a fresh worker see the same mode, model and conversation as the request that set them.
A store that reports itself volatile is REFUSED for the durable slot, at the moment a session is opened. That is the guard the package exists for: a cache is disposable by definition, and the durable slot holds approvals a human has not answered yet.
Construct a PrismHarness with no drivers and it works — and then refuses durable state, loudly, with a message that names the fix. A package that silently accepted an in-memory durable store would pass every test in one process and lose a half-executed action the first time it ran on two.
Session.key() is byte for byte what the reference builds: session: plus the sha1 of the participant type truncated to 12, the participant id, and the scope. Matching exactly is what lets a PHP app and a Python agent share one store and resolve the same session.
record() assigns positions inside the store lock, reading the current length and writing the new messages as one operation. Two turns landing concurrently would otherwise both read position 4 and both write position 5, silently losing a message — the race the reference tracks as prism-harness#2.
A turn can carry media alongside its prompt:
from prism import Image runtime.send( session, "What is wrong with this layout?", additional_content=[Image.from_base64(screenshot, "image/png")], ) Pass prism-ai-core media objects or media already serialized. Attachments are stored with the turn in the shape UserMessage.from_dict() rebuilds. Each one must be an image, document, audio or video that carries its bytes, a provider file id or document chunks. The same rules as the PHP reference and the TypeScript port apply, pinned across all three by prism-parity's harness-turn-attachments corpus.
Refused, with a HarnessError whose code names the problem:
A refusal happens before a run starts: no run, no events, nothing in the thread.
A mode can declare provider_options. They reach your model client unchanged, as request.provider_options, on every step of every run in that mode:
from prism_harness import ModeRegistry ModeRegistry({"modes": {"overseer": {"provider_options": {"thinking": {"type": "adaptive"}}}}}) A value that is not a map is refused when the mode is resolved, with mode_malformed.
What your model client receives
request.messages is the thread, oldest first, in the shape the PHP reference stores Prism's messages:
Consecutive tool result rows reach the client as one, so each call's result is sent to the provider once. Return a call's provider ids on LlmToolCall (result_id, reasoning_id, reasoning_summary), and provider state for the turn as LlmResponse.additional_content: they are recorded and come back in messages.
When the answer is a document rather than prose, hand the turn a schema:
schema = { "name": "plan", "type": "object", "properties": { "title": {"type": "string"}, "steps": {"type": "array", "items": {"type": "string"}}, }, "required": ["title", "steps"], } response = runtime.send_structured(session, "Plan the release", schema) response.structured # {"title": "Ship it", "steps": ["write", "test"]} response.text # the document as the model wrote it Check finish_reason before reading structured. A structured turn that stops before the model answers, because it is waiting for a person ("awaiting_approval", with pending_approvals) or because it is out of steps ("budget_exhausted", with stopped_because), returns a StructuredAgentResponse whose structured is None. That is not an answer of "nothing": record the decisions and resume with send_structured again.
response = runtime.send_structured(session, brief, schema) if response.finish_reason == "awaiting_approval": ... # decide response.pending_approvals, then resume elif response.structured is None: ... # stopped early: response.stopped_because says why else: plan = response.structured It is the same run as send() — the mode's system prompt, its tools, the step budget, the events — asking the provider for structured output. Your client receives the schema as request.schema and returns what it parsed as LlmResponse.structured; with prism-ai-core that is Prism.structured().with_schema() and the response's structured.
The thread keeps the text, with the parsed object beside it. The assistant message is the raw document, and structured rides along in the row's additional_content. A later turn replays the conversation as messages and reads the text, so a thread that contains a structured answer reads like any other.
A document that misses the schema is refused, not repaired.
The check reads the schema's own JSON Schema, so a hand-written schema is held to the same terms. schema_problems() is exported if you want it directly. It checks declared types, required keys, enum members, array items, and — where a schema closes itself — keys nobody declared. It does not read $ref, allOf, oneOf or the numeric and string facets; what it cannot read, it passes, rather than reporting a constraint it did not actually check. The same rules as the PHP reference, message for message, so a document refused in one language is refused in the other for the same stated reason. True is not a number here, and a whole float reads as the integer JSON writes: both are ways Python alone would have answered differently.
A client response with finish_reason="error" or "unknown" ends the run with HarnessError.code == "model_step_failed". Its finish_reason identifies which of those two finishes occurred; the error message contains no model output. The step, cost, and assistant response are recorded before the error is raised. Tools requested by that response are refused, with no pending approval authority, so approving or resuming later cannot execute them. A new turn can still be sent.
A mode names the tools a person must approve:
ModeRegistry( { "modes": { "guarded": { "system_prompt": "...", "tools": ["read", "delete"], "requires_approval": ["delete"], } } } ) A step that calls one stops with finish_reason == "awaiting_approval". The calls that need nobody have already run. Record a decision for every pending approval, then resume with an empty prompt:
from prism_harness import record_approval response = runtime.send(session, "Clean up the failed run") if response.finish_reason == "awaiting_approval": for pending in response.pending_approvals: record_approval(session, pending.id, True) # or False, "not on production" runtime.send(session, "") On resume the approved calls run once and denied calls return their reason, and then the model continues. The model is not asked to make the calls again. A pending call with no decision is refused with "No approval response provided". A call that has a result never runs again. Who may approve is your application's decision: authorize before calling record_approval().
Each call is decided by its own approval, and every approval-gated call ends with exactly one recorded outcome:
Repeated ids are denied. If the paused step holds two tool calls with the same call id (an empty id counts), or two approval requests name the same call or share one approval id, none of the step's approval-gated calls runs, whatever was decided. Each gets Tool call was not run because another call in this step has the same id. Some providers give every call to one function the same id, so asking one tool twice in one step does this.
A replaced step runs nothing. A paused step is replaced when a later step with tool calls is recorded after it, or when your application records a user or assistant message on the thread (through Thread.record) while the approval is pending. Each of its approval-gated calls without a result gets Tool call was not run because a later step replaced it, once, in a row marked harness_replaced_step; a decision recorded for it is kept and runs nothing. Messages the runtime itself records in the run, such as the model's answer after a resume, never replace a step.
Record decisions before messages. If your application records user or assistant messages while an approval is pending, record every decision first and resume, then record the message.
Results answer their own step. Every result row the harness writes names the step it answers (harness_answers_step). A result counts only for that step, even when another step was recorded while a call ran, and a mark a host writes on its own row is ignored. Neither mark is sent to the model.
A started call reads interrupted. Just before an approved call runs, the harness records that it started (harness_started). A started call with no result, because the store failed after the tool ran, the process stopped or the call is still running, is answered Tool call was interrupted, it may have run in the history sent to the model. That answer is never stored: the call's own result, when it lands, is its one stored outcome. It is never run again, and it may already have had its effect; a new approval is a new call.
The decision is read again when the call starts. If the decision that stands for its approval is no longer an approve at that moment, the call does not run and reads Not run: this call is not the one that was approved, or it is no longer open.
An empty send continues the turn's step count. A resume counts the steps the turn has taken since its user message, so a run that ended budget_exhausted stays out of steps however many empty sends follow.
An agent given a goal keeps working across many requests. session.tasks() is the list of what remains, in the durable half:
from prism_harness import TaskOutcome tasks = session.tasks() tasks.add_many(["Read the brief", "Draft the reply", "Check the numbers"]) while (task := tasks.claim("worker-1")) is not None: # The APPLICATION releases, from evidence -- not the agent. worked = do_the_work(task.instruction) tasks.release(task, "worker-1", TaskOutcome.DONE if worked else TaskOutcome.FAILED) Four states — todo, claimed, done, failed — and no others, behind four methods: claim, release, pending and find. find is on the contract because release takes a task while every caller outside the loop — a tool, an HTTP route, a worker resuming after a restart — holds only an id.
A lease must be a finite number of seconds greater than zero. A zero or negative one is refused rather than clamped: it would expire the instant it was granted, so the claim it should protect would be stealable by the next caller.
claim() is one call, not a read followed by a mark: the read that picks the task and the write that takes it happen inside one store lock, so two workers get different tasks or one gets None. Never the same task twice.
A claim carries an owner and an expiry, five minutes by default. When a lease lapses the task returns to todo — never to failed, because a worker dying is not the task failing, and marking it failed burns a retry that never ran. A worker may push its own lease out while it still holds it, bounded by what the run's RunBudget has left on the wall clock; there is deliberately no second timeout here to set in the place that is not enforced.
done and failed are terminal, and re-releasing one raises rather than quietly doing nothing.
An agent cannot mark its own task complete. If the model can set its own task to done, "run until the goal is met" becomes "run until it decides it is met", and a stalled run ends by declaring victory. TaskCompletionTool exists for consumers who want that, and nothing registers it: you register it on your own ToolRegistry and gate it through the ToolAuthorizer you already have. It is bound to one worker and closes only the task that worker is holding.
That rule is enforced on the source, not just in the tool: release() takes the worker, and only the worker currently holding the lease may release. Without it, a worker whose lease lapsed mid-task overwrites the claim of whoever legitimately picked the task up — the task reads done while the second worker is still working, its work is discarded, and its own release then fails as "already terminal", blaming it for the first worker's mistake. The tool checks too, because a third party's AgentTaskSource cannot be made to.
The agent must state an outcome, and it is either exactly done or exactly failed or refused with task_outcome_invalid. No case folding, no trimming, no truthiness — and an ABSENT outcome is refused too, not read as done. An implementation that resolves what it cannot read always resolves it toward the privileged answer, whether it is coercing complete into done or inferring completion from a field the agent never sent.
The list is durable state, so a task source refuses to start on a volatile store — a half-finished list that vanishes on a deploy is indistinguishable from a finished one.
No task model, no schema, no migration. AgentTask is a Protocol, so a record you already have — an ORM model, a dataclass, a row wrapper — becomes one the moment it exposes id, instruction and state. If your columns are named something else, AgentTaskMixin maps them; that is what the PHP reference spells as a trait on an Eloquent model.
The store contract is sync, unlike prism-harness-ts. That port is async because Node's filesystem API is, not because the work is slow. Python's is not, the PHP reference is synchronous too, and a caller who needs this off the event loop can wrap it in asyncio.to_thread — which is what prism-workspace-py does for the same reason. Forcing async here would make every consumer of a plain WSGI application write asyncio.run around a dictionary lookup.
MemorySessionStore — volatile, and says so. Its lock is a real threading.Lock but process-local.
FileSessionStore — durable. Payload writes remain atomic. Cross-process local locks follow decision 0022: a complete nonce-bound owner directory is published atomically; TTL expiry never proves that a live holder died. Recovery requires a matching established native boot/PID realm and a proven dead or explicitly released owner. Local filesystems on one host only; SMB/NFS are unsupported.
On Windows, the first file-lock operation makes one fixed, read-only metadata query using the system Windows PowerShell and CIM module, with a fifteen-second timeout. Established identities and detected container conditions are cached for the process lifetime. Transient query failures are cached for sixty seconds, then permit a serialized new sample. With unknown identity a worker can acquire a free lock and release its own owner record, but unknown owners and unknown probers never authorize PID probes or recovery. A crashed unknown owner's lock stays held for explicit operator inspection. FileSessionStore.identity_status() is an in-memory snapshot and performs no query or filesystem work. No runtime compilation or extra dependency is used.
BREAKING CHANGE: Stop all old workers before upgrading the file-lock protocol. Inspect and archive stale legacy timestamp lockfiles explicitly. The library refuses them with session_locked and legacy_lock_requires_maintenance, naming the canonical path and action stop_old_workers_then_inspect_and_archive. On Windows, Node can replace a legacy file created between preflight and rename; leaving old workers running can break exclusion. No rolling upgrade is supported. The hard stop is a correctness requirement in both ports.
A blocked Windows reader can delay release. The callback may already have completed when release raises an error; the library does not replay it. Pending cleanup is retried at the owning process's next file-lock operation. The file_lock_release_pending warning includes only the key digest and nonce. Read store.pending_releases() for this directory's pending digest/nonce entries; the snapshot's length is the count. Querying does not retry or write anything.
Implement SessionStore for anything else, and declare your own durability(): only you know whether your Redis is persistent or a disposable cache, and that declaration is an assertion about your infrastructure, not a preference.
Both files in this release have provenance metadata.
MIT View SPDX License List
agents ai harness llm prism
Development Status 3 - Alpha
Intended Audience Developers
Programming Language Python :: 3
Release files for prism-ai-harness 0.5.4
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
Built distribution (wheel)
Total release size: 218.4 kB
Release files / prism_ai_harness-0.5.4.tar.gz
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Release files / prism_ai_harness-0.5.4-py3-none-any.whl
Security for prism-ai-harness 0.5.4
Both files in this release have been uploaded with provenance metadata.
With provenance prism_ai_harness-0.5.4.tar.gz Nov 27, 2026
Attestation for prism_ai_harness-0.5.4.tar.gz
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.
Release history Release notifications | RSS feed
Nov 27, 2026 2 release files Full provenance
Nov 24, 2026 2 release files Full provenance
Nov 23, 2026 2 release files Full provenance
Nov 7, 2026 2 release files Full provenance
Nov 6, 2026 2 release files Full provenance
Oct 29, 2026 2 release files Full provenance
Oct 27, 2026 2 release files Full provenance
Oct 7, 2026 2 release files Full provenance
Sep 21, 2026 2 release files Full provenance
Sep 15, 2026 2 release files Full provenance
"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.
© 2026 Python Software Foundation




