Metadata-Version: 2.4
Name: forum-ai-tracing
Version: 0.4.0
Summary: Record versioned agent sessions in Forum AI.
License: Proprietary
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# Forum AI Python SDK

Requires Python 3.10 or later.

```sh
python3 -m pip install forum-ai-tracing==0.4.0
```

```python
import os
from forum_ai import SessionClient

forum = SessionClient(
    base_url=os.environ["FORUM_BASE_URL"],
    api_key=os.environ["FORUM_API_KEY"],
    instance="production",
    project="support-agent",
)
session = forum.start_session(id=conversation_id, title="Support conversation")
trace = session.start_trace("Handle request", turn_id=request_id)
trace.message("user", message)
tool = trace.start_span("lookup_order", operation_type="tool", input={"order_id": order_id})
order = lookup_order(order_id)
tool.end(order)
reply = answer_question(message, order)
trace.message("assistant", reply)
trace.end(reply)
receipt = session.publish_snapshot()
print(receipt["recordingId"], receipt["revision"])
```

Adapt the application functions and identifiers. Keep credentials private. Handle instrumentation and delivery errors separately from the application's result.

## Boundaries

One native conversation or workflow session is one recording and evaluation target. Identity includes the destination agent, provider, instance, project, and session ID. Turn IDs are scoped to the session; span IDs are scoped to the trace.

A turn includes the input and the agent's work through its final response, interruption, or recorded yield. Ending a turn or compacting context does not end its session. Native child sessions stay separate with explicit `parent` identity.

Use `resume_session(id=..., title=...)` on later requests. Create traces inside that session. Keep agent work, child operations, tool results, and final output inside the trace that performed them. `span` and `async_span` manage child work; `run` and `async_run` preserve application results. `async_end` waits for child work. `end` called while `async_span` work is pending closes the trace when that work finishes. End manually created spans explicitly.

A resumed session loads the accepted fragment versions. Reusing an existing trace ID does not replace its evidence: the SDK reports a `trace_exists` error and does not deliver that trace. Writes after a trace ends are reported as `trace_closed` and are not recorded.

`flush()` delivers changed fragments. `publish_snapshot()` pins available evidence without closing the session. Call `complete()` only at a known session completion boundary.

All three calls deliver every valid trace first. While unacknowledged evidence remains missing, they raise `SessionDeliveryError` with code `undelivered_evidence`; its `evidence` lists the outstanding entries. `publish_snapshot()` still publishes the open snapshot and attaches its receipt as `error.receipt`. `complete()` does not declare completion.

Live capture starts at activation. Historical imports are explicit. Disclose missing history and unresolved work. Execution, coverage, cutoff, and eligibility are separate states.

## Delivery and evaluation

`upload()` accepts session protocol version 2. Each evidence fragment has a stable ID and an `expectedVersion`: `None` for a new fragment, its accepted version for a change. Independent fragments merge. Identical retries retain their exact receipts. Late evidence creates a new session revision without rewriting prior assessments or citations.

A changed session becomes automatically eligible after five quiet minutes. Active work and unresolved completion boundaries block eligibility. Explicit completion and finished imports can establish an immediate cutoff. Existing opt-in, judge selection, and sampling still apply.

Inspect the exact accepted revision to verify saved content. A receipt alone does not prove complete capture.

Fragments are limited to 8 MiB, requests to 64 MiB, and sessions to 128 MiB and 10,000 fragments. Large requests use staged delivery. Unsupported or oversized evidence fails explicitly, without truncation or artificial session splitting.

Instrumentation and delivery problems go to `on_delivery_error` as `SessionDeliveryError` and never replace the application's result. Network errors, server errors, `408`, `423`, `429`, and invalid receipts keep the exact request, and later traces wait until Forum confirms it. Retries honor `Retry-After`. The SDK never replaces a conflicting remote fragment.

Some evidence is not accepted: Forum rejects a fragment (for example `409 conflict` or `422`), a trace cannot be encoded as JSON, a fragment exceeds 8 MiB, or a trace reuses an existing trace ID. The SDK reports it and continues with other traces. `session.rejected_evidence()` returns a dictionary for each entry with `fragment_id`, `error`, and the exact rejected `fragment` or, for values that cannot be encoded, the `reason`. Later successful deliveries do not clear these entries or `last_delivery_error`. The SDK also delivers a gap fragment, `signal:gap:<SHA-256 of the fragment ID>` (lowercase hex), so its ID stays within limits for any trace ID. It names the trace in `unresolved`, has `partial` coverage, and contains none of the rejected evidence. It blocks automatic evaluation and completion. A gap fragment that Forum rejects is listed in the same way, gets no gap of its own, and is not resent until its content changes.

To resolve an entry, correct the trace's `fragment` in place and call `flush()`. When Forum accepts that trace, the SDK removes the entry and clears the gap's unresolved boundary. The gap keeps `partial` coverage. After a restart, `resume_session` finds the session's gap fragments; when the resumed session delivers a trace that Forum never accepted, the SDK clears that trace's gap with its accepted version. Evidence from a reused trace ID cannot replace the original trace. Its gap remains unresolved until explicitly acknowledged.

If evidence cannot be recovered, acknowledge that specific gap after its work ends:

```python
session.acknowledge_gap("trace:failed-trace", "The original value is unavailable.")
```

Use the fragment ID from `rejected_evidence()`. Supply a nonempty reason of at most 2,000 characters. The original rejected evidence remains inspectable, with an `acknowledgment` field. Forum records the reason in a new immutable revision and keeps coverage `partial`. Earlier revisions remain unchanged.

Acknowledgment refuses active roots, pending child work, and manually opened spans. Other unresolved gaps still block completion. If Forum received a trace's start but lost its ending, acknowledgment preserves that content and marks the ending as missing. It refuses a trace changed by another writer. Acknowledgment does not invent a final answer or complete coverage.

Use `resume_session` after restart, then acknowledge the same trace fragment ID. Forum checks the persisted marker without granting the upload credential access to raw evidence. A rejected or missing receipt does not confirm acknowledgment. Retry with the same fragment ID and reason after an uncertain result. Python also provides `async_acknowledge_gap`.

Retries are in memory. Applications requiring delivery after process exit must persist exact uploads, expected versions, snapshot requests, and receipts. Retry pending bytes before newer versions. Use the Forum CLI for durable coding-agent capture.

Old clients receive an upgrade error. Upgrade to protocol 2 and regenerate old import plans.
