This is the full developer documentation for Prefactor # Prefactor documentation > Prefactor records agent activity, classifies data risk, and stores quality evidence you attach — so you can review agents in production. This site covers the web app, CLI, and agent SDKs. # Introduction > The Admin UI is the web app where you operate Prefactor — register agents, inspect runs, manage risk profiles, and configure your account. The Admin UI is the web app for operating Prefactor. You come here to register agents, inspect what they did, assign risk profiles, review run health and attached quality evaluations, and manage your account. Most of the day-to-day work of running Prefactor — from onboarding a new agent to reviewing an instance’s span activity — happens here. The section is organised around three areas: **Agents** covers the agent list and every per-agent screen (including Quality tabs for run health and per-instance evaluations); **Risk** covers creating and tuning risk profiles; **Account** covers team membership, API tokens, and environments. ## Related [Section titled “Related”](#related) * [Prefactor platform introduction](/platform) — what Prefactor is and how the platform is structured. * [Agent](/platform/concepts/agent) — what an agent is, how versions are created, and the agent lifecycle. * [Risk profile](/platform/concepts/risk-profile) — how category weights and thresholds combine into a risk level. * [Account](/platform/concepts/account) — what an account is and how it relates to agents, environments, and tokens. # Account page > What Account settings covers and how its tabs fit together. Account settings covers the identity, membership, credentials, and environments for your account. ## Tabs [Section titled “Tabs”](#tabs) * [Details tab](/admin-ui/account/details) — purpose, organisation metadata when relevant, account name, account ID, destructive controls. * [Team tab](/admin-ui/account/team) — members already joined to this account. * [Invites tab](/admin-ui/account/invites) — outstanding invitations. * [API tokens tab](/admin-ui/account/api-tokens) — issuance and lifecycle for programmatic access. * [Environments tab](/admin-ui/account/environments) — environment identifiers used when routing SDK traffic. ## Related [Section titled “Related”](#related) * [Account](/platform/concepts/account) — what an account is and how it relates to agents, environments, and tokens. # API tokens tab > Create and manage tokens for programmatic access to Prefactor. API tokens are how your SDKs and scripts authenticate with Prefactor. Account-wide tokens grant access to all agents in the account; deployment-scoped tokens are narrower and embed the agent identity. All tokens associated with the account appear in this tab. ## Tokens table [Section titled “Tokens table”](#tokens-table) Each row is a single **Token** cell stacked with: * A status badge: **Active** (authenticates API calls), **Suspended** (authentication disabled but recoverable), or **Revoked** (permanently invalidated). * The token’s scope: **Account**, **Environment ()**, or **Agent deployment ( · )**. * **Created** – when the token was created. * **Expires** – when the token expires. * **Last used** – the last time the token was used in an API request, or *Never*. * **Created by** – the user who generated the token. A row action menu sits beside the cell. Available actions depend on the token’s current state: * **Suspend** – on an active token. Disables it without deleting it. * **Activate** – on a suspended token. Re-enables it. * **Revoke** – on an active or suspended token. Permanently invalidates it. A revoked token cannot be re-enabled. * **Delete** – on a revoked token. Removes the row. ## Creating a token [Section titled “Creating a token”](#creating-a-token) Token creation from this page produces account-wide tokens only. 1. Select **Create API token**. 2. Copy the token value when shown — it is only displayed once. To create a deployment-scoped token, open the agent’s [Agent › Deployments tab](/admin-ui/agent/deployments) and use **Create deployment token** there. Environment-scoped tokens may appear in the table if they were created programmatically or through a legacy flow. There is no interface on this page to create new environment-scoped tokens. ## Using a token with the SDK [Section titled “Using a token with the SDK”](#using-a-token-with-the-sdk) Pass the token as `PREFACTOR_API_TOKEN` in your environment, or set `apiToken` in the SDK config directly. See [Configuration and environment variables](/sdks/configuration) for details. ## Related [Section titled “Related”](#related) * [API token](/platform/concepts/api-token) — what API tokens are, scoping, and how they authenticate requests. * [Account page](/admin-ui/account) — how Account settings tabs fit together. * [Agent page › Deployments tab](/admin-ui/agent/deployments) — deployment-scoped tokens for a single agent. * [Configuration and environment variables](/sdks/configuration) — pass a token to the SDK via `PREFACTOR_API_TOKEN`. # Details tab > Manage your account name, ID, and top-level settings. The account’s display name and unique ID live here — the ID appears in API calls and support requests. For how Account settings fits together, see the [Account page](/admin-ui/account). ## Fields [Section titled “Fields”](#fields) * Purpose – what the account is used for. Drives whether other fields are shown. * Organisation name – shown when the purpose is not personal. * Website – the organisation’s website URL, with a copy-to-clipboard control beside it. * Account name – the display name shown in the navigation header. * Account ID – a read-only, system-generated identifier used in API calls and support requests. **Edit** opens a modal that updates Purpose, Organisation name, Website, and the account name in one form. **Delete account** permanently removes the account and its associated data. ## Irreversible actions [Section titled “Irreversible actions”](#irreversible-actions) **Delete account** permanently removes the account and all its data, including agents, instances, spans, schemas, and tokens. This cannot be undone. Before deleting, remove or transfer any integrations that depend on this account’s API tokens or Environment IDs. ## Related [Section titled “Related”](#related) * [Account](/platform/concepts/account) — what an account is and how it scopes agents, environments, and tokens. * [Account page](/admin-ui/account) — how Account settings tabs fit together. # Environments tab > Create and manage environments within your Prefactor account. Environments let you separate agent activity, deployments, and configuration across different stages of your lifecycle — for example, Development, Staging, and Production. Each environment has its own ID, used by deployments and integrations to route activity to the right place. Agents themselves belong to the account and are not filtered by environment. ## Environments table [Section titled “Environments table”](#environments-table) Each row shows: * **Name** – the display name for the environment. * **Purpose** – what the environment is used for: **Development**, **Staging**, **Testing**, or **Production**. * **Description** – an optional longer description of the environment. * **Environment ID** – a system-generated identifier used by deployments and integrations that target this environment. * **Actions**: * **Edit** – changes the environment’s name, purpose, or description. * **Delete** – removes the environment from the account. ## Creating an environment [Section titled “Creating an environment”](#creating-an-environment) 1. Select **Create environment**. 2. Provide a name and pick a **purpose** (Development, Staging, Testing, or Production). 3. Optionally add a description. Prefactor generates a new Environment ID on creation. ## Deleting an environment [Section titled “Deleting an environment”](#deleting-an-environment) **Delete** removes the environment from the account. Deployments, tokens, and integrations that reference the environment’s ID will stop working. Update or remove those dependencies before deleting. ## Related [Section titled “Related”](#related) * [Environment](/platform/concepts/environment) — what environments are and how they scope activity and deployments. * [Agent deployment](/platform/concepts/agent-deployment) — how a deployment ties a version to an environment. * [Account page](/admin-ui/account) — how Account settings tabs fit together. # Invites tab > Manage invitations for new team members to join your account. Invites are how you add new people to the account. An accepted invite grants full account access — the same permissions as any existing member, with visibility and management rights over all agents, environments, and settings. Outstanding invitations for the account are listed here. ## Invites table [Section titled “Invites table”](#invites-table) Each row shows: * **Email** – the address the invitation was sent to. * **Status** – current state of the invite: *Pending*, *Accepted*, or *Revoked*. * **Created** – when the invite was created. * **Actions** – on pending invites, **Copy invite URL** to copy the join link, or **Revoke** to invalidate the invite. ## Creating an invite [Section titled “Creating an invite”](#creating-an-invite) 1. Select **Invite a team member**. 2. Enter the recipient’s email address. 3. Confirm to send. The recipient receives an email with a link to join the account. Once they complete sign-up or sign-in, their status changes to **Accepted** and they appear on the **Team** tab. ## Related [Section titled “Related”](#related) * [Account page](/admin-ui/account) — how Account settings tabs fit together. * [Account › Team tab](/admin-ui/account/team) — members who have joined the account. # Team tab > View and manage members who have access to your account. Team membership controls who can sign in to the account and view or manage its agents. All members of an account share the same level of access — there are no role-based permission distinctions within an account. Everyone with access is listed here. ## Team members table [Section titled “Team members table”](#team-members-table) Each row shows: * **Name** – the user’s display name. * **Email** – the address the user signs in with. * **Job title** – the user’s job title. Shown only when the account purpose is not personal. * **Joined** – when the user first joined the account. The table is scoped to the current account. ## Managing access [Section titled “Managing access”](#managing-access) To invite a new member, go to **Account settings → Invites**. Member removal is not available directly from the Team tab. If your account uses single sign-on (SSO), remove the user from your identity provider — their access to Prefactor will end when their SSO session expires. If your account does not use SSO, contact Prefactor support to remove a user. When a member is removed, any API tokens they created remain active until manually revoked. To review and revoke their tokens, go to [Account › API tokens tab](/admin-ui/account/api-tokens). ## Related [Section titled “Related”](#related) * [Account page](/admin-ui/account) — how Account settings tabs fit together. * [Account › Invites tab](/admin-ui/account/invites) — send invitations to new members. * [Account › API tokens tab](/admin-ui/account/api-tokens) — review and revoke tokens when a member leaves. # Agent page > What the Agent page covers: purpose, the strip above the tabs, and how the tabs fit together. Prefactor surfaces recent behaviour and deployments for the agent selected from the [Agents page](/admin-ui/agents): whether things look healthy, which versions run where, and how spans line up with your schemas. Above the tab row, several regions stay fixed while you switch tabs — agent identity and actions, instance risk distribution (when a profile is assigned), the activity timeline for the previous day, and how deployments line up across environments. ## Above the tabs [Section titled “Above the tabs”](#above-the-tabs) * Name and description — assigned when the agent was registered. * Status — Pending or Active. * Registered and Last updated — first appearance and last configuration or activity Prefactor saw. * Agent ID — internal ID used by APIs and integrations. * **Edit** — name, description, and risk profile assignment. * **Delete agent** — permanent removal. ## Instance risk distribution [Section titled “Instance risk distribution”](#instance-risk-distribution) When the agent has a risk profile assigned, Prefactor shows how many instances fell into each risk level — Low, Medium, High, and Critical — across every run the agent has produced. The distribution links through to the full [Instances tab](/admin-ui/agent/instances). ## Activity over the last 24 hours [Section titled “Activity over the last 24 hours”](#activity-over-the-last-24-hours) A timeline of spans generated by this agent in the previous 24 hours, with a breakdown by state: * Pending * Active * Complete * Failed * Cancelled ## Deployment snapshot [Section titled “Deployment snapshot”](#deployment-snapshot) This strip shows the current [agent deployment](/platform/concepts/agent-deployment) for each environment — which version is deployed there and when it was last updated. Each environment row lists the environment name, the deployed version, and when it was last updated. You can update the pinned version from the snapshot; the [Versions tab](/admin-ui/agent/versions) holds the full version history and where each version is deployed. If an environment is not listed, the agent has no deployment in that environment and activity is recorded against whichever version the SDK reports at runtime. ## Tabs [Section titled “Tabs”](#tabs) * [Overview tab](/admin-ui/agent/overview) — instance counts by state and the recent-span list with drill-through to instances. * [Instances tab](/admin-ui/agent/instances) — every run over time; drill through into instance docs from here. * [Versions tab](/admin-ui/agent/versions) — version history and which environments each version is deployed to. * [Deployments tab](/admin-ui/agent/deployments) — deployment-scoped API tokens for this agent. * [Activity schema tab](/admin-ui/agent/activity-schemas) — schema versions and span validation for this agent. * [Quality tab](/admin-ui/agent/quality) — duration, success, and failure signals from the last day of runs. ## Related [Section titled “Related”](#related) * [Agent](/platform/concepts/agent) — what an agent is, how versions are created, and the agent lifecycle. * [Agent deployment](/platform/concepts/agent-deployment) — how deployments pin a version to an environment. * [Agents page](/admin-ui/agents) — the account-wide list; navigate here to pick an agent. # Agent instance page > What the Agent instance page covers: purpose, the strip above the tabs, and how the tabs fit together. Prefactor records how one run unfolded: lifecycle timing, span hierarchy when present, data-risk signals tied to your schemas and profiles, and tools such as terminating an active instance. One strip sits above the tab row: it summarises run state and holds actions that affect the whole instance (such as terminate). Switching tabs swaps the detail underneath without losing that context. ## Above the tabs [Section titled “Above the tabs”](#above-the-tabs) * Status — Pending, Active, Complete, Failed, Cancelled, or Terminated. * Purpose — why the run happened: Live, Smoke test, or Eval (see [Instance](/platform/concepts/instance)). * Time — for completed or terminated runs, the wall-clock range; for active runs, the start time; for pending runs, “Ready to start”. * Created and Last updated — when Prefactor first recorded the instance and when it last changed. * **Risk profile** — the profile assigned to the agent, linked through to its configuration. * **Terminate** — appears while the instance is **Active**; ends the run after you confirm with a reason (see below). Above the tab content, Prefactor surfaces a **Risk score** — the run’s numeric total and risk level under the assigned profile — and an **Activity over last 24 hours** chart with span counts in five-minute buckets. The score’s composition by span type lives on the [Risk tab](/admin-ui/agent-instance/risk). ### Terminate [Section titled “Terminate”](#terminate) The modal captures a reason before Prefactor sets the status to **Terminated** and signals the running agent to stop — how the run winds down depends on the agent’s SDK integration; see [Handle instance termination](/sdks/handling-termination). You cannot undo termination; the reason travels with the instance and audit trail. Prefactor does not close spans on termination: they keep whatever status they reached, and the agent’s integration winds down anything still in flight. ## Tabs [Section titled “Tabs”](#tabs) * [Activity tab](/admin-ui/agent-instance/activity) — span-by-span inspection for this run. * [Risk tab](/admin-ui/agent-instance/risk) — score composition and how the instance total was calculated. * [Quality tab](/admin-ui/agent-instance/quality) — the quality evaluations attached to this run. * [Details tab](/admin-ui/agent-instance/details) — structural metadata (agent line, version links, timestamps). ## Related [Section titled “Related”](#related) * [Instance](/platform/concepts/instance) — what an instance is and the states it moves through. * [Handle instance termination](/sdks/handling-termination) — how the running agent finds out and responds. * [Risk profile](/platform/concepts/risk-profile) — how risk levels are derived from spans. * [Agent page › Instances tab](/admin-ui/agent/instances) — the list you navigated from. * [Agent page](/admin-ui/agent) — agent-level context, deployments, and versions. # Activity tab > Inspect the spans produced during a single agent execution. The spans produced during this instance are listed here, one card per span. For how this screen fits together and what sits above the tab row, see the [Agent instance page](/admin-ui/agent-instance). ## Spans [Section titled “Spans”](#spans) The activity list renders one card per span. Each card shows the span title, a one-line summary (rendered from the span type’s [summary template](/api/summary-templates), when it declares one), the duration and start/end timestamps, and a status badge. Hovering a card reveals **View**, which opens the span detail panel. Possible span status values: Pending, Active, Complete, Failed, or Cancelled. Spans do not use Terminated — that status is for instances only. Agents instrumented with the OpenClaw plugin (a conversational agent integration; see [OpenClaw plugin](/sdks/typescript-sdk/api/packages/openclaw-prefactor-plugin)) render the same span data in a **Conversation** layout by default — a structured view suited to conversational agent workflows — with a **Raw** view available to see the underlying spans. ## Span detail [Section titled “Span detail”](#span-detail) Selecting **View** on a span opens an in-page detail panel (URL-patched modal) that shows: * **Payload** – the span’s input payload. * **Result** – the span’s output payload, when one was recorded. Both fields render as JSON. The panel does not show nested child spans; to see a child span, open it from its own card in the list. ### Sensitive values [Section titled “Sensitive values”](#sensitive-values) Values the integration marked as [sensitive](/platform/sensitive-data) render redacted — a labelled placeholder naming the data categories in place of the value. Tick **Show sensitive information** in the panel to reveal them; the toggle applies to your current view only and resets when you leave. When a span holds sensitive values, a **Discard sensitive** button appears next to the payload. It opens a confirmation modal before permanently deleting the stored values — the span keeps its category labels, so the record still shows what kind of data was present, but the values cannot be viewed again. This cannot be undone. ## Related [Section titled “Related”](#related) * [Span](/platform/concepts/span) — what a span records, span types, and payload structure. * [Sensitive data](/platform/sensitive-data) — how marked values are stored, redacted, and discarded. * [Instance](/platform/concepts/instance) — the instance that owns these spans. * [Agent instance page](/admin-ui/agent-instance) — the strip above the tabs, including the risk score card and Terminate action. * [Agent instance page › Risk tab](/admin-ui/agent-instance/risk) — how the instance total score is composed. * [Agent instance page › Details tab](/admin-ui/agent-instance/details) — instance metadata and timing. # Details tab > View metadata and timing information for a single agent execution. Metadata for this instance appears here, without the span-by-span breakdown. For how this screen fits together and what sits above the tab row, see the [Agent instance page](/admin-ui/agent-instance). ## Details [Section titled “Details”](#details) * **Agent** – the agent that ran this instance, with a link to its overview page. * **Agent version** – the version of the agent that ran this instance, linked to its detail panel on the Versions tab. * **Status** – the current lifecycle state. * **Created** – when the instance record was first created. * **Last updated** – when Prefactor last saw a change to this instance. * **Started** – when execution began. * **Finished** – when execution completed. ## Related [Section titled “Related”](#related) * [Instance](/platform/concepts/instance) — what an instance record contains and how its lifecycle works. * [Agent instance page](/admin-ui/agent-instance) — the fixed strip above the tabs. * [Agent instance page › Activity tab](/admin-ui/agent-instance/activity) — span-by-span view for this run. # Quality tab > The quality evaluations attached to a single agent run. The quality evaluations for this run, as submitted by your evaluation process after it finished. Each named quality schema with a recorded payload gets its own section, headed by the schema’s title (or its name, when no title is set) with the schema name shown underneath. If the schema has a summary template, the rendered one-line summary appears first, with the raw quality payload available underneath as JSON; without a template, the payload is shown directly. Prefactor does not produce these evaluations — they arrive through the SDK or API, shaped by the quality schemas declared in the agent’s [activity schema](/platform/concepts/activity-schema). Each change to a named payload is also recorded as a quality span, visible in the run’s span record. For how this screen fits together and what sits above the tab row, see the [Agent instance page](/admin-ui/agent-instance). ## Related [Section titled “Related”](#related) * [Quality and performance](/platform/quality-and-performance) — what quality evaluations are and how they reach Prefactor. * [Record quality evaluations](/sdks/quality-evaluations) — declare quality schemas and record payloads from the SDKs. * [Instance](/platform/concepts/instance) — the run-level record that carries the quality payloads. * [Agent page › Quality tab](/admin-ui/agent/quality) — agent-wide run health over the last day. * [Activity tab](/admin-ui/agent-instance/activity) — the span record, including quality spans. # Risk tab > How the instance's total risk score was calculated under the assigned profile. How Prefactor scored this run under the agent’s assigned [risk profile](/platform/concepts/risk-profile). The score and risk level are summarised above the tabs; this tab shows what went into them. ## How risk is calculated [Section titled “How risk is calculated”](#how-risk-is-calculated) Prefactor restates the scoring model for the assigned profile so you can read it without leaving the page: each span type’s score is the sum of `category weight × action multiplier` across its declared categories and actions, and the instance total weights each span type’s score by how many spans of that type ran. The thresholds, included categories with their weights, and allowed actions with their multipliers from the profile are shown alongside. ## Score composition [Section titled “Score composition”](#score-composition) Prefactor breaks the instance total down by span type. For each span type that contributed, you get the span type name, the number of spans of that type recorded for this run, that type’s share of all spans, and the points it added to the total. A summed equation reconciles those contributions with the instance score. ## Related [Section titled “Related”](#related) * [Risk profile](/platform/concepts/risk-profile) — how profiles define weights, multipliers, thresholds, and agreed scope. * [Agent instance page](/admin-ui/agent-instance) — the risk score summary and the strip above the tabs. * [Activity tab](/admin-ui/agent-instance/activity) — per-span inspection. # Activity schema tab > View and manage the schema that validates an agent's spans. Schema versions defined for the agent appear here, along with the definitions that describe the expected structure of its spans. To define or update a schema, use the SDK — see [Schemas and result schemas](/sdks/concepts-schemas). ## Schema versions [Section titled “Schema versions”](#schema-versions) A list of all schema versions for the agent. Each entry shows the schema identifier and when it was created. Each schema version also lists the environments where it is currently in use. Selecting a schema version shows: * **Schema version number** – the version identifier as shown on the agent page. * **Deployed environments** – the environments using this schema version. * **Created** – when this schema version was created. ## Span types [Section titled “Span types”](#span-types) For the selected schema version, the page lists every span type the agent emits. Each span type has its own block with: * The span type identifier and a human-readable title. * A risk summary card. * An optional **Template** — the Liquid template that renders each span’s one-line summary; see [Summary templates](/api/summary-templates). * **Params data** and **Result data** sample payloads. * An **Action profile**, when one is configured. * The definitions for the span’s payload and result, shown as structured rules, with a **Valid** or **Invalid** indicator and an error alert when validation fails. Common patterns include `user_message` and `assistant_message` for conversation, plus one span type per tool you care to govern (for example `web_search` and `read_file`), each with definitions aligned to that tool. In the SDK, span types map to the keys in `agentSchema.span_schemas` and `agentSchema.span_result_schemas`. The identifiers shown here (for example `user_message`, `web_search`) correspond directly to those keys. ## Payload and result definitions [Section titled “Payload and result definitions”](#payload-and-result-definitions) Each span type has two definitions: * **Payload** — describes and validates the input payload for that span. * **Result** — describes and validates the output payload for that span. Definitions are shown inline. Each is marked **Valid** or **Invalid**; **Invalid** entries display an error alert with the validation failure. **Invalid** here means a problem in the definition itself, not a runtime validation failure. Spans are recorded regardless. Example permissive payload definition: ```json { "additionalProperties": true, "type": "object" } ``` Example stricter result definition: ```json { "additionalProperties": false, "type": "object" } ``` ## Related [Section titled “Related”](#related) * [Activity schema](/platform/concepts/activity-schema) — what an activity schema is in Prefactor and how it fits with agents and spans. * [Schemas and result schemas](/sdks/concepts-schemas) — how to define and register schemas from the SDK. * [Agent page](/admin-ui/agent) — what stays fixed above the tabs and how they fit together; choose **Activity schema** there. # Deployments tab > Manage deployment-scoped API tokens for an agent. The Deployments tab manages [deployment-scoped API tokens](/platform/concepts/api-token) for this agent — credentials scoped to one agent in one environment, with the agent identity built in. SDK calls authenticated with one of these tokens can omit the agent identifier. The tokens listed here cover all [agent deployments](/platform/concepts/agent-deployment) for this agent. Version pins (which version is current in each environment) live on the [deployment snapshot](/admin-ui/agent#deployment-snapshot) on the Agent page, not in this tab. See [agent deployment](/platform/concepts/agent-deployment) for how those records work. ## Deployment tokens table [Section titled “Deployment tokens table”](#deployment-tokens-table) Each row shows: * **Token** — the token’s scope, status badge, and the deployment it belongs to (agent name and environment). * **Created** / **Expires** / **Last used** / **Created by** — token metadata. * A row action menu, scoped to the token’s current state. ## Creating a deployment token [Section titled “Creating a deployment token”](#creating-a-deployment-token) 1. Open the agent’s **Deployments** tab. 2. Select **Create deployment token**. 3. Pick the target environment. 4. Confirm to create the token. Copy the value when shown — it is only displayed once. Tokens created here are deployment-scoped. To create an account-wide token instead, see [Account › API tokens tab](/admin-ui/account/api-tokens). ## Token actions [Section titled “Token actions”](#token-actions) Available actions depend on the token’s current state: * **Suspend** — on an active token. Disables it without deleting it. * **Activate** — on a suspended token. Re-enables it. * **Revoke** — on an active or suspended token. Permanently invalidates it. A revoked token cannot be re-enabled. * **Delete** — on a revoked token. Removes the row from the table. ## Related [Section titled “Related”](#related) * [Configuration and environment variables](/sdks/configuration) — set `PREFACTOR_API_TOKEN` to use a deployment-scoped token from the SDK. * [Account › API tokens tab](/admin-ui/account/api-tokens) — account-wide tokens for general API access. * [Agent page](/admin-ui/agent#deployment-snapshot) — deployment snapshot and version pins across environments. # Instances tab > Browse and investigate every execution of an agent over time. Each row records one execution of a specific agent version. ## Instances table [Section titled “Instances table”](#instances-table) Columns: * **Instance ID** – unique identifier for the instance. * **Environment** – the environment this instance ran in. * **Status** – lifecycle state shown as a badge. Possible values: Pending, Active, Complete, Failed, Cancelled, or Terminated. * **Time** – duration and timestamps. Complete instances show duration and start/end times. Active instances show the start time. Pending instances show when the instance was created. * **Version** – the agent version that ran this instance. * **Risk level** – Low, Medium, High, or Critical, derived from the instance’s total risk score under the assigned profile. Blank when the agent has no risk profile or no spans are assessable yet. See [Risk profile](/platform/concepts/risk-profile) for how scores are calculated. * **Actions** – **View** opens the instance detail pages. The table is ordered most-recent first. ## Related [Section titled “Related”](#related) * [Instance](/platform/concepts/instance) — what an instance is and how its lifecycle states are defined. * [Risk profile](/platform/concepts/risk-profile) — how the instance risk level is calculated from spans. * [Agent page](/admin-ui/agent) — the fixed strip above the tabs. * [Agent instance page](/admin-ui/agent-instance) — span-by-span inspection and details for a single run. # Overview tab > High-level health and activity view for a single agent. The Overview tab shows instance counts by state and the most recent spans for this agent, with a link through to any individual run. For the fixed strip that stays visible above the tab row — instance risk distribution, activity timeline, deployment snapshot, and agent identity — see the [Agent page](/admin-ui/agent). ## Risk summary [Section titled “Risk summary”](#risk-summary) Prefactor compares the agent’s declared span capabilities against its assigned [risk profile](/platform/concepts/risk-profile) and surfaces the result here: a link to the profile, the actions the agent’s schema declares it can perform, and the data categories those span types declare. When the schema declares actions or categories outside the profile’s agreed scope, the summary flags them as exceeding agreed scope. Span types without a data-risk definition in the schema are counted separately as unassessed. The summary links across to the [Activity schema tab](/admin-ui/agent/activity-schemas) to inspect the schema directly. ## Instances summary [Section titled “Instances summary”](#instances-summary) Counts of instances by state (matching the six lifecycle states on the [Instance](/platform/concepts/instance) concept, with Failed and Cancelled combined in the UI): * Total – all instances tracked for this agent. * Pending – registered, not yet running. * Active – currently running. * Complete – finished successfully. * Failed or cancelled – finished unsuccessfully (Failed and Cancelled combined). * Terminated – stopped from the platform with a reason. ## Recent activity [Section titled “Recent activity”](#recent-activity) The latest spans produced by the agent. Each entry shows: * Name or type – for example, `ai-sdk:tool` or `ai-sdk:llm`. * Status – Complete, Failed, etc. * Duration – how long the span took. * Time range – start and end timestamps. * **View instance** – opens the full instance view for that span. ## Related [Section titled “Related”](#related) * [Instance](/platform/concepts/instance) — what an instance is and how its lifecycle states work. * [Span](/platform/concepts/span) — what a span records and how span types are defined. * [Agent page](/admin-ui/agent) — the fixed strip above the tabs, including instance risk distribution. * [Agent page › Instances tab](/admin-ui/agent/instances) — the full list of every execution over time. * [Agent page › Activity schema tab](/admin-ui/agent/activity-schemas) — span-type definitions and per-type risk cards. # Quality tab > Duration, success, and failure signals for an agent's runs over the last day. Operational quality signals for the agent — whether runs are completing, how long they take, and where the failures are — computed from instances and spans started in the last 24 hours. Come here when you want to know if the agent is healthy before digging into individual runs. For the fixed strip that stays visible above the tab row, see the [Agent page](/admin-ui/agent). For quality evaluations of individual runs — scores and verdicts rather than run health — see the [Agent › Instance › Quality tab](/admin-ui/agent-instance/quality). ## Quality summary [Section titled “Quality summary”](#quality-summary) Four headline figures for the last day: **Success rate** (the share of finished runs that completed successfully), **Typical duration** (the average finished instance), **Worst case** (the longest), and **Failures** (runs that finished as Failed or Terminated). Below the headline figures, the instance duration distribution breaks finished runs down by Best, P25, Median, Average, P95, Worst, and standard deviation, so a healthy-looking average cannot hide a bad tail. ## Outcomes [Section titled “Outcomes”](#outcomes) Every instance from the last 24 hours by how it ended — Complete, Failed, Cancelled, or Terminated — with counts and percentages. ## Span duration distribution [Section titled “Span duration distribution”](#span-duration-distribution) The same timing analysis at span level, grouped by span type across schema versions and sorted by average duration. Each span type shows its call count, success rate, failure count, and duration spread (min, p25, median, p95, max, and average) on a shared time axis, so the slowest step in the agent’s workflow stands out. Only activity spans are counted here; [quality spans](/platform/concepts/span) written by the platform are excluded. ## Related [Section titled “Related”](#related) * [Quality and performance](/platform/quality-and-performance) — what quality means for an agent and how evaluations work. * [Instance](/platform/concepts/instance) — the run-level record these statistics aggregate. * [Span](/platform/concepts/span) — the step-level record behind the span statistics. * [Agent page › Instances tab](/admin-ui/agent/instances) — drill through to the individual runs behind the numbers. * [Agent › Instance › Quality tab](/admin-ui/agent-instance/quality) — the quality evaluation attached to a single run. # Versions tab > View the version history of an agent, including which versions are deployed per environment. Prefactor creates a [version](/platform/concepts/agent#versions) each time an instance arrives with a combination of metadata and schema it has not seen before for that agent. This tab lists all known versions and shows where each is currently deployed. ## Version history [Section titled “Version history”](#version-history) A list of all known versions for the agent. Each entry shows the version identifier and when it was first registered. Each version also lists the environments it is currently deployed to, or ”- not deployed -” if it has not been deployed anywhere. Selecting a version opens its details panel. ## Version details [Section titled “Version details”](#version-details) * **Version number** – the identifier used by your deployment system. * **Schema version number** – the activity schema version associated with this code version. * **Deployed environments** – the environments where this version is currently deployed. * **Risk classification** – two scores when classification data is available: **Theoretical risk** (potential risk from the activity schema and action profile, calculated before any runs) and **Observed risk** (derived from spans recorded during actual executions). See [Risk profile](/platform/concepts/risk-profile) for how scores are computed. * **Runtime environment** – SDK, runtime, and OS reported for this version, when the SDK records that data. * **Registered** – when Prefactor first observed this version. ## Recent instances for this version [Section titled “Recent instances for this version”](#recent-instances-for-this-version) A table of recent instances that ran under the selected version. Columns: Instance ID, Environment, Status, Time, Version. A **View all** link opens a filtered instances view for this version. ## Related [Section titled “Related”](#related) * [Agent](/platform/concepts/agent#versions) — how Prefactor creates versions and what they represent. * [Agent deployment](/platform/concepts/agent-deployment) — how a version is pinned to an environment. * [Agent page](/admin-ui/agent) — the fixed strip above the tabs. * [Agent page › Deployments tab](/admin-ui/agent/deployments) — deployment-scoped tokens tied to each environment. * [Agent page › Activity schema tab](/admin-ui/agent/activity-schemas) — the schema version associated with each code version. # Agents page > Manage and monitor applications instrumented with Prefactor. Every agent in your account appears here. The activity chart at the top is account-wide; agents belong to the account, not to a single environment. ## Activity chart [Section titled “Activity chart”](#activity-chart) At the top of the page, a chart shows agent activity for the last 24 hours, broken down by span state: * Pending * Active * Complete * Failed * Cancelled **Terminated** applies to [instances](/platform/concepts/instance), not spans. Terminating a run signals the agent to stop; the run’s spans keep whatever status they reached. ## Agents list [Section titled “Agents list”](#agents-list) Each entry in the list shows: * **Agent** – the identifier assigned when the agent was registered. * **Status** – the agent’s lifecycle state: Pending or Active. * **Description** – a short description of what the agent does. * **View details** – opens the agent’s detail pages. ## Registering an agent [Section titled “Registering an agent”](#registering-an-agent) Select **Register agent** to open the creation form. Provide a name and description, and optionally assign a **Risk profile**. Once you save, configure your SDK with the agent ID and an API token. Prefer a deployment-scoped token from the [Agent page › Deployments tab](/admin-ui/agent/deployments) for runtime SDKs; use [Account › API tokens tab](/admin-ui/account/api-tokens) for account-wide access. See [Configuration](/sdks/configuration) for the environment variables. When the SDK records instances, they appear in the [Agent page › Instances tab](/admin-ui/agent/instances). SDK calls authenticated with a deployment-scoped token can omit the agent ID — the deployment supplies it. ## Related [Section titled “Related”](#related) * [Agent](/platform/concepts/agent) — what an agent is, how versions are created, and how the agent lifecycle works. * [Agent page](/admin-ui/agent) — the fixed strip above the tabs and how the tabs fit together for a single agent. * [Agent page › Deployments tab](/admin-ui/agent/deployments) — deployment-scoped tokens for runtime SDKs. * [Account › API tokens tab](/admin-ui/account/api-tokens) — account-wide tokens for admin and general API access. * [Configuration and environment variables](/sdks/configuration) — set `PREFACTOR_API_TOKEN` and `PREFACTOR_AGENT_ID` in the SDK. # Risk page > Create and manage risk profiles, and review the configuration of a single profile. The **Risk** item in the main navigation is where you create and tune risk profiles for your account. A profile decides how Prefactor turns declared span-type capabilities into a risk classification for each run — category weights, action multipliers, and score thresholds. You assign a profile to an agent to control how those declarations are scored. For how weights and multipliers combine into a score, see [risk profile](/platform/concepts/risk-profile). ## Profiles list [Section titled “Profiles list”](#profiles-list) Every profile configured for your account is listed here. Open one to review or edit its configuration; use **Create profile** to add a new one. ### Create risk profile [Section titled “Create risk profile”](#create-risk-profile) Use **Create profile** to open the creation form. Fields: * **Name** (required) and **Description**. * **Start from template** — choose one preset; it pre-fills weights and related fields. * **Data category values** — weights for the categories under Standard PII, Sensitive data, and GDPR Article 9 Special Categories. Each category has a weight from 0 to 10 and an inclusion toggle. Excluding a category drops it from the profile regardless of the weight; including a category with weight 0 keeps it in scope but contributes nothing to scores. * **Action risk multipliers** (advanced) — Destroy data, Financial transactions, External communication, Create data, Update data, and Read data. Actions also have an inclusion toggle. Excluded actions are not allowed under the profile’s agreed risk. * **Risk level thresholds** — **Medium ≥**, **High ≥**, and **Critical ≥** (numeric inputs within the allowed range). Saving returns you to the list with the new profile in it. Open it for the full configuration below. ## Profile detail [Section titled “Profile detail”](#profile-detail) Opening a profile shows its score thresholds, agreed risk scope, category scores, action multipliers, and the agents currently assigned to it. ### Score thresholds [Section titled “Score thresholds”](#score-thresholds) Low, Medium, High, and Critical each map to a threshold value configured in the profile, with each band running from one threshold up to the next. If the values are not strictly ascending (medium > 0, high > medium, critical > high), the section shows an error — fix the values under **Edit**. ### Agreed risk [Section titled “Agreed risk”](#agreed-risk) The scope an agent using this profile is agreed to operate within: which actions it may perform and which data categories it may touch. Prefactor compares the agent’s declared capabilities against this scope on the [Overview tab](/admin-ui/agent/overview) of the agent and flags anything that exceeds it. ### Category scores [Section titled “Category scores”](#category-scores) The categories the profile scores against, with their weights, grouped under Standard PII, Sensitive data, and GDPR Special Categories (Article 9). Zero-weight categories are hidden — included categories with no weight are still part of the agreed scope but do not contribute to the score. ### Action multipliers [Section titled “Action multipliers”](#action-multipliers) Each included action type carries a multiplier. Values above 1 amplify that action in the risk score; 1 is neutral; below 1 reduces it. Actions excluded from agreed risk are not listed. ### Agents using this profile [Section titled “Agents using this profile”](#agents-using-this-profile) Lists agents currently linked to this profile, each linking to that agent’s overview. ## Actions [Section titled “Actions”](#actions) ### Editing a profile [Section titled “Editing a profile”](#editing-a-profile) Use **Edit** to change the profile’s name, description, category weights and inclusion, action multipliers and inclusion, and thresholds. The same fields are available when creating a profile. Editing does not re-offer the **Start from template** picker; templates only apply when a profile is first created. ### Deleting a profile [Section titled “Deleting a profile”](#deleting-a-profile) **Delete profile** is in the action menu. Agents that used the profile keep the association in their history and the configuration is preserved for audit, but no new instances will be scored against it. ## Related [Section titled “Related”](#related) * [Risk profile](/platform/concepts/risk-profile) — what a risk profile is and how category weights, multipliers, and thresholds combine into a risk level. * [Agents page](/admin-ui/agents) — agents list; assign a profile when registering or editing an agent. * [Prefactor introduction](/platform) — how risk profiles fit into the platform. # API > Call the Prefactor platform API over HTTP or WebSocket — conventions, rate limits, and the generated operation reference. The Prefactor platform API lets you work with the platform from your own code — list agents, register and query instances, and watch runs as they happen. Every operation is available as a plain HTTPS request, and a WebSocket transport carries the same operations plus server-pushed notifications when instances change. The TypeScript and Python SDKs are built on this API, and handle authentication, retries, and rate limiting for you. Come to this section when you’re calling the API directly or writing your own client. ## In this section [Section titled “In this section”](#in-this-section) * [HTTP API](/api/http) — base URL, authentication, response and error shapes, and bulk operations * [WebSocket API](/api/websocket) — connection, JSON-RPC message format, and notifications when instances change * [Rate limits](/api/rate-limits) — how limits are applied, and what a limited response looks like * [Summary templates](/api/summary-templates) — the Liquid template language behind the summaries rendered for span types and quality schemas * [Sensitive encoding](/api/sensitive-encoding) — the `$sensitive` marker format for flagging sensitive values in span payloads * [Stream agent instance updates](/api/stream-instance-updates) — a runnable script that subscribes to an instance and prints every change ## Operation reference [Section titled “Operation reference”](#operation-reference) * [Platform API docs](/api/platform) — the generated explorer: every operation with its params and response schemas * [Swagger UI](https://app.prefactorai.com/api-docs/v1) — try requests against the live API from your browser * [OpenAPI JSON](https://app.prefactorai.com/api/v1/openapi) — the raw schema, for API clients and code generation * [OpenRPC JSON](https://app.prefactorai.com/api/v1/openrpc) — the machine-readable spec for the WebSocket methods ## Related [Section titled “Related”](#related) * [API token](/platform/concepts/api-token) — every call authenticates with a bearer token; the token’s scope decides which operations you can call * [SDK overview](/sdks) — the TypeScript and Python SDKs call this API for you * [Prefactor CLI](/cli) — the same operations from the terminal, without writing code # HTTP API > Call the platform API over HTTP — base URL, authentication, response and error shapes, and bulk operations. The HTTP API is the primary way to call the Prefactor platform. Every operation is a plain HTTPS request, and both SDKs are built on it. This page lists the conventions that apply to every call; the operations themselves live in the [OpenAPI spec](/api/platform). For live streams of instance changes, see the [WebSocket API](/api/websocket). ## Calling the API [Section titled “Calling the API”](#calling-the-api) The base URL is `https://app.prefactorai.com/api/v1`. Authenticate every request with an `Authorization: Bearer ` header, using an [API token](/platform/concepts/api-token) — create one from the [Account › API tokens tab](/admin-ui/account/api-tokens). Both account tokens and deployment tokens work; the token’s scope decides which operations you can call. ```bash curl https://app.prefactorai.com/api/v1/agent \ -H "Authorization: Bearer $PREFACTOR_API_TOKEN" ``` Requests and responses are JSON. The official SDKs also send an `X-Prefactor-SDK` header identifying their package versions; hand-written clients can leave it off. ## Responses [Section titled “Responses”](#responses) A successful call returns `200` with a `status` of `"success"` plus the operation’s payload — `summaries` for list operations, `details` for a single record: ```json {"status": "success", "summaries": []} ``` ## Errors [Section titled “Errors”](#errors) A failed call returns a non-200 status with a `status` of `"error"`, a machine-readable `code`, and a human-readable `message`: ```json {"status": "error", "code": "not_found", "message": "Agent instance not found"} ``` | `code` | HTTP status | When | | ------------------------------ | ----------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `bad_request` | 400 | The request is malformed — bad params or an unknown field. | | `validation_errors` | 400 | Params failed validation. The body adds an `errors` map keyed by field. | | `not_authenticated` | 401 | No `Authorization` header on the request. | | `bad_authtoken` | 401 | The token is invalid, expired, suspended, or revoked. | | `not_permitted` | 403 | The token’s scope cannot perform this operation. | | `not_found` | 404 | The record does not exist. | | `invalid_action` | 409 | The operation conflicts with the record’s current state — for example, terminating an instance that is not active. | | `idempotency_key_already_used` | 409 | The idempotency key was already used — see [Bulk operations](#bulk-operations). | | `rate_limited` | 429 | Rate limited. The body adds `retry_after_ms`, and the `Retry-After` header carries the same wait — see [Rate limits](/api/rate-limits). | | `temporarily_unavailable` | 503 | Try again shortly. | | `unknown`, `unexpected` | 500 | Something failed on Prefactor’s side. | | `not_implemented` | 501 | The operation is not available. | Individual operations can return more specific codes — `alert_already_cleared` (`409`), `required_value` (`400`), and similar — in the same envelope. ## Bulk operations [Section titled “Bulk operations”](#bulk-operations) [POST /bulk](/api/platform/operations/bulkexecute) runs several operations in one request. Each item carries a `_type` (the operation name, such as `agents/list`), a unique `idempotency_key` (8–128 characters), and the operation’s params: ```json { "items": [ {"_type": "agents/list", "idempotency_key": "list-agents-001"}, {"_type": "agents/show", "idempotency_key": "show-agent-001", "agent_id": "01J..."} ] } ``` The response’s `outputs` is a map keyed by idempotency key: ```json { "status": "success", "outputs": { "list-agents-001": {"status": "success", "summaries": []}, "show-agent-001": {"status": "success", "details": {"id": "01J..."}} } } ``` Items are processed in order, each in its own transaction. Processing stops at the first error: items before it keep their results, items after it are dropped from `outputs`. A reused idempotency key is recorded as an error for that item but does not stop the batch, so retrying the whole request is safe. Subscription operations such as `agent_instances/subscribe` are rejected here — they are only available on the [WebSocket API](/api/websocket). ## Related [Section titled “Related”](#related) * [API Reference](/api) — the section overview: transports, rate limits, and the operation reference. * [WebSocket API](/api/websocket) — the same operations over a persistent connection, plus server-pushed notifications. * [Rate limits](/api/rate-limits) — how limits are applied, and the shape of a limited response. * [API token](/platform/concepts/api-token) — account tokens and deployment tokens, and where to manage them. # Rate limits > How Prefactor limits requests to the platform API, and what a rate-limited response looks like. Prefactor rate limits requests to the platform API so that one busy integration cannot degrade the service for everyone else. This page lists how limits are applied and what a limited response looks like. If you use the TypeScript or Python SDK, retries are handled for you — see [Handle rate limiting](/sdks/handling-rate-limits). ## How limits are applied [Section titled “How limits are applied”](#how-limits-are-applied) Every HTTP request counts against a high per-IP ceiling that exists to absorb floods. Authenticated requests count against additional scopes, checked over fixed one-minute windows. Which scopes apply depends on the token: an [account token](/platform/concepts/api-token) counts against the token itself and the account; a deployment token counts against the token, its agent deployment, its agent, and the account. A single request counts against every applicable scope at once, and exceeding any one of them limits the request. Reads (queries) have a higher allowance than writes (actions) and live subscriptions. The same limits apply to every account. The web app and login are not rate limited beyond the per-IP ceiling. ## The 429 response [Section titled “The 429 response”](#the-429-response) A limited HTTP request returns status `429` with a `Retry-After` header in whole seconds and a JSON body: ```json { "status": "error", "code": "rate_limited", "message": "Rate limited on the API token", "retry_after_ms": 1500 } ``` | Field | Type | Description | | ---------------- | ------- | ------------------------------------------------------------------------------- | | `status` | string | Always `"error"`. | | `code` | string | Always `"rate_limited"`. | | `message` | string | Names the scope that was exceeded — for example, “Rate limited on the account”. | | `retry_after_ms` | integer | Milliseconds to wait before retrying. | `Retry-After` and `retry_after_ms` carry the same wait; use either. ## WebSocket connections [Section titled “WebSocket connections”](#websocket-connections) The [WebSocket API](/api/websocket) (`/api/v1/ws`) speaks JSON-RPC, so a limited call returns a JSON-RPC error with code `-32000` instead of an HTTP status. The error’s `data` object carries the same fields as the HTTP body above. ## Related [Section titled “Related”](#related) * [API token](/platform/concepts/api-token) — account tokens and deployment tokens, and where to manage them. * [Handle rate limiting](/sdks/handling-rate-limits) — how the SDKs retry limited requests, and what happens when retries run out. * [Configuration and environment variables](/sdks/configuration) — retry settings for both SDKs. # Sensitive encoding > The $sensitive marker format for flagging sensitive values in span payloads — enabling the encoding, marker shape, escaping literal keys, and read-back. Sensitive encoding is the payload format your integration uses to flag sensitive values in a [span](/platform/concepts/span)’s input and result. When the encoding is enabled for a payload, Prefactor parses it for `$sensitive` markers and handles each marked value under the storage, redaction, and discard rules described in [Sensitive data](/platform/sensitive-data). ## Enabling the encoding [Section titled “Enabling the encoding”](#enabling-the-encoding) The encoding is off by default and enabled per payload. Set `sensitive_encoding: true` when you create the span to have the input payload parsed, and again when you finish the span to have the result payload parsed. The two are independent. With the flag off, nothing is parsed: the payload is stored as-is, and a literal `$sensitive` key in your data is just a key. With the flag on, that key needs escaping — see Escaping literal `$sensitive` keys below. ## Marker shape [Section titled “Marker shape”](#marker-shape) A marker is a JSON object that wraps a single value. It records the value’s type, the categories of sensitive data the value contains, and the value itself: ```json { "email": { "$sensitive": "string", "labels": ["personal_identifiers", "contact_information"], "value": "ada@example.com" } } ``` | Field | Type | Description | | ------------ | -------------------------------------- | --------------------------------------- | | `$sensitive` | `"string"`, `"number"`, or `"boolean"` | The wrapped value’s type. | | `labels` | array of strings | The data categories the value contains. | | `value` | string, number, or boolean | The value itself. | The `labels` list uses the same data-category vocabulary as [risk profiles](/platform/concepts/risk-profile) — `personal_identifiers`, `contact_information`, `financial_information`, `health_and_medical`, `authentication_and_secrets`, and the rest, including the GDPR special categories. ## Escaping literal `$sensitive` keys [Section titled “Escaping literal $sensitive keys”](#escaping-literal-sensitive-keys) With the encoding on, Prefactor parses every object that contains a `$sensitive` key, so your data cannot use that key directly. To keep a literal `$sensitive` key, wrap the object that contains it in an escape marker: ```json { "mapping": { "$sensitive": "escape", "value": { "$sensitive": "a field name in your own data", "other": "data" } } } ``` The wrapper has exactly two fields — `$sensitive` set to `"escape"`, and `value` holding the object — and anything else is rejected. The escape shields only the outer object: markers nested inside `value` are parsed as usual. On read-back, any object containing a `$sensitive` key is returned in the escape-wrapped form, including data written with the encoding off, so a literal key always survives the round trip. Few payloads contain a `$sensitive` field of their own, so few integrations need the escape marker. If you are not sure whether yours does, it almost certainly does not — this section exists for completeness. ## Read-back [Section titled “Read-back”](#read-back) Marked values are stored separately from the span record, but the API always accepts and returns the combined payload: your integration sends markers in and reads the same payload back out. Read-back is also where you choose who the payload is safe for. Span list and detail queries accept a `redacted` parameter that defaults to `false` — the API returns the real values unless you ask otherwise, the opposite of the web app, which redacts by default. Pass `redacted: true` when the data is headed somewhere less trusted, such as an export or an evaluation pipeline. Each marker then comes back without its value: ```json { "email": { "$sensitive": "string", "labels": ["personal_identifiers", "contact_information"] } } ``` The type and labels survive, so the redacted form still records what kind of data was there; only the value is gone. Summaries on the same queries render with the redaction labels in place of the values, matching what the web app shows. A discarded value never comes back: its marker has no value on any read, however `redacted` is set. ## SDK support [Section titled “SDK support”](#sdk-support) In the TypeScript SDK, pass `sensitiveEncoding: true` in the span options and build the marker objects in your payload; the SDK sends them through unchanged. The Python SDK does not support sensitive encoding yet — call the [HTTP API](/api/http) directly to mark values from Python. ## Related [Section titled “Related”](#related) * [Sensitive data](/platform/sensitive-data) — the model behind the markers: separate storage, redaction by default, reveal on demand, and discard. * [Risk profile](/platform/concepts/risk-profile) — where the data-category vocabulary in `labels` comes from. * [Summary templates](/api/summary-templates) — how redacted values render in span summaries. * [OpenAPI spec](/api/platform) — the span create, finish, and query operations. # Stream agent instance updates > A step-by-step walkthrough with a runnable example script — subscribe to an agent instance over the WebSocket API and print every change as it happens. When you want to watch a run as it happens — waiting out a smoke test, or feeding live status into your own tooling — polling the [HTTP API](/api/http) works, but a subscription is cheaper and faster. By the end of this page, you have a script that prints every change to one [instance](/platform/concepts/instance) until you stop it. The subscription lives on the WebSocket API. [WebSocket API](/api/websocket) covers the connection and message format in full; this page is the shortest path to a working stream. ## Before you start [Section titled “Before you start”](#before-you-start) * An [API token](/platform/concepts/api-token) for the account the instance belongs to. Create one from the [Account › API tokens tab](/admin-ui/account/api-tokens). * The ID of the agent instance you want to watch. Find it on the [Agent page › Instances tab](/admin-ui/agent/instances). * Node.js with the `ws` package installed (`npm install ws`). The browser `WebSocket` API cannot set the `Authorization` header, so the example runs in Node. ## Steps [Section titled “Steps”](#steps) 1. Save this script as `stream-instance.mjs`: ```javascript import WebSocket from "ws"; const token = process.env.PREFACTOR_API_TOKEN; const instanceId = process.env.PREFACTOR_AGENT_INSTANCE_ID; if (!token || !instanceId) { console.error("Set PREFACTOR_API_TOKEN and PREFACTOR_AGENT_INSTANCE_ID"); process.exit(1); } function connect() { const ws = new WebSocket("wss://app.prefactorai.com/api/v1/ws", { headers: { Authorization: `Bearer ${token}` }, }); ws.on("open", () => { ws.send( JSON.stringify({ jsonrpc: "2.0", id: 1, method: "agent_instances/subscribe", params: { agent_instance_id: instanceId }, }), ); }); ws.on("message", (data) => { const message = JSON.parse(data.toString()); if (message.id !== undefined) { if (message.error) { console.error("Subscribe failed:", JSON.stringify(message.error)); ws.close(); } else { console.log(`Subscribed to ${instanceId}`); } return; } if (message.method === "error") { console.error("Prefactor is closing the stream:", message.params.message); return; } console.log(message.method, JSON.stringify(message.params)); }); ws.on("close", (code) => { if (code === 1008) { console.error("Authentication is no longer valid - check the API token."); process.exit(1); } console.log(`Connection closed (${code}); reconnecting in 5s`); setTimeout(connect, 5000); }); ws.on("error", (err) => { console.error("Connection error:", err.message); }); } connect(); ``` The script does four things: opens the socket with the token in the `Authorization` header, sends `agent_instances/subscribe` once the socket is open, prints each notification that arrives, and reconnects when the connection closes — unless the close means your token stopped being valid. 2. Run it with your token and instance ID: ```bash PREFACTOR_API_TOKEN=your-token PREFACTOR_AGENT_INSTANCE_ID=your-instance-id node stream-instance.mjs ``` You should see `Subscribed to your-instance-id` within a second or two. The script now waits; every change to the instance prints as an `agent_instances/updated` line with the full instance details. ## Verify [Section titled “Verify”](#verify) With the script running, make the instance change — let the agent finish its run, or terminate the instance from the [Agent instance page](/admin-ui/agent-instance). A notification prints each time. If the instance is deleted, you get one `agent_instances/deleted` message and then nothing further. ## If it didn’t work [Section titled “If it didn’t work”](#if-it-didnt-work) * **`Connection error: Unexpected server response: 401`.** The token is missing, malformed, or no longer valid. Create a fresh one from the [Account › API tokens tab](/admin-ui/account/api-tokens). * **`Subscribe failed` with code `-32602`.** The instance ID is wrong, or the token’s account cannot see that instance. Check the ID on the [Agent page › Instances tab](/admin-ui/agent/instances). * **`Subscribe failed` with code `-32000`.** You are rate limited. The error’s `retry_after_ms` says how long to wait; [Rate limits](/api/rate-limits) covers how limits are applied. * **The script exits after `Prefactor is closing the stream`.** The token was revoked, suspended, or expired mid-stream, and Prefactor closed the connection with code `1008`. Re-authenticate with a valid token. * **`Subscribed to ...` prints, but no notifications arrive.** Notifications only fire when the instance changes. Record a span or let the run finish; if it stays silent, check that you subscribed to the right instance ID. ## Related [Section titled “Related”](#related) * [WebSocket API](/api/websocket) — the full protocol: methods, notifications, error codes, and close codes. * [Rate limits](/api/rate-limits) — how limits are applied to socket calls. * [Instance](/platform/concepts/instance) — the lifecycle you are watching. * [Handle instance termination](/sdks/handling-termination) — how your agent finds out when Prefactor stops a run. # Summary templates > The Liquid template language behind the summaries Prefactor renders for span types and quality schemas — available data, control flow, filters, and failure behaviour. Any schema in an agent’s [activity schema](/platform/concepts/activity-schema) can carry a template that renders a one-line summary of the data that schema describes. Span types use it for the summary on each span card in the [Activity tab](/admin-ui/agent-instance/activity); quality schemas use it for the summary on the instance [Quality tab](/admin-ui/agent-instance/quality). Templates are written in [Liquid](https://shopify.github.io/liquid/) and rendered server-side by Prefactor each time the summary is displayed. Nothing renders in your SDK or in the browser, so the same template produces the same summary everywhere it appears. ## Declaring a template [Section titled “Declaring a template”](#declaring-a-template) Templates are declared on the schema entry, not inside the JSON schema itself. Each span type in the agent schema carries a `template` field alongside its `params_schema` and `result_schema`; each quality schema carries one alongside its `schema`: ```json { "name": "web_search", "params_schema": { "type": "object", "properties": { "query": { "type": "string" } } }, "template": "Searched for {{query}} — {{results.size}} results" } ``` A span type’s template can reference both params and result fields; a quality schema’s template references the fields of the recorded payload. The SDKs expose the same field — TypeScript as `template` on a span type or quality schema entry, Python as the `template` argument to `register_type` and `register_quality_schema`. Templates need this structured form: the flat `span_schemas` map of names to JSON schemas has no place for one. See [Schemas and result schemas](/sdks/concepts-schemas) and [Quality evaluations](/sdks/quality-evaluations) for the full declaration flow. ## Available data [Section titled “Available data”](#available-data) What the template can see depends on the schema kind. **Span types** render with the span’s params and result fields merged into one flat namespace. When the same name exists in both, the result field wins. Given params: ```json { "query": "refund policy", "limit": 5 } ``` and result: ```json { "results": ["a", "b", "c"], "limit": 3 } ``` the template `Searched for "{{query}}" — returned {{results.size}} of {{limit}} requested` renders as `Searched for "refund policy" — returned 3 of 3 requested`, because the result’s `limit` shadows the params’ `limit`. **Quality schemas** render with the recorded quality payload as the data — the same fields the quality schema declares, as in `Scored {{overall_score}}/100 ({{verdict}})`. ## Control flow [Section titled “Control flow”](#control-flow) Templates support Liquid’s standard control-flow tags: * `{% if %}` with `{% elsif %}` and `{% else %}`, closed by `{% endif %}` * `{% unless %}` … `{% endunless %}` * `{% case %}` with `{% when %}` and `{% else %}`, closed by `{% endcase %}` * `{% for %}` … `{% endfor %}`, with `limit:`, `offset:`, and `reversed` parameters ```plaintext {% if verdict == "pass" %}Passed{% else %}Failed — {{notes}}{% endif %} ``` ```plaintext {% for item in results limit:3 reversed %}{{item}} {% endfor %} ``` The [Liquid documentation](https://shopify.github.io/liquid/) covers the full tag syntax. ## Filters [Section titled “Filters”](#filters) The standard Liquid filters are available — `default`, `upcase`, `downcase`, `capitalize`, `append`, `prepend`, `replace`, `join`, `split`, `map`, `first`, `last`, `date`, `plus`, `minus`, `round`, and the rest: ```plaintext {{notes | default: "No notes recorded"}} ``` `default` earns its keep here: because unknown variables render as empty (see [Failure behaviour](#failure-behaviour)), it is the usual way to show something meaningful when a field is absent. ## Property access [Section titled “Property access”](#property-access) * A field name on its own reads that field from the merged data: `{{query}}`. * Dot access walks into nested objects, as deep as the data goes: `{{customer.email}}`. * A field whose name itself contains a dot needs bracket notation with the quoted name — `{{["ai.model"]}}` at the top level, or `{{request["ai.model"]}}` inside a nested object. Writing `{{ai.model}}` looks for a `model` field inside `ai` and renders empty. The bracket form works anywhere a field is referenced, including conditions. * Lists support `.first`, `.last`, `.size`, and integer indexes: `{{items[0]}}`. * Dots and indexes chain together: `{{items[0].title}}`. * Strings support `.size`, giving the length in characters. * Objects support `.size`, giving the number of keys. A missing key or an out-of-range index renders as empty rather than raising an error. ## Failure behaviour [Section titled “Failure behaviour”](#failure-behaviour) | Situation | What renders | | --------------------------------- | ----------------------------------------------------- | | Unknown variable or missing field | Nothing — the reference renders as empty text. | | Template does not parse | No summary is shown at all. | | Error while rendering | The summary shows `Summary render failed: `. | Rendering never fails the request that asked for the summary — the worst case is the fallback message in place of the summary text. ## Redacted values [Section titled “Redacted values”](#redacted-values) When a payload carries [sensitive](/platform/sensitive-data) values, a redacted field renders in templates as its redaction placeholder: `🔒` followed by the data-category labels, for example `🔒 personal_identifiers, contact_information`. A discarded value renders as `🔒 - discarded`. Conditions on a redacted field therefore test the placeholder, not the original value. The placeholder is a non-empty string, so `{% if email %}` is true for a redacted email and `{{email}}` prints the placeholder. When a viewer reveals sensitive values in the web app, the summary re-renders with the real values; API callers get the same choice through the `redacted` parameter on span queries. ## Related [Section titled “Related”](#related) * [Activity schema](/platform/concepts/activity-schema) — where span types and quality schemas are declared. * [Schemas and result schemas](/sdks/concepts-schemas) — declaring schemas from the SDKs. * [Quality evaluations](/sdks/quality-evaluations) — quality schemas and their templates, end to end. * [Sensitive data](/platform/sensitive-data) — how marked values are stored, redacted, and discarded. * [Liquid template language](https://shopify.github.io/liquid/) — the full syntax reference. # WebSocket API > Call the platform API over a persistent WebSocket connection, and receive live notifications when agent instances change. The WebSocket API gives you a persistent connection to the Prefactor platform API. The same operations as the [HTTP API](/api/http) are available over the socket, and the socket can also receive server-pushed notifications when agent instances change. This page lists the connection details, message format, methods, and error and close codes; [Stream agent instance updates](/api/stream-instance-updates) walks through a working subscription. The TypeScript and Python SDKs speak HTTP, not WebSocket — this API is for when you’re writing your own client. ## Connecting [Section titled “Connecting”](#connecting) The endpoint is `wss://app.prefactorai.com/api/v1/ws`. Authenticate by sending an `Authorization: Bearer ` header on the upgrade request, using an [API token](/platform/concepts/api-token) — create one from the [Account › API tokens tab](/admin-ui/account/api-tokens). Both account tokens and deployment tokens work; the token’s scope decides what you can call and subscribe to. The browser `WebSocket` API cannot set request headers, so browser code cannot authenticate directly. Use a client that can, such as the `ws` package in Node.js, or put a proxy in front that adds the header. A failed upgrade returns a plain HTTP response instead of opening the socket: | Status | Cause | | ------ | ----------------------------------------------------------------------- | | `400` | Not a WebSocket upgrade request, or a malformed `Authorization` header. | | `401` | Missing, invalid, or expired token. | ## Message format [Section titled “Message format”](#message-format) The socket speaks JSON-RPC 2.0 over text frames. Each request carries an `id`, which the response echoes back: ```json {"jsonrpc": "2.0", "id": 1, "method": "agents/list", "params": {}} ``` ```json {"jsonrpc": "2.0", "id": 1, "result": {"status": "success", "summaries": []}} ``` Prefactor also sends notifications, which have no `id` — see [Notifications](#notifications): ```json {"jsonrpc": "2.0", "method": "agent_instances/updated", "params": {"status": "success", "details": {"id": "01J..."}}} ``` Three rules to know: * Send text frames only. Binary frames are rejected with an `invalid_request` error. * JSON-RPC batch requests are not supported. * A message without an `id` is treated as a notification and ignored — no response, no effect. ## Methods [Section titled “Methods”](#methods) Method names follow the resources: `agents/list`, `agent_instances/register`, `risk_profiles/show`, and so on. Params and results match the corresponding HTTP operations in the [OpenAPI spec](/api/platform); the [OpenRPC spec](#openrpc-spec) lists every method name with its schema. Two methods are worth knowing on their own: | Method | Description | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `bulk/execute` | Runs several operations in one request. Params and result match [POST /bulk](/api/platform/operations/bulkexecute). | | `ping` | Returns details of the token you’re authenticated with. Also useful as a keepalive — see [Connection lifecycle](#connection-lifecycle). | One method is only available over WebSocket: | Method | Params | Result | | --------------------------- | ------------------------------------------------------------ | --------------------------------------------------------- | | `agent_instances/subscribe` | `agent_instance_id` (required), `idempotency_key` (optional) | `refs` — the records the connection is now subscribed to. | ## Notifications [Section titled “Notifications”](#notifications) After a successful `agent_instances/subscribe`, Prefactor pushes a notification each time the instance changes. Notifications are JSON-RPC messages with no `id`: | Method | Sent when | Params | | -------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `agent_instances/inserted` | The instance is created. | `details` — the full instance, in the same shape as [GET /agent\_instance/{agent\_instance\_id}](/api/platform/operations/queryagentinstancegetdetailsbyid). | | `agent_instances/updated` | The instance changes — status, span counts, and so on. | `details`, as above. | | `agent_instances/deleted` | The instance is deleted. | `id` of the deleted instance; the record itself no longer exists. | | `error` | Your token stops being valid. | `code` and `message` describing the failure. Prefactor closes the connection right after sending this — see [Connection lifecycle](#connection-lifecycle). | Notifications are filtered by the token’s permissions: if the token cannot see the instance, the notification is dropped rather than sent. Pushed notifications are not rate limited. ## Errors [Section titled “Errors”](#errors) Errors come back as JSON-RPC error objects. The top-level `code` is a JSON-RPC code; `data` carries the Prefactor error, in the same shape as an HTTP error response: ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32602, "message": "Agent instance not found", "data": {"status": "error", "code": "not_found", "message": "Agent instance not found"} } } ``` | Code | Meaning | | -------- | -------------------------------------------------------------------------------------------------------------------------- | | `-32700` | Parse error — the frame was not valid JSON. The connection is then closed with code `1007`. | | `-32600` | Invalid request — malformed JSON-RPC, a binary frame, or a batch request. | | `-32601` | The operation is not implemented. | | `-32602` | Invalid params, an unknown method name, or an application error such as `not_found`. `data.code` names the specific error. | | `-32603` | Internal server error. | | `-32000` | Rate limited. `data.retry_after_ms` says how long to wait before retrying — see [Rate limits](/api/rate-limits). | | `-32001` | Temporarily unavailable. | ## Connection lifecycle [Section titled “Connection lifecycle”](#connection-lifecycle) Prefactor does not send heartbeats. If you need to detect a dead connection, call `ping` on your own schedule. | Close code | Meaning | What to do | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | | `1000` | Normal close. | Reconnect if you still need the stream. | | `1007` | A frame contained malformed JSON. | Fix the payload, then reconnect. | | `1008` | Authentication is no longer valid — the token was revoked, suspended, or expired, or the account, environment, or deployment it belongs to was deleted. Prefactor sends an `error` notification before closing. | Re-authenticate with a valid token before reconnecting. | Nothing persists across connections. To resume after a reconnect, open a new socket and send `agent_instances/subscribe` again. Calls over the socket count against the same rate limits as HTTP requests — [Rate limits](/api/rate-limits) covers how they are applied. ## OpenRPC spec [Section titled “OpenRPC spec”](#openrpc-spec) The machine-readable spec for the WebSocket API is at . It lists every JSON-RPC method with its params and result schemas, including the WebSocket-only subscription and the server-pushed notifications. ## Related [Section titled “Related”](#related) * [API Reference](/api) — the section overview: transports, rate limits, and the operation reference. * [HTTP API](/api/http) — base URL, authentication, and error shapes for plain HTTPS calls. * [Rate limits](/api/rate-limits) — how limits are applied, and the shape of a limited response. * [API token](/platform/concepts/api-token) — account tokens and deployment tokens, and where to manage them. * [Instance](/platform/concepts/instance) — what an agent instance is. * [Stream agent instance updates](/api/stream-instance-updates) — subscribe to an instance and handle the notifications. # Prefactor CLI > Use the Prefactor CLI to manage accounts, environments, and agents from the terminal, in CI pipelines, or from inside a coding tool. The Prefactor CLI is the command-line tool for working with the Prefactor API without writing code. You can use it to query accounts, list environments, manage agents, and run bulk operations from any terminal. For interactive use, install the binary, run `prefactor login`, and use named profiles to switch between accounts. For automation, the CLI reads credentials from `PREFACTOR_API_TOKEN` so it works in CI and other non-interactive environments without a config file. Use an account-scoped token for admin and CLI automation; deployment-scoped tokens are for agent runtime SDKs. Commands that accept JSON payloads also accept a file path prefixed with `@` (`--items @./bulk-items.json`), which keeps large or repeated inputs in versioned files rather than inline. Coding tools like Cursor and Claude Code can invoke the CLI directly. The [agent skills](/cli/agent-skills) provide instruction files that tell those tools how to bootstrap Prefactor resources, instrument agents, and record risk data — covering the patterns that come up repeatedly when setting up a new integration. ## In this section [Section titled “In this section”](#in-this-section) * [Getting started](/cli/getting-started) — install the CLI, configure a profile, and run your first commands * [Configuration](/cli/configuration) — config file format, profiles, and environment variables * [Agent skills](/cli/agent-skills) — install skills that teach coding tools how to work with Prefactor # Agent skills The Prefactor agent skills are a set of instruction files that teach coding tools and AI agents how to work with Prefactor. Once installed, your coding tool can bootstrap Prefactor resources, instrument an existing agent, populate risk data on spans, and build custom provider adapters — without you having to explain the patterns each time. The skills live in the Prefactor TypeScript SDK repository but cover patterns that apply across any supported framework. ## What the skills cover [Section titled “What the skills cover”](#what-the-skills-cover) * **Bootstrap existing agent with Prefactor CLI** — provision the environment, agent, and instance resources via the CLI before adding instrumentation code. * **Instrument existing agent with Prefactor SDK** — add tracing for runs, LLM calls, tool calls, and failures to an agent that already works. * **Report agent risk data** — populate `data_risk` fields on span types for compliance tracking and data governance. * **Create provider package with core** — build a custom adapter on top of `@prefactor/core` when no built-in adapter exists for your framework. ## Install via the skills CLI [Section titled “Install via the skills CLI”](#install-via-the-skills-cli) ```bash bunx skills add https://github.com/prefactordev/typescript-sdk/ ``` This fetches the skills from the SDK repository and installs them into your coding tool’s local skills directory. ## Install via an agent [Section titled “Install via an agent”](#install-via-an-agent) If your tool does not support the skills CLI, paste the following into your agent as a prompt: ```text Clone the skills repo to a temporary folder, copy the skill folders, then delete the clone. 1) git clone https://github.com/prefactordev/typescript-sdk /tmp/prefactor-skills 2) Copy the folders into your coding tool's local skills directory: - /tmp/prefactor-skills/skills 3) Delete the temporary clone: rm -rf /tmp/prefactor-skills ``` The agent will run the steps and install the skills into the right place for your tool. # CLI configuration This page covers the config file, environment variables, and input conventions for the Prefactor CLI. ## Config file [Section titled “Config file”](#config-file) The CLI stores profiles in a `prefactor.json` file. Each top-level key is a profile name, and each profile has a single `api_key` field containing the [API token](/admin-ui/account/api-tokens) for that profile. ```json { "default": { "api_key": "pf_..." } } ``` ### Resolution order [Section titled “Resolution order”](#resolution-order) The CLI checks these locations in order and uses the first file it finds: 1. `/prefactor.json` — the CLI walks up from the current directory to find the git or worktree root 2. `/prefactor.json` — next to the installed binary If neither exists, creating a profile writes `/prefactor.json`. ## Environment variables [Section titled “Environment variables”](#environment-variables) If no matching profile is found, the CLI falls back to `PREFACTOR_API_TOKEN`. This is useful in CI or for short-lived runs where creating a config file is impractical. For day-to-day use, named profiles are more predictable. To select a profile by name without using the `--profile` flag, set `PREFACTOR_PROFILE=`. A profile authenticated with an account-level token has the same access scope as that token. Prefer deployment-scoped tokens when your CLI operations are limited to a single agent. ## Security [Section titled “Security”](#security) `prefactor.json` stores API tokens. Do not commit it to source control. The CLI attempts to add `prefactor.json` to `.gitignore` automatically when the config is local and the current directory is a git repository. Verify this manually in monorepos or with non-standard git setups: ```bash git check-ignore prefactor.json git status --short ``` ## JSON input from files [Section titled “JSON input from files”](#json-input-from-files) Commands that accept JSON payloads also accept a file path prefixed with `@`: ```bash prefactor bulk execute --items @./bulk-items.json prefactor agent_spans create --payload @./span.json ``` Use this to keep large payloads in versioned files rather than inline in shell history. ## Related [Section titled “Related”](#related) * [Getting started with the CLI](/cli/getting-started) — install and first-run walkthrough * [API tokens](/admin-ui/account/api-tokens) — create and manage the tokens your profiles use # Getting started with the CLI By the end of this page you’ll have the CLI installed, a profile configured, and your first commands running. ## Before you start [Section titled “Before you start”](#before-you-start) * A Prefactor account with at least one environment ## Install [Section titled “Install”](#install) **macOS or Linux:** ```bash curl -fsSL https://prefactor.tech/install.sh | bash ``` **Windows (PowerShell):** ```powershell irm https://prefactor.tech/install.ps1 | iex ``` The binary installs to `~/.prefactor/bin/prefactor` on macOS/Linux or `%USERPROFILE%\.prefactor\bin\prefactor.exe` on Windows. The installer prints the PATH change needed if the bin directory isn’t already on your path. ## Configure [Section titled “Configure”](#configure) ```bash prefactor login ``` This opens a browser to the Prefactor login page. After authenticating, copy your API token and paste it at the prompt. Credentials save to the `default` profile automatically. Select which profile a command uses with `--profile `. ## First run [Section titled “First run”](#first-run) ```bash # Verify access prefactor accounts list # List environments for your account prefactor environments list --account_id # List agents in an environment prefactor agents list --environment_id ``` ## Verify [Section titled “Verify”](#verify) `prefactor accounts list` should return your account. If you see an authentication error, run `prefactor login` again. ## Where to go next [Section titled “Where to go next”](#where-to-go-next) * [Configuration](/cli/configuration) — config file format, resolution order, and environment variables * [API tokens](/admin-ui/account/api-tokens) — create and manage the tokens your profiles use # Introduction > What Prefactor is, how the platform is structured, and where to find what you need. Prefactor records agent activity, classifies data risk from your activity schemas, and stores quality evidence you (or your eval pipeline) attach. You instrument agents with the SDK; every run is an [instance](/platform/concepts/instance) made up of [spans](/platform/concepts/span), one per step. Prefactor scores each instance against a configurable [risk profile](/platform/concepts/risk-profile), and quality evaluations attach to the instance (Prefactor also writes quality spans as an audit side-effect). The [web app](/admin-ui) is where you inspect runs, configure risk profiles, and review scores and quality results. ## From pilot to production [Section titled “From pilot to production”](#from-pilot-to-production) **Pilot.** Instrument your first agent with the SDK. You get span-level activity records — LLM calls, tool invocations, and agent spans — on the [Agents page](/admin-ui/agents) and the agent’s [Instances tab](/admin-ui/agent/instances). The default schema covers you at this stage; no custom schema or risk profile is required. The [Quickstart](/quickstart) walks through a demo end to end. **Adding structure.** Tighten [activity schema](/platform/concepts/activity-schema) definitions where you need clearer contracts. Once those definitions deploy, the web app shows conformance for each span type and flags gaps. Assign a [risk profile](/platform/concepts/risk-profile) so Prefactor classifies each run from the span types that ran and what those types declare. Declare quality schemas and start attaching evaluations when you need scored evidence on runs — see [Quality and performance](/platform/quality-and-performance). **Going to production.** Create a Production [environment](/platform/concepts/environment) alongside Development. Pin a version per environment with an [agent deployment](/platform/concepts/agent-deployment), and use a deployment-scoped [API token](/platform/concepts/api-token) for the runtime. Purpose labels (**Live**, **Eval**, **Smoke test**) keep evaluation traffic distinct from production. **Evidence and audit.** Every instance, span, schema version, risk classification, and attached quality payload is available for review — subject to what your integration sent under its capture and sampling settings. See [The audit trail](/platform/audit-trail). ## Concepts and explainers [Section titled “Concepts and explainers”](#concepts-and-explainers) * [Data model](/platform/data-model) — how account, agent, instance, span, and schema fit together. * [Risk](/platform/risk) — what Prefactor means by data risk. * [Sensitive data](/platform/sensitive-data) — marking, redaction, and discard. * [Quality and performance](/platform/quality-and-performance) — evaluations vs risk vs business performance. * [Instrumentation strategy](/platform/instrumentation-strategy) — how to grow schemas over time. * [Audit trail](/platform/audit-trail) — what the connected record contains. # The audit trail > How Prefactor produces a connected chain of evidence for every agent run — and what that chain contains. The record Prefactor keeps for each agent run is more than a log of what happened. Every run record is tied to the specific agent version that produced it, the activity schema version that governed it, the spans that make up its timeline, and — where a risk profile is assigned — the risk classification derived from those spans. When you attach a quality evaluation, that payload (and the quality spans Prefactor writes when it changes) is part of the same chain. Those connections are what make the record useful for review and not just for debugging. ## What gets recorded [Section titled “What gets recorded”](#what-gets-recorded) Every time an agent runs, Prefactor creates an [instance](/platform/concepts/instance) — a run record that accumulates everything that happened during that execution. The instance is the unit of record. Everything else hangs off it. Inside that instance, each step the agent takes is recorded as a [span](/platform/concepts/span): an LLM call, a tool invocation, a message sent or received. Each span can carry the inputs that went in, the outputs that came back, the time it took, and whether it succeeded or failed — subject to your SDK [capture and sampling settings](/sdks/configuration). Together, the spans form the activity timeline of the run. The instance record also carries what ties it to its context: the [agent version](/platform/concepts/agent#versions) that was running, the [activity schema](/platform/concepts/activity-schema) version that governed it, and the [environment](/platform/concepts/environment) it ran in. If the agent has a [risk profile](/platform/concepts/risk-profile) assigned, the risk classification for that run is recorded on the instance too, derived from the span types that ran and what those types declare. A [quality payload](/platform/quality-and-performance) on the instance, when present, is part of the same audit trail. Redaction of sensitive values applies only to values your integration marked. Unmarked payloads are stored as-is; see [Sensitive data](/platform/sensitive-data). ## How the records connect [Section titled “How the records connect”](#how-the-records-connect) The version record is the traceability anchor. Every instance points to the specific agent version that produced it, and that version does not change when a new version ships. A review conducted six months from now draws on exactly the same version record as one conducted today. The schema link is the conformance record. Each instance is tied to the activity schema version that was current when that run was registered. If a span’s payload diverged from the declared shape, Prefactor recorded the mismatch — it is part of the record, not hidden. You can see not just what happened but where the agent’s behaviour differed from what was declared. The risk classification is a calculated result, not a judgement made after the fact. It is derived from the spans in that run against the weights and thresholds in the assigned risk profile, and it is reproducible: given the same span-type counts and the same profile, the same classification follows. ## What stays fixed — and what can change [Section titled “What stays fixed — and what can change”](#what-stays-fixed--and-what-can-change) Prefactor does not re-score historical runs when a risk profile is updated, or re-validate past spans when a schema changes. Each run stays tied to the schema version and risk inputs under which it occurred. Some fields can still change after the run is first recorded: * **Discard sensitive** permanently removes stored sensitive values from a span while leaving redacted markers ([Sensitive data](/platform/sensitive-data)). * **Quality payloads** can be set, updated, or cleared independently for each named quality schema; each change is recorded as its own quality span. * **Lifecycle** transitions (including terminate) update the instance status; terminating a run also records the reason and signals the agent to stop. Capture, sampling, and payload length limits in the SDK also determine how complete the stored evidence is — see [Configuration](/sdks/configuration). ## What a review looks like in practice [Section titled “What a review looks like in practice”](#what-a-review-looks-like-in-practice) A compliance reviewer working in Prefactor would typically look at a specific agent’s instance list, filter to the relevant environment and time window, and open the instances that reached a risk level they care about. From there, the span timeline shows every step in sequence, with inputs and outputs as captured. The version and schema version for that instance are visible alongside it. The instance Quality tab shows any attached evaluations. If the reviewer needs to verify what the schema declared for a particular span type, the activity schema tab for that agent shows every version’s definitions. ## Further reading [Section titled “Further reading”](#further-reading) * [Instance](/platform/concepts/instance) — what an instance record contains and its lifecycle states. * [Span](/platform/concepts/span) — the individual steps recorded within an instance. * [Risk profile](/platform/concepts/risk-profile) — how risk classifications are calculated and what they mean. * [Activity schema](/platform/concepts/activity-schema) — how schema versions are created and what they declare. * [Quality and performance](/platform/quality-and-performance) — how quality evaluations attach to the record. * [Sensitive data](/platform/sensitive-data) — marking, redaction, and discard. # Account > What a Prefactor account is, what it contains, and where to find it in the platform. An account is the top-level boundary in Prefactor — it maps to your organisation. Every agent, environment, team member, and API token in Prefactor belongs to an account. When you sign in, you land inside one. Nothing crosses that boundary: activity, audit history, and configuration are all scoped to the account you are in. Projects, teams, and products all sit inside the same account. Inside an account, you manage [agents](/platform/concepts/agent), the [environments](/platform/concepts/environment) that separate your lifecycle stages, and the [risk profiles](/platform/concepts/risk-profile) that classify the data risk of your agents’ runs. You control who can access the account through team membership and pending invitations, and you create the [API tokens](/platform/concepts/api-token) that let your integrations authenticate with Prefactor. ## In the web app [Section titled “In the web app”](#in-the-web-app) * [Account › Details tab](/admin-ui/account/details) — the account’s name and ID, with links to the other account settings tabs. * [Account › Team tab](/admin-ui/account/team) — members currently in the account. * [Account › Invites tab](/admin-ui/account/invites) — pending invitations. * [Account › API tokens tab](/admin-ui/account/api-tokens) — tokens for programmatic access. * [Account › Environments tab](/admin-ui/account/environments) — the environments configured for this account. ## Related concepts [Section titled “Related concepts”](#related-concepts) * [Agent](/platform/concepts/agent) — agents belong to the account and are visible across all its environments. * [Environment](/platform/concepts/environment) — environments live inside an account and separate lifecycle stages. * [Risk profile](/platform/concepts/risk-profile) — risk profiles are configured at the account level and assigned to individual agents. * [API token](/platform/concepts/api-token) — tokens authenticate integrations with Prefactor; both account-wide and deployment-scoped tokens belong to the account. # Activity schema > What an activity schema is in Prefactor, why span types and payload definitions exist, how versioning works, and where to review schemas in the platform. An activity schema tells Prefactor what shape of work to expect from an [agent](/platform/concepts/agent) — it names the span types the agent emits and declares the expected structure of each type’s inputs and outputs. Every span type your agent records must have payload and result definitions in that agent’s activity schema — there is always a schema for each type, even when it is effectively wide open. Integration defaults are usually permissive: they allow extra fields you did not list so you can start tracing without pinning every property up front; you can tighten definitions when your instrumentation stabilises. That contract still lives in the platform: everyone reviewing a run can see which fields belong to a user turn, an assistant turn, or a given tool call, and when a payload diverges from what you declared, Prefactor surfaces that for review instead of leaving you to spot drift by hand. The definitions for an agent cover one or more span types — for example `user_message` and `assistant_message` for conversation, plus a separate type for each tool you instrument (such as `web_search` and `read_file`), with shapes that match that tool’s arguments and results. For each type, the schema holds two definitions: one for the span payload (what went in) and one for the result (what came back). Schemas describe the shape of the data rather than enforcing it at runtime. Those definitions are also what let you organise and make sense of what your agent recorded. Prefactor records every span your integration sends, whether or not it matches the declared shape. A mismatch does not stop a run; it is visible so you can tighten instrumentation or adjust the schema deliberately. Besides span types, a schema version can declare one or more named quality schemas: each names the shape of a quality evaluation payload that can be attached to an [instance](/platform/concepts/instance) after it runs, with an optional template that renders the payload as a one-line summary. See [Quality and performance](/platform/quality-and-performance) for how evaluations work. Span types can carry a template too: a `template` field on the span type renders the one-line summary shown for each span in the activity timeline. Templates are Liquid, rendered server-side; see [Summary templates](/api/summary-templates) for the language. ## Versioning [Section titled “Versioning”](#versioning) Activity schemas belong to a single agent and are versioned over time. Prefactor creates a new schema version on demand: when an instance arrives with a schema not seen before for that agent, a new version is recorded automatically — the same mechanism that creates new [agent versions](/platform/concepts/agent). You do not push schema versions explicitly; they appear as a side-effect of runs arriving with new definitions. Reviewers can see which environments use which version. Each [instance](/platform/concepts/instance) is tied to the activity schema version it was registered with — that is the version Prefactor uses to interpret and validate spans for that run, regardless of what changes afterward. ## In the web app [Section titled “In the web app”](#in-the-web-app) * [Agent › Activity schema tab](/admin-ui/agent/activity-schemas) — every schema version, span type, payload and result definitions, and validation status for the agent. ## Related concepts [Section titled “Related concepts”](#related-concepts) * [Agent](/platform/concepts/agent) — each agent owns its activity schema versions. * [Span](/platform/concepts/span) — span types and payloads are defined by the activity schema. * [Instance](/platform/concepts/instance) — each run is tied to the activity schema version supplied when that instance was registered. # Agent > What an agent is in Prefactor, how it relates to instances, environments, and your account, and where to see it in the platform. An agent is an AI agent you have connected to Prefactor — a conversational assistant, an automated workflow, a retrieval pipeline, or any other AI system whose behaviour you want to govern. Every agent has a stable identity in the platform. That identity is the anchor for everything Prefactor tracks on its behalf: the runs it produces, the versions it has, the [activity schema](/platform/concepts/activity-schema) that describes its span types and payloads, the [risk profile](/platform/concepts/risk-profile) that governs how the data risk of its runs is classified, and the [agent deployments](/platform/concepts/agent-deployment) that deploy specific versions to specific environments. Without that anchor, spans and instances would be floating data with no way to compare behaviour over time or tie a compliance review to a specific agent. An agent belongs to your [account](/platform/concepts/account), not to any single environment. You register an agent once; it then shows up in every environment where it produces runs. Each run is recorded as an [instance](/platform/concepts/instance) under that agent, against the version specified when the run was started. Registering an agent in the platform creates the named entry. At runtime, your integration identifies itself with an [API token](/platform/concepts/api-token): a deployment-scoped token embeds the agent and environment, so the SDK can omit those identifiers; an account-scoped token requires you to supply the agent identity explicitly (for example `PREFACTOR_AGENT_ID`). ## Lifecycle [Section titled “Lifecycle”](#lifecycle) An agent moves through a small set of lifecycle states: * **Pending** — registered in Prefactor, with no instances yet. * **Active** — Prefactor has recorded at least one instance for the agent. ## Versions [Section titled “Versions”](#versions) Each agent accumulates a history of versions. Prefactor creates a version on demand: when an instance arrives reporting a combination of metadata and schema not seen before for that agent, a new version is created automatically — the same mechanism that creates new [activity schema](/platform/concepts/activity-schema) versions. The external identifier reported with the instance (a semver tag, a commit SHA, or any string your deployment uses) becomes the version’s name. Versions exist for traceability. Every instance is tied to the version it ran under, and every version is paired with the activity schema version registered alongside it, so you can always trace a run back to the exact code and schema that produced it. When you deploy a version to an environment, Prefactor records that as an [agent deployment](/platform/concepts/agent-deployment). The Versions tab shows which environments each version is currently deployed in. ## In the web app [Section titled “In the web app”](#in-the-web-app) * [Agents page](/admin-ui/agents) — the full list of agents in your account, with a 24-hour activity summary. * [Agent page](/admin-ui/agent) — identity, the 24-hour activity timeline, deployment snapshot across environments, and how the tabs fit together. * [Agent page › Overview tab](/admin-ui/agent/overview) — instance counts by state and recent spans with drill-through to instances. * [Agent page › Versions tab](/admin-ui/agent/versions) — the full version history for an agent, with schema version associations and deployment status. ## Related concepts [Section titled “Related concepts”](#related-concepts) * [Account](/platform/concepts/account) — the boundary that owns agents, environments, and team access. * [Activity schema](/platform/concepts/activity-schema) — describes each agent’s span types and payloads; each version is paired with an activity schema version. * [Agent deployment](/platform/concepts/agent-deployment) — deploys a specific version to an environment as the current release. * [API token](/platform/concepts/api-token) — deployment tokens carry agent identity at runtime; account tokens require you to pass it. * [Instance](/platform/concepts/instance) — a single run of an agent; every run is attributed to one agent and one version. * [Environment](/platform/concepts/environment) — controls which activity is visible, not which agents exist. * [Risk profile](/platform/concepts/risk-profile) — risk profiles are assigned to agents and classify the data risk of their runs. # Agent deployment > What an agent deployment is in Prefactor, how it records the current version deployed to an environment, and where to manage deployments. An agent deployment is the record that a specific version of an agent is the current release in a specific environment. When you ship a new version of your agent to production, you update the agent deployment for that environment to point to the new version. The deployment record says: “in this environment, this version is what’s running.” That makes it explicit and reviewable — anyone inspecting the platform can see exactly which version is live in each environment at any given time, and when it was last updated. Environments can carry different versions simultaneously, so staging and production can diverge deliberately rather than by accident. An agent deployment sits at the intersection of three concepts: the [agent](/platform/concepts/agent) it belongs to, the [version](/platform/concepts/agent#versions) it points to, and the [environment](/platform/concepts/environment) it covers. There is at most one active deployment per agent per environment. Updating a deployment — deploying a newer version — is tracked with a timestamp, so the history of what ran where is always available. Agent deployments are distinct from deployment tokens. A [deployment token](/platform/concepts/api-token) is a credential scoped to one agent in one environment; it carries the agent identity at runtime so your SDK does not need to supply it separately. The token and the deployment record are related — a deployment token is issued for a specific deployment — but the token is a secret used for authentication, while the deployment record is the platform’s statement of which version is current. ## In the web app [Section titled “In the web app”](#in-the-web-app) * The deployment snapshot on the [Agent page](/admin-ui/agent#deployment-snapshot) — the current version deployed to each environment and controls to update it. * [Agent › Deployments tab](/admin-ui/agent/deployments) — deployment-scoped tokens for each agent deployment. ## Related concepts [Section titled “Related concepts”](#related-concepts) * [Agent](/platform/concepts/agent) — agent deployments belong to an agent; each agent accumulates deployments across its environments. * [Environment](/platform/concepts/environment) — each deployment covers one environment; environments can be on different versions at the same time. * [API token](/platform/concepts/api-token) — deployment tokens are scoped to one agent deployment and carry its identity at runtime. # API token > What API tokens are in Prefactor, the difference between account tokens and deployment tokens, and where to manage them. An API token is the credential your integration uses to authenticate with Prefactor — it is how a running agent proves to the platform which account it belongs to and, in the case of a deployment token, which agent it is. Account tokens and deployment tokens are the two scopes you should use day to day. Choosing the right one depends on what you need to identify at runtime. Environment-scoped tokens may still appear in the web app from older or programmatic creation; they are not creatable there. ## Account tokens [Section titled “Account tokens”](#account-tokens) An account token grants access to the whole account. Any SDK or script authenticated with one can send activity for any agent in the account and read data across all of them via the API. You pass the agent identity separately when using an account token — the token itself says nothing about which agent is running. Account tokens are suited to scripts, CI pipelines, or administrative access where you need account-wide reach rather than agent-specific identity. ## Deployment tokens [Section titled “Deployment tokens”](#deployment-tokens) A deployment token is scoped to a single [agent deployment](/platform/concepts/agent-deployment) — one agent in one environment. The agent identity is built into the token, so an SDK authenticated with one does not need to pass an agent identifier — Prefactor knows which agent the activity belongs to from the token alone. This is the recommended way to instrument a deployed agent, because it ties the running code to a specific agent and environment without any extra configuration. ## Environment-scoped tokens [Section titled “Environment-scoped tokens”](#environment-scoped-tokens) Environment-scoped tokens may appear in the [Account › API tokens tab](/admin-ui/account/api-tokens) if they were created programmatically or through a legacy flow. There is no interface in the web app to create new ones. Prefer account tokens for admin and CLI access, and deployment tokens for agent runtimes. All creatable token types go through the same lifecycle: **Active** tokens authenticate requests; a token can be **Suspended** (disabled but recoverable) or **Revoked** (permanently invalidated). Revoked tokens can then be deleted. ## In the web app [Section titled “In the web app”](#in-the-web-app) * [Account › API tokens tab](/admin-ui/account/api-tokens) — create and manage account-wide tokens, view all tokens associated with the account. * [Agent › Deployments tab](/admin-ui/agent/deployments) — create and manage deployment-scoped tokens for a specific agent. ## Related concepts [Section titled “Related concepts”](#related-concepts) * [Account](/platform/concepts/account) — tokens belong to an account and are managed from account settings. * [Agent](/platform/concepts/agent) — deployment tokens carry the agent identity and are the recommended way to instrument a deployed agent. * [Agent deployment](/platform/concepts/agent-deployment) — deployment tokens are issued for a specific agent deployment and carry its identity at runtime. * [Environment](/platform/concepts/environment) — deployment tokens are scoped to one agent in one environment. # Environment > What an environment is in Prefactor, how it filters activity and deployments, and where to see it in the platform. An environment is a named delivery stage — development, staging, production, or similar — configured at the [account](/platform/concepts/account) level and shared across all agents in that account. Environments give each [agent](/platform/concepts/agent) a set of stages to track independently. For each agent, a [deployment](/platform/concepts/agent-deployment) records which version is current in each environment; different stages can be on different versions at the same time. Each [instance](/platform/concepts/instance) is attributed to the environment the agent reported when the run started, so activity from different stages is always kept separate. ## In the web app [Section titled “In the web app”](#in-the-web-app) * [Account › Environments tab](/admin-ui/account/environments) — create and manage environments. * The deployment snapshot on the [Agent page](/admin-ui/agent#deployment-snapshot) — which version is deployed per environment. ## Related concepts [Section titled “Related concepts”](#related-concepts) * [Account](/platform/concepts/account) — environments are configured within an account and are visible across all its agents. * [Agent](/platform/concepts/agent) — agents belong to the account; environments determine the lens through which you view their activity. * [Agent deployment](/platform/concepts/agent-deployment) — records which version of an agent is current in a given environment. * [Instance](/platform/concepts/instance) — instances are attributed to the environment the agent reported when the run started. # Instance > What an agent instance is in Prefactor, its lifecycle states, how it relates to spans and versions, and where to see it. An instance is a single run of an agent from start to finish — one discrete execution, tracked by Prefactor as a unit. Every time your agent runs, Prefactor creates an instance record. That record collects everything that happened during that run: the [spans](/platform/concepts/span) produced (each LLM call, tool invocation, or sub-agent execution), the [agent version](/platform/concepts/agent#versions) that was running, the [environment](/platform/concepts/environment) it ran in, and the lifecycle state the run reached. The instance is the level at which risk is assessed — if the agent has a risk profile, the risk classification for that run is attributed to the instance, derived from its spans. An instance moves through a set of states as it runs. It starts as **Pending**, becomes **Active** once running, and finishes as **Complete**, **Failed**, **Cancelled**, or **Terminated** depending on how it ends. Complete, Failed, and Cancelled come from the agent itself: the run finishes, fails, or is cancelled before it starts. **Terminated** means the run was stopped from outside — by someone on your team, from the web app or through the API. Termination always carries a reason, which is recorded on the instance and in the [audit trail](/platform/audit-trail), and a terminated run counts as a failure in [quality statistics](/platform/quality-and-performance). Only an active run can be terminated, and an agent cannot terminate its own run — its API token doesn’t carry that permission. Termination is cooperative rather than a hard kill. Prefactor signals the running agent to stop, and the agent’s integration winds the run down; until it does, Prefactor keeps accepting its spans. Prefactor never terminates a run on its own schedule — there are no idle timeouts or run-duration limits. Each instance also records a purpose — why the run happened. **Live** (`live`) is a real run (the default), **Eval** (`eval`) is an evaluation run, and **Smoke test** (`smoke_test`) is a pipeline check. The integration sets the purpose when it registers the run, and it is shown wherever the instance appears, so evaluation traffic never masquerades as production traffic. Each instance contains exactly the spans that were recorded during that run. The spans it contains and how detailed they are depend on the choices made by the team building the agent — what they chose to instrument and at what granularity. After the run, an instance can carry a quality payload for each named quality schema declared in the agent’s [activity schema](/platform/concepts/activity-schema) — the result of evaluating that run against that schema. Each payload is set through the SDK or the API, and every change to it is recorded as its own quality span within the instance, so the evaluation history is part of the run’s record. See [Quality and performance](/platform/quality-and-performance) for how evaluations work. ## In the web app [Section titled “In the web app”](#in-the-web-app) * [Agent instance page](/admin-ui/agent-instance) — terminate an active run from the strip above the tabs, reason required. * [Agent › Instances tab](/admin-ui/agent/instances) — the per-agent table of every run, filterable by environment and status. * [Agent › Instance › Details tab](/admin-ui/agent-instance/details) — lifecycle timestamps and metadata for a single run. * [Agent › Instance › Activity tab](/admin-ui/agent-instance/activity) — the full span hierarchy for a single run. * [Agent › Instance › Quality tab](/admin-ui/agent-instance/quality) — the quality evaluations attached to a single run. * [Agent › Instance › Risk tab](/admin-ui/agent-instance/risk) — the risk classification and contributors for a single run. * [Agent › Versions tab](/admin-ui/agent/versions) — each instance records the agent version it ran under. ## Related concepts [Section titled “Related concepts”](#related-concepts) * [Agent](/platform/concepts/agent) — every instance belongs to one agent. * [Activity schema](/platform/concepts/activity-schema) — each instance is tied to the activity schema version supplied when that run was registered. * [Span](/platform/concepts/span) — the individual steps recorded within an instance. * [Environment](/platform/concepts/environment) — instances are attributed to the environment the agent reported when the run started. * [Risk profile](/platform/concepts/risk-profile) — risk classification is calculated and displayed at the instance level. # Risk profile > What a risk profile is in Prefactor, how it classifies the data risk of an agent's runs, and where to manage profiles. A risk profile is a configuration assigned to an agent that tells Prefactor how to classify the data risk of each run it produces. You build a profile by setting weights for categories of data — personal identifiers, financial information, health records, and similar — multipliers for types of actions performed, and thresholds that map an aggregated score to a risk level: Low, Medium, High, or Critical. Once a profile is assigned to an [agent](/platform/concepts/agent), every [instance](/platform/concepts/instance) that agent produces gets a risk classification derived from the [spans](/platform/concepts/span) in that run. Risk profiles belong to the [account](/platform/concepts/account) and can be assigned to as many agents as you like. One profile can serve as the baseline across many agents; individual agents can each have their own when the data they handle warrants different thresholds. ## How risk is scored [Section titled “How risk is scored”](#how-risk-is-scored) Each span type in the activity schema declares which data categories and actions it can touch. Prefactor scores that declaration by summing, for every included category and allowed action, `category weight × action multiplier`. A span type that declares several categories or actions therefore scores higher than one that declares only a single pair. For an [instance](/platform/concepts/instance), Prefactor multiplies each span type’s score by how many spans of that type ran in the run, then sums those contributions. The instance’s risk level is whichever band contains that total score. For example, a span type that reads Personal identifiers (weight 8) and Contact information (weight 4) under the Read data multiplier of 1.0 scores `8 × 1.0 + 4 × 1.0 = 12` per invocation. Three such spans contribute `36` to the instance total. A second span type scoring `5` once adds `5`, for a total of `41`. If `41` falls in the Medium band configured in the profile, the instance is classified Medium. Profiles also define **agreed risk** — which actions are allowed and which data categories are in scope. Prefactor compares an agent’s declared capabilities against that agreement and flags anything that exceeds it on the [Agent Overview tab](/admin-ui/agent/overview). Crossing a threshold does not automatically block or terminate a run. The classification is a label shown in the platform for human review — enforcement remains with your team. ## In the web app [Section titled “In the web app”](#in-the-web-app) * [Risk page](/admin-ui/risk) — create and manage profiles, and review thresholds, agreed risk, category scores, multipliers, and which agents use a profile. ## Related concepts [Section titled “Related concepts”](#related-concepts) * [Account](/platform/concepts/account) — risk profiles belong to the account and can be reused across agents. * [Agent](/platform/concepts/agent) — risk profiles are assigned to agents; an agent with a profile will have its instances classified. * [Instance](/platform/concepts/instance) — risk classification is calculated and displayed at the instance level. * [Span](/platform/concepts/span) — each span contributes to the instance’s risk score via the categories and actions its span type declares. # Span > What a span is in Prefactor, how span types are defined, and where to see spans in the platform. A span is the atomic record of a single step inside an agent run — one discrete unit of work that Prefactor captures as its own record within an [instance](/platform/concepts/instance). Spans are the activity record of a run. When Prefactor records a run, it records each step as a span: the input that went in, the output that came back, how long it took, and whether it completed or failed. Together, the spans form the activity timeline of the instance — you can read the sequence as a narrative of what the agent did and in what order. That timeline is also the basis for [risk scoring](/platform/concepts/risk-profile#how-risk-is-scored): each span contributes to the instance’s risk classification by way of the risk profile assigned to the [agent](/platform/concepts/agent). Quality evaluation is separate — see [Quality and performance](/platform/quality-and-performance). Spans can be nested — a parent span can contain child spans, with the hierarchy preserved in the activity timeline. This allows business-level actions to be recorded alongside the lower-level calls that compose them, giving reviewers both the intent and the detail in a single record. Span types are defined by the agent’s [activity schema](/platform/concepts/activity-schema) — they can represent anything the team building the agent decides to instrument: for example `user_message` and `assistant_message` for chat turns, or separate types per tool (such as `web_search` and `read_file`) so each definition matches that tool’s inputs and outputs. Each type must have payload and result definitions in that activity schema; those can be strict or broadly permissive. If a span’s payload does not match the declared shape, the mismatch is recorded and flagged for review. The span still records regardless. Span payloads can carry [sensitive values](/platform/sensitive-data). When the integration marks a value as sensitive, Prefactor stores it separately from the rest of the span, redacts it by default in the web app, and can permanently discard it while keeping the rest of the record intact. Not every span is agent activity. Each span has a purpose — **activity** for the steps the agent performed, or **quality** for evaluation records. Prefactor writes a quality span into the instance whenever a named quality payload changes, using that quality schema’s name as the span type; your integration cannot create these directly, and they are excluded from activity metrics. ## In the web app [Section titled “In the web app”](#in-the-web-app) * [Agent › Instance › Activity tab](/admin-ui/agent-instance/activity) — the full span timeline for a single run, with inputs, outputs, duration, and status. ## Related concepts [Section titled “Related concepts”](#related-concepts) * [Instance](/platform/concepts/instance) — spans belong to an instance; the instance is the unit of a run. * [Activity schema](/platform/concepts/activity-schema) — declares the expected structure for each span type and surfaces conformance gaps. * [Risk profile](/platform/concepts/risk-profile) — spans drive the data-risk calculation for their instance. * [Sensitive data](/platform/sensitive-data) — how marked values in span payloads are stored, redacted, and discarded. # Data model > How the nine platform concepts relate to each other — containment, lifecycle, and the connections between them. ```plaintext Account ├── Environments (one or more named delivery stages) ├── Risk profiles (reusable, assignable to agents) └── Agents (one or more; each spans all environments) ├── Versions (created automatically on new runs) ├── Activity schema (one per agent, versioned automatically) │ └── Span type definitions (payload + result per type) ├── Agent deployments (one per environment; points to a version) └── Instances (one per run) └── Spans (one per instrumented step) ``` The [account](/platform/concepts/account) is the outer boundary. Everything in Prefactor belongs to an account — agents, environments, risk profiles, and all the runtime data they produce. Nothing crosses that boundary. ## The agent layer [Section titled “The agent layer”](#the-agent-layer) [Agents](/platform/concepts/agent) belong to the account, not to any particular environment. An agent is a stable identity that persists across environments and versions. Three further concepts describe the configuration of an agent — what version it is on, what schema governs its spans, and where it is deployed: [Versions](/platform/concepts/agent#versions) are created automatically. When a run arrives with a combination of metadata not seen before for that agent, Prefactor creates a new version record. The [activity schema](/platform/concepts/activity-schema) belongs to one agent and accumulates versions by the same mechanism. Each version declares the span types the agent emits and the expected shape of their payloads and results. [Agent deployments](/platform/concepts/agent-deployment) record which version is the current release in each environment. There is at most one active deployment per agent per environment. Environments can be on different versions simultaneously. ## The runtime layer [Section titled “The runtime layer”](#the-runtime-layer) [Environments](/platform/concepts/environment) are named stages — development, staging, production, or whatever your organisation uses. Each instance is attributed to the environment the agent reported when the run started. An [instance](/platform/concepts/instance) is a single run from start to finish. It is stamped with the agent, the version, the activity schema version, and the environment. If the agent has a risk profile, the instance also carries the risk classification for that run. [Spans](/platform/concepts/span) are the individual steps recorded within an instance. Each span has a type, a payload, a result, a duration, and a status. Spans belong to exactly one instance and are created by the SDK as the agent runs. ## The risk layer [Section titled “The risk layer”](#the-risk-layer) A [risk profile](/platform/concepts/risk-profile) belongs to the account and can be assigned to any number of agents. Prefactor uses the profile’s weights, multipliers, and thresholds to calculate a risk classification for every instance that agent produces. One profile can cover many agents; individual agents can each have their own. ## Further reading [Section titled “Further reading”](#further-reading) * [Instrumentation strategy](/platform/instrumentation-strategy) — how instrumentation choices shape the runtime layer. * [The audit trail](/platform/audit-trail) — how the connections between records support compliance review. # Instrumentation strategy > The theory behind what to instrument in an AI agent, why span granularity matters, and how schema design shapes what Prefactor can score. Prefactor records what the SDK sends. Which steps you choose to instrument, at what level of detail, and with what declared schema determines what the platform can surface, validate, and score. ## What makes a span worth instrumenting [Section titled “What makes a span worth instrumenting”](#what-makes-a-span-worth-instrumenting) A span is worth recording when it represents a discrete, meaningful unit of work with identifiable inputs and outputs. “The agent processed a request” is too coarse to be useful. “The agent called the web search tool with this query and received these results” is specific enough to inspect, validate, and score. A useful test: would this span give a reviewer a clear picture of what happened at this step? Steps left uninstrumented are gaps in the record that cannot be filled in later. Over-instrumentation is also a problem. Wrapping every internal function call produces noise that obscures the meaningful record. The right granularity is usually aligned with the conceptual steps in the agent’s work — a conversation turn, a tool call, a sub-agent invocation — not streaming chunks or retries inside a library. ## Nesting spans for business context [Section titled “Nesting spans for business context”](#nesting-spans-for-business-context) Spans can be nested: a parent span can contain child spans, with the hierarchy preserved in the activity timeline. Rather than recording only the raw API calls an agent makes, you can wrap a group of related calls in a parent span that names the business-level action they collectively represent. An agent researching a competitor might make several web searches and an LLM summarisation call — all of which can sit inside a `research_competitor` span that makes the intent explicit. A reviewer reading the timeline sees both the high-level action and the steps that composed it. A parent span can carry its own type and payload, allowing the business action to be classified for risk independently of its constituent calls. ## Per-tool span types [Section titled “Per-tool span types”](#per-tool-span-types) A common shortcut is using a single generic span type for all tool calls — something like `tool_call` with a payload containing `tool_name` and arguments. The problem is that the [activity schema](/platform/concepts/activity-schema) can then only declare one shape to cover all tools, which means it cannot validate any of them precisely. A `web_search` call has a different shape from `read_file`, which has a different shape from `send_email`; a schema that tries to accommodate all three ends up either too permissive to validate anything, or too narrow to cover the others. Giving each tool its own span type allows the schema to declare the exact expected shape for each one. Payload validation can flag deviations specific to that tool, and risk scoring can apply the appropriate action type for each — the consequence of `send_email` is different from `read_file`, and that distinction requires separate types. ## Permissive vs strict schema definitions [Section titled “Permissive vs strict schema definitions”](#permissive-vs-strict-schema-definitions) Every span type has a payload definition and a result definition. These can be strict — listing exactly which fields are expected — or permissive, allowing extra or unknown fields through without flagging them. A strict schema catches drift early but requires your instrumentation to be stable first. A permissive schema lets you start recording without constraining yourself, but provides no conformance signal. The practical approach is to start permissive and tighten over time. When you first instrument a span type, you may not know the full shape of its payloads. Recording with a permissive schema gives you real payload data to inspect. Once the shape stabilises, you update the schema to reflect what you actually expect — from that point, any deviation is flagged. What’s a schema version? Prefactor creates a new [activity schema](/platform/concepts/activity-schema) version automatically when a run arrives with definitions that differ from the current version. You do not push schema versions explicitly — they appear as a side-effect of runs arriving with updated definitions. ## Schema granularity and risk scoring [Section titled “Schema granularity and risk scoring”](#schema-granularity-and-risk-scoring) The more precisely a schema declares span types, data categories, and actions, the more Prefactor can validate and the more precisely it can score for risk. [Risk profiles](/platform/concepts/risk-profile) score each span type from those declarations, then multiply by how many spans of that type ran. A span type that declares which categories and actions it can exercise allows a clear risk assessment. A permissive or incomplete schema leaves span types unassessed or coarsely declared — Prefactor does not infer categories by inspecting live payload contents. ## Further reading [Section titled “Further reading”](#further-reading) * [Activity schema](/platform/concepts/activity-schema) — how schema versions are created and what they validate. * [Span](/platform/concepts/span) — the unit of instrumentation and what each span record contains. * [Risk profile](/platform/concepts/risk-profile) — how declared span-type capabilities feed into risk scoring. # Quality and performance > What quality and business performance mean for AI agents, how Prefactor records quality evaluations, and how they differ from risk. Risk tells you which declared data categories and actions a run exercised (from the activity schema and span-type counts). Quality and performance tell you whether the agent actually did its job well. These are different questions — a governance review asks the first; a business review asks the second — and an agent can score well on one while failing the other. ## Quality [Section titled “Quality”](#quality) Quality for an AI agent is whether it produces outputs that are accurate, relevant, and useful given what was asked of it. This is harder to define than correctness in traditional software, where a function either returns the right result or it does not. An agent’s outputs are often natural language, judgement calls, or sequences of decisions that only make sense in context — and evaluating them requires knowing what “right” looks like for that task. Reliability is part of quality: whether runs complete, whether tool calls succeed, whether the agent stays on task. These are the technical foundations on which usefulness depends. An agent that fails half its runs is not a performance problem — it is a quality problem. Prefactor summarises these signals per agent — success rates, duration distributions, and failure counts over the last day — on the agent’s Quality tab. The harder half of quality — whether an output was actually good — cannot be read off a trace, because it depends on knowing what the task was. Prefactor does not judge your agent’s outputs; its role is to record the judgement you make. You define what a quality evaluation looks like for your agent, evaluate runs however suits you, and attach the result to each run. ## Recording quality evaluations [Section titled “Recording quality evaluations”](#recording-quality-evaluations) Because “good” means something different for every agent, the shape of a quality evaluation is yours to define. An agent’s [activity schema](/platform/concepts/activity-schema) can include one or more named quality schemas — each a JSON Schema describing an evaluation payload for that agent’s runs (a score and a verdict, a set of rubric fields, whatever your evaluation produces), plus an optional template that renders the payload as a one-line summary. Naming lets one agent carry several kinds of evaluation at once — a summary-quality schema and a policy-compliance schema, for example — evaluated and recorded independently. The evaluation itself happens outside Prefactor, and usually after the run: an automated eval suite, a model grading the output, or a person reviewing it. Whatever produces the judgement, it attaches the result to the [instance](/platform/concepts/instance) as a quality payload for the matching schema name, through the SDK or the API. Prefactor renders the summary from that schema’s template and shows both on the instance’s Quality tab. Quality payloads are part of the audit trail, not just a mutable field. Every time a named quality payload is set, changed, or cleared, Prefactor records the change as a [span](/platform/concepts/span) within that instance — a quality span, written by the platform itself and kept apart from the agent’s own activity. The evaluation history of a run is reconstructable from its span record, the same way the run itself is. ## Eval runs and live runs [Section titled “Eval runs and live runs”](#eval-runs-and-live-runs) Once you evaluate runs routinely, not every run is production traffic. Each instance records a purpose: **Live** for a real run, **Eval** for an evaluation run, or **Smoke test** for a pipeline check. Your integration sets the purpose when the run is registered; it defaults to Live. The purpose is shown wherever the instance appears, so evaluation traffic is distinguishable from the traffic it is meant to protect. ## Performance [Section titled “Performance”](#performance) Performance is whether the agent, as a whole, is delivering the business value it was put in place to deliver — not whether any individual output was correct, but whether the initiative is working. Prefactor does not compute a business performance score. What it provides is a continuous run history (and the quality evaluations attached to it) against which you assess change outside the product: across many runs, over time, against the outcomes the agent was intended to drive. ## Tracking change over time [Section titled “Tracking change over time”](#tracking-change-over-time) Agents change for reasons that are not always obvious or deliberate. The underlying model may be updated by the provider. Code or prompts may be revised. The way people interact with the agent shifts as it becomes familiar. Any of these can affect quality and performance — and without a continuous record, it is hard to know whether something changed, when it changed, or what caused it. Prefactor’s run history — and the quality evaluations attached to it — gives you a continuous record against which change becomes visible. When something shifts, for better or worse, you have the before and after to compare. ## Further reading [Section titled “Further reading”](#further-reading) * [Record quality evaluations](/sdks/quality-evaluations) — declare quality schemas and submit payloads from the SDKs. * [Agent page › Quality tab](/admin-ui/agent/quality) — success, duration, and failure signals for an agent over the last day. * [Agent › Instance › Quality tab](/admin-ui/agent-instance/quality) — the rendered evaluation for a single run. * [Risk](/platform/risk) — the separate question of declared capabilities exercised in a run. * [Instance](/platform/concepts/instance) — the run-level record, including purpose, lifecycle state, and version. # Risk > What risk means in the context of AI agents, and how Prefactor thinks about assessing it. Data risk classification is a standard part of enterprise software governance. What makes AI agents different is not that they introduce risk where none existed before, but that their risk profile is harder to assess statically — and that new categories of risk emerge from their non-deterministic nature. A traditional software system that queries a database does so in a way that is mostly fixed at design time — you can read the code and know what it accesses. An AI agent makes decisions dynamically: which tools it calls, what data it retrieves, what actions it takes. Two runs of the same agent on different inputs can touch entirely different categories of data and take entirely different kinds of actions. The non-determinism also means that vulnerabilities can arise from combinations that would not be obvious from inspecting each capability in isolation. An agent with access to an email tool and an outbound HTTP tool might be entirely safe when each is used independently. In a single context — say, an email containing a prompt that causes the agent to chain both tools together — those same capabilities can become an exfiltration vector. ## What risk means [Section titled “What risk means”](#what-risk-means) In formal risk management — the kind used in insurance, finance, and enterprise governance — risk is not simply danger or the presence of something hazardous. It is a way of quantifying uncertainty about future events in terms of two properties: the likelihood that an event occurs, and the magnitude of its consequences if it does. An event that is highly likely but has minor consequences may be lower risk than one that is unlikely but catastrophic. Risk is always prospective — it describes exposure to possible outcomes, not outcomes that have already occurred. Risk management exists to make that exposure legible before anything goes wrong, so that organisations can make informed decisions about what level of exposure is acceptable and where controls are warranted. In data governance, this translates to questions like: what sensitive information does this system have access to, what could happen if it were mishandled, and how likely is mishandling given how the system operates? ## Two dimensions [Section titled “Two dimensions”](#two-dimensions) Every action an agent takes has two risk-relevant properties: the sensitivity of the data involved, and the consequence of the action being performed. Data sensitivity reflects the regulatory and ethical weight attached to a category of information. Personal identifiers, financial records, and health data each carry different implications if they are mishandled, exposed, or processed without appropriate controls. Action consequence reflects what the agent did with the data. Reading a record is different from writing one. Retrieving information is different from initiating a transaction. The potential for harm scales with the type of action — an agent that reads a health record poses different risk than one that modifies it. ## What risk classification does and does not tell you [Section titled “What risk classification does and does not tell you”](#what-risk-classification-does-and-does-not-tell-you) In Prefactor, a risk classification is derived from the [activity schema](/platform/concepts/activity-schema): each span type declares which data categories and actions it can exercise, Prefactor scores that declaration, then multiplies by how many spans of that type ran in the [instance](/platform/concepts/instance). It is not a judgement about whether the agent behaved correctly or produced accurate outputs — those are quality questions — and it is not a scan of the actual values in the payload. [Sensitive markers](/platform/sensitive-data) on stored values do not change the score. Risk and quality are orthogonal: an agent can be high-risk and functioning exactly as intended, or low-risk and producing poor outputs. A High classification means the run exercised span types that declare high-sensitivity categories, high-consequence actions, or both — enough times to cross the High band in the assigned [risk profile](/platform/concepts/risk-profile). It identifies runs that warrant closer attention; it does not mean something went wrong. Risk in the formal sense is prospective (exposure to possible outcomes). Prefactor applies that model by classifying each recorded run from declared capabilities and observed span-type volume, so exposure stays legible in production. ## Further reading [Section titled “Further reading”](#further-reading) * [Risk profile](/platform/concepts/risk-profile) — how to configure the weights, multipliers, and thresholds that translate risk dimensions into a classification. * [Span](/platform/concepts/span) — the unit at which risk is assessed. * [Instance](/platform/concepts/instance) — where the aggregate risk classification is recorded. * [Sensitive data](/platform/sensitive-data) — how the actual sensitive values in a run’s record are stored, redacted, and discarded. * [Quality and performance](/platform/quality-and-performance) — the separate question of how well an agent does its job. # Sensitive data > How Prefactor stores, redacts, and discards the sensitive values your integration marks in span payloads. A faithful record of what an agent did will sooner or later contain things you do not want every reviewer to read: email addresses, account numbers, medical details, credentials. Dropping those values from the record weakens the audit trail; keeping them in plain view turns the audit trail itself into an exposure. Prefactor resolves this by letting your integration mark the sensitive values in a [span](/platform/concepts/span)’s payload, and then handling those values differently from the rest of the record — stored separately, redacted by default, revealed on demand, and removable for good. Prefactor does not detect sensitive data for you. The team building the agent knows which fields carry a customer’s email and which carry a search query, so marking is done in your integration, at the point where the payload is built. ## Marking values [Section titled “Marking values”](#marking-values) Marking uses the [sensitive encoding](/api/sensitive-encoding): your integration wraps each sensitive value in a marker that names the categories of data it contains — personal identifiers, contact information, credentials, and so on. The labels travel with the value wherever it appears, so a reviewer always knows what kind of data was redacted even when they cannot see the value itself. ## What Prefactor does with marked values [Section titled “What Prefactor does with marked values”](#what-prefactor-does-with-marked-values) Marked values never sit in the main span record. On write, Prefactor splits them out: the span’s payload keeps a redacted marker — the type and labels, no value — and the values move to a separate secure store attached to the span. The split is a storage arrangement, not something you manage. In the web app, sensitive values are redacted by default. Span summaries and conversation views render with the values hidden, and the span detail panel shows each marked value as a labelled placeholder. A **Show sensitive information** toggle in the panel reveals the values for that viewing; it is off again the next time you look. ## Discarding values [Section titled “Discarding values”](#discarding-values) Some values should not be retrievable at all once a run has been reviewed — or should never have been captured in the first place. The **Discard sensitive** action on a span permanently deletes its stored sensitive values. The span keeps its redacted markers, so the record still shows that sensitive data of those categories was present; only the values are gone, and there is no way to recover them. Discard is also available through the API, span by span. ## Sensitive markers and risk [Section titled “Sensitive markers and risk”](#sensitive-markers-and-risk) Markers and [risk scoring](/platform/concepts/risk-profile#how-risk-is-scored) share a vocabulary but do different jobs. Risk is scored from the activity schema’s declarations — which data categories each span type can touch — because risk is about what the agent is capable of handling, assessed before and across runs. Markers annotate the actual values in an actual run, so they drive redaction and discard, not the risk score. An agent whose schema declares `personal_identifiers` scores for it whether or not a given run marked any values; a marked value in a run does not add to the score. ## Further reading [Section titled “Further reading”](#further-reading) * [Span](/platform/concepts/span) — the record that carries payloads, results, and sensitive markers. * [Sensitive encoding](/api/sensitive-encoding) — the marker format and flag your integration uses to mark values. * [Risk](/platform/risk) — what data sensitivity means for scoring and classification. * [Agent › Instance › Activity tab](/admin-ui/agent-instance/activity) — where redacted values, the reveal toggle, and the discard action appear. # Quickstart > Put a demo agent on Prefactor and look around. This quickstart registers a demo agent and wires it to Prefactor. By the end, the demo agent is sending spans you can open in Prefactor. ## Clone the demo [Section titled “Clone the demo”](#clone-the-demo) ```bash git clone https://github.com/prefactordev/prefactor-chatbot-demo.git cd prefactor-chatbot-demo bun install ``` To run this chatbot as-is, you will need [Bun](https://bun.sh) and an [Anthropic API key](https://console.anthropic.com/settings/keys). ## Set up Prefactor [Section titled “Set up Prefactor”](#set-up-prefactor) Prefactor provides a CLI for getting started quickly. You can follow along in the [web app](https://app.prefactorai.com/getting-started) or run the CLI commands below. You need a [Prefactor account](https://app.prefactorai.com). If you are new, the app walks you through signing in and creating your first account and environment. Install the CLI: ```bash curl -fsSL https://prefactor.tech/install.sh | bash ``` Sign in: ```bash prefactor login ``` For more about CLI authentication and profiles, see [Getting started with the CLI](/cli/getting-started). ## Create an agent [Section titled “Create an agent”](#create-an-agent) An [agent](/platform/concepts/agent) is the Prefactor record for the chatbot. Create one: ```bash prefactor agents create \ --name "Chatbot demo" \ --description "Support chatbot demo" ``` The response looks like this. Copy `details.id` — that is your ``: ```json { "status": "success", "details": { "id": "01exampleagentid00000000000000000", "name": "Chatbot demo", "status": "pending", "type": "agent", "description": "Support chatbot demo" } } ``` In the web app, the same step is **Register agent** on the [Agents page](/admin-ui/agents). The agent ID is on the agent after you create it. ## Get a deployment token [Section titled “Get a deployment token”](#get-a-deployment-token) Pick a path. Both produce a deployment-scoped [API token](/platform/concepts/api-token) for the agent. If no [deployment](/platform/concepts/agent-deployment) exists yet, Prefactor creates one. * Setup command Run `prefactor setup` with your agent ID: ```bash prefactor setup ``` The command checks the agent, creates a deployment if needed, mints a deployment token, and prints values you can paste into `.env`: ```bash PREFACTOR_API_URL=https://app.prefactorai.com PREFACTOR_API_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... PREFACTOR_AGENT_ID=01exampleagentid00000000000000000 PREFACTOR_AGENT_IDENTIFIER=1.0.0 ``` Copy `PREFACTOR_API_URL`, `PREFACTOR_API_TOKEN`, and `PREFACTOR_AGENT_ID` from that output. * Manual List your accounts: ```bash prefactor accounts list ``` Copy the `id` of the account you want — that is your ``: ```json { "status": "success", "summaries": [ { "id": "01exampleaccountid000000000000000", "name": "Acme", "type": "account" } ] } ``` List environments for that account: ```bash prefactor environments list --account_id ``` Copy the `id` of the environment you want to use (often Development) — that is your ``: ```json { "status": "success", "summaries": [ { "id": "01exampleenvid0000000000000000000", "name": "Development", "type": "environment", "account_id": "01exampleaccountid000000000000000", "purpose": "development" } ] } ``` Create a deployment-scoped token: ```bash prefactor api_tokens create \ --token_scope agent_deployment \ --agent_id \ --environment_id ``` The secret value is in the top-level `token` field. Copy it now — Prefactor only shows it when the token is created: ```json { "status": "success", "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "details": { "id": "01exampletokenid00000000000000000", "status": "active", "type": "api_token", "token_scope": "agent_deployment", "agent_id": "01exampleagentid00000000000000000", "environment_id": "01exampleenvid0000000000000000000" } } ``` In the web app, open the [Agent page › Deployments tab](/admin-ui/agent/deployments) for that agent, select **Create deployment token**, pick the same environment, and copy the value once. ## Configure the demo [Section titled “Configure the demo”](#configure-the-demo) From the demo repo root, create a local environment file: ```bash cp .env.example .env ``` Open `.env` and fill in the required values. Match the names in `.env.example`: ```dotenv ANTHROPIC_API_KEY=your-anthropic-api-key PREFACTOR_API_URL=https://app.prefactorai.com PREFACTOR_API_TOKEN=your-deployment-token PREFACTOR_AGENT_ID=your-agent-id ``` Use: * `ANTHROPIC_API_KEY` — from the [Anthropic console](https://console.anthropic.com/settings/keys) * `PREFACTOR_API_URL` — from `prefactor setup`, or `https://app.prefactorai.com` for Prefactor cloud * `PREFACTOR_API_TOKEN` — from `prefactor setup` or the `token` field from `api_tokens create` * `PREFACTOR_AGENT_ID` — the agent `details.id` from `agents create` The value from `prefactor setup` is a deployment-scoped [API token](/platform/concepts/api-token) — a kind of API token that already carries agent and environment identity. For this demo, still set `PREFACTOR_AGENT_ID` explicitly from the setup output (or `agents create`) so it matches what you copied. Optionally, create a second agent and deployment token the same way and fill in `PREFACTOR_AGENT_ID_SUPPORT` and `PREFACTOR_API_TOKEN_SUPPORT` to send background support investigations to a separate agent. Without them, that work still runs through the primary deployment. ## Run the chatbot [Section titled “Run the chatbot”](#run-the-chatbot) Start the development server: ```bash bun run dev ``` Open and send a message. Questions about an invoice or account access also exercise the demo’s background support path. ## Inspect the activity [Section titled “Inspect the activity”](#inspect-the-activity) Open the [Agents page](/admin-ui/agents) in Prefactor and select **Chatbot demo**. The new chat appears on the [Agent page › Instances tab](/admin-ui/agent/instances). Open an instance to inspect its activity. ## Next [Section titled “Next”](#next) * [Agent](/platform/concepts/agent) — identity, versions, and lifecycle * [Risk profile](/platform/concepts/risk-profile) — classify data risk on runs * [Activity schema](/platform/concepts/activity-schema) — declare span types and payloads * [Quality and performance](/platform/quality-and-performance) — attach evaluations after a run # SDK overview > Choose an SDK and find shared SDK docs. The Prefactor SDKs instrument your agent applications so Prefactor can record [instances](/platform/concepts/instance) and [spans](/platform/concepts/span), classify [data risk](/platform/risk) from your [activity schemas](/platform/concepts/activity-schema), and accept [quality evaluation](/sdks/quality-evaluations) payloads you attach. When your agent runs, the SDK captures LLM calls, tool invocations, and agent spans — along with their inputs, outputs, and token usage — and sends them as structured trace data. `PREFACTOR_CAPTURE_INPUTS`, `PREFACTOR_CAPTURE_OUTPUTS`, and `PREFACTOR_SAMPLE_RATE` control the data footprint; see [Configuration and environment variables](/sdks/configuration) for defaults. Both the TypeScript and Python SDKs follow the same model: you initialise the SDK with an integration package that matches your framework, and the shared configuration and schema options described in this section apply to both. ## SDKs [Section titled “SDKs”](#sdks) | Language | Links | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | TypeScript | [Docs](/sdks/typescript-sdk) · [Source](https://github.com/prefactordev/typescript-sdk) · [DeepWiki](https://deepwiki.com/prefactordev/typescript-sdk) | | Python | [Docs](/sdks/python-sdk) · [Source](https://github.com/prefactordev/python-sdk) · [DeepWiki](https://deepwiki.com/prefactordev/python-sdk) | ## Shared topics [Section titled “Shared topics”](#shared-topics) * [Quickstart](/quickstart): clone the demo, create an agent, and send your first spans * [Schemas and result schemas](/sdks/concepts-schemas): how span payload schemas and result schemas are defined and when to override them * [Quality evaluations](/sdks/quality-evaluations): declare quality schemas and submit evaluation payloads * [Configuration and environment variables](/sdks/configuration): runtime config, environment variables, transport settings, and retries * [Handle instance termination](/sdks/handling-termination): how your agent finds out a run was terminated, and how to respond * [Handle rate limiting](/sdks/handling-rate-limits): how the SDKs retry limited requests, and what happens when retries run out * [CLI tool](/cli): command-line access for working with Prefactor from your terminal ## Integrations [Section titled “Integrations”](#integrations) Available integration packages depend on the SDK: * TypeScript includes packages for LangChain, the Vercel AI SDK, Claude, and other adapters in the TypeScript repo * Python includes packages for LangChain and LiveKit in the Python repo # Schemas and result schemas Prefactor agent schemas describe the expected shape of span payloads and span results for each span type. In the SDK this is `agentSchema` / the agent schema object; in the platform it is the [activity schema](/platform/concepts/activity-schema). You provide these through `httpConfig.agentSchema` and they are registered with the agent manager during initialisation. Every span type must have payload and result definitions in the activity schema; integration packages supply permissive defaults for their prefixed span types so you can start recording traces before you write tight, custom schemas. Schemas describe rather than enforce. The web app reports whether incoming payloads match the schema, and that shape is what lets you organise and understand the recorded data. The SDK records spans regardless of whether they match the schema. Each default schema defines both `span_schemas` and `span_result_schemas`. This separation lets you validate request-side fields and result-side fields independently, which is useful when your workflows evolve at different speeds for inputs and outputs. Out of the box, the SDK defaults are permissive: they describe a generic object and allow properties you have not listed yet, so they do not block incremental instrumentation. When you need stronger constraints, provide your own schema object in `httpConfig.agentSchema`. A common pattern is permissive definitions for chat turns (`user_message`, `assistant_message`) alongside tighter definitions for each tool span type so payloads and results match that tool’s real contract. A span type can also declare a summary template that renders the one-line summary shown for each span — a `template` field on the span type entry, alongside its params and result schemas. Templates are Liquid, rendered server-side, and can reference both params and result fields; see [Summary templates](/api/summary-templates) for the language. The agent schema can also carry one or more named quality schemas, each declaring the shape of an evaluation payload you attach to a run after it finishes. See [Quality evaluations](/sdks/quality-evaluations). ## TypeScript example [Section titled “TypeScript example”](#typescript-example) An `agentSchema` for a conversational agent: open shapes for messages, and per-tool definitions for `web_search` and `read_file`. This example uses `init` from `@prefactor/core` with a provider so you can pass `agentSchema` on the client config. For the usual middleware-only path, see [Getting started with the TypeScript SDK](/sdks/typescript-sdk). ```typescript import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const openObject = { type: 'object', additionalProperties: true, } as const; const agentSchema = { span_schemas: { user_message: openObject, assistant_message: openObject, web_search: { type: 'object', properties: { query: { type: 'string' }, max_results: { type: 'number' }, }, required: ['query'], additionalProperties: false, }, read_file: { type: 'object', properties: { path: { type: 'string' }, }, required: ['path'], additionalProperties: false, }, }, span_result_schemas: { user_message: openObject, assistant_message: { type: 'object', properties: { content: { type: 'string' }, }, required: ['content'], additionalProperties: true, }, web_search: { type: 'object', properties: { results: { type: 'array' }, }, required: ['results'], additionalProperties: true, }, read_file: { type: 'object', properties: { contents: { type: 'string' }, }, required: ['contents'], additionalProperties: false, }, }, }; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', agentSchema, }, }); ``` ## Python example [Section titled “Python example”](#python-example) The Python SDK follows the same schema model. Pass your schema as `agent_schema` in the client config: ```python import os from prefactor_core import PrefactorCoreClient, PrefactorCoreConfig from prefactor_http import HttpClientConfig OPEN_OBJECT = {"type": "object", "additionalProperties": True} agent_schema = { "span_schemas": { "user_message": OPEN_OBJECT, "assistant_message": OPEN_OBJECT, "web_search": { "type": "object", "properties": { "query": {"type": "string"}, "max_results": {"type": "number"}, }, "required": ["query"], "additionalProperties": False, }, "read_file": { "type": "object", "properties": { "path": {"type": "string"}, }, "required": ["path"], "additionalProperties": False, }, }, "span_result_schemas": { "user_message": OPEN_OBJECT, "assistant_message": { "type": "object", "properties": { "content": {"type": "string"}, }, "required": ["content"], "additionalProperties": True, }, "web_search": { "type": "object", "properties": { "results": {"type": "array"}, }, "required": ["results"], "additionalProperties": True, }, "read_file": { "type": "object", "properties": { "contents": {"type": "string"}, }, "required": ["contents"], "additionalProperties": False, }, }, } config = PrefactorCoreConfig( http_config=HttpClientConfig( api_url="https://app.prefactorai.com", api_token=os.environ["PREFACTOR_API_TOKEN"], agent_schema=agent_schema, ) ) client = PrefactorCoreClient(config) await client.initialize() ``` See the [Python SDK reference](/sdks/python-sdk/api/core) for the exact parameter names. ## Activity schema in the web app [Section titled “Activity schema in the web app”](#activity-schema-in-the-web-app) The schema you register from the SDK appears in the **Activity schema** tab of the agent in the Prefactor web app. The span type identifiers you define (for example `user_message`, `assistant_message`, `web_search`) correspond to the span types shown there. See the [Agent › Activity schema tab](/admin-ui/agent/activity-schemas) to view deployed schemas and their validation status. # Configuration and environment variables These configuration options apply to both the TypeScript and Python SDKs. Variable names and programmatic keys are consistent across both. Pass configuration in code, through environment variables, or as a combination of both. Programmatic values take precedence over environment variables. This pattern lets local development and production deployments share the same initialisation path with minimal branching. ## Authentication and identity [Section titled “Authentication and identity”](#authentication-and-identity) Set `PREFACTOR_API_URL` and `PREFACTOR_API_TOKEN` to configure the HTTP transport. To identify the agent sending data, use these optional variables: * `PREFACTOR_AGENT_ID` — the agent’s Prefactor ID (a ULID). Maps to `agentId` in the SDK config * `PREFACTOR_AGENT_NAME` — an optional display name for the agent * `PREFACTOR_AGENT_IDENTIFIER` — the version string for this deployment (maps to `agentIdentifier` in the SDK config; accepts a semver tag, commit SHA, or any identifier you want to track) ### Token scope and identity [Section titled “Token scope and identity”](#token-scope-and-identity) Which identity fields you need depends on the token: * **Account-scoped token** — requires the agent ID (`PREFACTOR_AGENT_ID` / `agentId`). Environment identity usually comes from the deployment or token path you use at runtime; the SDKs do not document a separate environment env var here. * **Deployment-scoped token** — may omit the agent ID; agent and environment identity are carried by the token. * If you set `PREFACTOR_AGENT_ID`, it must be the platform agent ID (ULID), not a display name. Use `PREFACTOR_AGENT_NAME` for a human-readable label. ## Capture and sampling [Section titled “Capture and sampling”](#capture-and-sampling) * `PREFACTOR_SAMPLE_RATE` — trace sampling from `0` to `1`. Default: `1.0` (all spans recorded). * `PREFACTOR_CAPTURE_INPUTS` and `PREFACTOR_CAPTURE_OUTPUTS` — whether input and output payloads are recorded. Both default to `true`. * `PREFACTOR_MAX_INPUT_LENGTH` and `PREFACTOR_MAX_OUTPUT_LENGTH` — maximum serialised payload sizes. Default: `10,000` characters. ## Logging [Section titled “Logging”](#logging) `PREFACTOR_LOG_LEVEL` controls SDK log verbosity: `debug`, `info`, `warn`, or `error`. Default is `info`. Unlike other config fields, log level is not part of the main `Config` object — it is read from the environment directly by the logger. ## Retry behaviour [Section titled “Retry behaviour”](#retry-behaviour) Retry behaviour can be tuned for network conditions through HTTP config fields: `maxRetries`, `initialRetryDelay`, `maxRetryDelay`, and `retryMultiplier`. You can also set `PREFACTOR_RETRY_ON_STATUS_CODES` to match specific HTTP status codes. In most applications the default retry profile is sufficient; adjust only when operational data shows a clear need. Rate-limited requests (`429`) are retried under the same settings — see [Handle rate limiting](/sdks/handling-rate-limits) for what happens when retries run out. ## Defaults and impact on evidence [Section titled “Defaults and impact on evidence”](#defaults-and-impact-on-evidence) By default, `PREFACTOR_SAMPLE_RATE` is `1.0`, both capture flags are `true`, and payload truncation limits are 10,000 characters. Lowering the sample rate or disabling capture reduces evidence completeness in the web app — useful for high-throughput production workloads, but worth reviewing before a compliance review. ## When things go wrong [Section titled “When things go wrong”](#when-things-go-wrong) | Symptom | Likely cause | First step | | ------------------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SDK initialises but no spans appear | Missing or invalid `PREFACTOR_API_TOKEN` | Set `PREFACTOR_LOG_LEVEL=debug` and check for auth errors in the log output | | Unexpected sparse data in the web app | `PREFACTOR_SAMPLE_RATE` is set below `1.0` | Confirm the sample rate in your environment and check [Defaults and impact on evidence](#defaults-and-impact-on-evidence) | | SDK silently stops sending | Token suspended or revoked | Check token status in [Agent › Deployments tab](/admin-ui/agent/deployments) for deployment tokens, or [Account › API tokens tab](/admin-ui/account/api-tokens) for account tokens | Set `PREFACTOR_LOG_LEVEL=debug` as your first debugging step — it surfaces transport errors, auth failures, and dropped spans. # Handle rate limiting > How the TypeScript and Python SDKs respond when Prefactor rate limits a request, and what happens when retries run out. Prefactor rate limits requests to the platform API — [Rate limits](/api/rate-limits) covers how limits are applied and what a limited response contains. Both SDKs treat a rate-limited response as transient and retry it for you; this page covers what those retries look like and what you see when they run out. ## Automatic retries [Section titled “Automatic retries”](#automatic-retries) When Prefactor returns `429`, both SDKs wait and retry the request with exponential backoff and jitter. The defaults retry three times — about a second after the first failure, doubling from there, capped at a minute — and suit most applications. You can tune them through the HTTP config fields (`maxRetries`, `initialRetryDelay`, `maxRetryDelay`, `retryMultiplier`; the same names with underscores in Python) described in [Configuration and environment variables](/sdks/configuration). The SDKs back off on their own schedule rather than reading the `Retry-After` hint the server sends. Because limits are counted over one-minute windows, the default retries can all land inside the same window — if retries keep running out under sustained load, raise the initial delay or the retry count. ## TypeScript: when retries run out [Section titled “TypeScript: when retries run out”](#typescript-when-retries-run-out) If a request is still limited after the last retry, the transport treats it as fatal. It records a `PrefactorFatalError` with kind `retry_exhausted`, stops sending telemetry, and later telemetry calls throw the same error. If you set the `failureHandling.onFatalError` callback, it fires once with the error — that is the place to alert or restart the run. ## Python: when retries run out [Section titled “Python: when retries run out”](#python-when-retries-run-out) After the HTTP client’s own retries run out, the queue worker retries the whole operation again before dropping it: the worker logs the failure and moves on to the next item. The client is not latched, so later spans and operations are sent as normal. ## Related [Section titled “Related”](#related) * [Rate limits](/api/rate-limits) — how limits are applied, and the shape of the 429 response. * [Configuration and environment variables](/sdks/configuration) — retry settings for both SDKs. * [Handle instance termination](/sdks/handling-termination) — how your agent finds out when Prefactor stops a run. # Handle instance termination > How your agent finds out that Prefactor terminated its run, and how to handle it in TypeScript and Python. Someone on your team can stop a running agent from the [Agent instance page](/admin-ui/agent-instance) in the web app, or through the API — see [Instance](/platform/concepts/instance) for what termination means on the platform. This page covers how your agent finds out and how to handle it, with examples in TypeScript and Python. ## How your agent finds out [Section titled “How your agent finds out”](#how-your-agent-finds-out) Detection is built into both SDKs; there is nothing to configure. While a run is active, the SDK learns about termination two ways: * **Span responses.** Every span create and finish response carries a control signal once the instance is terminated, so an agent that is actively emitting spans finds out on its next span. * **Polling.** An idle agent that isn’t emitting spans polls the instance every 30 seconds, so termination is detected within about half a minute even when the agent is quiet. Termination is cooperative. Prefactor records the termination and signals the agent, but it does not kill your process, and it keeps accepting spans until the agent stops. Responding is up to your code — or to your integration’s middleware. To watch for termination from outside the agent — in a dashboard or a supervisor process — subscribe to the instance over the [WebSocket API](/api/websocket). A terminated run arrives as an `agent_instances/updated` notification with status `terminated` and the operator’s reason. ## Handle termination in TypeScript [Section titled “Handle termination in TypeScript”](#handle-termination-in-typescript) The core runtime detects termination for you and exposes it through the termination monitor: a standard `AbortSignal` you can check in your own loop or pass to long-running work, plus callbacks that fire the moment termination is detected. Nothing throws on its own — checking the signal is up to your code. ```typescript import { createCore } from '@prefactor/core'; const core = createCore({ transportType: 'http', httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: 'my-agent-v1', }, }); const monitor = core.terminationMonitor; monitor.onTerminated((reason) => { console.log('Run terminated by Prefactor:', reason); }); core.agentManager.startInstance(); try { while (!monitor.signal.aborted) { // ... your agent's next step ... } } finally { core.agentManager.finishInstance(); monitor.reset(); } ``` Finishing an already-terminated instance is treated as success, so the `finally` block is safe however the run ended. `reset()` readies the monitor for the next run and replaces the signal — read `monitor.signal` fresh each run rather than capturing it once. ### LangChain [Section titled “LangChain”](#langchain) The LangChain integration (`@prefactor/langchain`) throws for you. Initialise through `init` from `@prefactor/core` with the LangChain provider, and the middleware raises an error named `PrefactorTerminatedError` at the next agent, model, or tool hook once termination is detected: ```typescript import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: 'my-agent-v1', }, }); try { await agent.invoke({ messages: [{ role: 'user', content: query }] }); } catch (err) { if (err instanceof Error && err.name === 'PrefactorTerminatedError') { // The run was terminated. Clean up, then continue to the next run. } else { throw err; } } finally { prefactor.finishCurrentRun(); } ``` `PrefactorTerminatedError` is not an exported class — catch it by checking `error.name`, as above; the operator’s reason is in `error.message`. Call `finishCurrentRun()` after every run, terminated or not: it finishes the instance if it’s still open and resets the monitor for the next one. Initialising with `init` from `@prefactor/langchain` instead — the form that returns middleware directly — detects termination internally but never throws it, and gives you no client handle to check the signal yourself. ### LiveKit [Section titled “LiveKit”](#livekit) The LiveKit integration (`@prefactor/livekit`) shuts the session down without draining and finishes the run’s open spans as failed with the termination error. ### AI SDK and Claude [Section titled “AI SDK and Claude”](#ai-sdk-and-claude) The AI SDK (`@prefactor/ai`) and Claude (`@prefactor/claude`) adapters don’t raise on termination yet. Check `monitor.signal` yourself in long-running code paths. ## Handle termination in Python [Section titled “Handle termination in Python”](#handle-termination-in-python) The core client detects termination internally, but its monitor isn’t part of the public API — the supported reaction point is an integration’s middleware. ### LangChain [Section titled “LangChain”](#langchain-1) The LangChain middleware (`prefactor-langchain`) raises `PrefactorTerminatedError` before the next agent, model, or tool hook once termination is detected. The exception is exported from `prefactor_core` and carries the termination reason: ```python import os from langchain.agents import create_agent from prefactor_core import PrefactorTerminatedError from prefactor_langchain import PrefactorMiddleware middleware = PrefactorMiddleware.from_config( api_url="https://app.prefactorai.com", api_token=os.environ["PREFACTOR_API_TOKEN"], agent_id="01exampleagentid00000000000000000", agent_name="My Agent", ) agent = create_agent(model, tools=[...], middleware=[middleware]) try: result = await agent.ainvoke({"messages": [{"role": "user", "content": query}]}) except PrefactorTerminatedError as e: logger.info("Run terminated by Prefactor: %s", e.reason) finally: await middleware.close() ``` A service that runs its agent in a loop catches the error, waits, and starts the next run as a fresh instance: ```python while True: try: await run_once() except PrefactorTerminatedError: logger.info("Run terminated — next run in %.0fs.", restart_delay) await asyncio.sleep(restart_delay) ``` ### LiveKit [Section titled “LiveKit”](#livekit-1) The LiveKit integration (`prefactor-livekit`) doesn’t respond to termination yet; the run keeps recording until your process stops. ## Terminate a run from the API [Section titled “Terminate a run from the API”](#terminate-a-run-from-the-api) Terminating is an operator action, not an SDK call — neither SDK exposes it. Use the [HTTP API](/api/http) directly with an account-scoped token: ```bash curl -X POST https://app.prefactorai.com/api/v1/agent_instance//terminate \ -H "Authorization: Bearer $PREFACTOR_ACCOUNT_TOKEN" \ -H "Content-Type: application/json" \ -d '{"reason": "Runaway retry loop"}' ``` The reason is required and is stored on the instance. Only an active run can be terminated; the request fails with a conflict otherwise. The deployment-scoped token your agent runs with cannot terminate its own instance — use an account-scoped token from the [Account › API tokens tab](/admin-ui/account/api-tokens). The full request and response shape is under [POST /agent\_instance/{agent\_instance\_id}/terminate](/api/platform/operations/actionagentinstanceterminate) in the API reference. ## Termination vs shutdown [Section titled “Termination vs shutdown”](#termination-vs-shutdown) These two are easy to conflate. Termination is the platform stopping your run; `shutdown()` is your process exiting cleanly — it flushes queued telemetry and closes the transport. Call `shutdown()` (TypeScript) or `middleware.close()` (Python) when your app exits, regardless of how the run ended. `PrefactorShutdownError` in the TypeScript SDK means telemetry couldn’t be flushed cleanly during shutdown; it is not a terminated-run signal. ## Limits [Section titled “Limits”](#limits) * Termination is cooperative. If your agent never observes the signal — because it does blocking work without yielding, or its integration doesn’t check — it keeps running and Prefactor keeps recording its spans. * An idle agent can take up to about 30 seconds to notice; an agent emitting spans notices on the next span. ## Verify [Section titled “Verify”](#verify) Terminate a run from the [Agent instance page](/admin-ui/agent-instance) while your agent is active. Your agent should stop at its next step — or within about 30 seconds if it’s idle — and the instance shows as **Terminated** with your reason. ## Related [Section titled “Related”](#related) * [Instance](/platform/concepts/instance) — lifecycle states and what termination records. * [Agent instance page](/admin-ui/agent-instance) — the Terminate control in the web app. * [Stream agent instance updates](/api/stream-instance-updates) — watch a run’s state change live over the WebSocket API. * [Configuration and environment variables](/sdks/configuration) — transport and capture settings for both SDKs. * [TerminationMonitor](/sdks/typescript-sdk/api/core/classes/TerminationMonitor) — generated TypeScript API reference. * [prefactor\_core.exceptions](/sdks/python-sdk/api/core/reference/prefactor_core.exceptions) — generated Python API reference including `PrefactorTerminatedError`. # Getting started with the Python SDK > Install the Prefactor Python SDK and choose the package that matches your integration. The Python SDK is split into small packages. Start with the package that matches how you want to integrate Prefactor. ## Links [Section titled “Links”](#links) * Source: [prefactordev/python-sdk](https://github.com/prefactordev/python-sdk) * DeepWiki: [prefactordev/python-sdk on DeepWiki](https://deepwiki.com/prefactordev/python-sdk) ## Choose a package [Section titled “Choose a package”](#choose-a-package) | Package | Use it when | Reference | | --------------------- | --------------------------------------------------------------------------------- | ------------------------------------------- | | `prefactor-core` | Core client for agent instances, spans, schema registration, and wrapper authors. | [Reference](/sdks/python-sdk/api/core) | | `prefactor-http` | Low-level async client for direct access to the Prefactor API. | [Reference](/sdks/python-sdk/api/http) | | `prefactor-langchain` | LangChain integration package with middleware and LangChain-specific span types. | [Reference](/sdks/python-sdk/api/langchain) | | `prefactor-livekit` | LiveKit integration package for tracing session and voice-agent events. | [Reference](/sdks/python-sdk/api/livekit) | ## Installation [Section titled “Installation”](#installation) Install the package you need: ```bash pip install prefactor-langchain ``` Or install a different package: ```bash pip install prefactor-core pip install prefactor-http pip install prefactor-livekit ``` ## Quick start [Section titled “Quick start”](#quick-start) Most applications start with an integration package. This example uses the LangChain middleware. `agent_id` is the Prefactor agent ID (a ULID from `prefactor agents create` or the Agent page). With a deployment-scoped token you can omit it; with an account-scoped token you must supply it. ```python import os from prefactor_langchain import PrefactorMiddleware middleware = PrefactorMiddleware.from_config( api_url="https://app.prefactorai.com", api_token=os.environ["PREFACTOR_API_TOKEN"], # never hardcode tokens agent_id="01exampleagentid00000000000000000", # Prefactor agent id (ULID) agent_name="My Agent", ) ``` If you want to build your own wrapper or instrument code directly, start with `prefactor-core`: ```python import os from prefactor_core import PrefactorCoreClient, PrefactorCoreConfig from prefactor_http import HttpClientConfig config = PrefactorCoreConfig( http_config=HttpClientConfig( api_url="https://app.prefactorai.com", api_token=os.environ["PREFACTOR_API_TOKEN"], ) ) client = PrefactorCoreClient(config) await client.initialize() ``` ## Next steps [Section titled “Next steps”](#next-steps) * [Python SDK API overview](/sdks/python-sdk/api/overview) * [Prefactor Core](/sdks/python-sdk/api/core) * [Prefactor HTTP Client](/sdks/python-sdk/api/http) * [Prefactor LangChain](/sdks/python-sdk/api/langchain) * [Prefactor LiveKit](/sdks/python-sdk/api/livekit) * [Schemas and result schemas](/sdks/concepts-schemas) * [Configuration and environment variables](/sdks/configuration) * [Handle instance termination](/sdks/handling-termination) * [Handle rate limiting](/sdks/handling-rate-limits) # Prefactor SDK # Prefactor SDK [Section titled “Prefactor SDK”](#prefactor-sdk) Automatic observability for LangChain agents. Trace LLM calls, tool executions, and agent workflows with zero code changes. ## Installation [Section titled “Installation”](#installation) ```bash pip install prefactor-langchain ``` ## Quick Start [Section titled “Quick Start”](#quick-start) ```python import ast import asyncio import operator from langchain.agents import create_agent from langchain_core.tools import tool from prefactor_langchain import PrefactorMiddleware _OPS = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, } def _safe_eval(node): if isinstance(node, ast.Constant): return node.n if isinstance(node, ast.BinOp): return _OPS[type(node.op)](_safe_eval(node.left), _safe_eval(node.right)) if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub): return -_safe_eval(node.operand) raise ValueError(f"Unsupported: {node}") @tool def calculator(expression: str) -> str: """Evaluate a mathematical expression safely.""" try: return str(_safe_eval(ast.parse(expression, mode="eval").body)) except Exception as e: return f"Error: {e}" async def main(): middleware = PrefactorMiddleware.from_config( api_url="https://app.prefactorai.com", api_token="your-token", agent_id="my-agent", agent_name="My Agent", ) agent = create_agent( model="claude-haiku-4-5-20251001", tools=[calculator], middleware=[middleware], ) # All LLM calls and tool executions are automatically traced try: result = await agent.ainvoke( {"messages": [{"role": "user", "content": "What is 6 * 7?"}]} ) finally: await middleware.close() asyncio.run(main()) ``` ## Features [Section titled “Features”](#features) * Automatic tracing of LLM calls with token usage * Tool execution tracking * Agent workflow visualization * Parent-child span relationships * Error tracking and debugging * Zero-overhead instrumentation ## Development Setup [Section titled “Development Setup”](#development-setup) This project uses [mise](https://mise.jdx.dev) for reproducible development environments with the following tools: * **Python 3.11** with **uv** as the package manager * **ty** for blazing-fast type checking (10-100x faster than mypy/pyright) * **ruff** for linting and formatting (replaces Black, isort, Flake8, etc.) * **lefthook** for git pre-commit hooks ### Prerequisites [Section titled “Prerequisites”](#prerequisites) Install mise using one of these methods: ```bash # macOS (Homebrew) brew install mise # Linux/macOS (curl) curl https://mise.run | sh # Other methods: https://mise.jdx.dev/getting-started.html ``` After installation, activate mise in your shell: ```bash # For bash (add to ~/.bashrc) eval "$(mise activate bash)" # For zsh (add to ~/.zshrc) eval "$(mise activate zsh)" # For fish (add to ~/.config/fish/config.fish) mise activate fish | source ``` Alternatively, if you use [direnv](https://direnv.net/), mise will activate automatically when you enter the project directory. ### Getting Started [Section titled “Getting Started”](#getting-started) 1. Clone the repository: ```bash git clone https://github.com/prefactordev/python-sdk.git cd python-sdk ``` 2. Install project tools (Python, uv, ruff, etc.): ```bash mise install ``` 3. Set up the project (install dependencies and git hooks): ```bash mise run setup ``` This will: * Create a virtual environment at `.venv` * Install all dependencies via `uv sync --all-extras` * Install git pre-commit hooks via lefthook 4. You’re ready to develop! The virtual environment activates automatically when you enter the directory. ### Common Tasks [Section titled “Common Tasks”](#common-tasks) ```bash # Run tests mise run test # Run all quality checks (format, lint, typecheck) mise run check # Individual checks mise run format # Format code with ruff mise run lint # Lint code with ruff mise run typecheck # Type check with ty # Install/update dependencies mise run install ``` ### Running Tests [Section titled “Running Tests”](#running-tests) ```bash # Run all tests pytest # Run specific test file pytest packages/core/tests/test_client.py # Run with verbose output pytest -v # Run specific test pytest packages/core/tests/test_client.py::TestClient::test_initialize -v ``` ### Pre-commit Hooks [Section titled “Pre-commit Hooks”](#pre-commit-hooks) Git pre-commit hooks run automatically on each commit via lefthook: 1. `ruff format` - Format staged Python files 2. `ruff check --fix` - Lint and auto-fix staged Python files 3. `uvx ty check` - Type check the entire codebase To run hooks manually: ```bash lefthook run pre-commit ``` ### Versioning [Section titled “Versioning”](#versioning) Package versions are defined in each package’s `src//_version.py` file. That file is the single source of truth for both runtime `__version__` and build metadata. * `packages/http/src/prefactor_http/_version.py` * `packages/core/src/prefactor_core/_version.py` * `packages/langchain/src/prefactor_langchain/_version.py` * `packages/livekit/src/prefactor_livekit/_version.py` Each package `pyproject.toml` uses Hatch dynamic versioning and reads the version directly from that `_version.py` file. We do not resolve versions from installed metadata or parse `pyproject.toml` at import time. When bumping a package version: 1. Update `__version__` in that package’s `_version.py`. 2. Update any dependent package constraints if the new version requires it. 3. Run `mise run test` before committing. ### Project Structure [Section titled “Project Structure”](#project-structure) ```text python-sdk/ ├── packages/ │ ├── core/ # Core tracing and span lifecycle │ ├── http/ # HTTP client for the Prefactor API │ ├── langchain/ # LangChain instrumentation │ └── livekit/ # LiveKit instrumentation ├── mise.toml # mise configuration ├── lefthook.yml # Git hooks configuration └── pyproject.toml # Python project configuration (workspace root) ``` ### Tools Reference [Section titled “Tools Reference”](#tools-reference) | Tool | Purpose | Documentation | | ---------------------------------------------------- | ---------------------- | ------------------------------ | | [mise](https://mise.jdx.dev) | Tool version manager | Manages Python, uv, ruff, etc. | | [uv](https://github.com/astral-sh/uv) | Python package manager | Fast dependency resolution | | [ruff](https://github.com/astral-sh/ruff) | Linter and formatter | Replaces Black, isort, Flake8 | | [ty](https://github.com/astral-sh/ty) | Type checker | 10-100x faster than mypy | | [lefthook](https://github.com/evilmartians/lefthook) | Git hooks manager | Runs pre-commit checks | ### Claude Code Integration [Section titled “Claude Code Integration”](#claude-code-integration) If you use [Claude Code](https://claude.ai/code), hooks are configured in `.claude/settings.json`: * **PostToolUse**: Automatically formats and lints Python files after editing * **PreToolUse**: Runs type checking before git commits # Prefactor Core # Prefactor Core [Section titled “Prefactor Core”](#prefactor-core) High-level Prefactor SDK with async queue-based processing. ## Features [Section titled “Features”](#features) * **Queue-Based Processing**: Operations are queued and processed asynchronously by a worker pool * **Non-Blocking API**: Agent execution is never blocked by observability calls * **Automatic Parent Detection**: Nested spans automatically detect their parent from the context stack * **Schema Registry**: Compose and register span schemas before instance creation * **Configurable Workers**: Tune concurrency and retry behavior for the background queue ## Installation [Section titled “Installation”](#installation) ```bash pip install prefactor-core ``` ## Quick Start [Section titled “Quick Start”](#quick-start) ```python import asyncio from prefactor_core import PrefactorCoreClient, PrefactorCoreConfig, SchemaRegistry from prefactor_http import HttpClientConfig registry = SchemaRegistry() registry.register_type( name="agent:llm", params_schema={ "type": "object", "properties": { "model": {"type": "string"}, "prompt": {"type": "string"}, }, "required": ["model", "prompt"], }, result_schema={ "type": "object", "properties": {"response": {"type": "string"}}, }, title="LLM Call", description="A call to a language model", template="{{model}}: {{prompt}} → {{response}}", ) async def main(): config = PrefactorCoreConfig( http_config=HttpClientConfig( api_url="https://app.prefactorai.com", api_token="your-token", ), schema_registry=registry, ) async with PrefactorCoreClient(config) as client: instance = await client.create_agent_instance( agent_id="my-agent", agent_version={"name": "My Agent", "external_identifier": "v1.0.0"}, ) await instance.start() async with instance.span("agent:llm") as span: await span.start({"model": "gpt-4", "prompt": "Hello"}) result = await call_llm() await span.complete({"response": result}) await instance.finish() asyncio.run(main()) ``` `create_agent_instance()` supports two auth modes: * Account-scoped token: pass `agent_id` and usually `environment_id`. * Deployment-scoped token: omit `agent_id` and `environment_id`; the API derives both from the token. ## API Reference [Section titled “API Reference”](#api-reference) ### `PrefactorCoreClient` [Section titled “PrefactorCoreClient”](#prefactorcoreclient) The main entry point. Use as an async context manager or call `initialize()` / `close()` manually. ```python client = PrefactorCoreClient(config) await client.initialize() # ... use client ... await client.close() ``` #### `create_agent_instance` [Section titled “create\_agent\_instance”](#create_agent_instance) ```python handle = await client.create_agent_instance( agent_version={"name": "My Agent", "external_identifier": "v1.0.0"}, agent_schema_version=None, # Optional: auto-generated if schema_registry is configured agent_id="my-agent", # Optional for deployment-scoped tokens external_schema_version_id=None, # Optional: reference an existing schema version ) -> AgentInstanceHandle ``` #### `span` (context manager) [Section titled “span (context manager)”](#span-context-manager) ```python async with client.span( instance_id="instance_123", schema_name="agent:llm", parent_span_id=None, # Optional: auto-detected from context stack if omitted payload=None, # Optional: used as params if span.start() is never called explicitly ) as span: await span.start({"model": "gpt-4", "prompt": "Hello"}) result = await call_llm() await span.complete({"response": result}) ``` ### `AgentInstanceHandle` [Section titled “AgentInstanceHandle”](#agentinstancehandle) Returned by `create_agent_instance`. Manages the lifecycle of a single agent instance. ```python handle.id # -> str await handle.start() await handle.finish() async with handle.span("agent:llm") as span: ... ``` ### `SpanContext` [Section titled “SpanContext”](#spancontext) The object yielded by span context managers. Spans follow a three-phase lifecycle: 1. **Enter context** — span is prepared locally, no HTTP call yet. 2. **`await span.start(payload)`** — POSTs the span to the API as `active` with the given params payload. 3. **`await span.complete(result)`** / **`span.fail(result)`** / **`span.cancel()`** — finishes the span with a terminal status. If `start()` or a finish method is not called explicitly, the context manager handles them automatically on exit. ```python span.id # -> str (API-generated after start()) await span.start(payload: dict) # POST span as active with params payload await span.complete(result: dict) # finish with status "complete" await span.fail(result: dict) # finish with status "failed" await span.cancel() # finish with status "cancelled" span.set_result(data: dict) # accumulate result data for auto-finish await span.finish() # finish with current status (default: "complete") ``` **Status note:** `cancel()` can be called before or after `start()`. If called before `start()`, the span is posted as `pending` and immediately cancelled — the only valid pre-active cancellation path the API supports. #### Full lifecycle example [Section titled “Full lifecycle example”](#full-lifecycle-example) ```python async with instance.span("agent:llm") as span: await span.start({"model": "gpt-4", "prompt": "Hello"}) try: result = await call_llm() await span.complete({"response": result}) except Exception as exc: await span.fail({"error": str(exc)}) # Cancel before starting (e.g. a conditional step that is skipped): async with instance.span("agent:retrieval") as span: if not needed: await span.cancel() else: await span.start({"query": "..."}) docs = await retrieve() await span.complete({"documents": docs, "count": len(docs)}) ``` ## Configuration [Section titled “Configuration”](#configuration) ```python from prefactor_core import PrefactorCoreConfig, QueueConfig from prefactor_http import HttpClientConfig config = PrefactorCoreConfig( http_config=HttpClientConfig( api_url="https://app.prefactorai.com", api_token="your-token", ), queue_config=QueueConfig( num_workers=3, # Number of background workers max_retries=3, # Retries per operation retry_delay_base=1.0, # Base delay (seconds) for exponential backoff ), schema_registry=None, # Optional: SchemaRegistry instance ) ``` ## Schema Registry [Section titled “Schema Registry”](#schema-registry) Use `SchemaRegistry` to compose span schemas from multiple sources and auto-generate the `agent_schema_version` passed to `create_agent_instance`. ```python from prefactor_core import SchemaRegistry registry = SchemaRegistry() registry.register_type( name="agent:llm", params_schema={ "type": "object", "properties": { "model": {"type": "string"}, "prompt": {"type": "string"}, }, "required": ["model", "prompt"], }, result_schema={ "type": "object", "properties": {"response": {"type": "string"}}, }, title="LLM Call", description="A call to a language model", template="{{model}}: {{prompt}} → {{response}}", ) registry.register_type( name="agent:tool", params_schema={"type": "object", "properties": {...}}, result_schema={"type": "object", "properties": {...}}, title="Tool Call", ) config = PrefactorCoreConfig( http_config=..., schema_registry=registry, ) async with PrefactorCoreClient(config) as client: # agent_schema_version is generated automatically from the registry instance = await client.create_agent_instance( agent_version={"name": "My Agent", "external_identifier": "v1.0.0"}, agent_id="my-agent", # Optional for deployment-scoped tokens ) ``` ## Error Handling [Section titled “Error Handling”](#error-handling) ```python from prefactor_core import ( PrefactorCoreError, ClientNotInitializedError, ClientAlreadyInitializedError, OperationError, InstanceNotFoundError, SpanNotFoundError, ) ``` ## Architecture [Section titled “Architecture”](#architecture) The client uses a three-layer design: 1. **Queue infrastructure**: `InMemoryQueue` + `TaskExecutor` worker pool process operations in the background 2. **Managers**: `AgentInstanceManager` and `SpanManager` translate high-level calls into `Operation` objects and route them to the HTTP client 3. **Client API**: `PrefactorCoreClient` exposes the user-facing interface and wires the layers together All observability operations are enqueued and executed asynchronously — the calling code is never blocked waiting for API responses. ## License [Section titled “License”](#license) MIT # prefactor_core # prefactor\_core [Section titled “prefactor\_core”](#prefactor_core) * [prefactor\_core package](prefactor_core.md) * [`AgentInstance`](prefactor_core.md#prefactor_core.AgentInstance) * [`AgentInstance.id`](prefactor_core.md#prefactor_core.AgentInstance.id) * [`AgentInstance.agent_id`](prefactor_core.md#prefactor_core.AgentInstance.agent_id) * [`AgentInstance.status`](prefactor_core.md#prefactor_core.AgentInstance.status) * [`AgentInstance.created_at`](prefactor_core.md#prefactor_core.AgentInstance.created_at) * [`AgentInstance.started_at`](prefactor_core.md#prefactor_core.AgentInstance.started_at) * [`AgentInstance.finished_at`](prefactor_core.md#prefactor_core.AgentInstance.finished_at) * [`AgentInstance.metadata`](prefactor_core.md#prefactor_core.AgentInstance.metadata) * [`AgentInstance.agent_id`](prefactor_core.md#id0) * [`AgentInstance.created_at`](prefactor_core.md#id1) * [`AgentInstance.finished_at`](prefactor_core.md#id2) * [`AgentInstance.id`](prefactor_core.md#id3) * [`AgentInstance.metadata`](prefactor_core.md#id4) * [`AgentInstance.purpose`](prefactor_core.md#prefactor_core.AgentInstance.purpose) * [`AgentInstance.quality_payloads`](prefactor_core.md#prefactor_core.AgentInstance.quality_payloads) * [`AgentInstance.started_at`](prefactor_core.md#id5) * [`AgentInstance.status`](prefactor_core.md#id6) * [`AgentInstanceHandle`](prefactor_core.md#prefactor_core.AgentInstanceHandle) * [`AgentInstanceHandle.create_span()`](prefactor_core.md#prefactor_core.AgentInstanceHandle.create_span) * [`AgentInstanceHandle.finish()`](prefactor_core.md#prefactor_core.AgentInstanceHandle.finish) * [`AgentInstanceHandle.finish_span()`](prefactor_core.md#prefactor_core.AgentInstanceHandle.finish_span) * [`AgentInstanceHandle.id`](prefactor_core.md#prefactor_core.AgentInstanceHandle.id) * [`AgentInstanceHandle.record_quality()`](prefactor_core.md#prefactor_core.AgentInstanceHandle.record_quality) * [`AgentInstanceHandle.span()`](prefactor_core.md#prefactor_core.AgentInstanceHandle.span) * [`AgentInstanceHandle.start()`](prefactor_core.md#prefactor_core.AgentInstanceHandle.start) * [`ClientAlreadyInitializedError`](prefactor_core.md#prefactor_core.ClientAlreadyInitializedError) * [`ClientNotInitializedError`](prefactor_core.md#prefactor_core.ClientNotInitializedError) * [`InMemoryQueue`](prefactor_core.md#prefactor_core.InMemoryQueue) * [`InMemoryQueue.close()`](prefactor_core.md#prefactor_core.InMemoryQueue.close) * [`InMemoryQueue.closed`](prefactor_core.md#prefactor_core.InMemoryQueue.closed) * [`InMemoryQueue.get()`](prefactor_core.md#prefactor_core.InMemoryQueue.get) * [`InMemoryQueue.put()`](prefactor_core.md#prefactor_core.InMemoryQueue.put) * [`InMemoryQueue.size()`](prefactor_core.md#prefactor_core.InMemoryQueue.size) * [`InstanceNotFoundError`](prefactor_core.md#prefactor_core.InstanceNotFoundError) * [`Operation`](prefactor_core.md#prefactor_core.Operation) * [`Operation.type`](prefactor_core.md#prefactor_core.Operation.type) * [`Operation.payload`](prefactor_core.md#prefactor_core.Operation.payload) * [`Operation.timestamp`](prefactor_core.md#prefactor_core.Operation.timestamp) * [`Operation.idempotency_key`](prefactor_core.md#prefactor_core.Operation.idempotency_key) * [`Operation.metadata`](prefactor_core.md#prefactor_core.Operation.metadata) * [`Operation.idempotency_key`](prefactor_core.md#id7) * [`Operation.metadata`](prefactor_core.md#id8) * [`Operation.payload`](prefactor_core.md#id9) * [`Operation.timestamp`](prefactor_core.md#id10) * [`Operation.type`](prefactor_core.md#id11) * [`OperationError`](prefactor_core.md#prefactor_core.OperationError) * [`OperationType`](prefactor_core.md#prefactor_core.OperationType) * [`OperationType.CREATE_SPAN`](prefactor_core.md#prefactor_core.OperationType.CREATE_SPAN) * [`OperationType.FINISH_AGENT_INSTANCE`](prefactor_core.md#prefactor_core.OperationType.FINISH_AGENT_INSTANCE) * [`OperationType.FINISH_SPAN`](prefactor_core.md#prefactor_core.OperationType.FINISH_SPAN) * [`OperationType.RECORD_QUALITY`](prefactor_core.md#prefactor_core.OperationType.RECORD_QUALITY) * [`OperationType.REGISTER_AGENT_INSTANCE`](prefactor_core.md#prefactor_core.OperationType.REGISTER_AGENT_INSTANCE) * [`OperationType.START_AGENT_INSTANCE`](prefactor_core.md#prefactor_core.OperationType.START_AGENT_INSTANCE) * [`PrefactorCoreClient`](prefactor_core.md#prefactor_core.PrefactorCoreClient) * [`PrefactorCoreClient.close()`](prefactor_core.md#prefactor_core.PrefactorCoreClient.close) * [`PrefactorCoreClient.create_agent_instance()`](prefactor_core.md#prefactor_core.PrefactorCoreClient.create_agent_instance) * [`PrefactorCoreClient.create_span()`](prefactor_core.md#prefactor_core.PrefactorCoreClient.create_span) * [`PrefactorCoreClient.finish_span()`](prefactor_core.md#prefactor_core.PrefactorCoreClient.finish_span) * [`PrefactorCoreClient.initialize()`](prefactor_core.md#prefactor_core.PrefactorCoreClient.initialize) * [`PrefactorCoreClient.instance_manager`](prefactor_core.md#prefactor_core.PrefactorCoreClient.instance_manager) * [`PrefactorCoreClient.record_quality()`](prefactor_core.md#prefactor_core.PrefactorCoreClient.record_quality) * [`PrefactorCoreClient.span()`](prefactor_core.md#prefactor_core.PrefactorCoreClient.span) * [`PrefactorCoreConfig`](prefactor_core.md#prefactor_core.PrefactorCoreConfig) * [`PrefactorCoreConfig.http_config`](prefactor_core.md#prefactor_core.PrefactorCoreConfig.http_config) * [`PrefactorCoreConfig.queue_config`](prefactor_core.md#prefactor_core.PrefactorCoreConfig.queue_config) * [`PrefactorCoreConfig.schema_registry`](prefactor_core.md#prefactor_core.PrefactorCoreConfig.schema_registry) * [`PrefactorCoreConfig.http_config`](prefactor_core.md#id12) * [`PrefactorCoreConfig.model_config`](prefactor_core.md#prefactor_core.PrefactorCoreConfig.model_config) * [`PrefactorCoreConfig.queue_config`](prefactor_core.md#id13) * [`PrefactorCoreConfig.schema_registry`](prefactor_core.md#id14) * [`PrefactorCoreError`](prefactor_core.md#prefactor_core.PrefactorCoreError) * [`PrefactorTelemetryFailureError`](prefactor_core.md#prefactor_core.PrefactorTelemetryFailureError) * [`PrefactorTerminatedError`](prefactor_core.md#prefactor_core.PrefactorTerminatedError) * [`Queue`](prefactor_core.md#prefactor_core.Queue) * [`Queue.close()`](prefactor_core.md#prefactor_core.Queue.close) * [`Queue.closed`](prefactor_core.md#prefactor_core.Queue.closed) * [`Queue.get()`](prefactor_core.md#prefactor_core.Queue.get) * [`Queue.put()`](prefactor_core.md#prefactor_core.Queue.put) * [`Queue.size()`](prefactor_core.md#prefactor_core.Queue.size) * [`QueueClosedError`](prefactor_core.md#prefactor_core.QueueClosedError) * [`QueueConfig`](prefactor_core.md#prefactor_core.QueueConfig) * [`QueueConfig.num_workers`](prefactor_core.md#prefactor_core.QueueConfig.num_workers) * [`QueueConfig.max_retries`](prefactor_core.md#prefactor_core.QueueConfig.max_retries) * [`QueueConfig.retry_delay_base`](prefactor_core.md#prefactor_core.QueueConfig.retry_delay_base) * [`QueueConfig.max_retries`](prefactor_core.md#id15) * [`QueueConfig.model_config`](prefactor_core.md#prefactor_core.QueueConfig.model_config) * [`QueueConfig.num_workers`](prefactor_core.md#id16) * [`QueueConfig.retry_delay_base`](prefactor_core.md#id17) * [`SchemaRegistry`](prefactor_core.md#prefactor_core.SchemaRegistry) * [`SchemaRegistry.get()`](prefactor_core.md#prefactor_core.SchemaRegistry.get) * [`SchemaRegistry.has_schema()`](prefactor_core.md#prefactor_core.SchemaRegistry.has_schema) * [`SchemaRegistry.list_schemas()`](prefactor_core.md#prefactor_core.SchemaRegistry.list_schemas) * [`SchemaRegistry.merge()`](prefactor_core.md#prefactor_core.SchemaRegistry.merge) * [`SchemaRegistry.register()`](prefactor_core.md#prefactor_core.SchemaRegistry.register) * [`SchemaRegistry.register_quality_schema()`](prefactor_core.md#prefactor_core.SchemaRegistry.register_quality_schema) * [`SchemaRegistry.register_result()`](prefactor_core.md#prefactor_core.SchemaRegistry.register_result) * [`SchemaRegistry.register_type()`](prefactor_core.md#prefactor_core.SchemaRegistry.register_type) * [`SchemaRegistry.register_unsafe()`](prefactor_core.md#prefactor_core.SchemaRegistry.register_unsafe) * [`SchemaRegistry.to_agent_schema_version()`](prefactor_core.md#prefactor_core.SchemaRegistry.to_agent_schema_version) * [`Span`](prefactor_core.md#prefactor_core.Span) * [`Span.id`](prefactor_core.md#prefactor_core.Span.id) * [`Span.instance_id`](prefactor_core.md#prefactor_core.Span.instance_id) * [`Span.parent_span_id`](prefactor_core.md#prefactor_core.Span.parent_span_id) * [`Span.schema_name`](prefactor_core.md#prefactor_core.Span.schema_name) * [`Span.status`](prefactor_core.md#prefactor_core.Span.status) * [`Span.payload`](prefactor_core.md#prefactor_core.Span.payload) * [`Span.created_at`](prefactor_core.md#prefactor_core.Span.created_at) * [`Span.started_at`](prefactor_core.md#prefactor_core.Span.started_at) * [`Span.finished_at`](prefactor_core.md#prefactor_core.Span.finished_at) * [`Span.created_at`](prefactor_core.md#id18) * [`Span.finished_at`](prefactor_core.md#id19) * [`Span.id`](prefactor_core.md#id20) * [`Span.instance_id`](prefactor_core.md#id21) * [`Span.parent_span_id`](prefactor_core.md#id22) * [`Span.payload`](prefactor_core.md#id23) * [`Span.schema_name`](prefactor_core.md#id24) * [`Span.started_at`](prefactor_core.md#id25) * [`Span.status`](prefactor_core.md#id26) * [`SpanContext`](prefactor_core.md#prefactor_core.SpanContext) * [`SpanContext.cancel()`](prefactor_core.md#prefactor_core.SpanContext.cancel) * [`SpanContext.complete()`](prefactor_core.md#prefactor_core.SpanContext.complete) * [`SpanContext.fail()`](prefactor_core.md#prefactor_core.SpanContext.fail) * [`SpanContext.finish()`](prefactor_core.md#prefactor_core.SpanContext.finish) * [`SpanContext.id`](prefactor_core.md#prefactor_core.SpanContext.id) * [`SpanContext.set_result()`](prefactor_core.md#prefactor_core.SpanContext.set_result) * [`SpanContext.start()`](prefactor_core.md#prefactor_core.SpanContext.start) * [`SpanContextStack`](prefactor_core.md#prefactor_core.SpanContextStack) * [`SpanContextStack.depth()`](prefactor_core.md#prefactor_core.SpanContextStack.depth) * [`SpanContextStack.get_stack()`](prefactor_core.md#prefactor_core.SpanContextStack.get_stack) * [`SpanContextStack.is_empty()`](prefactor_core.md#prefactor_core.SpanContextStack.is_empty) * [`SpanContextStack.peek()`](prefactor_core.md#prefactor_core.SpanContextStack.peek) * [`SpanContextStack.pop()`](prefactor_core.md#prefactor_core.SpanContextStack.pop) * [`SpanContextStack.push()`](prefactor_core.md#prefactor_core.SpanContextStack.push) * [`SpanNotFoundError`](prefactor_core.md#prefactor_core.SpanNotFoundError) * [`TaskExecutor`](prefactor_core.md#prefactor_core.TaskExecutor) * [`TaskExecutor.start()`](prefactor_core.md#prefactor_core.TaskExecutor.start) * [`TaskExecutor.stop()`](prefactor_core.md#prefactor_core.TaskExecutor.stop) * [`build_runtime_environment()`](prefactor_core.md#prefactor_core.build_runtime_environment) * [`generate_idempotency_key()`](prefactor_core.md#prefactor_core.generate_idempotency_key) * [`validate_idempotency_key()`](prefactor_core.md#prefactor_core.validate_idempotency_key) * [`warn_missing_adaptor_config()`](prefactor_core.md#prefactor_core.warn_missing_adaptor_config) * [Subpackages](prefactor_core.md#subpackages) * [prefactor\_core.managers package](prefactor_core.managers.md) * [`AgentInstanceHandle`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceHandle) * [`AgentInstanceManager`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceManager) * [`SpanManager`](prefactor_core.managers.md#prefactor_core.managers.SpanManager) * [Submodules](prefactor_core.managers.md#submodules) * [prefactor\_core.monitoring package](prefactor_core.monitoring.md) * [`TerminationMonitor`](prefactor_core.monitoring.md#prefactor_core.monitoring.TerminationMonitor) * [Submodules](prefactor_core.monitoring.md#submodules) * [prefactor\_core.queue package](prefactor_core.queue.md) * [`InMemoryQueue`](prefactor_core.queue.md#prefactor_core.queue.InMemoryQueue) * [`Queue`](prefactor_core.queue.md#prefactor_core.queue.Queue) * [`QueueClosedError`](prefactor_core.queue.md#prefactor_core.queue.QueueClosedError) * [`TaskExecutor`](prefactor_core.queue.md#prefactor_core.queue.TaskExecutor) * [Submodules](prefactor_core.queue.md#submodules) * [Submodules](prefactor_core.md#submodules) * [prefactor\_core.client module](prefactor_core.client.md) * [`PrefactorCoreClient`](prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient) * [prefactor\_core.config module](prefactor_core.config.md) * [`PrefactorCoreConfig`](prefactor_core.config.md#prefactor_core.config.PrefactorCoreConfig) * [`QueueConfig`](prefactor_core.config.md#prefactor_core.config.QueueConfig) * [prefactor\_core.context\_stack module](prefactor_core.context_stack.md) * [`SpanContextStack`](prefactor_core.context_stack.md#prefactor_core.context_stack.SpanContextStack) * [prefactor\_core.exceptions module](prefactor_core.exceptions.md) * [`ClientAlreadyInitializedError`](prefactor_core.exceptions.md#prefactor_core.exceptions.ClientAlreadyInitializedError) * [`ClientNotInitializedError`](prefactor_core.exceptions.md#prefactor_core.exceptions.ClientNotInitializedError) * [`InstanceNotFoundError`](prefactor_core.exceptions.md#prefactor_core.exceptions.InstanceNotFoundError) * [`OperationError`](prefactor_core.exceptions.md#prefactor_core.exceptions.OperationError) * [`PrefactorCoreError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorCoreError) * [`PrefactorTelemetryFailureError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorTelemetryFailureError) * [`PrefactorTerminatedError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorTerminatedError) * [`SpanNotFoundError`](prefactor_core.exceptions.md#prefactor_core.exceptions.SpanNotFoundError) * [prefactor\_core.models module](prefactor_core.models.md) * [`AgentInstance`](prefactor_core.models.md#prefactor_core.models.AgentInstance) * [`Span`](prefactor_core.models.md#prefactor_core.models.Span) * [prefactor\_core.operations module](prefactor_core.operations.md) * [`Operation`](prefactor_core.operations.md#prefactor_core.operations.Operation) * [`OperationType`](prefactor_core.operations.md#prefactor_core.operations.OperationType) * [prefactor\_core.runtime module](prefactor_core.runtime.md) * [`build_runtime_environment()`](prefactor_core.runtime.md#prefactor_core.runtime.build_runtime_environment) * [prefactor\_core.schema\_registry module](prefactor_core.schema_registry.md) * [`SchemaRegistry`](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry) * [prefactor\_core.span\_context module](prefactor_core.span_context.md) * [`SpanContext`](prefactor_core.span_context.md#prefactor_core.span_context.SpanContext) * [prefactor\_core.utils module](prefactor_core.utils.md) * [`generate_idempotency_key()`](prefactor_core.utils.md#prefactor_core.utils.generate_idempotency_key) * [`validate_idempotency_key()`](prefactor_core.utils.md#prefactor_core.utils.validate_idempotency_key) * [`warn_missing_adaptor_config()`](prefactor_core.utils.md#prefactor_core.utils.warn_missing_adaptor_config) # prefactor_core package # prefactor\_core package [Section titled “prefactor\_core package”](#prefactor_core-package) Public API for prefactor-core. This module exports the main classes and functions for the prefactor-core SDK. ### *class* prefactor\_core.AgentInstance(id: str, agent\_id: str, status: str = ‘pending’, purpose: str | None = None, created\_at: datetime = , started\_at: datetime | None = None, finished\_at: datetime | None = None, metadata: dict\[str, \~typing.Any]=, quality\_payloads: dict\[str, dict\[str, \~typing.Any]] | None=None) [Section titled “class prefactor\_core.AgentInstance(id: str, agent\_id: str, status: str = ‘pending’, purpose: str | None = None, created\_at: datetime = , started\_at: datetime | None = None, finished\_at: datetime | None = None, metadata: dict\[str, \~typing.Any\]=, quality\_payloads: dict\[str, dict\[str, \~typing.Any\]\] | None=None)”](#class-prefactor_coreagentinstanceid-str-agent_id-str-status-str--pending-purpose-str--none--none-created_at-datetime---started_at-datetime--none--none-finished_at-datetime--none--none-metadata-dictstr-typingany-quality_payloads-dictstr-dictstr-typingany--nonenone) Bases: `object` Represents an agent instance. An agent instance is a single execution of an agent. It tracks the lifecycle from registration through completion. #### id [Section titled “id”](#id) Unique identifier for this instance. * **Type:** str #### agent\_id [Section titled “agent\_id”](#agent_id) ID of the agent this is an instance of. * **Type:** str #### status [Section titled “status”](#status) Current status (pending, active, complete). * **Type:** str #### created\_at [Section titled “created\_at”](#created_at) When the instance was registered. * **Type:** datetime.datetime #### started\_at [Section titled “started\_at”](#started_at) When the instance started executing (if started). * **Type:** datetime.datetime | None #### finished\_at [Section titled “finished\_at”](#finished_at) When the instance completed (if finished). * **Type:** datetime.datetime | None #### metadata [Section titled “metadata”](#metadata) Additional metadata about the instance. * **Type:** dict\[str, Any] #### agent\_id *: str* [Section titled “agent\_id : str”](#agent_id--str) #### created\_at *: datetime* [Section titled “created\_at : datetime”](#created_at--datetime) #### finished\_at *: datetime | None* *= None* [Section titled “finished\_at : datetime | None = None”](#finished_at--datetime--none--none) #### id *: str* [Section titled “id : str”](#id--str) #### metadata *: dict\[str, Any]* [Section titled “metadata : dict\[str, Any\]”](#metadata--dictstr-any) #### purpose *: str | None* *= None* [Section titled “purpose : str | None = None”](#purpose--str--none--none) #### quality\_payloads *: dict\[str, dict\[str, Any]] | None* *= None* [Section titled “quality\_payloads : dict\[str, dict\[str, Any\]\] | None = None”](#quality_payloads--dictstr-dictstr-any--none--none) #### started\_at *: datetime | None* *= None* [Section titled “started\_at : datetime | None = None”](#started_at--datetime--none--none) #### status *: str* *= ‘pending’* [Section titled “status : str = ‘pending’”](#status--str--pending) ### *class* prefactor\_core.AgentInstanceHandle(instance\_id: str, client: [PrefactorCoreClient](#prefactor_core.PrefactorCoreClient)) [Section titled “class prefactor\_core.AgentInstanceHandle(instance\_id: str, client: PrefactorCoreClient)”](#class-prefactor_coreagentinstancehandleinstance_id-str-client-prefactorcoreclient) Bases: `object` Handle to an agent instance with convenience methods. This class provides a clean interface for: * Starting and finishing the instance * Creating spans within the instance * Managing the instance lifecycle ### Example [Section titled “Example”](#example) async with client.create\_agent\_instance(…) as instance: : await instance.start()\ async with instance.span(“agent:llm”) as span: : span.set\_payload({“model”: “gpt-4”}) # … do work …\ await instance.finish() #### *async* create\_span(schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any] | None = None, started\_at: datetime | None = None) → str [Section titled “async create\_span(schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any\] | None = None, started\_at: datetime | None = None) → str”](#async-create_spanschema_name-str-parent_span_id-str--none--none-payload-dictstr-any--none--none-started_at-datetime--none--none--str) Create a span within this instance and return its ID. The span stays open until finish\_span() is called. * **Parameters:** * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional explicit parent span ID. * **payload** – Optional initial payload (params/inputs) stored on creation. * **started\_at** – Optional ISO 8601 start time (defaults to current time). * **Returns:** The span ID. #### *async* finish(status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None [Section titled “async finish(status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None”](#async-finishstatus-finishstatus--complete-timestamp-datetime--none--none--none) Mark the instance as finished. Resets the termination monitor (fence + new event) before enqueueing the HTTP finish so stale span responses from the dying run cannot trigger termination on the next run. * **Parameters:** * **status** – Terminal status for the instance — one of `"complete"`, `"failed"`, or `"cancelled"`. Defaults to `"complete"`. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* finish\_span(span\_id: str, result\_payload: dict\[str, Any] | None = None, timestamp: datetime | None = None) → None [Section titled “async finish\_span(span\_id: str, result\_payload: dict\[str, Any\] | None = None, timestamp: datetime | None = None) → None”](#async-finish_spanspan_id-str-result_payload-dictstr-any--none--none-timestamp-datetime--none--none--none) Finish a previously created span. * **Parameters:** * **span\_id** – The ID of the span to finish. * **result\_payload** – Optional result data to store on the span. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *property* id *: str* [Section titled “property id : str”](#property-id--str) Get the instance ID. * **Returns:** The unique identifier for this agent instance. #### *async* record\_quality(name: str, payload: dict\[str, Any] | None = None) → None [Section titled “async record\_quality(name: str, payload: dict\[str, Any\] | None = None) → None”](#async-record_qualityname-str-payload-dictstr-any--none--none--none) Record a quality payload on the instance. This queues a record\_quality operation for the instance. * **Parameters:** * **name** – Quality schema name (key in the agent schema version quality\_schemas). * **payload** – Quality payload for this name (None to remove). #### span(schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any] | None = None) [Section titled “span(schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any\] | None = None)”](#spanschema_name-str-parent_span_id-str--none--none-payload-dictstr-any--none--none) Create a span within this instance. This is a convenience method that delegates to the client. * **Parameters:** * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional explicit parent span ID. * **payload** – Optional initial payload (params/inputs) stored on creation. * **Yields:** SpanContext for the created span. #### *async* start(timestamp: datetime | None = None) → None [Section titled “async start(timestamp: datetime | None = None) → None”](#async-starttimestamp-datetime--none--none--none) Mark the instance as started. This queues a start operation for the instance. * **Parameters:** **timestamp** – Optional ISO 8601 start time (defaults to current time). ### *exception* prefactor\_core.ClientAlreadyInitializedError [Section titled “exception prefactor\_core.ClientAlreadyInitializedError”](#exception-prefactor_coreclientalreadyinitializederror) Bases: [`PrefactorCoreError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorCoreError) Raised when attempting to initialize a client that’s already initialized. ### *exception* prefactor\_core.ClientNotInitializedError [Section titled “exception prefactor\_core.ClientNotInitializedError”](#exception-prefactor_coreclientnotinitializederror) Bases: [`PrefactorCoreError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorCoreError) Raised when attempting to use a client that hasn’t been initialized. ### *class* prefactor\_core.InMemoryQueue [Section titled “class prefactor\_core.InMemoryQueue”](#class-prefactor_coreinmemoryqueue) Bases: [`Queue`](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue)\[`T`] Unbounded in-memory queue implementation. This is the default queue implementation. It’s simple, fast, and suitable for most use cases. All data is stored in memory and will be lost if the process terminates before processing completes. The queue uses asyncio.Queue internally for thread-safe operations. ### Example [Section titled “Example”](#example-1) queue = InMemoryQueue() await queue.put(“operation”) item = await queue.get() await queue.close() #### *async* close(num\_waiters: int = 1) → None [Section titled “async close(num\_waiters: int = 1) → None”](#async-closenum_waiters-int--1--none) Close the queue. After closing, no new items can be added. Workers will continue to process existing items until the queue is empty, then exit. * **Parameters:** **num\_waiters** – Number of sentinel values to enqueue to wake up that many workers currently blocked in get(). #### *property* closed *: bool* [Section titled “property closed : bool”](#property-closed--bool) Check if the queue has been closed. * **Returns:** True if the queue is closed. #### *async* get() → T [Section titled “async get() → T”](#async-get--t) Remove and return an item from the queue. * **Returns:** The next item from the queue. * **Raises:** [**QueueClosedError**](#prefactor_core.QueueClosedError) – If the queue is closed and empty. #### *async* put(item: T) → None [Section titled “async put(item: T) → None”](#async-putitem-t--none) Add an item to the queue. * **Parameters:** **item** – The item to add. * **Raises:** [**QueueClosedError**](#prefactor_core.QueueClosedError) – If the queue has been closed. #### size() → int [Section titled “size() → int”](#size--int) Return the current number of items in the queue. * **Returns:** The queue size. ### *exception* prefactor\_core.InstanceNotFoundError [Section titled “exception prefactor\_core.InstanceNotFoundError”](#exception-prefactor_coreinstancenotfounderror) Bases: [`PrefactorCoreError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorCoreError) Raised when an agent instance is not found. ### *class* prefactor\_core.Operation(type: \~prefactor\_core.operations.OperationType, payload: dict\[str, \~typing.Any], timestamp: \~datetime.datetime, idempotency\_key: str | None = None, metadata: dict\[str, \~typing.Any] = ) [Section titled “class prefactor\_core.Operation(type: \~prefactor\_core.operations.OperationType, payload: dict\[str, \~typing.Any\], timestamp: \~datetime.datetime, idempotency\_key: str | None = None, metadata: dict\[str, \~typing.Any\] = )”](#class-prefactor_coreoperationtype-prefactor_coreoperationsoperationtype-payload-dictstr-typingany-timestamp-datetimedatetime-idempotency_key-str--none--none-metadata-dictstr-typingany--) Bases: `object` A single operation to be queued and processed. Operations are immutable and contain all data needed for execution. They are created synchronously and processed asynchronously by workers. #### type [Section titled “type”](#type) The type of operation to perform. * **Type:** [prefactor\_core.operations.OperationType](prefactor_core.operations.md#prefactor_core.operations.OperationType) #### payload [Section titled “payload”](#payload) Dictionary containing operation-specific data. * **Type:** dict\[str, Any] #### timestamp [Section titled “timestamp”](#timestamp) When the operation was created. * **Type:** datetime.datetime #### idempotency\_key [Section titled “idempotency\_key”](#idempotency_key) Optional key for idempotent operations. * **Type:** str | None #### metadata [Section titled “metadata”](#metadata-1) Optional additional metadata. * **Type:** dict\[str, Any] ### Example [Section titled “Example”](#example-2) from datetime import datetime, timezone operation = Operation( : type=OperationType.CREATE\_SPAN, payload={ > “instance\_id”: “inst-123”, “schema\_name”: “agent:llm”, “span\_id”: “span-456” > > }, timestamp=datetime.now(timezone.utc), idempotency\_key=”span-456” ) #### idempotency\_key *: str | None* *= None* [Section titled “idempotency\_key : str | None = None”](#idempotency_key--str--none--none) #### metadata *: dict\[str, Any]* [Section titled “metadata : dict\[str, Any\]”](#metadata--dictstr-any-1) #### payload *: dict\[str, Any]* [Section titled “payload : dict\[str, Any\]”](#payload--dictstr-any) #### timestamp *: datetime* [Section titled “timestamp : datetime”](#timestamp--datetime) #### type *: [OperationType](prefactor_core.operations.md#prefactor_core.operations.OperationType)* [Section titled “type : OperationType”](#type--operationtype) ### *exception* prefactor\_core.OperationError(message: str, operation\_type: str | None = None) [Section titled “exception prefactor\_core.OperationError(message: str, operation\_type: str | None = None)”](#exception-prefactor_coreoperationerrormessage-str-operation_type-str--none--none) Bases: [`PrefactorCoreError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorCoreError) Raised when an operation fails to process. ### *class* prefactor\_core.OperationType(\*values) [Section titled “class prefactor\_core.OperationType(\*values)”](#class-prefactor_coreoperationtypevalues) Bases: `Enum` Types of operations that can be performed. Each operation type corresponds to a specific API endpoint action. #### CREATE\_SPAN *= 5* [Section titled “CREATE\_SPAN = 5”](#create_span--5) #### FINISH\_AGENT\_INSTANCE *= 3* [Section titled “FINISH\_AGENT\_INSTANCE = 3”](#finish_agent_instance--3) #### FINISH\_SPAN *= 6* [Section titled “FINISH\_SPAN = 6”](#finish_span--6) #### RECORD\_QUALITY *= 4* [Section titled “RECORD\_QUALITY = 4”](#record_quality--4) #### REGISTER\_AGENT\_INSTANCE *= 1* [Section titled “REGISTER\_AGENT\_INSTANCE = 1”](#register_agent_instance--1) #### START\_AGENT\_INSTANCE *= 2* [Section titled “START\_AGENT\_INSTANCE = 2”](#start_agent_instance--2) ### *class* prefactor\_core.PrefactorCoreClient(config: [PrefactorCoreConfig](prefactor_core.config.md#prefactor_core.config.PrefactorCoreConfig), queue: [Queue](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue)\[[Operation](prefactor_core.operations.md#prefactor_core.operations.Operation)] | None = None, sdk\_header\_entry: str | None = None) [Section titled “class prefactor\_core.PrefactorCoreClient(config: PrefactorCoreConfig, queue: Queue\[Operation\] | None = None, sdk\_header\_entry: str | None = None)”](#class-prefactor_coreprefactorcoreclientconfig-prefactorcoreconfig-queue-queueoperation--none--none-sdk_header_entry-str--none--none) Bases: `object` Main entry point for the prefactor-core SDK. This client provides a high-level interface for managing agent instances and spans. All operations are queued and processed asynchronously, ensuring minimal impact on agent execution flow. The client must be initialized before use, either by calling initialize() or using it as an async context manager. ### Example [Section titled “Example”](#example-3) config = PrefactorCoreConfig(http\_config=…) async with PrefactorCoreClient(config) as client: : instance = await client.create\_agent\_instance(…) await instance.start()\ async with instance.span(“agent:llm”) as span: : span.set\_payload({“model”: “gpt-4”}) # Your agent logic here\ await instance.finish() #### *async* close() → None [Section titled “async close() → None”](#async-close--none) Close the client and cleanup resources. This method gracefully shuts down the executor and closes the HTTP client. It should be called when the client is no longer needed. #### *async* create\_agent\_instance(agent\_version: dict\[str, Any], agent\_schema\_version: dict\[str, Any] | None = None, agent\_id: str | None = None, instance\_id: str | None = None, external\_schema\_version\_id: str | None = None, environment\_id: str | None = None, purpose: InstancePurpose | None = None, external\_identifier: str | None = None) → [AgentInstanceHandle](#prefactor_core.AgentInstanceHandle) [Section titled “async create\_agent\_instance(agent\_version: dict\[str, Any\], agent\_schema\_version: dict\[str, Any\] | None = None, agent\_id: str | None = None, instance\_id: str | None = None, external\_schema\_version\_id: str | None = None, environment\_id: str | None = None, purpose: InstancePurpose | None = None, external\_identifier: str | None = None) → AgentInstanceHandle”](#async-create_agent_instanceagent_version-dictstr-any-agent_schema_version-dictstr-any--none--none-agent_id-str--none--none-instance_id-str--none--none-external_schema_version_id-str--none--none-environment_id-str--none--none-purpose-instancepurpose--none--none-external_identifier-str--none--none--agentinstancehandle) Create a new agent instance. Returns immediately with a handle. The actual registration happens asynchronously via the queue. If agent\_schema\_version is not provided but the client has a schema\_registry, the registry’s schemas will be used automatically. * **Parameters:** * **agent\_id** – Agent ID. Omit when using a deployment-scoped token. * **agent\_version** – Version information (name, etc.). * **agent\_schema\_version** – Schema version. Uses registry if not provided and registry is configured. * **instance\_id** – Optional custom ID for the instance. * **external\_schema\_version\_id** – Optional external identifier for the schema version. Defaults to “auto-generated” when using registry. * **environment\_id** – Optional environment ID used to scope the agent instance. * **external\_identifier** – Optional external identifier for this agent instance in an external system (unique per agent). * **purpose** – Why this instance ran — `"live"`, `"smoke_test"`, or `"eval"`. Omitted (None) lets the API default to `"live"`. * **Returns:** AgentInstanceHandle for the created instance. * **Raises:** * [**ClientNotInitializedError**](#prefactor_core.ClientNotInitializedError) – If the client is not initialized. * **ValueError** – If no schema version provided and registry not configured. #### *async* create\_span(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any] | None = None, started\_at: datetime | None = None) → str [Section titled “async create\_span(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any\] | None = None, started\_at: datetime | None = None) → str”](#async-create_spaninstance_id-str-schema_name-str-parent_span_id-str--none--none-payload-dictstr-any--none--none-started_at-datetime--none--none--str) Create a span and return its ID without finishing it. Use this for spans that need to stay open across multiple operations. Call finish\_span() when done. * **Parameters:** * **instance\_id** – ID of the agent instance this span belongs to. * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional explicit parent span ID. * **payload** – Optional initial payload (params/inputs) stored on creation. * **started\_at** – Optional ISO 8601 start time (defaults to current time). * **Returns:** The span ID. #### *async* finish\_span(span\_id: str, result\_payload: dict\[str, Any] | None = None, timestamp: datetime | None = None) → None [Section titled “async finish\_span(span\_id: str, result\_payload: dict\[str, Any\] | None = None, timestamp: datetime | None = None) → None”](#async-finish_spanspan_id-str-result_payload-dictstr-any--none--none-timestamp-datetime--none--none--none-1) Finish a previously created span. * **Parameters:** * **span\_id** – The ID of the span to finish. * **result\_payload** – Optional result data to store on the span. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* initialize() → None [Section titled “async initialize() → None”](#async-initialize--none) Initialize the client and start processing. This method: 1. Initializes the HTTP client 2. Starts the task executor 3. Initializes managers * **Raises:** [**ClientAlreadyInitializedError**](#prefactor_core.ClientAlreadyInitializedError) – If already initialized. #### *property* instance\_manager *: [AgentInstanceManager](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceManager) | None* [Section titled “property instance\_manager : AgentInstanceManager | None”](#property-instance_manager--agentinstancemanager--none) Public accessor for the agent instance manager. #### *async* record\_quality(instance\_id: str, name: str, payload: dict\[str, Any] | None = None) → None [Section titled “async record\_quality(instance\_id: str, name: str, payload: dict\[str, Any\] | None = None) → None”](#async-record_qualityinstance_id-str-name-str-payload-dictstr-any--none--none--none) Record a quality payload on an agent instance. * **Parameters:** * **instance\_id** – The ID of the instance to update. * **name** – Quality schema name (key in the agent schema version quality\_schemas). * **payload** – Quality payload for this name, or None to remove the recorded payload for this name. #### span(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any] | None = None) [Section titled “span(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any\] | None = None)”](#spaninstance_id-str-schema_name-str-parent_span_id-str--none--none-payload-dictstr-any--none--none) Context manager for creating and finishing a span. If parent\_span\_id is not provided, the current span from the SpanContextStack is used as the parent. The returned [`SpanContext`](#prefactor_core.SpanContext) supports an explicit lifecycle: 1. `await span.start(payload)` — POST the span to the API. 2. Do work. 3. `await span.complete(result)` / `span.fail(result)` / `span.cancel()` — finish with a specific status. If `start()` or a finish method is not called explicitly, the context manager handles them automatically on exit. * **Parameters:** * **instance\_id** – ID of the agent instance this span belongs to. * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional explicit parent span ID. * **payload** – Optional initial payload sent via auto-start on exit if `start()` is never called explicitly. * **Yields:** SpanContext for the created span. ### *class* prefactor\_core.PrefactorCoreConfig(\*, http\_config: [HttpClientConfig](../../http/reference/prefactor_http.config.md#prefactor_http.config.HttpClientConfig), queue\_config: [QueueConfig](prefactor_core.config.md#prefactor_core.config.QueueConfig) = , schema\_registry: Any = None) [Section titled “class prefactor\_core.PrefactorCoreConfig(\*, http\_config: HttpClientConfig, queue\_config: QueueConfig = , schema\_registry: Any = None)”](#class-prefactor_coreprefactorcoreconfig-http_config-httpclientconfig-queue_config-queueconfig---schema_registry-any--none) Bases: `BaseModel` Complete configuration for PrefactorCoreClient. #### http\_config [Section titled “http\_config”](#http_config) Configuration for the HTTP client. * **Type:** [prefactor\_http.config.HttpClientConfig](../../http/reference/prefactor_http.config.md#prefactor_http.config.HttpClientConfig) #### queue\_config [Section titled “queue\_config”](#queue_config) Configuration for queue processing. * **Type:** [prefactor\_core.config.QueueConfig](prefactor_core.config.md#prefactor_core.config.QueueConfig) #### schema\_registry [Section titled “schema\_registry”](#schema_registry) Optional schema registry for aggregating span type definitions. * **Type:** Any ### Example [Section titled “Example”](#example-4) from prefactor\_core.schema\_registry import SchemaRegistry from prefactor\_core import PrefactorCoreConfig registry = SchemaRegistry() registry.register(“langchain:llm”, {“type”: “object”}) config = PrefactorCoreConfig( : http\_config=HttpClientConfig(…), schema\_registry=registry ) #### http\_config *: [HttpClientConfig](../../http/reference/prefactor_http.md#prefactor_http.HttpClientConfig)* [Section titled “http\_config : HttpClientConfig”](#http_config--httpclientconfig) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config--) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### queue\_config *: [QueueConfig](#prefactor_core.QueueConfig)* [Section titled “queue\_config : QueueConfig”](#queue_config--queueconfig) #### schema\_registry *: Any* [Section titled “schema\_registry : Any”](#schema_registry--any) ### *exception* prefactor\_core.PrefactorCoreError [Section titled “exception prefactor\_core.PrefactorCoreError”](#exception-prefactor_coreprefactorcoreerror) Bases: `Exception` Base exception for all prefactor-core errors. ### *exception* prefactor\_core.PrefactorTelemetryFailureError(message: str, , cause: Exception, operation\_type: str | None = None, dropped\_operations: int = 0) [Section titled “exception prefactor\_core.PrefactorTelemetryFailureError(message: str, , cause: Exception, operation\_type: str | None = None, dropped\_operations: int = 0)”](#exception-prefactor_coreprefactortelemetryfailureerrormessage-str--cause-exception-operation_type-str--none--none-dropped_operations-int--0) Bases: [`PrefactorCoreError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorCoreError) Raised when telemetry enters a permanent failure state. ### *exception* prefactor\_core.PrefactorTerminatedError(reason: str | None = None) [Section titled “exception prefactor\_core.PrefactorTerminatedError(reason: str | None = None)”](#exception-prefactor_coreprefactorterminatederrorreason-str--none--none) Bases: [`PrefactorCoreError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorCoreError) Raised when the agent instance has been terminated by p2. * **Parameters:** **reason** – Optional reason reported by p2 for the termination. ### *class* prefactor\_core.Queue [Section titled “class prefactor\_core.Queue”](#class-prefactor_corequeue) Bases: `ABC`, `Generic`\[`T`] Abstract base class for all queue implementations. This interface defines the contract for queue operations used by the TaskExecutor. Implementations must be thread-safe and support async operations. #### *abstractmethod async* close(num\_waiters: int = 1) → None [Section titled “abstractmethod async close(num\_waiters: int = 1) → None”](#abstractmethod-async-closenum_waiters-int--1--none) Close the queue and signal workers to stop. After closing, no new items can be added. Workers should finish processing remaining items and then exit. * **Parameters:** **num\_waiters** – Number of workers currently blocked in get() that need to be woken up so they can observe the closed state. #### *abstract property* closed *: bool* [Section titled “abstract property closed : bool”](#abstract-property-closed--bool) Check if the queue has been closed. * **Returns:** True if close() has been called, False otherwise. #### *abstractmethod async* get() → T [Section titled “abstractmethod async get() → T”](#abstractmethod-async-get--t) Remove and return an item from the queue. This method blocks until an item is available or the queue is closed. * **Returns:** The next item from the queue. * **Raises:** [**QueueClosedError**](#prefactor_core.QueueClosedError) – If the queue is closed and empty. #### *abstractmethod async* put(item: T) → None [Section titled “abstractmethod async put(item: T) → None”](#abstractmethod-async-putitem-t--none) Add an item to the queue. This method should return immediately without blocking the caller. The item will be processed asynchronously by workers. * **Parameters:** **item** – The item to add to the queue. * **Raises:** [**QueueClosedError**](#prefactor_core.QueueClosedError) – If the queue has been closed. #### *abstractmethod* size() → int [Section titled “abstractmethod size() → int”](#abstractmethod-size--int) Return the current number of items in the queue. * **Returns:** The queue size (non-negative integer). ### *exception* prefactor\_core.QueueClosedError [Section titled “exception prefactor\_core.QueueClosedError”](#exception-prefactor_corequeueclosederror) Bases: `Exception` Raised when attempting to use a closed queue. ### *class* prefactor\_core.QueueConfig(, num\_workers: Annotated\[int, Ge(ge=1), Le(le=20)] = 3, max\_retries: Annotated\[int, Ge(ge=0)] = 3, retry\_delay\_base: Annotated\[float, Gt(gt=0)] = 1.0) [Section titled “class prefactor\_core.QueueConfig(, num\_workers: Annotated\[int, Ge(ge=1), Le(le=20)\] = 3, max\_retries: Annotated\[int, Ge(ge=0)\] = 3, retry\_delay\_base: Annotated\[float, Gt(gt=0)\] = 1.0)”](#class-prefactor_corequeueconfig-num_workers-annotatedint-gege1-lele20--3-max_retries-annotatedint-gege0--3-retry_delay_base-annotatedfloat-gtgt0--10) Bases: `BaseModel` Configuration for queue processing. #### num\_workers [Section titled “num\_workers”](#num_workers) Number of concurrent worker tasks. * **Type:** int #### max\_retries [Section titled “max\_retries”](#max_retries) Maximum retry attempts per failed operation. * **Type:** int #### retry\_delay\_base [Section titled “retry\_delay\_base”](#retry_delay_base) Base delay for exponential backoff (seconds). * **Type:** float #### max\_retries *: int* [Section titled “max\_retries : int”](#max_retries--int) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### num\_workers *: int* [Section titled “num\_workers : int”](#num_workers--int) #### retry\_delay\_base *: float* [Section titled “retry\_delay\_base : float”](#retry_delay_base--float) ### *class* prefactor\_core.SchemaRegistry [Section titled “class prefactor\_core.SchemaRegistry”](#class-prefactor_coreschemaregistry) Bases: `object` Central registry for span schemas - allows pre-registration. Multiple components can register their schemas independently before agent instance creation. The registry aggregates all into a single format suitable for the API. The API supports three ways to define span schemas, in increasing order of expressiveness: * `span_schemas`: flat map of span name → params JSON schema * `span_result_schemas`: flat map of span name → result JSON schema * `span_type_schemas`: structured list with params, result, title, description, and template per span type Use `register()` for simple payload schemas, `register_result()` to add a result schema for an existing entry, `register_type()` for the full structured form, or `register_quality_schema()` for named quality schemas. All approaches can be mixed; `to_agent_schema_version()` emits whichever fields are populated. ### Example [Section titled “Example”](#example-5) registry = SchemaRegistry() # Simple params-only schema [Section titled “Simple params-only schema”](#simple-params-only-schema) registry.register(“langchain:agent”, {“type”: “object”}) # Full structured schema with result and display metadata [Section titled “Full structured schema with result and display metadata”](#full-structured-schema-with-result-and-display-metadata) registry.register\_type( > name=”agent:llm”, params\_schema={ > > “type”: “object”, “properties”: { > > > “model”: {“type”: “string”}, “prompt”: {“type”: “string”}, > > }, “required”: \[“model”, “prompt”], > }, result\_schema={ > > “type”: “object”, “properties”: {“response”: {“type”: “string”}}, > }, title=”LLM Call”, description=”A call to a language model”, template=”{{model}}: {{prompt}} → {{response}}”, ) # Convert to API format [Section titled “Convert to API format”](#convert-to-api-format) version = registry.to\_agent\_schema\_version(“combined-1.0.0”) #### get(schema\_name: str) → dict\[str, Any] | None [Section titled “get(schema\_name: str) → dict\[str, Any\] | None”](#getschema_name-str--dictstr-any--none) Get a params schema by name. * **Parameters:** **schema\_name** – The schema identifier to look up * **Returns:** The schema dict if found, None otherwise #### has\_schema(schema\_name: str) → bool [Section titled “has\_schema(schema\_name: str) → bool”](#has_schemaschema_name-str--bool) Check if a params schema is registered for a span type. * **Parameters:** **schema\_name** – The schema identifier to check * **Returns:** True if the schema is registered, False otherwise #### list\_schemas() → list\[str] [Section titled “list\_schemas() → list\[str\]”](#list_schemas--liststr) List all registered span schema names (params schemas only). * **Returns:** List of registered schema names #### merge(other: [SchemaRegistry](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry)) → None [Section titled “merge(other: SchemaRegistry) → None”](#mergeother-schemaregistry--none) Merge schemas from another registry into this one. * **Parameters:** **other** – Another SchemaRegistry to merge. Conflicting schemas from the other registry will be rejected. * **Raises:** **ValueError** – If there are conflicting schema names in any category. #### register(schema\_name: str, schema: dict\[str, Any]) → None [Section titled “register(schema\_name: str, schema: dict\[str, Any\]) → None”](#registerschema_name-str-schema-dictstr-any--none) Register a params schema for a span type. Adds to `span_schemas` (the flat params-schema map). Use `register_type()` if you also need a result schema, title, description, or template. * **Parameters:** * **schema\_name** – Unique identifier for this span type (e.g., “langchain:llm”) * **schema** – JSON Schema dict defining the span payload structure * **Raises:** **ValueError** – If schema\_name is already registered. #### register\_quality\_schema(name: str, schema: dict\[str, Any], title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: dict\[str, Any] | None = None) → None [Section titled “register\_quality\_schema(name: str, schema: dict\[str, Any\], title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: dict\[str, Any\] | None = None) → None”](#register_quality_schemaname-str-schema-dictstr-any-title-str--none--none-description-str--none--none-template-str--none--none-data_risk-dictstr-any--none--none--none) Register a named quality schema for instance evaluations. Quality schemas define the shape of quality payloads that can be recorded on agent instances. Multiple quality schemas can be registered, each identified by a unique `name`. * **Parameters:** * **name** – Schema name (key used when recording quality payloads). * **schema** – JSON Schema dict defining the quality payload structure. * **title** – Optional human-readable title (defaults to name on API). * **description** – Optional description of the quality evaluation. * **template** – Optional display template using `{{field}}` interpolation. * **data\_risk** – Optional data risk classification dict (same structure as span type data\_risk). * **Raises:** **ValueError** – If a quality schema with the same name is already registered. #### register\_result(schema\_name: str, result\_schema: dict\[str, Any]) → None [Section titled “register\_result(schema\_name: str, result\_schema: dict\[str, Any\]) → None”](#register_resultschema_name-str-result_schema-dictstr-any--none) Register a result schema for a span type. Adds to `span_result_schemas` (the flat result-schema map). The span type does not need to have a params schema registered first. * **Parameters:** * **schema\_name** – Span type identifier (e.g., “agent:llm”) * **result\_schema** – JSON Schema dict defining the span result payload * **Raises:** **ValueError** – If a result schema for schema\_name is already registered. #### register\_type(name: str, params\_schema: dict\[str, Any], result\_schema: dict\[str, Any] | None = None, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: dict\[str, Any] | None = None) → None [Section titled “register\_type(name: str, params\_schema: dict\[str, Any\], result\_schema: dict\[str, Any\] | None = None, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: dict\[str, Any\] | None = None) → None”](#register_typename-str-params_schema-dictstr-any-result_schema-dictstr-any--none--none-title-str--none--none-description-str--none--none-template-str--none--none-data_risk-dictstr-any--none--none--none) Register a full structured span type schema. Adds to `span_type_schemas`. This is the richest form and supports all API fields: params schema, result schema, human-readable title, description, template, and data risk classification. * **Parameters:** * **name** – Span type name (e.g., “agent:llm”) * **params\_schema** – JSON Schema for the span payload (params) * **result\_schema** – Optional JSON Schema for the span result payload * **title** – Optional human-readable title (defaults to name on the API) * **description** – Optional description of the span type * **template** – Optional display template using `{{field}}` interpolation * **data\_risk** – Optional data risk classification dict. See DataRisk model in prefactor\_http.models.agent\_instance for structure. Must include: * action\_profile (object): Permitted actions with keys: > create\_data, read\_data, update\_data, destroy\_data, financial\_transactions, external\_communication (values: “unknown” | “allowed” | “disallowed”) * params\_data\_categories (object): Input data categories with keys like personal\_identifiers, contact\_information, financial\_information, etc. (values: “unknown” | “included” | “excluded”) * result\_data\_categories (object): Output data categories, same structure as params\_data\_categories All three top-level keys are required; fields within each default to “unknown” when omitted. Example: { > ”action\_profile”: {“read\_data”: “allowed”}, “params\_data\_categories”: {“personal\_identifiers”: “included”}, “result\_data\_categories”: {}, } * **Raises:** **ValueError** – If name is already registered as a span type schema. #### register\_unsafe(schema\_name: str, schema: dict\[str, Any]) → None [Section titled “register\_unsafe(schema\_name: str, schema: dict\[str, Any\]) → None”](#register_unsafeschema_name-str-schema-dictstr-any--none) Register a params schema, overwriting if it already exists. * **Parameters:** * **schema\_name** – Unique identifier for this span type * **schema** – JSON Schema dict defining the span payload structure #### to\_agent\_schema\_version(external\_id: str) → dict\[str, Any] [Section titled “to\_agent\_schema\_version(external\_id: str) → dict\[str, Any\]”](#to_agent_schema_versionexternal_id-str--dictstr-any) Convert registry contents to API-compatible agent\_schema\_version format. Emits `span_schemas`, `span_result_schemas`, `span_type_schemas`, and `quality_schemas` for whichever have been populated. * **Parameters:** **external\_id** – External identifier for this combined schema version * **Returns:** Dict with `external_identifier` and whichever schema fields are non-empty. ### *class* prefactor\_core.Span(id: str, instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, status: str = ‘pending’, payload: dict\[str, \~typing.Any]=, created\_at: datetime = , started\_at: datetime | None = None, finished\_at: datetime | None = None) [Section titled “class prefactor\_core.Span(id: str, instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, status: str = ‘pending’, payload: dict\[str, \~typing.Any\]=, created\_at: datetime = , started\_at: datetime | None = None, finished\_at: datetime | None = None)”](#class-prefactor_corespanid-str-instance_id-str-schema_name-str-parent_span_id-str--none--none-status-str--pending-payload-dictstr-typingany-created_at-datetime---started_at-datetime--none--none-finished_at-datetime--none--none) Bases: `object` Represents a span within an agent instance. Spans represent discrete units of work within an agent execution, such as LLM calls, tool executions, or processing steps. #### id [Section titled “id”](#id-1) Unique identifier for this span. * **Type:** str #### instance\_id [Section titled “instance\_id”](#instance_id) ID of the agent instance this span belongs to. * **Type:** str #### parent\_span\_id [Section titled “parent\_span\_id”](#parent_span_id) ID of the parent span (if nested). * **Type:** str | None #### schema\_name [Section titled “schema\_name”](#schema_name) Name of the schema defining this span type. * **Type:** str #### status [Section titled “status”](#status-1) Current status (pending, active, complete). * **Type:** str #### payload [Section titled “payload”](#payload-1) Arbitrary data associated with this span. * **Type:** dict\[str, Any] #### created\_at [Section titled “created\_at”](#created_at-1) When the span was created. * **Type:** datetime.datetime #### started\_at [Section titled “started\_at”](#started_at-1) When the span started (defaults to created\_at). * **Type:** datetime.datetime | None #### finished\_at [Section titled “finished\_at”](#finished_at-1) When the span completed (if finished). * **Type:** datetime.datetime | None #### created\_at *: datetime* [Section titled “created\_at : datetime”](#created_at--datetime-1) #### finished\_at *: datetime | None* *= None* [Section titled “finished\_at : datetime | None = None”](#finished_at--datetime--none--none-1) #### id *: str* [Section titled “id : str”](#id--str-1) #### instance\_id *: str* [Section titled “instance\_id : str”](#instance_id--str) #### parent\_span\_id *: str | None* *= None* [Section titled “parent\_span\_id : str | None = None”](#parent_span_id--str--none--none) #### payload *: dict\[str, Any]* [Section titled “payload : dict\[str, Any\]”](#payload--dictstr-any-1) #### schema\_name *: str* [Section titled “schema\_name : str”](#schema_name--str) #### started\_at *: datetime | None* *= None* [Section titled “started\_at : datetime | None = None”](#started_at--datetime--none--none-1) #### status *: str* *= ‘pending’* [Section titled “status : str = ‘pending’”](#status--str--pending-1) ### *class* prefactor\_core.SpanContext(temp\_id: str, span\_manager: [SpanManager](prefactor_core.managers.md#prefactor_core.managers.SpanManager), default\_payload: dict\[str, Any] | None = None) [Section titled “class prefactor\_core.SpanContext(temp\_id: str, span\_manager: SpanManager, default\_payload: dict\[str, Any\] | None = None)”](#class-prefactor_corespancontexttemp_id-str-span_manager-spanmanager-default_payload-dictstr-any--none--none) Bases: `object` Context for an active span. Returned by `instance.span()` / `client.span()` context managers. Spans follow a three-phase lifecycle: 1. **Enter context** — span is prepared locally (no HTTP call yet). 2. **“await span.start(payload)“** — POSTs the span to the API as `active` with the given params payload. 3. **“await span.complete(result)“** (or `.fail()` / `.cancel()`) — finishes the span with the appropriate terminal status. `cancelled` before start is handled via `pending → cancelled`; once started, the span transitions from `active` to a terminal status. If `start()` or a finish method is omitted, the context manager calls them automatically on exit (auto-start uses `default_payload`; the default finish status is `complete`), so explicit calls are opt-in. Example: ```default async with instance.span("agent:llm_call") as span: await span.start({"model": "claude-3-5-sonnet", "prompt": "Hi"}) try: response = await call_llm(...) await span.complete({"response": response, "tokens": 42}) except Exception as exc: await span.fail({"error": str(exc)}) # Skip start entirely to cancel before any work begins: async with instance.span("agent:retrieval") as span: if not needed: await span.cancel() else: await span.start({"query": "..."}) ... ``` #### *async* cancel(timestamp: datetime | None = None) → None [Section titled “async cancel(timestamp: datetime | None = None) → None”](#async-canceltimestamp-datetime--none--none--none) Finish the span with `cancelled` status. Can be called before or after `start()`. If `start()` has not been called yet, the span is posted as `pending` then immediately cancelled — the API only accepts cancellation from the `pending` state, so this is always a valid sequence. * **Parameters:** **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* complete(result: dict\[str, Any] | None = None, timestamp: datetime | None = None) → None [Section titled “async complete(result: dict\[str, Any\] | None = None, timestamp: datetime | None = None) → None”](#async-completeresult-dictstr-any--none--none-timestamp-datetime--none--none--none) Finish the span with `complete` status. * **Parameters:** * **result** – Optional result payload to attach to the span. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* fail(result: dict\[str, Any] | None = None, timestamp: datetime | None = None) → None [Section titled “async fail(result: dict\[str, Any\] | None = None, timestamp: datetime | None = None) → None”](#async-failresult-dictstr-any--none--none-timestamp-datetime--none--none--none) Finish the span with `failed` status. * **Parameters:** * **result** – Optional result payload (e.g. error details). * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* finish() → None [Section titled “async finish() → None”](#async-finish--none) Finish the span using whichever status was last set (default: `complete`). Called automatically when exiting the context manager. Can also be called manually; subsequent calls are no-ops. #### *property* id *: str* [Section titled “property id : str”](#property-id--str-1) Get the span ID. Before `start()` is called this returns the temporary local ID. After `start()` it returns the API-generated ID. * **Returns:** The span identifier. #### set\_result(data: dict\[str, Any]) → None [Section titled “set\_result(data: dict\[str, Any\]) → None”](#set_resultdata-dictstr-any--none) Store result data to be sent when the span finishes. The data is merged and sent as `result_payload` when the span finishes. Calling this does **not** finish the span. * **Parameters:** **data** – Dictionary of result data for the span. #### *async* start(payload: dict\[str, Any] | None = None, started\_at: datetime | None = None) → None [Section titled “async start(payload: dict\[str, Any\] | None = None, started\_at: datetime | None = None) → None”](#async-startpayload-dictstr-any--none--none-started_at-datetime--none--none--none) Post the span to the API as `active` with the given params payload. This triggers `POST /api/v1/agent_spans`. The span is created as `pending` so that any terminal status (`complete`, `failed`, `cancelled`) is a valid transition via the finish endpoint. Must be called at most once; subsequent calls are no-ops. * **Parameters:** * **payload** – Optional params/inputs for the span (e.g. model name, prompt text, tool input). Stored as the span’s `payload` field in the API. * **started\_at** – Optional ISO 8601 start time (defaults to current time). ### *class* prefactor\_core.SpanContextStack [Section titled “class prefactor\_core.SpanContextStack”](#class-prefactor_corespancontextstack) Bases: `object` Manages a stack of active span IDs within an async context. The stack tracks the hierarchy of nested spans. The top of the stack is always the current (innermost) active span, which serves as the default parent for any new spans created within the same context. This class uses contextvars to ensure that each async task maintains its own independent stack, preventing interference between concurrent operations. ### Example [Section titled “Example”](#example-6) # Root span [Section titled “Root span”](#root-span) SpanContextStack.push(“span-1”) assert SpanContextStack.peek() == “span-1” # Nested span (child of span-1) [Section titled “Nested span (child of span-1)”](#nested-span-child-of-span-1) SpanContextStack.push(“span-2”) assert SpanContextStack.peek() == “span-2” # Exit nested span [Section titled “Exit nested span”](#exit-nested-span) SpanContextStack.pop() assert SpanContextStack.peek() == “span-1” # Exit root span [Section titled “Exit root span”](#exit-root-span) SpanContextStack.pop() assert SpanContextStack.peek() is None #### *classmethod* depth() → int [Section titled “classmethod depth() → int”](#classmethod-depth--int) Get the current nesting depth. * **Returns:** The number of active spans in the stack (0 if empty). #### *classmethod* get\_stack() → list\[str] [Section titled “classmethod get\_stack() → list\[str\]”](#classmethod-get_stack--liststr) Get the current span stack for this async context. * **Returns:** A list of span IDs, from outermost to innermost. Returns an empty list if no spans are active. #### *classmethod* is\_empty() → bool [Section titled “classmethod is\_empty() → bool”](#classmethod-is_empty--bool) Check if the stack is empty. * **Returns:** True if no spans are currently active. #### *classmethod* peek() → str | None [Section titled “classmethod peek() → str | None”](#classmethod-peek--str--none) Get the current span ID without removing it from the stack. * **Returns:** The ID of the current (innermost) span, or None if no spans are active in this context. #### *classmethod* pop() → str | None [Section titled “classmethod pop() → str | None”](#classmethod-pop--str--none) Pop and return the current span ID from the stack. * **Returns:** The span ID that was removed from the stack, or None if the stack was empty. #### *classmethod* push(span\_id: str) → None [Section titled “classmethod push(span\_id: str) → None”](#classmethod-pushspan_id-str--none) Push a span ID onto the stack. This marks the span as the current (innermost) active span. * **Parameters:** **span\_id** – The ID of the span to push onto the stack. ### *exception* prefactor\_core.SpanNotFoundError [Section titled “exception prefactor\_core.SpanNotFoundError”](#exception-prefactor_corespannotfounderror) Bases: [`PrefactorCoreError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorCoreError) Raised when a span is not found. ### *class* prefactor\_core.TaskExecutor(queue: [Queue](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue)\[Any], handler: Callable\[\[Any], Awaitable\[None]], num\_workers: int = 3, max\_retries: int = 3, , is\_retryable: Callable\[\[Exception], bool] | None = None) [Section titled “class prefactor\_core.TaskExecutor(queue: Queue\[Any\], handler: Callable\[\[Any\], Awaitable\[None\]\], num\_workers: int = 3, max\_retries: int = 3, , is\_retryable: Callable\[\[Exception\], bool\] | None = None)”](#class-prefactor_coretaskexecutorqueue-queueany-handler-callableany-awaitablenone-num_workers-int--3-max_retries-int--3--is_retryable-callableexception-bool--none--none) Bases: `object` Manages async workers that process queue items. The executor runs a configurable number of worker tasks that continuously pull items from the queue and process them. If processing fails, items are retried with exponential backoff. ### Example [Section titled “Example”](#example-7) async def handler(item: str) -> None: : print(f”Processing: {item}”) queue = InMemoryQueue() executor = TaskExecutor(queue, handler, num\_workers=3) executor.start() await queue.put(“item1”) await queue.put(“item2”) # Later, when done [Section titled “Later, when done”](#later-when-done) await executor.stop() #### start() → None [Section titled “start() → None”](#start--none) Start the worker tasks. Workers will begin pulling items from the queue immediately. #### *async* stop() → None [Section titled “async stop() → None”](#async-stop--none) Stop all workers gracefully. Closes the queue (so no new items can be added), wakes any workers blocked in get(), and waits for them to drain the remaining items and exit on their own. Workers are never cancelled — that would discard already-queued items. ### prefactor\_core.build\_runtime\_environment(sdk\_header\_entry: str | None = None) → dict [Section titled “prefactor\_core.build\_runtime\_environment(sdk\_header\_entry: str | None = None) → dict”](#prefactor_corebuild_runtime_environmentsdk_header_entry-str--none--none--dict) Build the `runtime_environment` dict for `agent_version`. Parses *sdk\_header\_entry* (a space-separated list of `"pkg@ver"` tokens as set by upstream adaptors) into `agent_sdk` entries. Always includes `prefactor_sdk`, `os`, and `runtime`. * **Parameters:** **sdk\_header\_entry** – Space-separated SDK header string set by upstream adaptors (e.g. `"prefactor-langchain@0.2.7"`). The trailing `prefactor-core@...` self-entry added by the client is automatically stripped from `agent_sdk`. * **Returns:** A dict with keys `agent_sdk`, `os`, `prefactor_sdk`, and `runtime`, suitable for use as the `runtime_environment` field of `agent_version`. ### prefactor\_core.generate\_idempotency\_key() → str [Section titled “prefactor\_core.generate\_idempotency\_key() → str”](#prefactor_coregenerate_idempotency_key--str) Generate a new UUID-based idempotency key. The returned key is a UUID4 string (36 characters), always within the 64-character API limit. * **Returns:** A unique idempotency key string. ### prefactor\_core.validate\_idempotency\_key(key: str) → str [Section titled “prefactor\_core.validate\_idempotency\_key(key: str) → str”](#prefactor_corevalidate_idempotency_keykey-str--str) Validate that an idempotency key is a non-empty string of at most 64 characters. * **Parameters:** **key** – The idempotency key to validate. * **Returns:** The key unchanged if valid. * **Raises:** **ValueError** – If the key is empty or exceeds 64 characters. ### prefactor\_core.warn\_missing\_adaptor\_config(instance\_id: str, adaptor\_name: str, create\_client\_call: str) → None [Section titled “prefactor\_core.warn\_missing\_adaptor\_config(instance\_id: str, adaptor\_name: str, create\_client\_call: str) → None”](#prefactor_corewarn_missing_adaptor_configinstance_id-str-adaptor_name-str-create_client_call-str--none) Warn that an instance was registered before the adaptor configured the client. Called by framework adaptors (langchain, livekit, etc.) when a pre-created instance is passed in and the backing client wasn’t set up through `create_client()` or `from_config()`. * **Parameters:** * **instance\_id** – The agent instance ID that was registered too early. * **adaptor\_name** – Human-readable adaptor name (e.g. `"middleware"`). * **create\_client\_call** – The call the user should use instead (e.g. `"PrefactorMiddleware.create_client(config)"`). ## Subpackages [Section titled “Subpackages”](#subpackages) * [prefactor\_core.managers package](prefactor_core.managers.md) * [`AgentInstanceHandle`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceHandle) * [`AgentInstanceHandle.create_span()`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceHandle.create_span) * [`AgentInstanceHandle.finish()`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceHandle.finish) * [`AgentInstanceHandle.finish_span()`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceHandle.finish_span) * [`AgentInstanceHandle.id`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceHandle.id) * [`AgentInstanceHandle.record_quality()`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceHandle.record_quality) * [`AgentInstanceHandle.span()`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceHandle.span) * [`AgentInstanceHandle.start()`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceHandle.start) * [`AgentInstanceManager`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceManager) * [`AgentInstanceManager.finish()`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceManager.finish) * [`AgentInstanceManager.finish_with_idempotency_key()`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceManager.finish_with_idempotency_key) * [`AgentInstanceManager.record_quality()`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceManager.record_quality) * [`AgentInstanceManager.register()`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceManager.register) * [`AgentInstanceManager.start()`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceManager.start) * [`AgentInstanceManager.start_with_idempotency_key()`](prefactor_core.managers.md#prefactor_core.managers.AgentInstanceManager.start_with_idempotency_key) * [`SpanManager`](prefactor_core.managers.md#prefactor_core.managers.SpanManager) * [`SpanManager.cancel_unstarted()`](prefactor_core.managers.md#prefactor_core.managers.SpanManager.cancel_unstarted) * [`SpanManager.create()`](prefactor_core.managers.md#prefactor_core.managers.SpanManager.create) * [`SpanManager.finish()`](prefactor_core.managers.md#prefactor_core.managers.SpanManager.finish) * [`SpanManager.get_span()`](prefactor_core.managers.md#prefactor_core.managers.SpanManager.get_span) * [`SpanManager.prepare()`](prefactor_core.managers.md#prefactor_core.managers.SpanManager.prepare) * [`SpanManager.start()`](prefactor_core.managers.md#prefactor_core.managers.SpanManager.start) * [Submodules](prefactor_core.managers.md#submodules) * [prefactor\_core.managers.agent\_instance module](prefactor_core.managers.agent_instance.md) * [`AgentInstanceHandle`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle) * [`AgentInstanceManager`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceManager) * [prefactor\_core.managers.span module](prefactor_core.managers.span.md) * [`SpanManager`](prefactor_core.managers.span.md#prefactor_core.managers.span.SpanManager) * [prefactor\_core.monitoring package](prefactor_core.monitoring.md) * [`TerminationMonitor`](prefactor_core.monitoring.md#prefactor_core.monitoring.TerminationMonitor) * [`TerminationMonitor.destroy()`](prefactor_core.monitoring.md#prefactor_core.monitoring.TerminationMonitor.destroy) * [`TerminationMonitor.detect_termination()`](prefactor_core.monitoring.md#prefactor_core.monitoring.TerminationMonitor.detect_termination) * [`TerminationMonitor.get_termination_event()`](prefactor_core.monitoring.md#prefactor_core.monitoring.TerminationMonitor.get_termination_event) * [`TerminationMonitor.reset()`](prefactor_core.monitoring.md#prefactor_core.monitoring.TerminationMonitor.reset) * [`TerminationMonitor.subscribe()`](prefactor_core.monitoring.md#prefactor_core.monitoring.TerminationMonitor.subscribe) * [`TerminationMonitor.sync()`](prefactor_core.monitoring.md#prefactor_core.monitoring.TerminationMonitor.sync) * [`TerminationMonitor.termination_reason`](prefactor_core.monitoring.md#prefactor_core.monitoring.TerminationMonitor.termination_reason) * [Submodules](prefactor_core.monitoring.md#submodules) * [prefactor\_core.monitoring.termination\_monitor module](prefactor_core.monitoring.termination_monitor.md) * [`TerminationMonitor`](prefactor_core.monitoring.termination_monitor.md#prefactor_core.monitoring.termination_monitor.TerminationMonitor) * [prefactor\_core.queue package](prefactor_core.queue.md) * [`InMemoryQueue`](prefactor_core.queue.md#prefactor_core.queue.InMemoryQueue) * [`InMemoryQueue.close()`](prefactor_core.queue.md#prefactor_core.queue.InMemoryQueue.close) * [`InMemoryQueue.closed`](prefactor_core.queue.md#prefactor_core.queue.InMemoryQueue.closed) * [`InMemoryQueue.get()`](prefactor_core.queue.md#prefactor_core.queue.InMemoryQueue.get) * [`InMemoryQueue.put()`](prefactor_core.queue.md#prefactor_core.queue.InMemoryQueue.put) * [`InMemoryQueue.size()`](prefactor_core.queue.md#prefactor_core.queue.InMemoryQueue.size) * [`Queue`](prefactor_core.queue.md#prefactor_core.queue.Queue) * [`Queue.close()`](prefactor_core.queue.md#prefactor_core.queue.Queue.close) * [`Queue.closed`](prefactor_core.queue.md#prefactor_core.queue.Queue.closed) * [`Queue.get()`](prefactor_core.queue.md#prefactor_core.queue.Queue.get) * [`Queue.put()`](prefactor_core.queue.md#prefactor_core.queue.Queue.put) * [`Queue.size()`](prefactor_core.queue.md#prefactor_core.queue.Queue.size) * [`QueueClosedError`](prefactor_core.queue.md#prefactor_core.queue.QueueClosedError) * [`TaskExecutor`](prefactor_core.queue.md#prefactor_core.queue.TaskExecutor) * [`TaskExecutor.start()`](prefactor_core.queue.md#prefactor_core.queue.TaskExecutor.start) * [`TaskExecutor.stop()`](prefactor_core.queue.md#prefactor_core.queue.TaskExecutor.stop) * [Submodules](prefactor_core.queue.md#submodules) * [prefactor\_core.queue.base module](prefactor_core.queue.base.md) * [`Queue`](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue) * [`QueueClosedError`](prefactor_core.queue.base.md#prefactor_core.queue.base.QueueClosedError) * [prefactor\_core.queue.executor module](prefactor_core.queue.executor.md) * [`TaskExecutor`](prefactor_core.queue.executor.md#prefactor_core.queue.executor.TaskExecutor) * [prefactor\_core.queue.memory module](prefactor_core.queue.memory.md) * [`InMemoryQueue`](prefactor_core.queue.memory.md#prefactor_core.queue.memory.InMemoryQueue) ## Submodules [Section titled “Submodules”](#submodules) * [prefactor\_core.client module](prefactor_core.client.md) * [`PrefactorCoreClient`](prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient) * [`PrefactorCoreClient.close()`](prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient.close) * [`PrefactorCoreClient.create_agent_instance()`](prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient.create_agent_instance) * [`PrefactorCoreClient.create_span()`](prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient.create_span) * [`PrefactorCoreClient.finish_span()`](prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient.finish_span) * [`PrefactorCoreClient.initialize()`](prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient.initialize) * [`PrefactorCoreClient.instance_manager`](prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient.instance_manager) * [`PrefactorCoreClient.record_quality()`](prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient.record_quality) * [`PrefactorCoreClient.span()`](prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient.span) * [prefactor\_core.config module](prefactor_core.config.md) * [`PrefactorCoreConfig`](prefactor_core.config.md#prefactor_core.config.PrefactorCoreConfig) * [`PrefactorCoreConfig.http_config`](prefactor_core.config.md#prefactor_core.config.PrefactorCoreConfig.http_config) * [`PrefactorCoreConfig.queue_config`](prefactor_core.config.md#prefactor_core.config.PrefactorCoreConfig.queue_config) * [`PrefactorCoreConfig.schema_registry`](prefactor_core.config.md#prefactor_core.config.PrefactorCoreConfig.schema_registry) * [`PrefactorCoreConfig.http_config`](prefactor_core.config.md#id0) * [`PrefactorCoreConfig.model_config`](prefactor_core.config.md#prefactor_core.config.PrefactorCoreConfig.model_config) * [`PrefactorCoreConfig.queue_config`](prefactor_core.config.md#id1) * [`PrefactorCoreConfig.schema_registry`](prefactor_core.config.md#id2) * [`QueueConfig`](prefactor_core.config.md#prefactor_core.config.QueueConfig) * [`QueueConfig.num_workers`](prefactor_core.config.md#prefactor_core.config.QueueConfig.num_workers) * [`QueueConfig.max_retries`](prefactor_core.config.md#prefactor_core.config.QueueConfig.max_retries) * [`QueueConfig.retry_delay_base`](prefactor_core.config.md#prefactor_core.config.QueueConfig.retry_delay_base) * [`QueueConfig.max_retries`](prefactor_core.config.md#id3) * [`QueueConfig.model_config`](prefactor_core.config.md#prefactor_core.config.QueueConfig.model_config) * [`QueueConfig.num_workers`](prefactor_core.config.md#id4) * [`QueueConfig.retry_delay_base`](prefactor_core.config.md#id5) * [prefactor\_core.context\_stack module](prefactor_core.context_stack.md) * [`SpanContextStack`](prefactor_core.context_stack.md#prefactor_core.context_stack.SpanContextStack) * [`SpanContextStack.depth()`](prefactor_core.context_stack.md#prefactor_core.context_stack.SpanContextStack.depth) * [`SpanContextStack.get_stack()`](prefactor_core.context_stack.md#prefactor_core.context_stack.SpanContextStack.get_stack) * [`SpanContextStack.is_empty()`](prefactor_core.context_stack.md#prefactor_core.context_stack.SpanContextStack.is_empty) * [`SpanContextStack.peek()`](prefactor_core.context_stack.md#prefactor_core.context_stack.SpanContextStack.peek) * [`SpanContextStack.pop()`](prefactor_core.context_stack.md#prefactor_core.context_stack.SpanContextStack.pop) * [`SpanContextStack.push()`](prefactor_core.context_stack.md#prefactor_core.context_stack.SpanContextStack.push) * [prefactor\_core.exceptions module](prefactor_core.exceptions.md) * [`ClientAlreadyInitializedError`](prefactor_core.exceptions.md#prefactor_core.exceptions.ClientAlreadyInitializedError) * [`ClientNotInitializedError`](prefactor_core.exceptions.md#prefactor_core.exceptions.ClientNotInitializedError) * [`InstanceNotFoundError`](prefactor_core.exceptions.md#prefactor_core.exceptions.InstanceNotFoundError) * [`OperationError`](prefactor_core.exceptions.md#prefactor_core.exceptions.OperationError) * [`PrefactorCoreError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorCoreError) * [`PrefactorTelemetryFailureError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorTelemetryFailureError) * [`PrefactorTerminatedError`](prefactor_core.exceptions.md#prefactor_core.exceptions.PrefactorTerminatedError) * [`SpanNotFoundError`](prefactor_core.exceptions.md#prefactor_core.exceptions.SpanNotFoundError) * [prefactor\_core.models module](prefactor_core.models.md) * [`AgentInstance`](prefactor_core.models.md#prefactor_core.models.AgentInstance) * [`AgentInstance.id`](prefactor_core.models.md#prefactor_core.models.AgentInstance.id) * [`AgentInstance.agent_id`](prefactor_core.models.md#prefactor_core.models.AgentInstance.agent_id) * [`AgentInstance.status`](prefactor_core.models.md#prefactor_core.models.AgentInstance.status) * [`AgentInstance.created_at`](prefactor_core.models.md#prefactor_core.models.AgentInstance.created_at) * [`AgentInstance.started_at`](prefactor_core.models.md#prefactor_core.models.AgentInstance.started_at) * [`AgentInstance.finished_at`](prefactor_core.models.md#prefactor_core.models.AgentInstance.finished_at) * [`AgentInstance.metadata`](prefactor_core.models.md#prefactor_core.models.AgentInstance.metadata) * [`AgentInstance.agent_id`](prefactor_core.models.md#id0) * [`AgentInstance.created_at`](prefactor_core.models.md#id1) * [`AgentInstance.finished_at`](prefactor_core.models.md#id2) * [`AgentInstance.id`](prefactor_core.models.md#id3) * [`AgentInstance.metadata`](prefactor_core.models.md#id4) * [`AgentInstance.purpose`](prefactor_core.models.md#prefactor_core.models.AgentInstance.purpose) * [`AgentInstance.quality_payloads`](prefactor_core.models.md#prefactor_core.models.AgentInstance.quality_payloads) * [`AgentInstance.started_at`](prefactor_core.models.md#id5) * [`AgentInstance.status`](prefactor_core.models.md#id6) * [`Span`](prefactor_core.models.md#prefactor_core.models.Span) * [`Span.id`](prefactor_core.models.md#prefactor_core.models.Span.id) * [`Span.instance_id`](prefactor_core.models.md#prefactor_core.models.Span.instance_id) * [`Span.parent_span_id`](prefactor_core.models.md#prefactor_core.models.Span.parent_span_id) * [`Span.schema_name`](prefactor_core.models.md#prefactor_core.models.Span.schema_name) * [`Span.status`](prefactor_core.models.md#prefactor_core.models.Span.status) * [`Span.payload`](prefactor_core.models.md#prefactor_core.models.Span.payload) * [`Span.created_at`](prefactor_core.models.md#prefactor_core.models.Span.created_at) * [`Span.started_at`](prefactor_core.models.md#prefactor_core.models.Span.started_at) * [`Span.finished_at`](prefactor_core.models.md#prefactor_core.models.Span.finished_at) * [`Span.created_at`](prefactor_core.models.md#id7) * [`Span.finished_at`](prefactor_core.models.md#id8) * [`Span.id`](prefactor_core.models.md#id9) * [`Span.instance_id`](prefactor_core.models.md#id10) * [`Span.parent_span_id`](prefactor_core.models.md#id11) * [`Span.payload`](prefactor_core.models.md#id12) * [`Span.schema_name`](prefactor_core.models.md#id13) * [`Span.started_at`](prefactor_core.models.md#id14) * [`Span.status`](prefactor_core.models.md#id15) * [prefactor\_core.operations module](prefactor_core.operations.md) * [`Operation`](prefactor_core.operations.md#prefactor_core.operations.Operation) * [`Operation.type`](prefactor_core.operations.md#prefactor_core.operations.Operation.type) * [`Operation.payload`](prefactor_core.operations.md#prefactor_core.operations.Operation.payload) * [`Operation.timestamp`](prefactor_core.operations.md#prefactor_core.operations.Operation.timestamp) * [`Operation.idempotency_key`](prefactor_core.operations.md#prefactor_core.operations.Operation.idempotency_key) * [`Operation.metadata`](prefactor_core.operations.md#prefactor_core.operations.Operation.metadata) * [`Operation.idempotency_key`](prefactor_core.operations.md#id0) * [`Operation.metadata`](prefactor_core.operations.md#id1) * [`Operation.payload`](prefactor_core.operations.md#id2) * [`Operation.timestamp`](prefactor_core.operations.md#id3) * [`Operation.type`](prefactor_core.operations.md#id4) * [`OperationType`](prefactor_core.operations.md#prefactor_core.operations.OperationType) * [`OperationType.CREATE_SPAN`](prefactor_core.operations.md#prefactor_core.operations.OperationType.CREATE_SPAN) * [`OperationType.FINISH_AGENT_INSTANCE`](prefactor_core.operations.md#prefactor_core.operations.OperationType.FINISH_AGENT_INSTANCE) * [`OperationType.FINISH_SPAN`](prefactor_core.operations.md#prefactor_core.operations.OperationType.FINISH_SPAN) * [`OperationType.RECORD_QUALITY`](prefactor_core.operations.md#prefactor_core.operations.OperationType.RECORD_QUALITY) * [`OperationType.REGISTER_AGENT_INSTANCE`](prefactor_core.operations.md#prefactor_core.operations.OperationType.REGISTER_AGENT_INSTANCE) * [`OperationType.START_AGENT_INSTANCE`](prefactor_core.operations.md#prefactor_core.operations.OperationType.START_AGENT_INSTANCE) * [prefactor\_core.runtime module](prefactor_core.runtime.md) * [`build_runtime_environment()`](prefactor_core.runtime.md#prefactor_core.runtime.build_runtime_environment) * [prefactor\_core.schema\_registry module](prefactor_core.schema_registry.md) * [`SchemaRegistry`](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry) * [`SchemaRegistry.get()`](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry.get) * [`SchemaRegistry.has_schema()`](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry.has_schema) * [`SchemaRegistry.list_schemas()`](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry.list_schemas) * [`SchemaRegistry.merge()`](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry.merge) * [`SchemaRegistry.register()`](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry.register) * [`SchemaRegistry.register_quality_schema()`](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry.register_quality_schema) * [`SchemaRegistry.register_result()`](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry.register_result) * [`SchemaRegistry.register_type()`](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry.register_type) * [`SchemaRegistry.register_unsafe()`](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry.register_unsafe) * [`SchemaRegistry.to_agent_schema_version()`](prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry.to_agent_schema_version) * [prefactor\_core.span\_context module](prefactor_core.span_context.md) * [`SpanContext`](prefactor_core.span_context.md#prefactor_core.span_context.SpanContext) * [`SpanContext.cancel()`](prefactor_core.span_context.md#prefactor_core.span_context.SpanContext.cancel) * [`SpanContext.complete()`](prefactor_core.span_context.md#prefactor_core.span_context.SpanContext.complete) * [`SpanContext.fail()`](prefactor_core.span_context.md#prefactor_core.span_context.SpanContext.fail) * [`SpanContext.finish()`](prefactor_core.span_context.md#prefactor_core.span_context.SpanContext.finish) * [`SpanContext.id`](prefactor_core.span_context.md#prefactor_core.span_context.SpanContext.id) * [`SpanContext.set_result()`](prefactor_core.span_context.md#prefactor_core.span_context.SpanContext.set_result) * [`SpanContext.start()`](prefactor_core.span_context.md#prefactor_core.span_context.SpanContext.start) * [prefactor\_core.utils module](prefactor_core.utils.md) * [`generate_idempotency_key()`](prefactor_core.utils.md#prefactor_core.utils.generate_idempotency_key) * [`validate_idempotency_key()`](prefactor_core.utils.md#prefactor_core.utils.validate_idempotency_key) * [`warn_missing_adaptor_config()`](prefactor_core.utils.md#prefactor_core.utils.warn_missing_adaptor_config) # prefactor_core.client module # prefactor\_core.client module [Section titled “prefactor\_core.client module”](#prefactor_coreclient-module) Main client for prefactor-core. This module provides the PrefactorCoreClient, which is the main entry point for the SDK. It manages the complete lifecycle of agent instances and spans through an async queue-based architecture. ### *class* prefactor\_core.client.PrefactorCoreClient(config: [PrefactorCoreConfig](prefactor_core.config.md#prefactor_core.config.PrefactorCoreConfig), queue: [Queue](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue)\[[Operation](prefactor_core.operations.md#prefactor_core.operations.Operation)] | None = None, sdk\_header\_entry: str | None = None) [Section titled “class prefactor\_core.client.PrefactorCoreClient(config: PrefactorCoreConfig, queue: Queue\[Operation\] | None = None, sdk\_header\_entry: str | None = None)”](#class-prefactor_coreclientprefactorcoreclientconfig-prefactorcoreconfig-queue-queueoperation--none--none-sdk_header_entry-str--none--none) Bases: `object` Main entry point for the prefactor-core SDK. This client provides a high-level interface for managing agent instances and spans. All operations are queued and processed asynchronously, ensuring minimal impact on agent execution flow. The client must be initialized before use, either by calling initialize() or using it as an async context manager. ### Example [Section titled “Example”](#example) config = PrefactorCoreConfig(http\_config=…) async with PrefactorCoreClient(config) as client: : instance = await client.create\_agent\_instance(…) await instance.start()\ async with instance.span(“agent:llm”) as span: : span.set\_payload({“model”: “gpt-4”}) # Your agent logic here\ await instance.finish() #### *async* close() → None [Section titled “async close() → None”](#async-close--none) Close the client and cleanup resources. This method gracefully shuts down the executor and closes the HTTP client. It should be called when the client is no longer needed. #### *async* create\_agent\_instance(agent\_version: dict\[str, Any], agent\_schema\_version: dict\[str, Any] | None = None, agent\_id: str | None = None, instance\_id: str | None = None, external\_schema\_version\_id: str | None = None, environment\_id: str | None = None, purpose: InstancePurpose | None = None, external\_identifier: str | None = None) → [AgentInstanceHandle](prefactor_core.md#prefactor_core.AgentInstanceHandle) [Section titled “async create\_agent\_instance(agent\_version: dict\[str, Any\], agent\_schema\_version: dict\[str, Any\] | None = None, agent\_id: str | None = None, instance\_id: str | None = None, external\_schema\_version\_id: str | None = None, environment\_id: str | None = None, purpose: InstancePurpose | None = None, external\_identifier: str | None = None) → AgentInstanceHandle”](#async-create_agent_instanceagent_version-dictstr-any-agent_schema_version-dictstr-any--none--none-agent_id-str--none--none-instance_id-str--none--none-external_schema_version_id-str--none--none-environment_id-str--none--none-purpose-instancepurpose--none--none-external_identifier-str--none--none--agentinstancehandle) Create a new agent instance. Returns immediately with a handle. The actual registration happens asynchronously via the queue. If agent\_schema\_version is not provided but the client has a schema\_registry, the registry’s schemas will be used automatically. * **Parameters:** * **agent\_id** – Agent ID. Omit when using a deployment-scoped token. * **agent\_version** – Version information (name, etc.). * **agent\_schema\_version** – Schema version. Uses registry if not provided and registry is configured. * **instance\_id** – Optional custom ID for the instance. * **external\_schema\_version\_id** – Optional external identifier for the schema version. Defaults to “auto-generated” when using registry. * **environment\_id** – Optional environment ID used to scope the agent instance. * **external\_identifier** – Optional external identifier for this agent instance in an external system (unique per agent). * **purpose** – Why this instance ran — `"live"`, `"smoke_test"`, or `"eval"`. Omitted (None) lets the API default to `"live"`. * **Returns:** AgentInstanceHandle for the created instance. * **Raises:** * [**ClientNotInitializedError**](prefactor_core.md#prefactor_core.ClientNotInitializedError) – If the client is not initialized. * **ValueError** – If no schema version provided and registry not configured. #### *async* create\_span(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any] | None = None, started\_at: datetime | None = None) → str [Section titled “async create\_span(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any\] | None = None, started\_at: datetime | None = None) → str”](#async-create_spaninstance_id-str-schema_name-str-parent_span_id-str--none--none-payload-dictstr-any--none--none-started_at-datetime--none--none--str) Create a span and return its ID without finishing it. Use this for spans that need to stay open across multiple operations. Call finish\_span() when done. * **Parameters:** * **instance\_id** – ID of the agent instance this span belongs to. * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional explicit parent span ID. * **payload** – Optional initial payload (params/inputs) stored on creation. * **started\_at** – Optional ISO 8601 start time (defaults to current time). * **Returns:** The span ID. #### *async* finish\_span(span\_id: str, result\_payload: dict\[str, Any] | None = None, timestamp: datetime | None = None) → None [Section titled “async finish\_span(span\_id: str, result\_payload: dict\[str, Any\] | None = None, timestamp: datetime | None = None) → None”](#async-finish_spanspan_id-str-result_payload-dictstr-any--none--none-timestamp-datetime--none--none--none) Finish a previously created span. * **Parameters:** * **span\_id** – The ID of the span to finish. * **result\_payload** – Optional result data to store on the span. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* initialize() → None [Section titled “async initialize() → None”](#async-initialize--none) Initialize the client and start processing. This method: 1. Initializes the HTTP client 2. Starts the task executor 3. Initializes managers * **Raises:** [**ClientAlreadyInitializedError**](prefactor_core.md#prefactor_core.ClientAlreadyInitializedError) – If already initialized. #### *property* instance\_manager *: [AgentInstanceManager](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceManager) | None* [Section titled “property instance\_manager : AgentInstanceManager | None”](#property-instance_manager--agentinstancemanager--none) Public accessor for the agent instance manager. #### *async* record\_quality(instance\_id: str, name: str, payload: dict\[str, Any] | None = None) → None [Section titled “async record\_quality(instance\_id: str, name: str, payload: dict\[str, Any\] | None = None) → None”](#async-record_qualityinstance_id-str-name-str-payload-dictstr-any--none--none--none) Record a quality payload on an agent instance. * **Parameters:** * **instance\_id** – The ID of the instance to update. * **name** – Quality schema name (key in the agent schema version quality\_schemas). * **payload** – Quality payload for this name, or None to remove the recorded payload for this name. #### span(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any] | None = None) [Section titled “span(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any\] | None = None)”](#spaninstance_id-str-schema_name-str-parent_span_id-str--none--none-payload-dictstr-any--none--none) Context manager for creating and finishing a span. If parent\_span\_id is not provided, the current span from the SpanContextStack is used as the parent. The returned `SpanContext` supports an explicit lifecycle: 1. `await span.start(payload)` — POST the span to the API. 2. Do work. 3. `await span.complete(result)` / `span.fail(result)` / `span.cancel()` — finish with a specific status. If `start()` or a finish method is not called explicitly, the context manager handles them automatically on exit. * **Parameters:** * **instance\_id** – ID of the agent instance this span belongs to. * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional explicit parent span ID. * **payload** – Optional initial payload sent via auto-start on exit if `start()` is never called explicitly. * **Yields:** SpanContext for the created span. # prefactor_core.config module # prefactor\_core.config module [Section titled “prefactor\_core.config module”](#prefactor_coreconfig-module) Configuration for prefactor-core. This module contains configuration classes for the prefactor-core SDK. ### *class* prefactor\_core.config.PrefactorCoreConfig(\*, http\_config: [HttpClientConfig](../../http/reference/prefactor_http.config.md#prefactor_http.config.HttpClientConfig), queue\_config: [QueueConfig](#prefactor_core.config.QueueConfig) = , schema\_registry: Any = None) [Section titled “class prefactor\_core.config.PrefactorCoreConfig(\*, http\_config: HttpClientConfig, queue\_config: QueueConfig = , schema\_registry: Any = None)”](#class-prefactor_coreconfigprefactorcoreconfig-http_config-httpclientconfig-queue_config-queueconfig---schema_registry-any--none) Bases: `BaseModel` Complete configuration for PrefactorCoreClient. #### http\_config [Section titled “http\_config”](#http_config) Configuration for the HTTP client. * **Type:** [HttpClientConfig](../../http/reference/prefactor_http.md#prefactor_http.HttpClientConfig) #### queue\_config [Section titled “queue\_config”](#queue_config) Configuration for queue processing. * **Type:** [QueueConfig](#prefactor_core.config.QueueConfig) #### schema\_registry [Section titled “schema\_registry”](#schema_registry) Optional schema registry for aggregating span type definitions. * **Type:** Any ### Example [Section titled “Example”](#example) from prefactor\_core.schema\_registry import SchemaRegistry from prefactor\_core import PrefactorCoreConfig registry = SchemaRegistry() registry.register(“langchain:llm”, {“type”: “object”}) config = PrefactorCoreConfig( : http\_config=HttpClientConfig(…), schema\_registry=registry ) #### http\_config *: [HttpClientConfig](../../http/reference/prefactor_http.md#prefactor_http.HttpClientConfig)* [Section titled “http\_config : HttpClientConfig”](#http_config--httpclientconfig) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config--) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### queue\_config *: [QueueConfig](#prefactor_core.config.QueueConfig)* [Section titled “queue\_config : QueueConfig”](#queue_config--queueconfig) #### schema\_registry *: Any* [Section titled “schema\_registry : Any”](#schema_registry--any) ### *class* prefactor\_core.config.QueueConfig(, num\_workers: Annotated\[int, Ge(ge=1), Le(le=20)] = 3, max\_retries: Annotated\[int, Ge(ge=0)] = 3, retry\_delay\_base: Annotated\[float, Gt(gt=0)] = 1.0) [Section titled “class prefactor\_core.config.QueueConfig(, num\_workers: Annotated\[int, Ge(ge=1), Le(le=20)\] = 3, max\_retries: Annotated\[int, Ge(ge=0)\] = 3, retry\_delay\_base: Annotated\[float, Gt(gt=0)\] = 1.0)”](#class-prefactor_coreconfigqueueconfig-num_workers-annotatedint-gege1-lele20--3-max_retries-annotatedint-gege0--3-retry_delay_base-annotatedfloat-gtgt0--10) Bases: `BaseModel` Configuration for queue processing. #### num\_workers [Section titled “num\_workers”](#num_workers) Number of concurrent worker tasks. * **Type:** int #### max\_retries [Section titled “max\_retries”](#max_retries) Maximum retry attempts per failed operation. * **Type:** int #### retry\_delay\_base [Section titled “retry\_delay\_base”](#retry_delay_base) Base delay for exponential backoff (seconds). * **Type:** float #### max\_retries *: int* [Section titled “max\_retries : int”](#max_retries--int) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### num\_workers *: int* [Section titled “num\_workers : int”](#num_workers--int) #### retry\_delay\_base *: float* [Section titled “retry\_delay\_base : float”](#retry_delay_base--float) # prefactor_core.context_stack module # prefactor\_core.context\_stack module [Section titled “prefactor\_core.context\_stack module”](#prefactor_corecontext_stack-module) Span context stack for managing nested span relationships. The SpanContextStack provides a stack-based context tracking system for nested spans. Each async context maintains its own stack of active span IDs, allowing automatic parent detection when creating new spans. This module uses contextvars to ensure proper isolation between concurrent async operations. ### *class* prefactor\_core.context\_stack.SpanContextStack [Section titled “class prefactor\_core.context\_stack.SpanContextStack”](#class-prefactor_corecontext_stackspancontextstack) Bases: `object` Manages a stack of active span IDs within an async context. The stack tracks the hierarchy of nested spans. The top of the stack is always the current (innermost) active span, which serves as the default parent for any new spans created within the same context. This class uses contextvars to ensure that each async task maintains its own independent stack, preventing interference between concurrent operations. ### Example [Section titled “Example”](#example) # Root span [Section titled “Root span”](#root-span) SpanContextStack.push(“span-1”) assert SpanContextStack.peek() == “span-1” # Nested span (child of span-1) [Section titled “Nested span (child of span-1)”](#nested-span-child-of-span-1) SpanContextStack.push(“span-2”) assert SpanContextStack.peek() == “span-2” # Exit nested span [Section titled “Exit nested span”](#exit-nested-span) SpanContextStack.pop() assert SpanContextStack.peek() == “span-1” # Exit root span [Section titled “Exit root span”](#exit-root-span) SpanContextStack.pop() assert SpanContextStack.peek() is None #### *classmethod* depth() → int [Section titled “classmethod depth() → int”](#classmethod-depth--int) Get the current nesting depth. * **Returns:** The number of active spans in the stack (0 if empty). #### *classmethod* get\_stack() → list\[str] [Section titled “classmethod get\_stack() → list\[str\]”](#classmethod-get_stack--liststr) Get the current span stack for this async context. * **Returns:** A list of span IDs, from outermost to innermost. Returns an empty list if no spans are active. #### *classmethod* is\_empty() → bool [Section titled “classmethod is\_empty() → bool”](#classmethod-is_empty--bool) Check if the stack is empty. * **Returns:** True if no spans are currently active. #### *classmethod* peek() → str | None [Section titled “classmethod peek() → str | None”](#classmethod-peek--str--none) Get the current span ID without removing it from the stack. * **Returns:** The ID of the current (innermost) span, or None if no spans are active in this context. #### *classmethod* pop() → str | None [Section titled “classmethod pop() → str | None”](#classmethod-pop--str--none) Pop and return the current span ID from the stack. * **Returns:** The span ID that was removed from the stack, or None if the stack was empty. #### *classmethod* push(span\_id: str) → None [Section titled “classmethod push(span\_id: str) → None”](#classmethod-pushspan_id-str--none) Push a span ID onto the stack. This marks the span as the current (innermost) active span. * **Parameters:** **span\_id** – The ID of the span to push onto the stack. # prefactor_core.exceptions module # prefactor\_core.exceptions module [Section titled “prefactor\_core.exceptions module”](#prefactor_coreexceptions-module) Custom exceptions for prefactor-core. ### *exception* prefactor\_core.exceptions.ClientAlreadyInitializedError [Section titled “exception prefactor\_core.exceptions.ClientAlreadyInitializedError”](#exception-prefactor_coreexceptionsclientalreadyinitializederror) Bases: [`PrefactorCoreError`](#prefactor_core.exceptions.PrefactorCoreError) Raised when attempting to initialize a client that’s already initialized. ### *exception* prefactor\_core.exceptions.ClientNotInitializedError [Section titled “exception prefactor\_core.exceptions.ClientNotInitializedError”](#exception-prefactor_coreexceptionsclientnotinitializederror) Bases: [`PrefactorCoreError`](#prefactor_core.exceptions.PrefactorCoreError) Raised when attempting to use a client that hasn’t been initialized. ### *exception* prefactor\_core.exceptions.InstanceNotFoundError [Section titled “exception prefactor\_core.exceptions.InstanceNotFoundError”](#exception-prefactor_coreexceptionsinstancenotfounderror) Bases: [`PrefactorCoreError`](#prefactor_core.exceptions.PrefactorCoreError) Raised when an agent instance is not found. ### *exception* prefactor\_core.exceptions.OperationError(message: str, operation\_type: str | None = None) [Section titled “exception prefactor\_core.exceptions.OperationError(message: str, operation\_type: str | None = None)”](#exception-prefactor_coreexceptionsoperationerrormessage-str-operation_type-str--none--none) Bases: [`PrefactorCoreError`](#prefactor_core.exceptions.PrefactorCoreError) Raised when an operation fails to process. ### *exception* prefactor\_core.exceptions.PrefactorCoreError [Section titled “exception prefactor\_core.exceptions.PrefactorCoreError”](#exception-prefactor_coreexceptionsprefactorcoreerror) Bases: `Exception` Base exception for all prefactor-core errors. ### *exception* prefactor\_core.exceptions.PrefactorTelemetryFailureError(message: str, , cause: Exception, operation\_type: str | None = None, dropped\_operations: int = 0) [Section titled “exception prefactor\_core.exceptions.PrefactorTelemetryFailureError(message: str, , cause: Exception, operation\_type: str | None = None, dropped\_operations: int = 0)”](#exception-prefactor_coreexceptionsprefactortelemetryfailureerrormessage-str--cause-exception-operation_type-str--none--none-dropped_operations-int--0) Bases: [`PrefactorCoreError`](#prefactor_core.exceptions.PrefactorCoreError) Raised when telemetry enters a permanent failure state. ### *exception* prefactor\_core.exceptions.PrefactorTerminatedError(reason: str | None = None) [Section titled “exception prefactor\_core.exceptions.PrefactorTerminatedError(reason: str | None = None)”](#exception-prefactor_coreexceptionsprefactorterminatederrorreason-str--none--none) Bases: [`PrefactorCoreError`](#prefactor_core.exceptions.PrefactorCoreError) Raised when the agent instance has been terminated by p2. * **Parameters:** **reason** – Optional reason reported by p2 for the termination. ### *exception* prefactor\_core.exceptions.SpanNotFoundError [Section titled “exception prefactor\_core.exceptions.SpanNotFoundError”](#exception-prefactor_coreexceptionsspannotfounderror) Bases: [`PrefactorCoreError`](#prefactor_core.exceptions.PrefactorCoreError) Raised when a span is not found. # prefactor_core.managers package # prefactor\_core.managers package [Section titled “prefactor\_core.managers package”](#prefactor_coremanagers-package) Manager exports for prefactor-core. ### *class* prefactor\_core.managers.AgentInstanceHandle(instance\_id: str, client: [PrefactorCoreClient](prefactor_core.md#prefactor_core.PrefactorCoreClient)) [Section titled “class prefactor\_core.managers.AgentInstanceHandle(instance\_id: str, client: PrefactorCoreClient)”](#class-prefactor_coremanagersagentinstancehandleinstance_id-str-client-prefactorcoreclient) Bases: `object` Handle to an agent instance with convenience methods. This class provides a clean interface for: * Starting and finishing the instance * Creating spans within the instance * Managing the instance lifecycle ### Example [Section titled “Example”](#example) async with client.create\_agent\_instance(…) as instance: : await instance.start()\ async with instance.span(“agent:llm”) as span: : span.set\_payload({“model”: “gpt-4”}) # … do work …\ await instance.finish() #### *async* create\_span(schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any] | None = None, started\_at: datetime | None = None) → str [Section titled “async create\_span(schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any\] | None = None, started\_at: datetime | None = None) → str”](#async-create_spanschema_name-str-parent_span_id-str--none--none-payload-dictstr-any--none--none-started_at-datetime--none--none--str) Create a span within this instance and return its ID. The span stays open until finish\_span() is called. * **Parameters:** * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional explicit parent span ID. * **payload** – Optional initial payload (params/inputs) stored on creation. * **started\_at** – Optional ISO 8601 start time (defaults to current time). * **Returns:** The span ID. #### *async* finish(status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None [Section titled “async finish(status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None”](#async-finishstatus-finishstatus--complete-timestamp-datetime--none--none--none) Mark the instance as finished. Resets the termination monitor (fence + new event) before enqueueing the HTTP finish so stale span responses from the dying run cannot trigger termination on the next run. * **Parameters:** * **status** – Terminal status for the instance — one of `"complete"`, `"failed"`, or `"cancelled"`. Defaults to `"complete"`. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* finish\_span(span\_id: str, result\_payload: dict\[str, Any] | None = None, timestamp: datetime | None = None) → None [Section titled “async finish\_span(span\_id: str, result\_payload: dict\[str, Any\] | None = None, timestamp: datetime | None = None) → None”](#async-finish_spanspan_id-str-result_payload-dictstr-any--none--none-timestamp-datetime--none--none--none) Finish a previously created span. * **Parameters:** * **span\_id** – The ID of the span to finish. * **result\_payload** – Optional result data to store on the span. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *property* id *: str* [Section titled “property id : str”](#property-id--str) Get the instance ID. * **Returns:** The unique identifier for this agent instance. #### *async* record\_quality(name: str, payload: dict\[str, Any] | None = None) → None [Section titled “async record\_quality(name: str, payload: dict\[str, Any\] | None = None) → None”](#async-record_qualityname-str-payload-dictstr-any--none--none--none) Record a quality payload on the instance. This queues a record\_quality operation for the instance. * **Parameters:** * **name** – Quality schema name (key in the agent schema version quality\_schemas). * **payload** – Quality payload for this name (None to remove). #### span(schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any] | None = None) [Section titled “span(schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any\] | None = None)”](#spanschema_name-str-parent_span_id-str--none--none-payload-dictstr-any--none--none) Create a span within this instance. This is a convenience method that delegates to the client. * **Parameters:** * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional explicit parent span ID. * **payload** – Optional initial payload (params/inputs) stored on creation. * **Yields:** SpanContext for the created span. #### *async* start(timestamp: datetime | None = None) → None [Section titled “async start(timestamp: datetime | None = None) → None”](#async-starttimestamp-datetime--none--none--none) Mark the instance as started. This queues a start operation for the instance. * **Parameters:** **timestamp** – Optional ISO 8601 start time (defaults to current time). ### *class* prefactor\_core.managers.AgentInstanceManager(http\_client: [PrefactorHttpClient](../../http/reference/prefactor_http.md#prefactor_http.PrefactorHttpClient), enqueue: Callable\[\[[Operation](prefactor_core.operations.md#prefactor_core.operations.Operation)], Awaitable\[None]]) [Section titled “class prefactor\_core.managers.AgentInstanceManager(http\_client: PrefactorHttpClient, enqueue: Callable\[\[Operation\], Awaitable\[None\]\])”](#class-prefactor_coremanagersagentinstancemanagerhttp_client-prefactorhttpclient-enqueue-callableoperation-awaitablenone) Bases: `object` Manages agent instance lifecycle operations. This class provides a high-level interface for agent instance operations. Registration is done synchronously to get the API-generated ID, while start/finish operations are queued for async processing. ### Example [Section titled “Example”](#example-1) manager = AgentInstanceManager(http\_client, enqueue\_func) # Register a new instance (synchronous - returns API-generated ID) [Section titled “Register a new instance (synchronous - returns API-generated ID)”](#register-a-new-instance-synchronous---returns-api-generated-id) instance\_id = await manager.register( > agent\_id=”my-agent”, agent\_version={“name”: “1.0.0”}, agent\_schema\_version={“version”: “1.0.0”} ) # Start the instance (queued) [Section titled “Start the instance (queued)”](#start-the-instance-queued) await manager.start(instance\_id) # Finish the instance (queued) [Section titled “Finish the instance (queued)”](#finish-the-instance-queued) await manager.finish(instance\_id) #### *async* finish(instance\_id: str, status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None [Section titled “async finish(instance\_id: str, status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None”](#async-finishinstance_id-str-status-finishstatus--complete-timestamp-datetime--none--none--none) Mark an instance as finished. Queues a finish operation for the instance. * **Parameters:** * **instance\_id** – The ID of the instance to finish. * **status** – Terminal status for the instance. Defaults to `"complete"`. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* finish\_with\_idempotency\_key(instance\_id: str, idempotency\_key: str, status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None [Section titled “async finish\_with\_idempotency\_key(instance\_id: str, idempotency\_key: str, status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None”](#async-finish_with_idempotency_keyinstance_id-str-idempotency_key-str-status-finishstatus--complete-timestamp-datetime--none--none--none) Queue a finish operation using a stable idempotency key. * **Parameters:** * **instance\_id** – The ID of the instance to finish. * **idempotency\_key** – Stable key for idempotent retries. * **status** – Terminal status for the instance. Defaults to `"complete"`. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* record\_quality(instance\_id: str, name: str, payload: dict\[str, Any] | None = None) → None [Section titled “async record\_quality(instance\_id: str, name: str, payload: dict\[str, Any\] | None = None) → None”](#async-record_qualityinstance_id-str-name-str-payload-dictstr-any--none--none--none) Record a quality payload on an agent instance. Queues a record\_quality operation for the instance. * **Parameters:** * **instance\_id** – The ID of the instance to update. * **name** – Quality schema name (key in the agent schema version quality\_schemas). * **payload** – Quality payload for this name (None to remove). #### *async* register(agent\_version: dict\[str, Any], agent\_schema\_version: dict\[str, Any], agent\_id: str | None = None, instance\_id: str | None = None, environment\_id: str | None = None, purpose: InstancePurpose | None = None, external\_identifier: str | None = None) → str [Section titled “async register(agent\_version: dict\[str, Any\], agent\_schema\_version: dict\[str, Any\], agent\_id: str | None = None, instance\_id: str | None = None, environment\_id: str | None = None, purpose: InstancePurpose | None = None, external\_identifier: str | None = None) → str”](#async-registeragent_version-dictstr-any-agent_schema_version-dictstr-any-agent_id-str--none--none-instance_id-str--none--none-environment_id-str--none--none-purpose-instancepurpose--none--none-external_identifier-str--none--none--str) Register a new agent instance. Makes a synchronous API call to register the instance and returns the API-generated ID. * **Parameters:** * **agent\_id** – Agent ID. Omit when using a deployment-scoped token. * **agent\_version** – Version information (name, external\_identifier, etc.). * **agent\_schema\_version** – Schema version information. * **instance\_id** – Optional ID to forward to the API as `id`. When provided, the API uses it as the instance ID; when omitted, the API generates one. * **environment\_id** – Optional environment ID. Required when using an account-scoped token; omit when using a deployment-scoped token. * **external\_identifier** – Optional external identifier for this agent instance in an external system (unique per agent). * **purpose** – Why this instance ran — `"live"`, `"smoke_test"`, or `"eval"`. Omitted (None) lets the API default to `"live"`. * **Returns:** The instance ID (API-generated). #### *async* start(instance\_id: str, timestamp: datetime | None = None) → None [Section titled “async start(instance\_id: str, timestamp: datetime | None = None) → None”](#async-startinstance_id-str-timestamp-datetime--none--none--none) Mark an instance as started. Queues a start operation for the instance. * **Parameters:** * **instance\_id** – The ID of the instance to start. * **timestamp** – Optional ISO 8601 start time (defaults to current time). #### *async* start\_with\_idempotency\_key(instance\_id: str, idempotency\_key: str, timestamp: datetime | None = None) → None [Section titled “async start\_with\_idempotency\_key(instance\_id: str, idempotency\_key: str, timestamp: datetime | None = None) → None”](#async-start_with_idempotency_keyinstance_id-str-idempotency_key-str-timestamp-datetime--none--none--none) Queue a start operation using a stable idempotency key. * **Parameters:** * **instance\_id** – The ID of the instance to start. * **idempotency\_key** – Stable key for idempotent retries. * **timestamp** – Optional ISO 8601 start time (defaults to current time). ### *class* prefactor\_core.managers.SpanManager(http\_client: [PrefactorHttpClient](../../http/reference/prefactor_http.md#prefactor_http.PrefactorHttpClient), enqueue: Callable\[\[[Operation](prefactor_core.operations.md#prefactor_core.operations.Operation)], Awaitable\[None]]) [Section titled “class prefactor\_core.managers.SpanManager(http\_client: PrefactorHttpClient, enqueue: Callable\[\[Operation\], Awaitable\[None\]\])”](#class-prefactor_coremanagersspanmanagerhttp_client-prefactorhttpclient-enqueue-callableoperation-awaitablenone) Bases: `object` Manages span lifecycle operations. Spans follow a three-phase lifecycle that maps to the API’s state machine: 1. `prepare()` — synchronous; allocates a local temp ID and pushes it onto the SpanContextStack so nested spans can auto-detect their parent. No HTTP call is made. 2. `start()` — async; POSTs the span to the API with status `"active"` and the params payload, then re-keys local state under the API-generated ID. The span is now running. 3. `finish()` — async; queues a `FINISH_SPAN` operation that calls `POST /agent_spans/{id}/finish` with the desired terminal status (`complete`, `failed`, or `cancelled`). API state machine: : pending → cancelled (cancel\_unstarted: POST pending, finish cancelled) active → complete / failed / cancelled (start then finish) `cancel_unstarted()` handles the case where the span is cancelled before `start()` is ever called — it POSTs the span as `pending` then immediately cancels it, which is the only valid pre-active cancellation path the API supports. ### Example [Section titled “Example”](#example-2) manager = SpanManager(http\_client, enqueue\_func) temp\_id = manager.prepare(instance\_id=”inst-123”, schema\_name=”agent:llm”) api\_id = await manager.start(temp\_id, payload={“model”: “gpt-4”}) await manager.finish(api\_id, status=”complete”, result\_payload={…}) #### *async* cancel\_unstarted(temp\_id: str, timestamp: datetime | None = None) → None [Section titled “async cancel\_unstarted(temp\_id: str, timestamp: datetime | None = None) → None”](#async-cancel_unstartedtemp_id-str-timestamp-datetime--none--none--none) Cancel a span that was never started. When `cancel()` is called before `start()`, the span has not yet been posted to the API. The API state machine only allows `pending → cancelled`, so this method creates the span as `pending` then immediately cancels it via the finish endpoint. * **Parameters:** * **temp\_id** – The temporary ID returned by `prepare()`. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). * **Raises:** **KeyError** – If temp\_id is not a known pending span. #### *async* create(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any] | None = None, span\_id: str | None = None, started\_at: datetime | None = None) → str [Section titled “async create(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any\] | None = None, span\_id: str | None = None, started\_at: datetime | None = None) → str”](#async-createinstance_id-str-schema_name-str-parent_span_id-str--none--none-payload-dictstr-any--none--none-span_id-str--none--none-started_at-datetime--none--none--str) Create a span in one step (prepare + start). Convenience method that combines `prepare()` and `start()` for callers that don’t need the two-phase lifecycle. * **Parameters:** * **instance\_id** – ID of the agent instance this span belongs to. * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional parent span ID (auto-detected if None). * **payload** – Optional initial payload data. * **span\_id** – Ignored (API generates IDs). * **started\_at** – Optional ISO 8601 start time (defaults to current time). * **Returns:** The API-generated span ID. #### *async* finish(span\_id: str, result\_payload: dict\[str, Any] | None = None, status: FinishStatus = ‘complete’, idempotency\_key: str | None = None, timestamp: datetime | None = None) → None [Section titled “async finish(span\_id: str, result\_payload: dict\[str, Any\] | None = None, status: FinishStatus = ‘complete’, idempotency\_key: str | None = None, timestamp: datetime | None = None) → None”](#async-finishspan_id-str-result_payload-dictstr-any--none--none-status-finishstatus--complete-idempotency_key-str--none--none-timestamp-datetime--none--none--none) Mark a span as finished. Queues a finish operation and removes the span from the stack. * **Parameters:** * **span\_id** – The ID of the span to finish. * **result\_payload** – Optional result data to store on the span. * **status** – Terminal status — `"complete"`, `"failed"`, or `"cancelled"` (default: `"complete"`). The span must be `active` for this to succeed; use `cancel_unstarted()` to cancel a span that was never started. * **idempotency\_key** – Optional key to make repeated finish requests duplicate-safe. When omitted, a new key is generated. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). * **Raises:** **KeyError** – If the span ID is not known. #### get\_span(span\_id: str) → [Span](prefactor_core.models.md#prefactor_core.models.Span) | None [Section titled “get\_span(span\_id: str) → Span | None”](#get_spanspan_id-str--span--none) Get a span by ID. * **Parameters:** **span\_id** – The span ID to look up. * **Returns:** The span if known, None otherwise. #### prepare(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None) → str [Section titled “prepare(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None) → str”](#prepareinstance_id-str-schema_name-str-parent_span_id-str--none--none--str) Reserve a local span slot and push it onto the context stack. Allocates a temporary local ID and pushes it onto the SpanContextStack so that nested `prepare()` calls can auto-detect their parent. The actual HTTP POST is deferred to `start()`. * **Parameters:** * **instance\_id** – ID of the agent instance this span belongs to. * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional parent span ID (auto-detected from stack if None). * **Returns:** A temporary span ID (replaced by the API-generated ID in `start()`). #### *async* start(temp\_id: str, payload: dict\[str, Any] | None = None, started\_at: datetime | None = None) → str [Section titled “async start(temp\_id: str, payload: dict\[str, Any\] | None = None, started\_at: datetime | None = None) → str”](#async-starttemp_id-str-payload-dictstr-any--none--none-started_at-datetime--none--none--str) Post the span to the API as `active` and return the API-generated ID. POSTs the span with `status="active"`, which allows it to be finished via the finish endpoint with any terminal status (`complete`, `failed`, or `cancelled`). Replaces the temporary local ID with the API-generated ID in local state and on the context stack. * **Parameters:** * **temp\_id** – The temporary ID returned by `prepare()`. * **payload** – Optional params/inputs to send with the span. * **started\_at** – Optional ISO 8601 start time (defaults to current time). * **Returns:** The API-generated span ID. * **Raises:** **KeyError** – If temp\_id is not a known pending span. ## Submodules [Section titled “Submodules”](#submodules) * [prefactor\_core.managers.agent\_instance module](prefactor_core.managers.agent_instance.md) * [`AgentInstanceHandle`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle) * [`AgentInstanceHandle.create_span()`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle.create_span) * [`AgentInstanceHandle.finish()`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle.finish) * [`AgentInstanceHandle.finish_span()`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle.finish_span) * [`AgentInstanceHandle.id`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle.id) * [`AgentInstanceHandle.record_quality()`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle.record_quality) * [`AgentInstanceHandle.span()`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle.span) * [`AgentInstanceHandle.start()`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle.start) * [`AgentInstanceManager`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceManager) * [`AgentInstanceManager.finish()`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceManager.finish) * [`AgentInstanceManager.finish_with_idempotency_key()`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceManager.finish_with_idempotency_key) * [`AgentInstanceManager.record_quality()`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceManager.record_quality) * [`AgentInstanceManager.register()`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceManager.register) * [`AgentInstanceManager.start()`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceManager.start) * [`AgentInstanceManager.start_with_idempotency_key()`](prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceManager.start_with_idempotency_key) * [prefactor\_core.managers.span module](prefactor_core.managers.span.md) * [`SpanManager`](prefactor_core.managers.span.md#prefactor_core.managers.span.SpanManager) * [`SpanManager.cancel_unstarted()`](prefactor_core.managers.span.md#prefactor_core.managers.span.SpanManager.cancel_unstarted) * [`SpanManager.create()`](prefactor_core.managers.span.md#prefactor_core.managers.span.SpanManager.create) * [`SpanManager.finish()`](prefactor_core.managers.span.md#prefactor_core.managers.span.SpanManager.finish) * [`SpanManager.get_span()`](prefactor_core.managers.span.md#prefactor_core.managers.span.SpanManager.get_span) * [`SpanManager.prepare()`](prefactor_core.managers.span.md#prefactor_core.managers.span.SpanManager.prepare) * [`SpanManager.start()`](prefactor_core.managers.span.md#prefactor_core.managers.span.SpanManager.start) # prefactor_core.managers.agent_instance module # prefactor\_core.managers.agent\_instance module [Section titled “prefactor\_core.managers.agent\_instance module”](#prefactor_coremanagersagent_instance-module) Agent instance handle and manager for convenient span creation. The AgentInstanceManager handles agent instance lifecycle operations, while AgentInstanceHandle provides a high-level interface for managing an agent instance and creating spans within it. ### *class* prefactor\_core.managers.agent\_instance.AgentInstanceHandle(instance\_id: str, client: [PrefactorCoreClient](prefactor_core.md#prefactor_core.PrefactorCoreClient)) [Section titled “class prefactor\_core.managers.agent\_instance.AgentInstanceHandle(instance\_id: str, client: PrefactorCoreClient)”](#class-prefactor_coremanagersagent_instanceagentinstancehandleinstance_id-str-client-prefactorcoreclient) Bases: `object` Handle to an agent instance with convenience methods. This class provides a clean interface for: * Starting and finishing the instance * Creating spans within the instance * Managing the instance lifecycle ### Example [Section titled “Example”](#example) async with client.create\_agent\_instance(…) as instance: : await instance.start()\ async with instance.span(“agent:llm”) as span: : span.set\_payload({“model”: “gpt-4”}) # … do work …\ await instance.finish() #### *async* create\_span(schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any] | None = None, started\_at: datetime | None = None) → str [Section titled “async create\_span(schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any\] | None = None, started\_at: datetime | None = None) → str”](#async-create_spanschema_name-str-parent_span_id-str--none--none-payload-dictstr-any--none--none-started_at-datetime--none--none--str) Create a span within this instance and return its ID. The span stays open until finish\_span() is called. * **Parameters:** * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional explicit parent span ID. * **payload** – Optional initial payload (params/inputs) stored on creation. * **started\_at** – Optional ISO 8601 start time (defaults to current time). * **Returns:** The span ID. #### *async* finish(status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None [Section titled “async finish(status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None”](#async-finishstatus-finishstatus--complete-timestamp-datetime--none--none--none) Mark the instance as finished. Resets the termination monitor (fence + new event) before enqueueing the HTTP finish so stale span responses from the dying run cannot trigger termination on the next run. * **Parameters:** * **status** – Terminal status for the instance — one of `"complete"`, `"failed"`, or `"cancelled"`. Defaults to `"complete"`. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* finish\_span(span\_id: str, result\_payload: dict\[str, Any] | None = None, timestamp: datetime | None = None) → None [Section titled “async finish\_span(span\_id: str, result\_payload: dict\[str, Any\] | None = None, timestamp: datetime | None = None) → None”](#async-finish_spanspan_id-str-result_payload-dictstr-any--none--none-timestamp-datetime--none--none--none) Finish a previously created span. * **Parameters:** * **span\_id** – The ID of the span to finish. * **result\_payload** – Optional result data to store on the span. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *property* id *: str* [Section titled “property id : str”](#property-id--str) Get the instance ID. * **Returns:** The unique identifier for this agent instance. #### *async* record\_quality(name: str, payload: dict\[str, Any] | None = None) → None [Section titled “async record\_quality(name: str, payload: dict\[str, Any\] | None = None) → None”](#async-record_qualityname-str-payload-dictstr-any--none--none--none) Record a quality payload on the instance. This queues a record\_quality operation for the instance. * **Parameters:** * **name** – Quality schema name (key in the agent schema version quality\_schemas). * **payload** – Quality payload for this name (None to remove). #### span(schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any] | None = None) [Section titled “span(schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any\] | None = None)”](#spanschema_name-str-parent_span_id-str--none--none-payload-dictstr-any--none--none) Create a span within this instance. This is a convenience method that delegates to the client. * **Parameters:** * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional explicit parent span ID. * **payload** – Optional initial payload (params/inputs) stored on creation. * **Yields:** SpanContext for the created span. #### *async* start(timestamp: datetime | None = None) → None [Section titled “async start(timestamp: datetime | None = None) → None”](#async-starttimestamp-datetime--none--none--none) Mark the instance as started. This queues a start operation for the instance. * **Parameters:** **timestamp** – Optional ISO 8601 start time (defaults to current time). ### *class* prefactor\_core.managers.agent\_instance.AgentInstanceManager(http\_client: [PrefactorHttpClient](../../http/reference/prefactor_http.md#prefactor_http.PrefactorHttpClient), enqueue: Callable\[\[[Operation](prefactor_core.operations.md#prefactor_core.operations.Operation)], Awaitable\[None]]) [Section titled “class prefactor\_core.managers.agent\_instance.AgentInstanceManager(http\_client: PrefactorHttpClient, enqueue: Callable\[\[Operation\], Awaitable\[None\]\])”](#class-prefactor_coremanagersagent_instanceagentinstancemanagerhttp_client-prefactorhttpclient-enqueue-callableoperation-awaitablenone) Bases: `object` Manages agent instance lifecycle operations. This class provides a high-level interface for agent instance operations. Registration is done synchronously to get the API-generated ID, while start/finish operations are queued for async processing. ### Example [Section titled “Example”](#example-1) manager = AgentInstanceManager(http\_client, enqueue\_func) # Register a new instance (synchronous - returns API-generated ID) [Section titled “Register a new instance (synchronous - returns API-generated ID)”](#register-a-new-instance-synchronous---returns-api-generated-id) instance\_id = await manager.register( > agent\_id=”my-agent”, agent\_version={“name”: “1.0.0”}, agent\_schema\_version={“version”: “1.0.0”} ) # Start the instance (queued) [Section titled “Start the instance (queued)”](#start-the-instance-queued) await manager.start(instance\_id) # Finish the instance (queued) [Section titled “Finish the instance (queued)”](#finish-the-instance-queued) await manager.finish(instance\_id) #### *async* finish(instance\_id: str, status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None [Section titled “async finish(instance\_id: str, status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None”](#async-finishinstance_id-str-status-finishstatus--complete-timestamp-datetime--none--none--none) Mark an instance as finished. Queues a finish operation for the instance. * **Parameters:** * **instance\_id** – The ID of the instance to finish. * **status** – Terminal status for the instance. Defaults to `"complete"`. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* finish\_with\_idempotency\_key(instance\_id: str, idempotency\_key: str, status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None [Section titled “async finish\_with\_idempotency\_key(instance\_id: str, idempotency\_key: str, status: FinishStatus = ‘complete’, timestamp: datetime | None = None) → None”](#async-finish_with_idempotency_keyinstance_id-str-idempotency_key-str-status-finishstatus--complete-timestamp-datetime--none--none--none) Queue a finish operation using a stable idempotency key. * **Parameters:** * **instance\_id** – The ID of the instance to finish. * **idempotency\_key** – Stable key for idempotent retries. * **status** – Terminal status for the instance. Defaults to `"complete"`. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* record\_quality(instance\_id: str, name: str, payload: dict\[str, Any] | None = None) → None [Section titled “async record\_quality(instance\_id: str, name: str, payload: dict\[str, Any\] | None = None) → None”](#async-record_qualityinstance_id-str-name-str-payload-dictstr-any--none--none--none) Record a quality payload on an agent instance. Queues a record\_quality operation for the instance. * **Parameters:** * **instance\_id** – The ID of the instance to update. * **name** – Quality schema name (key in the agent schema version quality\_schemas). * **payload** – Quality payload for this name (None to remove). #### *async* register(agent\_version: dict\[str, Any], agent\_schema\_version: dict\[str, Any], agent\_id: str | None = None, instance\_id: str | None = None, environment\_id: str | None = None, purpose: InstancePurpose | None = None, external\_identifier: str | None = None) → str [Section titled “async register(agent\_version: dict\[str, Any\], agent\_schema\_version: dict\[str, Any\], agent\_id: str | None = None, instance\_id: str | None = None, environment\_id: str | None = None, purpose: InstancePurpose | None = None, external\_identifier: str | None = None) → str”](#async-registeragent_version-dictstr-any-agent_schema_version-dictstr-any-agent_id-str--none--none-instance_id-str--none--none-environment_id-str--none--none-purpose-instancepurpose--none--none-external_identifier-str--none--none--str) Register a new agent instance. Makes a synchronous API call to register the instance and returns the API-generated ID. * **Parameters:** * **agent\_id** – Agent ID. Omit when using a deployment-scoped token. * **agent\_version** – Version information (name, external\_identifier, etc.). * **agent\_schema\_version** – Schema version information. * **instance\_id** – Optional ID to forward to the API as `id`. When provided, the API uses it as the instance ID; when omitted, the API generates one. * **environment\_id** – Optional environment ID. Required when using an account-scoped token; omit when using a deployment-scoped token. * **external\_identifier** – Optional external identifier for this agent instance in an external system (unique per agent). * **purpose** – Why this instance ran — `"live"`, `"smoke_test"`, or `"eval"`. Omitted (None) lets the API default to `"live"`. * **Returns:** The instance ID (API-generated). #### *async* start(instance\_id: str, timestamp: datetime | None = None) → None [Section titled “async start(instance\_id: str, timestamp: datetime | None = None) → None”](#async-startinstance_id-str-timestamp-datetime--none--none--none) Mark an instance as started. Queues a start operation for the instance. * **Parameters:** * **instance\_id** – The ID of the instance to start. * **timestamp** – Optional ISO 8601 start time (defaults to current time). #### *async* start\_with\_idempotency\_key(instance\_id: str, idempotency\_key: str, timestamp: datetime | None = None) → None [Section titled “async start\_with\_idempotency\_key(instance\_id: str, idempotency\_key: str, timestamp: datetime | None = None) → None”](#async-start_with_idempotency_keyinstance_id-str-idempotency_key-str-timestamp-datetime--none--none--none) Queue a start operation using a stable idempotency key. * **Parameters:** * **instance\_id** – The ID of the instance to start. * **idempotency\_key** – Stable key for idempotent retries. * **timestamp** – Optional ISO 8601 start time (defaults to current time). # prefactor_core.managers.span module # prefactor\_core.managers.span module [Section titled “prefactor\_core.managers.span module”](#prefactor_coremanagersspan-module) Manager for span lifecycle operations. The SpanManager handles high-level operations for spans, converting user calls into Operation objects that are queued for processing. It also manages the span stack for automatic parent detection. ### *class* prefactor\_core.managers.span.SpanManager(http\_client: [PrefactorHttpClient](../../http/reference/prefactor_http.md#prefactor_http.PrefactorHttpClient), enqueue: Callable\[\[[Operation](prefactor_core.operations.md#prefactor_core.operations.Operation)], Awaitable\[None]]) [Section titled “class prefactor\_core.managers.span.SpanManager(http\_client: PrefactorHttpClient, enqueue: Callable\[\[Operation\], Awaitable\[None\]\])”](#class-prefactor_coremanagersspanspanmanagerhttp_client-prefactorhttpclient-enqueue-callableoperation-awaitablenone) Bases: `object` Manages span lifecycle operations. Spans follow a three-phase lifecycle that maps to the API’s state machine: 1. `prepare()` — synchronous; allocates a local temp ID and pushes it onto the SpanContextStack so nested spans can auto-detect their parent. No HTTP call is made. 2. `start()` — async; POSTs the span to the API with status `"active"` and the params payload, then re-keys local state under the API-generated ID. The span is now running. 3. `finish()` — async; queues a `FINISH_SPAN` operation that calls `POST /agent_spans/{id}/finish` with the desired terminal status (`complete`, `failed`, or `cancelled`). API state machine: : pending → cancelled (cancel\_unstarted: POST pending, finish cancelled) active → complete / failed / cancelled (start then finish) `cancel_unstarted()` handles the case where the span is cancelled before `start()` is ever called — it POSTs the span as `pending` then immediately cancels it, which is the only valid pre-active cancellation path the API supports. ### Example [Section titled “Example”](#example) manager = SpanManager(http\_client, enqueue\_func) temp\_id = manager.prepare(instance\_id=”inst-123”, schema\_name=”agent:llm”) api\_id = await manager.start(temp\_id, payload={“model”: “gpt-4”}) await manager.finish(api\_id, status=”complete”, result\_payload={…}) #### *async* cancel\_unstarted(temp\_id: str, timestamp: datetime | None = None) → None [Section titled “async cancel\_unstarted(temp\_id: str, timestamp: datetime | None = None) → None”](#async-cancel_unstartedtemp_id-str-timestamp-datetime--none--none--none) Cancel a span that was never started. When `cancel()` is called before `start()`, the span has not yet been posted to the API. The API state machine only allows `pending → cancelled`, so this method creates the span as `pending` then immediately cancels it via the finish endpoint. * **Parameters:** * **temp\_id** – The temporary ID returned by `prepare()`. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). * **Raises:** **KeyError** – If temp\_id is not a known pending span. #### *async* create(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any] | None = None, span\_id: str | None = None, started\_at: datetime | None = None) → str [Section titled “async create(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, payload: dict\[str, Any\] | None = None, span\_id: str | None = None, started\_at: datetime | None = None) → str”](#async-createinstance_id-str-schema_name-str-parent_span_id-str--none--none-payload-dictstr-any--none--none-span_id-str--none--none-started_at-datetime--none--none--str) Create a span in one step (prepare + start). Convenience method that combines `prepare()` and `start()` for callers that don’t need the two-phase lifecycle. * **Parameters:** * **instance\_id** – ID of the agent instance this span belongs to. * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional parent span ID (auto-detected if None). * **payload** – Optional initial payload data. * **span\_id** – Ignored (API generates IDs). * **started\_at** – Optional ISO 8601 start time (defaults to current time). * **Returns:** The API-generated span ID. #### *async* finish(span\_id: str, result\_payload: dict\[str, Any] | None = None, status: FinishStatus = ‘complete’, idempotency\_key: str | None = None, timestamp: datetime | None = None) → None [Section titled “async finish(span\_id: str, result\_payload: dict\[str, Any\] | None = None, status: FinishStatus = ‘complete’, idempotency\_key: str | None = None, timestamp: datetime | None = None) → None”](#async-finishspan_id-str-result_payload-dictstr-any--none--none-status-finishstatus--complete-idempotency_key-str--none--none-timestamp-datetime--none--none--none) Mark a span as finished. Queues a finish operation and removes the span from the stack. * **Parameters:** * **span\_id** – The ID of the span to finish. * **result\_payload** – Optional result data to store on the span. * **status** – Terminal status — `"complete"`, `"failed"`, or `"cancelled"` (default: `"complete"`). The span must be `active` for this to succeed; use `cancel_unstarted()` to cancel a span that was never started. * **idempotency\_key** – Optional key to make repeated finish requests duplicate-safe. When omitted, a new key is generated. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). * **Raises:** **KeyError** – If the span ID is not known. #### get\_span(span\_id: str) → [Span](prefactor_core.models.md#prefactor_core.models.Span) | None [Section titled “get\_span(span\_id: str) → Span | None”](#get_spanspan_id-str--span--none) Get a span by ID. * **Parameters:** **span\_id** – The span ID to look up. * **Returns:** The span if known, None otherwise. #### prepare(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None) → str [Section titled “prepare(instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None) → str”](#prepareinstance_id-str-schema_name-str-parent_span_id-str--none--none--str) Reserve a local span slot and push it onto the context stack. Allocates a temporary local ID and pushes it onto the SpanContextStack so that nested `prepare()` calls can auto-detect their parent. The actual HTTP POST is deferred to `start()`. * **Parameters:** * **instance\_id** – ID of the agent instance this span belongs to. * **schema\_name** – Name of the schema for this span. * **parent\_span\_id** – Optional parent span ID (auto-detected from stack if None). * **Returns:** A temporary span ID (replaced by the API-generated ID in `start()`). #### *async* start(temp\_id: str, payload: dict\[str, Any] | None = None, started\_at: datetime | None = None) → str [Section titled “async start(temp\_id: str, payload: dict\[str, Any\] | None = None, started\_at: datetime | None = None) → str”](#async-starttemp_id-str-payload-dictstr-any--none--none-started_at-datetime--none--none--str) Post the span to the API as `active` and return the API-generated ID. POSTs the span with `status="active"`, which allows it to be finished via the finish endpoint with any terminal status (`complete`, `failed`, or `cancelled`). Replaces the temporary local ID with the API-generated ID in local state and on the context stack. * **Parameters:** * **temp\_id** – The temporary ID returned by `prepare()`. * **payload** – Optional params/inputs to send with the span. * **started\_at** – Optional ISO 8601 start time (defaults to current time). * **Returns:** The API-generated span ID. * **Raises:** **KeyError** – If temp\_id is not a known pending span. # prefactor_core.models module # prefactor\_core.models module [Section titled “prefactor\_core.models module”](#prefactor_coremodels-module) Data models for prefactor-core. This module contains dataclasses and models used throughout the SDK. ### *class* prefactor\_core.models.AgentInstance(id: str, agent\_id: str, status: str = ‘pending’, purpose: str | None = None, created\_at: datetime = , started\_at: datetime | None = None, finished\_at: datetime | None = None, metadata: dict\[str, \~typing.Any]=, quality\_payloads: dict\[str, dict\[str, \~typing.Any]] | None=None) [Section titled “class prefactor\_core.models.AgentInstance(id: str, agent\_id: str, status: str = ‘pending’, purpose: str | None = None, created\_at: datetime = , started\_at: datetime | None = None, finished\_at: datetime | None = None, metadata: dict\[str, \~typing.Any\]=, quality\_payloads: dict\[str, dict\[str, \~typing.Any\]\] | None=None)”](#class-prefactor_coremodelsagentinstanceid-str-agent_id-str-status-str--pending-purpose-str--none--none-created_at-datetime---started_at-datetime--none--none-finished_at-datetime--none--none-metadata-dictstr-typingany-quality_payloads-dictstr-dictstr-typingany--nonenone) Bases: `object` Represents an agent instance. An agent instance is a single execution of an agent. It tracks the lifecycle from registration through completion. #### id [Section titled “id”](#id) Unique identifier for this instance. * **Type:** str #### agent\_id [Section titled “agent\_id”](#agent_id) ID of the agent this is an instance of. * **Type:** str #### status [Section titled “status”](#status) Current status (pending, active, complete). * **Type:** str #### created\_at [Section titled “created\_at”](#created_at) When the instance was registered. * **Type:** datetime.datetime #### started\_at [Section titled “started\_at”](#started_at) When the instance started executing (if started). * **Type:** datetime.datetime | None #### finished\_at [Section titled “finished\_at”](#finished_at) When the instance completed (if finished). * **Type:** datetime.datetime | None #### metadata [Section titled “metadata”](#metadata) Additional metadata about the instance. * **Type:** dict\[str, Any] #### agent\_id *: str* [Section titled “agent\_id : str”](#agent_id--str) #### created\_at *: datetime* [Section titled “created\_at : datetime”](#created_at--datetime) #### finished\_at *: datetime | None* *= None* [Section titled “finished\_at : datetime | None = None”](#finished_at--datetime--none--none) #### id *: str* [Section titled “id : str”](#id--str) #### metadata *: dict\[str, Any]* [Section titled “metadata : dict\[str, Any\]”](#metadata--dictstr-any) #### purpose *: str | None* *= None* [Section titled “purpose : str | None = None”](#purpose--str--none--none) #### quality\_payloads *: dict\[str, dict\[str, Any]] | None* *= None* [Section titled “quality\_payloads : dict\[str, dict\[str, Any\]\] | None = None”](#quality_payloads--dictstr-dictstr-any--none--none) #### started\_at *: datetime | None* *= None* [Section titled “started\_at : datetime | None = None”](#started_at--datetime--none--none) #### status *: str* *= ‘pending’* [Section titled “status : str = ‘pending’”](#status--str--pending) ### *class* prefactor\_core.models.Span(id: str, instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, status: str = ‘pending’, payload: dict\[str, \~typing.Any]=, created\_at: datetime = , started\_at: datetime | None = None, finished\_at: datetime | None = None) [Section titled “class prefactor\_core.models.Span(id: str, instance\_id: str, schema\_name: str, parent\_span\_id: str | None = None, status: str = ‘pending’, payload: dict\[str, \~typing.Any\]=, created\_at: datetime = , started\_at: datetime | None = None, finished\_at: datetime | None = None)”](#class-prefactor_coremodelsspanid-str-instance_id-str-schema_name-str-parent_span_id-str--none--none-status-str--pending-payload-dictstr-typingany-created_at-datetime---started_at-datetime--none--none-finished_at-datetime--none--none) Bases: `object` Represents a span within an agent instance. Spans represent discrete units of work within an agent execution, such as LLM calls, tool executions, or processing steps. #### id [Section titled “id”](#id-1) Unique identifier for this span. * **Type:** str #### instance\_id [Section titled “instance\_id”](#instance_id) ID of the agent instance this span belongs to. * **Type:** str #### parent\_span\_id [Section titled “parent\_span\_id”](#parent_span_id) ID of the parent span (if nested). * **Type:** str | None #### schema\_name [Section titled “schema\_name”](#schema_name) Name of the schema defining this span type. * **Type:** str #### status [Section titled “status”](#status-1) Current status (pending, active, complete). * **Type:** str #### payload [Section titled “payload”](#payload) Arbitrary data associated with this span. * **Type:** dict\[str, Any] #### created\_at [Section titled “created\_at”](#created_at-1) When the span was created. * **Type:** datetime.datetime #### started\_at [Section titled “started\_at”](#started_at-1) When the span started (defaults to created\_at). * **Type:** datetime.datetime | None #### finished\_at [Section titled “finished\_at”](#finished_at-1) When the span completed (if finished). * **Type:** datetime.datetime | None #### created\_at *: datetime* [Section titled “created\_at : datetime”](#created_at--datetime-1) #### finished\_at *: datetime | None* *= None* [Section titled “finished\_at : datetime | None = None”](#finished_at--datetime--none--none-1) #### id *: str* [Section titled “id : str”](#id--str-1) #### instance\_id *: str* [Section titled “instance\_id : str”](#instance_id--str) #### parent\_span\_id *: str | None* *= None* [Section titled “parent\_span\_id : str | None = None”](#parent_span_id--str--none--none) #### payload *: dict\[str, Any]* [Section titled “payload : dict\[str, Any\]”](#payload--dictstr-any) #### schema\_name *: str* [Section titled “schema\_name : str”](#schema_name--str) #### started\_at *: datetime | None* *= None* [Section titled “started\_at : datetime | None = None”](#started_at--datetime--none--none-1) #### status *: str* *= ‘pending’* [Section titled “status : str = ‘pending’”](#status--str--pending-1) # prefactor_core.monitoring package # prefactor\_core.monitoring package [Section titled “prefactor\_core.monitoring package”](#prefactor_coremonitoring-package) ### *class* prefactor\_core.monitoring.TerminationMonitor(fetch\_instance: Callable, poll\_interval: float = 30.0) [Section titled “class prefactor\_core.monitoring.TerminationMonitor(fetch\_instance: Callable, poll\_interval: float = 30.0)”](#class-prefactor_coremonitoringterminationmonitorfetch_instance-callable-poll_interval-float--300) Bases: `object` Monitors an agent instance for termination. Thread-safety note: detect\_termination and get\_termination\_event().is\_set() are safe to call from sync worker threads — they only read/write a bool under the GIL (asyncio.Event.\_value is a plain bool). #### destroy() → None [Section titled “destroy() → None”](#destroy--none) Permanently shut down the monitor (no further events will fire). #### detect\_termination(reason: str | None) → None [Section titled “detect\_termination(reason: str | None) → None”](#detect_terminationreason-str--none--none) Signal that the instance has been terminated. No-op if already terminated, destroyed, or fenced (post-reset stale call). #### get\_termination\_event() → Event [Section titled “get\_termination\_event() → Event”](#get_termination_event--event) #### reset() → None [Section titled “reset() → None”](#reset--none) Prepare monitor for the next agent run. * Creates a fresh (unset) event * Clears the termination reason * Cancels any in-flight poll * Sets fence so stale callbacks from the dying run are ignored * Increments generation so stale polls self-discard #### subscribe(callback: Callable\[\[], None]) → Callable\[\[], None] [Section titled “subscribe(callback: Callable\[\[\], None\]) → Callable\[\[\], None\]”](#subscribecallback-callable-none--callable-none) Register a callback invoked on termination. Returns an unsubscribe fn. #### sync(instance\_id: str | None) → None [Section titled “sync(instance\_id: str | None) → None”](#syncinstance_id-str--none--none) Update the tracked instance ID and start/stop the fallback poll. Idempotent: calling with the same non-None ID when a poll is already running does not restart it (preserving the sleep interval). #### *property* termination\_reason *: str | None* [Section titled “property termination\_reason : str | None”](#property-termination_reason--str--none) ## Submodules [Section titled “Submodules”](#submodules) * [prefactor\_core.monitoring.termination\_monitor module](prefactor_core.monitoring.termination_monitor.md) * [`TerminationMonitor`](prefactor_core.monitoring.termination_monitor.md#prefactor_core.monitoring.termination_monitor.TerminationMonitor) * [`TerminationMonitor.destroy()`](prefactor_core.monitoring.termination_monitor.md#prefactor_core.monitoring.termination_monitor.TerminationMonitor.destroy) * [`TerminationMonitor.detect_termination()`](prefactor_core.monitoring.termination_monitor.md#prefactor_core.monitoring.termination_monitor.TerminationMonitor.detect_termination) * [`TerminationMonitor.get_termination_event()`](prefactor_core.monitoring.termination_monitor.md#prefactor_core.monitoring.termination_monitor.TerminationMonitor.get_termination_event) * [`TerminationMonitor.reset()`](prefactor_core.monitoring.termination_monitor.md#prefactor_core.monitoring.termination_monitor.TerminationMonitor.reset) * [`TerminationMonitor.subscribe()`](prefactor_core.monitoring.termination_monitor.md#prefactor_core.monitoring.termination_monitor.TerminationMonitor.subscribe) * [`TerminationMonitor.sync()`](prefactor_core.monitoring.termination_monitor.md#prefactor_core.monitoring.termination_monitor.TerminationMonitor.sync) * [`TerminationMonitor.termination_reason`](prefactor_core.monitoring.termination_monitor.md#prefactor_core.monitoring.termination_monitor.TerminationMonitor.termination_reason) # prefactor_core.monitoring.termination_monitor module # prefactor\_core.monitoring.termination\_monitor module [Section titled “prefactor\_core.monitoring.termination\_monitor module”](#prefactor_coremonitoringtermination_monitor-module) TerminationMonitor — detects agent instance termination via two paths: 1. Fast: control signal in span API responses (pushed via callback) 2. Slow: polling the instance status endpoint every poll\_interval seconds ### *class* prefactor\_core.monitoring.termination\_monitor.TerminationMonitor(fetch\_instance: Callable, poll\_interval: float = 30.0) [Section titled “class prefactor\_core.monitoring.termination\_monitor.TerminationMonitor(fetch\_instance: Callable, poll\_interval: float = 30.0)”](#class-prefactor_coremonitoringtermination_monitorterminationmonitorfetch_instance-callable-poll_interval-float--300) Bases: `object` Monitors an agent instance for termination. Thread-safety note: detect\_termination and get\_termination\_event().is\_set() are safe to call from sync worker threads — they only read/write a bool under the GIL (asyncio.Event.\_value is a plain bool). #### destroy() → None [Section titled “destroy() → None”](#destroy--none) Permanently shut down the monitor (no further events will fire). #### detect\_termination(reason: str | None) → None [Section titled “detect\_termination(reason: str | None) → None”](#detect_terminationreason-str--none--none) Signal that the instance has been terminated. No-op if already terminated, destroyed, or fenced (post-reset stale call). #### get\_termination\_event() → Event [Section titled “get\_termination\_event() → Event”](#get_termination_event--event) #### reset() → None [Section titled “reset() → None”](#reset--none) Prepare monitor for the next agent run. * Creates a fresh (unset) event * Clears the termination reason * Cancels any in-flight poll * Sets fence so stale callbacks from the dying run are ignored * Increments generation so stale polls self-discard #### subscribe(callback: Callable\[\[], None]) → Callable\[\[], None] [Section titled “subscribe(callback: Callable\[\[\], None\]) → Callable\[\[\], None\]”](#subscribecallback-callable-none--callable-none) Register a callback invoked on termination. Returns an unsubscribe fn. #### sync(instance\_id: str | None) → None [Section titled “sync(instance\_id: str | None) → None”](#syncinstance_id-str--none--none) Update the tracked instance ID and start/stop the fallback poll. Idempotent: calling with the same non-None ID when a poll is already running does not restart it (preserving the sleep interval). #### *property* termination\_reason *: str | None* [Section titled “property termination\_reason : str | None”](#property-termination_reason--str--none) # prefactor_core.operations module # prefactor\_core.operations module [Section titled “prefactor\_core.operations module”](#prefactor_coreoperations-module) Operation types for prefactor-core. Operations represent discrete units of work that can be queued and processed asynchronously. Each operation type maps to a specific API action. ### *class* prefactor\_core.operations.Operation(type: \~prefactor\_core.operations.OperationType, payload: dict\[str, \~typing.Any], timestamp: \~datetime.datetime, idempotency\_key: str | None = None, metadata: dict\[str, \~typing.Any] = ) [Section titled “class prefactor\_core.operations.Operation(type: \~prefactor\_core.operations.OperationType, payload: dict\[str, \~typing.Any\], timestamp: \~datetime.datetime, idempotency\_key: str | None = None, metadata: dict\[str, \~typing.Any\] = )”](#class-prefactor_coreoperationsoperationtype-prefactor_coreoperationsoperationtype-payload-dictstr-typingany-timestamp-datetimedatetime-idempotency_key-str--none--none-metadata-dictstr-typingany--) Bases: `object` A single operation to be queued and processed. Operations are immutable and contain all data needed for execution. They are created synchronously and processed asynchronously by workers. #### type [Section titled “type”](#type) The type of operation to perform. * **Type:** [prefactor\_core.operations.OperationType](#prefactor_core.operations.OperationType) #### payload [Section titled “payload”](#payload) Dictionary containing operation-specific data. * **Type:** dict\[str, Any] #### timestamp [Section titled “timestamp”](#timestamp) When the operation was created. * **Type:** datetime.datetime #### idempotency\_key [Section titled “idempotency\_key”](#idempotency_key) Optional key for idempotent operations. * **Type:** str | None #### metadata [Section titled “metadata”](#metadata) Optional additional metadata. * **Type:** dict\[str, Any] ### Example [Section titled “Example”](#example) from datetime import datetime, timezone operation = Operation( : type=OperationType.CREATE\_SPAN, payload={ > “instance\_id”: “inst-123”, “schema\_name”: “agent:llm”, “span\_id”: “span-456” > > }, timestamp=datetime.now(timezone.utc), idempotency\_key=”span-456” ) #### idempotency\_key *: str | None* *= None* [Section titled “idempotency\_key : str | None = None”](#idempotency_key--str--none--none) #### metadata *: dict\[str, Any]* [Section titled “metadata : dict\[str, Any\]”](#metadata--dictstr-any) #### payload *: dict\[str, Any]* [Section titled “payload : dict\[str, Any\]”](#payload--dictstr-any) #### timestamp *: datetime* [Section titled “timestamp : datetime”](#timestamp--datetime) #### type *: [OperationType](#prefactor_core.operations.OperationType)* [Section titled “type : OperationType”](#type--operationtype) ### *class* prefactor\_core.operations.OperationType(\*values) [Section titled “class prefactor\_core.operations.OperationType(\*values)”](#class-prefactor_coreoperationsoperationtypevalues) Bases: `Enum` Types of operations that can be performed. Each operation type corresponds to a specific API endpoint action. #### CREATE\_SPAN *= 5* [Section titled “CREATE\_SPAN = 5”](#create_span--5) #### FINISH\_AGENT\_INSTANCE *= 3* [Section titled “FINISH\_AGENT\_INSTANCE = 3”](#finish_agent_instance--3) #### FINISH\_SPAN *= 6* [Section titled “FINISH\_SPAN = 6”](#finish_span--6) #### RECORD\_QUALITY *= 4* [Section titled “RECORD\_QUALITY = 4”](#record_quality--4) #### REGISTER\_AGENT\_INSTANCE *= 1* [Section titled “REGISTER\_AGENT\_INSTANCE = 1”](#register_agent_instance--1) #### START\_AGENT\_INSTANCE *= 2* [Section titled “START\_AGENT\_INSTANCE = 2”](#start_agent_instance--2) # prefactor_core.queue package # prefactor\_core.queue package [Section titled “prefactor\_core.queue package”](#prefactor_corequeue-package) Queue infrastructure layer for prefactor-core. This module provides the foundation for asynchronous queue-based processing: * Queue interface for different queue implementations * InMemoryQueue for simple use cases * TaskExecutor for managing worker pools Future implementations can provide persistent queues (Redis, PostgreSQL, etc.) by implementing the Queue interface. ### *class* prefactor\_core.queue.InMemoryQueue [Section titled “class prefactor\_core.queue.InMemoryQueue”](#class-prefactor_corequeueinmemoryqueue) Bases: [`Queue`](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue)\[`T`] Unbounded in-memory queue implementation. This is the default queue implementation. It’s simple, fast, and suitable for most use cases. All data is stored in memory and will be lost if the process terminates before processing completes. The queue uses asyncio.Queue internally for thread-safe operations. ### Example [Section titled “Example”](#example) queue = InMemoryQueue() await queue.put(“operation”) item = await queue.get() await queue.close() #### *async* close(num\_waiters: int = 1) → None [Section titled “async close(num\_waiters: int = 1) → None”](#async-closenum_waiters-int--1--none) Close the queue. After closing, no new items can be added. Workers will continue to process existing items until the queue is empty, then exit. * **Parameters:** **num\_waiters** – Number of sentinel values to enqueue to wake up that many workers currently blocked in get(). #### *property* closed *: bool* [Section titled “property closed : bool”](#property-closed--bool) Check if the queue has been closed. * **Returns:** True if the queue is closed. #### *async* get() → T [Section titled “async get() → T”](#async-get--t) Remove and return an item from the queue. * **Returns:** The next item from the queue. * **Raises:** [**QueueClosedError**](#prefactor_core.queue.QueueClosedError) – If the queue is closed and empty. #### *async* put(item: T) → None [Section titled “async put(item: T) → None”](#async-putitem-t--none) Add an item to the queue. * **Parameters:** **item** – The item to add. * **Raises:** [**QueueClosedError**](#prefactor_core.queue.QueueClosedError) – If the queue has been closed. #### size() → int [Section titled “size() → int”](#size--int) Return the current number of items in the queue. * **Returns:** The queue size. ### *class* prefactor\_core.queue.Queue [Section titled “class prefactor\_core.queue.Queue”](#class-prefactor_corequeuequeue) Bases: `ABC`, `Generic`\[`T`] Abstract base class for all queue implementations. This interface defines the contract for queue operations used by the TaskExecutor. Implementations must be thread-safe and support async operations. #### *abstractmethod async* close(num\_waiters: int = 1) → None [Section titled “abstractmethod async close(num\_waiters: int = 1) → None”](#abstractmethod-async-closenum_waiters-int--1--none) Close the queue and signal workers to stop. After closing, no new items can be added. Workers should finish processing remaining items and then exit. * **Parameters:** **num\_waiters** – Number of workers currently blocked in get() that need to be woken up so they can observe the closed state. #### *abstract property* closed *: bool* [Section titled “abstract property closed : bool”](#abstract-property-closed--bool) Check if the queue has been closed. * **Returns:** True if close() has been called, False otherwise. #### *abstractmethod async* get() → T [Section titled “abstractmethod async get() → T”](#abstractmethod-async-get--t) Remove and return an item from the queue. This method blocks until an item is available or the queue is closed. * **Returns:** The next item from the queue. * **Raises:** [**QueueClosedError**](#prefactor_core.queue.QueueClosedError) – If the queue is closed and empty. #### *abstractmethod async* put(item: T) → None [Section titled “abstractmethod async put(item: T) → None”](#abstractmethod-async-putitem-t--none) Add an item to the queue. This method should return immediately without blocking the caller. The item will be processed asynchronously by workers. * **Parameters:** **item** – The item to add to the queue. * **Raises:** [**QueueClosedError**](#prefactor_core.queue.QueueClosedError) – If the queue has been closed. #### *abstractmethod* size() → int [Section titled “abstractmethod size() → int”](#abstractmethod-size--int) Return the current number of items in the queue. * **Returns:** The queue size (non-negative integer). ### *exception* prefactor\_core.queue.QueueClosedError [Section titled “exception prefactor\_core.queue.QueueClosedError”](#exception-prefactor_corequeuequeueclosederror) Bases: `Exception` Raised when attempting to use a closed queue. ### *class* prefactor\_core.queue.TaskExecutor(queue: [Queue](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue)\[Any], handler: Callable\[\[Any], Awaitable\[None]], num\_workers: int = 3, max\_retries: int = 3, , is\_retryable: Callable\[\[Exception], bool] | None = None) [Section titled “class prefactor\_core.queue.TaskExecutor(queue: Queue\[Any\], handler: Callable\[\[Any\], Awaitable\[None\]\], num\_workers: int = 3, max\_retries: int = 3, , is\_retryable: Callable\[\[Exception\], bool\] | None = None)”](#class-prefactor_corequeuetaskexecutorqueue-queueany-handler-callableany-awaitablenone-num_workers-int--3-max_retries-int--3--is_retryable-callableexception-bool--none--none) Bases: `object` Manages async workers that process queue items. The executor runs a configurable number of worker tasks that continuously pull items from the queue and process them. If processing fails, items are retried with exponential backoff. ### Example [Section titled “Example”](#example-1) async def handler(item: str) -> None: : print(f”Processing: {item}”) queue = InMemoryQueue() executor = TaskExecutor(queue, handler, num\_workers=3) executor.start() await queue.put(“item1”) await queue.put(“item2”) # Later, when done [Section titled “Later, when done”](#later-when-done) await executor.stop() #### start() → None [Section titled “start() → None”](#start--none) Start the worker tasks. Workers will begin pulling items from the queue immediately. #### *async* stop() → None [Section titled “async stop() → None”](#async-stop--none) Stop all workers gracefully. Closes the queue (so no new items can be added), wakes any workers blocked in get(), and waits for them to drain the remaining items and exit on their own. Workers are never cancelled — that would discard already-queued items. ## Submodules [Section titled “Submodules”](#submodules) * [prefactor\_core.queue.base module](prefactor_core.queue.base.md) * [`Queue`](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue) * [`Queue.close()`](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue.close) * [`Queue.closed`](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue.closed) * [`Queue.get()`](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue.get) * [`Queue.put()`](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue.put) * [`Queue.size()`](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue.size) * [`QueueClosedError`](prefactor_core.queue.base.md#prefactor_core.queue.base.QueueClosedError) * [prefactor\_core.queue.executor module](prefactor_core.queue.executor.md) * [`TaskExecutor`](prefactor_core.queue.executor.md#prefactor_core.queue.executor.TaskExecutor) * [`TaskExecutor.start()`](prefactor_core.queue.executor.md#prefactor_core.queue.executor.TaskExecutor.start) * [`TaskExecutor.stop()`](prefactor_core.queue.executor.md#prefactor_core.queue.executor.TaskExecutor.stop) * [prefactor\_core.queue.memory module](prefactor_core.queue.memory.md) * [`InMemoryQueue`](prefactor_core.queue.memory.md#prefactor_core.queue.memory.InMemoryQueue) * [`InMemoryQueue.close()`](prefactor_core.queue.memory.md#prefactor_core.queue.memory.InMemoryQueue.close) * [`InMemoryQueue.closed`](prefactor_core.queue.memory.md#prefactor_core.queue.memory.InMemoryQueue.closed) * [`InMemoryQueue.get()`](prefactor_core.queue.memory.md#prefactor_core.queue.memory.InMemoryQueue.get) * [`InMemoryQueue.put()`](prefactor_core.queue.memory.md#prefactor_core.queue.memory.InMemoryQueue.put) * [`InMemoryQueue.size()`](prefactor_core.queue.memory.md#prefactor_core.queue.memory.InMemoryQueue.size) # prefactor_core.queue.base module # prefactor\_core.queue.base module [Section titled “prefactor\_core.queue.base module”](#prefactor_corequeuebase-module) Queue infrastructure for prefactor-core. This module provides the foundation layer for async queue-based processing. All queue implementations must satisfy the Queue interface to be used with the TaskExecutor. ### *class* prefactor\_core.queue.base.Queue [Section titled “class prefactor\_core.queue.base.Queue”](#class-prefactor_corequeuebasequeue) Bases: `ABC`, `Generic`\[`T`] Abstract base class for all queue implementations. This interface defines the contract for queue operations used by the TaskExecutor. Implementations must be thread-safe and support async operations. #### *abstractmethod async* close(num\_waiters: int = 1) → None [Section titled “abstractmethod async close(num\_waiters: int = 1) → None”](#abstractmethod-async-closenum_waiters-int--1--none) Close the queue and signal workers to stop. After closing, no new items can be added. Workers should finish processing remaining items and then exit. * **Parameters:** **num\_waiters** – Number of workers currently blocked in get() that need to be woken up so they can observe the closed state. #### *abstract property* closed *: bool* [Section titled “abstract property closed : bool”](#abstract-property-closed--bool) Check if the queue has been closed. * **Returns:** True if close() has been called, False otherwise. #### *abstractmethod async* get() → T [Section titled “abstractmethod async get() → T”](#abstractmethod-async-get--t) Remove and return an item from the queue. This method blocks until an item is available or the queue is closed. * **Returns:** The next item from the queue. * **Raises:** [**QueueClosedError**](#prefactor_core.queue.base.QueueClosedError) – If the queue is closed and empty. #### *abstractmethod async* put(item: T) → None [Section titled “abstractmethod async put(item: T) → None”](#abstractmethod-async-putitem-t--none) Add an item to the queue. This method should return immediately without blocking the caller. The item will be processed asynchronously by workers. * **Parameters:** **item** – The item to add to the queue. * **Raises:** [**QueueClosedError**](#prefactor_core.queue.base.QueueClosedError) – If the queue has been closed. #### *abstractmethod* size() → int [Section titled “abstractmethod size() → int”](#abstractmethod-size--int) Return the current number of items in the queue. * **Returns:** The queue size (non-negative integer). ### *exception* prefactor\_core.queue.base.QueueClosedError [Section titled “exception prefactor\_core.queue.base.QueueClosedError”](#exception-prefactor_corequeuebasequeueclosederror) Bases: `Exception` Raised when attempting to use a closed queue. # prefactor_core.queue.executor module # prefactor\_core.queue.executor module [Section titled “prefactor\_core.queue.executor module”](#prefactor_corequeueexecutor-module) Task executor for processing queue items asynchronously. The TaskExecutor manages a pool of async workers that continuously pull items from a queue and process them using a handler function. ### *class* prefactor\_core.queue.executor.TaskExecutor(queue: [Queue](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue)\[Any], handler: Callable\[\[Any], Awaitable\[None]], num\_workers: int = 3, max\_retries: int = 3, , is\_retryable: Callable\[\[Exception], bool] | None = None) [Section titled “class prefactor\_core.queue.executor.TaskExecutor(queue: Queue\[Any\], handler: Callable\[\[Any\], Awaitable\[None\]\], num\_workers: int = 3, max\_retries: int = 3, , is\_retryable: Callable\[\[Exception\], bool\] | None = None)”](#class-prefactor_corequeueexecutortaskexecutorqueue-queueany-handler-callableany-awaitablenone-num_workers-int--3-max_retries-int--3--is_retryable-callableexception-bool--none--none) Bases: `object` Manages async workers that process queue items. The executor runs a configurable number of worker tasks that continuously pull items from the queue and process them. If processing fails, items are retried with exponential backoff. ### Example [Section titled “Example”](#example) async def handler(item: str) -> None: : print(f”Processing: {item}”) queue = InMemoryQueue() executor = TaskExecutor(queue, handler, num\_workers=3) executor.start() await queue.put(“item1”) await queue.put(“item2”) # Later, when done [Section titled “Later, when done”](#later-when-done) await executor.stop() #### start() → None [Section titled “start() → None”](#start--none) Start the worker tasks. Workers will begin pulling items from the queue immediately. #### *async* stop() → None [Section titled “async stop() → None”](#async-stop--none) Stop all workers gracefully. Closes the queue (so no new items can be added), wakes any workers blocked in get(), and waits for them to drain the remaining items and exit on their own. Workers are never cancelled — that would discard already-queued items. # prefactor_core.queue.memory module # prefactor\_core.queue.memory module [Section titled “prefactor\_core.queue.memory module”](#prefactor_corequeuememory-module) In-memory queue implementation. Provides a simple, unbounded in-memory queue suitable for most use cases. Data is lost on process termination - use a persistent queue implementation for durability requirements. ### *class* prefactor\_core.queue.memory.InMemoryQueue [Section titled “class prefactor\_core.queue.memory.InMemoryQueue”](#class-prefactor_corequeuememoryinmemoryqueue) Bases: [`Queue`](prefactor_core.queue.base.md#prefactor_core.queue.base.Queue)\[`T`] Unbounded in-memory queue implementation. This is the default queue implementation. It’s simple, fast, and suitable for most use cases. All data is stored in memory and will be lost if the process terminates before processing completes. The queue uses asyncio.Queue internally for thread-safe operations. ### Example [Section titled “Example”](#example) queue = InMemoryQueue() await queue.put(“operation”) item = await queue.get() await queue.close() #### *async* close(num\_waiters: int = 1) → None [Section titled “async close(num\_waiters: int = 1) → None”](#async-closenum_waiters-int--1--none) Close the queue. After closing, no new items can be added. Workers will continue to process existing items until the queue is empty, then exit. * **Parameters:** **num\_waiters** – Number of sentinel values to enqueue to wake up that many workers currently blocked in get(). #### *property* closed *: bool* [Section titled “property closed : bool”](#property-closed--bool) Check if the queue has been closed. * **Returns:** True if the queue is closed. #### *async* get() → T [Section titled “async get() → T”](#async-get--t) Remove and return an item from the queue. * **Returns:** The next item from the queue. * **Raises:** [**QueueClosedError**](prefactor_core.md#prefactor_core.QueueClosedError) – If the queue is closed and empty. #### *async* put(item: T) → None [Section titled “async put(item: T) → None”](#async-putitem-t--none) Add an item to the queue. * **Parameters:** **item** – The item to add. * **Raises:** [**QueueClosedError**](prefactor_core.md#prefactor_core.QueueClosedError) – If the queue has been closed. #### size() → int [Section titled “size() → int”](#size--int) Return the current number of items in the queue. * **Returns:** The queue size. # prefactor_core.runtime module # prefactor\_core.runtime module [Section titled “prefactor\_core.runtime module”](#prefactor_coreruntime-module) Runtime environment collection for agent version registration. Provides [`build_runtime_environment()`](#prefactor_core.runtime.build_runtime_environment) which collects OS, Python runtime, and SDK version information into the dict format expected by the Prefactor API’s `agent_version.runtime_environment` field. ### prefactor\_core.runtime.build\_runtime\_environment(sdk\_header\_entry: str | None = None) → dict [Section titled “prefactor\_core.runtime.build\_runtime\_environment(sdk\_header\_entry: str | None = None) → dict”](#prefactor_coreruntimebuild_runtime_environmentsdk_header_entry-str--none--none--dict) Build the `runtime_environment` dict for `agent_version`. Parses *sdk\_header\_entry* (a space-separated list of `"pkg@ver"` tokens as set by upstream adaptors) into `agent_sdk` entries. Always includes `prefactor_sdk`, `os`, and `runtime`. * **Parameters:** **sdk\_header\_entry** – Space-separated SDK header string set by upstream adaptors (e.g. `"prefactor-langchain@0.2.7"`). The trailing `prefactor-core@...` self-entry added by the client is automatically stripped from `agent_sdk`. * **Returns:** A dict with keys `agent_sdk`, `os`, `prefactor_sdk`, and `runtime`, suitable for use as the `runtime_environment` field of `agent_version`. # prefactor_core.schema_registry module # prefactor\_core.schema\_registry module [Section titled “prefactor\_core.schema\_registry module”](#prefactor_coreschema_registry-module) Schema registry for span type definitions. This module provides a SchemaRegistry that allows registration of span schemas from multiple packages before agent instances are created. ### *class* prefactor\_core.schema\_registry.SchemaRegistry [Section titled “class prefactor\_core.schema\_registry.SchemaRegistry”](#class-prefactor_coreschema_registryschemaregistry) Bases: `object` Central registry for span schemas - allows pre-registration. Multiple components can register their schemas independently before agent instance creation. The registry aggregates all into a single format suitable for the API. The API supports three ways to define span schemas, in increasing order of expressiveness: * `span_schemas`: flat map of span name → params JSON schema * `span_result_schemas`: flat map of span name → result JSON schema * `span_type_schemas`: structured list with params, result, title, description, and template per span type Use `register()` for simple payload schemas, `register_result()` to add a result schema for an existing entry, `register_type()` for the full structured form, or `register_quality_schema()` for named quality schemas. All approaches can be mixed; `to_agent_schema_version()` emits whichever fields are populated. ### Example [Section titled “Example”](#example) registry = SchemaRegistry() # Simple params-only schema [Section titled “Simple params-only schema”](#simple-params-only-schema) registry.register(“langchain:agent”, {“type”: “object”}) # Full structured schema with result and display metadata [Section titled “Full structured schema with result and display metadata”](#full-structured-schema-with-result-and-display-metadata) registry.register\_type( > name=”agent:llm”, params\_schema={ > > “type”: “object”, “properties”: { > > > “model”: {“type”: “string”}, “prompt”: {“type”: “string”}, > > }, “required”: \[“model”, “prompt”], > }, result\_schema={ > > “type”: “object”, “properties”: {“response”: {“type”: “string”}}, > }, title=”LLM Call”, description=”A call to a language model”, template=”{{model}}: {{prompt}} → {{response}}”, ) # Convert to API format [Section titled “Convert to API format”](#convert-to-api-format) version = registry.to\_agent\_schema\_version(“combined-1.0.0”) #### get(schema\_name: str) → dict\[str, Any] | None [Section titled “get(schema\_name: str) → dict\[str, Any\] | None”](#getschema_name-str--dictstr-any--none) Get a params schema by name. * **Parameters:** **schema\_name** – The schema identifier to look up * **Returns:** The schema dict if found, None otherwise #### has\_schema(schema\_name: str) → bool [Section titled “has\_schema(schema\_name: str) → bool”](#has_schemaschema_name-str--bool) Check if a params schema is registered for a span type. * **Parameters:** **schema\_name** – The schema identifier to check * **Returns:** True if the schema is registered, False otherwise #### list\_schemas() → list\[str] [Section titled “list\_schemas() → list\[str\]”](#list_schemas--liststr) List all registered span schema names (params schemas only). * **Returns:** List of registered schema names #### merge(other: [SchemaRegistry](#prefactor_core.schema_registry.SchemaRegistry)) → None [Section titled “merge(other: SchemaRegistry) → None”](#mergeother-schemaregistry--none) Merge schemas from another registry into this one. * **Parameters:** **other** – Another SchemaRegistry to merge. Conflicting schemas from the other registry will be rejected. * **Raises:** **ValueError** – If there are conflicting schema names in any category. #### register(schema\_name: str, schema: dict\[str, Any]) → None [Section titled “register(schema\_name: str, schema: dict\[str, Any\]) → None”](#registerschema_name-str-schema-dictstr-any--none) Register a params schema for a span type. Adds to `span_schemas` (the flat params-schema map). Use `register_type()` if you also need a result schema, title, description, or template. * **Parameters:** * **schema\_name** – Unique identifier for this span type (e.g., “langchain:llm”) * **schema** – JSON Schema dict defining the span payload structure * **Raises:** **ValueError** – If schema\_name is already registered. #### register\_quality\_schema(name: str, schema: dict\[str, Any], title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: dict\[str, Any] | None = None) → None [Section titled “register\_quality\_schema(name: str, schema: dict\[str, Any\], title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: dict\[str, Any\] | None = None) → None”](#register_quality_schemaname-str-schema-dictstr-any-title-str--none--none-description-str--none--none-template-str--none--none-data_risk-dictstr-any--none--none--none) Register a named quality schema for instance evaluations. Quality schemas define the shape of quality payloads that can be recorded on agent instances. Multiple quality schemas can be registered, each identified by a unique `name`. * **Parameters:** * **name** – Schema name (key used when recording quality payloads). * **schema** – JSON Schema dict defining the quality payload structure. * **title** – Optional human-readable title (defaults to name on API). * **description** – Optional description of the quality evaluation. * **template** – Optional display template using `{{field}}` interpolation. * **data\_risk** – Optional data risk classification dict (same structure as span type data\_risk). * **Raises:** **ValueError** – If a quality schema with the same name is already registered. #### register\_result(schema\_name: str, result\_schema: dict\[str, Any]) → None [Section titled “register\_result(schema\_name: str, result\_schema: dict\[str, Any\]) → None”](#register_resultschema_name-str-result_schema-dictstr-any--none) Register a result schema for a span type. Adds to `span_result_schemas` (the flat result-schema map). The span type does not need to have a params schema registered first. * **Parameters:** * **schema\_name** – Span type identifier (e.g., “agent:llm”) * **result\_schema** – JSON Schema dict defining the span result payload * **Raises:** **ValueError** – If a result schema for schema\_name is already registered. #### register\_type(name: str, params\_schema: dict\[str, Any], result\_schema: dict\[str, Any] | None = None, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: dict\[str, Any] | None = None) → None [Section titled “register\_type(name: str, params\_schema: dict\[str, Any\], result\_schema: dict\[str, Any\] | None = None, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: dict\[str, Any\] | None = None) → None”](#register_typename-str-params_schema-dictstr-any-result_schema-dictstr-any--none--none-title-str--none--none-description-str--none--none-template-str--none--none-data_risk-dictstr-any--none--none--none) Register a full structured span type schema. Adds to `span_type_schemas`. This is the richest form and supports all API fields: params schema, result schema, human-readable title, description, template, and data risk classification. * **Parameters:** * **name** – Span type name (e.g., “agent:llm”) * **params\_schema** – JSON Schema for the span payload (params) * **result\_schema** – Optional JSON Schema for the span result payload * **title** – Optional human-readable title (defaults to name on the API) * **description** – Optional description of the span type * **template** – Optional display template using `{{field}}` interpolation * **data\_risk** – Optional data risk classification dict. See DataRisk model in prefactor\_http.models.agent\_instance for structure. Must include: * action\_profile (object): Permitted actions with keys: > create\_data, read\_data, update\_data, destroy\_data, financial\_transactions, external\_communication (values: “unknown” | “allowed” | “disallowed”) * params\_data\_categories (object): Input data categories with keys like personal\_identifiers, contact\_information, financial\_information, etc. (values: “unknown” | “included” | “excluded”) * result\_data\_categories (object): Output data categories, same structure as params\_data\_categories All three top-level keys are required; fields within each default to “unknown” when omitted. Example: { > ”action\_profile”: {“read\_data”: “allowed”}, “params\_data\_categories”: {“personal\_identifiers”: “included”}, “result\_data\_categories”: {}, } * **Raises:** **ValueError** – If name is already registered as a span type schema. #### register\_unsafe(schema\_name: str, schema: dict\[str, Any]) → None [Section titled “register\_unsafe(schema\_name: str, schema: dict\[str, Any\]) → None”](#register_unsafeschema_name-str-schema-dictstr-any--none) Register a params schema, overwriting if it already exists. * **Parameters:** * **schema\_name** – Unique identifier for this span type * **schema** – JSON Schema dict defining the span payload structure #### to\_agent\_schema\_version(external\_id: str) → dict\[str, Any] [Section titled “to\_agent\_schema\_version(external\_id: str) → dict\[str, Any\]”](#to_agent_schema_versionexternal_id-str--dictstr-any) Convert registry contents to API-compatible agent\_schema\_version format. Emits `span_schemas`, `span_result_schemas`, `span_type_schemas`, and `quality_schemas` for whichever have been populated. * **Parameters:** **external\_id** – External identifier for this combined schema version * **Returns:** Dict with `external_identifier` and whichever schema fields are non-empty. # prefactor_core.span_context module # prefactor\_core.span\_context module [Section titled “prefactor\_core.span\_context module”](#prefactor_corespan_context-module) Span context for automatic lifecycle management. The SpanContext provides an interface for updating span data during execution and ensures proper cleanup when the span completes. ### *class* prefactor\_core.span\_context.SpanContext(temp\_id: str, span\_manager: [SpanManager](prefactor_core.managers.md#prefactor_core.managers.SpanManager), default\_payload: dict\[str, Any] | None = None) [Section titled “class prefactor\_core.span\_context.SpanContext(temp\_id: str, span\_manager: SpanManager, default\_payload: dict\[str, Any\] | None = None)”](#class-prefactor_corespan_contextspancontexttemp_id-str-span_manager-spanmanager-default_payload-dictstr-any--none--none) Bases: `object` Context for an active span. Returned by `instance.span()` / `client.span()` context managers. Spans follow a three-phase lifecycle: 1. **Enter context** — span is prepared locally (no HTTP call yet). 2. **“await span.start(payload)“** — POSTs the span to the API as `active` with the given params payload. 3. **“await span.complete(result)“** (or `.fail()` / `.cancel()`) — finishes the span with the appropriate terminal status. `cancelled` before start is handled via `pending → cancelled`; once started, the span transitions from `active` to a terminal status. If `start()` or a finish method is omitted, the context manager calls them automatically on exit (auto-start uses `default_payload`; the default finish status is `complete`), so explicit calls are opt-in. Example: ```default async with instance.span("agent:llm_call") as span: await span.start({"model": "claude-3-5-sonnet", "prompt": "Hi"}) try: response = await call_llm(...) await span.complete({"response": response, "tokens": 42}) except Exception as exc: await span.fail({"error": str(exc)}) # Skip start entirely to cancel before any work begins: async with instance.span("agent:retrieval") as span: if not needed: await span.cancel() else: await span.start({"query": "..."}) ... ``` #### *async* cancel(timestamp: datetime | None = None) → None [Section titled “async cancel(timestamp: datetime | None = None) → None”](#async-canceltimestamp-datetime--none--none--none) Finish the span with `cancelled` status. Can be called before or after `start()`. If `start()` has not been called yet, the span is posted as `pending` then immediately cancelled — the API only accepts cancellation from the `pending` state, so this is always a valid sequence. * **Parameters:** **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* complete(result: dict\[str, Any] | None = None, timestamp: datetime | None = None) → None [Section titled “async complete(result: dict\[str, Any\] | None = None, timestamp: datetime | None = None) → None”](#async-completeresult-dictstr-any--none--none-timestamp-datetime--none--none--none) Finish the span with `complete` status. * **Parameters:** * **result** – Optional result payload to attach to the span. * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* fail(result: dict\[str, Any] | None = None, timestamp: datetime | None = None) → None [Section titled “async fail(result: dict\[str, Any\] | None = None, timestamp: datetime | None = None) → None”](#async-failresult-dictstr-any--none--none-timestamp-datetime--none--none--none) Finish the span with `failed` status. * **Parameters:** * **result** – Optional result payload (e.g. error details). * **timestamp** – Optional ISO 8601 finish time (defaults to current time). #### *async* finish() → None [Section titled “async finish() → None”](#async-finish--none) Finish the span using whichever status was last set (default: `complete`). Called automatically when exiting the context manager. Can also be called manually; subsequent calls are no-ops. #### *property* id *: str* [Section titled “property id : str”](#property-id--str) Get the span ID. Before `start()` is called this returns the temporary local ID. After `start()` it returns the API-generated ID. * **Returns:** The span identifier. #### set\_result(data: dict\[str, Any]) → None [Section titled “set\_result(data: dict\[str, Any\]) → None”](#set_resultdata-dictstr-any--none) Store result data to be sent when the span finishes. The data is merged and sent as `result_payload` when the span finishes. Calling this does **not** finish the span. * **Parameters:** **data** – Dictionary of result data for the span. #### *async* start(payload: dict\[str, Any] | None = None, started\_at: datetime | None = None) → None [Section titled “async start(payload: dict\[str, Any\] | None = None, started\_at: datetime | None = None) → None”](#async-startpayload-dictstr-any--none--none-started_at-datetime--none--none--none) Post the span to the API as `active` with the given params payload. This triggers `POST /api/v1/agent_spans`. The span is created as `pending` so that any terminal status (`complete`, `failed`, `cancelled`) is a valid transition via the finish endpoint. Must be called at most once; subsequent calls are no-ops. * **Parameters:** * **payload** – Optional params/inputs for the span (e.g. model name, prompt text, tool input). Stored as the span’s `payload` field in the API. * **started\_at** – Optional ISO 8601 start time (defaults to current time). # prefactor_core.utils module # prefactor\_core.utils module [Section titled “prefactor\_core.utils module”](#prefactor_coreutils-module) Utility functions for prefactor-core. ### prefactor\_core.utils.generate\_idempotency\_key() → str [Section titled “prefactor\_core.utils.generate\_idempotency\_key() → str”](#prefactor_coreutilsgenerate_idempotency_key--str) Generate a new UUID-based idempotency key. The returned key is a UUID4 string (36 characters), always within the 64-character API limit. * **Returns:** A unique idempotency key string. ### prefactor\_core.utils.validate\_idempotency\_key(key: str) → str [Section titled “prefactor\_core.utils.validate\_idempotency\_key(key: str) → str”](#prefactor_coreutilsvalidate_idempotency_keykey-str--str) Validate that an idempotency key is a non-empty string of at most 64 characters. * **Parameters:** **key** – The idempotency key to validate. * **Returns:** The key unchanged if valid. * **Raises:** **ValueError** – If the key is empty or exceeds 64 characters. ### prefactor\_core.utils.warn\_missing\_adaptor\_config(instance\_id: str, adaptor\_name: str, create\_client\_call: str) → None [Section titled “prefactor\_core.utils.warn\_missing\_adaptor\_config(instance\_id: str, adaptor\_name: str, create\_client\_call: str) → None”](#prefactor_coreutilswarn_missing_adaptor_configinstance_id-str-adaptor_name-str-create_client_call-str--none) Warn that an instance was registered before the adaptor configured the client. Called by framework adaptors (langchain, livekit, etc.) when a pre-created instance is passed in and the backing client wasn’t set up through `create_client()` or `from_config()`. * **Parameters:** * **instance\_id** – The agent instance ID that was registered too early. * **adaptor\_name** – Human-readable adaptor name (e.g. `"middleware"`). * **create\_client\_call** – The call the user should use instead (e.g. `"PrefactorMiddleware.create_client(config)"`). # Prefactor HTTP Client # Prefactor HTTP Client [Section titled “Prefactor HTTP Client”](#prefactor-http-client) A low-level async HTTP client for the Prefactor API. ## Features [Section titled “Features”](#features) * **Typed Endpoint Clients**: Dedicated clients for agent instances, agent spans, and bulk operations * **Automatic Retries**: Exponential backoff with jitter for transient failures * **Type Safety**: Full Pydantic models for all request/response data * **Clear Error Hierarchy**: Specific exception types for different failure modes * **Idempotency**: Built-in support for idempotency keys ## Installation [Section titled “Installation”](#installation) ```bash pip install prefactor-http ``` ## Quick Start [Section titled “Quick Start”](#quick-start) ```python import asyncio from prefactor_http import PrefactorHttpClient, HttpClientConfig async def main(): config = HttpClientConfig( api_url="https://app.prefactorai.com", api_token="your-api-token", ) async with PrefactorHttpClient(config) as client: instance = await client.agent_instances.register( agent_id="agent_123", agent_version={"name": "My Agent", "external_identifier": "v1.0.0"}, agent_schema_version={ "external_identifier": "v1.0.0", "span_type_schemas": [ { "name": "agent:llm", "title": "LLM Call", "description": "A call to a language model", "params_schema": { "type": "object", "properties": { "model": {"type": "string"}, "prompt": {"type": "string"}, }, "required": ["model", "prompt"], }, "result_schema": { "type": "object", "properties": {"response": {"type": "string"}}, }, "template": "{{model}}: {{prompt}} → {{response}}", }, ], }, ) print(f"Registered instance: {instance.id}") asyncio.run(main()) ``` `agent_instances.register()` supports two auth modes: * Account-scoped token: pass `agent_id` and usually `environment_id`. * Deployment-scoped token: omit `agent_id` and `environment_id`; the API derives both from the token. ## Endpoints [Section titled “Endpoints”](#endpoints) ### Agent Instances (`client.agent_instances`) [Section titled “Agent Instances (client.agent\_instances)”](#agent-instances-clientagent_instances) ```python # Register a new agent instance instance = await client.agent_instances.register( agent_id="agent_123", agent_version={ "name": "My Agent", "external_identifier": "v1.0.0", "description": "Optional description", }, agent_schema_version={ "external_identifier": "schema-v1", "span_type_schemas": [ { "name": "agent:llm", "title": "LLM Call", # Optional "description": "A call to a language model", # Optional "params_schema": {"type": "object", "properties": {...}}, "result_schema": {"type": "object", "properties": {...}}, # Optional "template": "{{model}}: {{prompt}} → {{response}}", # Optional }, ], # Alternatively, use flat maps for simpler cases: # "span_schemas": {"agent:llm": {"type": "object", ...}}, # "span_result_schemas": {"agent:llm": {"type": "object", ...}}, }, id=None, # Optional: pre-assign an ID idempotency_key=None, # Optional: idempotency key update_current_version=True, # Optional: update the agent's current version ) # Register with a deployment-scoped token instance = await client.agent_instances.register( agent_version={ "name": "My Agent", "external_identifier": "v1.0.0", }, agent_schema_version={ "external_identifier": "schema-v1", "span_type_schemas": [], }, ) # Start an instance instance = await client.agent_instances.start( agent_instance_id=instance.id, timestamp=None, # Optional: override start time idempotency_key=None, ) # Finish an instance instance = await client.agent_instances.finish( agent_instance_id=instance.id, status=None, # Optional: "complete" | "failed" | "cancelled" timestamp=None, # Optional: override finish time idempotency_key=None, ) ``` The `AgentInstance` response includes: `id`, `agent_id`, `status`, `started_at`, `finished_at`, `span_counts`, and more. ### Agent Spans (`client.agent_spans`) [Section titled “Agent Spans (client.agent\_spans)”](#agent-spans-clientagent_spans) ```python # Create a span span = await client.agent_spans.create( agent_instance_id="instance_123", schema_name="agent:llm", status="active", payload={"model": "gpt-4", "prompt": "Hello"}, # Optional result_payload=None, # Optional id=None, # Optional: pre-assign an ID parent_span_id=None, # Optional: parent for nesting started_at=None, # Optional: override start time finished_at=None, idempotency_key=None, ) # Finish a span span = await client.agent_spans.finish( agent_span_id=span.id, status=None, # Optional: "complete" | "failed" | "cancelled" result_payload=None, # Optional: final result data timestamp=None, # Optional: override finish time idempotency_key=None, ) ``` The `AgentSpan` response includes: `id`, `agent_instance_id`, `schema_name`, `status`, `payload`, `result_payload`, `parent_span_id`, `started_at`, `finished_at`, and more. ### Bulk Operations (`client.bulk`) [Section titled “Bulk Operations (client.bulk)”](#bulk-operations-clientbulk) Execute multiple POST actions in a single HTTP request. ```python from prefactor_http import BulkRequest, BulkItem request = BulkRequest( items=[ BulkItem( _type="agent_instances/register", idempotency_key="register-instance-001", agent_id="agent_123", agent_version={"name": "My Agent", "external_identifier": "v1.0.0"}, agent_schema_version={ "external_identifier": "v1.0.0", "span_type_schemas": [ { "name": "agent:llm", "title": "LLM Call", "params_schema": { "type": "object", "properties": { "model": {"type": "string"}, "prompt": {"type": "string"}, }, "required": ["model", "prompt"], }, "result_schema": { "type": "object", "properties": {"response": {"type": "string"}}, }, }, ], }, ), BulkItem( _type="agent_spans/create", idempotency_key="create-span-001", agent_instance_id="instance_123", schema_name="agent:llm", status="active", ), ] ) response = await client.bulk.execute(request) for key, output in response.outputs.items(): print(f"{key}: {output.status}") # "success" or "error" ``` **Validation rules:** * Each item must have a unique `idempotency_key` (8–64 characters) * The request must contain at least one item ## Error Handling [Section titled “Error Handling”](#error-handling) ```python from prefactor_http import ( PrefactorHttpError, PrefactorApiError, PrefactorAuthError, PrefactorNotFoundError, PrefactorValidationError, PrefactorRetryExhaustedError, PrefactorClientError, ) try: async with PrefactorHttpClient(config) as client: instance = await client.agent_instances.register(...) except PrefactorValidationError as e: print(f"Validation error: {e.errors}") except PrefactorAuthError: print("Authentication failed - check your API token") except PrefactorNotFoundError: print("Resource not found") except PrefactorRetryExhaustedError as e: print(f"Request failed after retries: {e.last_error}") except PrefactorApiError as e: print(f"API error {e.status_code}: {e.code}") ``` ## Configuration [Section titled “Configuration”](#configuration) ```python config = HttpClientConfig( # Required api_url="https://app.prefactorai.com", api_token="your-token", # Retry behavior max_retries=3, initial_retry_delay=1.0, max_retry_delay=60.0, retry_multiplier=2.0, # Timeouts request_timeout=30.0, connect_timeout=10.0, ) ``` ## Types [Section titled “Types”](#types) ```python from prefactor_http import AgentStatus, FinishStatus # AgentStatus = Literal["pending", "active", "complete", "failed", "cancelled", "terminated"] # FinishStatus = Literal["complete", "failed", "cancelled"] ``` ## License [Section titled “License”](#license) MIT # prefactor_http # prefactor\_http [Section titled “prefactor\_http”](#prefactor_http) * [prefactor\_http package](prefactor_http.md) * [`AgentInstance`](prefactor_http.md#prefactor_http.AgentInstance) * [`AgentInstance.type`](prefactor_http.md#prefactor_http.AgentInstance.type) * [`AgentInstance.id`](prefactor_http.md#prefactor_http.AgentInstance.id) * [`AgentInstance.account_id`](prefactor_http.md#prefactor_http.AgentInstance.account_id) * [`AgentInstance.agent_id`](prefactor_http.md#prefactor_http.AgentInstance.agent_id) * [`AgentInstance.agent_version_id`](prefactor_http.md#prefactor_http.AgentInstance.agent_version_id) * [`AgentInstance.environment_id`](prefactor_http.md#prefactor_http.AgentInstance.environment_id) * [`AgentInstance.agent_deployment_id`](prefactor_http.md#prefactor_http.AgentInstance.agent_deployment_id) * [`AgentInstance.status`](prefactor_http.md#prefactor_http.AgentInstance.status) * [`AgentInstance.inserted_at`](prefactor_http.md#prefactor_http.AgentInstance.inserted_at) * [`AgentInstance.updated_at`](prefactor_http.md#prefactor_http.AgentInstance.updated_at) * [`AgentInstance.started_at`](prefactor_http.md#prefactor_http.AgentInstance.started_at) * [`AgentInstance.finished_at`](prefactor_http.md#prefactor_http.AgentInstance.finished_at) * [`AgentInstance.termination_reason`](prefactor_http.md#prefactor_http.AgentInstance.termination_reason) * [`AgentInstance.external_identifier`](prefactor_http.md#prefactor_http.AgentInstance.external_identifier) * [`AgentInstance.span_counts`](prefactor_http.md#prefactor_http.AgentInstance.span_counts) * [`AgentInstance.purpose`](prefactor_http.md#prefactor_http.AgentInstance.purpose) * [`AgentInstance.quality_payloads`](prefactor_http.md#prefactor_http.AgentInstance.quality_payloads) * [`AgentInstance.quality_summaries`](prefactor_http.md#prefactor_http.AgentInstance.quality_summaries) * [`AgentInstance.account_id`](prefactor_http.md#id0) * [`AgentInstance.agent_deployment_id`](prefactor_http.md#id1) * [`AgentInstance.agent_id`](prefactor_http.md#id2) * [`AgentInstance.agent_version_id`](prefactor_http.md#id3) * [`AgentInstance.environment_id`](prefactor_http.md#id4) * [`AgentInstance.external_identifier`](prefactor_http.md#id5) * [`AgentInstance.finished_at`](prefactor_http.md#id6) * [`AgentInstance.id`](prefactor_http.md#id7) * [`AgentInstance.inserted_at`](prefactor_http.md#id8) * [`AgentInstance.model_config`](prefactor_http.md#prefactor_http.AgentInstance.model_config) * [`AgentInstance.purpose`](prefactor_http.md#id9) * [`AgentInstance.quality_payloads`](prefactor_http.md#id10) * [`AgentInstance.quality_summaries`](prefactor_http.md#id11) * [`AgentInstance.span_counts`](prefactor_http.md#id12) * [`AgentInstance.started_at`](prefactor_http.md#id13) * [`AgentInstance.status`](prefactor_http.md#id14) * [`AgentInstance.termination_reason`](prefactor_http.md#id15) * [`AgentInstance.type`](prefactor_http.md#id16) * [`AgentInstance.updated_at`](prefactor_http.md#id17) * [`AgentInstanceRecordQuality`](prefactor_http.md#prefactor_http.AgentInstanceRecordQuality) * [`AgentInstanceRecordQuality.name`](prefactor_http.md#prefactor_http.AgentInstanceRecordQuality.name) * [`AgentInstanceRecordQuality.payload`](prefactor_http.md#prefactor_http.AgentInstanceRecordQuality.payload) * [`AgentInstanceRecordQuality.model_config`](prefactor_http.md#prefactor_http.AgentInstanceRecordQuality.model_config) * [`AgentInstanceRecordQuality.name`](prefactor_http.md#id18) * [`AgentInstanceRecordQuality.payload`](prefactor_http.md#id19) * [`AgentInstanceSpanCounts`](prefactor_http.md#prefactor_http.AgentInstanceSpanCounts) * [`AgentInstanceSpanCounts.total`](prefactor_http.md#prefactor_http.AgentInstanceSpanCounts.total) * [`AgentInstanceSpanCounts.active`](prefactor_http.md#prefactor_http.AgentInstanceSpanCounts.active) * [`AgentInstanceSpanCounts.complete`](prefactor_http.md#prefactor_http.AgentInstanceSpanCounts.complete) * [`AgentInstanceSpanCounts.failed`](prefactor_http.md#prefactor_http.AgentInstanceSpanCounts.failed) * [`AgentInstanceSpanCounts.cancelled`](prefactor_http.md#prefactor_http.AgentInstanceSpanCounts.cancelled) * [`AgentInstanceSpanCounts.finished`](prefactor_http.md#prefactor_http.AgentInstanceSpanCounts.finished) * [`AgentInstanceSpanCounts.active`](prefactor_http.md#id20) * [`AgentInstanceSpanCounts.cancelled`](prefactor_http.md#id21) * [`AgentInstanceSpanCounts.complete`](prefactor_http.md#id22) * [`AgentInstanceSpanCounts.failed`](prefactor_http.md#id23) * [`AgentInstanceSpanCounts.finished`](prefactor_http.md#id24) * [`AgentInstanceSpanCounts.model_config`](prefactor_http.md#prefactor_http.AgentInstanceSpanCounts.model_config) * [`AgentInstanceSpanCounts.total`](prefactor_http.md#id25) * [`AgentSchemaVersionForRegister`](prefactor_http.md#prefactor_http.AgentSchemaVersionForRegister) * [`AgentSchemaVersionForRegister.external_identifier`](prefactor_http.md#prefactor_http.AgentSchemaVersionForRegister.external_identifier) * [`AgentSchemaVersionForRegister.span_schemas`](prefactor_http.md#prefactor_http.AgentSchemaVersionForRegister.span_schemas) * [`AgentSchemaVersionForRegister.span_result_schemas`](prefactor_http.md#prefactor_http.AgentSchemaVersionForRegister.span_result_schemas) * [`AgentSchemaVersionForRegister.span_type_schemas`](prefactor_http.md#prefactor_http.AgentSchemaVersionForRegister.span_type_schemas) * [`AgentSchemaVersionForRegister.quality_schemas`](prefactor_http.md#prefactor_http.AgentSchemaVersionForRegister.quality_schemas) * [`AgentSchemaVersionForRegister.external_identifier`](prefactor_http.md#id26) * [`AgentSchemaVersionForRegister.model_config`](prefactor_http.md#prefactor_http.AgentSchemaVersionForRegister.model_config) * [`AgentSchemaVersionForRegister.quality_schemas`](prefactor_http.md#id27) * [`AgentSchemaVersionForRegister.span_result_schemas`](prefactor_http.md#id28) * [`AgentSchemaVersionForRegister.span_schemas`](prefactor_http.md#id29) * [`AgentSchemaVersionForRegister.span_type_schemas`](prefactor_http.md#id30) * [`AgentSpan`](prefactor_http.md#prefactor_http.AgentSpan) * [`AgentSpan.type`](prefactor_http.md#prefactor_http.AgentSpan.type) * [`AgentSpan.id`](prefactor_http.md#prefactor_http.AgentSpan.id) * [`AgentSpan.account_id`](prefactor_http.md#prefactor_http.AgentSpan.account_id) * [`AgentSpan.agent_id`](prefactor_http.md#prefactor_http.AgentSpan.agent_id) * [`AgentSpan.agent_instance_id`](prefactor_http.md#prefactor_http.AgentSpan.agent_instance_id) * [`AgentSpan.parent_span_id`](prefactor_http.md#prefactor_http.AgentSpan.parent_span_id) * [`AgentSpan.schema_name`](prefactor_http.md#prefactor_http.AgentSpan.schema_name) * [`AgentSpan.schema_title`](prefactor_http.md#prefactor_http.AgentSpan.schema_title) * [`AgentSpan.status`](prefactor_http.md#prefactor_http.AgentSpan.status) * [`AgentSpan.payload`](prefactor_http.md#prefactor_http.AgentSpan.payload) * [`AgentSpan.result_payload`](prefactor_http.md#prefactor_http.AgentSpan.result_payload) * [`AgentSpan.summary`](prefactor_http.md#prefactor_http.AgentSpan.summary) * [`AgentSpan.started_at`](prefactor_http.md#prefactor_http.AgentSpan.started_at) * [`AgentSpan.inserted_at`](prefactor_http.md#prefactor_http.AgentSpan.inserted_at) * [`AgentSpan.updated_at`](prefactor_http.md#prefactor_http.AgentSpan.updated_at) * [`AgentSpan.finished_at`](prefactor_http.md#prefactor_http.AgentSpan.finished_at) * [`AgentSpan.account_id`](prefactor_http.md#id31) * [`AgentSpan.agent_id`](prefactor_http.md#id32) * [`AgentSpan.agent_instance_id`](prefactor_http.md#id33) * [`AgentSpan.finished_at`](prefactor_http.md#id34) * [`AgentSpan.id`](prefactor_http.md#id35) * [`AgentSpan.inserted_at`](prefactor_http.md#id36) * [`AgentSpan.model_config`](prefactor_http.md#prefactor_http.AgentSpan.model_config) * [`AgentSpan.parent_span_id`](prefactor_http.md#id37) * [`AgentSpan.payload`](prefactor_http.md#id38) * [`AgentSpan.result_payload`](prefactor_http.md#id39) * [`AgentSpan.schema_name`](prefactor_http.md#id40) * [`AgentSpan.schema_title`](prefactor_http.md#id41) * [`AgentSpan.started_at`](prefactor_http.md#id42) * [`AgentSpan.status`](prefactor_http.md#id43) * [`AgentSpan.summary`](prefactor_http.md#id44) * [`AgentSpan.type`](prefactor_http.md#id45) * [`AgentSpan.updated_at`](prefactor_http.md#id46) * [`AgentVersionForRegister`](prefactor_http.md#prefactor_http.AgentVersionForRegister) * [`AgentVersionForRegister.name`](prefactor_http.md#prefactor_http.AgentVersionForRegister.name) * [`AgentVersionForRegister.external_identifier`](prefactor_http.md#prefactor_http.AgentVersionForRegister.external_identifier) * [`AgentVersionForRegister.description`](prefactor_http.md#prefactor_http.AgentVersionForRegister.description) * [`AgentVersionForRegister.runtime_environment`](prefactor_http.md#prefactor_http.AgentVersionForRegister.runtime_environment) * [`AgentVersionForRegister.description`](prefactor_http.md#id47) * [`AgentVersionForRegister.external_identifier`](prefactor_http.md#id48) * [`AgentVersionForRegister.model_config`](prefactor_http.md#prefactor_http.AgentVersionForRegister.model_config) * [`AgentVersionForRegister.name`](prefactor_http.md#id49) * [`AgentVersionForRegister.runtime_environment`](prefactor_http.md#id50) * [`ApiResponse`](prefactor_http.md#prefactor_http.ApiResponse) * [`ApiResponse.status`](prefactor_http.md#prefactor_http.ApiResponse.status) * [`ApiResponse.details`](prefactor_http.md#prefactor_http.ApiResponse.details) * [`ApiResponse.details`](prefactor_http.md#id51) * [`ApiResponse.model_config`](prefactor_http.md#prefactor_http.ApiResponse.model_config) * [`ApiResponse.status`](prefactor_http.md#id52) * [`BulkItem`](prefactor_http.md#prefactor_http.BulkItem) * [`BulkItem.idempotency_key`](prefactor_http.md#prefactor_http.BulkItem.idempotency_key) * [`BulkItem.model_config`](prefactor_http.md#prefactor_http.BulkItem.model_config) * [`BulkItem.type`](prefactor_http.md#prefactor_http.BulkItem.type) * [`BulkOutput`](prefactor_http.md#prefactor_http.BulkOutput) * [`BulkOutput.model_config`](prefactor_http.md#prefactor_http.BulkOutput.model_config) * [`BulkOutput.status`](prefactor_http.md#prefactor_http.BulkOutput.status) * [`BulkOutput.validate_status()`](prefactor_http.md#prefactor_http.BulkOutput.validate_status) * [`BulkRequest`](prefactor_http.md#prefactor_http.BulkRequest) * [`BulkRequest.items`](prefactor_http.md#prefactor_http.BulkRequest.items) * [`BulkRequest.model_config`](prefactor_http.md#prefactor_http.BulkRequest.model_config) * [`BulkRequest.validate_unique_idempotency_keys()`](prefactor_http.md#prefactor_http.BulkRequest.validate_unique_idempotency_keys) * [`BulkResponse`](prefactor_http.md#prefactor_http.BulkResponse) * [`BulkResponse.model_config`](prefactor_http.md#prefactor_http.BulkResponse.model_config) * [`BulkResponse.outputs`](prefactor_http.md#prefactor_http.BulkResponse.outputs) * [`BulkResponse.status`](prefactor_http.md#prefactor_http.BulkResponse.status) * [`FinishInstanceRequest`](prefactor_http.md#prefactor_http.FinishInstanceRequest) * [`FinishInstanceRequest.status`](prefactor_http.md#prefactor_http.FinishInstanceRequest.status) * [`FinishInstanceRequest.timestamp`](prefactor_http.md#prefactor_http.FinishInstanceRequest.timestamp) * [`FinishInstanceRequest.idempotency_key`](prefactor_http.md#prefactor_http.FinishInstanceRequest.idempotency_key) * [`FinishInstanceRequest.idempotency_key`](prefactor_http.md#id53) * [`FinishInstanceRequest.model_config`](prefactor_http.md#prefactor_http.FinishInstanceRequest.model_config) * [`FinishInstanceRequest.status`](prefactor_http.md#id54) * [`FinishInstanceRequest.timestamp`](prefactor_http.md#id55) * [`HttpClientConfig`](prefactor_http.md#prefactor_http.HttpClientConfig) * [`HttpClientConfig.api_url`](prefactor_http.md#prefactor_http.HttpClientConfig.api_url) * [`HttpClientConfig.api_token`](prefactor_http.md#prefactor_http.HttpClientConfig.api_token) * [`HttpClientConfig.request_timeout`](prefactor_http.md#prefactor_http.HttpClientConfig.request_timeout) * [`HttpClientConfig.connect_timeout`](prefactor_http.md#prefactor_http.HttpClientConfig.connect_timeout) * [`HttpClientConfig.max_retries`](prefactor_http.md#prefactor_http.HttpClientConfig.max_retries) * [`HttpClientConfig.initial_retry_delay`](prefactor_http.md#prefactor_http.HttpClientConfig.initial_retry_delay) * [`HttpClientConfig.max_retry_delay`](prefactor_http.md#prefactor_http.HttpClientConfig.max_retry_delay) * [`HttpClientConfig.retry_multiplier`](prefactor_http.md#prefactor_http.HttpClientConfig.retry_multiplier) * [`HttpClientConfig.retry_on_status_codes`](prefactor_http.md#prefactor_http.HttpClientConfig.retry_on_status_codes) * [`HttpClientConfig.default_idempotency_key`](prefactor_http.md#prefactor_http.HttpClientConfig.default_idempotency_key) * [`HttpClientConfig.api_token`](prefactor_http.md#id56) * [`HttpClientConfig.api_url`](prefactor_http.md#id57) * [`HttpClientConfig.connect_timeout`](prefactor_http.md#id58) * [`HttpClientConfig.default_idempotency_key`](prefactor_http.md#id59) * [`HttpClientConfig.initial_retry_delay`](prefactor_http.md#id60) * [`HttpClientConfig.max_retries`](prefactor_http.md#id61) * [`HttpClientConfig.max_retry_delay`](prefactor_http.md#id62) * [`HttpClientConfig.request_timeout`](prefactor_http.md#id63) * [`HttpClientConfig.retry_multiplier`](prefactor_http.md#id64) * [`HttpClientConfig.retry_on_status_codes`](prefactor_http.md#id65) * [`PrefactorApiError`](prefactor_http.md#prefactor_http.PrefactorApiError) * [`PrefactorApiError.message`](prefactor_http.md#prefactor_http.PrefactorApiError.message) * [`PrefactorApiError.code`](prefactor_http.md#prefactor_http.PrefactorApiError.code) * [`PrefactorApiError.status_code`](prefactor_http.md#prefactor_http.PrefactorApiError.status_code) * [`PrefactorAuthError`](prefactor_http.md#prefactor_http.PrefactorAuthError) * [`PrefactorClientError`](prefactor_http.md#prefactor_http.PrefactorClientError) * [`PrefactorHttpClient`](prefactor_http.md#prefactor_http.PrefactorHttpClient) * [`PrefactorHttpClient.agent_instances`](prefactor_http.md#prefactor_http.PrefactorHttpClient.agent_instances) * [`PrefactorHttpClient.agent_spans`](prefactor_http.md#prefactor_http.PrefactorHttpClient.agent_spans) * [`PrefactorHttpClient.agents`](prefactor_http.md#prefactor_http.PrefactorHttpClient.agents) * [`PrefactorHttpClient.bulk`](prefactor_http.md#prefactor_http.PrefactorHttpClient.bulk) * [`PrefactorHttpClient.close()`](prefactor_http.md#prefactor_http.PrefactorHttpClient.close) * [`PrefactorHttpClient.request()`](prefactor_http.md#prefactor_http.PrefactorHttpClient.request) * [`PrefactorHttpClient.validate_token()`](prefactor_http.md#prefactor_http.PrefactorHttpClient.validate_token) * [`PrefactorHttpError`](prefactor_http.md#prefactor_http.PrefactorHttpError) * [`PrefactorNotFoundError`](prefactor_http.md#prefactor_http.PrefactorNotFoundError) * [`PrefactorResponseContractError`](prefactor_http.md#prefactor_http.PrefactorResponseContractError) * [`PrefactorRetryExhaustedError`](prefactor_http.md#prefactor_http.PrefactorRetryExhaustedError) * [`PrefactorRetryExhaustedError.last_error`](prefactor_http.md#prefactor_http.PrefactorRetryExhaustedError.last_error) * [`PrefactorValidationError`](prefactor_http.md#prefactor_http.PrefactorValidationError) * [`PrefactorValidationError.errors`](prefactor_http.md#prefactor_http.PrefactorValidationError.errors) * [`QualitySchemaDetails`](prefactor_http.md#prefactor_http.QualitySchemaDetails) * [`QualitySchemaDetails.name`](prefactor_http.md#prefactor_http.QualitySchemaDetails.name) * [`QualitySchemaDetails.title`](prefactor_http.md#prefactor_http.QualitySchemaDetails.title) * [`QualitySchemaDetails.description`](prefactor_http.md#prefactor_http.QualitySchemaDetails.description) * [`QualitySchemaDetails.template`](prefactor_http.md#prefactor_http.QualitySchemaDetails.template) * [`QualitySchemaDetails.data_risk`](prefactor_http.md#prefactor_http.QualitySchemaDetails.data_risk) * [`QualitySchemaDetails.schema`](prefactor_http.md#prefactor_http.QualitySchemaDetails.schema) * [`QualitySchemaDetails.schema_validation`](prefactor_http.md#prefactor_http.QualitySchemaDetails.schema_validation) * [`QualitySchemaDetails.data_risk`](prefactor_http.md#id66) * [`QualitySchemaDetails.description`](prefactor_http.md#id67) * [`QualitySchemaDetails.model_config`](prefactor_http.md#prefactor_http.QualitySchemaDetails.model_config) * [`QualitySchemaDetails.name`](prefactor_http.md#id68) * [`QualitySchemaDetails.schema_`](prefactor_http.md#prefactor_http.QualitySchemaDetails.schema_) * [`QualitySchemaDetails.schema_validation`](prefactor_http.md#id69) * [`QualitySchemaDetails.template`](prefactor_http.md#id70) * [`QualitySchemaDetails.title`](prefactor_http.md#id71) * [`QualitySchemaForCreate`](prefactor_http.md#prefactor_http.QualitySchemaForCreate) * [`QualitySchemaForCreate.name`](prefactor_http.md#prefactor_http.QualitySchemaForCreate.name) * [`QualitySchemaForCreate.schema`](prefactor_http.md#prefactor_http.QualitySchemaForCreate.schema) * [`QualitySchemaForCreate.title`](prefactor_http.md#prefactor_http.QualitySchemaForCreate.title) * [`QualitySchemaForCreate.description`](prefactor_http.md#prefactor_http.QualitySchemaForCreate.description) * [`QualitySchemaForCreate.template`](prefactor_http.md#prefactor_http.QualitySchemaForCreate.template) * [`QualitySchemaForCreate.data_risk`](prefactor_http.md#prefactor_http.QualitySchemaForCreate.data_risk) * [`QualitySchemaForCreate.data_risk`](prefactor_http.md#id72) * [`QualitySchemaForCreate.description`](prefactor_http.md#id73) * [`QualitySchemaForCreate.model_config`](prefactor_http.md#prefactor_http.QualitySchemaForCreate.model_config) * [`QualitySchemaForCreate.name`](prefactor_http.md#id74) * [`QualitySchemaForCreate.schema_`](prefactor_http.md#prefactor_http.QualitySchemaForCreate.schema_) * [`QualitySchemaForCreate.template`](prefactor_http.md#id75) * [`QualitySchemaForCreate.title`](prefactor_http.md#id76) * [`RuntimeEnvironment`](prefactor_http.md#prefactor_http.RuntimeEnvironment) * [`RuntimeEnvironment.agent_sdk`](prefactor_http.md#prefactor_http.RuntimeEnvironment.agent_sdk) * [`RuntimeEnvironment.os`](prefactor_http.md#prefactor_http.RuntimeEnvironment.os) * [`RuntimeEnvironment.prefactor_sdk`](prefactor_http.md#prefactor_http.RuntimeEnvironment.prefactor_sdk) * [`RuntimeEnvironment.runtime`](prefactor_http.md#prefactor_http.RuntimeEnvironment.runtime) * [`RuntimeEnvironment.agent_sdk`](prefactor_http.md#id77) * [`RuntimeEnvironment.model_config`](prefactor_http.md#prefactor_http.RuntimeEnvironment.model_config) * [`RuntimeEnvironment.os`](prefactor_http.md#id78) * [`RuntimeEnvironment.prefactor_sdk`](prefactor_http.md#id79) * [`RuntimeEnvironment.runtime`](prefactor_http.md#id80) * [`SpanTypeSchemaForCreate`](prefactor_http.md#prefactor_http.SpanTypeSchemaForCreate) * [`SpanTypeSchemaForCreate.name`](prefactor_http.md#prefactor_http.SpanTypeSchemaForCreate.name) * [`SpanTypeSchemaForCreate.params_schema`](prefactor_http.md#prefactor_http.SpanTypeSchemaForCreate.params_schema) * [`SpanTypeSchemaForCreate.result_schema`](prefactor_http.md#prefactor_http.SpanTypeSchemaForCreate.result_schema) * [`SpanTypeSchemaForCreate.title`](prefactor_http.md#prefactor_http.SpanTypeSchemaForCreate.title) * [`SpanTypeSchemaForCreate.description`](prefactor_http.md#prefactor_http.SpanTypeSchemaForCreate.description) * [`SpanTypeSchemaForCreate.template`](prefactor_http.md#prefactor_http.SpanTypeSchemaForCreate.template) * [`SpanTypeSchemaForCreate.data_risk`](prefactor_http.md#prefactor_http.SpanTypeSchemaForCreate.data_risk) * [`SpanTypeSchemaForCreate.data_risk`](prefactor_http.md#id81) * [`SpanTypeSchemaForCreate.description`](prefactor_http.md#id82) * [`SpanTypeSchemaForCreate.model_config`](prefactor_http.md#prefactor_http.SpanTypeSchemaForCreate.model_config) * [`SpanTypeSchemaForCreate.name`](prefactor_http.md#id83) * [`SpanTypeSchemaForCreate.params_schema`](prefactor_http.md#id84) * [`SpanTypeSchemaForCreate.result_schema`](prefactor_http.md#id85) * [`SpanTypeSchemaForCreate.template`](prefactor_http.md#id86) * [`SpanTypeSchemaForCreate.title`](prefactor_http.md#id87) * [Subpackages](prefactor_http.md#subpackages) * [prefactor\_http.endpoints package](prefactor_http.endpoints.md) * [`AgentClient`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentClient) * [`AgentInstanceClient`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentInstanceClient) * [`AgentSpanClient`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentSpanClient) * [`BulkClient`](prefactor_http.endpoints.md#prefactor_http.endpoints.BulkClient) * [Submodules](prefactor_http.endpoints.md#submodules) * [prefactor\_http.models package](prefactor_http.models.md) * [`ActionProfile`](prefactor_http.models.md#prefactor_http.models.ActionProfile) * [`Agent`](prefactor_http.models.md#prefactor_http.models.Agent) * [`AgentAvailableActions`](prefactor_http.models.md#prefactor_http.models.AgentAvailableActions) * [`AgentForCreate`](prefactor_http.models.md#prefactor_http.models.AgentForCreate) * [`AgentForUpdate`](prefactor_http.models.md#prefactor_http.models.AgentForUpdate) * [`AgentInstance`](prefactor_http.models.md#prefactor_http.models.AgentInstance) * [`AgentInstanceCounts`](prefactor_http.models.md#prefactor_http.models.AgentInstanceCounts) * [`AgentInstanceRecordQuality`](prefactor_http.models.md#prefactor_http.models.AgentInstanceRecordQuality) * [`AgentInstanceSpanCounts`](prefactor_http.models.md#prefactor_http.models.AgentInstanceSpanCounts) * [`AgentSchemaVersionForRegister`](prefactor_http.models.md#prefactor_http.models.AgentSchemaVersionForRegister) * [`AgentSpan`](prefactor_http.models.md#prefactor_http.models.AgentSpan) * [`AgentSummary`](prefactor_http.models.md#prefactor_http.models.AgentSummary) * [`AgentVersionForRegister`](prefactor_http.models.md#prefactor_http.models.AgentVersionForRegister) * [`ApiResponse`](prefactor_http.models.md#prefactor_http.models.ApiResponse) * [`BulkItem`](prefactor_http.models.md#prefactor_http.models.BulkItem) * [`BulkOutput`](prefactor_http.models.md#prefactor_http.models.BulkOutput) * [`BulkRequest`](prefactor_http.models.md#prefactor_http.models.BulkRequest) * [`BulkResponse`](prefactor_http.models.md#prefactor_http.models.BulkResponse) * [`DataCategories`](prefactor_http.models.md#prefactor_http.models.DataCategories) * [`DataRisk`](prefactor_http.models.md#prefactor_http.models.DataRisk) * [`FinishInstanceRequest`](prefactor_http.models.md#prefactor_http.models.FinishInstanceRequest) * [`QualitySchemaDetails`](prefactor_http.models.md#prefactor_http.models.QualitySchemaDetails) * [`QualitySchemaForCreate`](prefactor_http.models.md#prefactor_http.models.QualitySchemaForCreate) * [`RuntimeEnvironment`](prefactor_http.models.md#prefactor_http.models.RuntimeEnvironment) * [`SpanTypeSchemaForCreate`](prefactor_http.models.md#prefactor_http.models.SpanTypeSchemaForCreate) * [Submodules](prefactor_http.models.md#submodules) * [Submodules](prefactor_http.md#submodules) * [prefactor\_http.client module](prefactor_http.client.md) * [`PrefactorHttpClient`](prefactor_http.client.md#prefactor_http.client.PrefactorHttpClient) * [prefactor\_http.config module](prefactor_http.config.md) * [`HttpClientConfig`](prefactor_http.config.md#prefactor_http.config.HttpClientConfig) * [prefactor\_http.exceptions module](prefactor_http.exceptions.md) * [`PrefactorApiError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorApiError) * [`PrefactorAuthError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorAuthError) * [`PrefactorClientError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorClientError) * [`PrefactorHttpError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorHttpError) * [`PrefactorNotFoundError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorNotFoundError) * [`PrefactorResponseContractError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorResponseContractError) * [`PrefactorRetryExhaustedError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorRetryExhaustedError) * [`PrefactorValidationError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorValidationError) * [`is_permanent_http_error()`](prefactor_http.exceptions.md#prefactor_http.exceptions.is_permanent_http_error) * [`is_transient_http_error()`](prefactor_http.exceptions.md#prefactor_http.exceptions.is_transient_http_error) * [prefactor\_http.retry module](prefactor_http.retry.md) * [`RetryHandler`](prefactor_http.retry.md#prefactor_http.retry.RetryHandler) # prefactor_http package # prefactor\_http package [Section titled “prefactor\_http package”](#prefactor_http-package) Prefactor HTTP Client - Async HTTP client for Prefactor API. This package provides a high-level async HTTP client for interacting with the Prefactor API, including: * AgentInstance endpoints (register, start, finish) * AgentSpan endpoints (create, finish) * Bulk endpoints (execute multiple operations) * Automatic retry with exponential backoff * Comprehensive error handling * Type-safe data models ### Example [Section titled “Example”](#example) ```pycon >>> import asyncio >>> from prefactor_http import PrefactorHttpClient, HttpClientConfig >>> >>> async def main(): ... config = HttpClientConfig( ... api_url="https://app.prefactorai.com", ... api_token="your-token" ... ) ... async with PrefactorHttpClient(config) as client: ... instance = await client.agent_instances.register(...) ... print(instance) >>> >>> asyncio.run(main()) ``` ### *class* prefactor\_http.AgentInstance(, type: Literal\[‘agent\_instance’], id: str, account\_id: str, agent\_id: str, agent\_version\_id: str, environment\_id: str, agent\_deployment\_id: str, status: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’], inserted\_at: datetime, updated\_at: datetime, started\_at: datetime | None = None, finished\_at: datetime | None = None, termination\_reason: str | None = None, external\_identifier: str | None = None, span\_counts: [AgentInstanceSpanCounts](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceSpanCounts) | None = None, purpose: Literal\[‘live’, ‘smoke\_test’, ‘eval’] | None = None, quality\_payloads: dict\[str, dict] | None = None, quality\_summaries: dict\[str, str] | None = None) [Section titled “class prefactor\_http.AgentInstance(, type: Literal\[‘agent\_instance’\], id: str, account\_id: str, agent\_id: str, agent\_version\_id: str, environment\_id: str, agent\_deployment\_id: str, status: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\], inserted\_at: datetime, updated\_at: datetime, started\_at: datetime | None = None, finished\_at: datetime | None = None, termination\_reason: str | None = None, external\_identifier: str | None = None, span\_counts: AgentInstanceSpanCounts | None = None, purpose: Literal\[‘live’, ‘smoke\_test’, ‘eval’\] | None = None, quality\_payloads: dict\[str, dict\] | None = None, quality\_summaries: dict\[str, str\] | None = None)”](#class-prefactor_httpagentinstance-type-literalagent_instance-id-str-account_id-str-agent_id-str-agent_version_id-str-environment_id-str-agent_deployment_id-str-status-literalpending-active-complete-failed-cancelled-terminated-inserted_at-datetime-updated_at-datetime-started_at-datetime--none--none-finished_at-datetime--none--none-termination_reason-str--none--none-external_identifier-str--none--none-span_counts-agentinstancespancounts--none--none-purpose-literallive-smoke_test-eval--none--none-quality_payloads-dictstr-dict--none--none-quality_summaries-dictstr-str--none--none) Bases: `BaseModel` Agent instance model. #### type [Section titled “type”](#type) Resource type (always “agent\_instance”) * **Type:** Literal\[‘agent\_instance’] #### id [Section titled “id”](#id) Instance ID * **Type:** str #### account\_id [Section titled “account\_id”](#account_id) Account ID * **Type:** str #### agent\_id [Section titled “agent\_id”](#agent_id) Agent ID * **Type:** str #### agent\_version\_id [Section titled “agent\_version\_id”](#agent_version_id) Agent version ID * **Type:** str #### environment\_id [Section titled “environment\_id”](#environment_id) Environment ID * **Type:** str #### agent\_deployment\_id [Section titled “agent\_deployment\_id”](#agent_deployment_id) Agent deployment ID * **Type:** str #### status [Section titled “status”](#status) Instance status * **Type:** AgentStatus #### inserted\_at [Section titled “inserted\_at”](#inserted_at) When the instance was created * **Type:** datetime #### updated\_at [Section titled “updated\_at”](#updated_at) When the instance was last updated * **Type:** datetime #### started\_at [Section titled “started\_at”](#started_at) When the instance started (null if not started) * **Type:** datetime | None #### finished\_at [Section titled “finished\_at”](#finished_at) When the instance finished (null if not finished) * **Type:** datetime | None #### termination\_reason [Section titled “termination\_reason”](#termination_reason) Reason for termination (null if not terminated) * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier) Optional external identifier (unique per agent) * **Type:** str | None #### span\_counts [Section titled “span\_counts”](#span_counts) Span counts for this instance * **Type:** [AgentInstanceSpanCounts](#prefactor_http.AgentInstanceSpanCounts) | None #### purpose [Section titled “purpose”](#purpose) Why this instance ran (live, smoke\_test, eval) * **Type:** InstancePurpose | None #### quality\_payloads [Section titled “quality\_payloads”](#quality_payloads) Map of quality schema name to evaluation payload * **Type:** dict\[str, dict] | None #### quality\_summaries [Section titled “quality\_summaries”](#quality_summaries) Map of quality schema name to rendered summary * **Type:** dict\[str, str] | None #### account\_id *: str* [Section titled “account\_id : str”](#account_id--str) #### agent\_deployment\_id *: str* [Section titled “agent\_deployment\_id : str”](#agent_deployment_id--str) #### agent\_id *: str* [Section titled “agent\_id : str”](#agent_id--str) #### agent\_version\_id *: str* [Section titled “agent\_version\_id : str”](#agent_version_id--str) #### environment\_id *: str* [Section titled “environment\_id : str”](#environment_id--str) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none) #### finished\_at *: datetime | None* [Section titled “finished\_at : datetime | None”](#finished_at--datetime--none) #### id *: str* [Section titled “id : str”](#id--str) #### inserted\_at *: datetime* [Section titled “inserted\_at : datetime”](#inserted_at--datetime) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config--) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### purpose *: InstancePurpose | None* [Section titled “purpose : InstancePurpose | None”](#purpose--instancepurpose--none) #### quality\_payloads *: dict\[str, dict] | None* [Section titled “quality\_payloads : dict\[str, dict\] | None”](#quality_payloads--dictstr-dict--none) #### quality\_summaries *: dict\[str, str] | None* [Section titled “quality\_summaries : dict\[str, str\] | None”](#quality_summaries--dictstr-str--none) #### span\_counts *: [AgentInstanceSpanCounts](#prefactor_http.AgentInstanceSpanCounts) | None* [Section titled “span\_counts : AgentInstanceSpanCounts | None”](#span_counts--agentinstancespancounts--none) #### started\_at *: datetime | None* [Section titled “started\_at : datetime | None”](#started_at--datetime--none) #### status *: AgentStatus* [Section titled “status : AgentStatus”](#status--agentstatus) #### termination\_reason *: str | None* [Section titled “termination\_reason : str | None”](#termination_reason--str--none) #### type *: Literal\[‘agent\_instance’]* [Section titled “type : Literal\[‘agent\_instance’\]”](#type--literalagent_instance) #### updated\_at *: datetime* [Section titled “updated\_at : datetime”](#updated_at--datetime) ### *class* prefactor\_http.AgentInstanceRecordQuality(, name: str, payload: dict | None = None) [Section titled “class prefactor\_http.AgentInstanceRecordQuality(, name: str, payload: dict | None = None)”](#class-prefactor_httpagentinstancerecordquality-name-str-payload-dict--none--none) Bases: `BaseModel` Parameters for recording a quality payload on an agent instance. #### name [Section titled “name”](#name) Unique identifier of the quality schema entry to record against * **Type:** str #### payload [Section titled “payload”](#payload) Quality payload for this name, or None to remove the recorded payload for this name * **Type:** dict | None #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str) #### payload *: dict | None* [Section titled “payload : dict | None”](#payload--dict--none) ### *class* prefactor\_http.AgentInstanceSpanCounts(, total: int = 0, active: int = 0, complete: int = 0, failed: int = 0, cancelled: int = 0, finished: int = 0) [Section titled “class prefactor\_http.AgentInstanceSpanCounts(, total: int = 0, active: int = 0, complete: int = 0, failed: int = 0, cancelled: int = 0, finished: int = 0)”](#class-prefactor_httpagentinstancespancounts-total-int--0-active-int--0-complete-int--0-failed-int--0-cancelled-int--0-finished-int--0) Bases: `BaseModel` Span counts for an agent instance. #### total [Section titled “total”](#total) Total number of spans * **Type:** int #### active [Section titled “active”](#active) Number of active spans * **Type:** int #### complete [Section titled “complete”](#complete) Number of completed spans * **Type:** int #### failed [Section titled “failed”](#failed) Number of failed spans * **Type:** int #### cancelled [Section titled “cancelled”](#cancelled) Number of cancelled spans * **Type:** int #### finished [Section titled “finished”](#finished) Number of finished spans (complete + failed + cancelled) * **Type:** int #### active *: int* [Section titled “active : int”](#active--int) #### cancelled *: int* [Section titled “cancelled : int”](#cancelled--int) #### complete *: int* [Section titled “complete : int”](#complete--int) #### failed *: int* [Section titled “failed : int”](#failed--int) #### finished *: int* [Section titled “finished : int”](#finished--int) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---2) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### total *: int* [Section titled “total : int”](#total--int) ### *class* prefactor\_http.AgentSchemaVersionForRegister(, external\_identifier: str | None = None, span\_schemas: dict\[str, dict] | None = None, span\_result\_schemas: dict\[str, dict] | None = None, span\_type\_schemas: list\[[SpanTypeSchemaForCreate](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate)] | None = None, quality\_schemas: list\[[QualitySchemaForCreate](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaForCreate)] | None = None) [Section titled “class prefactor\_http.AgentSchemaVersionForRegister(, external\_identifier: str | None = None, span\_schemas: dict\[str, dict\] | None = None, span\_result\_schemas: dict\[str, dict\] | None = None, span\_type\_schemas: list\[SpanTypeSchemaForCreate\] | None = None, quality\_schemas: list\[QualitySchemaForCreate\] | None = None)”](#class-prefactor_httpagentschemaversionforregister-external_identifier-str--none--none-span_schemas-dictstr-dict--none--none-span_result_schemas-dictstr-dict--none--none-span_type_schemas-listspantypeschemaforcreate--none--none-quality_schemas-listqualityschemaforcreate--none--none) Bases: `BaseModel` Schema version information for registration. #### external\_identifier [Section titled “external\_identifier”](#external_identifier-1) External identifier for the schema version * **Type:** str | None #### span\_schemas [Section titled “span\_schemas”](#span_schemas) Map of span type names to JSON schemas * **Type:** dict\[str, dict] | None #### span\_result\_schemas [Section titled “span\_result\_schemas”](#span_result_schemas) Map of span type names to result JSON schemas * **Type:** dict\[str, dict] | None #### span\_type\_schemas [Section titled “span\_type\_schemas”](#span_type_schemas) List of span type schema details * **Type:** list\[[SpanTypeSchemaForCreate](#prefactor_http.SpanTypeSchemaForCreate)] | None #### quality\_schemas [Section titled “quality\_schemas”](#quality_schemas) Optional list of named quality schemas for instance evaluations * **Type:** list\[[QualitySchemaForCreate](#prefactor_http.QualitySchemaForCreate)] | None #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none-1) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---3) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### quality\_schemas *: list\[[QualitySchemaForCreate](#prefactor_http.QualitySchemaForCreate)] | None* [Section titled “quality\_schemas : list\[QualitySchemaForCreate\] | None”](#quality_schemas--listqualityschemaforcreate--none) #### span\_result\_schemas *: dict\[str, dict] | None* [Section titled “span\_result\_schemas : dict\[str, dict\] | None”](#span_result_schemas--dictstr-dict--none) #### span\_schemas *: dict\[str, dict] | None* [Section titled “span\_schemas : dict\[str, dict\] | None”](#span_schemas--dictstr-dict--none) #### span\_type\_schemas *: list\[[SpanTypeSchemaForCreate](#prefactor_http.SpanTypeSchemaForCreate)] | None* [Section titled “span\_type\_schemas : list\[SpanTypeSchemaForCreate\] | None”](#span_type_schemas--listspantypeschemaforcreate--none) ### *class* prefactor\_http.AgentSpan(\*, type: \~typing.Literal\[‘agent\_span’], id: str, account\_id: str | None = None, agent\_id: str | None = None, agent\_instance\_id: str, parent\_span\_id: str | None = None, schema\_name: str, schema\_title: str | None = None, status: \~typing.Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’], payload: dict = , result\_payload: dict | None = None, summary: str | None = None, started\_at: \~datetime.datetime | None = None, inserted\_at: \~datetime.datetime | None = None, updated\_at: \~datetime.datetime | None = None, finished\_at: \~datetime.datetime | None = None) [Section titled “class prefactor\_http.AgentSpan(\*, type: \~typing.Literal\[‘agent\_span’\], id: str, account\_id: str | None = None, agent\_id: str | None = None, agent\_instance\_id: str, parent\_span\_id: str | None = None, schema\_name: str, schema\_title: str | None = None, status: \~typing.Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\], payload: dict = , result\_payload: dict | None = None, summary: str | None = None, started\_at: \~datetime.datetime | None = None, inserted\_at: \~datetime.datetime | None = None, updated\_at: \~datetime.datetime | None = None, finished\_at: \~datetime.datetime | None = None)”](#class-prefactor_httpagentspan-type-typingliteralagent_span-id-str-account_id-str--none--none-agent_id-str--none--none-agent_instance_id-str-parent_span_id-str--none--none-schema_name-str-schema_title-str--none--none-status-typingliteralpending-active-complete-failed-cancelled-terminated-payload-dict---result_payload-dict--none--none-summary-str--none--none-started_at-datetimedatetime--none--none-inserted_at-datetimedatetime--none--none-updated_at-datetimedatetime--none--none-finished_at-datetimedatetime--none--none) Bases: `BaseModel` Agent span model. #### type [Section titled “type”](#type-1) Resource type (always “agent\_span”) * **Type:** Literal\[‘agent\_span’] #### id [Section titled “id”](#id-1) Span ID * **Type:** str #### account\_id [Section titled “account\_id”](#account_id-1) Account ID * **Type:** str | None #### agent\_id [Section titled “agent\_id”](#agent_id-1) Agent ID * **Type:** str | None #### agent\_instance\_id [Section titled “agent\_instance\_id”](#agent_instance_id) Agent instance ID * **Type:** str #### parent\_span\_id [Section titled “parent\_span\_id”](#parent_span_id) Parent span ID (None if root span) * **Type:** str | None #### schema\_name [Section titled “schema\_name”](#schema_name) Name of the schema for this span * **Type:** str #### schema\_title [Section titled “schema\_title”](#schema_title) Title of the schema for this span * **Type:** str | None #### status [Section titled “status”](#status-1) Span status * **Type:** Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’] #### payload [Section titled “payload”](#payload-1) Span payload data * **Type:** dict #### result\_payload [Section titled “result\_payload”](#result_payload) Result payload data * **Type:** dict | None #### summary [Section titled “summary”](#summary) Optional span summary * **Type:** str | None #### started\_at [Section titled “started\_at”](#started_at-1) When the span started * **Type:** datetime.datetime | None #### inserted\_at [Section titled “inserted\_at”](#inserted_at-1) When the span was created * **Type:** datetime.datetime | None #### updated\_at [Section titled “updated\_at”](#updated_at-1) When the span was last updated * **Type:** datetime.datetime | None #### finished\_at [Section titled “finished\_at”](#finished_at-1) When the span finished (None if in progress) * **Type:** datetime.datetime | None #### account\_id *: str | None* [Section titled “account\_id : str | None”](#account_id--str--none) #### agent\_id *: str | None* [Section titled “agent\_id : str | None”](#agent_id--str--none) #### agent\_instance\_id *: str* [Section titled “agent\_instance\_id : str”](#agent_instance_id--str) #### finished\_at *: datetime | None* [Section titled “finished\_at : datetime | None”](#finished_at--datetime--none-1) #### id *: str* [Section titled “id : str”](#id--str-1) #### inserted\_at *: datetime | None* [Section titled “inserted\_at : datetime | None”](#inserted_at--datetime--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---4) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### parent\_span\_id *: str | None* [Section titled “parent\_span\_id : str | None”](#parent_span_id--str--none) #### payload *: dict* [Section titled “payload : dict”](#payload--dict) #### result\_payload *: dict | None* [Section titled “result\_payload : dict | None”](#result_payload--dict--none) #### schema\_name *: str* [Section titled “schema\_name : str”](#schema_name--str) #### schema\_title *: str | None* [Section titled “schema\_title : str | None”](#schema_title--str--none) #### started\_at *: datetime | None* [Section titled “started\_at : datetime | None”](#started_at--datetime--none-1) #### status *: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’]* [Section titled “status : Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\]”](#status--literalpending-active-complete-failed-cancelled-terminated) #### summary *: str | None* [Section titled “summary : str | None”](#summary--str--none) #### type *: Literal\[‘agent\_span’]* [Section titled “type : Literal\[‘agent\_span’\]”](#type--literalagent_span) #### updated\_at *: datetime | None* [Section titled “updated\_at : datetime | None”](#updated_at--datetime--none) ### *class* prefactor\_http.AgentVersionForRegister(, name: str | None = None, external\_identifier: str | None = None, description: str | None = None, runtime\_environment: [RuntimeEnvironment](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RuntimeEnvironment) | None = None) [Section titled “class prefactor\_http.AgentVersionForRegister(, name: str | None = None, external\_identifier: str | None = None, description: str | None = None, runtime\_environment: RuntimeEnvironment | None = None)”](#class-prefactor_httpagentversionforregister-name-str--none--none-external_identifier-str--none--none-description-str--none--none-runtime_environment-runtimeenvironment--none--none) Bases: `BaseModel` Agent version information for registration. #### name [Section titled “name”](#name-1) Name of the agent version * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier-2) External identifier for the version (e.g., “v1.0.0”) * **Type:** str | None #### description [Section titled “description”](#description) Optional description of the version * **Type:** str | None #### runtime\_environment [Section titled “runtime\_environment”](#runtime_environment) Runtime environment metadata * **Type:** [RuntimeEnvironment](#prefactor_http.RuntimeEnvironment) | None #### description *: str | None* [Section titled “description : str | None”](#description--str--none) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none-2) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---5) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str | None* [Section titled “name : str | None”](#name--str--none) #### runtime\_environment *: [RuntimeEnvironment](#prefactor_http.RuntimeEnvironment) | None* [Section titled “runtime\_environment : RuntimeEnvironment | None”](#runtime_environment--runtimeenvironment--none) ### *class* prefactor\_http.ApiResponse(, status: str, details: T) [Section titled “class prefactor\_http.ApiResponse(, status: str, details: T)”](#class-prefactor_httpapiresponse-status-str-details-t) Bases: `BaseModel`, `Generic`\[`T`] Generic API response wrapper. #### status [Section titled “status”](#status-2) Response status (always “success” for successful requests) * **Type:** str #### details [Section titled “details”](#details) Detailed response data * **Type:** prefactor\_http.models.base.T #### details *: T* [Section titled “details : T”](#details--t) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---6) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### status *: str* [Section titled “status : str”](#status--str) ### *class* prefactor\_http.BulkItem(, \_type: str, idempotency\_key: Annotated\[str, MinLen(min\_length=8), MaxLen(max\_length=64)], \*\*extra\_data: Any) [Section titled “class prefactor\_http.BulkItem(, \_type: str, idempotency\_key: Annotated\[str, MinLen(min\_length=8), MaxLen(max\_length=64)\], \*\*extra\_data: Any)”](#class-prefactor_httpbulkitem-_type-str-idempotency_key-annotatedstr-minlenmin_length8-maxlenmax_length64-extra_data-any) Bases: `BaseModel` A single item in a bulk request. Each item must include \_type and idempotency\_key, plus any additional parameters required by the specific action type. #### idempotency\_key *: str* [Section titled “idempotency\_key : str”](#idempotency_key--str) Required unique idempotency key for this item. Must be at least 8 characters long and unique within the request. #### model\_config *= {‘extra’: ‘allow’}* [Section titled “model\_config = {‘extra’: ‘allow’}”](#model_config--extra-allow) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### type *: str* [Section titled “type : str”](#type--str) The type of query/action to execute (e.g., ‘agents/list’, ‘agents/create’). ### *class* prefactor\_http.BulkOutput(, status: str, \*\*extra\_data: Any) [Section titled “class prefactor\_http.BulkOutput(, status: str, \*\*extra\_data: Any)”](#class-prefactor_httpbulkoutput-status-str-extra_data-any) Bases: `BaseModel` Output from a query or action. Contains either a success response (with ‘status’: ‘success’ and operation-specific data) or an error response (with ‘status’: ‘error’, ‘code’, ‘message’, and optionally ‘errors’). #### model\_config *= {‘extra’: ‘allow’}* [Section titled “model\_config = {‘extra’: ‘allow’}”](#model_config--extra-allow-1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### status *: str* [Section titled “status : str”](#status--str-1) ‘success’ or ‘error’. * **Type:** Status of the operation #### *classmethod* validate\_status(v: str) → str [Section titled “classmethod validate\_status(v: str) → str”](#classmethod-validate_statusv-str--str) ### *class* prefactor\_http.BulkRequest(, items: Annotated\[list\[[BulkItem](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem)], MinLen(min\_length=1)]) [Section titled “class prefactor\_http.BulkRequest(, items: Annotated\[list\[BulkItem\], MinLen(min\_length=1)\])”](#class-prefactor_httpbulkrequest-items-annotatedlistbulkitem-minlenmin_length1) Bases: `BaseModel` Request body for bulk query/action operations. Allows executing multiple API operations in a single request. #### items *: list\[[BulkItem](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem)]* [Section titled “items : list\[BulkItem\]”](#items--listbulkitem) List of items to process in bulk. Each item will be processed independently in its own transaction. #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---7) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### *classmethod* validate\_unique\_idempotency\_keys(items: list\[[BulkItem](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem)]) → list\[[BulkItem](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem)] [Section titled “classmethod validate\_unique\_idempotency\_keys(items: list\[BulkItem\]) → list\[BulkItem\]”](#classmethod-validate_unique_idempotency_keysitems-listbulkitem--listbulkitem) Validate that all idempotency keys are unique within the request. ### *class* prefactor\_http.BulkResponse(, status: str = ‘success’, outputs: dict\[str, [BulkOutput](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkOutput)]) [Section titled “class prefactor\_http.BulkResponse(, status: str = ‘success’, outputs: dict\[str, BulkOutput\])”](#class-prefactor_httpbulkresponse-status-str--success-outputs-dictstr-bulkoutput) Bases: `BaseModel` Response from bulk query/action operations. Contains a map of results keyed by the idempotency\_key from each request item. #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---8) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### outputs *: dict\[str, [BulkOutput](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkOutput)]* [Section titled “outputs : dict\[str, BulkOutput\]”](#outputs--dictstr-bulkoutput) Map where keys are the idempotency\_key values from the request, and values are the corresponding query/action outputs or error responses. #### status *: str* [Section titled “status : str”](#status--str-2) Response status, always ‘success’ when the request is processed. ### *class* prefactor\_http.FinishInstanceRequest(, status: Literal\[‘complete’, ‘failed’, ‘cancelled’] | None = None, timestamp: str | None = None, idempotency\_key: str | None = None) [Section titled “class prefactor\_http.FinishInstanceRequest(, status: Literal\[‘complete’, ‘failed’, ‘cancelled’\] | None = None, timestamp: str | None = None, idempotency\_key: str | None = None)”](#class-prefactor_httpfinishinstancerequest-status-literalcomplete-failed-cancelled--none--none-timestamp-str--none--none-idempotency_key-str--none--none) Bases: `BaseModel` Request to finish an agent instance. #### status [Section titled “status”](#status-3) Optional finish status (complete, failed, cancelled) * **Type:** FinishStatus | None #### timestamp [Section titled “timestamp”](#timestamp) Optional ISO 8601 timestamp (defaults to current time) * **Type:** str | None #### idempotency\_key [Section titled “idempotency\_key”](#idempotency_key) Optional idempotency key * **Type:** str | None #### idempotency\_key *: str | None* [Section titled “idempotency\_key : str | None”](#idempotency_key--str--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---9) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### status *: FinishStatus | None* [Section titled “status : FinishStatus | None”](#status--finishstatus--none) #### timestamp *: str | None* [Section titled “timestamp : str | None”](#timestamp--str--none) ### *class* prefactor\_http.HttpClientConfig(api\_url: str, api\_token: str, request\_timeout: float = 30.0, connect\_timeout: float = 10.0, max\_retries: int = 3, initial\_retry\_delay: float = 1.0, max\_retry\_delay: float = 60.0, retry\_multiplier: float = 2.0, retry\_on\_status\_codes: tuple\[int, …] = (429, 500, 502, 503, 504), default\_idempotency\_key: str | None = None) [Section titled “class prefactor\_http.HttpClientConfig(api\_url: str, api\_token: str, request\_timeout: float = 30.0, connect\_timeout: float = 10.0, max\_retries: int = 3, initial\_retry\_delay: float = 1.0, max\_retry\_delay: float = 60.0, retry\_multiplier: float = 2.0, retry\_on\_status\_codes: tuple\[int, …\] = (429, 500, 502, 503, 504), default\_idempotency\_key: str | None = None)”](#class-prefactor_httphttpclientconfigapi_url-str-api_token-str-request_timeout-float--300-connect_timeout-float--100-max_retries-int--3-initial_retry_delay-float--10-max_retry_delay-float--600-retry_multiplier-float--20-retry_on_status_codes-tupleint---429-500-502-503-504-default_idempotency_key-str--none--none) Bases: `object` Configuration for the HTTP client. #### api\_url [Section titled “api\_url”](#api_url) Base URL for the Prefactor API. Example: ‘’ * **Type:** str #### api\_token [Section titled “api\_token”](#api_token) Bearer token for API authentication. * **Type:** str #### request\_timeout [Section titled “request\_timeout”](#request_timeout) Total timeout for requests in seconds (default: 30.0). * **Type:** float #### connect\_timeout [Section titled “connect\_timeout”](#connect_timeout) Connection timeout in seconds (default: 10.0). * **Type:** float #### max\_retries [Section titled “max\_retries”](#max_retries) Maximum number of retry attempts (default: 3). * **Type:** int #### initial\_retry\_delay [Section titled “initial\_retry\_delay”](#initial_retry_delay) Initial delay between retries in seconds (default: 1.0). * **Type:** float #### max\_retry\_delay [Section titled “max\_retry\_delay”](#max_retry_delay) Maximum delay between retries in seconds (default: 60.0). * **Type:** float #### retry\_multiplier [Section titled “retry\_multiplier”](#retry_multiplier) Multiplier for exponential backoff (default: 2.0). * **Type:** float #### retry\_on\_status\_codes [Section titled “retry\_on\_status\_codes”](#retry_on_status_codes) HTTP status codes to retry on (default: 429, 500, 502, 503, 504). * **Type:** tuple\[int, …] #### default\_idempotency\_key [Section titled “default\_idempotency\_key”](#default_idempotency_key) Optional default idempotency key prefix. * **Type:** str | None #### api\_token *: str* [Section titled “api\_token : str”](#api_token--str) #### api\_url *: str* [Section titled “api\_url : str”](#api_url--str) #### connect\_timeout *: float* *= 10.0* [Section titled “connect\_timeout : float = 10.0”](#connect_timeout--float--100) #### default\_idempotency\_key *: str | None* *= None* [Section titled “default\_idempotency\_key : str | None = None”](#default_idempotency_key--str--none--none) #### initial\_retry\_delay *: float* *= 1.0* [Section titled “initial\_retry\_delay : float = 1.0”](#initial_retry_delay--float--10) #### max\_retries *: int* *= 3* [Section titled “max\_retries : int = 3”](#max_retries--int--3) #### max\_retry\_delay *: float* *= 60.0* [Section titled “max\_retry\_delay : float = 60.0”](#max_retry_delay--float--600) #### request\_timeout *: float* *= 30.0* [Section titled “request\_timeout : float = 30.0”](#request_timeout--float--300) #### retry\_multiplier *: float* *= 2.0* [Section titled “retry\_multiplier : float = 2.0”](#retry_multiplier--float--20) #### retry\_on\_status\_codes *: tuple\[int, …]* *= (429, 500, 502, 503, 504)* [Section titled “retry\_on\_status\_codes : tuple\[int, …\] = (429, 500, 502, 503, 504)”](#retry_on_status_codes--tupleint---429-500-502-503-504) ### *exception* prefactor\_http.PrefactorApiError(message: str, code: str, status\_code: int) [Section titled “exception prefactor\_http.PrefactorApiError(message: str, code: str, status\_code: int)”](#exception-prefactor_httpprefactorapierrormessage-str-code-str-status_code-int) Bases: [`PrefactorHttpError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorHttpError) API returned an error response. #### message [Section titled “message”](#message) Human-readable error message #### code [Section titled “code”](#code) Error code from the API #### status\_code [Section titled “status\_code”](#status_code) HTTP status code ### *exception* prefactor\_http.PrefactorAuthError(message: str, code: str, status\_code: int) [Section titled “exception prefactor\_http.PrefactorAuthError(message: str, code: str, status\_code: int)”](#exception-prefactor_httpprefactorautherrormessage-str-code-str-status_code-int) Bases: [`PrefactorApiError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorApiError) Authentication/authorization errors (401, 403). ### *exception* prefactor\_http.PrefactorClientError [Section titled “exception prefactor\_http.PrefactorClientError”](#exception-prefactor_httpprefactorclienterror) Bases: [`PrefactorHttpError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorHttpError) Client-side error (not related to API). ### *class* prefactor\_http.PrefactorHttpClient(config: [HttpClientConfig](prefactor_http.config.md#prefactor_http.config.HttpClientConfig), sdk\_header: str | None = None) [Section titled “class prefactor\_http.PrefactorHttpClient(config: HttpClientConfig, sdk\_header: str | None = None)”](#class-prefactor_httpprefactorhttpclientconfig-httpclientconfig-sdk_header-str--none--none) Bases: `object` Main HTTP client for interacting with the Prefactor API. This client provides high-level methods for all API endpoints with built-in retry logic, error handling, and idempotency support. Usage: : async with PrefactorHttpClient(config) as client: : instance = await client.agent\_instances.register(…) span = await client.agent\_spans.create(…) #### *property* agent\_instances *: [AgentInstanceClient](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentInstanceClient)* [Section titled “property agent\_instances : AgentInstanceClient”](#property-agent_instances--agentinstanceclient) Access the agent instance endpoint client. Provides methods to interact with agent instances: * register: Create a new agent instance * start: Mark an instance as started * finish: Mark an instance as finished ### Example [Section titled “Example”](#example-1) instance = await client.agent\_instances.register(agent\_id, agent\_version) #### *property* agent\_spans *: [AgentSpanClient](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentSpanClient)* [Section titled “property agent\_spans : AgentSpanClient”](#property-agent_spans--agentspanclient) Access the agent span endpoint client. Provides methods to interact with agent spans: * create: Create a new agent span * finish: Mark a span as finished ### Example [Section titled “Example”](#example-2) span = await client.agent\_spans.create( : agent\_instance\_id, schema\_name, payload ) #### *property* agents *: [AgentClient](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentClient)* [Section titled “property agents : AgentClient”](#property-agents--agentclient) Access the agent endpoint client. Provides methods to manage agents: * create: Create a new agent * get: Fetch an agent by ID * update: Update an agent * list: List agents * show: Look up an agent by ID or external\_identifier * retire: Retire an agent * reinstate: Reinstate a retired agent * delete: Delete an agent ### Example [Section titled “Example”](#example-3) agent = await client.agents.create( : AgentForCreate(name=”My Agent”, external\_identifier=”ext-123”) ) #### *property* bulk *: [BulkClient](prefactor_http.endpoints.md#prefactor_http.endpoints.BulkClient)* [Section titled “property bulk : BulkClient”](#property-bulk--bulkclient) Access the bulk endpoint client. Provides methods to execute multiple queries/actions in a single request: * execute: Execute bulk operations ### Example [Section titled “Example”](#example-4) response = await client.bulk.execute(bulk\_request) #### *async* close() → None [Section titled “async close() → None”](#async-close--none) Close the HTTP session. #### *async* request(method: str, path: str, , params: dict\[str, Any] | None = None, json\_data: dict\[str, Any] | None = None, idempotency\_key: str | None = None) → dict\[str, Any] [Section titled “async request(method: str, path: str, , params: dict\[str, Any\] | None = None, json\_data: dict\[str, Any\] | None = None, idempotency\_key: str | None = None) → dict\[str, Any\]”](#async-requestmethod-str-path-str--params-dictstr-any--none--none-json_data-dictstr-any--none--none-idempotency_key-str--none--none--dictstr-any) Make an HTTP request with retry logic. This is the public request method that wraps the core request with retry handling. * **Parameters:** * **method** – HTTP method (GET, POST, PUT, DELETE). * **path** – API path. * **params** – Query parameters. * **json\_data** – JSON body data. * **idempotency\_key** – Optional idempotency key. * **Returns:** Parsed JSON response. * **Raises:** * [**PrefactorRetryExhaustedError**](#prefactor_http.PrefactorRetryExhaustedError) – When retries are exhausted. * [**PrefactorApiError**](#prefactor_http.PrefactorApiError) – On API errors. #### *async* validate\_token() → dict\[str, Any] [Section titled “async validate\_token() → dict\[str, Any\]”](#async-validate_token--dictstr-any) Validate the configured API token against the Prefactor ping endpoint. * **Returns:** Parsed JSON response from the ping endpoint. * **Raises:** [**PrefactorAuthError**](#prefactor_http.PrefactorAuthError) – When the token is invalid, expired, or unauthorized. ### *exception* prefactor\_http.PrefactorHttpError [Section titled “exception prefactor\_http.PrefactorHttpError”](#exception-prefactor_httpprefactorhttperror) Bases: `Exception` Base exception for all HTTP client errors. ### *exception* prefactor\_http.PrefactorNotFoundError(message: str, code: str, status\_code: int) [Section titled “exception prefactor\_http.PrefactorNotFoundError(message: str, code: str, status\_code: int)”](#exception-prefactor_httpprefactornotfounderrormessage-str-code-str-status_code-int) Bases: [`PrefactorApiError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorApiError) Resource not found (404). ### *exception* prefactor\_http.PrefactorResponseContractError(message: str, , status\_code: int | None = None, body\_snippet: str | None = None, cause: Exception | None = None) [Section titled “exception prefactor\_http.PrefactorResponseContractError(message: str, , status\_code: int | None = None, body\_snippet: str | None = None, cause: Exception | None = None)”](#exception-prefactor_httpprefactorresponsecontracterrormessage-str--status_code-int--none--none-body_snippet-str--none--none-cause-exception--none--none) Bases: [`PrefactorHttpError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorHttpError) Backend response violated the SDK’s expected response contract. ### *exception* prefactor\_http.PrefactorRetryExhaustedError(message: str, last\_error: Exception | None = None) [Section titled “exception prefactor\_http.PrefactorRetryExhaustedError(message: str, last\_error: Exception | None = None)”](#exception-prefactor_httpprefactorretryexhaustederrormessage-str-last_error-exception--none--none) Bases: [`PrefactorHttpError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorHttpError) All retry attempts exhausted. #### last\_error [Section titled “last\_error”](#last_error) The last exception that caused the retry to fail ### *exception* prefactor\_http.PrefactorValidationError(message: str, code: str, status\_code: int, errors: dict) [Section titled “exception prefactor\_http.PrefactorValidationError(message: str, code: str, status\_code: int, errors: dict)”](#exception-prefactor_httpprefactorvalidationerrormessage-str-code-str-status_code-int-errors-dict) Bases: [`PrefactorApiError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorApiError) Validation errors (400, 422). #### errors [Section titled “errors”](#errors) Detailed validation errors mapping field names to error messages ### *class* prefactor\_http.QualitySchemaDetails(, name: str, title: str, description: str | None = None, template: str | None = None, data\_risk: [DataRisk](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataRisk), schema: dict, schema\_validation: dict) [Section titled “class prefactor\_http.QualitySchemaDetails(, name: str, title: str, description: str | None = None, template: str | None = None, data\_risk: DataRisk, schema: dict, schema\_validation: dict)”](#class-prefactor_httpqualityschemadetails-name-str-title-str-description-str--none--none-template-str--none--none-data_risk-datarisk-schema-dict-schema_validation-dict) Bases: `BaseModel` Quality schema details returned in agent schema version responses. #### name [Section titled “name”](#name-2) Unique identifier for this quality schema entry * **Type:** str #### title [Section titled “title”](#title) Human-readable title * **Type:** str #### description [Section titled “description”](#description-1) Optional description * **Type:** str | None #### template [Section titled “template”](#template) Optional display template * **Type:** str | None #### data\_risk [Section titled “data\_risk”](#data_risk) Data risk classification * **Type:** [DataRisk](prefactor_http.models.md#prefactor_http.models.DataRisk) #### schema [Section titled “schema”](#schema) JSON schema for the quality payload #### schema\_validation [Section titled “schema\_validation”](#schema_validation) Schema validation result * **Type:** dict #### data\_risk *: [DataRisk](prefactor_http.models.md#prefactor_http.models.DataRisk)* [Section titled “data\_risk : DataRisk”](#data_risk--datarisk) #### description *: str | None* [Section titled “description : str | None”](#description--str--none-1) #### model\_config *= {‘populate\_by\_name’: True, ‘validate\_by\_alias’: True, ‘validate\_by\_name’: True}* [Section titled “model\_config = {‘populate\_by\_name’: True, ‘validate\_by\_alias’: True, ‘validate\_by\_name’: True}”](#model_config--populate_by_name-true-validate_by_alias-true-validate_by_name-true) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-1) #### schema\_ *: dict* [Section titled “schema\_ : dict”](#schema_--dict) #### schema\_validation *: dict* [Section titled “schema\_validation : dict”](#schema_validation--dict) #### template *: str | None* [Section titled “template : str | None”](#template--str--none) #### title *: str* [Section titled “title : str”](#title--str) ### *class* prefactor\_http.QualitySchemaForCreate(, name: str, schema: dict, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: [DataRisk](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataRisk) | None = None) [Section titled “class prefactor\_http.QualitySchemaForCreate(, name: str, schema: dict, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: DataRisk | None = None)”](#class-prefactor_httpqualityschemaforcreate-name-str-schema-dict-title-str--none--none-description-str--none--none-template-str--none--none-data_risk-datarisk--none--none) Bases: `BaseModel` Named quality schema definition for agent schema version registration. #### name [Section titled “name”](#name-3) Unique identifier for this quality schema entry * **Type:** str #### schema [Section titled “schema”](#schema-1) JSON schema for the quality payload #### title [Section titled “title”](#title-1) Optional human-readable title (defaults to name) * **Type:** str | None #### description [Section titled “description”](#description-2) Optional description * **Type:** str | None #### template [Section titled “template”](#template-1) Optional display template using `{{field}}` interpolation * **Type:** str | None #### data\_risk [Section titled “data\_risk”](#data_risk-1) Optional data risk classification * **Type:** [DataRisk](prefactor_http.models.md#prefactor_http.models.DataRisk) | None #### data\_risk *: [DataRisk](prefactor_http.models.md#prefactor_http.models.DataRisk) | None* [Section titled “data\_risk : DataRisk | None”](#data_risk--datarisk--none) #### description *: str | None* [Section titled “description : str | None”](#description--str--none-2) #### model\_config *= {‘populate\_by\_name’: True, ‘validate\_by\_alias’: True, ‘validate\_by\_name’: True}* [Section titled “model\_config = {‘populate\_by\_name’: True, ‘validate\_by\_alias’: True, ‘validate\_by\_name’: True}”](#model_config--populate_by_name-true-validate_by_alias-true-validate_by_name-true-1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-2) #### schema\_ *: dict* [Section titled “schema\_ : dict”](#schema_--dict-1) #### template *: str | None* [Section titled “template : str | None”](#template--str--none-1) #### title *: str | None* [Section titled “title : str | None”](#title--str--none) ### *class* prefactor\_http.RuntimeEnvironment(, agent\_sdk: list\[str] | None = None, os: str | None = None, prefactor\_sdk: list\[str] | None = None, runtime: str | None = None) [Section titled “class prefactor\_http.RuntimeEnvironment(, agent\_sdk: list\[str\] | None = None, os: str | None = None, prefactor\_sdk: list\[str\] | None = None, runtime: str | None = None)”](#class-prefactor_httpruntimeenvironment-agent_sdk-liststr--none--none-os-str--none--none-prefactor_sdk-liststr--none--none-runtime-str--none--none) Bases: `BaseModel` Runtime environment information for an agent version. Captures the agent framework, Prefactor SDK, OS, and language runtime in use when this agent version was registered. #### agent\_sdk [Section titled “agent\_sdk”](#agent_sdk) Agent framework packages (e.g. \[””]). * **Type:** list\[str] | None #### os [Section titled “os”](#os) Operating system name (e.g. “linux”, “darwin”). * **Type:** str | None #### prefactor\_sdk [Section titled “prefactor\_sdk”](#prefactor_sdk) Prefactor SDK packages in use. * **Type:** list\[str] | None #### runtime [Section titled “runtime”](#runtime) Language runtime (e.g. “”). * **Type:** str | None #### agent\_sdk *: list\[str] | None* [Section titled “agent\_sdk : list\[str\] | None”](#agent_sdk--liststr--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---10) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### os *: str | None* [Section titled “os : str | None”](#os--str--none) #### prefactor\_sdk *: list\[str] | None* [Section titled “prefactor\_sdk : list\[str\] | None”](#prefactor_sdk--liststr--none) #### runtime *: str | None* [Section titled “runtime : str | None”](#runtime--str--none) ### *class* prefactor\_http.SpanTypeSchemaForCreate(, name: str, params\_schema: dict, result\_schema: dict | None = None, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: [DataRisk](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataRisk) | None = None) [Section titled “class prefactor\_http.SpanTypeSchemaForCreate(, name: str, params\_schema: dict, result\_schema: dict | None = None, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: DataRisk | None = None)”](#class-prefactor_httpspantypeschemaforcreate-name-str-params_schema-dict-result_schema-dict--none--none-title-str--none--none-description-str--none--none-template-str--none--none-data_risk-datarisk--none--none) Bases: `BaseModel` Span type schema details for registration. #### name [Section titled “name”](#name-4) Name of the span type * **Type:** str #### params\_schema [Section titled “params\_schema”](#params_schema) JSON schema for span parameters * **Type:** dict #### result\_schema [Section titled “result\_schema”](#result_schema) Optional JSON schema for span results * **Type:** dict | None #### title [Section titled “title”](#title-2) Optional human-readable title * **Type:** str | None #### description [Section titled “description”](#description-3) Optional description * **Type:** str | None #### template [Section titled “template”](#template-2) Optional template string * **Type:** str | None #### data\_risk [Section titled “data\_risk”](#data_risk-2) Optional data risk classification * **Type:** [DataRisk](prefactor_http.models.md#prefactor_http.models.DataRisk) | None #### data\_risk *: [DataRisk](prefactor_http.models.md#prefactor_http.models.DataRisk) | None* [Section titled “data\_risk : DataRisk | None”](#data_risk--datarisk--none-1) #### description *: str | None* [Section titled “description : str | None”](#description--str--none-3) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---11) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-3) #### params\_schema *: dict* [Section titled “params\_schema : dict”](#params_schema--dict) #### result\_schema *: dict | None* [Section titled “result\_schema : dict | None”](#result_schema--dict--none) #### template *: str | None* [Section titled “template : str | None”](#template--str--none-2) #### title *: str | None* [Section titled “title : str | None”](#title--str--none-1) ## Subpackages [Section titled “Subpackages”](#subpackages) * [prefactor\_http.endpoints package](prefactor_http.endpoints.md) * [`AgentClient`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentClient) * [`AgentClient.create()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentClient.create) * [`AgentClient.delete()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentClient.delete) * [`AgentClient.get()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentClient.get) * [`AgentClient.list_agents()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentClient.list_agents) * [`AgentClient.reinstate()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentClient.reinstate) * [`AgentClient.retire()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentClient.retire) * [`AgentClient.show()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentClient.show) * [`AgentClient.update()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentClient.update) * [`AgentInstanceClient`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentInstanceClient) * [`AgentInstanceClient.finish()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentInstanceClient.finish) * [`AgentInstanceClient.get()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentInstanceClient.get) * [`AgentInstanceClient.record_quality()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentInstanceClient.record_quality) * [`AgentInstanceClient.register()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentInstanceClient.register) * [`AgentInstanceClient.start()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentInstanceClient.start) * [`AgentSpanClient`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentSpanClient) * [`AgentSpanClient.create()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentSpanClient.create) * [`AgentSpanClient.finish()`](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentSpanClient.finish) * [`BulkClient`](prefactor_http.endpoints.md#prefactor_http.endpoints.BulkClient) * [`BulkClient.execute()`](prefactor_http.endpoints.md#prefactor_http.endpoints.BulkClient.execute) * [Submodules](prefactor_http.endpoints.md#submodules) * [prefactor\_http.endpoints.agent module](prefactor_http.endpoints.agent.md) * [`AgentClient`](prefactor_http.endpoints.agent.md#prefactor_http.endpoints.agent.AgentClient) * [prefactor\_http.endpoints.agent\_instance module](prefactor_http.endpoints.agent_instance.md) * [`AgentInstanceClient`](prefactor_http.endpoints.agent_instance.md#prefactor_http.endpoints.agent_instance.AgentInstanceClient) * [prefactor\_http.endpoints.agent\_span module](prefactor_http.endpoints.agent_span.md) * [`AgentSpanClient`](prefactor_http.endpoints.agent_span.md#prefactor_http.endpoints.agent_span.AgentSpanClient) * [prefactor\_http.endpoints.bulk module](prefactor_http.endpoints.bulk.md) * [`BulkClient`](prefactor_http.endpoints.bulk.md#prefactor_http.endpoints.bulk.BulkClient) * [prefactor\_http.models package](prefactor_http.models.md) * [`ActionProfile`](prefactor_http.models.md#prefactor_http.models.ActionProfile) * [`ActionProfile.create_data`](prefactor_http.models.md#prefactor_http.models.ActionProfile.create_data) * [`ActionProfile.read_data`](prefactor_http.models.md#prefactor_http.models.ActionProfile.read_data) * [`ActionProfile.update_data`](prefactor_http.models.md#prefactor_http.models.ActionProfile.update_data) * [`ActionProfile.destroy_data`](prefactor_http.models.md#prefactor_http.models.ActionProfile.destroy_data) * [`ActionProfile.financial_transactions`](prefactor_http.models.md#prefactor_http.models.ActionProfile.financial_transactions) * [`ActionProfile.external_communication`](prefactor_http.models.md#prefactor_http.models.ActionProfile.external_communication) * [`ActionProfile.create_data`](prefactor_http.models.md#id0) * [`ActionProfile.destroy_data`](prefactor_http.models.md#id1) * [`ActionProfile.external_communication`](prefactor_http.models.md#id2) * [`ActionProfile.financial_transactions`](prefactor_http.models.md#id3) * [`ActionProfile.model_config`](prefactor_http.models.md#prefactor_http.models.ActionProfile.model_config) * [`ActionProfile.read_data`](prefactor_http.models.md#id4) * [`ActionProfile.update_data`](prefactor_http.models.md#id5) * [`Agent`](prefactor_http.models.md#prefactor_http.models.Agent) * [`Agent.type`](prefactor_http.models.md#prefactor_http.models.Agent.type) * [`Agent.id`](prefactor_http.models.md#prefactor_http.models.Agent.id) * [`Agent.name`](prefactor_http.models.md#prefactor_http.models.Agent.name) * [`Agent.description`](prefactor_http.models.md#prefactor_http.models.Agent.description) * [`Agent.external_identifier`](prefactor_http.models.md#prefactor_http.models.Agent.external_identifier) * [`Agent.status`](prefactor_http.models.md#prefactor_http.models.Agent.status) * [`Agent.owner_person_id`](prefactor_http.models.md#prefactor_http.models.Agent.owner_person_id) * [`Agent.risk_profile_id`](prefactor_http.models.md#prefactor_http.models.Agent.risk_profile_id) * [`Agent.team_id`](prefactor_http.models.md#prefactor_http.models.Agent.team_id) * [`Agent.instance_counts`](prefactor_http.models.md#prefactor_http.models.Agent.instance_counts) * [`Agent.available_actions`](prefactor_http.models.md#prefactor_http.models.Agent.available_actions) * [`Agent.inserted_at`](prefactor_http.models.md#prefactor_http.models.Agent.inserted_at) * [`Agent.updated_at`](prefactor_http.models.md#prefactor_http.models.Agent.updated_at) * [`Agent.available_actions`](prefactor_http.models.md#id6) * [`Agent.description`](prefactor_http.models.md#id7) * [`Agent.external_identifier`](prefactor_http.models.md#id8) * [`Agent.id`](prefactor_http.models.md#id9) * [`Agent.inserted_at`](prefactor_http.models.md#id10) * [`Agent.instance_counts`](prefactor_http.models.md#id11) * [`Agent.model_config`](prefactor_http.models.md#prefactor_http.models.Agent.model_config) * [`Agent.name`](prefactor_http.models.md#id12) * [`Agent.owner_person_id`](prefactor_http.models.md#id13) * [`Agent.risk_profile_id`](prefactor_http.models.md#id14) * [`Agent.status`](prefactor_http.models.md#id15) * [`Agent.team_id`](prefactor_http.models.md#id16) * [`Agent.type`](prefactor_http.models.md#id17) * [`Agent.updated_at`](prefactor_http.models.md#id18) * [`AgentAvailableActions`](prefactor_http.models.md#prefactor_http.models.AgentAvailableActions) * [`AgentAvailableActions.update`](prefactor_http.models.md#prefactor_http.models.AgentAvailableActions.update) * [`AgentAvailableActions.retire`](prefactor_http.models.md#prefactor_http.models.AgentAvailableActions.retire) * [`AgentAvailableActions.reinstate`](prefactor_http.models.md#prefactor_http.models.AgentAvailableActions.reinstate) * [`AgentAvailableActions.delete`](prefactor_http.models.md#prefactor_http.models.AgentAvailableActions.delete) * [`AgentAvailableActions.delete`](prefactor_http.models.md#id19) * [`AgentAvailableActions.model_config`](prefactor_http.models.md#prefactor_http.models.AgentAvailableActions.model_config) * [`AgentAvailableActions.reinstate`](prefactor_http.models.md#id20) * [`AgentAvailableActions.retire`](prefactor_http.models.md#id21) * [`AgentAvailableActions.update`](prefactor_http.models.md#id22) * [`AgentForCreate`](prefactor_http.models.md#prefactor_http.models.AgentForCreate) * [`AgentForCreate.name`](prefactor_http.models.md#prefactor_http.models.AgentForCreate.name) * [`AgentForCreate.description`](prefactor_http.models.md#prefactor_http.models.AgentForCreate.description) * [`AgentForCreate.external_identifier`](prefactor_http.models.md#prefactor_http.models.AgentForCreate.external_identifier) * [`AgentForCreate.id`](prefactor_http.models.md#prefactor_http.models.AgentForCreate.id) * [`AgentForCreate.owner_person_id`](prefactor_http.models.md#prefactor_http.models.AgentForCreate.owner_person_id) * [`AgentForCreate.risk_profile_id`](prefactor_http.models.md#prefactor_http.models.AgentForCreate.risk_profile_id) * [`AgentForCreate.team_id`](prefactor_http.models.md#prefactor_http.models.AgentForCreate.team_id) * [`AgentForCreate.description`](prefactor_http.models.md#id23) * [`AgentForCreate.external_identifier`](prefactor_http.models.md#id24) * [`AgentForCreate.id`](prefactor_http.models.md#id25) * [`AgentForCreate.model_config`](prefactor_http.models.md#prefactor_http.models.AgentForCreate.model_config) * [`AgentForCreate.name`](prefactor_http.models.md#id26) * [`AgentForCreate.owner_person_id`](prefactor_http.models.md#id27) * [`AgentForCreate.risk_profile_id`](prefactor_http.models.md#id28) * [`AgentForCreate.team_id`](prefactor_http.models.md#id29) * [`AgentForUpdate`](prefactor_http.models.md#prefactor_http.models.AgentForUpdate) * [`AgentForUpdate.name`](prefactor_http.models.md#prefactor_http.models.AgentForUpdate.name) * [`AgentForUpdate.description`](prefactor_http.models.md#prefactor_http.models.AgentForUpdate.description) * [`AgentForUpdate.owner_person_id`](prefactor_http.models.md#prefactor_http.models.AgentForUpdate.owner_person_id) * [`AgentForUpdate.risk_profile_id`](prefactor_http.models.md#prefactor_http.models.AgentForUpdate.risk_profile_id) * [`AgentForUpdate.team_id`](prefactor_http.models.md#prefactor_http.models.AgentForUpdate.team_id) * [`AgentForUpdate.description`](prefactor_http.models.md#id30) * [`AgentForUpdate.model_config`](prefactor_http.models.md#prefactor_http.models.AgentForUpdate.model_config) * [`AgentForUpdate.name`](prefactor_http.models.md#id31) * [`AgentForUpdate.owner_person_id`](prefactor_http.models.md#id32) * [`AgentForUpdate.risk_profile_id`](prefactor_http.models.md#id33) * [`AgentForUpdate.team_id`](prefactor_http.models.md#id34) * [`AgentInstance`](prefactor_http.models.md#prefactor_http.models.AgentInstance) * [`AgentInstance.type`](prefactor_http.models.md#prefactor_http.models.AgentInstance.type) * [`AgentInstance.id`](prefactor_http.models.md#prefactor_http.models.AgentInstance.id) * [`AgentInstance.account_id`](prefactor_http.models.md#prefactor_http.models.AgentInstance.account_id) * [`AgentInstance.agent_id`](prefactor_http.models.md#prefactor_http.models.AgentInstance.agent_id) * [`AgentInstance.agent_version_id`](prefactor_http.models.md#prefactor_http.models.AgentInstance.agent_version_id) * [`AgentInstance.environment_id`](prefactor_http.models.md#prefactor_http.models.AgentInstance.environment_id) * [`AgentInstance.agent_deployment_id`](prefactor_http.models.md#prefactor_http.models.AgentInstance.agent_deployment_id) * [`AgentInstance.status`](prefactor_http.models.md#prefactor_http.models.AgentInstance.status) * [`AgentInstance.inserted_at`](prefactor_http.models.md#prefactor_http.models.AgentInstance.inserted_at) * [`AgentInstance.updated_at`](prefactor_http.models.md#prefactor_http.models.AgentInstance.updated_at) * [`AgentInstance.started_at`](prefactor_http.models.md#prefactor_http.models.AgentInstance.started_at) * [`AgentInstance.finished_at`](prefactor_http.models.md#prefactor_http.models.AgentInstance.finished_at) * [`AgentInstance.termination_reason`](prefactor_http.models.md#prefactor_http.models.AgentInstance.termination_reason) * [`AgentInstance.external_identifier`](prefactor_http.models.md#prefactor_http.models.AgentInstance.external_identifier) * [`AgentInstance.span_counts`](prefactor_http.models.md#prefactor_http.models.AgentInstance.span_counts) * [`AgentInstance.purpose`](prefactor_http.models.md#prefactor_http.models.AgentInstance.purpose) * [`AgentInstance.quality_payloads`](prefactor_http.models.md#prefactor_http.models.AgentInstance.quality_payloads) * [`AgentInstance.quality_summaries`](prefactor_http.models.md#prefactor_http.models.AgentInstance.quality_summaries) * [`AgentInstance.account_id`](prefactor_http.models.md#id35) * [`AgentInstance.agent_deployment_id`](prefactor_http.models.md#id36) * [`AgentInstance.agent_id`](prefactor_http.models.md#id37) * [`AgentInstance.agent_version_id`](prefactor_http.models.md#id38) * [`AgentInstance.environment_id`](prefactor_http.models.md#id39) * [`AgentInstance.external_identifier`](prefactor_http.models.md#id40) * [`AgentInstance.finished_at`](prefactor_http.models.md#id41) * [`AgentInstance.id`](prefactor_http.models.md#id42) * [`AgentInstance.inserted_at`](prefactor_http.models.md#id43) * [`AgentInstance.model_config`](prefactor_http.models.md#prefactor_http.models.AgentInstance.model_config) * [`AgentInstance.purpose`](prefactor_http.models.md#id44) * [`AgentInstance.quality_payloads`](prefactor_http.models.md#id45) * [`AgentInstance.quality_summaries`](prefactor_http.models.md#id46) * [`AgentInstance.span_counts`](prefactor_http.models.md#id47) * [`AgentInstance.started_at`](prefactor_http.models.md#id48) * [`AgentInstance.status`](prefactor_http.models.md#id49) * [`AgentInstance.termination_reason`](prefactor_http.models.md#id50) * [`AgentInstance.type`](prefactor_http.models.md#id51) * [`AgentInstance.updated_at`](prefactor_http.models.md#id52) * [`AgentInstanceCounts`](prefactor_http.models.md#prefactor_http.models.AgentInstanceCounts) * [`AgentInstanceCounts.total`](prefactor_http.models.md#prefactor_http.models.AgentInstanceCounts.total) * [`AgentInstanceCounts.pending`](prefactor_http.models.md#prefactor_http.models.AgentInstanceCounts.pending) * [`AgentInstanceCounts.active`](prefactor_http.models.md#prefactor_http.models.AgentInstanceCounts.active) * [`AgentInstanceCounts.complete`](prefactor_http.models.md#prefactor_http.models.AgentInstanceCounts.complete) * [`AgentInstanceCounts.failed`](prefactor_http.models.md#prefactor_http.models.AgentInstanceCounts.failed) * [`AgentInstanceCounts.cancelled`](prefactor_http.models.md#prefactor_http.models.AgentInstanceCounts.cancelled) * [`AgentInstanceCounts.terminated`](prefactor_http.models.md#prefactor_http.models.AgentInstanceCounts.terminated) * [`AgentInstanceCounts.finished`](prefactor_http.models.md#prefactor_http.models.AgentInstanceCounts.finished) * [`AgentInstanceCounts.active`](prefactor_http.models.md#id53) * [`AgentInstanceCounts.cancelled`](prefactor_http.models.md#id54) * [`AgentInstanceCounts.complete`](prefactor_http.models.md#id55) * [`AgentInstanceCounts.failed`](prefactor_http.models.md#id56) * [`AgentInstanceCounts.finished`](prefactor_http.models.md#id57) * [`AgentInstanceCounts.model_config`](prefactor_http.models.md#prefactor_http.models.AgentInstanceCounts.model_config) * [`AgentInstanceCounts.pending`](prefactor_http.models.md#id58) * [`AgentInstanceCounts.terminated`](prefactor_http.models.md#id59) * [`AgentInstanceCounts.total`](prefactor_http.models.md#id60) * [`AgentInstanceRecordQuality`](prefactor_http.models.md#prefactor_http.models.AgentInstanceRecordQuality) * [`AgentInstanceRecordQuality.name`](prefactor_http.models.md#prefactor_http.models.AgentInstanceRecordQuality.name) * [`AgentInstanceRecordQuality.payload`](prefactor_http.models.md#prefactor_http.models.AgentInstanceRecordQuality.payload) * [`AgentInstanceRecordQuality.model_config`](prefactor_http.models.md#prefactor_http.models.AgentInstanceRecordQuality.model_config) * [`AgentInstanceRecordQuality.name`](prefactor_http.models.md#id61) * [`AgentInstanceRecordQuality.payload`](prefactor_http.models.md#id62) * [`AgentInstanceSpanCounts`](prefactor_http.models.md#prefactor_http.models.AgentInstanceSpanCounts) * [`AgentInstanceSpanCounts.total`](prefactor_http.models.md#prefactor_http.models.AgentInstanceSpanCounts.total) * [`AgentInstanceSpanCounts.active`](prefactor_http.models.md#prefactor_http.models.AgentInstanceSpanCounts.active) * [`AgentInstanceSpanCounts.complete`](prefactor_http.models.md#prefactor_http.models.AgentInstanceSpanCounts.complete) * [`AgentInstanceSpanCounts.failed`](prefactor_http.models.md#prefactor_http.models.AgentInstanceSpanCounts.failed) * [`AgentInstanceSpanCounts.cancelled`](prefactor_http.models.md#prefactor_http.models.AgentInstanceSpanCounts.cancelled) * [`AgentInstanceSpanCounts.finished`](prefactor_http.models.md#prefactor_http.models.AgentInstanceSpanCounts.finished) * [`AgentInstanceSpanCounts.active`](prefactor_http.models.md#id63) * [`AgentInstanceSpanCounts.cancelled`](prefactor_http.models.md#id64) * [`AgentInstanceSpanCounts.complete`](prefactor_http.models.md#id65) * [`AgentInstanceSpanCounts.failed`](prefactor_http.models.md#id66) * [`AgentInstanceSpanCounts.finished`](prefactor_http.models.md#id67) * [`AgentInstanceSpanCounts.model_config`](prefactor_http.models.md#prefactor_http.models.AgentInstanceSpanCounts.model_config) * [`AgentInstanceSpanCounts.total`](prefactor_http.models.md#id68) * [`AgentSchemaVersionForRegister`](prefactor_http.models.md#prefactor_http.models.AgentSchemaVersionForRegister) * [`AgentSchemaVersionForRegister.external_identifier`](prefactor_http.models.md#prefactor_http.models.AgentSchemaVersionForRegister.external_identifier) * [`AgentSchemaVersionForRegister.span_schemas`](prefactor_http.models.md#prefactor_http.models.AgentSchemaVersionForRegister.span_schemas) * [`AgentSchemaVersionForRegister.span_result_schemas`](prefactor_http.models.md#prefactor_http.models.AgentSchemaVersionForRegister.span_result_schemas) * [`AgentSchemaVersionForRegister.span_type_schemas`](prefactor_http.models.md#prefactor_http.models.AgentSchemaVersionForRegister.span_type_schemas) * [`AgentSchemaVersionForRegister.quality_schemas`](prefactor_http.models.md#prefactor_http.models.AgentSchemaVersionForRegister.quality_schemas) * [`AgentSchemaVersionForRegister.external_identifier`](prefactor_http.models.md#id69) * [`AgentSchemaVersionForRegister.model_config`](prefactor_http.models.md#prefactor_http.models.AgentSchemaVersionForRegister.model_config) * [`AgentSchemaVersionForRegister.quality_schemas`](prefactor_http.models.md#id70) * [`AgentSchemaVersionForRegister.span_result_schemas`](prefactor_http.models.md#id71) * [`AgentSchemaVersionForRegister.span_schemas`](prefactor_http.models.md#id72) * [`AgentSchemaVersionForRegister.span_type_schemas`](prefactor_http.models.md#id73) * [`AgentSpan`](prefactor_http.models.md#prefactor_http.models.AgentSpan) * [`AgentSpan.type`](prefactor_http.models.md#prefactor_http.models.AgentSpan.type) * [`AgentSpan.id`](prefactor_http.models.md#prefactor_http.models.AgentSpan.id) * [`AgentSpan.account_id`](prefactor_http.models.md#prefactor_http.models.AgentSpan.account_id) * [`AgentSpan.agent_id`](prefactor_http.models.md#prefactor_http.models.AgentSpan.agent_id) * [`AgentSpan.agent_instance_id`](prefactor_http.models.md#prefactor_http.models.AgentSpan.agent_instance_id) * [`AgentSpan.parent_span_id`](prefactor_http.models.md#prefactor_http.models.AgentSpan.parent_span_id) * [`AgentSpan.schema_name`](prefactor_http.models.md#prefactor_http.models.AgentSpan.schema_name) * [`AgentSpan.schema_title`](prefactor_http.models.md#prefactor_http.models.AgentSpan.schema_title) * [`AgentSpan.status`](prefactor_http.models.md#prefactor_http.models.AgentSpan.status) * [`AgentSpan.payload`](prefactor_http.models.md#prefactor_http.models.AgentSpan.payload) * [`AgentSpan.result_payload`](prefactor_http.models.md#prefactor_http.models.AgentSpan.result_payload) * [`AgentSpan.summary`](prefactor_http.models.md#prefactor_http.models.AgentSpan.summary) * [`AgentSpan.started_at`](prefactor_http.models.md#prefactor_http.models.AgentSpan.started_at) * [`AgentSpan.inserted_at`](prefactor_http.models.md#prefactor_http.models.AgentSpan.inserted_at) * [`AgentSpan.updated_at`](prefactor_http.models.md#prefactor_http.models.AgentSpan.updated_at) * [`AgentSpan.finished_at`](prefactor_http.models.md#prefactor_http.models.AgentSpan.finished_at) * [`AgentSpan.account_id`](prefactor_http.models.md#id74) * [`AgentSpan.agent_id`](prefactor_http.models.md#id75) * [`AgentSpan.agent_instance_id`](prefactor_http.models.md#id76) * [`AgentSpan.finished_at`](prefactor_http.models.md#id77) * [`AgentSpan.id`](prefactor_http.models.md#id78) * [`AgentSpan.inserted_at`](prefactor_http.models.md#id79) * [`AgentSpan.model_config`](prefactor_http.models.md#prefactor_http.models.AgentSpan.model_config) * [`AgentSpan.parent_span_id`](prefactor_http.models.md#id80) * [`AgentSpan.payload`](prefactor_http.models.md#id81) * [`AgentSpan.result_payload`](prefactor_http.models.md#id82) * [`AgentSpan.schema_name`](prefactor_http.models.md#id83) * [`AgentSpan.schema_title`](prefactor_http.models.md#id84) * [`AgentSpan.started_at`](prefactor_http.models.md#id85) * [`AgentSpan.status`](prefactor_http.models.md#id86) * [`AgentSpan.summary`](prefactor_http.models.md#id87) * [`AgentSpan.type`](prefactor_http.models.md#id88) * [`AgentSpan.updated_at`](prefactor_http.models.md#id89) * [`AgentSummary`](prefactor_http.models.md#prefactor_http.models.AgentSummary) * [`AgentSummary.type`](prefactor_http.models.md#prefactor_http.models.AgentSummary.type) * [`AgentSummary.id`](prefactor_http.models.md#prefactor_http.models.AgentSummary.id) * [`AgentSummary.name`](prefactor_http.models.md#prefactor_http.models.AgentSummary.name) * [`AgentSummary.description`](prefactor_http.models.md#prefactor_http.models.AgentSummary.description) * [`AgentSummary.external_identifier`](prefactor_http.models.md#prefactor_http.models.AgentSummary.external_identifier) * [`AgentSummary.status`](prefactor_http.models.md#prefactor_http.models.AgentSummary.status) * [`AgentSummary.owner_person_id`](prefactor_http.models.md#prefactor_http.models.AgentSummary.owner_person_id) * [`AgentSummary.team_id`](prefactor_http.models.md#prefactor_http.models.AgentSummary.team_id) * [`AgentSummary.available_actions`](prefactor_http.models.md#prefactor_http.models.AgentSummary.available_actions) * [`AgentSummary.inserted_at`](prefactor_http.models.md#prefactor_http.models.AgentSummary.inserted_at) * [`AgentSummary.updated_at`](prefactor_http.models.md#prefactor_http.models.AgentSummary.updated_at) * [`AgentSummary.available_actions`](prefactor_http.models.md#id90) * [`AgentSummary.description`](prefactor_http.models.md#id91) * [`AgentSummary.external_identifier`](prefactor_http.models.md#id92) * [`AgentSummary.id`](prefactor_http.models.md#id93) * [`AgentSummary.inserted_at`](prefactor_http.models.md#id94) * [`AgentSummary.model_config`](prefactor_http.models.md#prefactor_http.models.AgentSummary.model_config) * [`AgentSummary.name`](prefactor_http.models.md#id95) * [`AgentSummary.owner_person_id`](prefactor_http.models.md#id96) * [`AgentSummary.status`](prefactor_http.models.md#id97) * [`AgentSummary.team_id`](prefactor_http.models.md#id98) * [`AgentSummary.type`](prefactor_http.models.md#id99) * [`AgentSummary.updated_at`](prefactor_http.models.md#id100) * [`AgentVersionForRegister`](prefactor_http.models.md#prefactor_http.models.AgentVersionForRegister) * [`AgentVersionForRegister.name`](prefactor_http.models.md#prefactor_http.models.AgentVersionForRegister.name) * [`AgentVersionForRegister.external_identifier`](prefactor_http.models.md#prefactor_http.models.AgentVersionForRegister.external_identifier) * [`AgentVersionForRegister.description`](prefactor_http.models.md#prefactor_http.models.AgentVersionForRegister.description) * [`AgentVersionForRegister.runtime_environment`](prefactor_http.models.md#prefactor_http.models.AgentVersionForRegister.runtime_environment) * [`AgentVersionForRegister.description`](prefactor_http.models.md#id101) * [`AgentVersionForRegister.external_identifier`](prefactor_http.models.md#id102) * [`AgentVersionForRegister.model_config`](prefactor_http.models.md#prefactor_http.models.AgentVersionForRegister.model_config) * [`AgentVersionForRegister.name`](prefactor_http.models.md#id103) * [`AgentVersionForRegister.runtime_environment`](prefactor_http.models.md#id104) * [`ApiResponse`](prefactor_http.models.md#prefactor_http.models.ApiResponse) * [`ApiResponse.status`](prefactor_http.models.md#prefactor_http.models.ApiResponse.status) * [`ApiResponse.details`](prefactor_http.models.md#prefactor_http.models.ApiResponse.details) * [`ApiResponse.details`](prefactor_http.models.md#id105) * [`ApiResponse.model_config`](prefactor_http.models.md#prefactor_http.models.ApiResponse.model_config) * [`ApiResponse.status`](prefactor_http.models.md#id106) * [`BulkItem`](prefactor_http.models.md#prefactor_http.models.BulkItem) * [`BulkItem.idempotency_key`](prefactor_http.models.md#prefactor_http.models.BulkItem.idempotency_key) * [`BulkItem.model_config`](prefactor_http.models.md#prefactor_http.models.BulkItem.model_config) * [`BulkItem.type`](prefactor_http.models.md#prefactor_http.models.BulkItem.type) * [`BulkOutput`](prefactor_http.models.md#prefactor_http.models.BulkOutput) * [`BulkOutput.model_config`](prefactor_http.models.md#prefactor_http.models.BulkOutput.model_config) * [`BulkOutput.status`](prefactor_http.models.md#prefactor_http.models.BulkOutput.status) * [`BulkOutput.validate_status()`](prefactor_http.models.md#prefactor_http.models.BulkOutput.validate_status) * [`BulkRequest`](prefactor_http.models.md#prefactor_http.models.BulkRequest) * [`BulkRequest.items`](prefactor_http.models.md#prefactor_http.models.BulkRequest.items) * [`BulkRequest.model_config`](prefactor_http.models.md#prefactor_http.models.BulkRequest.model_config) * [`BulkRequest.validate_unique_idempotency_keys()`](prefactor_http.models.md#prefactor_http.models.BulkRequest.validate_unique_idempotency_keys) * [`BulkResponse`](prefactor_http.models.md#prefactor_http.models.BulkResponse) * [`BulkResponse.model_config`](prefactor_http.models.md#prefactor_http.models.BulkResponse.model_config) * [`BulkResponse.outputs`](prefactor_http.models.md#prefactor_http.models.BulkResponse.outputs) * [`BulkResponse.status`](prefactor_http.models.md#prefactor_http.models.BulkResponse.status) * [`DataCategories`](prefactor_http.models.md#prefactor_http.models.DataCategories) * [`DataCategories.personal_identifiers`](prefactor_http.models.md#prefactor_http.models.DataCategories.personal_identifiers) * [`DataCategories.contact_information`](prefactor_http.models.md#prefactor_http.models.DataCategories.contact_information) * [`DataCategories.financial_information`](prefactor_http.models.md#prefactor_http.models.DataCategories.financial_information) * [`DataCategories.health_and_medical`](prefactor_http.models.md#prefactor_http.models.DataCategories.health_and_medical) * [`DataCategories.criminal_justice`](prefactor_http.models.md#prefactor_http.models.DataCategories.criminal_justice) * [`DataCategories.authentication_and_secrets`](prefactor_http.models.md#prefactor_http.models.DataCategories.authentication_and_secrets) * [`DataCategories.organisational_confidential`](prefactor_http.models.md#prefactor_http.models.DataCategories.organisational_confidential) * [`DataCategories.minors_data`](prefactor_http.models.md#prefactor_http.models.DataCategories.minors_data) * [`DataCategories.location_and_tracking`](prefactor_http.models.md#prefactor_http.models.DataCategories.location_and_tracking) * [`DataCategories.behavioural_and_inferred`](prefactor_http.models.md#prefactor_http.models.DataCategories.behavioural_and_inferred) * [`DataCategories.gdpr_racial_or_ethnic_origin`](prefactor_http.models.md#prefactor_http.models.DataCategories.gdpr_racial_or_ethnic_origin) * [`DataCategories.gdpr_political_opinions`](prefactor_http.models.md#prefactor_http.models.DataCategories.gdpr_political_opinions) * [`DataCategories.gdpr_religious_or_philosophical_beliefs`](prefactor_http.models.md#prefactor_http.models.DataCategories.gdpr_religious_or_philosophical_beliefs) * [`DataCategories.gdpr_trade_union_membership`](prefactor_http.models.md#prefactor_http.models.DataCategories.gdpr_trade_union_membership) * [`DataCategories.gdpr_genetic_data`](prefactor_http.models.md#prefactor_http.models.DataCategories.gdpr_genetic_data) * [`DataCategories.gdpr_biometric_for_identification`](prefactor_http.models.md#prefactor_http.models.DataCategories.gdpr_biometric_for_identification) * [`DataCategories.gdpr_sex_life_or_sexual_orientation`](prefactor_http.models.md#prefactor_http.models.DataCategories.gdpr_sex_life_or_sexual_orientation) * [`DataCategories.classification`](prefactor_http.models.md#prefactor_http.models.DataCategories.classification) * [`DataCategories.authentication_and_secrets`](prefactor_http.models.md#id107) * [`DataCategories.behavioural_and_inferred`](prefactor_http.models.md#id108) * [`DataCategories.classification`](prefactor_http.models.md#id109) * [`DataCategories.contact_information`](prefactor_http.models.md#id110) * [`DataCategories.criminal_justice`](prefactor_http.models.md#id111) * [`DataCategories.financial_information`](prefactor_http.models.md#id112) * [`DataCategories.gdpr_biometric_for_identification`](prefactor_http.models.md#id113) * [`DataCategories.gdpr_genetic_data`](prefactor_http.models.md#id114) * [`DataCategories.gdpr_political_opinions`](prefactor_http.models.md#id115) * [`DataCategories.gdpr_racial_or_ethnic_origin`](prefactor_http.models.md#id116) * [`DataCategories.gdpr_religious_or_philosophical_beliefs`](prefactor_http.models.md#id117) * [`DataCategories.gdpr_sex_life_or_sexual_orientation`](prefactor_http.models.md#id118) * [`DataCategories.gdpr_trade_union_membership`](prefactor_http.models.md#id119) * [`DataCategories.health_and_medical`](prefactor_http.models.md#id120) * [`DataCategories.location_and_tracking`](prefactor_http.models.md#id121) * [`DataCategories.minors_data`](prefactor_http.models.md#id122) * [`DataCategories.model_config`](prefactor_http.models.md#prefactor_http.models.DataCategories.model_config) * [`DataCategories.organisational_confidential`](prefactor_http.models.md#id123) * [`DataCategories.personal_identifiers`](prefactor_http.models.md#id124) * [`DataRisk`](prefactor_http.models.md#prefactor_http.models.DataRisk) * [`DataRisk.action_profile`](prefactor_http.models.md#prefactor_http.models.DataRisk.action_profile) * [`DataRisk.params_data_categories`](prefactor_http.models.md#prefactor_http.models.DataRisk.params_data_categories) * [`DataRisk.result_data_categories`](prefactor_http.models.md#prefactor_http.models.DataRisk.result_data_categories) * [`DataRisk.action_profile`](prefactor_http.models.md#id125) * [`DataRisk.model_config`](prefactor_http.models.md#prefactor_http.models.DataRisk.model_config) * [`DataRisk.params_data_categories`](prefactor_http.models.md#id126) * [`DataRisk.result_data_categories`](prefactor_http.models.md#id127) * [`FinishInstanceRequest`](prefactor_http.models.md#prefactor_http.models.FinishInstanceRequest) * [`FinishInstanceRequest.status`](prefactor_http.models.md#prefactor_http.models.FinishInstanceRequest.status) * [`FinishInstanceRequest.timestamp`](prefactor_http.models.md#prefactor_http.models.FinishInstanceRequest.timestamp) * [`FinishInstanceRequest.idempotency_key`](prefactor_http.models.md#prefactor_http.models.FinishInstanceRequest.idempotency_key) * [`FinishInstanceRequest.idempotency_key`](prefactor_http.models.md#id128) * [`FinishInstanceRequest.model_config`](prefactor_http.models.md#prefactor_http.models.FinishInstanceRequest.model_config) * [`FinishInstanceRequest.status`](prefactor_http.models.md#id129) * [`FinishInstanceRequest.timestamp`](prefactor_http.models.md#id130) * [`QualitySchemaDetails`](prefactor_http.models.md#prefactor_http.models.QualitySchemaDetails) * [`QualitySchemaDetails.name`](prefactor_http.models.md#prefactor_http.models.QualitySchemaDetails.name) * [`QualitySchemaDetails.title`](prefactor_http.models.md#prefactor_http.models.QualitySchemaDetails.title) * [`QualitySchemaDetails.description`](prefactor_http.models.md#prefactor_http.models.QualitySchemaDetails.description) * [`QualitySchemaDetails.template`](prefactor_http.models.md#prefactor_http.models.QualitySchemaDetails.template) * [`QualitySchemaDetails.data_risk`](prefactor_http.models.md#prefactor_http.models.QualitySchemaDetails.data_risk) * [`QualitySchemaDetails.schema`](prefactor_http.models.md#prefactor_http.models.QualitySchemaDetails.schema) * [`QualitySchemaDetails.schema_validation`](prefactor_http.models.md#prefactor_http.models.QualitySchemaDetails.schema_validation) * [`QualitySchemaDetails.data_risk`](prefactor_http.models.md#id131) * [`QualitySchemaDetails.description`](prefactor_http.models.md#id132) * [`QualitySchemaDetails.model_config`](prefactor_http.models.md#prefactor_http.models.QualitySchemaDetails.model_config) * [`QualitySchemaDetails.name`](prefactor_http.models.md#id133) * [`QualitySchemaDetails.schema_`](prefactor_http.models.md#prefactor_http.models.QualitySchemaDetails.schema_) * [`QualitySchemaDetails.schema_validation`](prefactor_http.models.md#id134) * [`QualitySchemaDetails.template`](prefactor_http.models.md#id135) * [`QualitySchemaDetails.title`](prefactor_http.models.md#id136) * [`QualitySchemaForCreate`](prefactor_http.models.md#prefactor_http.models.QualitySchemaForCreate) * [`QualitySchemaForCreate.name`](prefactor_http.models.md#prefactor_http.models.QualitySchemaForCreate.name) * [`QualitySchemaForCreate.schema`](prefactor_http.models.md#prefactor_http.models.QualitySchemaForCreate.schema) * [`QualitySchemaForCreate.title`](prefactor_http.models.md#prefactor_http.models.QualitySchemaForCreate.title) * [`QualitySchemaForCreate.description`](prefactor_http.models.md#prefactor_http.models.QualitySchemaForCreate.description) * [`QualitySchemaForCreate.template`](prefactor_http.models.md#prefactor_http.models.QualitySchemaForCreate.template) * [`QualitySchemaForCreate.data_risk`](prefactor_http.models.md#prefactor_http.models.QualitySchemaForCreate.data_risk) * [`QualitySchemaForCreate.data_risk`](prefactor_http.models.md#id137) * [`QualitySchemaForCreate.description`](prefactor_http.models.md#id138) * [`QualitySchemaForCreate.model_config`](prefactor_http.models.md#prefactor_http.models.QualitySchemaForCreate.model_config) * [`QualitySchemaForCreate.name`](prefactor_http.models.md#id139) * [`QualitySchemaForCreate.schema_`](prefactor_http.models.md#prefactor_http.models.QualitySchemaForCreate.schema_) * [`QualitySchemaForCreate.template`](prefactor_http.models.md#id140) * [`QualitySchemaForCreate.title`](prefactor_http.models.md#id141) * [`RuntimeEnvironment`](prefactor_http.models.md#prefactor_http.models.RuntimeEnvironment) * [`RuntimeEnvironment.agent_sdk`](prefactor_http.models.md#prefactor_http.models.RuntimeEnvironment.agent_sdk) * [`RuntimeEnvironment.os`](prefactor_http.models.md#prefactor_http.models.RuntimeEnvironment.os) * [`RuntimeEnvironment.prefactor_sdk`](prefactor_http.models.md#prefactor_http.models.RuntimeEnvironment.prefactor_sdk) * [`RuntimeEnvironment.runtime`](prefactor_http.models.md#prefactor_http.models.RuntimeEnvironment.runtime) * [`RuntimeEnvironment.agent_sdk`](prefactor_http.models.md#id142) * [`RuntimeEnvironment.model_config`](prefactor_http.models.md#prefactor_http.models.RuntimeEnvironment.model_config) * [`RuntimeEnvironment.os`](prefactor_http.models.md#id143) * [`RuntimeEnvironment.prefactor_sdk`](prefactor_http.models.md#id144) * [`RuntimeEnvironment.runtime`](prefactor_http.models.md#id145) * [`SpanTypeSchemaForCreate`](prefactor_http.models.md#prefactor_http.models.SpanTypeSchemaForCreate) * [`SpanTypeSchemaForCreate.name`](prefactor_http.models.md#prefactor_http.models.SpanTypeSchemaForCreate.name) * [`SpanTypeSchemaForCreate.params_schema`](prefactor_http.models.md#prefactor_http.models.SpanTypeSchemaForCreate.params_schema) * [`SpanTypeSchemaForCreate.result_schema`](prefactor_http.models.md#prefactor_http.models.SpanTypeSchemaForCreate.result_schema) * [`SpanTypeSchemaForCreate.title`](prefactor_http.models.md#prefactor_http.models.SpanTypeSchemaForCreate.title) * [`SpanTypeSchemaForCreate.description`](prefactor_http.models.md#prefactor_http.models.SpanTypeSchemaForCreate.description) * [`SpanTypeSchemaForCreate.template`](prefactor_http.models.md#prefactor_http.models.SpanTypeSchemaForCreate.template) * [`SpanTypeSchemaForCreate.data_risk`](prefactor_http.models.md#prefactor_http.models.SpanTypeSchemaForCreate.data_risk) * [`SpanTypeSchemaForCreate.data_risk`](prefactor_http.models.md#id146) * [`SpanTypeSchemaForCreate.description`](prefactor_http.models.md#id147) * [`SpanTypeSchemaForCreate.model_config`](prefactor_http.models.md#prefactor_http.models.SpanTypeSchemaForCreate.model_config) * [`SpanTypeSchemaForCreate.name`](prefactor_http.models.md#id148) * [`SpanTypeSchemaForCreate.params_schema`](prefactor_http.models.md#id149) * [`SpanTypeSchemaForCreate.result_schema`](prefactor_http.models.md#id150) * [`SpanTypeSchemaForCreate.template`](prefactor_http.models.md#id151) * [`SpanTypeSchemaForCreate.title`](prefactor_http.models.md#id152) * [Submodules](prefactor_http.models.md#submodules) * [prefactor\_http.models.agent module](prefactor_http.models.agent.md) * [`Agent`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) * [`AgentAvailableActions`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentAvailableActions) * [`AgentForCreate`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForCreate) * [`AgentForUpdate`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForUpdate) * [`AgentInstanceCounts`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentInstanceCounts) * [`AgentSummary`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary) * [prefactor\_http.models.agent\_instance module](prefactor_http.models.agent_instance.md) * [`ActionProfile`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.ActionProfile) * [`AgentInstance`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance) * [`AgentInstanceRecordQuality`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceRecordQuality) * [`AgentInstanceSpanCounts`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceSpanCounts) * [`AgentSchemaVersionForRegister`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentSchemaVersionForRegister) * [`AgentVersionForRegister`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentVersionForRegister) * [`DataCategories`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories) * [`DataRisk`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataRisk) * [`FinishInstanceRequest`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.FinishInstanceRequest) * [`QualitySchemaDetails`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaDetails) * [`QualitySchemaForCreate`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaForCreate) * [`RegisterAgentInstanceRequest`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RegisterAgentInstanceRequest) * [`RuntimeEnvironment`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RuntimeEnvironment) * [`SpanTypeSchemaForCreate`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate) * [`TimestampRequest`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.TimestampRequest) * [prefactor\_http.models.agent\_span module](prefactor_http.models.agent_span.md) * [`AgentSpan`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan) * [`CreateAgentSpanRequest`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest) * [`FinishSpanRequest`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.FinishSpanRequest) * [prefactor\_http.models.base module](prefactor_http.models.base.md) * [`ApiError`](prefactor_http.models.base.md#prefactor_http.models.base.ApiError) * [`ApiResponse`](prefactor_http.models.base.md#prefactor_http.models.base.ApiResponse) * [`DetailedApiError`](prefactor_http.models.base.md#prefactor_http.models.base.DetailedApiError) * [`ListResponse`](prefactor_http.models.base.md#prefactor_http.models.base.ListResponse) * [`PaginationOutput`](prefactor_http.models.base.md#prefactor_http.models.base.PaginationOutput) * [`Sorting`](prefactor_http.models.base.md#prefactor_http.models.base.Sorting) * [prefactor\_http.models.bulk module](prefactor_http.models.bulk.md) * [`BulkItem`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem) * [`BulkOutput`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkOutput) * [`BulkRequest`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkRequest) * [`BulkResponse`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkResponse) * [prefactor\_http.models.types module](prefactor_http.models.types.md) ## Submodules [Section titled “Submodules”](#submodules) * [prefactor\_http.client module](prefactor_http.client.md) * [`PrefactorHttpClient`](prefactor_http.client.md#prefactor_http.client.PrefactorHttpClient) * [`PrefactorHttpClient.agent_instances`](prefactor_http.client.md#prefactor_http.client.PrefactorHttpClient.agent_instances) * [`PrefactorHttpClient.agent_spans`](prefactor_http.client.md#prefactor_http.client.PrefactorHttpClient.agent_spans) * [`PrefactorHttpClient.agents`](prefactor_http.client.md#prefactor_http.client.PrefactorHttpClient.agents) * [`PrefactorHttpClient.bulk`](prefactor_http.client.md#prefactor_http.client.PrefactorHttpClient.bulk) * [`PrefactorHttpClient.close()`](prefactor_http.client.md#prefactor_http.client.PrefactorHttpClient.close) * [`PrefactorHttpClient.request()`](prefactor_http.client.md#prefactor_http.client.PrefactorHttpClient.request) * [`PrefactorHttpClient.validate_token()`](prefactor_http.client.md#prefactor_http.client.PrefactorHttpClient.validate_token) * [prefactor\_http.config module](prefactor_http.config.md) * [`HttpClientConfig`](prefactor_http.config.md#prefactor_http.config.HttpClientConfig) * [`HttpClientConfig.api_url`](prefactor_http.config.md#prefactor_http.config.HttpClientConfig.api_url) * [`HttpClientConfig.api_token`](prefactor_http.config.md#prefactor_http.config.HttpClientConfig.api_token) * [`HttpClientConfig.request_timeout`](prefactor_http.config.md#prefactor_http.config.HttpClientConfig.request_timeout) * [`HttpClientConfig.connect_timeout`](prefactor_http.config.md#prefactor_http.config.HttpClientConfig.connect_timeout) * [`HttpClientConfig.max_retries`](prefactor_http.config.md#prefactor_http.config.HttpClientConfig.max_retries) * [`HttpClientConfig.initial_retry_delay`](prefactor_http.config.md#prefactor_http.config.HttpClientConfig.initial_retry_delay) * [`HttpClientConfig.max_retry_delay`](prefactor_http.config.md#prefactor_http.config.HttpClientConfig.max_retry_delay) * [`HttpClientConfig.retry_multiplier`](prefactor_http.config.md#prefactor_http.config.HttpClientConfig.retry_multiplier) * [`HttpClientConfig.retry_on_status_codes`](prefactor_http.config.md#prefactor_http.config.HttpClientConfig.retry_on_status_codes) * [`HttpClientConfig.default_idempotency_key`](prefactor_http.config.md#prefactor_http.config.HttpClientConfig.default_idempotency_key) * [`HttpClientConfig.api_token`](prefactor_http.config.md#id0) * [`HttpClientConfig.api_url`](prefactor_http.config.md#id1) * [`HttpClientConfig.connect_timeout`](prefactor_http.config.md#id2) * [`HttpClientConfig.default_idempotency_key`](prefactor_http.config.md#id3) * [`HttpClientConfig.initial_retry_delay`](prefactor_http.config.md#id4) * [`HttpClientConfig.max_retries`](prefactor_http.config.md#id5) * [`HttpClientConfig.max_retry_delay`](prefactor_http.config.md#id6) * [`HttpClientConfig.request_timeout`](prefactor_http.config.md#id7) * [`HttpClientConfig.retry_multiplier`](prefactor_http.config.md#id8) * [`HttpClientConfig.retry_on_status_codes`](prefactor_http.config.md#id9) * [prefactor\_http.exceptions module](prefactor_http.exceptions.md) * [`PrefactorApiError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorApiError) * [`PrefactorApiError.message`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorApiError.message) * [`PrefactorApiError.code`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorApiError.code) * [`PrefactorApiError.status_code`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorApiError.status_code) * [`PrefactorAuthError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorAuthError) * [`PrefactorClientError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorClientError) * [`PrefactorHttpError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorHttpError) * [`PrefactorNotFoundError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorNotFoundError) * [`PrefactorResponseContractError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorResponseContractError) * [`PrefactorRetryExhaustedError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorRetryExhaustedError) * [`PrefactorRetryExhaustedError.last_error`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorRetryExhaustedError.last_error) * [`PrefactorValidationError`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorValidationError) * [`PrefactorValidationError.errors`](prefactor_http.exceptions.md#prefactor_http.exceptions.PrefactorValidationError.errors) * [`is_permanent_http_error()`](prefactor_http.exceptions.md#prefactor_http.exceptions.is_permanent_http_error) * [`is_transient_http_error()`](prefactor_http.exceptions.md#prefactor_http.exceptions.is_transient_http_error) * [prefactor\_http.retry module](prefactor_http.retry.md) * [`RetryHandler`](prefactor_http.retry.md#prefactor_http.retry.RetryHandler) * [`RetryHandler.execute()`](prefactor_http.retry.md#prefactor_http.retry.RetryHandler.execute) # prefactor_http.client module # prefactor\_http.client module [Section titled “prefactor\_http.client module”](#prefactor_httpclient-module) HTTP client for Prefactor API. ### *class* prefactor\_http.client.PrefactorHttpClient(config: [HttpClientConfig](prefactor_http.config.md#prefactor_http.config.HttpClientConfig), sdk\_header: str | None = None) [Section titled “class prefactor\_http.client.PrefactorHttpClient(config: HttpClientConfig, sdk\_header: str | None = None)”](#class-prefactor_httpclientprefactorhttpclientconfig-httpclientconfig-sdk_header-str--none--none) Bases: `object` Main HTTP client for interacting with the Prefactor API. This client provides high-level methods for all API endpoints with built-in retry logic, error handling, and idempotency support. Usage: : async with PrefactorHttpClient(config) as client: : instance = await client.agent\_instances.register(…) span = await client.agent\_spans.create(…) #### *property* agent\_instances *: [AgentInstanceClient](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentInstanceClient)* [Section titled “property agent\_instances : AgentInstanceClient”](#property-agent_instances--agentinstanceclient) Access the agent instance endpoint client. Provides methods to interact with agent instances: * register: Create a new agent instance * start: Mark an instance as started * finish: Mark an instance as finished ### Example [Section titled “Example”](#example) instance = await client.agent\_instances.register(agent\_id, agent\_version) #### *property* agent\_spans *: [AgentSpanClient](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentSpanClient)* [Section titled “property agent\_spans : AgentSpanClient”](#property-agent_spans--agentspanclient) Access the agent span endpoint client. Provides methods to interact with agent spans: * create: Create a new agent span * finish: Mark a span as finished ### Example [Section titled “Example”](#example-1) span = await client.agent\_spans.create( : agent\_instance\_id, schema\_name, payload ) #### *property* agents *: [AgentClient](prefactor_http.endpoints.md#prefactor_http.endpoints.AgentClient)* [Section titled “property agents : AgentClient”](#property-agents--agentclient) Access the agent endpoint client. Provides methods to manage agents: * create: Create a new agent * get: Fetch an agent by ID * update: Update an agent * list: List agents * show: Look up an agent by ID or external\_identifier * retire: Retire an agent * reinstate: Reinstate a retired agent * delete: Delete an agent ### Example [Section titled “Example”](#example-2) agent = await client.agents.create( : AgentForCreate(name=”My Agent”, external\_identifier=”ext-123”) ) #### *property* bulk *: [BulkClient](prefactor_http.endpoints.md#prefactor_http.endpoints.BulkClient)* [Section titled “property bulk : BulkClient”](#property-bulk--bulkclient) Access the bulk endpoint client. Provides methods to execute multiple queries/actions in a single request: * execute: Execute bulk operations ### Example [Section titled “Example”](#example-3) response = await client.bulk.execute(bulk\_request) #### *async* close() → None [Section titled “async close() → None”](#async-close--none) Close the HTTP session. #### *async* request(method: str, path: str, , params: dict\[str, Any] | None = None, json\_data: dict\[str, Any] | None = None, idempotency\_key: str | None = None) → dict\[str, Any] [Section titled “async request(method: str, path: str, , params: dict\[str, Any\] | None = None, json\_data: dict\[str, Any\] | None = None, idempotency\_key: str | None = None) → dict\[str, Any\]”](#async-requestmethod-str-path-str--params-dictstr-any--none--none-json_data-dictstr-any--none--none-idempotency_key-str--none--none--dictstr-any) Make an HTTP request with retry logic. This is the public request method that wraps the core request with retry handling. * **Parameters:** * **method** – HTTP method (GET, POST, PUT, DELETE). * **path** – API path. * **params** – Query parameters. * **json\_data** – JSON body data. * **idempotency\_key** – Optional idempotency key. * **Returns:** Parsed JSON response. * **Raises:** * [**PrefactorRetryExhaustedError**](prefactor_http.md#prefactor_http.PrefactorRetryExhaustedError) – When retries are exhausted. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On API errors. #### *async* validate\_token() → dict\[str, Any] [Section titled “async validate\_token() → dict\[str, Any\]”](#async-validate_token--dictstr-any) Validate the configured API token against the Prefactor ping endpoint. * **Returns:** Parsed JSON response from the ping endpoint. * **Raises:** [**PrefactorAuthError**](prefactor_http.md#prefactor_http.PrefactorAuthError) – When the token is invalid, expired, or unauthorized. # prefactor_http.config module # prefactor\_http.config module [Section titled “prefactor\_http.config module”](#prefactor_httpconfig-module) Configuration for Prefactor HTTP Client. ### *class* prefactor\_http.config.HttpClientConfig(api\_url: str, api\_token: str, request\_timeout: float = 30.0, connect\_timeout: float = 10.0, max\_retries: int = 3, initial\_retry\_delay: float = 1.0, max\_retry\_delay: float = 60.0, retry\_multiplier: float = 2.0, retry\_on\_status\_codes: tuple\[int, …] = (429, 500, 502, 503, 504), default\_idempotency\_key: str | None = None) [Section titled “class prefactor\_http.config.HttpClientConfig(api\_url: str, api\_token: str, request\_timeout: float = 30.0, connect\_timeout: float = 10.0, max\_retries: int = 3, initial\_retry\_delay: float = 1.0, max\_retry\_delay: float = 60.0, retry\_multiplier: float = 2.0, retry\_on\_status\_codes: tuple\[int, …\] = (429, 500, 502, 503, 504), default\_idempotency\_key: str | None = None)”](#class-prefactor_httpconfighttpclientconfigapi_url-str-api_token-str-request_timeout-float--300-connect_timeout-float--100-max_retries-int--3-initial_retry_delay-float--10-max_retry_delay-float--600-retry_multiplier-float--20-retry_on_status_codes-tupleint---429-500-502-503-504-default_idempotency_key-str--none--none) Bases: `object` Configuration for the HTTP client. #### api\_url [Section titled “api\_url”](#api_url) Base URL for the Prefactor API. Example: ‘’ * **Type:** str #### api\_token [Section titled “api\_token”](#api_token) Bearer token for API authentication. * **Type:** str #### request\_timeout [Section titled “request\_timeout”](#request_timeout) Total timeout for requests in seconds (default: 30.0). * **Type:** float #### connect\_timeout [Section titled “connect\_timeout”](#connect_timeout) Connection timeout in seconds (default: 10.0). * **Type:** float #### max\_retries [Section titled “max\_retries”](#max_retries) Maximum number of retry attempts (default: 3). * **Type:** int #### initial\_retry\_delay [Section titled “initial\_retry\_delay”](#initial_retry_delay) Initial delay between retries in seconds (default: 1.0). * **Type:** float #### max\_retry\_delay [Section titled “max\_retry\_delay”](#max_retry_delay) Maximum delay between retries in seconds (default: 60.0). * **Type:** float #### retry\_multiplier [Section titled “retry\_multiplier”](#retry_multiplier) Multiplier for exponential backoff (default: 2.0). * **Type:** float #### retry\_on\_status\_codes [Section titled “retry\_on\_status\_codes”](#retry_on_status_codes) HTTP status codes to retry on (default: 429, 500, 502, 503, 504). * **Type:** tuple\[int, …] #### default\_idempotency\_key [Section titled “default\_idempotency\_key”](#default_idempotency_key) Optional default idempotency key prefix. * **Type:** str | None #### api\_token *: str* [Section titled “api\_token : str”](#api_token--str) #### api\_url *: str* [Section titled “api\_url : str”](#api_url--str) #### connect\_timeout *: float* *= 10.0* [Section titled “connect\_timeout : float = 10.0”](#connect_timeout--float--100) #### default\_idempotency\_key *: str | None* *= None* [Section titled “default\_idempotency\_key : str | None = None”](#default_idempotency_key--str--none--none) #### initial\_retry\_delay *: float* *= 1.0* [Section titled “initial\_retry\_delay : float = 1.0”](#initial_retry_delay--float--10) #### max\_retries *: int* *= 3* [Section titled “max\_retries : int = 3”](#max_retries--int--3) #### max\_retry\_delay *: float* *= 60.0* [Section titled “max\_retry\_delay : float = 60.0”](#max_retry_delay--float--600) #### request\_timeout *: float* *= 30.0* [Section titled “request\_timeout : float = 30.0”](#request_timeout--float--300) #### retry\_multiplier *: float* *= 2.0* [Section titled “retry\_multiplier : float = 2.0”](#retry_multiplier--float--20) #### retry\_on\_status\_codes *: tuple\[int, …]* *= (429, 500, 502, 503, 504)* [Section titled “retry\_on\_status\_codes : tuple\[int, …\] = (429, 500, 502, 503, 504)”](#retry_on_status_codes--tupleint---429-500-502-503-504) # prefactor_http.endpoints package # prefactor\_http.endpoints package [Section titled “prefactor\_http.endpoints package”](#prefactor_httpendpoints-package) Prefactor HTTP Client endpoints. ### *class* prefactor\_http.endpoints.AgentClient(http\_client: [PrefactorHttpClient](prefactor_http.md#prefactor_http.PrefactorHttpClient)) [Section titled “class prefactor\_http.endpoints.AgentClient(http\_client: PrefactorHttpClient)”](#class-prefactor_httpendpointsagentclienthttp_client-prefactorhttpclient) Bases: `object` Client for Agent endpoints. Provides methods to manage agents including: * create: Create a new agent * get: Fetch an agent by ID * update: Update an agent * list: List agents * show: Look up an agent by ID or external\_identifier * retire: Retire an agent * reinstate: Reinstate a retired agent * delete: Delete an agent #### *async* create(details: [AgentForCreate](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForCreate), idempotency\_key: str | None = None) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async create(details: AgentForCreate, idempotency\_key: str | None = None) → Agent”](#async-createdetails-agentforcreate-idempotency_key-str--none--none--agent) Create a new agent. POST /api/v1/agent * **Parameters:** * **details** – Agent creation parameters. * **idempotency\_key** – Optional idempotency key. * **Returns:** The created agent. * **Raises:** * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On API errors. * [**PrefactorValidationError**](prefactor_http.md#prefactor_http.PrefactorValidationError) – On validation errors. #### *async* delete(agent\_id: str, idempotency\_key: str | None = None) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async delete(agent\_id: str, idempotency\_key: str | None = None) → Agent”](#async-deleteagent_id-str-idempotency_key-str--none--none--agent) Delete an agent. DELETE /api/v1/agent/{agent\_id} * **Parameters:** * **agent\_id** – The agent ID to delete. * **idempotency\_key** – Optional idempotency key. * **Returns:** The deleted agent. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If agent not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* get(agent\_id: str) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async get(agent\_id: str) → Agent”](#async-getagent_id-str--agent) Fetch an agent by ID. GET /api/v1/agent/{agent\_id} * **Parameters:** **agent\_id** – The agent ID to fetch. * **Returns:** The agent. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If agent not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* list\_agents(risk\_profile\_id: str | None = None, team\_id: str | None = None, owner\_person\_id: str | None = None, sorting: str | None = None, offset: int | None = None, page\_size: int | None = None) → list\[[AgentSummary](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary)] [Section titled “async list\_agents(risk\_profile\_id: str | None = None, team\_id: str | None = None, owner\_person\_id: str | None = None, sorting: str | None = None, offset: int | None = None, page\_size: int | None = None) → list\[AgentSummary\]”](#async-list_agentsrisk_profile_id-str--none--none-team_id-str--none--none-owner_person_id-str--none--none-sorting-str--none--none-offset-int--none--none-page_size-int--none--none--listagentsummary) List agents. GET /api/v1/agent * **Parameters:** * **risk\_profile\_id** – Filter by risk profile (null for agents with none). * **team\_id** – Filter by team (null for agents with no team). * **owner\_person\_id** – Filter by owner (null for agents with no owner). * **sorting** – Sort order (e.g. `"name"` or `"-id"`). * **offset** – Zero-based offset for pagination. * **page\_size** – Number of items per page (1-100). * **Returns:** List of agent summaries. * **Raises:** [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On API errors. #### *async* reinstate(agent\_id: str, idempotency\_key: str | None = None) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async reinstate(agent\_id: str, idempotency\_key: str | None = None) → Agent”](#async-reinstateagent_id-str-idempotency_key-str--none--none--agent) Reinstate a retired agent. POST /api/v1/agent/{agent\_id}/reinstate * **Parameters:** * **agent\_id** – The agent ID to reinstate. * **idempotency\_key** – Optional idempotency key. * **Returns:** The updated agent. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If agent not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* retire(agent\_id: str, idempotency\_key: str | None = None) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async retire(agent\_id: str, idempotency\_key: str | None = None) → Agent”](#async-retireagent_id-str-idempotency_key-str--none--none--agent) Retire an agent. POST /api/v1/agent/{agent\_id}/retire * **Parameters:** * **agent\_id** – The agent ID to retire. * **idempotency\_key** – Optional idempotency key. * **Returns:** The updated agent. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If agent not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* show(, agent\_id: str | None = None, external\_identifier: str | None = None, environment\_id: str | None = None, include\_counts: bool = False, include\_risk\_rollup: bool = False) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async show(, agent\_id: str | None = None, external\_identifier: str | None = None, environment\_id: str | None = None, include\_counts: bool = False, include\_risk\_rollup: bool = False) → Agent”](#async-show-agent_id-str--none--none-external_identifier-str--none--none-environment_id-str--none--none-include_counts-bool--false-include_risk_rollup-bool--false--agent) Look up an agent by ID or external\_identifier. GET /api/v1/agent/show Provide exactly one of `agent_id` or `external_identifier`. * **Parameters:** * **agent\_id** – Agent ID to look up. * **external\_identifier** – External identifier to look up (exact match). * **environment\_id** – Optional environment to scope risk rollup and counts. * **include\_counts** – Include instance counts in the response. * **include\_risk\_rollup** – Include risk rollup in the response. * **Returns:** The agent. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If agent not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* update(agent\_id: str, details: [AgentForUpdate](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForUpdate), idempotency\_key: str | None = None) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async update(agent\_id: str, details: AgentForUpdate, idempotency\_key: str | None = None) → Agent”](#async-updateagent_id-str-details-agentforupdate-idempotency_key-str--none--none--agent) Update an agent. PUT /api/v1/agent/{agent\_id} * **Parameters:** * **agent\_id** – The agent ID to update. * **details** – Fields to update (only provided fields are changed). * **idempotency\_key** – Optional idempotency key. * **Returns:** The updated agent. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If agent not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. ### *class* prefactor\_http.endpoints.AgentInstanceClient(http\_client: [PrefactorHttpClient](prefactor_http.md#prefactor_http.PrefactorHttpClient)) [Section titled “class prefactor\_http.endpoints.AgentInstanceClient(http\_client: PrefactorHttpClient)”](#class-prefactor_httpendpointsagentinstanceclienthttp_client-prefactorhttpclient) Bases: `object` Client for AgentInstance POST endpoints. Provides methods to interact with agent instances including: * register: Create a new agent instance * start: Mark an instance as started * finish: Mark an instance as finished #### *async* finish(agent\_instance\_id: str, status: Literal\[‘complete’, ‘failed’, ‘cancelled’] | None = None, timestamp: datetime | None = None, idempotency\_key: str | None = None) → [AgentInstance](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance) [Section titled “async finish(agent\_instance\_id: str, status: Literal\[‘complete’, ‘failed’, ‘cancelled’\] | None = None, timestamp: datetime | None = None, idempotency\_key: str | None = None) → AgentInstance”](#async-finishagent_instance_id-str-status-literalcomplete-failed-cancelled--none--none-timestamp-datetime--none--none-idempotency_key-str--none--none--agentinstance) Mark an agent instance as finished. POST /api/v1/agent\_instance/{agent\_instance\_id}/finish * **Parameters:** * **agent\_instance\_id** – The instance ID * **status** – Optional finish status (complete, failed, cancelled) * **timestamp** – Optional finish time (defaults to now) * **idempotency\_key** – Optional idempotency key * **Returns:** The updated agent instance * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If instance not found * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors #### *async* get(agent\_instance\_id: str) → [AgentInstance](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance) [Section titled “async get(agent\_instance\_id: str) → AgentInstance”](#async-getagent_instance_id-str--agentinstance) Fetch an agent instance by ID. GET /api/v1/agent\_instance/{agent\_instance\_id} * **Parameters:** **agent\_instance\_id** – The instance ID to fetch. * **Returns:** The agent instance. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If instance not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* record\_quality(agent\_instance\_id: str, name: str, payload: dict | None = None, idempotency\_key: str | None = None) → [AgentInstance](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance) [Section titled “async record\_quality(agent\_instance\_id: str, name: str, payload: dict | None = None, idempotency\_key: str | None = None) → AgentInstance”](#async-record_qualityagent_instance_id-str-name-str-payload-dict--none--none-idempotency_key-str--none--none--agentinstance) Record a quality payload on an agent instance. POST /api/v1/agent\_instance/{agent\_instance\_id}/record\_quality Sets or clears one named quality payload. A null `payload` removes that name from the stored map. Other names are left unchanged. * **Parameters:** * **agent\_instance\_id** – The instance ID. * **name** – Quality schema name (key in the agent schema version quality\_schemas). * **payload** – Quality payload for this name, or None to remove the recorded payload for this name. * **idempotency\_key** – Optional idempotency key. * **Returns:** The updated agent instance. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If instance not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* register(agent\_version: dict, agent\_schema\_version: dict, agent\_id: str | None = None, environment\_id: str | None = None, id: str | None = None, idempotency\_key: str | None = None, update\_current\_version: bool = True, purpose: Literal\[‘live’, ‘smoke\_test’, ‘eval’] | None = None, external\_identifier: str | None = None) → [AgentInstance](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance) [Section titled “async register(agent\_version: dict, agent\_schema\_version: dict, agent\_id: str | None = None, environment\_id: str | None = None, id: str | None = None, idempotency\_key: str | None = None, update\_current\_version: bool = True, purpose: Literal\[‘live’, ‘smoke\_test’, ‘eval’\] | None = None, external\_identifier: str | None = None) → AgentInstance”](#async-registeragent_version-dict-agent_schema_version-dict-agent_id-str--none--none-environment_id-str--none--none-id-str--none--none-idempotency_key-str--none--none-update_current_version-bool--true-purpose-literallive-smoke_test-eval--none--none-external_identifier-str--none--none--agentinstance) Register a new agent instance. POST /api/v1/agent\_instance/register * **Parameters:** * **agent\_id** – Agent ID. Omit when using a deployment-scoped token. * **agent\_version** – Version info dict with name, external\_identifier, description * **agent\_schema\_version** – Schema version dict with external\_identifier and span type definitions (span\_type\_schemas, span\_schemas, and/or span\_result\_schemas) * **environment\_id** – Environment to deploy into. Required when using an account-scoped token; omit when using a deployment-scoped token * **id** – Optional custom ID for the instance * **external\_identifier** – Optional external identifier for this agent instance in an external system (unique per agent) * **idempotency\_key** – Optional idempotency key * **update\_current\_version** – Whether to update the deployment’s pinned version (defaults to True) * **purpose** – Why this instance ran — `"live"`, `"smoke_test"`, or `"eval"`. Omitted (None) lets the API default to `"live"`. * **Returns:** The created agent instance * **Raises:** * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On API errors * [**PrefactorValidationError**](prefactor_http.md#prefactor_http.PrefactorValidationError) – On validation errors #### *async* start(agent\_instance\_id: str, timestamp: datetime | None = None, idempotency\_key: str | None = None) → [AgentInstance](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance) [Section titled “async start(agent\_instance\_id: str, timestamp: datetime | None = None, idempotency\_key: str | None = None) → AgentInstance”](#async-startagent_instance_id-str-timestamp-datetime--none--none-idempotency_key-str--none--none--agentinstance) Mark an agent instance as started. POST /api/v1/agent\_instance/{agent\_instance\_id}/start * **Parameters:** * **agent\_instance\_id** – The instance ID * **timestamp** – Optional start time (defaults to now) * **idempotency\_key** – Optional idempotency key * **Returns:** The updated agent instance * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If instance not found * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors ### *class* prefactor\_http.endpoints.AgentSpanClient(http\_client: [PrefactorHttpClient](prefactor_http.md#prefactor_http.PrefactorHttpClient)) [Section titled “class prefactor\_http.endpoints.AgentSpanClient(http\_client: PrefactorHttpClient)”](#class-prefactor_httpendpointsagentspanclienthttp_client-prefactorhttpclient) Bases: `object` Client for AgentSpan POST endpoints. Provides methods to interact with agent spans including: * create: Create a new agent span * finish: Mark a span as finished #### *async* create(agent\_instance\_id: str, schema\_name: str, status: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’], payload: dict | None = None, result\_payload: dict | None = None, id: str | None = None, parent\_span\_id: str | None = None, started\_at: datetime | None = None, finished\_at: datetime | None = None, idempotency\_key: str | None = None, control\_signal\_callback: Callable\[\[str | None], None] | None = None) → [AgentSpan](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan) [Section titled “async create(agent\_instance\_id: str, schema\_name: str, status: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\], payload: dict | None = None, result\_payload: dict | None = None, id: str | None = None, parent\_span\_id: str | None = None, started\_at: datetime | None = None, finished\_at: datetime | None = None, idempotency\_key: str | None = None, control\_signal\_callback: Callable\[\[str | None\], None\] | None = None) → AgentSpan”](#async-createagent_instance_id-str-schema_name-str-status-literalpending-active-complete-failed-cancelled-terminated-payload-dict--none--none-result_payload-dict--none--none-id-str--none--none-parent_span_id-str--none--none-started_at-datetime--none--none-finished_at-datetime--none--none-idempotency_key-str--none--none-control_signal_callback-callablestr--none-none--none--none--agentspan) Create a new agent span. POST /api/v1/agent\_spans * **Parameters:** * **agent\_instance\_id** – ID of the agent instance this span belongs to * **schema\_name** – Name of the schema for this span * **status** – Status for the span * **payload** – Optional span payload data * **result\_payload** – Optional result payload data * **id** – Optional custom ID for the span * **parent\_span\_id** – Optional parent span ID * **started\_at** – Optional start time * **finished\_at** – Optional finish time * **idempotency\_key** – Optional idempotency key * **Returns:** The created agent span * **Raises:** * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On API errors * [**PrefactorValidationError**](prefactor_http.md#prefactor_http.PrefactorValidationError) – On validation errors #### *async* finish(agent\_span\_id: str, status: Literal\[‘complete’, ‘failed’, ‘cancelled’] | None = None, result\_payload: dict | None = None, timestamp: datetime | None = None, idempotency\_key: str | None = None, control\_signal\_callback: Callable\[\[str | None], None] | None = None) → [AgentSpan](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan) [Section titled “async finish(agent\_span\_id: str, status: Literal\[‘complete’, ‘failed’, ‘cancelled’\] | None = None, result\_payload: dict | None = None, timestamp: datetime | None = None, idempotency\_key: str | None = None, control\_signal\_callback: Callable\[\[str | None\], None\] | None = None) → AgentSpan”](#async-finishagent_span_id-str-status-literalcomplete-failed-cancelled--none--none-result_payload-dict--none--none-timestamp-datetime--none--none-idempotency_key-str--none--none-control_signal_callback-callablestr--none-none--none--none--agentspan) Finish an agent span. POST /api/v1/agent\_spans/{agent\_span\_id}/finish * **Parameters:** * **agent\_span\_id** – The span ID * **status** – Optional finish status (complete, failed, cancelled) * **result\_payload** – Optional result payload data * **timestamp** – Optional finish time (defaults to now) * **idempotency\_key** – Optional idempotency key * **Returns:** The updated agent span * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If span not found * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors ### *class* prefactor\_http.endpoints.BulkClient(http\_client: [PrefactorHttpClient](prefactor_http.md#prefactor_http.PrefactorHttpClient)) [Section titled “class prefactor\_http.endpoints.BulkClient(http\_client: PrefactorHttpClient)”](#class-prefactor_httpendpointsbulkclienthttp_client-prefactorhttpclient) Bases: `object` Client for bulk action operations. Execute multiple POST actions in a single HTTP request. This endpoint allows you to batch multiple operations together, reducing the number of round trips to the API. Key Features: : - Each item in the request is processed independently in its own database transaction * Processing stops early if any item returns an error * All successfully processed items up to the error are returned * Any unprocessed items (after the first error) are excluded from the result * All items must include a unique idempotency\_key (minimum 8 characters) * Results are returned as a map keyed by idempotency\_key ### Example [Section titled “Example”](#example) ```plaintext `` ``` ```plaintext ` ``` python request = BulkRequest( > items=\[ : BulkItem( # type: ignore\[call-arg] : \_type=”agent\_instances/register”, idempotency\_key=”register-instance-001”, agent\_id=”agent\_123”, agent\_version={“name”: “My Agent”, “external\_identifier”: “v1.0.0”}, agent\_schema\_version={\ > \> “external\_identifier”: “v1.0.0”, > “span\_type\_schemas”: \[\ > \> > { > > : “name”: “agent:llm”, > > “title”: “LLM Call”, > > “params\_schema”: { > >\ > \> > > “type”: “object”, > > > “properties”: { > >\ > \> > > > “model”: {“type”: “string”}, > > > > “prompt”: {“type”: “string”}, > >\ > \> > > }, > > > “required”: \[“model”, “prompt”], > >\ > \> > }, > > “result\_schema”: { > >\ > \> > > “type”: “object”, > > > “properties”: { > >\ > \> > > > “response”: {“type”: “string”}, > >\ > \> > > }, > >\ > \> > },\ > \> > },\ > \> ],\ > },\ > ), BulkItem( # type: ignore\[call-arg] > > > \_type=”agent\_spans/create”, idempotency\_key=”create-span-001”, agent\_instance\_id=”instance\_123”, schema\_name=”agent:llm”, status=”active”, > > > > > > ), > ] ) response = await client.bulk.execute(request) print(response.outputs\[“create-span-001”].status) ```plaintext `` ``` ```plaintext ` ``` #### *async* execute(request: [BulkRequest](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkRequest)) → [BulkResponse](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkResponse) [Section titled “async execute(request: BulkRequest) → BulkResponse”](#async-executerequest-bulkrequest--bulkresponse) Execute multiple queries/actions in a single request. * **Parameters:** **request** – The bulk request containing items to process. * **Returns:** BulkResponse with outputs keyed by idempotency\_key. * **Raises:** * [**PrefactorValidationError**](prefactor_http.md#prefactor_http.PrefactorValidationError) – If the request is invalid. * [**PrefactorRetryExhaustedError**](prefactor_http.md#prefactor_http.PrefactorRetryExhaustedError) – If the request fails after all retries. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – If the API returns an error response. ## Submodules [Section titled “Submodules”](#submodules) * [prefactor\_http.endpoints.agent module](prefactor_http.endpoints.agent.md) * [`AgentClient`](prefactor_http.endpoints.agent.md#prefactor_http.endpoints.agent.AgentClient) * [`AgentClient.create()`](prefactor_http.endpoints.agent.md#prefactor_http.endpoints.agent.AgentClient.create) * [`AgentClient.delete()`](prefactor_http.endpoints.agent.md#prefactor_http.endpoints.agent.AgentClient.delete) * [`AgentClient.get()`](prefactor_http.endpoints.agent.md#prefactor_http.endpoints.agent.AgentClient.get) * [`AgentClient.list_agents()`](prefactor_http.endpoints.agent.md#prefactor_http.endpoints.agent.AgentClient.list_agents) * [`AgentClient.reinstate()`](prefactor_http.endpoints.agent.md#prefactor_http.endpoints.agent.AgentClient.reinstate) * [`AgentClient.retire()`](prefactor_http.endpoints.agent.md#prefactor_http.endpoints.agent.AgentClient.retire) * [`AgentClient.show()`](prefactor_http.endpoints.agent.md#prefactor_http.endpoints.agent.AgentClient.show) * [`AgentClient.update()`](prefactor_http.endpoints.agent.md#prefactor_http.endpoints.agent.AgentClient.update) * [prefactor\_http.endpoints.agent\_instance module](prefactor_http.endpoints.agent_instance.md) * [`AgentInstanceClient`](prefactor_http.endpoints.agent_instance.md#prefactor_http.endpoints.agent_instance.AgentInstanceClient) * [`AgentInstanceClient.finish()`](prefactor_http.endpoints.agent_instance.md#prefactor_http.endpoints.agent_instance.AgentInstanceClient.finish) * [`AgentInstanceClient.get()`](prefactor_http.endpoints.agent_instance.md#prefactor_http.endpoints.agent_instance.AgentInstanceClient.get) * [`AgentInstanceClient.record_quality()`](prefactor_http.endpoints.agent_instance.md#prefactor_http.endpoints.agent_instance.AgentInstanceClient.record_quality) * [`AgentInstanceClient.register()`](prefactor_http.endpoints.agent_instance.md#prefactor_http.endpoints.agent_instance.AgentInstanceClient.register) * [`AgentInstanceClient.start()`](prefactor_http.endpoints.agent_instance.md#prefactor_http.endpoints.agent_instance.AgentInstanceClient.start) * [prefactor\_http.endpoints.agent\_span module](prefactor_http.endpoints.agent_span.md) * [`AgentSpanClient`](prefactor_http.endpoints.agent_span.md#prefactor_http.endpoints.agent_span.AgentSpanClient) * [`AgentSpanClient.create()`](prefactor_http.endpoints.agent_span.md#prefactor_http.endpoints.agent_span.AgentSpanClient.create) * [`AgentSpanClient.finish()`](prefactor_http.endpoints.agent_span.md#prefactor_http.endpoints.agent_span.AgentSpanClient.finish) * [prefactor\_http.endpoints.bulk module](prefactor_http.endpoints.bulk.md) * [`BulkClient`](prefactor_http.endpoints.bulk.md#prefactor_http.endpoints.bulk.BulkClient) * [`BulkClient.execute()`](prefactor_http.endpoints.bulk.md#prefactor_http.endpoints.bulk.BulkClient.execute) # prefactor_http.endpoints.agent module # prefactor\_http.endpoints.agent module [Section titled “prefactor\_http.endpoints.agent module”](#prefactor_httpendpointsagent-module) Agent endpoint client. ### *class* prefactor\_http.endpoints.agent.AgentClient(http\_client: [PrefactorHttpClient](prefactor_http.md#prefactor_http.PrefactorHttpClient)) [Section titled “class prefactor\_http.endpoints.agent.AgentClient(http\_client: PrefactorHttpClient)”](#class-prefactor_httpendpointsagentagentclienthttp_client-prefactorhttpclient) Bases: `object` Client for Agent endpoints. Provides methods to manage agents including: * create: Create a new agent * get: Fetch an agent by ID * update: Update an agent * list: List agents * show: Look up an agent by ID or external\_identifier * retire: Retire an agent * reinstate: Reinstate a retired agent * delete: Delete an agent #### *async* create(details: [AgentForCreate](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForCreate), idempotency\_key: str | None = None) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async create(details: AgentForCreate, idempotency\_key: str | None = None) → Agent”](#async-createdetails-agentforcreate-idempotency_key-str--none--none--agent) Create a new agent. POST /api/v1/agent * **Parameters:** * **details** – Agent creation parameters. * **idempotency\_key** – Optional idempotency key. * **Returns:** The created agent. * **Raises:** * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On API errors. * [**PrefactorValidationError**](prefactor_http.md#prefactor_http.PrefactorValidationError) – On validation errors. #### *async* delete(agent\_id: str, idempotency\_key: str | None = None) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async delete(agent\_id: str, idempotency\_key: str | None = None) → Agent”](#async-deleteagent_id-str-idempotency_key-str--none--none--agent) Delete an agent. DELETE /api/v1/agent/{agent\_id} * **Parameters:** * **agent\_id** – The agent ID to delete. * **idempotency\_key** – Optional idempotency key. * **Returns:** The deleted agent. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If agent not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* get(agent\_id: str) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async get(agent\_id: str) → Agent”](#async-getagent_id-str--agent) Fetch an agent by ID. GET /api/v1/agent/{agent\_id} * **Parameters:** **agent\_id** – The agent ID to fetch. * **Returns:** The agent. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If agent not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* list\_agents(risk\_profile\_id: str | None = None, team\_id: str | None = None, owner\_person\_id: str | None = None, sorting: str | None = None, offset: int | None = None, page\_size: int | None = None) → list\[[AgentSummary](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary)] [Section titled “async list\_agents(risk\_profile\_id: str | None = None, team\_id: str | None = None, owner\_person\_id: str | None = None, sorting: str | None = None, offset: int | None = None, page\_size: int | None = None) → list\[AgentSummary\]”](#async-list_agentsrisk_profile_id-str--none--none-team_id-str--none--none-owner_person_id-str--none--none-sorting-str--none--none-offset-int--none--none-page_size-int--none--none--listagentsummary) List agents. GET /api/v1/agent * **Parameters:** * **risk\_profile\_id** – Filter by risk profile (null for agents with none). * **team\_id** – Filter by team (null for agents with no team). * **owner\_person\_id** – Filter by owner (null for agents with no owner). * **sorting** – Sort order (e.g. `"name"` or `"-id"`). * **offset** – Zero-based offset for pagination. * **page\_size** – Number of items per page (1-100). * **Returns:** List of agent summaries. * **Raises:** [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On API errors. #### *async* reinstate(agent\_id: str, idempotency\_key: str | None = None) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async reinstate(agent\_id: str, idempotency\_key: str | None = None) → Agent”](#async-reinstateagent_id-str-idempotency_key-str--none--none--agent) Reinstate a retired agent. POST /api/v1/agent/{agent\_id}/reinstate * **Parameters:** * **agent\_id** – The agent ID to reinstate. * **idempotency\_key** – Optional idempotency key. * **Returns:** The updated agent. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If agent not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* retire(agent\_id: str, idempotency\_key: str | None = None) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async retire(agent\_id: str, idempotency\_key: str | None = None) → Agent”](#async-retireagent_id-str-idempotency_key-str--none--none--agent) Retire an agent. POST /api/v1/agent/{agent\_id}/retire * **Parameters:** * **agent\_id** – The agent ID to retire. * **idempotency\_key** – Optional idempotency key. * **Returns:** The updated agent. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If agent not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* show(, agent\_id: str | None = None, external\_identifier: str | None = None, environment\_id: str | None = None, include\_counts: bool = False, include\_risk\_rollup: bool = False) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async show(, agent\_id: str | None = None, external\_identifier: str | None = None, environment\_id: str | None = None, include\_counts: bool = False, include\_risk\_rollup: bool = False) → Agent”](#async-show-agent_id-str--none--none-external_identifier-str--none--none-environment_id-str--none--none-include_counts-bool--false-include_risk_rollup-bool--false--agent) Look up an agent by ID or external\_identifier. GET /api/v1/agent/show Provide exactly one of `agent_id` or `external_identifier`. * **Parameters:** * **agent\_id** – Agent ID to look up. * **external\_identifier** – External identifier to look up (exact match). * **environment\_id** – Optional environment to scope risk rollup and counts. * **include\_counts** – Include instance counts in the response. * **include\_risk\_rollup** – Include risk rollup in the response. * **Returns:** The agent. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If agent not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* update(agent\_id: str, details: [AgentForUpdate](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForUpdate), idempotency\_key: str | None = None) → [Agent](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) [Section titled “async update(agent\_id: str, details: AgentForUpdate, idempotency\_key: str | None = None) → Agent”](#async-updateagent_id-str-details-agentforupdate-idempotency_key-str--none--none--agent) Update an agent. PUT /api/v1/agent/{agent\_id} * **Parameters:** * **agent\_id** – The agent ID to update. * **details** – Fields to update (only provided fields are changed). * **idempotency\_key** – Optional idempotency key. * **Returns:** The updated agent. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If agent not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. # prefactor_http.endpoints.agent_instance module # prefactor\_http.endpoints.agent\_instance module [Section titled “prefactor\_http.endpoints.agent\_instance module”](#prefactor_httpendpointsagent_instance-module) AgentInstance endpoint client. ### *class* prefactor\_http.endpoints.agent\_instance.AgentInstanceClient(http\_client: [PrefactorHttpClient](prefactor_http.md#prefactor_http.PrefactorHttpClient)) [Section titled “class prefactor\_http.endpoints.agent\_instance.AgentInstanceClient(http\_client: PrefactorHttpClient)”](#class-prefactor_httpendpointsagent_instanceagentinstanceclienthttp_client-prefactorhttpclient) Bases: `object` Client for AgentInstance POST endpoints. Provides methods to interact with agent instances including: * register: Create a new agent instance * start: Mark an instance as started * finish: Mark an instance as finished #### *async* finish(agent\_instance\_id: str, status: Literal\[‘complete’, ‘failed’, ‘cancelled’] | None = None, timestamp: datetime | None = None, idempotency\_key: str | None = None) → [AgentInstance](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance) [Section titled “async finish(agent\_instance\_id: str, status: Literal\[‘complete’, ‘failed’, ‘cancelled’\] | None = None, timestamp: datetime | None = None, idempotency\_key: str | None = None) → AgentInstance”](#async-finishagent_instance_id-str-status-literalcomplete-failed-cancelled--none--none-timestamp-datetime--none--none-idempotency_key-str--none--none--agentinstance) Mark an agent instance as finished. POST /api/v1/agent\_instance/{agent\_instance\_id}/finish * **Parameters:** * **agent\_instance\_id** – The instance ID * **status** – Optional finish status (complete, failed, cancelled) * **timestamp** – Optional finish time (defaults to now) * **idempotency\_key** – Optional idempotency key * **Returns:** The updated agent instance * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If instance not found * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors #### *async* get(agent\_instance\_id: str) → [AgentInstance](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance) [Section titled “async get(agent\_instance\_id: str) → AgentInstance”](#async-getagent_instance_id-str--agentinstance) Fetch an agent instance by ID. GET /api/v1/agent\_instance/{agent\_instance\_id} * **Parameters:** **agent\_instance\_id** – The instance ID to fetch. * **Returns:** The agent instance. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If instance not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* record\_quality(agent\_instance\_id: str, name: str, payload: dict | None = None, idempotency\_key: str | None = None) → [AgentInstance](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance) [Section titled “async record\_quality(agent\_instance\_id: str, name: str, payload: dict | None = None, idempotency\_key: str | None = None) → AgentInstance”](#async-record_qualityagent_instance_id-str-name-str-payload-dict--none--none-idempotency_key-str--none--none--agentinstance) Record a quality payload on an agent instance. POST /api/v1/agent\_instance/{agent\_instance\_id}/record\_quality Sets or clears one named quality payload. A null `payload` removes that name from the stored map. Other names are left unchanged. * **Parameters:** * **agent\_instance\_id** – The instance ID. * **name** – Quality schema name (key in the agent schema version quality\_schemas). * **payload** – Quality payload for this name, or None to remove the recorded payload for this name. * **idempotency\_key** – Optional idempotency key. * **Returns:** The updated agent instance. * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If instance not found. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors. #### *async* register(agent\_version: dict, agent\_schema\_version: dict, agent\_id: str | None = None, environment\_id: str | None = None, id: str | None = None, idempotency\_key: str | None = None, update\_current\_version: bool = True, purpose: Literal\[‘live’, ‘smoke\_test’, ‘eval’] | None = None, external\_identifier: str | None = None) → [AgentInstance](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance) [Section titled “async register(agent\_version: dict, agent\_schema\_version: dict, agent\_id: str | None = None, environment\_id: str | None = None, id: str | None = None, idempotency\_key: str | None = None, update\_current\_version: bool = True, purpose: Literal\[‘live’, ‘smoke\_test’, ‘eval’\] | None = None, external\_identifier: str | None = None) → AgentInstance”](#async-registeragent_version-dict-agent_schema_version-dict-agent_id-str--none--none-environment_id-str--none--none-id-str--none--none-idempotency_key-str--none--none-update_current_version-bool--true-purpose-literallive-smoke_test-eval--none--none-external_identifier-str--none--none--agentinstance) Register a new agent instance. POST /api/v1/agent\_instance/register * **Parameters:** * **agent\_id** – Agent ID. Omit when using a deployment-scoped token. * **agent\_version** – Version info dict with name, external\_identifier, description * **agent\_schema\_version** – Schema version dict with external\_identifier and span type definitions (span\_type\_schemas, span\_schemas, and/or span\_result\_schemas) * **environment\_id** – Environment to deploy into. Required when using an account-scoped token; omit when using a deployment-scoped token * **id** – Optional custom ID for the instance * **external\_identifier** – Optional external identifier for this agent instance in an external system (unique per agent) * **idempotency\_key** – Optional idempotency key * **update\_current\_version** – Whether to update the deployment’s pinned version (defaults to True) * **purpose** – Why this instance ran — `"live"`, `"smoke_test"`, or `"eval"`. Omitted (None) lets the API default to `"live"`. * **Returns:** The created agent instance * **Raises:** * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On API errors * [**PrefactorValidationError**](prefactor_http.md#prefactor_http.PrefactorValidationError) – On validation errors #### *async* start(agent\_instance\_id: str, timestamp: datetime | None = None, idempotency\_key: str | None = None) → [AgentInstance](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance) [Section titled “async start(agent\_instance\_id: str, timestamp: datetime | None = None, idempotency\_key: str | None = None) → AgentInstance”](#async-startagent_instance_id-str-timestamp-datetime--none--none-idempotency_key-str--none--none--agentinstance) Mark an agent instance as started. POST /api/v1/agent\_instance/{agent\_instance\_id}/start * **Parameters:** * **agent\_instance\_id** – The instance ID * **timestamp** – Optional start time (defaults to now) * **idempotency\_key** – Optional idempotency key * **Returns:** The updated agent instance * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If instance not found * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors # prefactor_http.endpoints.agent_span module # prefactor\_http.endpoints.agent\_span module [Section titled “prefactor\_http.endpoints.agent\_span module”](#prefactor_httpendpointsagent_span-module) AgentSpan endpoint client. ### *class* prefactor\_http.endpoints.agent\_span.AgentSpanClient(http\_client: [PrefactorHttpClient](prefactor_http.md#prefactor_http.PrefactorHttpClient)) [Section titled “class prefactor\_http.endpoints.agent\_span.AgentSpanClient(http\_client: PrefactorHttpClient)”](#class-prefactor_httpendpointsagent_spanagentspanclienthttp_client-prefactorhttpclient) Bases: `object` Client for AgentSpan POST endpoints. Provides methods to interact with agent spans including: * create: Create a new agent span * finish: Mark a span as finished #### *async* create(agent\_instance\_id: str, schema\_name: str, status: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’], payload: dict | None = None, result\_payload: dict | None = None, id: str | None = None, parent\_span\_id: str | None = None, started\_at: datetime | None = None, finished\_at: datetime | None = None, idempotency\_key: str | None = None, control\_signal\_callback: Callable\[\[str | None], None] | None = None) → [AgentSpan](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan) [Section titled “async create(agent\_instance\_id: str, schema\_name: str, status: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\], payload: dict | None = None, result\_payload: dict | None = None, id: str | None = None, parent\_span\_id: str | None = None, started\_at: datetime | None = None, finished\_at: datetime | None = None, idempotency\_key: str | None = None, control\_signal\_callback: Callable\[\[str | None\], None\] | None = None) → AgentSpan”](#async-createagent_instance_id-str-schema_name-str-status-literalpending-active-complete-failed-cancelled-terminated-payload-dict--none--none-result_payload-dict--none--none-id-str--none--none-parent_span_id-str--none--none-started_at-datetime--none--none-finished_at-datetime--none--none-idempotency_key-str--none--none-control_signal_callback-callablestr--none-none--none--none--agentspan) Create a new agent span. POST /api/v1/agent\_spans * **Parameters:** * **agent\_instance\_id** – ID of the agent instance this span belongs to * **schema\_name** – Name of the schema for this span * **status** – Status for the span * **payload** – Optional span payload data * **result\_payload** – Optional result payload data * **id** – Optional custom ID for the span * **parent\_span\_id** – Optional parent span ID * **started\_at** – Optional start time * **finished\_at** – Optional finish time * **idempotency\_key** – Optional idempotency key * **Returns:** The created agent span * **Raises:** * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On API errors * [**PrefactorValidationError**](prefactor_http.md#prefactor_http.PrefactorValidationError) – On validation errors #### *async* finish(agent\_span\_id: str, status: Literal\[‘complete’, ‘failed’, ‘cancelled’] | None = None, result\_payload: dict | None = None, timestamp: datetime | None = None, idempotency\_key: str | None = None, control\_signal\_callback: Callable\[\[str | None], None] | None = None) → [AgentSpan](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan) [Section titled “async finish(agent\_span\_id: str, status: Literal\[‘complete’, ‘failed’, ‘cancelled’\] | None = None, result\_payload: dict | None = None, timestamp: datetime | None = None, idempotency\_key: str | None = None, control\_signal\_callback: Callable\[\[str | None\], None\] | None = None) → AgentSpan”](#async-finishagent_span_id-str-status-literalcomplete-failed-cancelled--none--none-result_payload-dict--none--none-timestamp-datetime--none--none-idempotency_key-str--none--none-control_signal_callback-callablestr--none-none--none--none--agentspan) Finish an agent span. POST /api/v1/agent\_spans/{agent\_span\_id}/finish * **Parameters:** * **agent\_span\_id** – The span ID * **status** – Optional finish status (complete, failed, cancelled) * **result\_payload** – Optional result payload data * **timestamp** – Optional finish time (defaults to now) * **idempotency\_key** – Optional idempotency key * **Returns:** The updated agent span * **Raises:** * [**PrefactorNotFoundError**](prefactor_http.md#prefactor_http.PrefactorNotFoundError) – If span not found * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – On other errors # prefactor_http.endpoints.bulk module # prefactor\_http.endpoints.bulk module [Section titled “prefactor\_http.endpoints.bulk module”](#prefactor_httpendpointsbulk-module) Bulk endpoint client for the Prefactor API. ### *class* prefactor\_http.endpoints.bulk.BulkClient(http\_client: [PrefactorHttpClient](prefactor_http.md#prefactor_http.PrefactorHttpClient)) [Section titled “class prefactor\_http.endpoints.bulk.BulkClient(http\_client: PrefactorHttpClient)”](#class-prefactor_httpendpointsbulkbulkclienthttp_client-prefactorhttpclient) Bases: `object` Client for bulk action operations. Execute multiple POST actions in a single HTTP request. This endpoint allows you to batch multiple operations together, reducing the number of round trips to the API. Key Features: : - Each item in the request is processed independently in its own database transaction * Processing stops early if any item returns an error * All successfully processed items up to the error are returned * Any unprocessed items (after the first error) are excluded from the result * All items must include a unique idempotency\_key (minimum 8 characters) * Results are returned as a map keyed by idempotency\_key ### Example [Section titled “Example”](#example) ```plaintext `` ``` ```plaintext ` ``` python request = BulkRequest( > items=\[ : BulkItem( # type: ignore\[call-arg] : \_type=”agent\_instances/register”, idempotency\_key=”register-instance-001”, agent\_id=”agent\_123”, agent\_version={“name”: “My Agent”, “external\_identifier”: “v1.0.0”}, agent\_schema\_version={\ > \> “external\_identifier”: “v1.0.0”, > “span\_type\_schemas”: \[\ > \> > { > > : “name”: “agent:llm”, > > “title”: “LLM Call”, > > “params\_schema”: { > >\ > \> > > “type”: “object”, > > > “properties”: { > >\ > \> > > > “model”: {“type”: “string”}, > > > > “prompt”: {“type”: “string”}, > >\ > \> > > }, > > > “required”: \[“model”, “prompt”], > >\ > \> > }, > > “result\_schema”: { > >\ > \> > > “type”: “object”, > > > “properties”: { > >\ > \> > > > “response”: {“type”: “string”}, > >\ > \> > > }, > >\ > \> > },\ > \> > },\ > \> ],\ > },\ > ), BulkItem( # type: ignore\[call-arg] > > > \_type=”agent\_spans/create”, idempotency\_key=”create-span-001”, agent\_instance\_id=”instance\_123”, schema\_name=”agent:llm”, status=”active”, > > > > > > ), > ] ) response = await client.bulk.execute(request) print(response.outputs\[“create-span-001”].status) ```plaintext `` ``` ```plaintext ` ``` #### *async* execute(request: [BulkRequest](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkRequest)) → [BulkResponse](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkResponse) [Section titled “async execute(request: BulkRequest) → BulkResponse”](#async-executerequest-bulkrequest--bulkresponse) Execute multiple queries/actions in a single request. * **Parameters:** **request** – The bulk request containing items to process. * **Returns:** BulkResponse with outputs keyed by idempotency\_key. * **Raises:** * [**PrefactorValidationError**](prefactor_http.md#prefactor_http.PrefactorValidationError) – If the request is invalid. * [**PrefactorRetryExhaustedError**](prefactor_http.md#prefactor_http.PrefactorRetryExhaustedError) – If the request fails after all retries. * [**PrefactorApiError**](prefactor_http.md#prefactor_http.PrefactorApiError) – If the API returns an error response. # prefactor_http.exceptions module # prefactor\_http.exceptions module [Section titled “prefactor\_http.exceptions module”](#prefactor_httpexceptions-module) Exceptions for Prefactor HTTP Client. ### *exception* prefactor\_http.exceptions.PrefactorApiError(message: str, code: str, status\_code: int) [Section titled “exception prefactor\_http.exceptions.PrefactorApiError(message: str, code: str, status\_code: int)”](#exception-prefactor_httpexceptionsprefactorapierrormessage-str-code-str-status_code-int) Bases: [`PrefactorHttpError`](#prefactor_http.exceptions.PrefactorHttpError) API returned an error response. #### message [Section titled “message”](#message) Human-readable error message #### code [Section titled “code”](#code) Error code from the API #### status\_code [Section titled “status\_code”](#status_code) HTTP status code ### *exception* prefactor\_http.exceptions.PrefactorAuthError(message: str, code: str, status\_code: int) [Section titled “exception prefactor\_http.exceptions.PrefactorAuthError(message: str, code: str, status\_code: int)”](#exception-prefactor_httpexceptionsprefactorautherrormessage-str-code-str-status_code-int) Bases: [`PrefactorApiError`](#prefactor_http.exceptions.PrefactorApiError) Authentication/authorization errors (401, 403). ### *exception* prefactor\_http.exceptions.PrefactorClientError [Section titled “exception prefactor\_http.exceptions.PrefactorClientError”](#exception-prefactor_httpexceptionsprefactorclienterror) Bases: [`PrefactorHttpError`](#prefactor_http.exceptions.PrefactorHttpError) Client-side error (not related to API). ### *exception* prefactor\_http.exceptions.PrefactorHttpError [Section titled “exception prefactor\_http.exceptions.PrefactorHttpError”](#exception-prefactor_httpexceptionsprefactorhttperror) Bases: `Exception` Base exception for all HTTP client errors. ### *exception* prefactor\_http.exceptions.PrefactorNotFoundError(message: str, code: str, status\_code: int) [Section titled “exception prefactor\_http.exceptions.PrefactorNotFoundError(message: str, code: str, status\_code: int)”](#exception-prefactor_httpexceptionsprefactornotfounderrormessage-str-code-str-status_code-int) Bases: [`PrefactorApiError`](#prefactor_http.exceptions.PrefactorApiError) Resource not found (404). ### *exception* prefactor\_http.exceptions.PrefactorResponseContractError(message: str, , status\_code: int | None = None, body\_snippet: str | None = None, cause: Exception | None = None) [Section titled “exception prefactor\_http.exceptions.PrefactorResponseContractError(message: str, , status\_code: int | None = None, body\_snippet: str | None = None, cause: Exception | None = None)”](#exception-prefactor_httpexceptionsprefactorresponsecontracterrormessage-str--status_code-int--none--none-body_snippet-str--none--none-cause-exception--none--none) Bases: [`PrefactorHttpError`](#prefactor_http.exceptions.PrefactorHttpError) Backend response violated the SDK’s expected response contract. ### *exception* prefactor\_http.exceptions.PrefactorRetryExhaustedError(message: str, last\_error: Exception | None = None) [Section titled “exception prefactor\_http.exceptions.PrefactorRetryExhaustedError(message: str, last\_error: Exception | None = None)”](#exception-prefactor_httpexceptionsprefactorretryexhaustederrormessage-str-last_error-exception--none--none) Bases: [`PrefactorHttpError`](#prefactor_http.exceptions.PrefactorHttpError) All retry attempts exhausted. #### last\_error [Section titled “last\_error”](#last_error) The last exception that caused the retry to fail ### *exception* prefactor\_http.exceptions.PrefactorValidationError(message: str, code: str, status\_code: int, errors: dict) [Section titled “exception prefactor\_http.exceptions.PrefactorValidationError(message: str, code: str, status\_code: int, errors: dict)”](#exception-prefactor_httpexceptionsprefactorvalidationerrormessage-str-code-str-status_code-int-errors-dict) Bases: [`PrefactorApiError`](#prefactor_http.exceptions.PrefactorApiError) Validation errors (400, 422). #### errors [Section titled “errors”](#errors) Detailed validation errors mapping field names to error messages ### prefactor\_http.exceptions.is\_permanent\_http\_error(error: Exception) → bool [Section titled “prefactor\_http.exceptions.is\_permanent\_http\_error(error: Exception) → bool”](#prefactor_httpexceptionsis_permanent_http_errorerror-exception--bool) Return True when retrying the same operation should stop immediately. ### prefactor\_http.exceptions.is\_transient\_http\_error(error: Exception) → bool [Section titled “prefactor\_http.exceptions.is\_transient\_http\_error(error: Exception) → bool”](#prefactor_httpexceptionsis_transient_http_errorerror-exception--bool) Return True when the error is safe to retry later. # prefactor_http.models package # prefactor\_http.models package [Section titled “prefactor\_http.models package”](#prefactor_httpmodels-package) Prefactor HTTP Client models. ### *class* prefactor\_http.models.ActionProfile(, create\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’] = ‘unknown’, read\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’] = ‘unknown’, update\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’] = ‘unknown’, destroy\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’] = ‘unknown’, financial\_transactions: Literal\[‘unknown’, ‘allowed’, ‘disallowed’] = ‘unknown’, external\_communication: Literal\[‘unknown’, ‘allowed’, ‘disallowed’] = ‘unknown’) [Section titled “class prefactor\_http.models.ActionProfile(, create\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’\] = ‘unknown’, read\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’\] = ‘unknown’, update\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’\] = ‘unknown’, destroy\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’\] = ‘unknown’, financial\_transactions: Literal\[‘unknown’, ‘allowed’, ‘disallowed’\] = ‘unknown’, external\_communication: Literal\[‘unknown’, ‘allowed’, ‘disallowed’\] = ‘unknown’)”](#class-prefactor_httpmodelsactionprofile-create_data-literalunknown-allowed-disallowed--unknown-read_data-literalunknown-allowed-disallowed--unknown-update_data-literalunknown-allowed-disallowed--unknown-destroy_data-literalunknown-allowed-disallowed--unknown-financial_transactions-literalunknown-allowed-disallowed--unknown-external_communication-literalunknown-allowed-disallowed--unknown) Bases: `BaseModel` Action profile defining what actions a span type performs. #### create\_data [Section titled “create\_data”](#create_data) Whether this span creates data * **Type:** Literal\[‘unknown’, ‘allowed’, ‘disallowed’] #### read\_data [Section titled “read\_data”](#read_data) Whether this span reads data * **Type:** Literal\[‘unknown’, ‘allowed’, ‘disallowed’] #### update\_data [Section titled “update\_data”](#update_data) Whether this span updates data * **Type:** Literal\[‘unknown’, ‘allowed’, ‘disallowed’] #### destroy\_data [Section titled “destroy\_data”](#destroy_data) Whether this span destroys data * **Type:** Literal\[‘unknown’, ‘allowed’, ‘disallowed’] #### financial\_transactions [Section titled “financial\_transactions”](#financial_transactions) Whether this span performs financial transactions * **Type:** Literal\[‘unknown’, ‘allowed’, ‘disallowed’] #### external\_communication [Section titled “external\_communication”](#external_communication) Whether this span sends external communications * **Type:** Literal\[‘unknown’, ‘allowed’, ‘disallowed’] #### create\_data *: Literal\[‘unknown’, ‘allowed’, ‘disallowed’]* [Section titled “create\_data : Literal\[‘unknown’, ‘allowed’, ‘disallowed’\]”](#create_data--literalunknown-allowed-disallowed) #### destroy\_data *: Literal\[‘unknown’, ‘allowed’, ‘disallowed’]* [Section titled “destroy\_data : Literal\[‘unknown’, ‘allowed’, ‘disallowed’\]”](#destroy_data--literalunknown-allowed-disallowed) #### external\_communication *: Literal\[‘unknown’, ‘allowed’, ‘disallowed’]* [Section titled “external\_communication : Literal\[‘unknown’, ‘allowed’, ‘disallowed’\]”](#external_communication--literalunknown-allowed-disallowed) #### financial\_transactions *: Literal\[‘unknown’, ‘allowed’, ‘disallowed’]* [Section titled “financial\_transactions : Literal\[‘unknown’, ‘allowed’, ‘disallowed’\]”](#financial_transactions--literalunknown-allowed-disallowed) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config--) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### read\_data *: Literal\[‘unknown’, ‘allowed’, ‘disallowed’]* [Section titled “read\_data : Literal\[‘unknown’, ‘allowed’, ‘disallowed’\]”](#read_data--literalunknown-allowed-disallowed) #### update\_data *: Literal\[‘unknown’, ‘allowed’, ‘disallowed’]* [Section titled “update\_data : Literal\[‘unknown’, ‘allowed’, ‘disallowed’\]”](#update_data--literalunknown-allowed-disallowed) ### *class* prefactor\_http.models.Agent(, type: Literal\[‘agent’], id: str, name: str, description: str | None = None, external\_identifier: str | None = None, status: Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’], owner\_person\_id: str | None = None, risk\_profile\_id: str | None = None, team\_id: str | None = None, instance\_counts: [AgentInstanceCounts](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentInstanceCounts) | None = None, available\_actions: [AgentAvailableActions](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentAvailableActions) | None = None, inserted\_at: datetime | None = None, updated\_at: datetime | None = None) [Section titled “class prefactor\_http.models.Agent(, type: Literal\[‘agent’\], id: str, name: str, description: str | None = None, external\_identifier: str | None = None, status: Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’\], owner\_person\_id: str | None = None, risk\_profile\_id: str | None = None, team\_id: str | None = None, instance\_counts: AgentInstanceCounts | None = None, available\_actions: AgentAvailableActions | None = None, inserted\_at: datetime | None = None, updated\_at: datetime | None = None)”](#class-prefactor_httpmodelsagent-type-literalagent-id-str-name-str-description-str--none--none-external_identifier-str--none--none-status-literalpending-active-dormant-retired-owner_person_id-str--none--none-risk_profile_id-str--none--none-team_id-str--none--none-instance_counts-agentinstancecounts--none--none-available_actions-agentavailableactions--none--none-inserted_at-datetime--none--none-updated_at-datetime--none--none) Bases: `BaseModel` Full agent details. #### type [Section titled “type”](#type) Resource type (always “agent”). * **Type:** Literal\[‘agent’] #### id [Section titled “id”](#id) Agent ID. * **Type:** str #### name [Section titled “name”](#name) Agent name. * **Type:** str #### description [Section titled “description”](#description) Optional agent description. * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier) Optional external identifier (unique per account). * **Type:** str | None #### status [Section titled “status”](#status) Agent status (pending, active, dormant, retired). * **Type:** Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’] #### owner\_person\_id [Section titled “owner\_person\_id”](#owner_person_id) Optional owner person ID. * **Type:** str | None #### risk\_profile\_id [Section titled “risk\_profile\_id”](#risk_profile_id) Optional risk profile ID. * **Type:** str | None #### team\_id [Section titled “team\_id”](#team_id) Optional team ID. * **Type:** str | None #### instance\_counts [Section titled “instance\_counts”](#instance_counts) Instance counts for this agent. * **Type:** [AgentInstanceCounts](#prefactor_http.models.AgentInstanceCounts) | None #### available\_actions [Section titled “available\_actions”](#available_actions) Available actions based on current status. * **Type:** [AgentAvailableActions](#prefactor_http.models.AgentAvailableActions) | None #### inserted\_at [Section titled “inserted\_at”](#inserted_at) When the agent was created. * **Type:** datetime | None #### updated\_at [Section titled “updated\_at”](#updated_at) When the agent was last updated. * **Type:** datetime | None #### available\_actions *: [AgentAvailableActions](#prefactor_http.models.AgentAvailableActions) | None* [Section titled “available\_actions : AgentAvailableActions | None”](#available_actions--agentavailableactions--none) #### description *: str | None* [Section titled “description : str | None”](#description--str--none) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none) #### id *: str* [Section titled “id : str”](#id--str) #### inserted\_at *: datetime | None* [Section titled “inserted\_at : datetime | None”](#inserted_at--datetime--none) #### instance\_counts *: [AgentInstanceCounts](#prefactor_http.models.AgentInstanceCounts) | None* [Section titled “instance\_counts : AgentInstanceCounts | None”](#instance_counts--agentinstancecounts--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str) #### owner\_person\_id *: str | None* [Section titled “owner\_person\_id : str | None”](#owner_person_id--str--none) #### risk\_profile\_id *: str | None* [Section titled “risk\_profile\_id : str | None”](#risk_profile_id--str--none) #### status *: Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’]* [Section titled “status : Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’\]”](#status--literalpending-active-dormant-retired) #### team\_id *: str | None* [Section titled “team\_id : str | None”](#team_id--str--none) #### type *: Literal\[‘agent’]* [Section titled “type : Literal\[‘agent’\]”](#type--literalagent) #### updated\_at *: datetime | None* [Section titled “updated\_at : datetime | None”](#updated_at--datetime--none) ### *class* prefactor\_http.models.AgentAvailableActions(, update: bool = False, retire: bool = False, reinstate: bool = False, delete: bool = False) [Section titled “class prefactor\_http.models.AgentAvailableActions(, update: bool = False, retire: bool = False, reinstate: bool = False, delete: bool = False)”](#class-prefactor_httpmodelsagentavailableactions-update-bool--false-retire-bool--false-reinstate-bool--false-delete-bool--false) Bases: `BaseModel` Available actions for an agent based on its status. #### update [Section titled “update”](#update) Whether the agent can be updated. * **Type:** bool #### retire [Section titled “retire”](#retire) Whether the agent can be retired. * **Type:** bool #### reinstate [Section titled “reinstate”](#reinstate) Whether the agent can be reinstated from retired. * **Type:** bool #### delete [Section titled “delete”](#delete) Whether the agent can be deleted. * **Type:** bool #### delete *: bool* [Section titled “delete : bool”](#delete--bool) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---2) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### reinstate *: bool* [Section titled “reinstate : bool”](#reinstate--bool) #### retire *: bool* [Section titled “retire : bool”](#retire--bool) #### update *: bool* [Section titled “update : bool”](#update--bool) ### *class* prefactor\_http.models.AgentForCreate(, name: str, description: str | None = None, external\_identifier: str | None = None, id: str | None = None, owner\_person\_id: str | None = None, risk\_profile\_id: str | None = None, team\_id: str | None = None) [Section titled “class prefactor\_http.models.AgentForCreate(, name: str, description: str | None = None, external\_identifier: str | None = None, id: str | None = None, owner\_person\_id: str | None = None, risk\_profile\_id: str | None = None, team\_id: str | None = None)”](#class-prefactor_httpmodelsagentforcreate-name-str-description-str--none--none-external_identifier-str--none--none-id-str--none--none-owner_person_id-str--none--none-risk_profile_id-str--none--none-team_id-str--none--none) Bases: `BaseModel` Parameters for creating a new agent. #### name [Section titled “name”](#name-1) Agent name (required). * **Type:** str #### description [Section titled “description”](#description-1) Optional agent description. * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier-1) Optional external identifier (unique per account). * **Type:** str | None #### id [Section titled “id”](#id-1) Optional custom ID (PFID with matching partition). * **Type:** str | None #### owner\_person\_id [Section titled “owner\_person\_id”](#owner_person_id-1) Optional owner person ID. * **Type:** str | None #### risk\_profile\_id [Section titled “risk\_profile\_id”](#risk_profile_id-1) Optional risk profile ID. * **Type:** str | None #### team\_id [Section titled “team\_id”](#team_id-1) Optional team ID. * **Type:** str | None #### description *: str | None* [Section titled “description : str | None”](#description--str--none-1) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none-1) #### id *: str | None* [Section titled “id : str | None”](#id--str--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---3) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-1) #### owner\_person\_id *: str | None* [Section titled “owner\_person\_id : str | None”](#owner_person_id--str--none-1) #### risk\_profile\_id *: str | None* [Section titled “risk\_profile\_id : str | None”](#risk_profile_id--str--none-1) #### team\_id *: str | None* [Section titled “team\_id : str | None”](#team_id--str--none-1) ### *class* prefactor\_http.models.AgentForUpdate(, name: str | None = None, description: str | None = None, owner\_person\_id: str | None = None, risk\_profile\_id: str | None = None, team\_id: str | None = None) [Section titled “class prefactor\_http.models.AgentForUpdate(, name: str | None = None, description: str | None = None, owner\_person\_id: str | None = None, risk\_profile\_id: str | None = None, team\_id: str | None = None)”](#class-prefactor_httpmodelsagentforupdate-name-str--none--none-description-str--none--none-owner_person_id-str--none--none-risk_profile_id-str--none--none-team_id-str--none--none) Bases: `BaseModel` Parameters for updating an agent. Note: `external_identifier` cannot be updated via the API — it is only settable at create time. #### name [Section titled “name”](#name-2) Agent name (omit to keep current). * **Type:** str | None #### description [Section titled “description”](#description-2) Agent description (omit to keep current). * **Type:** str | None #### owner\_person\_id [Section titled “owner\_person\_id”](#owner_person_id-2) Owner person ID (omit to keep current; null to clear). * **Type:** str | None #### risk\_profile\_id [Section titled “risk\_profile\_id”](#risk_profile_id-2) Risk profile ID (omit to keep current; null to clear). * **Type:** str | None #### team\_id [Section titled “team\_id”](#team_id-2) Team ID (omit to keep current; null to clear). * **Type:** str | None #### description *: str | None* [Section titled “description : str | None”](#description--str--none-2) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---4) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str | None* [Section titled “name : str | None”](#name--str--none) #### owner\_person\_id *: str | None* [Section titled “owner\_person\_id : str | None”](#owner_person_id--str--none-2) #### risk\_profile\_id *: str | None* [Section titled “risk\_profile\_id : str | None”](#risk_profile_id--str--none-2) #### team\_id *: str | None* [Section titled “team\_id : str | None”](#team_id--str--none-2) ### *class* prefactor\_http.models.AgentInstance(, type: Literal\[‘agent\_instance’], id: str, account\_id: str, agent\_id: str, agent\_version\_id: str, environment\_id: str, agent\_deployment\_id: str, status: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’], inserted\_at: datetime, updated\_at: datetime, started\_at: datetime | None = None, finished\_at: datetime | None = None, termination\_reason: str | None = None, external\_identifier: str | None = None, span\_counts: [AgentInstanceSpanCounts](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceSpanCounts) | None = None, purpose: Literal\[‘live’, ‘smoke\_test’, ‘eval’] | None = None, quality\_payloads: dict\[str, dict] | None = None, quality\_summaries: dict\[str, str] | None = None) [Section titled “class prefactor\_http.models.AgentInstance(, type: Literal\[‘agent\_instance’\], id: str, account\_id: str, agent\_id: str, agent\_version\_id: str, environment\_id: str, agent\_deployment\_id: str, status: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\], inserted\_at: datetime, updated\_at: datetime, started\_at: datetime | None = None, finished\_at: datetime | None = None, termination\_reason: str | None = None, external\_identifier: str | None = None, span\_counts: AgentInstanceSpanCounts | None = None, purpose: Literal\[‘live’, ‘smoke\_test’, ‘eval’\] | None = None, quality\_payloads: dict\[str, dict\] | None = None, quality\_summaries: dict\[str, str\] | None = None)”](#class-prefactor_httpmodelsagentinstance-type-literalagent_instance-id-str-account_id-str-agent_id-str-agent_version_id-str-environment_id-str-agent_deployment_id-str-status-literalpending-active-complete-failed-cancelled-terminated-inserted_at-datetime-updated_at-datetime-started_at-datetime--none--none-finished_at-datetime--none--none-termination_reason-str--none--none-external_identifier-str--none--none-span_counts-agentinstancespancounts--none--none-purpose-literallive-smoke_test-eval--none--none-quality_payloads-dictstr-dict--none--none-quality_summaries-dictstr-str--none--none) Bases: `BaseModel` Agent instance model. #### type [Section titled “type”](#type-1) Resource type (always “agent\_instance”) * **Type:** Literal\[‘agent\_instance’] #### id [Section titled “id”](#id-2) Instance ID * **Type:** str #### account\_id [Section titled “account\_id”](#account_id) Account ID * **Type:** str #### agent\_id [Section titled “agent\_id”](#agent_id) Agent ID * **Type:** str #### agent\_version\_id [Section titled “agent\_version\_id”](#agent_version_id) Agent version ID * **Type:** str #### environment\_id [Section titled “environment\_id”](#environment_id) Environment ID * **Type:** str #### agent\_deployment\_id [Section titled “agent\_deployment\_id”](#agent_deployment_id) Agent deployment ID * **Type:** str #### status [Section titled “status”](#status-1) Instance status * **Type:** AgentStatus #### inserted\_at [Section titled “inserted\_at”](#inserted_at-1) When the instance was created * **Type:** datetime #### updated\_at [Section titled “updated\_at”](#updated_at-1) When the instance was last updated * **Type:** datetime #### started\_at [Section titled “started\_at”](#started_at) When the instance started (null if not started) * **Type:** datetime | None #### finished\_at [Section titled “finished\_at”](#finished_at) When the instance finished (null if not finished) * **Type:** datetime | None #### termination\_reason [Section titled “termination\_reason”](#termination_reason) Reason for termination (null if not terminated) * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier-2) Optional external identifier (unique per agent) * **Type:** str | None #### span\_counts [Section titled “span\_counts”](#span_counts) Span counts for this instance * **Type:** [AgentInstanceSpanCounts](#prefactor_http.models.AgentInstanceSpanCounts) | None #### purpose [Section titled “purpose”](#purpose) Why this instance ran (live, smoke\_test, eval) * **Type:** InstancePurpose | None #### quality\_payloads [Section titled “quality\_payloads”](#quality_payloads) Map of quality schema name to evaluation payload * **Type:** dict\[str, dict] | None #### quality\_summaries [Section titled “quality\_summaries”](#quality_summaries) Map of quality schema name to rendered summary * **Type:** dict\[str, str] | None #### account\_id *: str* [Section titled “account\_id : str”](#account_id--str) #### agent\_deployment\_id *: str* [Section titled “agent\_deployment\_id : str”](#agent_deployment_id--str) #### agent\_id *: str* [Section titled “agent\_id : str”](#agent_id--str) #### agent\_version\_id *: str* [Section titled “agent\_version\_id : str”](#agent_version_id--str) #### environment\_id *: str* [Section titled “environment\_id : str”](#environment_id--str) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none-2) #### finished\_at *: datetime | None* [Section titled “finished\_at : datetime | None”](#finished_at--datetime--none) #### id *: str* [Section titled “id : str”](#id--str-1) #### inserted\_at *: datetime* [Section titled “inserted\_at : datetime”](#inserted_at--datetime) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---5) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### purpose *: InstancePurpose | None* [Section titled “purpose : InstancePurpose | None”](#purpose--instancepurpose--none) #### quality\_payloads *: dict\[str, dict] | None* [Section titled “quality\_payloads : dict\[str, dict\] | None”](#quality_payloads--dictstr-dict--none) #### quality\_summaries *: dict\[str, str] | None* [Section titled “quality\_summaries : dict\[str, str\] | None”](#quality_summaries--dictstr-str--none) #### span\_counts *: [AgentInstanceSpanCounts](#prefactor_http.models.AgentInstanceSpanCounts) | None* [Section titled “span\_counts : AgentInstanceSpanCounts | None”](#span_counts--agentinstancespancounts--none) #### started\_at *: datetime | None* [Section titled “started\_at : datetime | None”](#started_at--datetime--none) #### status *: AgentStatus* [Section titled “status : AgentStatus”](#status--agentstatus) #### termination\_reason *: str | None* [Section titled “termination\_reason : str | None”](#termination_reason--str--none) #### type *: Literal\[‘agent\_instance’]* [Section titled “type : Literal\[‘agent\_instance’\]”](#type--literalagent_instance) #### updated\_at *: datetime* [Section titled “updated\_at : datetime”](#updated_at--datetime) ### *class* prefactor\_http.models.AgentInstanceCounts(, total: int = 0, pending: int = 0, active: int = 0, complete: int = 0, failed: int = 0, cancelled: int = 0, terminated: int = 0, finished: int = 0) [Section titled “class prefactor\_http.models.AgentInstanceCounts(, total: int = 0, pending: int = 0, active: int = 0, complete: int = 0, failed: int = 0, cancelled: int = 0, terminated: int = 0, finished: int = 0)”](#class-prefactor_httpmodelsagentinstancecounts-total-int--0-pending-int--0-active-int--0-complete-int--0-failed-int--0-cancelled-int--0-terminated-int--0-finished-int--0) Bases: `BaseModel` Instance counts for an agent. #### total [Section titled “total”](#total) Total number of agent instances. * **Type:** int #### pending [Section titled “pending”](#pending) Number of instances with status pending. * **Type:** int #### active [Section titled “active”](#active) Number of instances with status active (running). * **Type:** int #### complete [Section titled “complete”](#complete) Number of instances with status complete. * **Type:** int #### failed [Section titled “failed”](#failed) Number of instances with status failed. * **Type:** int #### cancelled [Section titled “cancelled”](#cancelled) Number of instances with status cancelled. * **Type:** int #### terminated [Section titled “terminated”](#terminated) Number of instances with status terminated. * **Type:** int #### finished [Section titled “finished”](#finished) Number of instances in a finished state. * **Type:** int #### active *: int* [Section titled “active : int”](#active--int) #### cancelled *: int* [Section titled “cancelled : int”](#cancelled--int) #### complete *: int* [Section titled “complete : int”](#complete--int) #### failed *: int* [Section titled “failed : int”](#failed--int) #### finished *: int* [Section titled “finished : int”](#finished--int) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---6) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### pending *: int* [Section titled “pending : int”](#pending--int) #### terminated *: int* [Section titled “terminated : int”](#terminated--int) #### total *: int* [Section titled “total : int”](#total--int) ### *class* prefactor\_http.models.AgentInstanceRecordQuality(, name: str, payload: dict | None = None) [Section titled “class prefactor\_http.models.AgentInstanceRecordQuality(, name: str, payload: dict | None = None)”](#class-prefactor_httpmodelsagentinstancerecordquality-name-str-payload-dict--none--none) Bases: `BaseModel` Parameters for recording a quality payload on an agent instance. #### name [Section titled “name”](#name-3) Unique identifier of the quality schema entry to record against * **Type:** str #### payload [Section titled “payload”](#payload) Quality payload for this name, or None to remove the recorded payload for this name * **Type:** dict | None #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---7) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-2) #### payload *: dict | None* [Section titled “payload : dict | None”](#payload--dict--none) ### *class* prefactor\_http.models.AgentInstanceSpanCounts(, total: int = 0, active: int = 0, complete: int = 0, failed: int = 0, cancelled: int = 0, finished: int = 0) [Section titled “class prefactor\_http.models.AgentInstanceSpanCounts(, total: int = 0, active: int = 0, complete: int = 0, failed: int = 0, cancelled: int = 0, finished: int = 0)”](#class-prefactor_httpmodelsagentinstancespancounts-total-int--0-active-int--0-complete-int--0-failed-int--0-cancelled-int--0-finished-int--0) Bases: `BaseModel` Span counts for an agent instance. #### total [Section titled “total”](#total-1) Total number of spans * **Type:** int #### active [Section titled “active”](#active-1) Number of active spans * **Type:** int #### complete [Section titled “complete”](#complete-1) Number of completed spans * **Type:** int #### failed [Section titled “failed”](#failed-1) Number of failed spans * **Type:** int #### cancelled [Section titled “cancelled”](#cancelled-1) Number of cancelled spans * **Type:** int #### finished [Section titled “finished”](#finished-1) Number of finished spans (complete + failed + cancelled) * **Type:** int #### active *: int* [Section titled “active : int”](#active--int-1) #### cancelled *: int* [Section titled “cancelled : int”](#cancelled--int-1) #### complete *: int* [Section titled “complete : int”](#complete--int-1) #### failed *: int* [Section titled “failed : int”](#failed--int-1) #### finished *: int* [Section titled “finished : int”](#finished--int-1) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---8) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### total *: int* [Section titled “total : int”](#total--int-1) ### *class* prefactor\_http.models.AgentSchemaVersionForRegister(, external\_identifier: str | None = None, span\_schemas: dict\[str, dict] | None = None, span\_result\_schemas: dict\[str, dict] | None = None, span\_type\_schemas: list\[[SpanTypeSchemaForCreate](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate)] | None = None, quality\_schemas: list\[[QualitySchemaForCreate](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaForCreate)] | None = None) [Section titled “class prefactor\_http.models.AgentSchemaVersionForRegister(, external\_identifier: str | None = None, span\_schemas: dict\[str, dict\] | None = None, span\_result\_schemas: dict\[str, dict\] | None = None, span\_type\_schemas: list\[SpanTypeSchemaForCreate\] | None = None, quality\_schemas: list\[QualitySchemaForCreate\] | None = None)”](#class-prefactor_httpmodelsagentschemaversionforregister-external_identifier-str--none--none-span_schemas-dictstr-dict--none--none-span_result_schemas-dictstr-dict--none--none-span_type_schemas-listspantypeschemaforcreate--none--none-quality_schemas-listqualityschemaforcreate--none--none) Bases: `BaseModel` Schema version information for registration. #### external\_identifier [Section titled “external\_identifier”](#external_identifier-3) External identifier for the schema version * **Type:** str | None #### span\_schemas [Section titled “span\_schemas”](#span_schemas) Map of span type names to JSON schemas * **Type:** dict\[str, dict] | None #### span\_result\_schemas [Section titled “span\_result\_schemas”](#span_result_schemas) Map of span type names to result JSON schemas * **Type:** dict\[str, dict] | None #### span\_type\_schemas [Section titled “span\_type\_schemas”](#span_type_schemas) List of span type schema details * **Type:** list\[[SpanTypeSchemaForCreate](#prefactor_http.models.SpanTypeSchemaForCreate)] | None #### quality\_schemas [Section titled “quality\_schemas”](#quality_schemas) Optional list of named quality schemas for instance evaluations * **Type:** list\[[QualitySchemaForCreate](#prefactor_http.models.QualitySchemaForCreate)] | None #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none-3) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---9) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### quality\_schemas *: list\[[QualitySchemaForCreate](#prefactor_http.models.QualitySchemaForCreate)] | None* [Section titled “quality\_schemas : list\[QualitySchemaForCreate\] | None”](#quality_schemas--listqualityschemaforcreate--none) #### span\_result\_schemas *: dict\[str, dict] | None* [Section titled “span\_result\_schemas : dict\[str, dict\] | None”](#span_result_schemas--dictstr-dict--none) #### span\_schemas *: dict\[str, dict] | None* [Section titled “span\_schemas : dict\[str, dict\] | None”](#span_schemas--dictstr-dict--none) #### span\_type\_schemas *: list\[[SpanTypeSchemaForCreate](#prefactor_http.models.SpanTypeSchemaForCreate)] | None* [Section titled “span\_type\_schemas : list\[SpanTypeSchemaForCreate\] | None”](#span_type_schemas--listspantypeschemaforcreate--none) ### *class* prefactor\_http.models.AgentSpan(\*, type: \~typing.Literal\[‘agent\_span’], id: str, account\_id: str | None = None, agent\_id: str | None = None, agent\_instance\_id: str, parent\_span\_id: str | None = None, schema\_name: str, schema\_title: str | None = None, status: \~typing.Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’], payload: dict = , result\_payload: dict | None = None, summary: str | None = None, started\_at: \~datetime.datetime | None = None, inserted\_at: \~datetime.datetime | None = None, updated\_at: \~datetime.datetime | None = None, finished\_at: \~datetime.datetime | None = None) [Section titled “class prefactor\_http.models.AgentSpan(\*, type: \~typing.Literal\[‘agent\_span’\], id: str, account\_id: str | None = None, agent\_id: str | None = None, agent\_instance\_id: str, parent\_span\_id: str | None = None, schema\_name: str, schema\_title: str | None = None, status: \~typing.Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\], payload: dict = , result\_payload: dict | None = None, summary: str | None = None, started\_at: \~datetime.datetime | None = None, inserted\_at: \~datetime.datetime | None = None, updated\_at: \~datetime.datetime | None = None, finished\_at: \~datetime.datetime | None = None)”](#class-prefactor_httpmodelsagentspan-type-typingliteralagent_span-id-str-account_id-str--none--none-agent_id-str--none--none-agent_instance_id-str-parent_span_id-str--none--none-schema_name-str-schema_title-str--none--none-status-typingliteralpending-active-complete-failed-cancelled-terminated-payload-dict---result_payload-dict--none--none-summary-str--none--none-started_at-datetimedatetime--none--none-inserted_at-datetimedatetime--none--none-updated_at-datetimedatetime--none--none-finished_at-datetimedatetime--none--none) Bases: `BaseModel` Agent span model. #### type [Section titled “type”](#type-2) Resource type (always “agent\_span”) * **Type:** Literal\[‘agent\_span’] #### id [Section titled “id”](#id-3) Span ID * **Type:** str #### account\_id [Section titled “account\_id”](#account_id-1) Account ID * **Type:** str | None #### agent\_id [Section titled “agent\_id”](#agent_id-1) Agent ID * **Type:** str | None #### agent\_instance\_id [Section titled “agent\_instance\_id”](#agent_instance_id) Agent instance ID * **Type:** str #### parent\_span\_id [Section titled “parent\_span\_id”](#parent_span_id) Parent span ID (None if root span) * **Type:** str | None #### schema\_name [Section titled “schema\_name”](#schema_name) Name of the schema for this span * **Type:** str #### schema\_title [Section titled “schema\_title”](#schema_title) Title of the schema for this span * **Type:** str | None #### status [Section titled “status”](#status-2) Span status * **Type:** Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’] #### payload [Section titled “payload”](#payload-1) Span payload data * **Type:** dict #### result\_payload [Section titled “result\_payload”](#result_payload) Result payload data * **Type:** dict | None #### summary [Section titled “summary”](#summary) Optional span summary * **Type:** str | None #### started\_at [Section titled “started\_at”](#started_at-1) When the span started * **Type:** datetime.datetime | None #### inserted\_at [Section titled “inserted\_at”](#inserted_at-2) When the span was created * **Type:** datetime.datetime | None #### updated\_at [Section titled “updated\_at”](#updated_at-2) When the span was last updated * **Type:** datetime.datetime | None #### finished\_at [Section titled “finished\_at”](#finished_at-1) When the span finished (None if in progress) * **Type:** datetime.datetime | None #### account\_id *: str | None* [Section titled “account\_id : str | None”](#account_id--str--none) #### agent\_id *: str | None* [Section titled “agent\_id : str | None”](#agent_id--str--none) #### agent\_instance\_id *: str* [Section titled “agent\_instance\_id : str”](#agent_instance_id--str) #### finished\_at *: datetime | None* [Section titled “finished\_at : datetime | None”](#finished_at--datetime--none-1) #### id *: str* [Section titled “id : str”](#id--str-2) #### inserted\_at *: datetime | None* [Section titled “inserted\_at : datetime | None”](#inserted_at--datetime--none-1) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---10) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### parent\_span\_id *: str | None* [Section titled “parent\_span\_id : str | None”](#parent_span_id--str--none) #### payload *: dict* [Section titled “payload : dict”](#payload--dict) #### result\_payload *: dict | None* [Section titled “result\_payload : dict | None”](#result_payload--dict--none) #### schema\_name *: str* [Section titled “schema\_name : str”](#schema_name--str) #### schema\_title *: str | None* [Section titled “schema\_title : str | None”](#schema_title--str--none) #### started\_at *: datetime | None* [Section titled “started\_at : datetime | None”](#started_at--datetime--none-1) #### status *: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’]* [Section titled “status : Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\]”](#status--literalpending-active-complete-failed-cancelled-terminated) #### summary *: str | None* [Section titled “summary : str | None”](#summary--str--none) #### type *: Literal\[‘agent\_span’]* [Section titled “type : Literal\[‘agent\_span’\]”](#type--literalagent_span) #### updated\_at *: datetime | None* [Section titled “updated\_at : datetime | None”](#updated_at--datetime--none-1) ### *class* prefactor\_http.models.AgentSummary(, type: Literal\[‘agent’], id: str, name: str, description: str | None = None, external\_identifier: str | None = None, status: Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’], owner\_person\_id: str | None = None, team\_id: str | None = None, available\_actions: [AgentAvailableActions](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentAvailableActions) | None = None, inserted\_at: datetime | None = None, updated\_at: datetime | None = None) [Section titled “class prefactor\_http.models.AgentSummary(, type: Literal\[‘agent’\], id: str, name: str, description: str | None = None, external\_identifier: str | None = None, status: Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’\], owner\_person\_id: str | None = None, team\_id: str | None = None, available\_actions: AgentAvailableActions | None = None, inserted\_at: datetime | None = None, updated\_at: datetime | None = None)”](#class-prefactor_httpmodelsagentsummary-type-literalagent-id-str-name-str-description-str--none--none-external_identifier-str--none--none-status-literalpending-active-dormant-retired-owner_person_id-str--none--none-team_id-str--none--none-available_actions-agentavailableactions--none--none-inserted_at-datetime--none--none-updated_at-datetime--none--none) Bases: `BaseModel` Agent summary for list responses. #### type [Section titled “type”](#type-3) Resource type (always “agent”). * **Type:** Literal\[‘agent’] #### id [Section titled “id”](#id-4) Agent ID. * **Type:** str #### name [Section titled “name”](#name-4) Agent name. * **Type:** str #### description [Section titled “description”](#description-3) Optional agent description. * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier-4) Optional external identifier (unique per account). * **Type:** str | None #### status [Section titled “status”](#status-3) Agent status. * **Type:** Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’] #### owner\_person\_id [Section titled “owner\_person\_id”](#owner_person_id-3) Optional owner person ID. * **Type:** str | None #### team\_id [Section titled “team\_id”](#team_id-3) Optional team ID. * **Type:** str | None #### available\_actions [Section titled “available\_actions”](#available_actions-1) Available actions based on current status. * **Type:** [AgentAvailableActions](#prefactor_http.models.AgentAvailableActions) | None #### inserted\_at [Section titled “inserted\_at”](#inserted_at-3) When the agent was created. * **Type:** datetime | None #### updated\_at [Section titled “updated\_at”](#updated_at-3) When the agent was last updated. * **Type:** datetime | None #### available\_actions *: [AgentAvailableActions](#prefactor_http.models.AgentAvailableActions) | None* [Section titled “available\_actions : AgentAvailableActions | None”](#available_actions--agentavailableactions--none-1) #### description *: str | None* [Section titled “description : str | None”](#description--str--none-3) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none-4) #### id *: str* [Section titled “id : str”](#id--str-3) #### inserted\_at *: datetime | None* [Section titled “inserted\_at : datetime | None”](#inserted_at--datetime--none-2) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---11) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-3) #### owner\_person\_id *: str | None* [Section titled “owner\_person\_id : str | None”](#owner_person_id--str--none-3) #### status *: Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’]* [Section titled “status : Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’\]”](#status--literalpending-active-dormant-retired-1) #### team\_id *: str | None* [Section titled “team\_id : str | None”](#team_id--str--none-3) #### type *: Literal\[‘agent’]* [Section titled “type : Literal\[‘agent’\]”](#type--literalagent-1) #### updated\_at *: datetime | None* [Section titled “updated\_at : datetime | None”](#updated_at--datetime--none-2) ### *class* prefactor\_http.models.AgentVersionForRegister(, name: str | None = None, external\_identifier: str | None = None, description: str | None = None, runtime\_environment: [RuntimeEnvironment](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RuntimeEnvironment) | None = None) [Section titled “class prefactor\_http.models.AgentVersionForRegister(, name: str | None = None, external\_identifier: str | None = None, description: str | None = None, runtime\_environment: RuntimeEnvironment | None = None)”](#class-prefactor_httpmodelsagentversionforregister-name-str--none--none-external_identifier-str--none--none-description-str--none--none-runtime_environment-runtimeenvironment--none--none) Bases: `BaseModel` Agent version information for registration. #### name [Section titled “name”](#name-5) Name of the agent version * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier-5) External identifier for the version (e.g., “v1.0.0”) * **Type:** str | None #### description [Section titled “description”](#description-4) Optional description of the version * **Type:** str | None #### runtime\_environment [Section titled “runtime\_environment”](#runtime_environment) Runtime environment metadata * **Type:** [RuntimeEnvironment](#prefactor_http.models.RuntimeEnvironment) | None #### description *: str | None* [Section titled “description : str | None”](#description--str--none-4) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none-5) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---12) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str | None* [Section titled “name : str | None”](#name--str--none-1) #### runtime\_environment *: [RuntimeEnvironment](#prefactor_http.models.RuntimeEnvironment) | None* [Section titled “runtime\_environment : RuntimeEnvironment | None”](#runtime_environment--runtimeenvironment--none) ### *class* prefactor\_http.models.ApiResponse(, status: str, details: T) [Section titled “class prefactor\_http.models.ApiResponse(, status: str, details: T)”](#class-prefactor_httpmodelsapiresponse-status-str-details-t) Bases: `BaseModel`, `Generic`\[`T`] Generic API response wrapper. #### status [Section titled “status”](#status-4) Response status (always “success” for successful requests) * **Type:** str #### details [Section titled “details”](#details) Detailed response data * **Type:** prefactor\_http.models.base.T #### details *: T* [Section titled “details : T”](#details--t) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---13) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### status *: str* [Section titled “status : str”](#status--str) ### *class* prefactor\_http.models.BulkItem(, \_type: str, idempotency\_key: Annotated\[str, MinLen(min\_length=8), MaxLen(max\_length=64)], \*\*extra\_data: Any) [Section titled “class prefactor\_http.models.BulkItem(, \_type: str, idempotency\_key: Annotated\[str, MinLen(min\_length=8), MaxLen(max\_length=64)\], \*\*extra\_data: Any)”](#class-prefactor_httpmodelsbulkitem-_type-str-idempotency_key-annotatedstr-minlenmin_length8-maxlenmax_length64-extra_data-any) Bases: `BaseModel` A single item in a bulk request. Each item must include \_type and idempotency\_key, plus any additional parameters required by the specific action type. #### idempotency\_key *: str* [Section titled “idempotency\_key : str”](#idempotency_key--str) Required unique idempotency key for this item. Must be at least 8 characters long and unique within the request. #### model\_config *= {‘extra’: ‘allow’}* [Section titled “model\_config = {‘extra’: ‘allow’}”](#model_config--extra-allow) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### type *: str* [Section titled “type : str”](#type--str) The type of query/action to execute (e.g., ‘agents/list’, ‘agents/create’). ### *class* prefactor\_http.models.BulkOutput(, status: str, \*\*extra\_data: Any) [Section titled “class prefactor\_http.models.BulkOutput(, status: str, \*\*extra\_data: Any)”](#class-prefactor_httpmodelsbulkoutput-status-str-extra_data-any) Bases: `BaseModel` Output from a query or action. Contains either a success response (with ‘status’: ‘success’ and operation-specific data) or an error response (with ‘status’: ‘error’, ‘code’, ‘message’, and optionally ‘errors’). #### model\_config *= {‘extra’: ‘allow’}* [Section titled “model\_config = {‘extra’: ‘allow’}”](#model_config--extra-allow-1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### status *: str* [Section titled “status : str”](#status--str-1) ‘success’ or ‘error’. * **Type:** Status of the operation #### *classmethod* validate\_status(v: str) → str [Section titled “classmethod validate\_status(v: str) → str”](#classmethod-validate_statusv-str--str) ### *class* prefactor\_http.models.BulkRequest(, items: Annotated\[list\[[BulkItem](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem)], MinLen(min\_length=1)]) [Section titled “class prefactor\_http.models.BulkRequest(, items: Annotated\[list\[BulkItem\], MinLen(min\_length=1)\])”](#class-prefactor_httpmodelsbulkrequest-items-annotatedlistbulkitem-minlenmin_length1) Bases: `BaseModel` Request body for bulk query/action operations. Allows executing multiple API operations in a single request. #### items *: list\[[BulkItem](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem)]* [Section titled “items : list\[BulkItem\]”](#items--listbulkitem) List of items to process in bulk. Each item will be processed independently in its own transaction. #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---14) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### *classmethod* validate\_unique\_idempotency\_keys(items: list\[[BulkItem](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem)]) → list\[[BulkItem](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem)] [Section titled “classmethod validate\_unique\_idempotency\_keys(items: list\[BulkItem\]) → list\[BulkItem\]”](#classmethod-validate_unique_idempotency_keysitems-listbulkitem--listbulkitem) Validate that all idempotency keys are unique within the request. ### *class* prefactor\_http.models.BulkResponse(, status: str = ‘success’, outputs: dict\[str, [BulkOutput](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkOutput)]) [Section titled “class prefactor\_http.models.BulkResponse(, status: str = ‘success’, outputs: dict\[str, BulkOutput\])”](#class-prefactor_httpmodelsbulkresponse-status-str--success-outputs-dictstr-bulkoutput) Bases: `BaseModel` Response from bulk query/action operations. Contains a map of results keyed by the idempotency\_key from each request item. #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---15) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### outputs *: dict\[str, [BulkOutput](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkOutput)]* [Section titled “outputs : dict\[str, BulkOutput\]”](#outputs--dictstr-bulkoutput) Map where keys are the idempotency\_key values from the request, and values are the corresponding query/action outputs or error responses. #### status *: str* [Section titled “status : str”](#status--str-2) Response status, always ‘success’ when the request is processed. ### *class* prefactor\_http.models.DataCategories(, personal\_identifiers: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, contact\_information: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, financial\_information: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, health\_and\_medical: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, criminal\_justice: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, authentication\_and\_secrets: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, organisational\_confidential: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, minors\_data: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, location\_and\_tracking: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, behavioural\_and\_inferred: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_racial\_or\_ethnic\_origin: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_political\_opinions: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_religious\_or\_philosophical\_beliefs: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_trade\_union\_membership: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_genetic\_data: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_biometric\_for\_identification: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_sex\_life\_or\_sexual\_orientation: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, classification: Literal\[‘unknown’, ‘public’, ‘internal’, ‘confidential’, ‘restricted’, ‘secret’] = ‘unknown’) [Section titled “class prefactor\_http.models.DataCategories(, personal\_identifiers: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, contact\_information: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, financial\_information: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, health\_and\_medical: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, criminal\_justice: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, authentication\_and\_secrets: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, organisational\_confidential: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, minors\_data: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, location\_and\_tracking: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, behavioural\_and\_inferred: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_racial\_or\_ethnic\_origin: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_political\_opinions: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_religious\_or\_philosophical\_beliefs: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_trade\_union\_membership: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_genetic\_data: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_biometric\_for\_identification: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_sex\_life\_or\_sexual\_orientation: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, classification: Literal\[‘unknown’, ‘public’, ‘internal’, ‘confidential’, ‘restricted’, ‘secret’\] = ‘unknown’)”](#class-prefactor_httpmodelsdatacategories-personal_identifiers-literalunknown-included-excluded--unknown-contact_information-literalunknown-included-excluded--unknown-financial_information-literalunknown-included-excluded--unknown-health_and_medical-literalunknown-included-excluded--unknown-criminal_justice-literalunknown-included-excluded--unknown-authentication_and_secrets-literalunknown-included-excluded--unknown-organisational_confidential-literalunknown-included-excluded--unknown-minors_data-literalunknown-included-excluded--unknown-location_and_tracking-literalunknown-included-excluded--unknown-behavioural_and_inferred-literalunknown-included-excluded--unknown-gdpr_racial_or_ethnic_origin-literalunknown-included-excluded--unknown-gdpr_political_opinions-literalunknown-included-excluded--unknown-gdpr_religious_or_philosophical_beliefs-literalunknown-included-excluded--unknown-gdpr_trade_union_membership-literalunknown-included-excluded--unknown-gdpr_genetic_data-literalunknown-included-excluded--unknown-gdpr_biometric_for_identification-literalunknown-included-excluded--unknown-gdpr_sex_life_or_sexual_orientation-literalunknown-included-excluded--unknown-classification-literalunknown-public-internal-confidential-restricted-secret--unknown) Bases: `BaseModel` Data categories present in span data. #### personal\_identifiers [Section titled “personal\_identifiers”](#personal_identifiers) Personal identifiers present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### contact\_information [Section titled “contact\_information”](#contact_information) Contact information present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### financial\_information [Section titled “financial\_information”](#financial_information) Financial information present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### health\_and\_medical [Section titled “health\_and\_medical”](#health_and_medical) Health and medical data present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### criminal\_justice [Section titled “criminal\_justice”](#criminal_justice) Criminal justice data present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### authentication\_and\_secrets [Section titled “authentication\_and\_secrets”](#authentication_and_secrets) Authentication and secrets present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### organisational\_confidential [Section titled “organisational\_confidential”](#organisational_confidential) Organisational confidential data present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### minors\_data [Section titled “minors\_data”](#minors_data) Minors data present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### location\_and\_tracking [Section titled “location\_and\_tracking”](#location_and_tracking) Location and tracking data present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### behavioural\_and\_inferred [Section titled “behavioural\_and\_inferred”](#behavioural_and_inferred) Behavioural and inferred data present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_racial\_or\_ethnic\_origin [Section titled “gdpr\_racial\_or\_ethnic\_origin”](#gdpr_racial_or_ethnic_origin) GDPR: racial or ethnic origin * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_political\_opinions [Section titled “gdpr\_political\_opinions”](#gdpr_political_opinions) GDPR: political opinions * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_religious\_or\_philosophical\_beliefs [Section titled “gdpr\_religious\_or\_philosophical\_beliefs”](#gdpr_religious_or_philosophical_beliefs) GDPR: religious or philosophical beliefs * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_trade\_union\_membership [Section titled “gdpr\_trade\_union\_membership”](#gdpr_trade_union_membership) GDPR: trade union membership * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_genetic\_data [Section titled “gdpr\_genetic\_data”](#gdpr_genetic_data) GDPR: genetic data * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_biometric\_for\_identification [Section titled “gdpr\_biometric\_for\_identification”](#gdpr_biometric_for_identification) GDPR: biometric data for identification * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_sex\_life\_or\_sexual\_orientation [Section titled “gdpr\_sex\_life\_or\_sexual\_orientation”](#gdpr_sex_life_or_sexual_orientation) GDPR: sex life or sexual orientation * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### classification [Section titled “classification”](#classification) Classification level (unknown, public, internal, confidential, restricted, secret) * **Type:** Literal\[‘unknown’, ‘public’, ‘internal’, ‘confidential’, ‘restricted’, ‘secret’] #### authentication\_and\_secrets *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “authentication\_and\_secrets : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#authentication_and_secrets--literalunknown-included-excluded) #### behavioural\_and\_inferred *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “behavioural\_and\_inferred : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#behavioural_and_inferred--literalunknown-included-excluded) #### classification *: Literal\[‘unknown’, ‘public’, ‘internal’, ‘confidential’, ‘restricted’, ‘secret’]* [Section titled “classification : Literal\[‘unknown’, ‘public’, ‘internal’, ‘confidential’, ‘restricted’, ‘secret’\]”](#classification--literalunknown-public-internal-confidential-restricted-secret) #### contact\_information *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “contact\_information : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#contact_information--literalunknown-included-excluded) #### criminal\_justice *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “criminal\_justice : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#criminal_justice--literalunknown-included-excluded) #### financial\_information *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “financial\_information : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#financial_information--literalunknown-included-excluded) #### gdpr\_biometric\_for\_identification *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_biometric\_for\_identification : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_biometric_for_identification--literalunknown-included-excluded) #### gdpr\_genetic\_data *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_genetic\_data : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_genetic_data--literalunknown-included-excluded) #### gdpr\_political\_opinions *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_political\_opinions : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_political_opinions--literalunknown-included-excluded) #### gdpr\_racial\_or\_ethnic\_origin *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_racial\_or\_ethnic\_origin : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_racial_or_ethnic_origin--literalunknown-included-excluded) #### gdpr\_religious\_or\_philosophical\_beliefs *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_religious\_or\_philosophical\_beliefs : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_religious_or_philosophical_beliefs--literalunknown-included-excluded) #### gdpr\_sex\_life\_or\_sexual\_orientation *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_sex\_life\_or\_sexual\_orientation : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_sex_life_or_sexual_orientation--literalunknown-included-excluded) #### gdpr\_trade\_union\_membership *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_trade\_union\_membership : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_trade_union_membership--literalunknown-included-excluded) #### health\_and\_medical *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “health\_and\_medical : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#health_and_medical--literalunknown-included-excluded) #### location\_and\_tracking *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “location\_and\_tracking : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#location_and_tracking--literalunknown-included-excluded) #### minors\_data *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “minors\_data : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#minors_data--literalunknown-included-excluded) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---16) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### organisational\_confidential *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “organisational\_confidential : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#organisational_confidential--literalunknown-included-excluded) #### personal\_identifiers *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “personal\_identifiers : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#personal_identifiers--literalunknown-included-excluded) ### *class* prefactor\_http.models.DataRisk(, action\_profile: [ActionProfile](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.ActionProfile), params\_data\_categories: [DataCategories](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories), result\_data\_categories: [DataCategories](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories), \*\*extra\_data: Any) [Section titled “class prefactor\_http.models.DataRisk(, action\_profile: ActionProfile, params\_data\_categories: DataCategories, result\_data\_categories: DataCategories, \*\*extra\_data: Any)”](#class-prefactor_httpmodelsdatarisk-action_profile-actionprofile-params_data_categories-datacategories-result_data_categories-datacategories-extra_data-any) Bases: `BaseModel` Data risk specification for a span type. #### action\_profile [Section titled “action\_profile”](#action_profile) Actions this span performs * **Type:** [ActionProfile](#prefactor_http.models.ActionProfile) #### params\_data\_categories [Section titled “params\_data\_categories”](#params_data_categories) Data categories present in params * **Type:** [DataCategories](#prefactor_http.models.DataCategories) #### result\_data\_categories [Section titled “result\_data\_categories”](#result_data_categories) Data categories present in result * **Type:** [DataCategories](#prefactor_http.models.DataCategories) #### action\_profile *: [ActionProfile](#prefactor_http.models.ActionProfile)* [Section titled “action\_profile : ActionProfile”](#action_profile--actionprofile) #### model\_config *= {‘extra’: ‘allow’}* [Section titled “model\_config = {‘extra’: ‘allow’}”](#model_config--extra-allow-2) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### params\_data\_categories *: [DataCategories](#prefactor_http.models.DataCategories)* [Section titled “params\_data\_categories : DataCategories”](#params_data_categories--datacategories) #### result\_data\_categories *: [DataCategories](#prefactor_http.models.DataCategories)* [Section titled “result\_data\_categories : DataCategories”](#result_data_categories--datacategories) ### *class* prefactor\_http.models.FinishInstanceRequest(, status: Literal\[‘complete’, ‘failed’, ‘cancelled’] | None = None, timestamp: str | None = None, idempotency\_key: str | None = None) [Section titled “class prefactor\_http.models.FinishInstanceRequest(, status: Literal\[‘complete’, ‘failed’, ‘cancelled’\] | None = None, timestamp: str | None = None, idempotency\_key: str | None = None)”](#class-prefactor_httpmodelsfinishinstancerequest-status-literalcomplete-failed-cancelled--none--none-timestamp-str--none--none-idempotency_key-str--none--none) Bases: `BaseModel` Request to finish an agent instance. #### status [Section titled “status”](#status-5) Optional finish status (complete, failed, cancelled) * **Type:** FinishStatus | None #### timestamp [Section titled “timestamp”](#timestamp) Optional ISO 8601 timestamp (defaults to current time) * **Type:** str | None #### idempotency\_key [Section titled “idempotency\_key”](#idempotency_key) Optional idempotency key * **Type:** str | None #### idempotency\_key *: str | None* [Section titled “idempotency\_key : str | None”](#idempotency_key--str--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---17) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### status *: FinishStatus | None* [Section titled “status : FinishStatus | None”](#status--finishstatus--none) #### timestamp *: str | None* [Section titled “timestamp : str | None”](#timestamp--str--none) ### *class* prefactor\_http.models.QualitySchemaDetails(, name: str, title: str, description: str | None = None, template: str | None = None, data\_risk: [DataRisk](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataRisk), schema: dict, schema\_validation: dict) [Section titled “class prefactor\_http.models.QualitySchemaDetails(, name: str, title: str, description: str | None = None, template: str | None = None, data\_risk: DataRisk, schema: dict, schema\_validation: dict)”](#class-prefactor_httpmodelsqualityschemadetails-name-str-title-str-description-str--none--none-template-str--none--none-data_risk-datarisk-schema-dict-schema_validation-dict) Bases: `BaseModel` Quality schema details returned in agent schema version responses. #### name [Section titled “name”](#name-6) Unique identifier for this quality schema entry * **Type:** str #### title [Section titled “title”](#title) Human-readable title * **Type:** str #### description [Section titled “description”](#description-5) Optional description * **Type:** str | None #### template [Section titled “template”](#template) Optional display template * **Type:** str | None #### data\_risk [Section titled “data\_risk”](#data_risk) Data risk classification * **Type:** [DataRisk](#prefactor_http.models.DataRisk) #### schema [Section titled “schema”](#schema) JSON schema for the quality payload #### schema\_validation [Section titled “schema\_validation”](#schema_validation) Schema validation result * **Type:** dict #### data\_risk *: [DataRisk](#prefactor_http.models.DataRisk)* [Section titled “data\_risk : DataRisk”](#data_risk--datarisk) #### description *: str | None* [Section titled “description : str | None”](#description--str--none-5) #### model\_config *= {‘populate\_by\_name’: True, ‘validate\_by\_alias’: True, ‘validate\_by\_name’: True}* [Section titled “model\_config = {‘populate\_by\_name’: True, ‘validate\_by\_alias’: True, ‘validate\_by\_name’: True}”](#model_config--populate_by_name-true-validate_by_alias-true-validate_by_name-true) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-4) #### schema\_ *: dict* [Section titled “schema\_ : dict”](#schema_--dict) #### schema\_validation *: dict* [Section titled “schema\_validation : dict”](#schema_validation--dict) #### template *: str | None* [Section titled “template : str | None”](#template--str--none) #### title *: str* [Section titled “title : str”](#title--str) ### *class* prefactor\_http.models.QualitySchemaForCreate(, name: str, schema: dict, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: [DataRisk](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataRisk) | None = None) [Section titled “class prefactor\_http.models.QualitySchemaForCreate(, name: str, schema: dict, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: DataRisk | None = None)”](#class-prefactor_httpmodelsqualityschemaforcreate-name-str-schema-dict-title-str--none--none-description-str--none--none-template-str--none--none-data_risk-datarisk--none--none) Bases: `BaseModel` Named quality schema definition for agent schema version registration. #### name [Section titled “name”](#name-7) Unique identifier for this quality schema entry * **Type:** str #### schema [Section titled “schema”](#schema-1) JSON schema for the quality payload #### title [Section titled “title”](#title-1) Optional human-readable title (defaults to name) * **Type:** str | None #### description [Section titled “description”](#description-6) Optional description * **Type:** str | None #### template [Section titled “template”](#template-1) Optional display template using `{{field}}` interpolation * **Type:** str | None #### data\_risk [Section titled “data\_risk”](#data_risk-1) Optional data risk classification * **Type:** [DataRisk](#prefactor_http.models.DataRisk) | None #### data\_risk *: [DataRisk](#prefactor_http.models.DataRisk) | None* [Section titled “data\_risk : DataRisk | None”](#data_risk--datarisk--none) #### description *: str | None* [Section titled “description : str | None”](#description--str--none-6) #### model\_config *= {‘populate\_by\_name’: True, ‘validate\_by\_alias’: True, ‘validate\_by\_name’: True}* [Section titled “model\_config = {‘populate\_by\_name’: True, ‘validate\_by\_alias’: True, ‘validate\_by\_name’: True}”](#model_config--populate_by_name-true-validate_by_alias-true-validate_by_name-true-1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-5) #### schema\_ *: dict* [Section titled “schema\_ : dict”](#schema_--dict-1) #### template *: str | None* [Section titled “template : str | None”](#template--str--none-1) #### title *: str | None* [Section titled “title : str | None”](#title--str--none) ### *class* prefactor\_http.models.RuntimeEnvironment(, agent\_sdk: list\[str] | None = None, os: str | None = None, prefactor\_sdk: list\[str] | None = None, runtime: str | None = None) [Section titled “class prefactor\_http.models.RuntimeEnvironment(, agent\_sdk: list\[str\] | None = None, os: str | None = None, prefactor\_sdk: list\[str\] | None = None, runtime: str | None = None)”](#class-prefactor_httpmodelsruntimeenvironment-agent_sdk-liststr--none--none-os-str--none--none-prefactor_sdk-liststr--none--none-runtime-str--none--none) Bases: `BaseModel` Runtime environment information for an agent version. Captures the agent framework, Prefactor SDK, OS, and language runtime in use when this agent version was registered. #### agent\_sdk [Section titled “agent\_sdk”](#agent_sdk) Agent framework packages (e.g. \[””]). * **Type:** list\[str] | None #### os [Section titled “os”](#os) Operating system name (e.g. “linux”, “darwin”). * **Type:** str | None #### prefactor\_sdk [Section titled “prefactor\_sdk”](#prefactor_sdk) Prefactor SDK packages in use. * **Type:** list\[str] | None #### runtime [Section titled “runtime”](#runtime) Language runtime (e.g. “”). * **Type:** str | None #### agent\_sdk *: list\[str] | None* [Section titled “agent\_sdk : list\[str\] | None”](#agent_sdk--liststr--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---18) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### os *: str | None* [Section titled “os : str | None”](#os--str--none) #### prefactor\_sdk *: list\[str] | None* [Section titled “prefactor\_sdk : list\[str\] | None”](#prefactor_sdk--liststr--none) #### runtime *: str | None* [Section titled “runtime : str | None”](#runtime--str--none) ### *class* prefactor\_http.models.SpanTypeSchemaForCreate(, name: str, params\_schema: dict, result\_schema: dict | None = None, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: [DataRisk](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataRisk) | None = None) [Section titled “class prefactor\_http.models.SpanTypeSchemaForCreate(, name: str, params\_schema: dict, result\_schema: dict | None = None, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: DataRisk | None = None)”](#class-prefactor_httpmodelsspantypeschemaforcreate-name-str-params_schema-dict-result_schema-dict--none--none-title-str--none--none-description-str--none--none-template-str--none--none-data_risk-datarisk--none--none) Bases: `BaseModel` Span type schema details for registration. #### name [Section titled “name”](#name-8) Name of the span type * **Type:** str #### params\_schema [Section titled “params\_schema”](#params_schema) JSON schema for span parameters * **Type:** dict #### result\_schema [Section titled “result\_schema”](#result_schema) Optional JSON schema for span results * **Type:** dict | None #### title [Section titled “title”](#title-2) Optional human-readable title * **Type:** str | None #### description [Section titled “description”](#description-7) Optional description * **Type:** str | None #### template [Section titled “template”](#template-2) Optional template string * **Type:** str | None #### data\_risk [Section titled “data\_risk”](#data_risk-2) Optional data risk classification * **Type:** [DataRisk](#prefactor_http.models.DataRisk) | None #### data\_risk *: [DataRisk](#prefactor_http.models.DataRisk) | None* [Section titled “data\_risk : DataRisk | None”](#data_risk--datarisk--none-1) #### description *: str | None* [Section titled “description : str | None”](#description--str--none-7) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---19) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-6) #### params\_schema *: dict* [Section titled “params\_schema : dict”](#params_schema--dict) #### result\_schema *: dict | None* [Section titled “result\_schema : dict | None”](#result_schema--dict--none) #### template *: str | None* [Section titled “template : str | None”](#template--str--none-2) #### title *: str | None* [Section titled “title : str | None”](#title--str--none-1) ## Submodules [Section titled “Submodules”](#submodules) * [prefactor\_http.models.agent module](prefactor_http.models.agent.md) * [`Agent`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent) * [`Agent.type`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.type) * [`Agent.id`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.id) * [`Agent.name`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.name) * [`Agent.description`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.description) * [`Agent.external_identifier`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.external_identifier) * [`Agent.status`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.status) * [`Agent.owner_person_id`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.owner_person_id) * [`Agent.risk_profile_id`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.risk_profile_id) * [`Agent.team_id`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.team_id) * [`Agent.instance_counts`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.instance_counts) * [`Agent.available_actions`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.available_actions) * [`Agent.inserted_at`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.inserted_at) * [`Agent.updated_at`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.updated_at) * [`Agent.available_actions`](prefactor_http.models.agent.md#id0) * [`Agent.description`](prefactor_http.models.agent.md#id1) * [`Agent.external_identifier`](prefactor_http.models.agent.md#id2) * [`Agent.id`](prefactor_http.models.agent.md#id3) * [`Agent.inserted_at`](prefactor_http.models.agent.md#id4) * [`Agent.instance_counts`](prefactor_http.models.agent.md#id5) * [`Agent.model_config`](prefactor_http.models.agent.md#prefactor_http.models.agent.Agent.model_config) * [`Agent.name`](prefactor_http.models.agent.md#id6) * [`Agent.owner_person_id`](prefactor_http.models.agent.md#id7) * [`Agent.risk_profile_id`](prefactor_http.models.agent.md#id8) * [`Agent.status`](prefactor_http.models.agent.md#id9) * [`Agent.team_id`](prefactor_http.models.agent.md#id10) * [`Agent.type`](prefactor_http.models.agent.md#id11) * [`Agent.updated_at`](prefactor_http.models.agent.md#id12) * [`AgentAvailableActions`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentAvailableActions) * [`AgentAvailableActions.update`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentAvailableActions.update) * [`AgentAvailableActions.retire`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentAvailableActions.retire) * [`AgentAvailableActions.reinstate`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentAvailableActions.reinstate) * [`AgentAvailableActions.delete`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentAvailableActions.delete) * [`AgentAvailableActions.delete`](prefactor_http.models.agent.md#id13) * [`AgentAvailableActions.model_config`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentAvailableActions.model_config) * [`AgentAvailableActions.reinstate`](prefactor_http.models.agent.md#id14) * [`AgentAvailableActions.retire`](prefactor_http.models.agent.md#id15) * [`AgentAvailableActions.update`](prefactor_http.models.agent.md#id16) * [`AgentForCreate`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForCreate) * [`AgentForCreate.name`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForCreate.name) * [`AgentForCreate.description`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForCreate.description) * [`AgentForCreate.external_identifier`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForCreate.external_identifier) * [`AgentForCreate.id`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForCreate.id) * [`AgentForCreate.owner_person_id`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForCreate.owner_person_id) * [`AgentForCreate.risk_profile_id`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForCreate.risk_profile_id) * [`AgentForCreate.team_id`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForCreate.team_id) * [`AgentForCreate.description`](prefactor_http.models.agent.md#id17) * [`AgentForCreate.external_identifier`](prefactor_http.models.agent.md#id18) * [`AgentForCreate.id`](prefactor_http.models.agent.md#id19) * [`AgentForCreate.model_config`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForCreate.model_config) * [`AgentForCreate.name`](prefactor_http.models.agent.md#id20) * [`AgentForCreate.owner_person_id`](prefactor_http.models.agent.md#id21) * [`AgentForCreate.risk_profile_id`](prefactor_http.models.agent.md#id22) * [`AgentForCreate.team_id`](prefactor_http.models.agent.md#id23) * [`AgentForUpdate`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForUpdate) * [`AgentForUpdate.name`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForUpdate.name) * [`AgentForUpdate.description`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForUpdate.description) * [`AgentForUpdate.owner_person_id`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForUpdate.owner_person_id) * [`AgentForUpdate.risk_profile_id`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForUpdate.risk_profile_id) * [`AgentForUpdate.team_id`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForUpdate.team_id) * [`AgentForUpdate.description`](prefactor_http.models.agent.md#id24) * [`AgentForUpdate.model_config`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentForUpdate.model_config) * [`AgentForUpdate.name`](prefactor_http.models.agent.md#id25) * [`AgentForUpdate.owner_person_id`](prefactor_http.models.agent.md#id26) * [`AgentForUpdate.risk_profile_id`](prefactor_http.models.agent.md#id27) * [`AgentForUpdate.team_id`](prefactor_http.models.agent.md#id28) * [`AgentInstanceCounts`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentInstanceCounts) * [`AgentInstanceCounts.total`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentInstanceCounts.total) * [`AgentInstanceCounts.pending`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentInstanceCounts.pending) * [`AgentInstanceCounts.active`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentInstanceCounts.active) * [`AgentInstanceCounts.complete`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentInstanceCounts.complete) * [`AgentInstanceCounts.failed`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentInstanceCounts.failed) * [`AgentInstanceCounts.cancelled`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentInstanceCounts.cancelled) * [`AgentInstanceCounts.terminated`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentInstanceCounts.terminated) * [`AgentInstanceCounts.finished`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentInstanceCounts.finished) * [`AgentInstanceCounts.active`](prefactor_http.models.agent.md#id29) * [`AgentInstanceCounts.cancelled`](prefactor_http.models.agent.md#id30) * [`AgentInstanceCounts.complete`](prefactor_http.models.agent.md#id31) * [`AgentInstanceCounts.failed`](prefactor_http.models.agent.md#id32) * [`AgentInstanceCounts.finished`](prefactor_http.models.agent.md#id33) * [`AgentInstanceCounts.model_config`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentInstanceCounts.model_config) * [`AgentInstanceCounts.pending`](prefactor_http.models.agent.md#id34) * [`AgentInstanceCounts.terminated`](prefactor_http.models.agent.md#id35) * [`AgentInstanceCounts.total`](prefactor_http.models.agent.md#id36) * [`AgentSummary`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary) * [`AgentSummary.type`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary.type) * [`AgentSummary.id`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary.id) * [`AgentSummary.name`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary.name) * [`AgentSummary.description`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary.description) * [`AgentSummary.external_identifier`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary.external_identifier) * [`AgentSummary.status`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary.status) * [`AgentSummary.owner_person_id`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary.owner_person_id) * [`AgentSummary.team_id`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary.team_id) * [`AgentSummary.available_actions`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary.available_actions) * [`AgentSummary.inserted_at`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary.inserted_at) * [`AgentSummary.updated_at`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary.updated_at) * [`AgentSummary.available_actions`](prefactor_http.models.agent.md#id37) * [`AgentSummary.description`](prefactor_http.models.agent.md#id38) * [`AgentSummary.external_identifier`](prefactor_http.models.agent.md#id39) * [`AgentSummary.id`](prefactor_http.models.agent.md#id40) * [`AgentSummary.inserted_at`](prefactor_http.models.agent.md#id41) * [`AgentSummary.model_config`](prefactor_http.models.agent.md#prefactor_http.models.agent.AgentSummary.model_config) * [`AgentSummary.name`](prefactor_http.models.agent.md#id42) * [`AgentSummary.owner_person_id`](prefactor_http.models.agent.md#id43) * [`AgentSummary.status`](prefactor_http.models.agent.md#id44) * [`AgentSummary.team_id`](prefactor_http.models.agent.md#id45) * [`AgentSummary.type`](prefactor_http.models.agent.md#id46) * [`AgentSummary.updated_at`](prefactor_http.models.agent.md#id47) * [prefactor\_http.models.agent\_instance module](prefactor_http.models.agent_instance.md) * [`ActionProfile`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.ActionProfile) * [`ActionProfile.create_data`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.ActionProfile.create_data) * [`ActionProfile.read_data`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.ActionProfile.read_data) * [`ActionProfile.update_data`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.ActionProfile.update_data) * [`ActionProfile.destroy_data`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.ActionProfile.destroy_data) * [`ActionProfile.financial_transactions`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.ActionProfile.financial_transactions) * [`ActionProfile.external_communication`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.ActionProfile.external_communication) * [`ActionProfile.create_data`](prefactor_http.models.agent_instance.md#id0) * [`ActionProfile.destroy_data`](prefactor_http.models.agent_instance.md#id1) * [`ActionProfile.external_communication`](prefactor_http.models.agent_instance.md#id2) * [`ActionProfile.financial_transactions`](prefactor_http.models.agent_instance.md#id3) * [`ActionProfile.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.ActionProfile.model_config) * [`ActionProfile.read_data`](prefactor_http.models.agent_instance.md#id4) * [`ActionProfile.update_data`](prefactor_http.models.agent_instance.md#id5) * [`AgentInstance`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance) * [`AgentInstance.type`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.type) * [`AgentInstance.id`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.id) * [`AgentInstance.account_id`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.account_id) * [`AgentInstance.agent_id`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.agent_id) * [`AgentInstance.agent_version_id`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.agent_version_id) * [`AgentInstance.environment_id`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.environment_id) * [`AgentInstance.agent_deployment_id`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.agent_deployment_id) * [`AgentInstance.status`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.status) * [`AgentInstance.inserted_at`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.inserted_at) * [`AgentInstance.updated_at`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.updated_at) * [`AgentInstance.started_at`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.started_at) * [`AgentInstance.finished_at`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.finished_at) * [`AgentInstance.termination_reason`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.termination_reason) * [`AgentInstance.external_identifier`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.external_identifier) * [`AgentInstance.span_counts`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.span_counts) * [`AgentInstance.purpose`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.purpose) * [`AgentInstance.quality_payloads`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.quality_payloads) * [`AgentInstance.quality_summaries`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.quality_summaries) * [`AgentInstance.account_id`](prefactor_http.models.agent_instance.md#id6) * [`AgentInstance.agent_deployment_id`](prefactor_http.models.agent_instance.md#id7) * [`AgentInstance.agent_id`](prefactor_http.models.agent_instance.md#id8) * [`AgentInstance.agent_version_id`](prefactor_http.models.agent_instance.md#id9) * [`AgentInstance.environment_id`](prefactor_http.models.agent_instance.md#id10) * [`AgentInstance.external_identifier`](prefactor_http.models.agent_instance.md#id11) * [`AgentInstance.finished_at`](prefactor_http.models.agent_instance.md#id12) * [`AgentInstance.id`](prefactor_http.models.agent_instance.md#id13) * [`AgentInstance.inserted_at`](prefactor_http.models.agent_instance.md#id14) * [`AgentInstance.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstance.model_config) * [`AgentInstance.purpose`](prefactor_http.models.agent_instance.md#id15) * [`AgentInstance.quality_payloads`](prefactor_http.models.agent_instance.md#id16) * [`AgentInstance.quality_summaries`](prefactor_http.models.agent_instance.md#id17) * [`AgentInstance.span_counts`](prefactor_http.models.agent_instance.md#id18) * [`AgentInstance.started_at`](prefactor_http.models.agent_instance.md#id19) * [`AgentInstance.status`](prefactor_http.models.agent_instance.md#id20) * [`AgentInstance.termination_reason`](prefactor_http.models.agent_instance.md#id21) * [`AgentInstance.type`](prefactor_http.models.agent_instance.md#id22) * [`AgentInstance.updated_at`](prefactor_http.models.agent_instance.md#id23) * [`AgentInstanceRecordQuality`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceRecordQuality) * [`AgentInstanceRecordQuality.name`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceRecordQuality.name) * [`AgentInstanceRecordQuality.payload`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceRecordQuality.payload) * [`AgentInstanceRecordQuality.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceRecordQuality.model_config) * [`AgentInstanceRecordQuality.name`](prefactor_http.models.agent_instance.md#id24) * [`AgentInstanceRecordQuality.payload`](prefactor_http.models.agent_instance.md#id25) * [`AgentInstanceSpanCounts`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceSpanCounts) * [`AgentInstanceSpanCounts.total`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceSpanCounts.total) * [`AgentInstanceSpanCounts.active`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceSpanCounts.active) * [`AgentInstanceSpanCounts.complete`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceSpanCounts.complete) * [`AgentInstanceSpanCounts.failed`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceSpanCounts.failed) * [`AgentInstanceSpanCounts.cancelled`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceSpanCounts.cancelled) * [`AgentInstanceSpanCounts.finished`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceSpanCounts.finished) * [`AgentInstanceSpanCounts.active`](prefactor_http.models.agent_instance.md#id26) * [`AgentInstanceSpanCounts.cancelled`](prefactor_http.models.agent_instance.md#id27) * [`AgentInstanceSpanCounts.complete`](prefactor_http.models.agent_instance.md#id28) * [`AgentInstanceSpanCounts.failed`](prefactor_http.models.agent_instance.md#id29) * [`AgentInstanceSpanCounts.finished`](prefactor_http.models.agent_instance.md#id30) * [`AgentInstanceSpanCounts.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentInstanceSpanCounts.model_config) * [`AgentInstanceSpanCounts.total`](prefactor_http.models.agent_instance.md#id31) * [`AgentSchemaVersionForRegister`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentSchemaVersionForRegister) * [`AgentSchemaVersionForRegister.external_identifier`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentSchemaVersionForRegister.external_identifier) * [`AgentSchemaVersionForRegister.span_schemas`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentSchemaVersionForRegister.span_schemas) * [`AgentSchemaVersionForRegister.span_result_schemas`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentSchemaVersionForRegister.span_result_schemas) * [`AgentSchemaVersionForRegister.span_type_schemas`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentSchemaVersionForRegister.span_type_schemas) * [`AgentSchemaVersionForRegister.quality_schemas`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentSchemaVersionForRegister.quality_schemas) * [`AgentSchemaVersionForRegister.external_identifier`](prefactor_http.models.agent_instance.md#id32) * [`AgentSchemaVersionForRegister.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentSchemaVersionForRegister.model_config) * [`AgentSchemaVersionForRegister.quality_schemas`](prefactor_http.models.agent_instance.md#id33) * [`AgentSchemaVersionForRegister.span_result_schemas`](prefactor_http.models.agent_instance.md#id34) * [`AgentSchemaVersionForRegister.span_schemas`](prefactor_http.models.agent_instance.md#id35) * [`AgentSchemaVersionForRegister.span_type_schemas`](prefactor_http.models.agent_instance.md#id36) * [`AgentVersionForRegister`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentVersionForRegister) * [`AgentVersionForRegister.name`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentVersionForRegister.name) * [`AgentVersionForRegister.external_identifier`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentVersionForRegister.external_identifier) * [`AgentVersionForRegister.description`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentVersionForRegister.description) * [`AgentVersionForRegister.runtime_environment`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentVersionForRegister.runtime_environment) * [`AgentVersionForRegister.description`](prefactor_http.models.agent_instance.md#id37) * [`AgentVersionForRegister.external_identifier`](prefactor_http.models.agent_instance.md#id38) * [`AgentVersionForRegister.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.AgentVersionForRegister.model_config) * [`AgentVersionForRegister.name`](prefactor_http.models.agent_instance.md#id39) * [`AgentVersionForRegister.runtime_environment`](prefactor_http.models.agent_instance.md#id40) * [`DataCategories`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories) * [`DataCategories.personal_identifiers`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.personal_identifiers) * [`DataCategories.contact_information`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.contact_information) * [`DataCategories.financial_information`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.financial_information) * [`DataCategories.health_and_medical`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.health_and_medical) * [`DataCategories.criminal_justice`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.criminal_justice) * [`DataCategories.authentication_and_secrets`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.authentication_and_secrets) * [`DataCategories.organisational_confidential`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.organisational_confidential) * [`DataCategories.minors_data`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.minors_data) * [`DataCategories.location_and_tracking`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.location_and_tracking) * [`DataCategories.behavioural_and_inferred`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.behavioural_and_inferred) * [`DataCategories.gdpr_racial_or_ethnic_origin`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.gdpr_racial_or_ethnic_origin) * [`DataCategories.gdpr_political_opinions`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.gdpr_political_opinions) * [`DataCategories.gdpr_religious_or_philosophical_beliefs`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.gdpr_religious_or_philosophical_beliefs) * [`DataCategories.gdpr_trade_union_membership`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.gdpr_trade_union_membership) * [`DataCategories.gdpr_genetic_data`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.gdpr_genetic_data) * [`DataCategories.gdpr_biometric_for_identification`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.gdpr_biometric_for_identification) * [`DataCategories.gdpr_sex_life_or_sexual_orientation`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.gdpr_sex_life_or_sexual_orientation) * [`DataCategories.classification`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.classification) * [`DataCategories.authentication_and_secrets`](prefactor_http.models.agent_instance.md#id41) * [`DataCategories.behavioural_and_inferred`](prefactor_http.models.agent_instance.md#id42) * [`DataCategories.classification`](prefactor_http.models.agent_instance.md#id43) * [`DataCategories.contact_information`](prefactor_http.models.agent_instance.md#id44) * [`DataCategories.criminal_justice`](prefactor_http.models.agent_instance.md#id45) * [`DataCategories.financial_information`](prefactor_http.models.agent_instance.md#id46) * [`DataCategories.gdpr_biometric_for_identification`](prefactor_http.models.agent_instance.md#id47) * [`DataCategories.gdpr_genetic_data`](prefactor_http.models.agent_instance.md#id48) * [`DataCategories.gdpr_political_opinions`](prefactor_http.models.agent_instance.md#id49) * [`DataCategories.gdpr_racial_or_ethnic_origin`](prefactor_http.models.agent_instance.md#id50) * [`DataCategories.gdpr_religious_or_philosophical_beliefs`](prefactor_http.models.agent_instance.md#id51) * [`DataCategories.gdpr_sex_life_or_sexual_orientation`](prefactor_http.models.agent_instance.md#id52) * [`DataCategories.gdpr_trade_union_membership`](prefactor_http.models.agent_instance.md#id53) * [`DataCategories.health_and_medical`](prefactor_http.models.agent_instance.md#id54) * [`DataCategories.location_and_tracking`](prefactor_http.models.agent_instance.md#id55) * [`DataCategories.minors_data`](prefactor_http.models.agent_instance.md#id56) * [`DataCategories.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataCategories.model_config) * [`DataCategories.organisational_confidential`](prefactor_http.models.agent_instance.md#id57) * [`DataCategories.personal_identifiers`](prefactor_http.models.agent_instance.md#id58) * [`DataRisk`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataRisk) * [`DataRisk.action_profile`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataRisk.action_profile) * [`DataRisk.params_data_categories`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataRisk.params_data_categories) * [`DataRisk.result_data_categories`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataRisk.result_data_categories) * [`DataRisk.action_profile`](prefactor_http.models.agent_instance.md#id59) * [`DataRisk.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.DataRisk.model_config) * [`DataRisk.params_data_categories`](prefactor_http.models.agent_instance.md#id60) * [`DataRisk.result_data_categories`](prefactor_http.models.agent_instance.md#id61) * [`FinishInstanceRequest`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.FinishInstanceRequest) * [`FinishInstanceRequest.status`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.FinishInstanceRequest.status) * [`FinishInstanceRequest.timestamp`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.FinishInstanceRequest.timestamp) * [`FinishInstanceRequest.idempotency_key`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.FinishInstanceRequest.idempotency_key) * [`FinishInstanceRequest.idempotency_key`](prefactor_http.models.agent_instance.md#id62) * [`FinishInstanceRequest.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.FinishInstanceRequest.model_config) * [`FinishInstanceRequest.status`](prefactor_http.models.agent_instance.md#id63) * [`FinishInstanceRequest.timestamp`](prefactor_http.models.agent_instance.md#id64) * [`QualitySchemaDetails`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaDetails) * [`QualitySchemaDetails.name`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaDetails.name) * [`QualitySchemaDetails.title`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaDetails.title) * [`QualitySchemaDetails.description`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaDetails.description) * [`QualitySchemaDetails.template`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaDetails.template) * [`QualitySchemaDetails.data_risk`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaDetails.data_risk) * [`QualitySchemaDetails.schema`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaDetails.schema) * [`QualitySchemaDetails.schema_validation`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaDetails.schema_validation) * [`QualitySchemaDetails.data_risk`](prefactor_http.models.agent_instance.md#id65) * [`QualitySchemaDetails.description`](prefactor_http.models.agent_instance.md#id66) * [`QualitySchemaDetails.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaDetails.model_config) * [`QualitySchemaDetails.name`](prefactor_http.models.agent_instance.md#id67) * [`QualitySchemaDetails.schema_`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaDetails.schema_) * [`QualitySchemaDetails.schema_validation`](prefactor_http.models.agent_instance.md#id68) * [`QualitySchemaDetails.template`](prefactor_http.models.agent_instance.md#id69) * [`QualitySchemaDetails.title`](prefactor_http.models.agent_instance.md#id70) * [`QualitySchemaForCreate`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaForCreate) * [`QualitySchemaForCreate.name`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaForCreate.name) * [`QualitySchemaForCreate.schema`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaForCreate.schema) * [`QualitySchemaForCreate.title`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaForCreate.title) * [`QualitySchemaForCreate.description`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaForCreate.description) * [`QualitySchemaForCreate.template`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaForCreate.template) * [`QualitySchemaForCreate.data_risk`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaForCreate.data_risk) * [`QualitySchemaForCreate.data_risk`](prefactor_http.models.agent_instance.md#id71) * [`QualitySchemaForCreate.description`](prefactor_http.models.agent_instance.md#id72) * [`QualitySchemaForCreate.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaForCreate.model_config) * [`QualitySchemaForCreate.name`](prefactor_http.models.agent_instance.md#id73) * [`QualitySchemaForCreate.schema_`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.QualitySchemaForCreate.schema_) * [`QualitySchemaForCreate.template`](prefactor_http.models.agent_instance.md#id74) * [`QualitySchemaForCreate.title`](prefactor_http.models.agent_instance.md#id75) * [`RegisterAgentInstanceRequest`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RegisterAgentInstanceRequest) * [`RegisterAgentInstanceRequest.agent_id`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RegisterAgentInstanceRequest.agent_id) * [`RegisterAgentInstanceRequest.environment_id`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RegisterAgentInstanceRequest.environment_id) * [`RegisterAgentInstanceRequest.agent_version`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RegisterAgentInstanceRequest.agent_version) * [`RegisterAgentInstanceRequest.agent_schema_version`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RegisterAgentInstanceRequest.agent_schema_version) * [`RegisterAgentInstanceRequest.id`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RegisterAgentInstanceRequest.id) * [`RegisterAgentInstanceRequest.external_identifier`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RegisterAgentInstanceRequest.external_identifier) * [`RegisterAgentInstanceRequest.idempotency_key`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RegisterAgentInstanceRequest.idempotency_key) * [`RegisterAgentInstanceRequest.update_current_version`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RegisterAgentInstanceRequest.update_current_version) * [`RegisterAgentInstanceRequest.purpose`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RegisterAgentInstanceRequest.purpose) * [`RegisterAgentInstanceRequest.agent_id`](prefactor_http.models.agent_instance.md#id76) * [`RegisterAgentInstanceRequest.agent_schema_version`](prefactor_http.models.agent_instance.md#id77) * [`RegisterAgentInstanceRequest.agent_version`](prefactor_http.models.agent_instance.md#id78) * [`RegisterAgentInstanceRequest.environment_id`](prefactor_http.models.agent_instance.md#id79) * [`RegisterAgentInstanceRequest.external_identifier`](prefactor_http.models.agent_instance.md#id80) * [`RegisterAgentInstanceRequest.id`](prefactor_http.models.agent_instance.md#id81) * [`RegisterAgentInstanceRequest.idempotency_key`](prefactor_http.models.agent_instance.md#id82) * [`RegisterAgentInstanceRequest.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RegisterAgentInstanceRequest.model_config) * [`RegisterAgentInstanceRequest.purpose`](prefactor_http.models.agent_instance.md#id83) * [`RegisterAgentInstanceRequest.update_current_version`](prefactor_http.models.agent_instance.md#id84) * [`RuntimeEnvironment`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RuntimeEnvironment) * [`RuntimeEnvironment.agent_sdk`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RuntimeEnvironment.agent_sdk) * [`RuntimeEnvironment.os`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RuntimeEnvironment.os) * [`RuntimeEnvironment.prefactor_sdk`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RuntimeEnvironment.prefactor_sdk) * [`RuntimeEnvironment.runtime`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RuntimeEnvironment.runtime) * [`RuntimeEnvironment.agent_sdk`](prefactor_http.models.agent_instance.md#id85) * [`RuntimeEnvironment.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.RuntimeEnvironment.model_config) * [`RuntimeEnvironment.os`](prefactor_http.models.agent_instance.md#id86) * [`RuntimeEnvironment.prefactor_sdk`](prefactor_http.models.agent_instance.md#id87) * [`RuntimeEnvironment.runtime`](prefactor_http.models.agent_instance.md#id88) * [`SpanTypeSchemaForCreate`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate) * [`SpanTypeSchemaForCreate.name`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate.name) * [`SpanTypeSchemaForCreate.params_schema`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate.params_schema) * [`SpanTypeSchemaForCreate.result_schema`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate.result_schema) * [`SpanTypeSchemaForCreate.title`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate.title) * [`SpanTypeSchemaForCreate.description`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate.description) * [`SpanTypeSchemaForCreate.template`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate.template) * [`SpanTypeSchemaForCreate.data_risk`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate.data_risk) * [`SpanTypeSchemaForCreate.data_risk`](prefactor_http.models.agent_instance.md#id89) * [`SpanTypeSchemaForCreate.description`](prefactor_http.models.agent_instance.md#id90) * [`SpanTypeSchemaForCreate.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate.model_config) * [`SpanTypeSchemaForCreate.name`](prefactor_http.models.agent_instance.md#id91) * [`SpanTypeSchemaForCreate.params_schema`](prefactor_http.models.agent_instance.md#id92) * [`SpanTypeSchemaForCreate.result_schema`](prefactor_http.models.agent_instance.md#id93) * [`SpanTypeSchemaForCreate.template`](prefactor_http.models.agent_instance.md#id94) * [`SpanTypeSchemaForCreate.title`](prefactor_http.models.agent_instance.md#id95) * [`TimestampRequest`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.TimestampRequest) * [`TimestampRequest.timestamp`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.TimestampRequest.timestamp) * [`TimestampRequest.idempotency_key`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.TimestampRequest.idempotency_key) * [`TimestampRequest.idempotency_key`](prefactor_http.models.agent_instance.md#id96) * [`TimestampRequest.model_config`](prefactor_http.models.agent_instance.md#prefactor_http.models.agent_instance.TimestampRequest.model_config) * [`TimestampRequest.timestamp`](prefactor_http.models.agent_instance.md#id97) * [prefactor\_http.models.agent\_span module](prefactor_http.models.agent_span.md) * [`AgentSpan`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan) * [`AgentSpan.type`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.type) * [`AgentSpan.id`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.id) * [`AgentSpan.account_id`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.account_id) * [`AgentSpan.agent_id`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.agent_id) * [`AgentSpan.agent_instance_id`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.agent_instance_id) * [`AgentSpan.parent_span_id`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.parent_span_id) * [`AgentSpan.schema_name`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.schema_name) * [`AgentSpan.schema_title`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.schema_title) * [`AgentSpan.status`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.status) * [`AgentSpan.payload`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.payload) * [`AgentSpan.result_payload`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.result_payload) * [`AgentSpan.summary`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.summary) * [`AgentSpan.started_at`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.started_at) * [`AgentSpan.inserted_at`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.inserted_at) * [`AgentSpan.updated_at`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.updated_at) * [`AgentSpan.finished_at`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.finished_at) * [`AgentSpan.account_id`](prefactor_http.models.agent_span.md#id0) * [`AgentSpan.agent_id`](prefactor_http.models.agent_span.md#id1) * [`AgentSpan.agent_instance_id`](prefactor_http.models.agent_span.md#id2) * [`AgentSpan.finished_at`](prefactor_http.models.agent_span.md#id3) * [`AgentSpan.id`](prefactor_http.models.agent_span.md#id4) * [`AgentSpan.inserted_at`](prefactor_http.models.agent_span.md#id5) * [`AgentSpan.model_config`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.AgentSpan.model_config) * [`AgentSpan.parent_span_id`](prefactor_http.models.agent_span.md#id6) * [`AgentSpan.payload`](prefactor_http.models.agent_span.md#id7) * [`AgentSpan.result_payload`](prefactor_http.models.agent_span.md#id8) * [`AgentSpan.schema_name`](prefactor_http.models.agent_span.md#id9) * [`AgentSpan.schema_title`](prefactor_http.models.agent_span.md#id10) * [`AgentSpan.started_at`](prefactor_http.models.agent_span.md#id11) * [`AgentSpan.status`](prefactor_http.models.agent_span.md#id12) * [`AgentSpan.summary`](prefactor_http.models.agent_span.md#id13) * [`AgentSpan.type`](prefactor_http.models.agent_span.md#id14) * [`AgentSpan.updated_at`](prefactor_http.models.agent_span.md#id15) * [`CreateAgentSpanRequest`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest) * [`CreateAgentSpanRequest.agent_instance_id`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest.agent_instance_id) * [`CreateAgentSpanRequest.schema_name`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest.schema_name) * [`CreateAgentSpanRequest.status`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest.status) * [`CreateAgentSpanRequest.payload`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest.payload) * [`CreateAgentSpanRequest.result_payload`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest.result_payload) * [`CreateAgentSpanRequest.id`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest.id) * [`CreateAgentSpanRequest.parent_span_id`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest.parent_span_id) * [`CreateAgentSpanRequest.started_at`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest.started_at) * [`CreateAgentSpanRequest.finished_at`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest.finished_at) * [`CreateAgentSpanRequest.idempotency_key`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest.idempotency_key) * [`CreateAgentSpanRequest.agent_instance_id`](prefactor_http.models.agent_span.md#id16) * [`CreateAgentSpanRequest.finished_at`](prefactor_http.models.agent_span.md#id17) * [`CreateAgentSpanRequest.id`](prefactor_http.models.agent_span.md#id18) * [`CreateAgentSpanRequest.idempotency_key`](prefactor_http.models.agent_span.md#id19) * [`CreateAgentSpanRequest.model_config`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.CreateAgentSpanRequest.model_config) * [`CreateAgentSpanRequest.parent_span_id`](prefactor_http.models.agent_span.md#id20) * [`CreateAgentSpanRequest.payload`](prefactor_http.models.agent_span.md#id21) * [`CreateAgentSpanRequest.result_payload`](prefactor_http.models.agent_span.md#id22) * [`CreateAgentSpanRequest.schema_name`](prefactor_http.models.agent_span.md#id23) * [`CreateAgentSpanRequest.started_at`](prefactor_http.models.agent_span.md#id24) * [`CreateAgentSpanRequest.status`](prefactor_http.models.agent_span.md#id25) * [`FinishSpanRequest`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.FinishSpanRequest) * [`FinishSpanRequest.status`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.FinishSpanRequest.status) * [`FinishSpanRequest.result_payload`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.FinishSpanRequest.result_payload) * [`FinishSpanRequest.timestamp`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.FinishSpanRequest.timestamp) * [`FinishSpanRequest.idempotency_key`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.FinishSpanRequest.idempotency_key) * [`FinishSpanRequest.idempotency_key`](prefactor_http.models.agent_span.md#id26) * [`FinishSpanRequest.model_config`](prefactor_http.models.agent_span.md#prefactor_http.models.agent_span.FinishSpanRequest.model_config) * [`FinishSpanRequest.result_payload`](prefactor_http.models.agent_span.md#id27) * [`FinishSpanRequest.status`](prefactor_http.models.agent_span.md#id28) * [`FinishSpanRequest.timestamp`](prefactor_http.models.agent_span.md#id29) * [prefactor\_http.models.base module](prefactor_http.models.base.md) * [`ApiError`](prefactor_http.models.base.md#prefactor_http.models.base.ApiError) * [`ApiError.status`](prefactor_http.models.base.md#prefactor_http.models.base.ApiError.status) * [`ApiError.code`](prefactor_http.models.base.md#prefactor_http.models.base.ApiError.code) * [`ApiError.message`](prefactor_http.models.base.md#prefactor_http.models.base.ApiError.message) * [`ApiError.code`](prefactor_http.models.base.md#id0) * [`ApiError.message`](prefactor_http.models.base.md#id1) * [`ApiError.model_config`](prefactor_http.models.base.md#prefactor_http.models.base.ApiError.model_config) * [`ApiError.status`](prefactor_http.models.base.md#id2) * [`ApiResponse`](prefactor_http.models.base.md#prefactor_http.models.base.ApiResponse) * [`ApiResponse.status`](prefactor_http.models.base.md#prefactor_http.models.base.ApiResponse.status) * [`ApiResponse.details`](prefactor_http.models.base.md#prefactor_http.models.base.ApiResponse.details) * [`ApiResponse.details`](prefactor_http.models.base.md#id3) * [`ApiResponse.model_config`](prefactor_http.models.base.md#prefactor_http.models.base.ApiResponse.model_config) * [`ApiResponse.status`](prefactor_http.models.base.md#id4) * [`DetailedApiError`](prefactor_http.models.base.md#prefactor_http.models.base.DetailedApiError) * [`DetailedApiError.errors`](prefactor_http.models.base.md#prefactor_http.models.base.DetailedApiError.errors) * [`DetailedApiError.errors`](prefactor_http.models.base.md#id5) * [`DetailedApiError.model_config`](prefactor_http.models.base.md#prefactor_http.models.base.DetailedApiError.model_config) * [`ListResponse`](prefactor_http.models.base.md#prefactor_http.models.base.ListResponse) * [`ListResponse.status`](prefactor_http.models.base.md#prefactor_http.models.base.ListResponse.status) * [`ListResponse.summaries`](prefactor_http.models.base.md#prefactor_http.models.base.ListResponse.summaries) * [`ListResponse.pagination`](prefactor_http.models.base.md#prefactor_http.models.base.ListResponse.pagination) * [`ListResponse.sorting`](prefactor_http.models.base.md#prefactor_http.models.base.ListResponse.sorting) * [`ListResponse.model_config`](prefactor_http.models.base.md#prefactor_http.models.base.ListResponse.model_config) * [`ListResponse.pagination`](prefactor_http.models.base.md#id6) * [`ListResponse.sorting`](prefactor_http.models.base.md#id7) * [`ListResponse.status`](prefactor_http.models.base.md#id8) * [`ListResponse.summaries`](prefactor_http.models.base.md#id9) * [`PaginationOutput`](prefactor_http.models.base.md#prefactor_http.models.base.PaginationOutput) * [`PaginationOutput.item_count`](prefactor_http.models.base.md#prefactor_http.models.base.PaginationOutput.item_count) * [`PaginationOutput.item_end`](prefactor_http.models.base.md#prefactor_http.models.base.PaginationOutput.item_end) * [`PaginationOutput.item_start`](prefactor_http.models.base.md#prefactor_http.models.base.PaginationOutput.item_start) * [`PaginationOutput.next_page_offset`](prefactor_http.models.base.md#prefactor_http.models.base.PaginationOutput.next_page_offset) * [`PaginationOutput.page_count`](prefactor_http.models.base.md#prefactor_http.models.base.PaginationOutput.page_count) * [`PaginationOutput.page_index`](prefactor_http.models.base.md#prefactor_http.models.base.PaginationOutput.page_index) * [`PaginationOutput.page_offset`](prefactor_http.models.base.md#prefactor_http.models.base.PaginationOutput.page_offset) * [`PaginationOutput.page_size`](prefactor_http.models.base.md#prefactor_http.models.base.PaginationOutput.page_size) * [`PaginationOutput.previous_page_offset`](prefactor_http.models.base.md#prefactor_http.models.base.PaginationOutput.previous_page_offset) * [`PaginationOutput.item_count`](prefactor_http.models.base.md#id10) * [`PaginationOutput.item_end`](prefactor_http.models.base.md#id11) * [`PaginationOutput.item_start`](prefactor_http.models.base.md#id12) * [`PaginationOutput.model_config`](prefactor_http.models.base.md#prefactor_http.models.base.PaginationOutput.model_config) * [`PaginationOutput.next_page_offset`](prefactor_http.models.base.md#id13) * [`PaginationOutput.page_count`](prefactor_http.models.base.md#id14) * [`PaginationOutput.page_index`](prefactor_http.models.base.md#id15) * [`PaginationOutput.page_offset`](prefactor_http.models.base.md#id16) * [`PaginationOutput.page_size`](prefactor_http.models.base.md#id17) * [`PaginationOutput.previous_page_offset`](prefactor_http.models.base.md#id18) * [`Sorting`](prefactor_http.models.base.md#prefactor_http.models.base.Sorting) * [`Sorting.field`](prefactor_http.models.base.md#prefactor_http.models.base.Sorting.field) * [`Sorting.direction`](prefactor_http.models.base.md#prefactor_http.models.base.Sorting.direction) * [`Sorting.direction`](prefactor_http.models.base.md#id19) * [`Sorting.field`](prefactor_http.models.base.md#id20) * [`Sorting.model_config`](prefactor_http.models.base.md#prefactor_http.models.base.Sorting.model_config) * [prefactor\_http.models.bulk module](prefactor_http.models.bulk.md) * [`BulkItem`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem) * [`BulkItem.idempotency_key`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem.idempotency_key) * [`BulkItem.model_config`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem.model_config) * [`BulkItem.type`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkItem.type) * [`BulkOutput`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkOutput) * [`BulkOutput.model_config`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkOutput.model_config) * [`BulkOutput.status`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkOutput.status) * [`BulkOutput.validate_status()`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkOutput.validate_status) * [`BulkRequest`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkRequest) * [`BulkRequest.items`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkRequest.items) * [`BulkRequest.model_config`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkRequest.model_config) * [`BulkRequest.validate_unique_idempotency_keys()`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkRequest.validate_unique_idempotency_keys) * [`BulkResponse`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkResponse) * [`BulkResponse.model_config`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkResponse.model_config) * [`BulkResponse.outputs`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkResponse.outputs) * [`BulkResponse.status`](prefactor_http.models.bulk.md#prefactor_http.models.bulk.BulkResponse.status) * [prefactor\_http.models.types module](prefactor_http.models.types.md) # prefactor_http.models.agent module # prefactor\_http.models.agent module [Section titled “prefactor\_http.models.agent module”](#prefactor_httpmodelsagent-module) Agent data models. ### *class* prefactor\_http.models.agent.Agent(, type: Literal\[‘agent’], id: str, name: str, description: str | None = None, external\_identifier: str | None = None, status: Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’], owner\_person\_id: str | None = None, risk\_profile\_id: str | None = None, team\_id: str | None = None, instance\_counts: [AgentInstanceCounts](#prefactor_http.models.agent.AgentInstanceCounts) | None = None, available\_actions: [AgentAvailableActions](#prefactor_http.models.agent.AgentAvailableActions) | None = None, inserted\_at: datetime | None = None, updated\_at: datetime | None = None) [Section titled “class prefactor\_http.models.agent.Agent(, type: Literal\[‘agent’\], id: str, name: str, description: str | None = None, external\_identifier: str | None = None, status: Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’\], owner\_person\_id: str | None = None, risk\_profile\_id: str | None = None, team\_id: str | None = None, instance\_counts: AgentInstanceCounts | None = None, available\_actions: AgentAvailableActions | None = None, inserted\_at: datetime | None = None, updated\_at: datetime | None = None)”](#class-prefactor_httpmodelsagentagent-type-literalagent-id-str-name-str-description-str--none--none-external_identifier-str--none--none-status-literalpending-active-dormant-retired-owner_person_id-str--none--none-risk_profile_id-str--none--none-team_id-str--none--none-instance_counts-agentinstancecounts--none--none-available_actions-agentavailableactions--none--none-inserted_at-datetime--none--none-updated_at-datetime--none--none) Bases: `BaseModel` Full agent details. #### type [Section titled “type”](#type) Resource type (always “agent”). * **Type:** Literal\[‘agent’] #### id [Section titled “id”](#id) Agent ID. * **Type:** str #### name [Section titled “name”](#name) Agent name. * **Type:** str #### description [Section titled “description”](#description) Optional agent description. * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier) Optional external identifier (unique per account). * **Type:** str | None #### status [Section titled “status”](#status) Agent status (pending, active, dormant, retired). * **Type:** Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’] #### owner\_person\_id [Section titled “owner\_person\_id”](#owner_person_id) Optional owner person ID. * **Type:** str | None #### risk\_profile\_id [Section titled “risk\_profile\_id”](#risk_profile_id) Optional risk profile ID. * **Type:** str | None #### team\_id [Section titled “team\_id”](#team_id) Optional team ID. * **Type:** str | None #### instance\_counts [Section titled “instance\_counts”](#instance_counts) Instance counts for this agent. * **Type:** [AgentInstanceCounts](#prefactor_http.models.agent.AgentInstanceCounts) | None #### available\_actions [Section titled “available\_actions”](#available_actions) Available actions based on current status. * **Type:** [AgentAvailableActions](#prefactor_http.models.agent.AgentAvailableActions) | None #### inserted\_at [Section titled “inserted\_at”](#inserted_at) When the agent was created. * **Type:** datetime | None #### updated\_at [Section titled “updated\_at”](#updated_at) When the agent was last updated. * **Type:** datetime | None #### available\_actions *: [AgentAvailableActions](#prefactor_http.models.agent.AgentAvailableActions) | None* [Section titled “available\_actions : AgentAvailableActions | None”](#available_actions--agentavailableactions--none) #### description *: str | None* [Section titled “description : str | None”](#description--str--none) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none) #### id *: str* [Section titled “id : str”](#id--str) #### inserted\_at *: datetime | None* [Section titled “inserted\_at : datetime | None”](#inserted_at--datetime--none) #### instance\_counts *: [AgentInstanceCounts](#prefactor_http.models.agent.AgentInstanceCounts) | None* [Section titled “instance\_counts : AgentInstanceCounts | None”](#instance_counts--agentinstancecounts--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config--) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str) #### owner\_person\_id *: str | None* [Section titled “owner\_person\_id : str | None”](#owner_person_id--str--none) #### risk\_profile\_id *: str | None* [Section titled “risk\_profile\_id : str | None”](#risk_profile_id--str--none) #### status *: Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’]* [Section titled “status : Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’\]”](#status--literalpending-active-dormant-retired) #### team\_id *: str | None* [Section titled “team\_id : str | None”](#team_id--str--none) #### type *: Literal\[‘agent’]* [Section titled “type : Literal\[‘agent’\]”](#type--literalagent) #### updated\_at *: datetime | None* [Section titled “updated\_at : datetime | None”](#updated_at--datetime--none) ### *class* prefactor\_http.models.agent.AgentAvailableActions(, update: bool = False, retire: bool = False, reinstate: bool = False, delete: bool = False) [Section titled “class prefactor\_http.models.agent.AgentAvailableActions(, update: bool = False, retire: bool = False, reinstate: bool = False, delete: bool = False)”](#class-prefactor_httpmodelsagentagentavailableactions-update-bool--false-retire-bool--false-reinstate-bool--false-delete-bool--false) Bases: `BaseModel` Available actions for an agent based on its status. #### update [Section titled “update”](#update) Whether the agent can be updated. * **Type:** bool #### retire [Section titled “retire”](#retire) Whether the agent can be retired. * **Type:** bool #### reinstate [Section titled “reinstate”](#reinstate) Whether the agent can be reinstated from retired. * **Type:** bool #### delete [Section titled “delete”](#delete) Whether the agent can be deleted. * **Type:** bool #### delete *: bool* [Section titled “delete : bool”](#delete--bool) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### reinstate *: bool* [Section titled “reinstate : bool”](#reinstate--bool) #### retire *: bool* [Section titled “retire : bool”](#retire--bool) #### update *: bool* [Section titled “update : bool”](#update--bool) ### *class* prefactor\_http.models.agent.AgentForCreate(, name: str, description: str | None = None, external\_identifier: str | None = None, id: str | None = None, owner\_person\_id: str | None = None, risk\_profile\_id: str | None = None, team\_id: str | None = None) [Section titled “class prefactor\_http.models.agent.AgentForCreate(, name: str, description: str | None = None, external\_identifier: str | None = None, id: str | None = None, owner\_person\_id: str | None = None, risk\_profile\_id: str | None = None, team\_id: str | None = None)”](#class-prefactor_httpmodelsagentagentforcreate-name-str-description-str--none--none-external_identifier-str--none--none-id-str--none--none-owner_person_id-str--none--none-risk_profile_id-str--none--none-team_id-str--none--none) Bases: `BaseModel` Parameters for creating a new agent. #### name [Section titled “name”](#name-1) Agent name (required). * **Type:** str #### description [Section titled “description”](#description-1) Optional agent description. * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier-1) Optional external identifier (unique per account). * **Type:** str | None #### id [Section titled “id”](#id-1) Optional custom ID (PFID with matching partition). * **Type:** str | None #### owner\_person\_id [Section titled “owner\_person\_id”](#owner_person_id-1) Optional owner person ID. * **Type:** str | None #### risk\_profile\_id [Section titled “risk\_profile\_id”](#risk_profile_id-1) Optional risk profile ID. * **Type:** str | None #### team\_id [Section titled “team\_id”](#team_id-1) Optional team ID. * **Type:** str | None #### description *: str | None* [Section titled “description : str | None”](#description--str--none-1) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none-1) #### id *: str | None* [Section titled “id : str | None”](#id--str--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---2) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-1) #### owner\_person\_id *: str | None* [Section titled “owner\_person\_id : str | None”](#owner_person_id--str--none-1) #### risk\_profile\_id *: str | None* [Section titled “risk\_profile\_id : str | None”](#risk_profile_id--str--none-1) #### team\_id *: str | None* [Section titled “team\_id : str | None”](#team_id--str--none-1) ### *class* prefactor\_http.models.agent.AgentForUpdate(, name: str | None = None, description: str | None = None, owner\_person\_id: str | None = None, risk\_profile\_id: str | None = None, team\_id: str | None = None) [Section titled “class prefactor\_http.models.agent.AgentForUpdate(, name: str | None = None, description: str | None = None, owner\_person\_id: str | None = None, risk\_profile\_id: str | None = None, team\_id: str | None = None)”](#class-prefactor_httpmodelsagentagentforupdate-name-str--none--none-description-str--none--none-owner_person_id-str--none--none-risk_profile_id-str--none--none-team_id-str--none--none) Bases: `BaseModel` Parameters for updating an agent. Note: `external_identifier` cannot be updated via the API — it is only settable at create time. #### name [Section titled “name”](#name-2) Agent name (omit to keep current). * **Type:** str | None #### description [Section titled “description”](#description-2) Agent description (omit to keep current). * **Type:** str | None #### owner\_person\_id [Section titled “owner\_person\_id”](#owner_person_id-2) Owner person ID (omit to keep current; null to clear). * **Type:** str | None #### risk\_profile\_id [Section titled “risk\_profile\_id”](#risk_profile_id-2) Risk profile ID (omit to keep current; null to clear). * **Type:** str | None #### team\_id [Section titled “team\_id”](#team_id-2) Team ID (omit to keep current; null to clear). * **Type:** str | None #### description *: str | None* [Section titled “description : str | None”](#description--str--none-2) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---3) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str | None* [Section titled “name : str | None”](#name--str--none) #### owner\_person\_id *: str | None* [Section titled “owner\_person\_id : str | None”](#owner_person_id--str--none-2) #### risk\_profile\_id *: str | None* [Section titled “risk\_profile\_id : str | None”](#risk_profile_id--str--none-2) #### team\_id *: str | None* [Section titled “team\_id : str | None”](#team_id--str--none-2) ### *class* prefactor\_http.models.agent.AgentInstanceCounts(, total: int = 0, pending: int = 0, active: int = 0, complete: int = 0, failed: int = 0, cancelled: int = 0, terminated: int = 0, finished: int = 0) [Section titled “class prefactor\_http.models.agent.AgentInstanceCounts(, total: int = 0, pending: int = 0, active: int = 0, complete: int = 0, failed: int = 0, cancelled: int = 0, terminated: int = 0, finished: int = 0)”](#class-prefactor_httpmodelsagentagentinstancecounts-total-int--0-pending-int--0-active-int--0-complete-int--0-failed-int--0-cancelled-int--0-terminated-int--0-finished-int--0) Bases: `BaseModel` Instance counts for an agent. #### total [Section titled “total”](#total) Total number of agent instances. * **Type:** int #### pending [Section titled “pending”](#pending) Number of instances with status pending. * **Type:** int #### active [Section titled “active”](#active) Number of instances with status active (running). * **Type:** int #### complete [Section titled “complete”](#complete) Number of instances with status complete. * **Type:** int #### failed [Section titled “failed”](#failed) Number of instances with status failed. * **Type:** int #### cancelled [Section titled “cancelled”](#cancelled) Number of instances with status cancelled. * **Type:** int #### terminated [Section titled “terminated”](#terminated) Number of instances with status terminated. * **Type:** int #### finished [Section titled “finished”](#finished) Number of instances in a finished state. * **Type:** int #### active *: int* [Section titled “active : int”](#active--int) #### cancelled *: int* [Section titled “cancelled : int”](#cancelled--int) #### complete *: int* [Section titled “complete : int”](#complete--int) #### failed *: int* [Section titled “failed : int”](#failed--int) #### finished *: int* [Section titled “finished : int”](#finished--int) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---4) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### pending *: int* [Section titled “pending : int”](#pending--int) #### terminated *: int* [Section titled “terminated : int”](#terminated--int) #### total *: int* [Section titled “total : int”](#total--int) ### *class* prefactor\_http.models.agent.AgentSummary(, type: Literal\[‘agent’], id: str, name: str, description: str | None = None, external\_identifier: str | None = None, status: Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’], owner\_person\_id: str | None = None, team\_id: str | None = None, available\_actions: [AgentAvailableActions](#prefactor_http.models.agent.AgentAvailableActions) | None = None, inserted\_at: datetime | None = None, updated\_at: datetime | None = None) [Section titled “class prefactor\_http.models.agent.AgentSummary(, type: Literal\[‘agent’\], id: str, name: str, description: str | None = None, external\_identifier: str | None = None, status: Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’\], owner\_person\_id: str | None = None, team\_id: str | None = None, available\_actions: AgentAvailableActions | None = None, inserted\_at: datetime | None = None, updated\_at: datetime | None = None)”](#class-prefactor_httpmodelsagentagentsummary-type-literalagent-id-str-name-str-description-str--none--none-external_identifier-str--none--none-status-literalpending-active-dormant-retired-owner_person_id-str--none--none-team_id-str--none--none-available_actions-agentavailableactions--none--none-inserted_at-datetime--none--none-updated_at-datetime--none--none) Bases: `BaseModel` Agent summary for list responses. #### type [Section titled “type”](#type-1) Resource type (always “agent”). * **Type:** Literal\[‘agent’] #### id [Section titled “id”](#id-2) Agent ID. * **Type:** str #### name [Section titled “name”](#name-3) Agent name. * **Type:** str #### description [Section titled “description”](#description-3) Optional agent description. * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier-2) Optional external identifier (unique per account). * **Type:** str | None #### status [Section titled “status”](#status-1) Agent status. * **Type:** Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’] #### owner\_person\_id [Section titled “owner\_person\_id”](#owner_person_id-3) Optional owner person ID. * **Type:** str | None #### team\_id [Section titled “team\_id”](#team_id-3) Optional team ID. * **Type:** str | None #### available\_actions [Section titled “available\_actions”](#available_actions-1) Available actions based on current status. * **Type:** [AgentAvailableActions](#prefactor_http.models.agent.AgentAvailableActions) | None #### inserted\_at [Section titled “inserted\_at”](#inserted_at-1) When the agent was created. * **Type:** datetime | None #### updated\_at [Section titled “updated\_at”](#updated_at-1) When the agent was last updated. * **Type:** datetime | None #### available\_actions *: [AgentAvailableActions](#prefactor_http.models.agent.AgentAvailableActions) | None* [Section titled “available\_actions : AgentAvailableActions | None”](#available_actions--agentavailableactions--none-1) #### description *: str | None* [Section titled “description : str | None”](#description--str--none-3) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none-2) #### id *: str* [Section titled “id : str”](#id--str-1) #### inserted\_at *: datetime | None* [Section titled “inserted\_at : datetime | None”](#inserted_at--datetime--none-1) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---5) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-2) #### owner\_person\_id *: str | None* [Section titled “owner\_person\_id : str | None”](#owner_person_id--str--none-3) #### status *: Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’]* [Section titled “status : Literal\[‘pending’, ‘active’, ‘dormant’, ‘retired’\]”](#status--literalpending-active-dormant-retired-1) #### team\_id *: str | None* [Section titled “team\_id : str | None”](#team_id--str--none-3) #### type *: Literal\[‘agent’]* [Section titled “type : Literal\[‘agent’\]”](#type--literalagent-1) #### updated\_at *: datetime | None* [Section titled “updated\_at : datetime | None”](#updated_at--datetime--none-1) # prefactor_http.models.agent_instance module # prefactor\_http.models.agent\_instance module [Section titled “prefactor\_http.models.agent\_instance module”](#prefactor_httpmodelsagent_instance-module) AgentInstance data models. ### *class* prefactor\_http.models.agent\_instance.ActionProfile(, create\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’] = ‘unknown’, read\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’] = ‘unknown’, update\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’] = ‘unknown’, destroy\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’] = ‘unknown’, financial\_transactions: Literal\[‘unknown’, ‘allowed’, ‘disallowed’] = ‘unknown’, external\_communication: Literal\[‘unknown’, ‘allowed’, ‘disallowed’] = ‘unknown’) [Section titled “class prefactor\_http.models.agent\_instance.ActionProfile(, create\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’\] = ‘unknown’, read\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’\] = ‘unknown’, update\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’\] = ‘unknown’, destroy\_data: Literal\[‘unknown’, ‘allowed’, ‘disallowed’\] = ‘unknown’, financial\_transactions: Literal\[‘unknown’, ‘allowed’, ‘disallowed’\] = ‘unknown’, external\_communication: Literal\[‘unknown’, ‘allowed’, ‘disallowed’\] = ‘unknown’)”](#class-prefactor_httpmodelsagent_instanceactionprofile-create_data-literalunknown-allowed-disallowed--unknown-read_data-literalunknown-allowed-disallowed--unknown-update_data-literalunknown-allowed-disallowed--unknown-destroy_data-literalunknown-allowed-disallowed--unknown-financial_transactions-literalunknown-allowed-disallowed--unknown-external_communication-literalunknown-allowed-disallowed--unknown) Bases: `BaseModel` Action profile defining what actions a span type performs. #### create\_data [Section titled “create\_data”](#create_data) Whether this span creates data * **Type:** Literal\[‘unknown’, ‘allowed’, ‘disallowed’] #### read\_data [Section titled “read\_data”](#read_data) Whether this span reads data * **Type:** Literal\[‘unknown’, ‘allowed’, ‘disallowed’] #### update\_data [Section titled “update\_data”](#update_data) Whether this span updates data * **Type:** Literal\[‘unknown’, ‘allowed’, ‘disallowed’] #### destroy\_data [Section titled “destroy\_data”](#destroy_data) Whether this span destroys data * **Type:** Literal\[‘unknown’, ‘allowed’, ‘disallowed’] #### financial\_transactions [Section titled “financial\_transactions”](#financial_transactions) Whether this span performs financial transactions * **Type:** Literal\[‘unknown’, ‘allowed’, ‘disallowed’] #### external\_communication [Section titled “external\_communication”](#external_communication) Whether this span sends external communications * **Type:** Literal\[‘unknown’, ‘allowed’, ‘disallowed’] #### create\_data *: Literal\[‘unknown’, ‘allowed’, ‘disallowed’]* [Section titled “create\_data : Literal\[‘unknown’, ‘allowed’, ‘disallowed’\]”](#create_data--literalunknown-allowed-disallowed) #### destroy\_data *: Literal\[‘unknown’, ‘allowed’, ‘disallowed’]* [Section titled “destroy\_data : Literal\[‘unknown’, ‘allowed’, ‘disallowed’\]”](#destroy_data--literalunknown-allowed-disallowed) #### external\_communication *: Literal\[‘unknown’, ‘allowed’, ‘disallowed’]* [Section titled “external\_communication : Literal\[‘unknown’, ‘allowed’, ‘disallowed’\]”](#external_communication--literalunknown-allowed-disallowed) #### financial\_transactions *: Literal\[‘unknown’, ‘allowed’, ‘disallowed’]* [Section titled “financial\_transactions : Literal\[‘unknown’, ‘allowed’, ‘disallowed’\]”](#financial_transactions--literalunknown-allowed-disallowed) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config--) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### read\_data *: Literal\[‘unknown’, ‘allowed’, ‘disallowed’]* [Section titled “read\_data : Literal\[‘unknown’, ‘allowed’, ‘disallowed’\]”](#read_data--literalunknown-allowed-disallowed) #### update\_data *: Literal\[‘unknown’, ‘allowed’, ‘disallowed’]* [Section titled “update\_data : Literal\[‘unknown’, ‘allowed’, ‘disallowed’\]”](#update_data--literalunknown-allowed-disallowed) ### *class* prefactor\_http.models.agent\_instance.AgentInstance(, type: Literal\[‘agent\_instance’], id: str, account\_id: str, agent\_id: str, agent\_version\_id: str, environment\_id: str, agent\_deployment\_id: str, status: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’], inserted\_at: datetime, updated\_at: datetime, started\_at: datetime | None = None, finished\_at: datetime | None = None, termination\_reason: str | None = None, external\_identifier: str | None = None, span\_counts: [AgentInstanceSpanCounts](#prefactor_http.models.agent_instance.AgentInstanceSpanCounts) | None = None, purpose: Literal\[‘live’, ‘smoke\_test’, ‘eval’] | None = None, quality\_payloads: dict\[str, dict] | None = None, quality\_summaries: dict\[str, str] | None = None) [Section titled “class prefactor\_http.models.agent\_instance.AgentInstance(, type: Literal\[‘agent\_instance’\], id: str, account\_id: str, agent\_id: str, agent\_version\_id: str, environment\_id: str, agent\_deployment\_id: str, status: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\], inserted\_at: datetime, updated\_at: datetime, started\_at: datetime | None = None, finished\_at: datetime | None = None, termination\_reason: str | None = None, external\_identifier: str | None = None, span\_counts: AgentInstanceSpanCounts | None = None, purpose: Literal\[‘live’, ‘smoke\_test’, ‘eval’\] | None = None, quality\_payloads: dict\[str, dict\] | None = None, quality\_summaries: dict\[str, str\] | None = None)”](#class-prefactor_httpmodelsagent_instanceagentinstance-type-literalagent_instance-id-str-account_id-str-agent_id-str-agent_version_id-str-environment_id-str-agent_deployment_id-str-status-literalpending-active-complete-failed-cancelled-terminated-inserted_at-datetime-updated_at-datetime-started_at-datetime--none--none-finished_at-datetime--none--none-termination_reason-str--none--none-external_identifier-str--none--none-span_counts-agentinstancespancounts--none--none-purpose-literallive-smoke_test-eval--none--none-quality_payloads-dictstr-dict--none--none-quality_summaries-dictstr-str--none--none) Bases: `BaseModel` Agent instance model. #### type [Section titled “type”](#type) Resource type (always “agent\_instance”) * **Type:** Literal\[‘agent\_instance’] #### id [Section titled “id”](#id) Instance ID * **Type:** str #### account\_id [Section titled “account\_id”](#account_id) Account ID * **Type:** str #### agent\_id [Section titled “agent\_id”](#agent_id) Agent ID * **Type:** str #### agent\_version\_id [Section titled “agent\_version\_id”](#agent_version_id) Agent version ID * **Type:** str #### environment\_id [Section titled “environment\_id”](#environment_id) Environment ID * **Type:** str #### agent\_deployment\_id [Section titled “agent\_deployment\_id”](#agent_deployment_id) Agent deployment ID * **Type:** str #### status [Section titled “status”](#status) Instance status * **Type:** AgentStatus #### inserted\_at [Section titled “inserted\_at”](#inserted_at) When the instance was created * **Type:** datetime #### updated\_at [Section titled “updated\_at”](#updated_at) When the instance was last updated * **Type:** datetime #### started\_at [Section titled “started\_at”](#started_at) When the instance started (null if not started) * **Type:** datetime | None #### finished\_at [Section titled “finished\_at”](#finished_at) When the instance finished (null if not finished) * **Type:** datetime | None #### termination\_reason [Section titled “termination\_reason”](#termination_reason) Reason for termination (null if not terminated) * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier) Optional external identifier (unique per agent) * **Type:** str | None #### span\_counts [Section titled “span\_counts”](#span_counts) Span counts for this instance * **Type:** [AgentInstanceSpanCounts](#prefactor_http.models.agent_instance.AgentInstanceSpanCounts) | None #### purpose [Section titled “purpose”](#purpose) Why this instance ran (live, smoke\_test, eval) * **Type:** InstancePurpose | None #### quality\_payloads [Section titled “quality\_payloads”](#quality_payloads) Map of quality schema name to evaluation payload * **Type:** dict\[str, dict] | None #### quality\_summaries [Section titled “quality\_summaries”](#quality_summaries) Map of quality schema name to rendered summary * **Type:** dict\[str, str] | None #### account\_id *: str* [Section titled “account\_id : str”](#account_id--str) #### agent\_deployment\_id *: str* [Section titled “agent\_deployment\_id : str”](#agent_deployment_id--str) #### agent\_id *: str* [Section titled “agent\_id : str”](#agent_id--str) #### agent\_version\_id *: str* [Section titled “agent\_version\_id : str”](#agent_version_id--str) #### environment\_id *: str* [Section titled “environment\_id : str”](#environment_id--str) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none) #### finished\_at *: datetime | None* [Section titled “finished\_at : datetime | None”](#finished_at--datetime--none) #### id *: str* [Section titled “id : str”](#id--str) #### inserted\_at *: datetime* [Section titled “inserted\_at : datetime”](#inserted_at--datetime) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### purpose *: InstancePurpose | None* [Section titled “purpose : InstancePurpose | None”](#purpose--instancepurpose--none) #### quality\_payloads *: dict\[str, dict] | None* [Section titled “quality\_payloads : dict\[str, dict\] | None”](#quality_payloads--dictstr-dict--none) #### quality\_summaries *: dict\[str, str] | None* [Section titled “quality\_summaries : dict\[str, str\] | None”](#quality_summaries--dictstr-str--none) #### span\_counts *: [AgentInstanceSpanCounts](#prefactor_http.models.agent_instance.AgentInstanceSpanCounts) | None* [Section titled “span\_counts : AgentInstanceSpanCounts | None”](#span_counts--agentinstancespancounts--none) #### started\_at *: datetime | None* [Section titled “started\_at : datetime | None”](#started_at--datetime--none) #### status *: AgentStatus* [Section titled “status : AgentStatus”](#status--agentstatus) #### termination\_reason *: str | None* [Section titled “termination\_reason : str | None”](#termination_reason--str--none) #### type *: Literal\[‘agent\_instance’]* [Section titled “type : Literal\[‘agent\_instance’\]”](#type--literalagent_instance) #### updated\_at *: datetime* [Section titled “updated\_at : datetime”](#updated_at--datetime) ### *class* prefactor\_http.models.agent\_instance.AgentInstanceRecordQuality(, name: str, payload: dict | None = None) [Section titled “class prefactor\_http.models.agent\_instance.AgentInstanceRecordQuality(, name: str, payload: dict | None = None)”](#class-prefactor_httpmodelsagent_instanceagentinstancerecordquality-name-str-payload-dict--none--none) Bases: `BaseModel` Parameters for recording a quality payload on an agent instance. #### name [Section titled “name”](#name) Unique identifier of the quality schema entry to record against * **Type:** str #### payload [Section titled “payload”](#payload) Quality payload for this name, or None to remove the recorded payload for this name * **Type:** dict | None #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---2) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str) #### payload *: dict | None* [Section titled “payload : dict | None”](#payload--dict--none) ### *class* prefactor\_http.models.agent\_instance.AgentInstanceSpanCounts(, total: int = 0, active: int = 0, complete: int = 0, failed: int = 0, cancelled: int = 0, finished: int = 0) [Section titled “class prefactor\_http.models.agent\_instance.AgentInstanceSpanCounts(, total: int = 0, active: int = 0, complete: int = 0, failed: int = 0, cancelled: int = 0, finished: int = 0)”](#class-prefactor_httpmodelsagent_instanceagentinstancespancounts-total-int--0-active-int--0-complete-int--0-failed-int--0-cancelled-int--0-finished-int--0) Bases: `BaseModel` Span counts for an agent instance. #### total [Section titled “total”](#total) Total number of spans * **Type:** int #### active [Section titled “active”](#active) Number of active spans * **Type:** int #### complete [Section titled “complete”](#complete) Number of completed spans * **Type:** int #### failed [Section titled “failed”](#failed) Number of failed spans * **Type:** int #### cancelled [Section titled “cancelled”](#cancelled) Number of cancelled spans * **Type:** int #### finished [Section titled “finished”](#finished) Number of finished spans (complete + failed + cancelled) * **Type:** int #### active *: int* [Section titled “active : int”](#active--int) #### cancelled *: int* [Section titled “cancelled : int”](#cancelled--int) #### complete *: int* [Section titled “complete : int”](#complete--int) #### failed *: int* [Section titled “failed : int”](#failed--int) #### finished *: int* [Section titled “finished : int”](#finished--int) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---3) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### total *: int* [Section titled “total : int”](#total--int) ### *class* prefactor\_http.models.agent\_instance.AgentSchemaVersionForRegister(, external\_identifier: str | None = None, span\_schemas: dict\[str, dict] | None = None, span\_result\_schemas: dict\[str, dict] | None = None, span\_type\_schemas: list\[[SpanTypeSchemaForCreate](#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate)] | None = None, quality\_schemas: list\[[QualitySchemaForCreate](#prefactor_http.models.agent_instance.QualitySchemaForCreate)] | None = None) [Section titled “class prefactor\_http.models.agent\_instance.AgentSchemaVersionForRegister(, external\_identifier: str | None = None, span\_schemas: dict\[str, dict\] | None = None, span\_result\_schemas: dict\[str, dict\] | None = None, span\_type\_schemas: list\[SpanTypeSchemaForCreate\] | None = None, quality\_schemas: list\[QualitySchemaForCreate\] | None = None)”](#class-prefactor_httpmodelsagent_instanceagentschemaversionforregister-external_identifier-str--none--none-span_schemas-dictstr-dict--none--none-span_result_schemas-dictstr-dict--none--none-span_type_schemas-listspantypeschemaforcreate--none--none-quality_schemas-listqualityschemaforcreate--none--none) Bases: `BaseModel` Schema version information for registration. #### external\_identifier [Section titled “external\_identifier”](#external_identifier-1) External identifier for the schema version * **Type:** str | None #### span\_schemas [Section titled “span\_schemas”](#span_schemas) Map of span type names to JSON schemas * **Type:** dict\[str, dict] | None #### span\_result\_schemas [Section titled “span\_result\_schemas”](#span_result_schemas) Map of span type names to result JSON schemas * **Type:** dict\[str, dict] | None #### span\_type\_schemas [Section titled “span\_type\_schemas”](#span_type_schemas) List of span type schema details * **Type:** list\[[SpanTypeSchemaForCreate](#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate)] | None #### quality\_schemas [Section titled “quality\_schemas”](#quality_schemas) Optional list of named quality schemas for instance evaluations * **Type:** list\[[QualitySchemaForCreate](#prefactor_http.models.agent_instance.QualitySchemaForCreate)] | None #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none-1) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---4) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### quality\_schemas *: list\[[QualitySchemaForCreate](#prefactor_http.models.agent_instance.QualitySchemaForCreate)] | None* [Section titled “quality\_schemas : list\[QualitySchemaForCreate\] | None”](#quality_schemas--listqualityschemaforcreate--none) #### span\_result\_schemas *: dict\[str, dict] | None* [Section titled “span\_result\_schemas : dict\[str, dict\] | None”](#span_result_schemas--dictstr-dict--none) #### span\_schemas *: dict\[str, dict] | None* [Section titled “span\_schemas : dict\[str, dict\] | None”](#span_schemas--dictstr-dict--none) #### span\_type\_schemas *: list\[[SpanTypeSchemaForCreate](#prefactor_http.models.agent_instance.SpanTypeSchemaForCreate)] | None* [Section titled “span\_type\_schemas : list\[SpanTypeSchemaForCreate\] | None”](#span_type_schemas--listspantypeschemaforcreate--none) ### *class* prefactor\_http.models.agent\_instance.AgentVersionForRegister(, name: str | None = None, external\_identifier: str | None = None, description: str | None = None, runtime\_environment: [RuntimeEnvironment](#prefactor_http.models.agent_instance.RuntimeEnvironment) | None = None) [Section titled “class prefactor\_http.models.agent\_instance.AgentVersionForRegister(, name: str | None = None, external\_identifier: str | None = None, description: str | None = None, runtime\_environment: RuntimeEnvironment | None = None)”](#class-prefactor_httpmodelsagent_instanceagentversionforregister-name-str--none--none-external_identifier-str--none--none-description-str--none--none-runtime_environment-runtimeenvironment--none--none) Bases: `BaseModel` Agent version information for registration. #### name [Section titled “name”](#name-1) Name of the agent version * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier-2) External identifier for the version (e.g., “v1.0.0”) * **Type:** str | None #### description [Section titled “description”](#description) Optional description of the version * **Type:** str | None #### runtime\_environment [Section titled “runtime\_environment”](#runtime_environment) Runtime environment metadata * **Type:** [RuntimeEnvironment](#prefactor_http.models.agent_instance.RuntimeEnvironment) | None #### description *: str | None* [Section titled “description : str | None”](#description--str--none) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none-2) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---5) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str | None* [Section titled “name : str | None”](#name--str--none) #### runtime\_environment *: [RuntimeEnvironment](#prefactor_http.models.agent_instance.RuntimeEnvironment) | None* [Section titled “runtime\_environment : RuntimeEnvironment | None”](#runtime_environment--runtimeenvironment--none) ### *class* prefactor\_http.models.agent\_instance.DataCategories(, personal\_identifiers: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, contact\_information: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, financial\_information: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, health\_and\_medical: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, criminal\_justice: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, authentication\_and\_secrets: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, organisational\_confidential: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, minors\_data: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, location\_and\_tracking: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, behavioural\_and\_inferred: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_racial\_or\_ethnic\_origin: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_political\_opinions: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_religious\_or\_philosophical\_beliefs: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_trade\_union\_membership: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_genetic\_data: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_biometric\_for\_identification: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, gdpr\_sex\_life\_or\_sexual\_orientation: Literal\[‘unknown’, ‘included’, ‘excluded’] = ‘unknown’, classification: Literal\[‘unknown’, ‘public’, ‘internal’, ‘confidential’, ‘restricted’, ‘secret’] = ‘unknown’) [Section titled “class prefactor\_http.models.agent\_instance.DataCategories(, personal\_identifiers: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, contact\_information: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, financial\_information: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, health\_and\_medical: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, criminal\_justice: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, authentication\_and\_secrets: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, organisational\_confidential: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, minors\_data: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, location\_and\_tracking: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, behavioural\_and\_inferred: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_racial\_or\_ethnic\_origin: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_political\_opinions: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_religious\_or\_philosophical\_beliefs: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_trade\_union\_membership: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_genetic\_data: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_biometric\_for\_identification: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, gdpr\_sex\_life\_or\_sexual\_orientation: Literal\[‘unknown’, ‘included’, ‘excluded’\] = ‘unknown’, classification: Literal\[‘unknown’, ‘public’, ‘internal’, ‘confidential’, ‘restricted’, ‘secret’\] = ‘unknown’)”](#class-prefactor_httpmodelsagent_instancedatacategories-personal_identifiers-literalunknown-included-excluded--unknown-contact_information-literalunknown-included-excluded--unknown-financial_information-literalunknown-included-excluded--unknown-health_and_medical-literalunknown-included-excluded--unknown-criminal_justice-literalunknown-included-excluded--unknown-authentication_and_secrets-literalunknown-included-excluded--unknown-organisational_confidential-literalunknown-included-excluded--unknown-minors_data-literalunknown-included-excluded--unknown-location_and_tracking-literalunknown-included-excluded--unknown-behavioural_and_inferred-literalunknown-included-excluded--unknown-gdpr_racial_or_ethnic_origin-literalunknown-included-excluded--unknown-gdpr_political_opinions-literalunknown-included-excluded--unknown-gdpr_religious_or_philosophical_beliefs-literalunknown-included-excluded--unknown-gdpr_trade_union_membership-literalunknown-included-excluded--unknown-gdpr_genetic_data-literalunknown-included-excluded--unknown-gdpr_biometric_for_identification-literalunknown-included-excluded--unknown-gdpr_sex_life_or_sexual_orientation-literalunknown-included-excluded--unknown-classification-literalunknown-public-internal-confidential-restricted-secret--unknown) Bases: `BaseModel` Data categories present in span data. #### personal\_identifiers [Section titled “personal\_identifiers”](#personal_identifiers) Personal identifiers present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### contact\_information [Section titled “contact\_information”](#contact_information) Contact information present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### financial\_information [Section titled “financial\_information”](#financial_information) Financial information present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### health\_and\_medical [Section titled “health\_and\_medical”](#health_and_medical) Health and medical data present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### criminal\_justice [Section titled “criminal\_justice”](#criminal_justice) Criminal justice data present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### authentication\_and\_secrets [Section titled “authentication\_and\_secrets”](#authentication_and_secrets) Authentication and secrets present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### organisational\_confidential [Section titled “organisational\_confidential”](#organisational_confidential) Organisational confidential data present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### minors\_data [Section titled “minors\_data”](#minors_data) Minors data present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### location\_and\_tracking [Section titled “location\_and\_tracking”](#location_and_tracking) Location and tracking data present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### behavioural\_and\_inferred [Section titled “behavioural\_and\_inferred”](#behavioural_and_inferred) Behavioural and inferred data present * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_racial\_or\_ethnic\_origin [Section titled “gdpr\_racial\_or\_ethnic\_origin”](#gdpr_racial_or_ethnic_origin) GDPR: racial or ethnic origin * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_political\_opinions [Section titled “gdpr\_political\_opinions”](#gdpr_political_opinions) GDPR: political opinions * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_religious\_or\_philosophical\_beliefs [Section titled “gdpr\_religious\_or\_philosophical\_beliefs”](#gdpr_religious_or_philosophical_beliefs) GDPR: religious or philosophical beliefs * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_trade\_union\_membership [Section titled “gdpr\_trade\_union\_membership”](#gdpr_trade_union_membership) GDPR: trade union membership * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_genetic\_data [Section titled “gdpr\_genetic\_data”](#gdpr_genetic_data) GDPR: genetic data * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_biometric\_for\_identification [Section titled “gdpr\_biometric\_for\_identification”](#gdpr_biometric_for_identification) GDPR: biometric data for identification * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### gdpr\_sex\_life\_or\_sexual\_orientation [Section titled “gdpr\_sex\_life\_or\_sexual\_orientation”](#gdpr_sex_life_or_sexual_orientation) GDPR: sex life or sexual orientation * **Type:** Literal\[‘unknown’, ‘included’, ‘excluded’] #### classification [Section titled “classification”](#classification) Classification level (unknown, public, internal, confidential, restricted, secret) * **Type:** Literal\[‘unknown’, ‘public’, ‘internal’, ‘confidential’, ‘restricted’, ‘secret’] #### authentication\_and\_secrets *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “authentication\_and\_secrets : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#authentication_and_secrets--literalunknown-included-excluded) #### behavioural\_and\_inferred *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “behavioural\_and\_inferred : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#behavioural_and_inferred--literalunknown-included-excluded) #### classification *: Literal\[‘unknown’, ‘public’, ‘internal’, ‘confidential’, ‘restricted’, ‘secret’]* [Section titled “classification : Literal\[‘unknown’, ‘public’, ‘internal’, ‘confidential’, ‘restricted’, ‘secret’\]”](#classification--literalunknown-public-internal-confidential-restricted-secret) #### contact\_information *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “contact\_information : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#contact_information--literalunknown-included-excluded) #### criminal\_justice *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “criminal\_justice : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#criminal_justice--literalunknown-included-excluded) #### financial\_information *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “financial\_information : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#financial_information--literalunknown-included-excluded) #### gdpr\_biometric\_for\_identification *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_biometric\_for\_identification : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_biometric_for_identification--literalunknown-included-excluded) #### gdpr\_genetic\_data *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_genetic\_data : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_genetic_data--literalunknown-included-excluded) #### gdpr\_political\_opinions *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_political\_opinions : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_political_opinions--literalunknown-included-excluded) #### gdpr\_racial\_or\_ethnic\_origin *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_racial\_or\_ethnic\_origin : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_racial_or_ethnic_origin--literalunknown-included-excluded) #### gdpr\_religious\_or\_philosophical\_beliefs *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_religious\_or\_philosophical\_beliefs : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_religious_or_philosophical_beliefs--literalunknown-included-excluded) #### gdpr\_sex\_life\_or\_sexual\_orientation *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_sex\_life\_or\_sexual\_orientation : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_sex_life_or_sexual_orientation--literalunknown-included-excluded) #### gdpr\_trade\_union\_membership *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “gdpr\_trade\_union\_membership : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#gdpr_trade_union_membership--literalunknown-included-excluded) #### health\_and\_medical *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “health\_and\_medical : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#health_and_medical--literalunknown-included-excluded) #### location\_and\_tracking *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “location\_and\_tracking : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#location_and_tracking--literalunknown-included-excluded) #### minors\_data *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “minors\_data : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#minors_data--literalunknown-included-excluded) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---6) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### organisational\_confidential *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “organisational\_confidential : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#organisational_confidential--literalunknown-included-excluded) #### personal\_identifiers *: Literal\[‘unknown’, ‘included’, ‘excluded’]* [Section titled “personal\_identifiers : Literal\[‘unknown’, ‘included’, ‘excluded’\]”](#personal_identifiers--literalunknown-included-excluded) ### *class* prefactor\_http.models.agent\_instance.DataRisk(, action\_profile: [ActionProfile](#prefactor_http.models.agent_instance.ActionProfile), params\_data\_categories: [DataCategories](#prefactor_http.models.agent_instance.DataCategories), result\_data\_categories: [DataCategories](#prefactor_http.models.agent_instance.DataCategories), \*\*extra\_data: Any) [Section titled “class prefactor\_http.models.agent\_instance.DataRisk(, action\_profile: ActionProfile, params\_data\_categories: DataCategories, result\_data\_categories: DataCategories, \*\*extra\_data: Any)”](#class-prefactor_httpmodelsagent_instancedatarisk-action_profile-actionprofile-params_data_categories-datacategories-result_data_categories-datacategories-extra_data-any) Bases: `BaseModel` Data risk specification for a span type. #### action\_profile [Section titled “action\_profile”](#action_profile) Actions this span performs * **Type:** [ActionProfile](#prefactor_http.models.agent_instance.ActionProfile) #### params\_data\_categories [Section titled “params\_data\_categories”](#params_data_categories) Data categories present in params * **Type:** [DataCategories](#prefactor_http.models.agent_instance.DataCategories) #### result\_data\_categories [Section titled “result\_data\_categories”](#result_data_categories) Data categories present in result * **Type:** [DataCategories](#prefactor_http.models.agent_instance.DataCategories) #### action\_profile *: [ActionProfile](#prefactor_http.models.agent_instance.ActionProfile)* [Section titled “action\_profile : ActionProfile”](#action_profile--actionprofile) #### model\_config *= {‘extra’: ‘allow’}* [Section titled “model\_config = {‘extra’: ‘allow’}”](#model_config--extra-allow) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### params\_data\_categories *: [DataCategories](#prefactor_http.models.agent_instance.DataCategories)* [Section titled “params\_data\_categories : DataCategories”](#params_data_categories--datacategories) #### result\_data\_categories *: [DataCategories](#prefactor_http.models.agent_instance.DataCategories)* [Section titled “result\_data\_categories : DataCategories”](#result_data_categories--datacategories) ### *class* prefactor\_http.models.agent\_instance.FinishInstanceRequest(, status: Literal\[‘complete’, ‘failed’, ‘cancelled’] | None = None, timestamp: str | None = None, idempotency\_key: str | None = None) [Section titled “class prefactor\_http.models.agent\_instance.FinishInstanceRequest(, status: Literal\[‘complete’, ‘failed’, ‘cancelled’\] | None = None, timestamp: str | None = None, idempotency\_key: str | None = None)”](#class-prefactor_httpmodelsagent_instancefinishinstancerequest-status-literalcomplete-failed-cancelled--none--none-timestamp-str--none--none-idempotency_key-str--none--none) Bases: `BaseModel` Request to finish an agent instance. #### status [Section titled “status”](#status-1) Optional finish status (complete, failed, cancelled) * **Type:** FinishStatus | None #### timestamp [Section titled “timestamp”](#timestamp) Optional ISO 8601 timestamp (defaults to current time) * **Type:** str | None #### idempotency\_key [Section titled “idempotency\_key”](#idempotency_key) Optional idempotency key * **Type:** str | None #### idempotency\_key *: str | None* [Section titled “idempotency\_key : str | None”](#idempotency_key--str--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---7) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### status *: FinishStatus | None* [Section titled “status : FinishStatus | None”](#status--finishstatus--none) #### timestamp *: str | None* [Section titled “timestamp : str | None”](#timestamp--str--none) ### *class* prefactor\_http.models.agent\_instance.QualitySchemaDetails(, name: str, title: str, description: str | None = None, template: str | None = None, data\_risk: [DataRisk](#prefactor_http.models.agent_instance.DataRisk), schema: dict, schema\_validation: dict) [Section titled “class prefactor\_http.models.agent\_instance.QualitySchemaDetails(, name: str, title: str, description: str | None = None, template: str | None = None, data\_risk: DataRisk, schema: dict, schema\_validation: dict)”](#class-prefactor_httpmodelsagent_instancequalityschemadetails-name-str-title-str-description-str--none--none-template-str--none--none-data_risk-datarisk-schema-dict-schema_validation-dict) Bases: `BaseModel` Quality schema details returned in agent schema version responses. #### name [Section titled “name”](#name-2) Unique identifier for this quality schema entry * **Type:** str #### title [Section titled “title”](#title) Human-readable title * **Type:** str #### description [Section titled “description”](#description-1) Optional description * **Type:** str | None #### template [Section titled “template”](#template) Optional display template * **Type:** str | None #### data\_risk [Section titled “data\_risk”](#data_risk) Data risk classification * **Type:** [DataRisk](#prefactor_http.models.agent_instance.DataRisk) #### schema [Section titled “schema”](#schema) JSON schema for the quality payload #### schema\_validation [Section titled “schema\_validation”](#schema_validation) Schema validation result * **Type:** dict #### data\_risk *: [DataRisk](#prefactor_http.models.agent_instance.DataRisk)* [Section titled “data\_risk : DataRisk”](#data_risk--datarisk) #### description *: str | None* [Section titled “description : str | None”](#description--str--none-1) #### model\_config *= {‘populate\_by\_name’: True, ‘validate\_by\_alias’: True, ‘validate\_by\_name’: True}* [Section titled “model\_config = {‘populate\_by\_name’: True, ‘validate\_by\_alias’: True, ‘validate\_by\_name’: True}”](#model_config--populate_by_name-true-validate_by_alias-true-validate_by_name-true) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-1) #### schema\_ *: dict* [Section titled “schema\_ : dict”](#schema_--dict) #### schema\_validation *: dict* [Section titled “schema\_validation : dict”](#schema_validation--dict) #### template *: str | None* [Section titled “template : str | None”](#template--str--none) #### title *: str* [Section titled “title : str”](#title--str) ### *class* prefactor\_http.models.agent\_instance.QualitySchemaForCreate(, name: str, schema: dict, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: [DataRisk](#prefactor_http.models.agent_instance.DataRisk) | None = None) [Section titled “class prefactor\_http.models.agent\_instance.QualitySchemaForCreate(, name: str, schema: dict, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: DataRisk | None = None)”](#class-prefactor_httpmodelsagent_instancequalityschemaforcreate-name-str-schema-dict-title-str--none--none-description-str--none--none-template-str--none--none-data_risk-datarisk--none--none) Bases: `BaseModel` Named quality schema definition for agent schema version registration. #### name [Section titled “name”](#name-3) Unique identifier for this quality schema entry * **Type:** str #### schema [Section titled “schema”](#schema-1) JSON schema for the quality payload #### title [Section titled “title”](#title-1) Optional human-readable title (defaults to name) * **Type:** str | None #### description [Section titled “description”](#description-2) Optional description * **Type:** str | None #### template [Section titled “template”](#template-1) Optional display template using `{{field}}` interpolation * **Type:** str | None #### data\_risk [Section titled “data\_risk”](#data_risk-1) Optional data risk classification * **Type:** [DataRisk](#prefactor_http.models.agent_instance.DataRisk) | None #### data\_risk *: [DataRisk](#prefactor_http.models.agent_instance.DataRisk) | None* [Section titled “data\_risk : DataRisk | None”](#data_risk--datarisk--none) #### description *: str | None* [Section titled “description : str | None”](#description--str--none-2) #### model\_config *= {‘populate\_by\_name’: True, ‘validate\_by\_alias’: True, ‘validate\_by\_name’: True}* [Section titled “model\_config = {‘populate\_by\_name’: True, ‘validate\_by\_alias’: True, ‘validate\_by\_name’: True}”](#model_config--populate_by_name-true-validate_by_alias-true-validate_by_name-true-1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-2) #### schema\_ *: dict* [Section titled “schema\_ : dict”](#schema_--dict-1) #### template *: str | None* [Section titled “template : str | None”](#template--str--none-1) #### title *: str | None* [Section titled “title : str | None”](#title--str--none) ### *class* prefactor\_http.models.agent\_instance.RegisterAgentInstanceRequest(, agent\_id: str | None = None, environment\_id: str | None = None, agent\_version: [AgentVersionForRegister](#prefactor_http.models.agent_instance.AgentVersionForRegister), agent\_schema\_version: [AgentSchemaVersionForRegister](#prefactor_http.models.agent_instance.AgentSchemaVersionForRegister), id: str | None = None, external\_identifier: str | None = None, idempotency\_key: str | None = None, update\_current\_version: bool | None = None, purpose: Literal\[‘live’, ‘smoke\_test’, ‘eval’] | None = None) [Section titled “class prefactor\_http.models.agent\_instance.RegisterAgentInstanceRequest(, agent\_id: str | None = None, environment\_id: str | None = None, agent\_version: AgentVersionForRegister, agent\_schema\_version: AgentSchemaVersionForRegister, id: str | None = None, external\_identifier: str | None = None, idempotency\_key: str | None = None, update\_current\_version: bool | None = None, purpose: Literal\[‘live’, ‘smoke\_test’, ‘eval’\] | None = None)”](#class-prefactor_httpmodelsagent_instanceregisteragentinstancerequest-agent_id-str--none--none-environment_id-str--none--none-agent_version-agentversionforregister-agent_schema_version-agentschemaversionforregister-id-str--none--none-external_identifier-str--none--none-idempotency_key-str--none--none-update_current_version-bool--none--none-purpose-literallive-smoke_test-eval--none--none) Bases: `BaseModel` Request to register a new agent instance. #### agent\_id [Section titled “agent\_id”](#agent_id-1) Agent ID; omit when using a deployment-scoped token * **Type:** str | None #### environment\_id [Section titled “environment\_id”](#environment_id-1) Environment to deploy into; omit when using a deployment-scoped token (server reads it from the token) * **Type:** str | None #### agent\_version [Section titled “agent\_version”](#agent_version) Version information for the agent * **Type:** [AgentVersionForRegister](#prefactor_http.models.agent_instance.AgentVersionForRegister) #### agent\_schema\_version [Section titled “agent\_schema\_version”](#agent_schema_version) Schema version for the agent * **Type:** [AgentSchemaVersionForRegister](#prefactor_http.models.agent_instance.AgentSchemaVersionForRegister) #### id [Section titled “id”](#id-1) Optional custom ID for the instance * **Type:** str | None #### external\_identifier [Section titled “external\_identifier”](#external_identifier-3) Optional external identifier (unique per agent) * **Type:** str | None #### idempotency\_key [Section titled “idempotency\_key”](#idempotency_key-1) Optional idempotency key * **Type:** str | None #### update\_current\_version [Section titled “update\_current\_version”](#update_current_version) Whether to update the current version * **Type:** bool | None #### purpose [Section titled “purpose”](#purpose-1) Why this instance ran (live, smoke\_test, eval) * **Type:** InstancePurpose | None #### agent\_id *: str | None* [Section titled “agent\_id : str | None”](#agent_id--str--none) #### agent\_schema\_version *: [AgentSchemaVersionForRegister](#prefactor_http.models.agent_instance.AgentSchemaVersionForRegister)* [Section titled “agent\_schema\_version : AgentSchemaVersionForRegister”](#agent_schema_version--agentschemaversionforregister) #### agent\_version *: [AgentVersionForRegister](#prefactor_http.models.agent_instance.AgentVersionForRegister)* [Section titled “agent\_version : AgentVersionForRegister”](#agent_version--agentversionforregister) #### environment\_id *: str | None* [Section titled “environment\_id : str | None”](#environment_id--str--none) #### external\_identifier *: str | None* [Section titled “external\_identifier : str | None”](#external_identifier--str--none-3) #### id *: str | None* [Section titled “id : str | None”](#id--str--none) #### idempotency\_key *: str | None* [Section titled “idempotency\_key : str | None”](#idempotency_key--str--none-1) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---8) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### purpose *: InstancePurpose | None* [Section titled “purpose : InstancePurpose | None”](#purpose--instancepurpose--none-1) #### update\_current\_version *: bool | None* [Section titled “update\_current\_version : bool | None”](#update_current_version--bool--none) ### *class* prefactor\_http.models.agent\_instance.RuntimeEnvironment(, agent\_sdk: list\[str] | None = None, os: str | None = None, prefactor\_sdk: list\[str] | None = None, runtime: str | None = None) [Section titled “class prefactor\_http.models.agent\_instance.RuntimeEnvironment(, agent\_sdk: list\[str\] | None = None, os: str | None = None, prefactor\_sdk: list\[str\] | None = None, runtime: str | None = None)”](#class-prefactor_httpmodelsagent_instanceruntimeenvironment-agent_sdk-liststr--none--none-os-str--none--none-prefactor_sdk-liststr--none--none-runtime-str--none--none) Bases: `BaseModel` Runtime environment information for an agent version. Captures the agent framework, Prefactor SDK, OS, and language runtime in use when this agent version was registered. #### agent\_sdk [Section titled “agent\_sdk”](#agent_sdk) Agent framework packages (e.g. \[””]). * **Type:** list\[str] | None #### os [Section titled “os”](#os) Operating system name (e.g. “linux”, “darwin”). * **Type:** str | None #### prefactor\_sdk [Section titled “prefactor\_sdk”](#prefactor_sdk) Prefactor SDK packages in use. * **Type:** list\[str] | None #### runtime [Section titled “runtime”](#runtime) Language runtime (e.g. “”). * **Type:** str | None #### agent\_sdk *: list\[str] | None* [Section titled “agent\_sdk : list\[str\] | None”](#agent_sdk--liststr--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---9) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### os *: str | None* [Section titled “os : str | None”](#os--str--none) #### prefactor\_sdk *: list\[str] | None* [Section titled “prefactor\_sdk : list\[str\] | None”](#prefactor_sdk--liststr--none) #### runtime *: str | None* [Section titled “runtime : str | None”](#runtime--str--none) ### *class* prefactor\_http.models.agent\_instance.SpanTypeSchemaForCreate(, name: str, params\_schema: dict, result\_schema: dict | None = None, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: [DataRisk](#prefactor_http.models.agent_instance.DataRisk) | None = None) [Section titled “class prefactor\_http.models.agent\_instance.SpanTypeSchemaForCreate(, name: str, params\_schema: dict, result\_schema: dict | None = None, title: str | None = None, description: str | None = None, template: str | None = None, data\_risk: DataRisk | None = None)”](#class-prefactor_httpmodelsagent_instancespantypeschemaforcreate-name-str-params_schema-dict-result_schema-dict--none--none-title-str--none--none-description-str--none--none-template-str--none--none-data_risk-datarisk--none--none) Bases: `BaseModel` Span type schema details for registration. #### name [Section titled “name”](#name-4) Name of the span type * **Type:** str #### params\_schema [Section titled “params\_schema”](#params_schema) JSON schema for span parameters * **Type:** dict #### result\_schema [Section titled “result\_schema”](#result_schema) Optional JSON schema for span results * **Type:** dict | None #### title [Section titled “title”](#title-2) Optional human-readable title * **Type:** str | None #### description [Section titled “description”](#description-3) Optional description * **Type:** str | None #### template [Section titled “template”](#template-2) Optional template string * **Type:** str | None #### data\_risk [Section titled “data\_risk”](#data_risk-2) Optional data risk classification * **Type:** [DataRisk](#prefactor_http.models.agent_instance.DataRisk) | None #### data\_risk *: [DataRisk](#prefactor_http.models.agent_instance.DataRisk) | None* [Section titled “data\_risk : DataRisk | None”](#data_risk--datarisk--none-1) #### description *: str | None* [Section titled “description : str | None”](#description--str--none-3) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---10) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### name *: str* [Section titled “name : str”](#name--str-3) #### params\_schema *: dict* [Section titled “params\_schema : dict”](#params_schema--dict) #### result\_schema *: dict | None* [Section titled “result\_schema : dict | None”](#result_schema--dict--none) #### template *: str | None* [Section titled “template : str | None”](#template--str--none-2) #### title *: str | None* [Section titled “title : str | None”](#title--str--none-1) ### *class* prefactor\_http.models.agent\_instance.TimestampRequest(, timestamp: str | None = None, idempotency\_key: str | None = None) [Section titled “class prefactor\_http.models.agent\_instance.TimestampRequest(, timestamp: str | None = None, idempotency\_key: str | None = None)”](#class-prefactor_httpmodelsagent_instancetimestamprequest-timestamp-str--none--none-idempotency_key-str--none--none) Bases: `BaseModel` Request with optional timestamp for start/finish operations. #### timestamp [Section titled “timestamp”](#timestamp-1) Optional ISO 8601 timestamp (defaults to current time) * **Type:** str | None #### idempotency\_key [Section titled “idempotency\_key”](#idempotency_key-2) Optional idempotency key * **Type:** str | None #### idempotency\_key *: str | None* [Section titled “idempotency\_key : str | None”](#idempotency_key--str--none-2) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---11) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### timestamp *: str | None* [Section titled “timestamp : str | None”](#timestamp--str--none-1) # prefactor_http.models.agent_span module # prefactor\_http.models.agent\_span module [Section titled “prefactor\_http.models.agent\_span module”](#prefactor_httpmodelsagent_span-module) AgentSpan data models. ### *class* prefactor\_http.models.agent\_span.AgentSpan(\*, type: \~typing.Literal\[‘agent\_span’], id: str, account\_id: str | None = None, agent\_id: str | None = None, agent\_instance\_id: str, parent\_span\_id: str | None = None, schema\_name: str, schema\_title: str | None = None, status: \~typing.Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’], payload: dict = , result\_payload: dict | None = None, summary: str | None = None, started\_at: \~datetime.datetime | None = None, inserted\_at: \~datetime.datetime | None = None, updated\_at: \~datetime.datetime | None = None, finished\_at: \~datetime.datetime | None = None) [Section titled “class prefactor\_http.models.agent\_span.AgentSpan(\*, type: \~typing.Literal\[‘agent\_span’\], id: str, account\_id: str | None = None, agent\_id: str | None = None, agent\_instance\_id: str, parent\_span\_id: str | None = None, schema\_name: str, schema\_title: str | None = None, status: \~typing.Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\], payload: dict = , result\_payload: dict | None = None, summary: str | None = None, started\_at: \~datetime.datetime | None = None, inserted\_at: \~datetime.datetime | None = None, updated\_at: \~datetime.datetime | None = None, finished\_at: \~datetime.datetime | None = None)”](#class-prefactor_httpmodelsagent_spanagentspan-type-typingliteralagent_span-id-str-account_id-str--none--none-agent_id-str--none--none-agent_instance_id-str-parent_span_id-str--none--none-schema_name-str-schema_title-str--none--none-status-typingliteralpending-active-complete-failed-cancelled-terminated-payload-dict---result_payload-dict--none--none-summary-str--none--none-started_at-datetimedatetime--none--none-inserted_at-datetimedatetime--none--none-updated_at-datetimedatetime--none--none-finished_at-datetimedatetime--none--none) Bases: `BaseModel` Agent span model. #### type [Section titled “type”](#type) Resource type (always “agent\_span”) * **Type:** Literal\[‘agent\_span’] #### id [Section titled “id”](#id) Span ID * **Type:** str #### account\_id [Section titled “account\_id”](#account_id) Account ID * **Type:** str | None #### agent\_id [Section titled “agent\_id”](#agent_id) Agent ID * **Type:** str | None #### agent\_instance\_id [Section titled “agent\_instance\_id”](#agent_instance_id) Agent instance ID * **Type:** str #### parent\_span\_id [Section titled “parent\_span\_id”](#parent_span_id) Parent span ID (None if root span) * **Type:** str | None #### schema\_name [Section titled “schema\_name”](#schema_name) Name of the schema for this span * **Type:** str #### schema\_title [Section titled “schema\_title”](#schema_title) Title of the schema for this span * **Type:** str | None #### status [Section titled “status”](#status) Span status * **Type:** Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’] #### payload [Section titled “payload”](#payload) Span payload data * **Type:** dict #### result\_payload [Section titled “result\_payload”](#result_payload) Result payload data * **Type:** dict | None #### summary [Section titled “summary”](#summary) Optional span summary * **Type:** str | None #### started\_at [Section titled “started\_at”](#started_at) When the span started * **Type:** datetime.datetime | None #### inserted\_at [Section titled “inserted\_at”](#inserted_at) When the span was created * **Type:** datetime.datetime | None #### updated\_at [Section titled “updated\_at”](#updated_at) When the span was last updated * **Type:** datetime.datetime | None #### finished\_at [Section titled “finished\_at”](#finished_at) When the span finished (None if in progress) * **Type:** datetime.datetime | None #### account\_id *: str | None* [Section titled “account\_id : str | None”](#account_id--str--none) #### agent\_id *: str | None* [Section titled “agent\_id : str | None”](#agent_id--str--none) #### agent\_instance\_id *: str* [Section titled “agent\_instance\_id : str”](#agent_instance_id--str) #### finished\_at *: datetime | None* [Section titled “finished\_at : datetime | None”](#finished_at--datetime--none) #### id *: str* [Section titled “id : str”](#id--str) #### inserted\_at *: datetime | None* [Section titled “inserted\_at : datetime | None”](#inserted_at--datetime--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config--) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### parent\_span\_id *: str | None* [Section titled “parent\_span\_id : str | None”](#parent_span_id--str--none) #### payload *: dict* [Section titled “payload : dict”](#payload--dict) #### result\_payload *: dict | None* [Section titled “result\_payload : dict | None”](#result_payload--dict--none) #### schema\_name *: str* [Section titled “schema\_name : str”](#schema_name--str) #### schema\_title *: str | None* [Section titled “schema\_title : str | None”](#schema_title--str--none) #### started\_at *: datetime | None* [Section titled “started\_at : datetime | None”](#started_at--datetime--none) #### status *: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’]* [Section titled “status : Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\]”](#status--literalpending-active-complete-failed-cancelled-terminated) #### summary *: str | None* [Section titled “summary : str | None”](#summary--str--none) #### type *: Literal\[‘agent\_span’]* [Section titled “type : Literal\[‘agent\_span’\]”](#type--literalagent_span) #### updated\_at *: datetime | None* [Section titled “updated\_at : datetime | None”](#updated_at--datetime--none) ### *class* prefactor\_http.models.agent\_span.CreateAgentSpanRequest(\*, agent\_instance\_id: str, schema\_name: str, status: \~typing.Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’], payload: dict = , result\_payload: dict | None = None, id: str | None = None, parent\_span\_id: str | None = None, started\_at: str | None = None, finished\_at: str | None = None, idempotency\_key: str | None = None) [Section titled “class prefactor\_http.models.agent\_span.CreateAgentSpanRequest(\*, agent\_instance\_id: str, schema\_name: str, status: \~typing.Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\], payload: dict = , result\_payload: dict | None = None, id: str | None = None, parent\_span\_id: str | None = None, started\_at: str | None = None, finished\_at: str | None = None, idempotency\_key: str | None = None)”](#class-prefactor_httpmodelsagent_spancreateagentspanrequest-agent_instance_id-str-schema_name-str-status-typingliteralpending-active-complete-failed-cancelled-terminated-payload-dict---result_payload-dict--none--none-id-str--none--none-parent_span_id-str--none--none-started_at-str--none--none-finished_at-str--none--none-idempotency_key-str--none--none) Bases: `BaseModel` Request to create a new agent span. #### agent\_instance\_id [Section titled “agent\_instance\_id”](#agent_instance_id-1) ID of the agent instance this span belongs to * **Type:** str #### schema\_name [Section titled “schema\_name”](#schema_name-1) Name of the schema for this span * **Type:** str #### status [Section titled “status”](#status-1) Status for the span * **Type:** Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’] #### payload [Section titled “payload”](#payload-1) Span payload data (arbitrary JSON object) * **Type:** dict #### result\_payload [Section titled “result\_payload”](#result_payload-1) Optional result payload data * **Type:** dict | None #### id [Section titled “id”](#id-1) Optional custom ID for the span * **Type:** str | None #### parent\_span\_id [Section titled “parent\_span\_id”](#parent_span_id-1) Optional ID of the parent span * **Type:** str | None #### started\_at [Section titled “started\_at”](#started_at-1) Optional ISO 8601 start time (defaults to current time) * **Type:** str | None #### finished\_at [Section titled “finished\_at”](#finished_at-1) Optional ISO 8601 finish time (null if in progress) * **Type:** str | None #### idempotency\_key [Section titled “idempotency\_key”](#idempotency_key) Optional idempotency key * **Type:** str | None #### agent\_instance\_id *: str* [Section titled “agent\_instance\_id : str”](#agent_instance_id--str-1) #### finished\_at *: str | None* [Section titled “finished\_at : str | None”](#finished_at--str--none) #### id *: str | None* [Section titled “id : str | None”](#id--str--none) #### idempotency\_key *: str | None* [Section titled “idempotency\_key : str | None”](#idempotency_key--str--none) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### parent\_span\_id *: str | None* [Section titled “parent\_span\_id : str | None”](#parent_span_id--str--none-1) #### payload *: dict* [Section titled “payload : dict”](#payload--dict-1) #### result\_payload *: dict | None* [Section titled “result\_payload : dict | None”](#result_payload--dict--none-1) #### schema\_name *: str* [Section titled “schema\_name : str”](#schema_name--str-1) #### started\_at *: str | None* [Section titled “started\_at : str | None”](#started_at--str--none) #### status *: Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’]* [Section titled “status : Literal\[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’, ‘terminated’\]”](#status--literalpending-active-complete-failed-cancelled-terminated-1) ### *class* prefactor\_http.models.agent\_span.FinishSpanRequest(, status: Literal\[‘complete’, ‘failed’, ‘cancelled’] | None = None, result\_payload: dict | None = None, timestamp: str | None = None, idempotency\_key: str | None = None) [Section titled “class prefactor\_http.models.agent\_span.FinishSpanRequest(, status: Literal\[‘complete’, ‘failed’, ‘cancelled’\] | None = None, result\_payload: dict | None = None, timestamp: str | None = None, idempotency\_key: str | None = None)”](#class-prefactor_httpmodelsagent_spanfinishspanrequest-status-literalcomplete-failed-cancelled--none--none-result_payload-dict--none--none-timestamp-str--none--none-idempotency_key-str--none--none) Bases: `BaseModel` Request to finish an agent span. #### status [Section titled “status”](#status-2) Optional finish status (complete, failed, cancelled) * **Type:** Literal\[‘complete’, ‘failed’, ‘cancelled’] | None #### result\_payload [Section titled “result\_payload”](#result_payload-2) Optional result payload data * **Type:** dict | None #### timestamp [Section titled “timestamp”](#timestamp) Optional ISO 8601 timestamp (defaults to current time) * **Type:** str | None #### idempotency\_key [Section titled “idempotency\_key”](#idempotency_key-1) Optional idempotency key * **Type:** str | None #### idempotency\_key *: str | None* [Section titled “idempotency\_key : str | None”](#idempotency_key--str--none-1) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---2) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### result\_payload *: dict | None* [Section titled “result\_payload : dict | None”](#result_payload--dict--none-2) #### status *: Literal\[‘complete’, ‘failed’, ‘cancelled’] | None* [Section titled “status : Literal\[‘complete’, ‘failed’, ‘cancelled’\] | None”](#status--literalcomplete-failed-cancelled--none) #### timestamp *: str | None* [Section titled “timestamp : str | None”](#timestamp--str--none) # prefactor_http.models.base module # prefactor\_http.models.base module [Section titled “prefactor\_http.models.base module”](#prefactor_httpmodelsbase-module) Base response models for Prefactor API. ### *class* prefactor\_http.models.base.ApiError(, status: str = ‘error’, code: str, message: str) [Section titled “class prefactor\_http.models.base.ApiError(, status: str = ‘error’, code: str, message: str)”](#class-prefactor_httpmodelsbaseapierror-status-str--error-code-str-message-str) Bases: `BaseModel` API error response. #### status [Section titled “status”](#status) Response status (always “error”) * **Type:** str #### code [Section titled “code”](#code) Error code * **Type:** str #### message [Section titled “message”](#message) Human-readable error message * **Type:** str #### code *: str* [Section titled “code : str”](#code--str) #### message *: str* [Section titled “message : str”](#message--str) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config--) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### status *: str* [Section titled “status : str”](#status--str) ### *class* prefactor\_http.models.base.ApiResponse(, status: str, details: T) [Section titled “class prefactor\_http.models.base.ApiResponse(, status: str, details: T)”](#class-prefactor_httpmodelsbaseapiresponse-status-str-details-t) Bases: `BaseModel`, `Generic`\[`T`] Generic API response wrapper. #### status [Section titled “status”](#status-1) Response status (always “success” for successful requests) * **Type:** str #### details [Section titled “details”](#details) Detailed response data * **Type:** prefactor\_http.models.base.T #### details *: T* [Section titled “details : T”](#details--t) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### status *: str* [Section titled “status : str”](#status--str-1) ### *class* prefactor\_http.models.base.DetailedApiError(, status: str = ‘error’, code: str, message: str, errors: dict\[str, Any]) [Section titled “class prefactor\_http.models.base.DetailedApiError(, status: str = ‘error’, code: str, message: str, errors: dict\[str, Any\])”](#class-prefactor_httpmodelsbasedetailedapierror-status-str--error-code-str-message-str-errors-dictstr-any) Bases: [`ApiError`](#prefactor_http.models.base.ApiError) API error with detailed validation errors. #### errors [Section titled “errors”](#errors) Map of field names to error messages * **Type:** dict\[str, Any] #### errors *: dict\[str, Any]* [Section titled “errors : dict\[str, Any\]”](#errors--dictstr-any) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---2) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. ### *class* prefactor\_http.models.base.ListResponse(, status: str, summaries: list\[T], pagination: [PaginationOutput](#prefactor_http.models.base.PaginationOutput) | None, sorting: [Sorting](#prefactor_http.models.base.Sorting) | None) [Section titled “class prefactor\_http.models.base.ListResponse(, status: str, summaries: list\[T\], pagination: PaginationOutput | None, sorting: Sorting | None)”](#class-prefactor_httpmodelsbaselistresponse-status-str-summaries-listt-pagination-paginationoutput--none-sorting-sorting--none) Bases: `BaseModel`, `Generic`\[`T`] Generic list response wrapper. #### status [Section titled “status”](#status-2) Response status (always “success”) * **Type:** str #### summaries [Section titled “summaries”](#summaries) List of items * **Type:** list\[prefactor\_http.models.base.T] #### pagination [Section titled “pagination”](#pagination) Pagination information * **Type:** [prefactor\_http.models.base.PaginationOutput](#prefactor_http.models.base.PaginationOutput) | None #### sorting [Section titled “sorting”](#sorting) Sorting information * **Type:** [prefactor\_http.models.base.Sorting](#prefactor_http.models.base.Sorting) | None #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---3) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### pagination *: [PaginationOutput](#prefactor_http.models.base.PaginationOutput) | None* [Section titled “pagination : PaginationOutput | None”](#pagination--paginationoutput--none) #### sorting *: [Sorting](#prefactor_http.models.base.Sorting) | None* [Section titled “sorting : Sorting | None”](#sorting--sorting--none) #### status *: str* [Section titled “status : str”](#status--str-2) #### summaries *: list\[T]* [Section titled “summaries : list\[T\]”](#summaries--listt) ### *class* prefactor\_http.models.base.PaginationOutput(, item\_count: int, item\_end: int, item\_start: int, next\_page\_offset: int | None, page\_count: int, page\_index: int, page\_offset: int, page\_size: int, previous\_page\_offset: int | None) [Section titled “class prefactor\_http.models.base.PaginationOutput(, item\_count: int, item\_end: int, item\_start: int, next\_page\_offset: int | None, page\_count: int, page\_index: int, page\_offset: int, page\_size: int, previous\_page\_offset: int | None)”](#class-prefactor_httpmodelsbasepaginationoutput-item_count-int-item_end-int-item_start-int-next_page_offset-int--none-page_count-int-page_index-int-page_offset-int-page_size-int-previous_page_offset-int--none) Bases: `BaseModel` Pagination information. #### item\_count [Section titled “item\_count”](#item_count) Total number of items * **Type:** int #### item\_end [Section titled “item\_end”](#item_end) Index of last item in page (one-based) * **Type:** int #### item\_start [Section titled “item\_start”](#item_start) Index of first item in page (one-based) * **Type:** int #### next\_page\_offset [Section titled “next\_page\_offset”](#next_page_offset) Offset of next page (null if last page) * **Type:** int | None #### page\_count [Section titled “page\_count”](#page_count) Total number of pages * **Type:** int #### page\_index [Section titled “page\_index”](#page_index) Index of current page (one-based) * **Type:** int #### page\_offset [Section titled “page\_offset”](#page_offset) Offset of first item (zero-based) * **Type:** int #### page\_size [Section titled “page\_size”](#page_size) Number of items per page * **Type:** int #### previous\_page\_offset [Section titled “previous\_page\_offset”](#previous_page_offset) Offset of previous page (null if first page) * **Type:** int | None #### item\_count *: int* [Section titled “item\_count : int”](#item_count--int) #### item\_end *: int* [Section titled “item\_end : int”](#item_end--int) #### item\_start *: int* [Section titled “item\_start : int”](#item_start--int) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---4) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### next\_page\_offset *: int | None* [Section titled “next\_page\_offset : int | None”](#next_page_offset--int--none) #### page\_count *: int* [Section titled “page\_count : int”](#page_count--int) #### page\_index *: int* [Section titled “page\_index : int”](#page_index--int) #### page\_offset *: int* [Section titled “page\_offset : int”](#page_offset--int) #### page\_size *: int* [Section titled “page\_size : int”](#page_size--int) #### previous\_page\_offset *: int | None* [Section titled “previous\_page\_offset : int | None”](#previous_page_offset--int--none) ### *class* prefactor\_http.models.base.Sorting(, field: str, direction: str) [Section titled “class prefactor\_http.models.base.Sorting(, field: str, direction: str)”](#class-prefactor_httpmodelsbasesorting-field-str-direction-str) Bases: `BaseModel` Sorting information. #### field [Section titled “field”](#field) Field to sort by * **Type:** str #### direction [Section titled “direction”](#direction) Sort direction (asc or desc) * **Type:** str #### direction *: str* [Section titled “direction : str”](#direction--str) #### field *: str* [Section titled “field : str”](#field--str) #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---5) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. # prefactor_http.models.bulk module # prefactor\_http.models.bulk module [Section titled “prefactor\_http.models.bulk module”](#prefactor_httpmodelsbulk-module) Models for the Bulk API. ### *class* prefactor\_http.models.bulk.BulkItem(, \_type: str, idempotency\_key: Annotated\[str, MinLen(min\_length=8), MaxLen(max\_length=64)], \*\*extra\_data: Any) [Section titled “class prefactor\_http.models.bulk.BulkItem(, \_type: str, idempotency\_key: Annotated\[str, MinLen(min\_length=8), MaxLen(max\_length=64)\], \*\*extra\_data: Any)”](#class-prefactor_httpmodelsbulkbulkitem-_type-str-idempotency_key-annotatedstr-minlenmin_length8-maxlenmax_length64-extra_data-any) Bases: `BaseModel` A single item in a bulk request. Each item must include \_type and idempotency\_key, plus any additional parameters required by the specific action type. #### idempotency\_key *: str* [Section titled “idempotency\_key : str”](#idempotency_key--str) Required unique idempotency key for this item. Must be at least 8 characters long and unique within the request. #### model\_config *= {‘extra’: ‘allow’}* [Section titled “model\_config = {‘extra’: ‘allow’}”](#model_config--extra-allow) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### type *: str* [Section titled “type : str”](#type--str) The type of query/action to execute (e.g., ‘agents/list’, ‘agents/create’). ### *class* prefactor\_http.models.bulk.BulkOutput(, status: str, \*\*extra\_data: Any) [Section titled “class prefactor\_http.models.bulk.BulkOutput(, status: str, \*\*extra\_data: Any)”](#class-prefactor_httpmodelsbulkbulkoutput-status-str-extra_data-any) Bases: `BaseModel` Output from a query or action. Contains either a success response (with ‘status’: ‘success’ and operation-specific data) or an error response (with ‘status’: ‘error’, ‘code’, ‘message’, and optionally ‘errors’). #### model\_config *= {‘extra’: ‘allow’}* [Section titled “model\_config = {‘extra’: ‘allow’}”](#model_config--extra-allow-1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### status *: str* [Section titled “status : str”](#status--str) ‘success’ or ‘error’. * **Type:** Status of the operation #### *classmethod* validate\_status(v: str) → str [Section titled “classmethod validate\_status(v: str) → str”](#classmethod-validate_statusv-str--str) ### *class* prefactor\_http.models.bulk.BulkRequest(, items: Annotated\[list\[[BulkItem](#prefactor_http.models.bulk.BulkItem)], MinLen(min\_length=1)]) [Section titled “class prefactor\_http.models.bulk.BulkRequest(, items: Annotated\[list\[BulkItem\], MinLen(min\_length=1)\])”](#class-prefactor_httpmodelsbulkbulkrequest-items-annotatedlistbulkitem-minlenmin_length1) Bases: `BaseModel` Request body for bulk query/action operations. Allows executing multiple API operations in a single request. #### items *: list\[[BulkItem](#prefactor_http.models.bulk.BulkItem)]* [Section titled “items : list\[BulkItem\]”](#items--listbulkitem) List of items to process in bulk. Each item will be processed independently in its own transaction. #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config--) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### *classmethod* validate\_unique\_idempotency\_keys(items: list\[[BulkItem](#prefactor_http.models.bulk.BulkItem)]) → list\[[BulkItem](#prefactor_http.models.bulk.BulkItem)] [Section titled “classmethod validate\_unique\_idempotency\_keys(items: list\[BulkItem\]) → list\[BulkItem\]”](#classmethod-validate_unique_idempotency_keysitems-listbulkitem--listbulkitem) Validate that all idempotency keys are unique within the request. ### *class* prefactor\_http.models.bulk.BulkResponse(, status: str = ‘success’, outputs: dict\[str, [BulkOutput](#prefactor_http.models.bulk.BulkOutput)]) [Section titled “class prefactor\_http.models.bulk.BulkResponse(, status: str = ‘success’, outputs: dict\[str, BulkOutput\])”](#class-prefactor_httpmodelsbulkbulkresponse-status-str--success-outputs-dictstr-bulkoutput) Bases: `BaseModel` Response from bulk query/action operations. Contains a map of results keyed by the idempotency\_key from each request item. #### model\_config *= {}* [Section titled “model\_config = {}”](#model_config---1) Configuration for the model, should be a dictionary conforming to \[ConfigDict]\[pydantic.config.ConfigDict]. #### outputs *: dict\[str, [BulkOutput](#prefactor_http.models.bulk.BulkOutput)]* [Section titled “outputs : dict\[str, BulkOutput\]”](#outputs--dictstr-bulkoutput) Map where keys are the idempotency\_key values from the request, and values are the corresponding query/action outputs or error responses. #### status *: str* [Section titled “status : str”](#status--str-1) Response status, always ‘success’ when the request is processed. # prefactor_http.models.types module # prefactor\_http.models.types module [Section titled “prefactor\_http.models.types module”](#prefactor_httpmodelstypes-module) Shared type definitions for Prefactor API models. # prefactor_http.retry module # prefactor\_http.retry module [Section titled “prefactor\_http.retry module”](#prefactor_httpretry-module) Retry logic with exponential backoff and jitter. ### *class* prefactor\_http.retry.RetryHandler(config: [HttpClientConfig](prefactor_http.config.md#prefactor_http.config.HttpClientConfig)) [Section titled “class prefactor\_http.retry.RetryHandler(config: HttpClientConfig)”](#class-prefactor_httpretryretryhandlerconfig-httpclientconfig) Bases: `object` Handles retry logic with exponential backoff and jitter. #### *async* execute(operation: Callable\[\[…], Any], is\_retryable: Callable\[\[Exception], bool], \*args: Any, \*\*kwargs: Any) → Any [Section titled “async execute(operation: Callable\[\[…\], Any\], is\_retryable: Callable\[\[Exception\], bool\], \*args: Any, \*\*kwargs: Any) → Any”](#async-executeoperation-callable-any-is_retryable-callableexception-bool-args-any-kwargs-any--any) Execute an operation with retry logic. * **Parameters:** * **operation** – Async function to execute. * **is\_retryable** – Function that determines if an exception is retryable. * **\*args** – Positional arguments for the operation. * **\*\*kwargs** – Keyword arguments for the operation. * **Returns:** Result of the operation. * **Raises:** [**PrefactorRetryExhaustedError**](prefactor_http.md#prefactor_http.PrefactorRetryExhaustedError) – When all retry attempts are exhausted. # prefactor-langchain # prefactor-langchain [Section titled “prefactor-langchain”](#prefactor-langchain) LangChain integration for Prefactor observability. This package provides automatic tracing for LangChain agents using LangChain-specific span types. ## Installation [Section titled “Installation”](#installation) ```bash pip install prefactor-langchain ``` ## Usage [Section titled “Usage”](#usage) ### Factory pattern (quickest setup) [Section titled “Factory pattern (quickest setup)”](#factory-pattern-quickest-setup) ```python from prefactor_langchain import LangChainToolSchemaConfig, PrefactorMiddleware middleware = PrefactorMiddleware.from_config( api_url="https://app.prefactorai.com", api_token="your-api-token", agent_id="my-agent", # Optional for deployment-scoped tokens agent_name="My Agent", # optional tool_schemas={ "send_email": LangChainToolSchemaConfig( span_type="send-email", input_schema={ "type": "object", "properties": { "to": {"type": "string", "format": "email"}, "subject": {"type": "string"}, }, "required": ["to", "subject"], }, ) }, ) # Use with LangChain's create_agent() # Your agent will automatically create spans for: # - Agent execution (langchain:agent) # - LLM calls (langchain:llm) # - Tool executions (langchain:tool) # - Tool-specific executions (for example langchain:tool:send-email) result = agent.invoke({"messages": [...]}) # Middleware owns both client and instance; close when done await middleware.close() ``` With a deployment-scoped token you can omit `agent_id`; the backend derives the agent and environment from the token during registration. ### Pre-configured client [Section titled “Pre-configured client”](#pre-configured-client) Pass a client you created yourself when you need full control over its configuration or when you want to share a client across multiple middlewares. ```python from prefactor_core import PrefactorCoreClient, PrefactorCoreConfig from prefactor_http.config import HttpClientConfig from prefactor_langchain import PrefactorMiddleware http_config = HttpClientConfig( api_url="https://app.prefactorai.com", api_token="your-api-token" ) config = PrefactorCoreConfig(http_config=http_config) client = PrefactorCoreClient(config) await client.initialize() middleware = PrefactorMiddleware( client=client, agent_id="my-agent", # Optional for deployment-scoped tokens agent_name="My Agent", ) result = agent.invoke({"messages": [...]}) # You own the client; close both separately await middleware.close() # closes the agent instance only await client.close() ``` ### SchemaRegistry composition [Section titled “SchemaRegistry composition”](#schemaregistry-composition) Use a shared `SchemaRegistry` when you want custom workflow span types and LangChain tool schemas to be published together. ```python from prefactor_core import SchemaRegistry from prefactor_langchain import ( LangChainToolSchemaConfig, PrefactorMiddleware, register_langchain_schemas, ) registry = SchemaRegistry() registry.register_type( name="workflow:run", params_schema={"type": "object"}, result_schema={"type": "object"}, ) register_langchain_schemas( registry, tool_schemas={ "send_email": LangChainToolSchemaConfig( span_type="send-email", input_schema={ "type": "object", "properties": {"to": {"type": "string"}}, "required": ["to"], }, ) }, ) middleware = PrefactorMiddleware.from_config( api_url="https://app.prefactorai.com", api_token="your-api-token", agent_id="my-agent", # Optional for deployment-scoped tokens schema_registry=registry, ) ``` ### Pre-configured instance (spans outside the agent) [Section titled “Pre-configured instance (spans outside the agent)”](#pre-configured-instance-spans-outside-the-agent) Pass an `AgentInstanceHandle` you created yourself when you also need to instrument code that lives **outside** the LangChain agent — for example, pre-processing steps, post-processing, or any custom business logic that should appear as siblings of the agent spans in the same trace. ```python from prefactor_core import PrefactorCoreClient, PrefactorCoreConfig from prefactor_http.config import HttpClientConfig from prefactor_langchain import PrefactorMiddleware http_config = HttpClientConfig( api_url="https://app.prefactorai.com", api_token="your-api-token" ) config = PrefactorCoreConfig(http_config=http_config) client = PrefactorCoreClient(config) await client.initialize() instance = await client.create_agent_instance(agent_id="my-agent") await instance.start() # Share the instance with the middleware middleware = PrefactorMiddleware(instance=instance) # Instrument your own code using the same instance async with instance.span("custom:preprocessing") as ctx: ctx.set_payload({"step": "preprocess", "status": "ok"}) # Run your agent — the middleware traces it automatically under the same instance result = agent.invoke({"messages": [...]}) async with instance.span("custom:postprocessing") as ctx: ctx.set_payload({"step": "postprocess", "result": str(result)}) # You own the instance and client; clean them up yourself await instance.finish() await client.close() ``` If you pass `tool_schemas=...` with a pre-created instance, the middleware uses those mappings to emit the right tool span types at runtime. The instance’s already-registered schema version is not mutated, so you must register matching tool schemas before creating the instance if you want those per-tool span types to appear in the backend schema version. ## Span Types [Section titled “Span Types”](#span-types) This package creates LangChain-specific spans with the `langchain:*` namespace: * **`langchain:agent`** - Agent executions and chain runs * **`langchain:llm`** - LLM calls with model metadata (name, provider, token usage) * **`langchain:tool`** - Tool executions including retrievers Each span payload includes: * Timing information (start\_time, end\_time) * Inputs and outputs * Error information with stack traces * LangChain-specific metadata Trace correlation (span\_id, parent\_span\_id, trace\_id) is handled automatically by the prefactor-core client. ## Features [Section titled “Features”](#features) * **Automatic LLM call tracing** - Captures model name, provider, token usage, temperature * **Tool execution tracing** - Records tool name, arguments, execution time * **Agent/chain tracing** - Tracks agent lifecycle and message history * **Token usage capture** - Automatically extracts prompt/completion/total tokens * **Error tracking** - Captures error type, message, and stack traces * **Automatic parent-child relationships** - Uses SpanContextStack for hierarchy * **Bring your own instance** - Share a single `AgentInstanceHandle` between the middleware and your own instrumentation ## Architecture [Section titled “Architecture”](#architecture) This package follows the LangChain Adapter Redesign principles: 1. **Package Isolation**: LangChain-specific span types and schemas live in this package 2. **Opaque Payloads**: Span data is sent as payload to prefactor-core 3. **Type Namespacing**: Uses `langchain:agent`, `langchain:llm`, `langchain:tool` prefixes 4. **Uses prefactor-core**: All span/instance management via the prefactor-core client The middleware: 1. Accepts a `PrefactorCoreClient`, or a pre-created `AgentInstanceHandle`, or creates its own client via `from_config()` 2. Registers or borrows an agent instance 3. Creates spans with LangChain-specific payloads 4. Leverages `SpanContextStack` for automatic parent detection ## Development [Section titled “Development”](#development) Run tests: ```bash pytest tests/ ``` ## License [Section titled “License”](#license) MIT # prefactor_langchain # prefactor\_langchain [Section titled “prefactor\_langchain”](#prefactor_langchain) * [prefactor\_langchain package](prefactor_langchain.md) * [`AgentSpan`](prefactor_langchain.md#prefactor_langchain.AgentSpan) * [`AgentSpan.agent_config`](prefactor_langchain.md#prefactor_langchain.AgentSpan.agent_config) * [`AgentSpan.agent_name`](prefactor_langchain.md#prefactor_langchain.AgentSpan.agent_name) * [`AgentSpan.final_messages`](prefactor_langchain.md#prefactor_langchain.AgentSpan.final_messages) * [`AgentSpan.initial_messages`](prefactor_langchain.md#prefactor_langchain.AgentSpan.initial_messages) * [`AgentSpan.iteration_count`](prefactor_langchain.md#prefactor_langchain.AgentSpan.iteration_count) * [`AgentSpan.to_dict()`](prefactor_langchain.md#prefactor_langchain.AgentSpan.to_dict) * [`AgentSpan.type`](prefactor_langchain.md#prefactor_langchain.AgentSpan.type) * [`ErrorInfo`](prefactor_langchain.md#prefactor_langchain.ErrorInfo) * [`ErrorInfo.error_type`](prefactor_langchain.md#prefactor_langchain.ErrorInfo.error_type) * [`ErrorInfo.message`](prefactor_langchain.md#prefactor_langchain.ErrorInfo.message) * [`ErrorInfo.stacktrace`](prefactor_langchain.md#prefactor_langchain.ErrorInfo.stacktrace) * [`ErrorInfo.to_dict()`](prefactor_langchain.md#prefactor_langchain.ErrorInfo.to_dict) * [`LLMSpan`](prefactor_langchain.md#prefactor_langchain.LLMSpan) * [`LLMSpan.max_tokens`](prefactor_langchain.md#prefactor_langchain.LLMSpan.max_tokens) * [`LLMSpan.messages`](prefactor_langchain.md#prefactor_langchain.LLMSpan.messages) * [`LLMSpan.model_name`](prefactor_langchain.md#prefactor_langchain.LLMSpan.model_name) * [`LLMSpan.provider`](prefactor_langchain.md#prefactor_langchain.LLMSpan.provider) * [`LLMSpan.response_content`](prefactor_langchain.md#prefactor_langchain.LLMSpan.response_content) * [`LLMSpan.stop_sequences`](prefactor_langchain.md#prefactor_langchain.LLMSpan.stop_sequences) * [`LLMSpan.temperature`](prefactor_langchain.md#prefactor_langchain.LLMSpan.temperature) * [`LLMSpan.to_dict()`](prefactor_langchain.md#prefactor_langchain.LLMSpan.to_dict) * [`LLMSpan.token_usage`](prefactor_langchain.md#prefactor_langchain.LLMSpan.token_usage) * [`LLMSpan.top_p`](prefactor_langchain.md#prefactor_langchain.LLMSpan.top_p) * [`LLMSpan.type`](prefactor_langchain.md#prefactor_langchain.LLMSpan.type) * [`LangChainSpan`](prefactor_langchain.md#prefactor_langchain.LangChainSpan) * [`LangChainSpan.complete()`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.complete) * [`LangChainSpan.end_time`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.end_time) * [`LangChainSpan.error`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.error) * [`LangChainSpan.fail()`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.fail) * [`LangChainSpan.inputs`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.inputs) * [`LangChainSpan.metadata`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.metadata) * [`LangChainSpan.name`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.name) * [`LangChainSpan.outputs`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.outputs) * [`LangChainSpan.start_time`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.start_time) * [`LangChainSpan.status`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.status) * [`LangChainSpan.tags`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.tags) * [`LangChainSpan.to_dict()`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.to_dict) * [`LangChainSpan.type`](prefactor_langchain.md#prefactor_langchain.LangChainSpan.type) * [`LangChainToolSchemaConfig`](prefactor_langchain.md#prefactor_langchain.LangChainToolSchemaConfig) * [`LangChainToolSchemaConfig.span_type`](prefactor_langchain.md#prefactor_langchain.LangChainToolSchemaConfig.span_type) * [`LangChainToolSchemaConfig.input_schema`](prefactor_langchain.md#prefactor_langchain.LangChainToolSchemaConfig.input_schema) * [`LangChainToolSchemaConfig.input_schema`](prefactor_langchain.md#id0) * [`LangChainToolSchemaConfig.span_type`](prefactor_langchain.md#id1) * [`PrefactorMiddleware`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware) * [`PrefactorMiddleware.aafter_agent()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.aafter_agent) * [`PrefactorMiddleware.abefore_agent()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.abefore_agent) * [`PrefactorMiddleware.after_agent()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.after_agent) * [`PrefactorMiddleware.awrap_model_call()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.awrap_model_call) * [`PrefactorMiddleware.awrap_tool_call()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.awrap_tool_call) * [`PrefactorMiddleware.before_agent()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.before_agent) * [`PrefactorMiddleware.close()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.close) * [`PrefactorMiddleware.create_client()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.create_client) * [`PrefactorMiddleware.ensure_initialized()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.ensure_initialized) * [`PrefactorMiddleware.from_config()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.from_config) * [`PrefactorMiddleware.set_parent_span()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.set_parent_span) * [`PrefactorMiddleware.wrap_model_call()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.wrap_model_call) * [`PrefactorMiddleware.wrap_tool_call()`](prefactor_langchain.md#prefactor_langchain.PrefactorMiddleware.wrap_tool_call) * [`TokenUsage`](prefactor_langchain.md#prefactor_langchain.TokenUsage) * [`TokenUsage.completion_tokens`](prefactor_langchain.md#prefactor_langchain.TokenUsage.completion_tokens) * [`TokenUsage.prompt_tokens`](prefactor_langchain.md#prefactor_langchain.TokenUsage.prompt_tokens) * [`TokenUsage.to_dict()`](prefactor_langchain.md#prefactor_langchain.TokenUsage.to_dict) * [`TokenUsage.total_tokens`](prefactor_langchain.md#prefactor_langchain.TokenUsage.total_tokens) * [`ToolSpan`](prefactor_langchain.md#prefactor_langchain.ToolSpan) * [`ToolSpan.arguments`](prefactor_langchain.md#prefactor_langchain.ToolSpan.arguments) * [`ToolSpan.execution_time_ms`](prefactor_langchain.md#prefactor_langchain.ToolSpan.execution_time_ms) * [`ToolSpan.retriever_metadata`](prefactor_langchain.md#prefactor_langchain.ToolSpan.retriever_metadata) * [`ToolSpan.to_dict()`](prefactor_langchain.md#prefactor_langchain.ToolSpan.to_dict) * [`ToolSpan.tool_name`](prefactor_langchain.md#prefactor_langchain.ToolSpan.tool_name) * [`ToolSpan.tool_schema`](prefactor_langchain.md#prefactor_langchain.ToolSpan.tool_schema) * [`ToolSpan.tool_type`](prefactor_langchain.md#prefactor_langchain.ToolSpan.tool_type) * [`ToolSpan.type`](prefactor_langchain.md#prefactor_langchain.ToolSpan.type) * [`compile_langchain_agent_schema()`](prefactor_langchain.md#prefactor_langchain.compile_langchain_agent_schema) * [`extract_error_info()`](prefactor_langchain.md#prefactor_langchain.extract_error_info) * [`extract_token_usage()`](prefactor_langchain.md#prefactor_langchain.extract_token_usage) * [`register_langchain_schemas()`](prefactor_langchain.md#prefactor_langchain.register_langchain_schemas) * [Submodules](prefactor_langchain.md#submodules) * [prefactor\_langchain.metadata\_extractor module](prefactor_langchain.metadata_extractor.md) * [`extract_error_info()`](prefactor_langchain.metadata_extractor.md#prefactor_langchain.metadata_extractor.extract_error_info) * [`extract_token_usage()`](prefactor_langchain.metadata_extractor.md#prefactor_langchain.metadata_extractor.extract_token_usage) * [prefactor\_langchain.middleware module](prefactor_langchain.middleware.md) * [`PrefactorMiddleware`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware) * [prefactor\_langchain.schemas module](prefactor_langchain.schemas.md) * [`LangChainToolSchemaConfig`](prefactor_langchain.schemas.md#prefactor_langchain.schemas.LangChainToolSchemaConfig) * [`compile_langchain_agent_schema()`](prefactor_langchain.schemas.md#prefactor_langchain.schemas.compile_langchain_agent_schema) * [`register_langchain_schemas()`](prefactor_langchain.schemas.md#prefactor_langchain.schemas.register_langchain_schemas) * [prefactor\_langchain.spans module](prefactor_langchain.spans.md) * [`AgentSpan`](prefactor_langchain.spans.md#prefactor_langchain.spans.AgentSpan) * [`ErrorInfo`](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo) * [`LLMSpan`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan) * [`LangChainSpan`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan) * [`TokenUsage`](prefactor_langchain.spans.md#prefactor_langchain.spans.TokenUsage) * [`ToolSpan`](prefactor_langchain.spans.md#prefactor_langchain.spans.ToolSpan) # prefactor_langchain package # prefactor\_langchain package [Section titled “prefactor\_langchain package”](#prefactor_langchain-package) Prefactor LangChain - LangChain integration for Prefactor observability. ### *class* prefactor\_langchain.AgentSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’]=‘pending’, inputs: dict\[str, \~typing.Any]=, outputs: dict\[str, \~typing.Any] | None=None, metadata: dict\[str, \~typing.Any]=, tags: list\[str] = , error: [ErrorInfo](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo) | None = None, type: str = ‘langchain:agent’, agent\_name: str | None = None, agent\_config: dict\[str, \~typing.Any]=, initial\_messages: list\[dict\[str, \~typing.Any]]=, final\_messages: list\[dict\[str, \~typing.Any]]=, iteration\_count: int = 0) [Section titled “class prefactor\_langchain.AgentSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’\]=‘pending’, inputs: dict\[str, \~typing.Any\]=, outputs: dict\[str, \~typing.Any\] | None=None, metadata: dict\[str, \~typing.Any\]=, tags: list\[str\] = , error: ErrorInfo | None = None, type: str = ‘langchain:agent’, agent\_name: str | None = None, agent\_config: dict\[str, \~typing.Any\]=, initial\_messages: list\[dict\[str, \~typing.Any\]\]=, final\_messages: list\[dict\[str, \~typing.Any\]\]=, iteration\_count: int = 0)”](#class-prefactor_langchainagentspanname-str--unnamed-start_time-float---end_time-float--none--none-status-literalpending-running-completed-failedpending-inputs-dictstr-typingany-outputs-dictstr-typingany--nonenone-metadata-dictstr-typingany-tags-liststr---error-errorinfo--none--none-type-str--langchainagent-agent_name-str--none--none-agent_config-dictstr-typingany-initial_messages-listdictstr-typingany-final_messages-listdictstr-typingany-iteration_count-int--0) Bases: [`LangChainSpan`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan) Span representing an agent execution. Captures the lifecycle of an agent run, including the agent’s name, configuration, and the messages/state that drove the execution. #### agent\_config *: dict\[str, Any]* [Section titled “agent\_config : dict\[str, Any\]”](#agent_config--dictstr-any) #### agent\_name *: str | None* *= None* [Section titled “agent\_name : str | None = None”](#agent_name--str--none--none) #### final\_messages *: list\[dict\[str, Any]]* [Section titled “final\_messages : list\[dict\[str, Any\]\]”](#final_messages--listdictstr-any) #### initial\_messages *: list\[dict\[str, Any]]* [Section titled “initial\_messages : list\[dict\[str, Any\]\]”](#initial_messages--listdictstr-any) #### iteration\_count *: int* *= 0* [Section titled “iteration\_count : int = 0”](#iteration_count--int--0) #### to\_dict() → dict\[str, Any] [Section titled “to\_dict() → dict\[str, Any\]”](#to_dict--dictstr-any) Convert to dictionary including agent-specific fields. #### type *: str* *= ‘langchain:agent’* [Section titled “type : str = ‘langchain:agent’”](#type--str--langchainagent) ### *class* prefactor\_langchain.ErrorInfo(error\_type: str, message: str, stacktrace: str | None = None) [Section titled “class prefactor\_langchain.ErrorInfo(error\_type: str, message: str, stacktrace: str | None = None)”](#class-prefactor_langchainerrorinfoerror_type-str-message-str-stacktrace-str--none--none) Bases: `object` Error information for failed spans. #### error\_type *: str* [Section titled “error\_type : str”](#error_type--str) #### message *: str* [Section titled “message : str”](#message--str) #### stacktrace *: str | None* *= None* [Section titled “stacktrace : str | None = None”](#stacktrace--str--none--none) #### to\_dict() → dict\[str, Any] [Section titled “to\_dict() → dict\[str, Any\]”](#to_dict--dictstr-any-1) Convert to dictionary for serialization. ### *class* prefactor\_langchain.LLMSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’]=‘pending’, inputs: dict\[str, \~typing.Any]=, outputs: dict\[str, \~typing.Any] | None=None, metadata: dict\[str, \~typing.Any]=, tags: list\[str] = , error: [ErrorInfo](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo) | None = None, type: str = ‘langchain:agent’, model\_name: str | None = None, provider: str | None = None, token\_usage: [TokenUsage](prefactor_langchain.spans.md#prefactor_langchain.spans.TokenUsage) | None = None, temperature: float | None = None, max\_tokens: int | None = None, top\_p: float | None = None, stop\_sequences: list\[str] = , messages: list\[dict\[str, \~typing.Any]]=, response\_content: str | None = None) [Section titled “class prefactor\_langchain.LLMSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’\]=‘pending’, inputs: dict\[str, \~typing.Any\]=, outputs: dict\[str, \~typing.Any\] | None=None, metadata: dict\[str, \~typing.Any\]=, tags: list\[str\] = , error: ErrorInfo | None = None, type: str = ‘langchain:agent’, model\_name: str | None = None, provider: str | None = None, token\_usage: TokenUsage | None = None, temperature: float | None = None, max\_tokens: int | None = None, top\_p: float | None = None, stop\_sequences: list\[str\] = , messages: list\[dict\[str, \~typing.Any\]\]=, response\_content: str | None = None)”](#class-prefactor_langchainllmspanname-str--unnamed-start_time-float---end_time-float--none--none-status-literalpending-running-completed-failedpending-inputs-dictstr-typingany-outputs-dictstr-typingany--nonenone-metadata-dictstr-typingany-tags-liststr---error-errorinfo--none--none-type-str--langchainagent-model_name-str--none--none-provider-str--none--none-token_usage-tokenusage--none--none-temperature-float--none--none-max_tokens-int--none--none-top_p-float--none--none-stop_sequences-liststr---messages-listdictstr-typingany-response_content-str--none--none) Bases: [`LangChainSpan`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan) Span representing an LLM call. Captures model-specific metadata including the model name, provider, token usage, and generation parameters. #### max\_tokens *: int | None* *= None* [Section titled “max\_tokens : int | None = None”](#max_tokens--int--none--none) #### messages *: list\[dict\[str, Any]]* [Section titled “messages : list\[dict\[str, Any\]\]”](#messages--listdictstr-any) #### model\_name *: str | None* *= None* [Section titled “model\_name : str | None = None”](#model_name--str--none--none) #### provider *: str | None* *= None* [Section titled “provider : str | None = None”](#provider--str--none--none) #### response\_content *: str | None* *= None* [Section titled “response\_content : str | None = None”](#response_content--str--none--none) #### stop\_sequences *: list\[str]* [Section titled “stop\_sequences : list\[str\]”](#stop_sequences--liststr) #### temperature *: float | None* *= None* [Section titled “temperature : float | None = None”](#temperature--float--none--none) #### to\_dict() → dict\[str, Any] [Section titled “to\_dict() → dict\[str, Any\]”](#to_dict--dictstr-any-2) Convert to dictionary including LLM-specific fields. #### token\_usage *: [TokenUsage](prefactor_langchain.spans.md#prefactor_langchain.spans.TokenUsage) | None* *= None* [Section titled “token\_usage : TokenUsage | None = None”](#token_usage--tokenusage--none--none) #### top\_p *: float | None* *= None* [Section titled “top\_p : float | None = None”](#top_p--float--none--none) #### type *: str* *= ‘langchain:llm’* [Section titled “type : str = ‘langchain:llm’”](#type--str--langchainllm) ### *class* prefactor\_langchain.LangChainSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’]=‘pending’, inputs: dict\[str, \~typing.Any]=, outputs: dict\[str, \~typing.Any] | None=None, metadata: dict\[str, \~typing.Any]=, tags: list\[str] = , error: [ErrorInfo](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo) | None = None, type: str = ‘langchain:agent’) [Section titled “class prefactor\_langchain.LangChainSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’\]=‘pending’, inputs: dict\[str, \~typing.Any\]=, outputs: dict\[str, \~typing.Any\] | None=None, metadata: dict\[str, \~typing.Any\]=, tags: list\[str\] = , error: ErrorInfo | None = None, type: str = ‘langchain:agent’)”](#class-prefactor_langchainlangchainspanname-str--unnamed-start_time-float---end_time-float--none--none-status-literalpending-running-completed-failedpending-inputs-dictstr-typingany-outputs-dictstr-typingany--nonenone-metadata-dictstr-typingany-tags-liststr---error-errorinfo--none--none-type-str--langchainagent) Bases: `object` Base class for all LangChain spans. All LangChain spans share common fields for timing, status, inputs/outputs, and error information. Trace correlation (span\_id, parent\_span\_id, trace\_id) is handled by the backend. Note: The ‘type’ field is defined in subclasses to avoid dataclass field shadowing issues. #### complete(outputs: dict\[str, Any] | None = None) → None [Section titled “complete(outputs: dict\[str, Any\] | None = None) → None”](#completeoutputs-dictstr-any--none--none--none) Mark the span as completed with outputs. #### end\_time *: float | None* *= None* [Section titled “end\_time : float | None = None”](#end_time--float--none--none) #### error *: [ErrorInfo](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo) | None* *= None* [Section titled “error : ErrorInfo | None = None”](#error--errorinfo--none--none) #### fail(error: Exception) → None [Section titled “fail(error: Exception) → None”](#failerror-exception--none) Mark the span as failed with error information. #### inputs *: dict\[str, Any]* [Section titled “inputs : dict\[str, Any\]”](#inputs--dictstr-any) #### metadata *: dict\[str, Any]* [Section titled “metadata : dict\[str, Any\]”](#metadata--dictstr-any) #### name *: str* *= ‘unnamed’* [Section titled “name : str = ‘unnamed’”](#name--str--unnamed) #### outputs *: dict\[str, Any] | None* *= None* [Section titled “outputs : dict\[str, Any\] | None = None”](#outputs--dictstr-any--none--none) #### start\_time *: float* [Section titled “start\_time : float”](#start_time--float) #### status *: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’]* *= ‘pending’* [Section titled “status : Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’\] = ‘pending’”](#status--literalpending-running-completed-failed--pending) #### tags *: list\[str]* [Section titled “tags : list\[str\]”](#tags--liststr) #### to\_dict() → dict\[str, Any] [Section titled “to\_dict() → dict\[str, Any\]”](#to_dict--dictstr-any-3) Convert span to dictionary for serialization. Returns a JSON-serializable dictionary representation of the span. #### type *: str* *= ‘langchain:agent’* [Section titled “type : str = ‘langchain:agent’”](#type--str--langchainagent-1) ### *class* prefactor\_langchain.LangChainToolSchemaConfig(span\_type: str, input\_schema: dict\[str, Any]) [Section titled “class prefactor\_langchain.LangChainToolSchemaConfig(span\_type: str, input\_schema: dict\[str, Any\])”](#class-prefactor_langchainlangchaintoolschemaconfigspan_type-str-input_schema-dictstr-any) Bases: `object` Configuration for a tool-specific LangChain span schema. #### span\_type [Section titled “span\_type”](#span_type) Tool-specific span type suffix or full span type. Values are normalized to `langchain:tool:`. * **Type:** str #### input\_schema [Section titled “input\_schema”](#input_schema) JSON schema for the tool arguments stored in `inputs` for tool-specific spans. * **Type:** dict\[str, Any] #### input\_schema *: dict\[str, Any]* [Section titled “input\_schema : dict\[str, Any\]”](#input_schema--dictstr-any) #### span\_type *: str* [Section titled “span\_type : str”](#span_type--str) ### *class* prefactor\_langchain.PrefactorMiddleware(client: [PrefactorCoreClient](../../core/reference/prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient) | None = None, agent\_id: str | None = None, agent\_name: str | None = None, instance: [AgentInstanceHandle](../../core/reference/prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle) | None = None, tool\_schemas: Mapping\[str, [LangChainToolSchemaConfig](prefactor_langchain.schemas.md#prefactor_langchain.schemas.LangChainToolSchemaConfig) | Mapping\[str, Any]] | None = None) [Section titled “class prefactor\_langchain.PrefactorMiddleware(client: PrefactorCoreClient | None = None, agent\_id: str | None = None, agent\_name: str | None = None, instance: AgentInstanceHandle | None = None, tool\_schemas: Mapping\[str, LangChainToolSchemaConfig | Mapping\[str, Any\]\] | None = None)”](#class-prefactor_langchainprefactormiddlewareclient-prefactorcoreclient--none--none-agent_id-str--none--none-agent_name-str--none--none-instance-agentinstancehandle--none--none-tool_schemas-mappingstr-langchaintoolschemaconfig--mappingstr-any--none--none) Bases: `AgentMiddleware` LangChain middleware for automatic tracing. This middleware integrates with LangChain’s middleware system to automatically create and emit spans for agent execution, LLM calls, and tool executions. Three usage patterns are supported: 1. **Pre-configured Client** (recommended): Pass a pre-configured client for full control over settings. The user is responsible for client lifecycle. 2. **Pre-configured Instance**: Pass an existing AgentInstanceHandle to share a single instance between the LangChain middleware and other parts of your program. Use this when you need to create spans outside of the LangChain agent (e.g. for custom pre/post-processing steps). The caller owns the instance lifecycle and must call `instance.finish()` themselves. 3. **Factory Pattern**: Use from\_config() for quick setup. The middleware owns both client and agent instance lifecycle. Example - Pre-configured Client: : from prefactor\_core import PrefactorCoreClient, PrefactorCoreConfig from prefactor\_http.config import HttpClientConfig # Configure and initialize client yourself [Section titled “Configure and initialize client yourself”](#configure-and-initialize-client-yourself) http\_config = HttpClientConfig(api\_url=”…”, api\_token=”…”) config = PrefactorCoreConfig(http\_config=http\_config) client = PrefactorCoreClient(config) await client.initialize() # Create middleware with pre-configured client [Section titled “Create middleware with pre-configured client”](#create-middleware-with-pre-configured-client) middleware = PrefactorMiddleware( > client=client, agent\_id=”my-agent”, agent\_name=”My Agent”, > > ) # User must close both middleware and client [Section titled “User must close both middleware and client”](#user-must-close-both-middleware-and-client) await middleware.close() # Only closes agent instance await client.close() # User closes their own client Example - Pre-configured Instance (spans outside the agent): : from prefactor\_core import PrefactorCoreClient, PrefactorCoreConfig from prefactor\_http.config import HttpClientConfig\ http\_config = HttpClientConfig(api\_url=”…”, api\_token=”…”) config = PrefactorCoreConfig(http\_config=http\_config) client = PrefactorCoreClient(config) await client.initialize()\ instance = await client.create\_agent\_instance(agent\_id=”my-agent”) await instance.start() # Share the same instance with the middleware AND your own code [Section titled “Share the same instance with the middleware AND your own code”](#share-the-same-instance-with-the-middleware-and-your-own-code) middleware = PrefactorMiddleware(instance=instance) # Instrument your own code with the same instance [Section titled “Instrument your own code with the same instance”](#instrument-your-own-code-with-the-same-instance) async with instance.span(“custom:preprocessing”) as ctx: > ctx.set\_result({“step”: “preprocess”, “status”: “ok”}) > > # Run your LangChain agent (middleware traces it automatically) [Section titled “Run your LangChain agent (middleware traces it automatically)”](#run-your-langchain-agent-middleware-traces-it-automatically) result = agent.invoke({“messages”: \[…]}) # Caller is responsible for cleanup [Section titled “Caller is responsible for cleanup”](#caller-is-responsible-for-cleanup) await instance.finish() await client.close() Example - Factory Pattern: : middleware = PrefactorMiddleware.from\_config( : api\_url=””, api\_token=”my-token”, agent\_id=”my-agent”, agent\_name=”My Agent”,\ ) # Middleware manages both client and agent instance [Section titled “Middleware manages both client and agent instance”](#middleware-manages-both-client-and-agent-instance) await middleware.close() # Closes both #### *async* aafter\_agent(state: Any, runtime: Any) → dict\[str, Any] | None [Section titled “async aafter\_agent(state: Any, runtime: Any) → dict\[str, Any\] | None”](#async-aafter_agentstate-any-runtime-any--dictstr-any--none) Async hook called after agent completes execution. Finishes the `langchain:agent` span opened by `abefore_agent` by exiting its async context manager. * **Parameters:** * **state** – The agent state. * **runtime** – The runtime context. * **Returns:** Optional state updates. #### *async* abefore\_agent(state: Any, runtime: Any) → dict\[str, Any] | None [Section titled “async abefore\_agent(state: Any, runtime: Any) → dict\[str, Any\] | None”](#async-abefore_agentstate-any-runtime-any--dictstr-any--none) Async hook called before agent starts execution. Creates a `langchain:agent` span using the async context manager so that `SpanContextStack` is updated automatically. Any outer workflow span already on the stack (e.g. `workflow:agent_step`) is picked up as the parent without any manual `set_parent_span()` call. The span context is kept open and stored in `_agent_span_context` until `aafter_agent` exits it. * **Parameters:** * **state** – The agent state. * **runtime** – The runtime context. * **Returns:** Optional state updates. #### after\_agent(state: Any, runtime: Any) → dict\[str, Any] | None [Section titled “after\_agent(state: Any, runtime: Any) → dict\[str, Any\] | None”](#after_agentstate-any-runtime-any--dictstr-any--none) Hook called after agent completes execution. Finishes the agent span created in before\_agent. * **Parameters:** * **state** – The agent state. * **runtime** – The runtime context. * **Returns:** Optional state updates. #### *async* awrap\_model\_call(request: Any, handler: Callable\[\[Any], Any]) → Any [Section titled “async awrap\_model\_call(request: Any, handler: Callable\[\[Any\], Any\]) → Any”](#async-awrap_model_callrequest-any-handler-callableany-any--any) Wrap async model calls to trace LLM execution. * **Parameters:** * **request** – The model request. * **handler** – The function that executes the model call. * **Returns:** The model response. #### *async* awrap\_tool\_call(request: Any, handler: Callable\[\[Any], Any]) → Any [Section titled “async awrap\_tool\_call(request: Any, handler: Callable\[\[Any\], Any\]) → Any”](#async-awrap_tool_callrequest-any-handler-callableany-any--any) Wrap async tool calls to trace tool execution. * **Parameters:** * **request** – The tool request. * **handler** – The function that executes the tool call. * **Returns:** The tool response. #### before\_agent(state: Any, runtime: Any) → dict\[str, Any] | None [Section titled “before\_agent(state: Any, runtime: Any) → dict\[str, Any\] | None”](#before_agentstate-any-runtime-any--dictstr-any--none) Hook called before agent starts execution. Creates a root span for the entire agent execution. * **Parameters:** * **state** – The agent state. * **runtime** – The runtime context. * **Returns:** Optional state updates. #### *async* close() → None [Section titled “async close() → None”](#async-close--none) Close the middleware and cleanup resources. Awaits all in-flight span-emit tasks first, then closes the agent instance (if we created it) and finally the client. #### *static* create\_client(config: [PrefactorCoreConfig](../../core/reference/prefactor_core.config.md#prefactor_core.config.PrefactorCoreConfig)) → [PrefactorCoreClient](../../core/reference/prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient) [Section titled “static create\_client(config: PrefactorCoreConfig) → PrefactorCoreClient”](#static-create_clientconfig-prefactorcoreconfig--prefactorcoreclient) Create a PrefactorCoreClient configured for use with this adaptor. Use this when you need to manage the client and instance lifecycle yourself (e.g. to share a client between the middleware and eval code) instead of letting [`from_config()`](#prefactor_langchain.PrefactorMiddleware.from_config) manage them for you. * **Parameters:** **config** – Core configuration for the client. * **Returns:** A PrefactorCoreClient ready for `await client.initialize()`. ### Example [Section titled “Example”](#example) config = PrefactorCoreConfig(http\_config=…) client = PrefactorMiddleware.create\_client(config) await client.initialize() instance = await client.create\_agent\_instance( : agent\_id=”my-agent”, agent\_version={“name”: “My Agent”}, agent\_schema\_version=…, ) middleware = PrefactorMiddleware(instance=instance) #### *async* ensure\_initialized() → [AgentInstanceHandle](../../core/reference/prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle) [Section titled “async ensure\_initialized() → AgentInstanceHandle”](#async-ensure_initialized--agentinstancehandle) Initialize the middleware and return the agent instance handle. #### *classmethod* from\_config(api\_url: str, api\_token: str, agent\_id: str | None = None, agent\_name: str | None = None, environment\_id: str | None = None, schema\_registry: [SchemaRegistry](../../core/reference/prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry) | None = None, include\_langchain\_schemas: bool = True, tool\_schemas: Mapping\[str, [LangChainToolSchemaConfig](prefactor_langchain.schemas.md#prefactor_langchain.schemas.LangChainToolSchemaConfig) | Mapping\[str, Any]] | None = None) → [PrefactorMiddleware](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware) [Section titled “classmethod from\_config(api\_url: str, api\_token: str, agent\_id: str | None = None, agent\_name: str | None = None, environment\_id: str | None = None, schema\_registry: SchemaRegistry | None = None, include\_langchain\_schemas: bool = True, tool\_schemas: Mapping\[str, LangChainToolSchemaConfig | Mapping\[str, Any\]\] | None = None) → PrefactorMiddleware”](#classmethod-from_configapi_url-str-api_token-str-agent_id-str--none--none-agent_name-str--none--none-environment_id-str--none--none-schema_registry-schemaregistry--none--none-include_langchain_schemas-bool--true-tool_schemas-mappingstr-langchaintoolschemaconfig--mappingstr-any--none--none--prefactormiddleware) Factory method to create middleware from configuration. This creates a client and middleware with the specified settings. The middleware owns the client and will auto-initialize it on first use. * **Parameters:** * **api\_url** – The Prefactor API URL. * **api\_token** – The API token for authentication. * **agent\_id** – Optional agent identifier for categorization. * **agent\_name** – Optional human-readable agent name. * **environment\_id** – Optional environment identifier for scoping the agent. * **schema\_registry** – Optional SchemaRegistry for registering span schemas. * **include\_langchain\_schemas** – If True and schema\_registry is provided, automatically register LangChain-specific schemas. * **tool\_schemas** – Optional per-tool schema configuration for tool-specific span types. * **Returns:** A configured PrefactorMiddleware instance with lazy initialization. ### Example [Section titled “Example”](#example-1) middleware = PrefactorMiddleware.from\_config( : api\_url=””, api\_token=”my-token”, agent\_id=”my-agent”, agent\_name=”My Agent”, ) # Middleware auto-initializes on first use [Section titled “Middleware auto-initializes on first use”](#middleware-auto-initializes-on-first-use) # Cleanup when done: [Section titled “Cleanup when done:”](#cleanup-when-done) await middleware.close() # Closes both agent instance and client #### set\_parent\_span(span\_id: str | None) → None [Section titled “set\_parent\_span(span\_id: str | None) → None”](#set_parent_spanspan_id-str--none--none) Set the parent span ID for the next agent invocation (sync path only). Only needed when using `agent.invoke()` via `run_in_executor`. In that case, `before_agent` runs in a worker thread where `contextvars` are not inherited, so the parent span ID must be passed explicitly before entering the executor. When using `agent.ainvoke()` (the recommended async path), parent wiring is automatic via `SpanContextStack` — do not call this method. * **Parameters:** **span\_id** – The span ID to use as the parent, or None to clear it. #### wrap\_model\_call(request: Any, handler: Callable\[\[Any], Any]) → Any [Section titled “wrap\_model\_call(request: Any, handler: Callable\[\[Any\], Any\]) → Any”](#wrap_model_callrequest-any-handler-callableany-any--any) Wrap synchronous model calls to trace LLM execution. * **Parameters:** * **request** – The model request. * **handler** – The function that executes the model call. * **Returns:** The model response. #### wrap\_tool\_call(request: Any, handler: Callable\[\[Any], Any]) → Any [Section titled “wrap\_tool\_call(request: Any, handler: Callable\[\[Any\], Any\]) → Any”](#wrap_tool_callrequest-any-handler-callableany-any--any) Wrap synchronous tool calls to trace tool execution. * **Parameters:** * **request** – The tool request. * **handler** – The function that executes the tool call. * **Returns:** The tool response. ### *class* prefactor\_langchain.TokenUsage(prompt\_tokens: int, completion\_tokens: int, total\_tokens: int) [Section titled “class prefactor\_langchain.TokenUsage(prompt\_tokens: int, completion\_tokens: int, total\_tokens: int)”](#class-prefactor_langchaintokenusageprompt_tokens-int-completion_tokens-int-total_tokens-int) Bases: `object` Token usage information for LLM calls. #### completion\_tokens *: int* [Section titled “completion\_tokens : int”](#completion_tokens--int) #### prompt\_tokens *: int* [Section titled “prompt\_tokens : int”](#prompt_tokens--int) #### to\_dict() → dict\[str, Any] [Section titled “to\_dict() → dict\[str, Any\]”](#to_dict--dictstr-any-4) Convert to dictionary for serialization. #### total\_tokens *: int* [Section titled “total\_tokens : int”](#total_tokens--int) ### *class* prefactor\_langchain.ToolSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’]=‘pending’, inputs: dict\[str, \~typing.Any]=, outputs: dict\[str, \~typing.Any] | None=None, metadata: dict\[str, \~typing.Any]=, tags: list\[str] = , error: [ErrorInfo](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo) | None = None, type: str = ‘langchain:agent’, tool\_name: str | None = None, tool\_schema: dict\[str, \~typing.Any] | None=None, arguments: dict\[str, \~typing.Any]=, execution\_time\_ms: int | None = None, tool\_type: str | None = None, retriever\_metadata: dict\[str, \~typing.Any] | None=None) [Section titled “class prefactor\_langchain.ToolSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’\]=‘pending’, inputs: dict\[str, \~typing.Any\]=, outputs: dict\[str, \~typing.Any\] | None=None, metadata: dict\[str, \~typing.Any\]=, tags: list\[str\] = , error: ErrorInfo | None = None, type: str = ‘langchain:agent’, tool\_name: str | None = None, tool\_schema: dict\[str, \~typing.Any\] | None=None, arguments: dict\[str, \~typing.Any\]=, execution\_time\_ms: int | None = None, tool\_type: str | None = None, retriever\_metadata: dict\[str, \~typing.Any\] | None=None)”](#class-prefactor_langchaintoolspanname-str--unnamed-start_time-float---end_time-float--none--none-status-literalpending-running-completed-failedpending-inputs-dictstr-typingany-outputs-dictstr-typingany--nonenone-metadata-dictstr-typingany-tags-liststr---error-errorinfo--none--none-type-str--langchainagent-tool_name-str--none--none-tool_schema-dictstr-typingany--nonenone-arguments-dictstr-typingany-execution_time_ms-int--none--none-tool_type-str--none--none-retriever_metadata-dictstr-typingany--nonenone) Bases: [`LangChainSpan`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan) Span representing a tool execution. Captures tool-specific metadata including the tool name, schema, arguments, and execution time. Can represent any tool call including retrievers (with appropriate metadata). #### arguments *: dict\[str, Any]* [Section titled “arguments : dict\[str, Any\]”](#arguments--dictstr-any) #### execution\_time\_ms *: int | None* *= None* [Section titled “execution\_time\_ms : int | None = None”](#execution_time_ms--int--none--none) #### retriever\_metadata *: dict\[str, Any] | None* *= None* [Section titled “retriever\_metadata : dict\[str, Any\] | None = None”](#retriever_metadata--dictstr-any--none--none) #### to\_dict() → dict\[str, Any] [Section titled “to\_dict() → dict\[str, Any\]”](#to_dict--dictstr-any-5) Convert to dictionary including tool-specific fields. #### tool\_name *: str | None* *= None* [Section titled “tool\_name : str | None = None”](#tool_name--str--none--none) #### tool\_schema *: dict\[str, Any] | None* *= None* [Section titled “tool\_schema : dict\[str, Any\] | None = None”](#tool_schema--dictstr-any--none--none) #### tool\_type *: str | None* *= None* [Section titled “tool\_type : str | None = None”](#tool_type--str--none--none) #### type *: str* *= ‘langchain:tool’* [Section titled “type : str = ‘langchain:tool’”](#type--str--langchaintool) ### prefactor\_langchain.compile\_langchain\_agent\_schema(agent\_schema: Mapping\[str, Any] | None = None, , tool\_schemas: Mapping\[str, [LangChainToolSchemaConfig](prefactor_langchain.schemas.md#prefactor_langchain.schemas.LangChainToolSchemaConfig) | Mapping\[str, Any]] | None = None) → tuple\[dict\[str, Any], dict\[str, str]] [Section titled “prefactor\_langchain.compile\_langchain\_agent\_schema(agent\_schema: Mapping\[str, Any\] | None = None, , tool\_schemas: Mapping\[str, LangChainToolSchemaConfig | Mapping\[str, Any\]\] | None = None) → tuple\[dict\[str, Any\], dict\[str, str\]\]”](#prefactor_langchaincompile_langchain_agent_schemaagent_schema-mappingstr-any--none--none--tool_schemas-mappingstr-langchaintoolschemaconfig--mappingstr-any--none--none--tupledictstr-any-dictstr-str) Compile a LangChain agent schema with optional tool-specific span types. * **Parameters:** * **agent\_schema** – Optional base agent schema to merge with the built-in LangChain span schemas. * **tool\_schemas** – Optional Python-first per-tool schema configuration. * **Returns:** A tuple of `(compiled_agent_schema, tool_span_types)` where `tool_span_types` maps tool names to normalized span types. ### prefactor\_langchain.extract\_error\_info(error: Exception) → [ErrorInfo](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo) [Section titled “prefactor\_langchain.extract\_error\_info(error: Exception) → ErrorInfo”](#prefactor_langchainextract_error_infoerror-exception--errorinfo) Extract error information from an exception. * **Parameters:** **error** – The exception to extract information from. * **Returns:** ErrorInfo containing error details. ### prefactor\_langchain.extract\_token\_usage(response: Any) → [TokenUsage](prefactor_langchain.spans.md#prefactor_langchain.spans.TokenUsage) | None [Section titled “prefactor\_langchain.extract\_token\_usage(response: Any) → TokenUsage | None”](#prefactor_langchainextract_token_usageresponse-any--tokenusage--none) Extract token usage from a ModelResponse. Checks each message in `response.result` for `usage_metadata` (the standard LangChain field populated by all providers), accumulating totals across messages. * **Parameters:** **response** – A ModelResponse object from LangChain. * **Returns:** TokenUsage if available, None otherwise. ### prefactor\_langchain.register\_langchain\_schemas(registry: Any, , agent\_schema: Mapping\[str, Any] | None = None, tool\_schemas: Mapping\[str, [LangChainToolSchemaConfig](prefactor_langchain.schemas.md#prefactor_langchain.schemas.LangChainToolSchemaConfig) | Mapping\[str, Any]] | None = None) → dict\[str, str] [Section titled “prefactor\_langchain.register\_langchain\_schemas(registry: Any, , agent\_schema: Mapping\[str, Any\] | None = None, tool\_schemas: Mapping\[str, LangChainToolSchemaConfig | Mapping\[str, Any\]\] | None = None) → dict\[str, str\]”](#prefactor_langchainregister_langchain_schemasregistry-any--agent_schema-mappingstr-any--none--none-tool_schemas-mappingstr-langchaintoolschemaconfig--mappingstr-any--none--none--dictstr-str) Register all LangChain span schemas with a schema registry. Registers the built-in schemas for LangChain-specific span types (agent, llm, tool) using the full `span_type_schemas` form, which includes params schemas, result schemas, titles, and descriptions. When tool schemas are configured, this also registers per-tool span types. * **Parameters:** * **registry** – The SchemaRegistry to register schemas with. * **agent\_schema** – Optional base agent schema that may include embedded `toolSchemas` or `tool_schemas` config. * **tool\_schemas** – Optional Python-first per-tool schema configuration. * **Returns:** A dict mapping tool names to their normalized span types. Returns an empty dict when no tool-specific schemas are registered. ### Example [Section titled “Example”](#example-2) from prefactor\_core import SchemaRegistry from prefactor\_langchain.schemas import register\_langchain\_schemas registry = SchemaRegistry() register\_langchain\_schemas(registry) # Now the registry has langchain:agent, langchain:llm, langchain:tool [Section titled “Now the registry has langchain:agent, langchain:llm, langchain:tool”](#now-the-registry-has-langchainagent-langchainllm-langchaintool) assert registry.has\_schema(“langchain:llm”) ## Submodules [Section titled “Submodules”](#submodules) * [prefactor\_langchain.metadata\_extractor module](prefactor_langchain.metadata_extractor.md) * [`extract_error_info()`](prefactor_langchain.metadata_extractor.md#prefactor_langchain.metadata_extractor.extract_error_info) * [`extract_token_usage()`](prefactor_langchain.metadata_extractor.md#prefactor_langchain.metadata_extractor.extract_token_usage) * [prefactor\_langchain.middleware module](prefactor_langchain.middleware.md) * [`PrefactorMiddleware`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware) * [`PrefactorMiddleware.aafter_agent()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.aafter_agent) * [`PrefactorMiddleware.abefore_agent()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.abefore_agent) * [`PrefactorMiddleware.after_agent()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.after_agent) * [`PrefactorMiddleware.awrap_model_call()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.awrap_model_call) * [`PrefactorMiddleware.awrap_tool_call()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.awrap_tool_call) * [`PrefactorMiddleware.before_agent()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.before_agent) * [`PrefactorMiddleware.close()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.close) * [`PrefactorMiddleware.create_client()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.create_client) * [`PrefactorMiddleware.ensure_initialized()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.ensure_initialized) * [`PrefactorMiddleware.from_config()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.from_config) * [`PrefactorMiddleware.set_parent_span()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.set_parent_span) * [`PrefactorMiddleware.wrap_model_call()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.wrap_model_call) * [`PrefactorMiddleware.wrap_tool_call()`](prefactor_langchain.middleware.md#prefactor_langchain.middleware.PrefactorMiddleware.wrap_tool_call) * [prefactor\_langchain.schemas module](prefactor_langchain.schemas.md) * [`LangChainToolSchemaConfig`](prefactor_langchain.schemas.md#prefactor_langchain.schemas.LangChainToolSchemaConfig) * [`LangChainToolSchemaConfig.span_type`](prefactor_langchain.schemas.md#prefactor_langchain.schemas.LangChainToolSchemaConfig.span_type) * [`LangChainToolSchemaConfig.input_schema`](prefactor_langchain.schemas.md#prefactor_langchain.schemas.LangChainToolSchemaConfig.input_schema) * [`LangChainToolSchemaConfig.input_schema`](prefactor_langchain.schemas.md#id0) * [`LangChainToolSchemaConfig.span_type`](prefactor_langchain.schemas.md#id1) * [`compile_langchain_agent_schema()`](prefactor_langchain.schemas.md#prefactor_langchain.schemas.compile_langchain_agent_schema) * [`register_langchain_schemas()`](prefactor_langchain.schemas.md#prefactor_langchain.schemas.register_langchain_schemas) * [prefactor\_langchain.spans module](prefactor_langchain.spans.md) * [`AgentSpan`](prefactor_langchain.spans.md#prefactor_langchain.spans.AgentSpan) * [`AgentSpan.agent_config`](prefactor_langchain.spans.md#prefactor_langchain.spans.AgentSpan.agent_config) * [`AgentSpan.agent_name`](prefactor_langchain.spans.md#prefactor_langchain.spans.AgentSpan.agent_name) * [`AgentSpan.final_messages`](prefactor_langchain.spans.md#prefactor_langchain.spans.AgentSpan.final_messages) * [`AgentSpan.initial_messages`](prefactor_langchain.spans.md#prefactor_langchain.spans.AgentSpan.initial_messages) * [`AgentSpan.iteration_count`](prefactor_langchain.spans.md#prefactor_langchain.spans.AgentSpan.iteration_count) * [`AgentSpan.to_dict()`](prefactor_langchain.spans.md#prefactor_langchain.spans.AgentSpan.to_dict) * [`AgentSpan.type`](prefactor_langchain.spans.md#prefactor_langchain.spans.AgentSpan.type) * [`ErrorInfo`](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo) * [`ErrorInfo.error_type`](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo.error_type) * [`ErrorInfo.message`](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo.message) * [`ErrorInfo.stacktrace`](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo.stacktrace) * [`ErrorInfo.to_dict()`](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo.to_dict) * [`LLMSpan`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan) * [`LLMSpan.max_tokens`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan.max_tokens) * [`LLMSpan.messages`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan.messages) * [`LLMSpan.model_name`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan.model_name) * [`LLMSpan.provider`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan.provider) * [`LLMSpan.response_content`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan.response_content) * [`LLMSpan.stop_sequences`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan.stop_sequences) * [`LLMSpan.temperature`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan.temperature) * [`LLMSpan.to_dict()`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan.to_dict) * [`LLMSpan.token_usage`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan.token_usage) * [`LLMSpan.top_p`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan.top_p) * [`LLMSpan.type`](prefactor_langchain.spans.md#prefactor_langchain.spans.LLMSpan.type) * [`LangChainSpan`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan) * [`LangChainSpan.complete()`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.complete) * [`LangChainSpan.end_time`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.end_time) * [`LangChainSpan.error`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.error) * [`LangChainSpan.fail()`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.fail) * [`LangChainSpan.inputs`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.inputs) * [`LangChainSpan.metadata`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.metadata) * [`LangChainSpan.name`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.name) * [`LangChainSpan.outputs`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.outputs) * [`LangChainSpan.start_time`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.start_time) * [`LangChainSpan.status`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.status) * [`LangChainSpan.tags`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.tags) * [`LangChainSpan.to_dict()`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.to_dict) * [`LangChainSpan.type`](prefactor_langchain.spans.md#prefactor_langchain.spans.LangChainSpan.type) * [`TokenUsage`](prefactor_langchain.spans.md#prefactor_langchain.spans.TokenUsage) * [`TokenUsage.completion_tokens`](prefactor_langchain.spans.md#prefactor_langchain.spans.TokenUsage.completion_tokens) * [`TokenUsage.prompt_tokens`](prefactor_langchain.spans.md#prefactor_langchain.spans.TokenUsage.prompt_tokens) * [`TokenUsage.to_dict()`](prefactor_langchain.spans.md#prefactor_langchain.spans.TokenUsage.to_dict) * [`TokenUsage.total_tokens`](prefactor_langchain.spans.md#prefactor_langchain.spans.TokenUsage.total_tokens) * [`ToolSpan`](prefactor_langchain.spans.md#prefactor_langchain.spans.ToolSpan) * [`ToolSpan.arguments`](prefactor_langchain.spans.md#prefactor_langchain.spans.ToolSpan.arguments) * [`ToolSpan.execution_time_ms`](prefactor_langchain.spans.md#prefactor_langchain.spans.ToolSpan.execution_time_ms) * [`ToolSpan.retriever_metadata`](prefactor_langchain.spans.md#prefactor_langchain.spans.ToolSpan.retriever_metadata) * [`ToolSpan.to_dict()`](prefactor_langchain.spans.md#prefactor_langchain.spans.ToolSpan.to_dict) * [`ToolSpan.tool_name`](prefactor_langchain.spans.md#prefactor_langchain.spans.ToolSpan.tool_name) * [`ToolSpan.tool_schema`](prefactor_langchain.spans.md#prefactor_langchain.spans.ToolSpan.tool_schema) * [`ToolSpan.tool_type`](prefactor_langchain.spans.md#prefactor_langchain.spans.ToolSpan.tool_type) * [`ToolSpan.type`](prefactor_langchain.spans.md#prefactor_langchain.spans.ToolSpan.type) # prefactor_langchain.metadata_extractor module # prefactor\_langchain.metadata\_extractor module [Section titled “prefactor\_langchain.metadata\_extractor module”](#prefactor_langchainmetadata_extractor-module) Utilities for extracting metadata from LangChain objects. ### prefactor\_langchain.metadata\_extractor.extract\_error\_info(error: Exception) → [ErrorInfo](prefactor_langchain.spans.md#prefactor_langchain.spans.ErrorInfo) [Section titled “prefactor\_langchain.metadata\_extractor.extract\_error\_info(error: Exception) → ErrorInfo”](#prefactor_langchainmetadata_extractorextract_error_infoerror-exception--errorinfo) Extract error information from an exception. * **Parameters:** **error** – The exception to extract information from. * **Returns:** ErrorInfo containing error details. ### prefactor\_langchain.metadata\_extractor.extract\_token\_usage(response: Any) → [TokenUsage](prefactor_langchain.spans.md#prefactor_langchain.spans.TokenUsage) | None [Section titled “prefactor\_langchain.metadata\_extractor.extract\_token\_usage(response: Any) → TokenUsage | None”](#prefactor_langchainmetadata_extractorextract_token_usageresponse-any--tokenusage--none) Extract token usage from a ModelResponse. Checks each message in `response.result` for `usage_metadata` (the standard LangChain field populated by all providers), accumulating totals across messages. * **Parameters:** **response** – A ModelResponse object from LangChain. * **Returns:** TokenUsage if available, None otherwise. # prefactor_langchain.middleware module # prefactor\_langchain.middleware module [Section titled “prefactor\_langchain.middleware module”](#prefactor_langchainmiddleware-module) LangChain middleware for automatic tracing via prefactor-core. ### *class* prefactor\_langchain.middleware.PrefactorMiddleware(client: [PrefactorCoreClient](../../core/reference/prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient) | None = None, agent\_id: str | None = None, agent\_name: str | None = None, instance: [AgentInstanceHandle](../../core/reference/prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle) | None = None, tool\_schemas: Mapping\[str, [LangChainToolSchemaConfig](prefactor_langchain.schemas.md#prefactor_langchain.schemas.LangChainToolSchemaConfig) | Mapping\[str, Any]] | None = None) [Section titled “class prefactor\_langchain.middleware.PrefactorMiddleware(client: PrefactorCoreClient | None = None, agent\_id: str | None = None, agent\_name: str | None = None, instance: AgentInstanceHandle | None = None, tool\_schemas: Mapping\[str, LangChainToolSchemaConfig | Mapping\[str, Any\]\] | None = None)”](#class-prefactor_langchainmiddlewareprefactormiddlewareclient-prefactorcoreclient--none--none-agent_id-str--none--none-agent_name-str--none--none-instance-agentinstancehandle--none--none-tool_schemas-mappingstr-langchaintoolschemaconfig--mappingstr-any--none--none) Bases: `AgentMiddleware` LangChain middleware for automatic tracing. This middleware integrates with LangChain’s middleware system to automatically create and emit spans for agent execution, LLM calls, and tool executions. Three usage patterns are supported: 1. **Pre-configured Client** (recommended): Pass a pre-configured client for full control over settings. The user is responsible for client lifecycle. 2. **Pre-configured Instance**: Pass an existing AgentInstanceHandle to share a single instance between the LangChain middleware and other parts of your program. Use this when you need to create spans outside of the LangChain agent (e.g. for custom pre/post-processing steps). The caller owns the instance lifecycle and must call `instance.finish()` themselves. 3. **Factory Pattern**: Use from\_config() for quick setup. The middleware owns both client and agent instance lifecycle. Example - Pre-configured Client: : from prefactor\_core import PrefactorCoreClient, PrefactorCoreConfig from prefactor\_http.config import HttpClientConfig # Configure and initialize client yourself [Section titled “Configure and initialize client yourself”](#configure-and-initialize-client-yourself) http\_config = HttpClientConfig(api\_url=”…”, api\_token=”…”) config = PrefactorCoreConfig(http\_config=http\_config) client = PrefactorCoreClient(config) await client.initialize() # Create middleware with pre-configured client [Section titled “Create middleware with pre-configured client”](#create-middleware-with-pre-configured-client) middleware = PrefactorMiddleware( > client=client, agent\_id=”my-agent”, agent\_name=”My Agent”, > > ) # User must close both middleware and client [Section titled “User must close both middleware and client”](#user-must-close-both-middleware-and-client) await middleware.close() # Only closes agent instance await client.close() # User closes their own client Example - Pre-configured Instance (spans outside the agent): : from prefactor\_core import PrefactorCoreClient, PrefactorCoreConfig from prefactor\_http.config import HttpClientConfig\ http\_config = HttpClientConfig(api\_url=”…”, api\_token=”…”) config = PrefactorCoreConfig(http\_config=http\_config) client = PrefactorCoreClient(config) await client.initialize()\ instance = await client.create\_agent\_instance(agent\_id=”my-agent”) await instance.start() # Share the same instance with the middleware AND your own code [Section titled “Share the same instance with the middleware AND your own code”](#share-the-same-instance-with-the-middleware-and-your-own-code) middleware = PrefactorMiddleware(instance=instance) # Instrument your own code with the same instance [Section titled “Instrument your own code with the same instance”](#instrument-your-own-code-with-the-same-instance) async with instance.span(“custom:preprocessing”) as ctx: > ctx.set\_result({“step”: “preprocess”, “status”: “ok”}) > > # Run your LangChain agent (middleware traces it automatically) [Section titled “Run your LangChain agent (middleware traces it automatically)”](#run-your-langchain-agent-middleware-traces-it-automatically) result = agent.invoke({“messages”: \[…]}) # Caller is responsible for cleanup [Section titled “Caller is responsible for cleanup”](#caller-is-responsible-for-cleanup) await instance.finish() await client.close() Example - Factory Pattern: : middleware = PrefactorMiddleware.from\_config( : api\_url=””, api\_token=”my-token”, agent\_id=”my-agent”, agent\_name=”My Agent”,\ ) # Middleware manages both client and agent instance [Section titled “Middleware manages both client and agent instance”](#middleware-manages-both-client-and-agent-instance) await middleware.close() # Closes both #### *async* aafter\_agent(state: Any, runtime: Any) → dict\[str, Any] | None [Section titled “async aafter\_agent(state: Any, runtime: Any) → dict\[str, Any\] | None”](#async-aafter_agentstate-any-runtime-any--dictstr-any--none) Async hook called after agent completes execution. Finishes the `langchain:agent` span opened by `abefore_agent` by exiting its async context manager. * **Parameters:** * **state** – The agent state. * **runtime** – The runtime context. * **Returns:** Optional state updates. #### *async* abefore\_agent(state: Any, runtime: Any) → dict\[str, Any] | None [Section titled “async abefore\_agent(state: Any, runtime: Any) → dict\[str, Any\] | None”](#async-abefore_agentstate-any-runtime-any--dictstr-any--none) Async hook called before agent starts execution. Creates a `langchain:agent` span using the async context manager so that `SpanContextStack` is updated automatically. Any outer workflow span already on the stack (e.g. `workflow:agent_step`) is picked up as the parent without any manual `set_parent_span()` call. The span context is kept open and stored in `_agent_span_context` until `aafter_agent` exits it. * **Parameters:** * **state** – The agent state. * **runtime** – The runtime context. * **Returns:** Optional state updates. #### after\_agent(state: Any, runtime: Any) → dict\[str, Any] | None [Section titled “after\_agent(state: Any, runtime: Any) → dict\[str, Any\] | None”](#after_agentstate-any-runtime-any--dictstr-any--none) Hook called after agent completes execution. Finishes the agent span created in before\_agent. * **Parameters:** * **state** – The agent state. * **runtime** – The runtime context. * **Returns:** Optional state updates. #### *async* awrap\_model\_call(request: Any, handler: Callable\[\[Any], Any]) → Any [Section titled “async awrap\_model\_call(request: Any, handler: Callable\[\[Any\], Any\]) → Any”](#async-awrap_model_callrequest-any-handler-callableany-any--any) Wrap async model calls to trace LLM execution. * **Parameters:** * **request** – The model request. * **handler** – The function that executes the model call. * **Returns:** The model response. #### *async* awrap\_tool\_call(request: Any, handler: Callable\[\[Any], Any]) → Any [Section titled “async awrap\_tool\_call(request: Any, handler: Callable\[\[Any\], Any\]) → Any”](#async-awrap_tool_callrequest-any-handler-callableany-any--any) Wrap async tool calls to trace tool execution. * **Parameters:** * **request** – The tool request. * **handler** – The function that executes the tool call. * **Returns:** The tool response. #### before\_agent(state: Any, runtime: Any) → dict\[str, Any] | None [Section titled “before\_agent(state: Any, runtime: Any) → dict\[str, Any\] | None”](#before_agentstate-any-runtime-any--dictstr-any--none) Hook called before agent starts execution. Creates a root span for the entire agent execution. * **Parameters:** * **state** – The agent state. * **runtime** – The runtime context. * **Returns:** Optional state updates. #### *async* close() → None [Section titled “async close() → None”](#async-close--none) Close the middleware and cleanup resources. Awaits all in-flight span-emit tasks first, then closes the agent instance (if we created it) and finally the client. #### *static* create\_client(config: [PrefactorCoreConfig](../../core/reference/prefactor_core.config.md#prefactor_core.config.PrefactorCoreConfig)) → [PrefactorCoreClient](../../core/reference/prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient) [Section titled “static create\_client(config: PrefactorCoreConfig) → PrefactorCoreClient”](#static-create_clientconfig-prefactorcoreconfig--prefactorcoreclient) Create a PrefactorCoreClient configured for use with this adaptor. Use this when you need to manage the client and instance lifecycle yourself (e.g. to share a client between the middleware and eval code) instead of letting [`from_config()`](#prefactor_langchain.middleware.PrefactorMiddleware.from_config) manage them for you. * **Parameters:** **config** – Core configuration for the client. * **Returns:** A PrefactorCoreClient ready for `await client.initialize()`. ### Example [Section titled “Example”](#example) config = PrefactorCoreConfig(http\_config=…) client = PrefactorMiddleware.create\_client(config) await client.initialize() instance = await client.create\_agent\_instance( : agent\_id=”my-agent”, agent\_version={“name”: “My Agent”}, agent\_schema\_version=…, ) middleware = PrefactorMiddleware(instance=instance) #### *async* ensure\_initialized() → [AgentInstanceHandle](../../core/reference/prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle) [Section titled “async ensure\_initialized() → AgentInstanceHandle”](#async-ensure_initialized--agentinstancehandle) Initialize the middleware and return the agent instance handle. #### *classmethod* from\_config(api\_url: str, api\_token: str, agent\_id: str | None = None, agent\_name: str | None = None, environment\_id: str | None = None, schema\_registry: [SchemaRegistry](../../core/reference/prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry) | None = None, include\_langchain\_schemas: bool = True, tool\_schemas: Mapping\[str, [LangChainToolSchemaConfig](prefactor_langchain.schemas.md#prefactor_langchain.schemas.LangChainToolSchemaConfig) | Mapping\[str, Any]] | None = None) → [PrefactorMiddleware](#prefactor_langchain.middleware.PrefactorMiddleware) [Section titled “classmethod from\_config(api\_url: str, api\_token: str, agent\_id: str | None = None, agent\_name: str | None = None, environment\_id: str | None = None, schema\_registry: SchemaRegistry | None = None, include\_langchain\_schemas: bool = True, tool\_schemas: Mapping\[str, LangChainToolSchemaConfig | Mapping\[str, Any\]\] | None = None) → PrefactorMiddleware”](#classmethod-from_configapi_url-str-api_token-str-agent_id-str--none--none-agent_name-str--none--none-environment_id-str--none--none-schema_registry-schemaregistry--none--none-include_langchain_schemas-bool--true-tool_schemas-mappingstr-langchaintoolschemaconfig--mappingstr-any--none--none--prefactormiddleware) Factory method to create middleware from configuration. This creates a client and middleware with the specified settings. The middleware owns the client and will auto-initialize it on first use. * **Parameters:** * **api\_url** – The Prefactor API URL. * **api\_token** – The API token for authentication. * **agent\_id** – Optional agent identifier for categorization. * **agent\_name** – Optional human-readable agent name. * **environment\_id** – Optional environment identifier for scoping the agent. * **schema\_registry** – Optional SchemaRegistry for registering span schemas. * **include\_langchain\_schemas** – If True and schema\_registry is provided, automatically register LangChain-specific schemas. * **tool\_schemas** – Optional per-tool schema configuration for tool-specific span types. * **Returns:** A configured PrefactorMiddleware instance with lazy initialization. ### Example [Section titled “Example”](#example-1) middleware = PrefactorMiddleware.from\_config( : api\_url=””, api\_token=”my-token”, agent\_id=”my-agent”, agent\_name=”My Agent”, ) # Middleware auto-initializes on first use [Section titled “Middleware auto-initializes on first use”](#middleware-auto-initializes-on-first-use) # Cleanup when done: [Section titled “Cleanup when done:”](#cleanup-when-done) await middleware.close() # Closes both agent instance and client #### set\_parent\_span(span\_id: str | None) → None [Section titled “set\_parent\_span(span\_id: str | None) → None”](#set_parent_spanspan_id-str--none--none) Set the parent span ID for the next agent invocation (sync path only). Only needed when using `agent.invoke()` via `run_in_executor`. In that case, `before_agent` runs in a worker thread where `contextvars` are not inherited, so the parent span ID must be passed explicitly before entering the executor. When using `agent.ainvoke()` (the recommended async path), parent wiring is automatic via `SpanContextStack` — do not call this method. * **Parameters:** **span\_id** – The span ID to use as the parent, or None to clear it. #### wrap\_model\_call(request: Any, handler: Callable\[\[Any], Any]) → Any [Section titled “wrap\_model\_call(request: Any, handler: Callable\[\[Any\], Any\]) → Any”](#wrap_model_callrequest-any-handler-callableany-any--any) Wrap synchronous model calls to trace LLM execution. * **Parameters:** * **request** – The model request. * **handler** – The function that executes the model call. * **Returns:** The model response. #### wrap\_tool\_call(request: Any, handler: Callable\[\[Any], Any]) → Any [Section titled “wrap\_tool\_call(request: Any, handler: Callable\[\[Any\], Any\]) → Any”](#wrap_tool_callrequest-any-handler-callableany-any--any) Wrap synchronous tool calls to trace tool execution. * **Parameters:** * **request** – The tool request. * **handler** – The function that executes the tool call. * **Returns:** The tool response. # prefactor_langchain.schemas module # prefactor\_langchain.schemas module [Section titled “prefactor\_langchain.schemas module”](#prefactor_langchainschemas-module) LangChain span schemas for Prefactor. This module provides JSON schemas for the built-in LangChain span types, helpers for compiling per-tool span schemas, and registration helpers for loading those schemas into a `SchemaRegistry`. ### *class* prefactor\_langchain.schemas.LangChainToolSchemaConfig(span\_type: str, input\_schema: dict\[str, Any]) [Section titled “class prefactor\_langchain.schemas.LangChainToolSchemaConfig(span\_type: str, input\_schema: dict\[str, Any\])”](#class-prefactor_langchainschemaslangchaintoolschemaconfigspan_type-str-input_schema-dictstr-any) Bases: `object` Configuration for a tool-specific LangChain span schema. #### span\_type [Section titled “span\_type”](#span_type) Tool-specific span type suffix or full span type. Values are normalized to `langchain:tool:`. * **Type:** str #### input\_schema [Section titled “input\_schema”](#input_schema) JSON schema for the tool arguments stored in `inputs` for tool-specific spans. * **Type:** dict\[str, Any] #### input\_schema *: dict\[str, Any]* [Section titled “input\_schema : dict\[str, Any\]”](#input_schema--dictstr-any) #### span\_type *: str* [Section titled “span\_type : str”](#span_type--str) ### prefactor\_langchain.schemas.compile\_langchain\_agent\_schema(agent\_schema: Mapping\[str, Any] | None = None, , tool\_schemas: Mapping\[str, [LangChainToolSchemaConfig](#prefactor_langchain.schemas.LangChainToolSchemaConfig) | Mapping\[str, Any]] | None = None) → tuple\[dict\[str, Any], dict\[str, str]] [Section titled “prefactor\_langchain.schemas.compile\_langchain\_agent\_schema(agent\_schema: Mapping\[str, Any\] | None = None, , tool\_schemas: Mapping\[str, LangChainToolSchemaConfig | Mapping\[str, Any\]\] | None = None) → tuple\[dict\[str, Any\], dict\[str, str\]\]”](#prefactor_langchainschemascompile_langchain_agent_schemaagent_schema-mappingstr-any--none--none--tool_schemas-mappingstr-langchaintoolschemaconfig--mappingstr-any--none--none--tupledictstr-any-dictstr-str) Compile a LangChain agent schema with optional tool-specific span types. * **Parameters:** * **agent\_schema** – Optional base agent schema to merge with the built-in LangChain span schemas. * **tool\_schemas** – Optional Python-first per-tool schema configuration. * **Returns:** A tuple of `(compiled_agent_schema, tool_span_types)` where `tool_span_types` maps tool names to normalized span types. ### prefactor\_langchain.schemas.register\_langchain\_schemas(registry: Any, , agent\_schema: Mapping\[str, Any] | None = None, tool\_schemas: Mapping\[str, [LangChainToolSchemaConfig](#prefactor_langchain.schemas.LangChainToolSchemaConfig) | Mapping\[str, Any]] | None = None) → dict\[str, str] [Section titled “prefactor\_langchain.schemas.register\_langchain\_schemas(registry: Any, , agent\_schema: Mapping\[str, Any\] | None = None, tool\_schemas: Mapping\[str, LangChainToolSchemaConfig | Mapping\[str, Any\]\] | None = None) → dict\[str, str\]”](#prefactor_langchainschemasregister_langchain_schemasregistry-any--agent_schema-mappingstr-any--none--none-tool_schemas-mappingstr-langchaintoolschemaconfig--mappingstr-any--none--none--dictstr-str) Register all LangChain span schemas with a schema registry. Registers the built-in schemas for LangChain-specific span types (agent, llm, tool) using the full `span_type_schemas` form, which includes params schemas, result schemas, titles, and descriptions. When tool schemas are configured, this also registers per-tool span types. * **Parameters:** * **registry** – The SchemaRegistry to register schemas with. * **agent\_schema** – Optional base agent schema that may include embedded `toolSchemas` or `tool_schemas` config. * **tool\_schemas** – Optional Python-first per-tool schema configuration. * **Returns:** A dict mapping tool names to their normalized span types. Returns an empty dict when no tool-specific schemas are registered. ### Example [Section titled “Example”](#example) from prefactor\_core import SchemaRegistry from prefactor\_langchain.schemas import register\_langchain\_schemas registry = SchemaRegistry() register\_langchain\_schemas(registry) # Now the registry has langchain:agent, langchain:llm, langchain:tool [Section titled “Now the registry has langchain:agent, langchain:llm, langchain:tool”](#now-the-registry-has-langchainagent-langchainllm-langchaintool) assert registry.has\_schema(“langchain:llm”) # prefactor_langchain.spans module # prefactor\_langchain.spans module [Section titled “prefactor\_langchain.spans module”](#prefactor_langchainspans-module) LangChain-specific span definitions for Prefactor observability. This module defines span dataclasses that capture LangChain-specific semantics using the ‘langchain: ```plaintext * ``` ’ type namespace. These spans are self-contained and can be serialized to JSON for transport to the backend. Note: span\_id, parent\_span\_id, and trace\_id are managed by the backend automatically, so they are not included in these span definitions. ### *class* prefactor\_langchain.spans.AgentSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’]=‘pending’, inputs: dict\[str, \~typing.Any]=, outputs: dict\[str, \~typing.Any] | None=None, metadata: dict\[str, \~typing.Any]=, tags: list\[str] = , error: [ErrorInfo](#prefactor_langchain.spans.ErrorInfo) | None = None, type: str = ‘langchain:agent’, agent\_name: str | None = None, agent\_config: dict\[str, \~typing.Any]=, initial\_messages: list\[dict\[str, \~typing.Any]]=, final\_messages: list\[dict\[str, \~typing.Any]]=, iteration\_count: int = 0) [Section titled “class prefactor\_langchain.spans.AgentSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’\]=‘pending’, inputs: dict\[str, \~typing.Any\]=, outputs: dict\[str, \~typing.Any\] | None=None, metadata: dict\[str, \~typing.Any\]=, tags: list\[str\] = , error: ErrorInfo | None = None, type: str = ‘langchain:agent’, agent\_name: str | None = None, agent\_config: dict\[str, \~typing.Any\]=, initial\_messages: list\[dict\[str, \~typing.Any\]\]=, final\_messages: list\[dict\[str, \~typing.Any\]\]=, iteration\_count: int = 0)”](#class-prefactor_langchainspansagentspanname-str--unnamed-start_time-float---end_time-float--none--none-status-literalpending-running-completed-failedpending-inputs-dictstr-typingany-outputs-dictstr-typingany--nonenone-metadata-dictstr-typingany-tags-liststr---error-errorinfo--none--none-type-str--langchainagent-agent_name-str--none--none-agent_config-dictstr-typingany-initial_messages-listdictstr-typingany-final_messages-listdictstr-typingany-iteration_count-int--0) Bases: [`LangChainSpan`](#prefactor_langchain.spans.LangChainSpan) Span representing an agent execution. Captures the lifecycle of an agent run, including the agent’s name, configuration, and the messages/state that drove the execution. #### agent\_config *: dict\[str, Any]* [Section titled “agent\_config : dict\[str, Any\]”](#agent_config--dictstr-any) #### agent\_name *: str | None* *= None* [Section titled “agent\_name : str | None = None”](#agent_name--str--none--none) #### final\_messages *: list\[dict\[str, Any]]* [Section titled “final\_messages : list\[dict\[str, Any\]\]”](#final_messages--listdictstr-any) #### initial\_messages *: list\[dict\[str, Any]]* [Section titled “initial\_messages : list\[dict\[str, Any\]\]”](#initial_messages--listdictstr-any) #### iteration\_count *: int* *= 0* [Section titled “iteration\_count : int = 0”](#iteration_count--int--0) #### to\_dict() → dict\[str, Any] [Section titled “to\_dict() → dict\[str, Any\]”](#to_dict--dictstr-any) Convert to dictionary including agent-specific fields. #### type *: str* *= ‘langchain:agent’* [Section titled “type : str = ‘langchain:agent’”](#type--str--langchainagent) ### *class* prefactor\_langchain.spans.ErrorInfo(error\_type: str, message: str, stacktrace: str | None = None) [Section titled “class prefactor\_langchain.spans.ErrorInfo(error\_type: str, message: str, stacktrace: str | None = None)”](#class-prefactor_langchainspanserrorinfoerror_type-str-message-str-stacktrace-str--none--none) Bases: `object` Error information for failed spans. #### error\_type *: str* [Section titled “error\_type : str”](#error_type--str) #### message *: str* [Section titled “message : str”](#message--str) #### stacktrace *: str | None* *= None* [Section titled “stacktrace : str | None = None”](#stacktrace--str--none--none) #### to\_dict() → dict\[str, Any] [Section titled “to\_dict() → dict\[str, Any\]”](#to_dict--dictstr-any-1) Convert to dictionary for serialization. ### *class* prefactor\_langchain.spans.LLMSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’]=‘pending’, inputs: dict\[str, \~typing.Any]=, outputs: dict\[str, \~typing.Any] | None=None, metadata: dict\[str, \~typing.Any]=, tags: list\[str] = , error: [ErrorInfo](#prefactor_langchain.spans.ErrorInfo) | None = None, type: str = ‘langchain:agent’, model\_name: str | None = None, provider: str | None = None, token\_usage: [TokenUsage](#prefactor_langchain.spans.TokenUsage) | None = None, temperature: float | None = None, max\_tokens: int | None = None, top\_p: float | None = None, stop\_sequences: list\[str] = , messages: list\[dict\[str, \~typing.Any]]=, response\_content: str | None = None) [Section titled “class prefactor\_langchain.spans.LLMSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’\]=‘pending’, inputs: dict\[str, \~typing.Any\]=, outputs: dict\[str, \~typing.Any\] | None=None, metadata: dict\[str, \~typing.Any\]=, tags: list\[str\] = , error: ErrorInfo | None = None, type: str = ‘langchain:agent’, model\_name: str | None = None, provider: str | None = None, token\_usage: TokenUsage | None = None, temperature: float | None = None, max\_tokens: int | None = None, top\_p: float | None = None, stop\_sequences: list\[str\] = , messages: list\[dict\[str, \~typing.Any\]\]=, response\_content: str | None = None)”](#class-prefactor_langchainspansllmspanname-str--unnamed-start_time-float---end_time-float--none--none-status-literalpending-running-completed-failedpending-inputs-dictstr-typingany-outputs-dictstr-typingany--nonenone-metadata-dictstr-typingany-tags-liststr---error-errorinfo--none--none-type-str--langchainagent-model_name-str--none--none-provider-str--none--none-token_usage-tokenusage--none--none-temperature-float--none--none-max_tokens-int--none--none-top_p-float--none--none-stop_sequences-liststr---messages-listdictstr-typingany-response_content-str--none--none) Bases: [`LangChainSpan`](#prefactor_langchain.spans.LangChainSpan) Span representing an LLM call. Captures model-specific metadata including the model name, provider, token usage, and generation parameters. #### max\_tokens *: int | None* *= None* [Section titled “max\_tokens : int | None = None”](#max_tokens--int--none--none) #### messages *: list\[dict\[str, Any]]* [Section titled “messages : list\[dict\[str, Any\]\]”](#messages--listdictstr-any) #### model\_name *: str | None* *= None* [Section titled “model\_name : str | None = None”](#model_name--str--none--none) #### provider *: str | None* *= None* [Section titled “provider : str | None = None”](#provider--str--none--none) #### response\_content *: str | None* *= None* [Section titled “response\_content : str | None = None”](#response_content--str--none--none) #### stop\_sequences *: list\[str]* [Section titled “stop\_sequences : list\[str\]”](#stop_sequences--liststr) #### temperature *: float | None* *= None* [Section titled “temperature : float | None = None”](#temperature--float--none--none) #### to\_dict() → dict\[str, Any] [Section titled “to\_dict() → dict\[str, Any\]”](#to_dict--dictstr-any-2) Convert to dictionary including LLM-specific fields. #### token\_usage *: [TokenUsage](#prefactor_langchain.spans.TokenUsage) | None* *= None* [Section titled “token\_usage : TokenUsage | None = None”](#token_usage--tokenusage--none--none) #### top\_p *: float | None* *= None* [Section titled “top\_p : float | None = None”](#top_p--float--none--none) #### type *: str* *= ‘langchain:llm’* [Section titled “type : str = ‘langchain:llm’”](#type--str--langchainllm) ### *class* prefactor\_langchain.spans.LangChainSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’]=‘pending’, inputs: dict\[str, \~typing.Any]=, outputs: dict\[str, \~typing.Any] | None=None, metadata: dict\[str, \~typing.Any]=, tags: list\[str] = , error: [ErrorInfo](#prefactor_langchain.spans.ErrorInfo) | None = None, type: str = ‘langchain:agent’) [Section titled “class prefactor\_langchain.spans.LangChainSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’\]=‘pending’, inputs: dict\[str, \~typing.Any\]=, outputs: dict\[str, \~typing.Any\] | None=None, metadata: dict\[str, \~typing.Any\]=, tags: list\[str\] = , error: ErrorInfo | None = None, type: str = ‘langchain:agent’)”](#class-prefactor_langchainspanslangchainspanname-str--unnamed-start_time-float---end_time-float--none--none-status-literalpending-running-completed-failedpending-inputs-dictstr-typingany-outputs-dictstr-typingany--nonenone-metadata-dictstr-typingany-tags-liststr---error-errorinfo--none--none-type-str--langchainagent) Bases: `object` Base class for all LangChain spans. All LangChain spans share common fields for timing, status, inputs/outputs, and error information. Trace correlation (span\_id, parent\_span\_id, trace\_id) is handled by the backend. Note: The ‘type’ field is defined in subclasses to avoid dataclass field shadowing issues. #### complete(outputs: dict\[str, Any] | None = None) → None [Section titled “complete(outputs: dict\[str, Any\] | None = None) → None”](#completeoutputs-dictstr-any--none--none--none) Mark the span as completed with outputs. #### end\_time *: float | None* *= None* [Section titled “end\_time : float | None = None”](#end_time--float--none--none) #### error *: [ErrorInfo](#prefactor_langchain.spans.ErrorInfo) | None* *= None* [Section titled “error : ErrorInfo | None = None”](#error--errorinfo--none--none) #### fail(error: Exception) → None [Section titled “fail(error: Exception) → None”](#failerror-exception--none) Mark the span as failed with error information. #### inputs *: dict\[str, Any]* [Section titled “inputs : dict\[str, Any\]”](#inputs--dictstr-any) #### metadata *: dict\[str, Any]* [Section titled “metadata : dict\[str, Any\]”](#metadata--dictstr-any) #### name *: str* *= ‘unnamed’* [Section titled “name : str = ‘unnamed’”](#name--str--unnamed) #### outputs *: dict\[str, Any] | None* *= None* [Section titled “outputs : dict\[str, Any\] | None = None”](#outputs--dictstr-any--none--none) #### start\_time *: float* [Section titled “start\_time : float”](#start_time--float) #### status *: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’]* *= ‘pending’* [Section titled “status : Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’\] = ‘pending’”](#status--literalpending-running-completed-failed--pending) #### tags *: list\[str]* [Section titled “tags : list\[str\]”](#tags--liststr) #### to\_dict() → dict\[str, Any] [Section titled “to\_dict() → dict\[str, Any\]”](#to_dict--dictstr-any-3) Convert span to dictionary for serialization. Returns a JSON-serializable dictionary representation of the span. #### type *: str* *= ‘langchain:agent’* [Section titled “type : str = ‘langchain:agent’”](#type--str--langchainagent-1) ### *class* prefactor\_langchain.spans.TokenUsage(prompt\_tokens: int, completion\_tokens: int, total\_tokens: int) [Section titled “class prefactor\_langchain.spans.TokenUsage(prompt\_tokens: int, completion\_tokens: int, total\_tokens: int)”](#class-prefactor_langchainspanstokenusageprompt_tokens-int-completion_tokens-int-total_tokens-int) Bases: `object` Token usage information for LLM calls. #### completion\_tokens *: int* [Section titled “completion\_tokens : int”](#completion_tokens--int) #### prompt\_tokens *: int* [Section titled “prompt\_tokens : int”](#prompt_tokens--int) #### to\_dict() → dict\[str, Any] [Section titled “to\_dict() → dict\[str, Any\]”](#to_dict--dictstr-any-4) Convert to dictionary for serialization. #### total\_tokens *: int* [Section titled “total\_tokens : int”](#total_tokens--int) ### *class* prefactor\_langchain.spans.ToolSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’]=‘pending’, inputs: dict\[str, \~typing.Any]=, outputs: dict\[str, \~typing.Any] | None=None, metadata: dict\[str, \~typing.Any]=, tags: list\[str] = , error: [ErrorInfo](#prefactor_langchain.spans.ErrorInfo) | None = None, type: str = ‘langchain:agent’, tool\_name: str | None = None, tool\_schema: dict\[str, \~typing.Any] | None=None, arguments: dict\[str, \~typing.Any]=, execution\_time\_ms: int | None = None, tool\_type: str | None = None, retriever\_metadata: dict\[str, \~typing.Any] | None=None) [Section titled “class prefactor\_langchain.spans.ToolSpan(name: str = ‘unnamed’, start\_time: float = , end\_time: float | None = None, status: Literal\[‘pending’, ‘running’, ‘completed’, ‘failed’\]=‘pending’, inputs: dict\[str, \~typing.Any\]=, outputs: dict\[str, \~typing.Any\] | None=None, metadata: dict\[str, \~typing.Any\]=, tags: list\[str\] = , error: ErrorInfo | None = None, type: str = ‘langchain:agent’, tool\_name: str | None = None, tool\_schema: dict\[str, \~typing.Any\] | None=None, arguments: dict\[str, \~typing.Any\]=, execution\_time\_ms: int | None = None, tool\_type: str | None = None, retriever\_metadata: dict\[str, \~typing.Any\] | None=None)”](#class-prefactor_langchainspanstoolspanname-str--unnamed-start_time-float---end_time-float--none--none-status-literalpending-running-completed-failedpending-inputs-dictstr-typingany-outputs-dictstr-typingany--nonenone-metadata-dictstr-typingany-tags-liststr---error-errorinfo--none--none-type-str--langchainagent-tool_name-str--none--none-tool_schema-dictstr-typingany--nonenone-arguments-dictstr-typingany-execution_time_ms-int--none--none-tool_type-str--none--none-retriever_metadata-dictstr-typingany--nonenone) Bases: [`LangChainSpan`](#prefactor_langchain.spans.LangChainSpan) Span representing a tool execution. Captures tool-specific metadata including the tool name, schema, arguments, and execution time. Can represent any tool call including retrievers (with appropriate metadata). #### arguments *: dict\[str, Any]* [Section titled “arguments : dict\[str, Any\]”](#arguments--dictstr-any) #### execution\_time\_ms *: int | None* *= None* [Section titled “execution\_time\_ms : int | None = None”](#execution_time_ms--int--none--none) #### retriever\_metadata *: dict\[str, Any] | None* *= None* [Section titled “retriever\_metadata : dict\[str, Any\] | None = None”](#retriever_metadata--dictstr-any--none--none) #### to\_dict() → dict\[str, Any] [Section titled “to\_dict() → dict\[str, Any\]”](#to_dict--dictstr-any-5) Convert to dictionary including tool-specific fields. #### tool\_name *: str | None* *= None* [Section titled “tool\_name : str | None = None”](#tool_name--str--none--none) #### tool\_schema *: dict\[str, Any] | None* *= None* [Section titled “tool\_schema : dict\[str, Any\] | None = None”](#tool_schema--dictstr-any--none--none) #### tool\_type *: str | None* *= None* [Section titled “tool\_type : str | None = None”](#tool_type--str--none--none) #### type *: str* *= ‘langchain:tool’* [Section titled “type : str = ‘langchain:tool’”](#type--str--langchaintool) # prefactor-livekit # prefactor-livekit [Section titled “prefactor-livekit”](#prefactor-livekit) LiveKit Agents integration for Prefactor observability. This package wraps `livekit-agents` sessions and emits Prefactor spans from public LiveKit session events. ## Installation [Section titled “Installation”](#installation) ```bash pip install prefactor-livekit ``` ## Usage [Section titled “Usage”](#usage) ### Factory pattern [Section titled “Factory pattern”](#factory-pattern) ```python from livekit.agents import AgentSession from prefactor_livekit import PrefactorLiveKitSession session = AgentSession(...) tracer = PrefactorLiveKitSession.from_config( api_url="https://app.prefactorai.com", api_token="your-api-token", agent_id="voice-agent", # Optional for deployment-scoped tokens agent_name="Voice Agent", ) await tracer.start(session=session, agent=my_agent) await tracer.close() ``` With a deployment-scoped token you can omit `agent_id`; the backend derives the agent and environment from the token during registration. ### Example runner [Section titled “Example runner”](#example-runner) The example script has a local smoke mode that emits representative LiveKit session events into Prefactor without needing STT/TTS providers or a room. ```bash uv run python packages/livekit/examples/simple_session.py --mode smoke ``` It prints the Prefactor instance ID plus ready-to-run Prefactor CLI commands for retrieving the instance and listing spans for the example’s time window. ```bash prefactor agent_instances retrieve prefactor agent_spans list \ --agent_instance_id \ --start_time \ --end_time \ --include_summaries ``` There is also a model-backed mode for a real text turn: ```bash uv run python packages/livekit/examples/simple_session.py \ --mode live \ --model anthropic/claude-sonnet-4-5-20250929 ``` ### Manual attachment [Section titled “Manual attachment”](#manual-attachment) Use this when your app manages the session lifecycle itself and you just want the LiveKit events traced. ```python from prefactor_livekit import PrefactorLiveKitSession tracer = PrefactorLiveKitSession(instance=instance) await tracer.attach(session) await session.generate_reply(user_input="hello") await tracer.close() ``` ## Traced span types [Section titled “Traced span types”](#traced-span-types) * `livekit:session` * `livekit:user_turn` * `livekit:assistant_turn` * `livekit:tool` * `livekit:llm` * `livekit:stt` * `livekit:tts` * `livekit:state` * `livekit:error` ## Development [Section titled “Development”](#development) ```bash uv run pytest packages/livekit/tests -v ``` # prefactor_livekit # prefactor\_livekit [Section titled “prefactor\_livekit”](#prefactor_livekit) * [prefactor\_livekit package](prefactor_livekit.md) * [`LiveKitToolSchemaConfig`](prefactor_livekit.md#prefactor_livekit.LiveKitToolSchemaConfig) * [`LiveKitToolSchemaConfig.input_schema`](prefactor_livekit.md#prefactor_livekit.LiveKitToolSchemaConfig.input_schema) * [`LiveKitToolSchemaConfig.result_schema`](prefactor_livekit.md#prefactor_livekit.LiveKitToolSchemaConfig.result_schema) * [`LiveKitToolSchemaConfig.span_type`](prefactor_livekit.md#prefactor_livekit.LiveKitToolSchemaConfig.span_type) * [`PrefactorLiveKitSession`](prefactor_livekit.md#prefactor_livekit.PrefactorLiveKitSession) * [`PrefactorLiveKitSession.attach()`](prefactor_livekit.md#prefactor_livekit.PrefactorLiveKitSession.attach) * [`PrefactorLiveKitSession.close()`](prefactor_livekit.md#prefactor_livekit.PrefactorLiveKitSession.close) * [`PrefactorLiveKitSession.create_client()`](prefactor_livekit.md#prefactor_livekit.PrefactorLiveKitSession.create_client) * [`PrefactorLiveKitSession.ensure_initialized()`](prefactor_livekit.md#prefactor_livekit.PrefactorLiveKitSession.ensure_initialized) * [`PrefactorLiveKitSession.from_config()`](prefactor_livekit.md#prefactor_livekit.PrefactorLiveKitSession.from_config) * [`PrefactorLiveKitSession.start()`](prefactor_livekit.md#prefactor_livekit.PrefactorLiveKitSession.start) * [`compile_livekit_agent_schema()`](prefactor_livekit.md#prefactor_livekit.compile_livekit_agent_schema) * [`register_livekit_schemas()`](prefactor_livekit.md#prefactor_livekit.register_livekit_schemas) * [Submodules](prefactor_livekit.md#submodules) * [prefactor\_livekit.schemas module](prefactor_livekit.schemas.md) * [`LiveKitToolSchemaConfig`](prefactor_livekit.schemas.md#prefactor_livekit.schemas.LiveKitToolSchemaConfig) * [`compile_livekit_agent_schema()`](prefactor_livekit.schemas.md#prefactor_livekit.schemas.compile_livekit_agent_schema) * [`register_livekit_schemas()`](prefactor_livekit.schemas.md#prefactor_livekit.schemas.register_livekit_schemas) * [prefactor\_livekit.session module](prefactor_livekit.session.md) * [`PrefactorLiveKitSession`](prefactor_livekit.session.md#prefactor_livekit.session.PrefactorLiveKitSession) # prefactor_livekit package # prefactor\_livekit package [Section titled “prefactor\_livekit package”](#prefactor_livekit-package) Prefactor LiveKit integration package. ### *class* prefactor\_livekit.LiveKitToolSchemaConfig(span\_type: str, input\_schema: dict\[str, \~typing.Any], result\_schema: dict\[str, \~typing.Any] = ) [Section titled “class prefactor\_livekit.LiveKitToolSchemaConfig(span\_type: str, input\_schema: dict\[str, \~typing.Any\], result\_schema: dict\[str, \~typing.Any\] = )”](#class-prefactor_livekitlivekittoolschemaconfigspan_type-str-input_schema-dictstr-typingany-result_schema-dictstr-typingany--) Bases: `object` Configuration for a tool-specific LiveKit span schema. #### input\_schema *: dict\[str, Any]* [Section titled “input\_schema : dict\[str, Any\]”](#input_schema--dictstr-any) #### result\_schema *: dict\[str, Any]* [Section titled “result\_schema : dict\[str, Any\]”](#result_schema--dictstr-any) #### span\_type *: str* [Section titled “span\_type : str”](#span_type--str) ### *class* prefactor\_livekit.PrefactorLiveKitSession(client: [PrefactorCoreClient](../../core/reference/prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient) | None = None, agent\_id: str | None = None, agent\_name: str | None = None, instance: [AgentInstanceHandle](../../core/reference/prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle) | None = None, tool\_schemas: Mapping\[str, [LiveKitToolSchemaConfig](prefactor_livekit.schemas.md#prefactor_livekit.schemas.LiveKitToolSchemaConfig) | Mapping\[str, Any]] | None = None) [Section titled “class prefactor\_livekit.PrefactorLiveKitSession(client: PrefactorCoreClient | None = None, agent\_id: str | None = None, agent\_name: str | None = None, instance: AgentInstanceHandle | None = None, tool\_schemas: Mapping\[str, LiveKitToolSchemaConfig | Mapping\[str, Any\]\] | None = None)”](#class-prefactor_livekitprefactorlivekitsessionclient-prefactorcoreclient--none--none-agent_id-str--none--none-agent_name-str--none--none-instance-agentinstancehandle--none--none-tool_schemas-mappingstr-livekittoolschemaconfig--mappingstr-any--none--none) Bases: `object` High-level LiveKit session wrapper for Prefactor tracing. #### *async* attach(session: AgentSession\[Any]) → [AgentInstanceHandle](../../core/reference/prefactor_core.md#prefactor_core.AgentInstanceHandle) [Section titled “async attach(session: AgentSession\[Any\]) → AgentInstanceHandle”](#async-attachsession-agentsessionany--agentinstancehandle) Attach to an existing LiveKit session. #### *async* close() → None [Section titled “async close() → None”](#async-close--none) Flush pending tasks and release wrapper-owned resources. #### *static* create\_client(config: [PrefactorCoreConfig](../../core/reference/prefactor_core.config.md#prefactor_core.config.PrefactorCoreConfig)) → [PrefactorCoreClient](../../core/reference/prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient) [Section titled “static create\_client(config: PrefactorCoreConfig) → PrefactorCoreClient”](#static-create_clientconfig-prefactorcoreconfig--prefactorcoreclient) Create a PrefactorCoreClient configured for use with this adaptor. Use this when you need to manage the client and instance lifecycle yourself (e.g. to share a client between the session wrapper and other code) instead of letting [`from_config()`](#prefactor_livekit.PrefactorLiveKitSession.from_config) manage them for you. * **Parameters:** **config** – Core configuration for the client. * **Returns:** A PrefactorCoreClient ready for `await client.initialize()`. ### Example [Section titled “Example”](#example) config = PrefactorCoreConfig(http\_config=…) client = PrefactorLiveKitSession.create\_client(config) await client.initialize() instance = await client.create\_agent\_instance( : agent\_id=”my-agent”, agent\_version={“name”: “My Agent”}, agent\_schema\_version=…, ) session = PrefactorLiveKitSession(instance=instance) #### *async* ensure\_initialized() → [AgentInstanceHandle](../../core/reference/prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle) [Section titled “async ensure\_initialized() → AgentInstanceHandle”](#async-ensure_initialized--agentinstancehandle) Initialize and return the active Prefactor instance. #### *classmethod* from\_config(api\_url: str, api\_token: str, agent\_id: str | None = None, agent\_name: str | None = None, schema\_registry: [SchemaRegistry](../../core/reference/prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry) | None = None, include\_livekit\_schemas: bool = True, tool\_schemas: Mapping\[str, [LiveKitToolSchemaConfig](prefactor_livekit.schemas.md#prefactor_livekit.schemas.LiveKitToolSchemaConfig) | Mapping\[str, Any]] | None = None) → [PrefactorLiveKitSession](prefactor_livekit.session.md#prefactor_livekit.session.PrefactorLiveKitSession) [Section titled “classmethod from\_config(api\_url: str, api\_token: str, agent\_id: str | None = None, agent\_name: str | None = None, schema\_registry: SchemaRegistry | None = None, include\_livekit\_schemas: bool = True, tool\_schemas: Mapping\[str, LiveKitToolSchemaConfig | Mapping\[str, Any\]\] | None = None) → PrefactorLiveKitSession”](#classmethod-from_configapi_url-str-api_token-str-agent_id-str--none--none-agent_name-str--none--none-schema_registry-schemaregistry--none--none-include_livekit_schemas-bool--true-tool_schemas-mappingstr-livekittoolschemaconfig--mappingstr-any--none--none--prefactorlivekitsession) Create a wrapper from raw configuration. #### *async* start(session: AgentSession\[Any], agent: [Agent](../../http/reference/prefactor_http.models.md#prefactor_http.models.Agent), \*\*kwargs: Any) → Any [Section titled “async start(session: AgentSession\[Any\], agent: Agent, \*\*kwargs: Any) → Any”](#async-startsession-agentsessionany-agent-agent-kwargs-any--any) Attach and delegate to `AgentSession.start()`. ### prefactor\_livekit.compile\_livekit\_agent\_schema(tool\_schemas: Mapping\[str, [LiveKitToolSchemaConfig](prefactor_livekit.schemas.md#prefactor_livekit.schemas.LiveKitToolSchemaConfig) | Mapping\[str, Any]] | None = None) → tuple\[dict\[str, Any], dict\[str, str]] [Section titled “prefactor\_livekit.compile\_livekit\_agent\_schema(tool\_schemas: Mapping\[str, LiveKitToolSchemaConfig | Mapping\[str, Any\]\] | None = None) → tuple\[dict\[str, Any\], dict\[str, str\]\]”](#prefactor_livekitcompile_livekit_agent_schematool_schemas-mappingstr-livekittoolschemaconfig--mappingstr-any--none--none--tupledictstr-any-dictstr-str) Compile built-in and tool-specific LiveKit schemas. ### prefactor\_livekit.register\_livekit\_schemas(registry: [SchemaRegistry](../../core/reference/prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry), tool\_schemas: Mapping\[str, [LiveKitToolSchemaConfig](prefactor_livekit.schemas.md#prefactor_livekit.schemas.LiveKitToolSchemaConfig) | Mapping\[str, Any]] | None = None) → dict\[str, str] [Section titled “prefactor\_livekit.register\_livekit\_schemas(registry: SchemaRegistry, tool\_schemas: Mapping\[str, LiveKitToolSchemaConfig | Mapping\[str, Any\]\] | None = None) → dict\[str, str\]”](#prefactor_livekitregister_livekit_schemasregistry-schemaregistry-tool_schemas-mappingstr-livekittoolschemaconfig--mappingstr-any--none--none--dictstr-str) Register LiveKit schemas in a schema registry. ## Submodules [Section titled “Submodules”](#submodules) * [prefactor\_livekit.schemas module](prefactor_livekit.schemas.md) * [`LiveKitToolSchemaConfig`](prefactor_livekit.schemas.md#prefactor_livekit.schemas.LiveKitToolSchemaConfig) * [`LiveKitToolSchemaConfig.input_schema`](prefactor_livekit.schemas.md#prefactor_livekit.schemas.LiveKitToolSchemaConfig.input_schema) * [`LiveKitToolSchemaConfig.result_schema`](prefactor_livekit.schemas.md#prefactor_livekit.schemas.LiveKitToolSchemaConfig.result_schema) * [`LiveKitToolSchemaConfig.span_type`](prefactor_livekit.schemas.md#prefactor_livekit.schemas.LiveKitToolSchemaConfig.span_type) * [`compile_livekit_agent_schema()`](prefactor_livekit.schemas.md#prefactor_livekit.schemas.compile_livekit_agent_schema) * [`register_livekit_schemas()`](prefactor_livekit.schemas.md#prefactor_livekit.schemas.register_livekit_schemas) * [prefactor\_livekit.session module](prefactor_livekit.session.md) * [`PrefactorLiveKitSession`](prefactor_livekit.session.md#prefactor_livekit.session.PrefactorLiveKitSession) * [`PrefactorLiveKitSession.attach()`](prefactor_livekit.session.md#prefactor_livekit.session.PrefactorLiveKitSession.attach) * [`PrefactorLiveKitSession.close()`](prefactor_livekit.session.md#prefactor_livekit.session.PrefactorLiveKitSession.close) * [`PrefactorLiveKitSession.create_client()`](prefactor_livekit.session.md#prefactor_livekit.session.PrefactorLiveKitSession.create_client) * [`PrefactorLiveKitSession.ensure_initialized()`](prefactor_livekit.session.md#prefactor_livekit.session.PrefactorLiveKitSession.ensure_initialized) * [`PrefactorLiveKitSession.from_config()`](prefactor_livekit.session.md#prefactor_livekit.session.PrefactorLiveKitSession.from_config) * [`PrefactorLiveKitSession.start()`](prefactor_livekit.session.md#prefactor_livekit.session.PrefactorLiveKitSession.start) # prefactor_livekit.schemas module # prefactor\_livekit.schemas module [Section titled “prefactor\_livekit.schemas module”](#prefactor_livekitschemas-module) LiveKit span schemas for Prefactor. ### *class* prefactor\_livekit.schemas.LiveKitToolSchemaConfig(span\_type: str, input\_schema: dict\[str, \~typing.Any], result\_schema: dict\[str, \~typing.Any] = ) [Section titled “class prefactor\_livekit.schemas.LiveKitToolSchemaConfig(span\_type: str, input\_schema: dict\[str, \~typing.Any\], result\_schema: dict\[str, \~typing.Any\] = )”](#class-prefactor_livekitschemaslivekittoolschemaconfigspan_type-str-input_schema-dictstr-typingany-result_schema-dictstr-typingany--) Bases: `object` Configuration for a tool-specific LiveKit span schema. #### input\_schema *: dict\[str, Any]* [Section titled “input\_schema : dict\[str, Any\]”](#input_schema--dictstr-any) #### result\_schema *: dict\[str, Any]* [Section titled “result\_schema : dict\[str, Any\]”](#result_schema--dictstr-any) #### span\_type *: str* [Section titled “span\_type : str”](#span_type--str) ### prefactor\_livekit.schemas.compile\_livekit\_agent\_schema(tool\_schemas: Mapping\[str, [LiveKitToolSchemaConfig](#prefactor_livekit.schemas.LiveKitToolSchemaConfig) | Mapping\[str, Any]] | None = None) → tuple\[dict\[str, Any], dict\[str, str]] [Section titled “prefactor\_livekit.schemas.compile\_livekit\_agent\_schema(tool\_schemas: Mapping\[str, LiveKitToolSchemaConfig | Mapping\[str, Any\]\] | None = None) → tuple\[dict\[str, Any\], dict\[str, str\]\]”](#prefactor_livekitschemascompile_livekit_agent_schematool_schemas-mappingstr-livekittoolschemaconfig--mappingstr-any--none--none--tupledictstr-any-dictstr-str) Compile built-in and tool-specific LiveKit schemas. ### prefactor\_livekit.schemas.register\_livekit\_schemas(registry: [SchemaRegistry](../../core/reference/prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry), tool\_schemas: Mapping\[str, [LiveKitToolSchemaConfig](#prefactor_livekit.schemas.LiveKitToolSchemaConfig) | Mapping\[str, Any]] | None = None) → dict\[str, str] [Section titled “prefactor\_livekit.schemas.register\_livekit\_schemas(registry: SchemaRegistry, tool\_schemas: Mapping\[str, LiveKitToolSchemaConfig | Mapping\[str, Any\]\] | None = None) → dict\[str, str\]”](#prefactor_livekitschemasregister_livekit_schemasregistry-schemaregistry-tool_schemas-mappingstr-livekittoolschemaconfig--mappingstr-any--none--none--dictstr-str) Register LiveKit schemas in a schema registry. # prefactor_livekit.session module # prefactor\_livekit.session module [Section titled “prefactor\_livekit.session module”](#prefactor_livekitsession-module) LiveKit session wrapper for Prefactor observability. ### *class* prefactor\_livekit.session.PrefactorLiveKitSession(client: [PrefactorCoreClient](../../core/reference/prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient) | None = None, agent\_id: str | None = None, agent\_name: str | None = None, instance: [AgentInstanceHandle](../../core/reference/prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle) | None = None, tool\_schemas: Mapping\[str, [LiveKitToolSchemaConfig](prefactor_livekit.schemas.md#prefactor_livekit.schemas.LiveKitToolSchemaConfig) | Mapping\[str, Any]] | None = None) [Section titled “class prefactor\_livekit.session.PrefactorLiveKitSession(client: PrefactorCoreClient | None = None, agent\_id: str | None = None, agent\_name: str | None = None, instance: AgentInstanceHandle | None = None, tool\_schemas: Mapping\[str, LiveKitToolSchemaConfig | Mapping\[str, Any\]\] | None = None)”](#class-prefactor_livekitsessionprefactorlivekitsessionclient-prefactorcoreclient--none--none-agent_id-str--none--none-agent_name-str--none--none-instance-agentinstancehandle--none--none-tool_schemas-mappingstr-livekittoolschemaconfig--mappingstr-any--none--none) Bases: `object` High-level LiveKit session wrapper for Prefactor tracing. #### *async* attach(session: AgentSession\[Any]) → [AgentInstanceHandle](../../core/reference/prefactor_core.md#prefactor_core.AgentInstanceHandle) [Section titled “async attach(session: AgentSession\[Any\]) → AgentInstanceHandle”](#async-attachsession-agentsessionany--agentinstancehandle) Attach to an existing LiveKit session. #### *async* close() → None [Section titled “async close() → None”](#async-close--none) Flush pending tasks and release wrapper-owned resources. #### *static* create\_client(config: [PrefactorCoreConfig](../../core/reference/prefactor_core.config.md#prefactor_core.config.PrefactorCoreConfig)) → [PrefactorCoreClient](../../core/reference/prefactor_core.client.md#prefactor_core.client.PrefactorCoreClient) [Section titled “static create\_client(config: PrefactorCoreConfig) → PrefactorCoreClient”](#static-create_clientconfig-prefactorcoreconfig--prefactorcoreclient) Create a PrefactorCoreClient configured for use with this adaptor. Use this when you need to manage the client and instance lifecycle yourself (e.g. to share a client between the session wrapper and other code) instead of letting [`from_config()`](#prefactor_livekit.session.PrefactorLiveKitSession.from_config) manage them for you. * **Parameters:** **config** – Core configuration for the client. * **Returns:** A PrefactorCoreClient ready for `await client.initialize()`. ### Example [Section titled “Example”](#example) config = PrefactorCoreConfig(http\_config=…) client = PrefactorLiveKitSession.create\_client(config) await client.initialize() instance = await client.create\_agent\_instance( : agent\_id=”my-agent”, agent\_version={“name”: “My Agent”}, agent\_schema\_version=…, ) session = PrefactorLiveKitSession(instance=instance) #### *async* ensure\_initialized() → [AgentInstanceHandle](../../core/reference/prefactor_core.managers.agent_instance.md#prefactor_core.managers.agent_instance.AgentInstanceHandle) [Section titled “async ensure\_initialized() → AgentInstanceHandle”](#async-ensure_initialized--agentinstancehandle) Initialize and return the active Prefactor instance. #### *classmethod* from\_config(api\_url: str, api\_token: str, agent\_id: str | None = None, agent\_name: str | None = None, schema\_registry: [SchemaRegistry](../../core/reference/prefactor_core.schema_registry.md#prefactor_core.schema_registry.SchemaRegistry) | None = None, include\_livekit\_schemas: bool = True, tool\_schemas: Mapping\[str, [LiveKitToolSchemaConfig](prefactor_livekit.schemas.md#prefactor_livekit.schemas.LiveKitToolSchemaConfig) | Mapping\[str, Any]] | None = None) → [PrefactorLiveKitSession](#prefactor_livekit.session.PrefactorLiveKitSession) [Section titled “classmethod from\_config(api\_url: str, api\_token: str, agent\_id: str | None = None, agent\_name: str | None = None, schema\_registry: SchemaRegistry | None = None, include\_livekit\_schemas: bool = True, tool\_schemas: Mapping\[str, LiveKitToolSchemaConfig | Mapping\[str, Any\]\] | None = None) → PrefactorLiveKitSession”](#classmethod-from_configapi_url-str-api_token-str-agent_id-str--none--none-agent_name-str--none--none-schema_registry-schemaregistry--none--none-include_livekit_schemas-bool--true-tool_schemas-mappingstr-livekittoolschemaconfig--mappingstr-any--none--none--prefactorlivekitsession) Create a wrapper from raw configuration. #### *async* start(session: AgentSession\[Any], agent: [Agent](../../http/reference/prefactor_http.models.md#prefactor_http.models.Agent), \*\*kwargs: Any) → Any [Section titled “async start(session: AgentSession\[Any\], agent: Agent, \*\*kwargs: Any) → Any”](#async-startsession-agentsessionany-agent-agent-kwargs-any--any) Attach and delegate to `AgentSession.start()`. # Prefactor SDK # Prefactor SDK [Section titled “Prefactor SDK”](#prefactor-sdk) Automatic observability for LangChain agents. Trace LLM calls, tool executions, and agent workflows with zero code changes. ## Installation [Section titled “Installation”](#installation) ```bash pip install prefactor-langchain ``` ## Quick Start [Section titled “Quick Start”](#quick-start) ```python import ast import asyncio import operator from langchain.agents import create_agent from langchain_core.tools import tool from prefactor_langchain import PrefactorMiddleware _OPS = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, } def _safe_eval(node): if isinstance(node, ast.Constant): return node.n if isinstance(node, ast.BinOp): return _OPS[type(node.op)](_safe_eval(node.left), _safe_eval(node.right)) if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub): return -_safe_eval(node.operand) raise ValueError(f"Unsupported: {node}") @tool def calculator(expression: str) -> str: """Evaluate a mathematical expression safely.""" try: return str(_safe_eval(ast.parse(expression, mode="eval").body)) except Exception as e: return f"Error: {e}" async def main(): middleware = PrefactorMiddleware.from_config( api_url="https://app.prefactorai.com", api_token="your-token", agent_id="my-agent", agent_name="My Agent", ) agent = create_agent( model="claude-haiku-4-5-20251001", tools=[calculator], middleware=[middleware], ) # All LLM calls and tool executions are automatically traced try: result = await agent.ainvoke( {"messages": [{"role": "user", "content": "What is 6 * 7?"}]} ) finally: await middleware.close() asyncio.run(main()) ``` ## Features [Section titled “Features”](#features) * Automatic tracing of LLM calls with token usage * Tool execution tracking * Agent workflow visualization * Parent-child span relationships * Error tracking and debugging * Zero-overhead instrumentation ## Development Setup [Section titled “Development Setup”](#development-setup) This project uses [mise](https://mise.jdx.dev) for reproducible development environments with the following tools: * **Python 3.11** with **uv** as the package manager * **ty** for blazing-fast type checking (10-100x faster than mypy/pyright) * **ruff** for linting and formatting (replaces Black, isort, Flake8, etc.) * **lefthook** for git pre-commit hooks ### Prerequisites [Section titled “Prerequisites”](#prerequisites) Install mise using one of these methods: ```bash # macOS (Homebrew) brew install mise # Linux/macOS (curl) curl https://mise.run | sh # Other methods: https://mise.jdx.dev/getting-started.html ``` After installation, activate mise in your shell: ```bash # For bash (add to ~/.bashrc) eval "$(mise activate bash)" # For zsh (add to ~/.zshrc) eval "$(mise activate zsh)" # For fish (add to ~/.config/fish/config.fish) mise activate fish | source ``` Alternatively, if you use [direnv](https://direnv.net/), mise will activate automatically when you enter the project directory. ### Getting Started [Section titled “Getting Started”](#getting-started) 1. Clone the repository: ```bash git clone https://github.com/prefactordev/python-sdk.git cd python-sdk ``` 2. Install project tools (Python, uv, ruff, etc.): ```bash mise install ``` 3. Set up the project (install dependencies and git hooks): ```bash mise run setup ``` This will: * Create a virtual environment at `.venv` * Install all dependencies via `uv sync --all-extras` * Install git pre-commit hooks via lefthook 4. You’re ready to develop! The virtual environment activates automatically when you enter the directory. ### Common Tasks [Section titled “Common Tasks”](#common-tasks) ```bash # Run tests mise run test # Run all quality checks (format, lint, typecheck) mise run check # Individual checks mise run format # Format code with ruff mise run lint # Lint code with ruff mise run typecheck # Type check with ty # Install/update dependencies mise run install ``` ### Running Tests [Section titled “Running Tests”](#running-tests) ```bash # Run all tests pytest # Run specific test file pytest packages/core/tests/test_client.py # Run with verbose output pytest -v # Run specific test pytest packages/core/tests/test_client.py::TestClient::test_initialize -v ``` ### Pre-commit Hooks [Section titled “Pre-commit Hooks”](#pre-commit-hooks) Git pre-commit hooks run automatically on each commit via lefthook: 1. `ruff format` - Format staged Python files 2. `ruff check --fix` - Lint and auto-fix staged Python files 3. `uvx ty check` - Type check the entire codebase To run hooks manually: ```bash lefthook run pre-commit ``` ### Versioning [Section titled “Versioning”](#versioning) Package versions are defined in each package’s `src//_version.py` file. That file is the single source of truth for both runtime `__version__` and build metadata. * `packages/http/src/prefactor_http/_version.py` * `packages/core/src/prefactor_core/_version.py` * `packages/langchain/src/prefactor_langchain/_version.py` * `packages/livekit/src/prefactor_livekit/_version.py` Each package `pyproject.toml` uses Hatch dynamic versioning and reads the version directly from that `_version.py` file. We do not resolve versions from installed metadata or parse `pyproject.toml` at import time. When bumping a package version: 1. Update `__version__` in that package’s `_version.py`. 2. Update any dependent package constraints if the new version requires it. 3. Run `mise run test` before committing. ### Project Structure [Section titled “Project Structure”](#project-structure) ```text python-sdk/ ├── packages/ │ ├── core/ # Core tracing and span lifecycle │ ├── http/ # HTTP client for the Prefactor API │ ├── langchain/ # LangChain instrumentation │ └── livekit/ # LiveKit instrumentation ├── mise.toml # mise configuration ├── lefthook.yml # Git hooks configuration └── pyproject.toml # Python project configuration (workspace root) ``` ### Tools Reference [Section titled “Tools Reference”](#tools-reference) | Tool | Purpose | Documentation | | ---------------------------------------------------- | ---------------------- | ------------------------------ | | [mise](https://mise.jdx.dev) | Tool version manager | Manages Python, uv, ruff, etc. | | [uv](https://github.com/astral-sh/uv) | Python package manager | Fast dependency resolution | | [ruff](https://github.com/astral-sh/ruff) | Linter and formatter | Replaces Black, isort, Flake8 | | [ty](https://github.com/astral-sh/ty) | Type checker | 10-100x faster than mypy | | [lefthook](https://github.com/evilmartians/lefthook) | Git hooks manager | Runs pre-commit checks | ### Claude Code Integration [Section titled “Claude Code Integration”](#claude-code-integration) If you use [Claude Code](https://claude.ai/code), hooks are configured in `.claude/settings.json`: * **PostToolUse**: Automatically formats and lints Python files after editing * **PreToolUse**: Runs type checking before git commits # Quality evaluations Attach quality evaluations to agent runs: declare the shape of your evaluation payload, mark evaluation runs as such, and submit the result after the run. The evaluation itself — an eval suite, a grading model, a human review — happens outside Prefactor; this page covers getting its output into the platform. Three pieces are involved. One or more named quality schemas in the agent schema each declare what an evaluation payload looks like and how to summarise it. An instance purpose (`live`, `smoke_test`, or `eval`) tells Prefactor why a run happened, so evaluation traffic is distinguishable from production. And a quality payload for a given schema name — recorded on the instance after the run — carries the evaluation result. When a named payload changes, Prefactor records the change as a quality span inside the instance, so the evaluation history is auditable; you never write those spans yourself. ## Declare quality schemas [Section titled “Declare quality schemas”](#declare-quality-schemas) Quality schemas are part of the agent schema, alongside the span type definitions described in [Schemas and result schemas](/sdks/concepts-schemas). In the SDK this is `agentSchema` / the agent schema object; in the platform it is the [activity schema](/platform/concepts/activity-schema). Each quality schema has a name — the key you pass when you later record a payload against it — plus a JSON Schema for the payload and, optionally, a title, description, and a `{{field}}` template that Prefactor uses to render a one-line summary in the web app. Templates are Liquid, rendered server-side — see [Summary templates](/api/summary-templates) for the full language. Register as many named quality schemas as your agent needs: a summary-quality schema and a policy-compliance schema for the same runs, for example. In TypeScript, add a `quality_schemas` array to the `agentSchema` object in `httpConfig`: ```typescript const agentSchema = { span_schemas: { // ... span type definitions ... }, quality_schemas: [ { name: 'summary_quality', schema: { type: 'object', properties: { overall_score: { type: 'number' }, verdict: { type: 'string' }, comments: { type: 'string' }, }, required: ['overall_score', 'verdict'], }, template: 'Scored {{overall_score}}/100 ({{verdict}}): {{comments}}', }, ], }; ``` In Python, register each one on the `SchemaRegistry` by name: ```python from prefactor_core.schema_registry import SchemaRegistry registry = SchemaRegistry() # ... registry.register(...) calls for span types ... registry.register_quality_schema( name="summary_quality", schema={ "type": "object", "properties": { "overall_score": {"type": "number"}, "verdict": {"type": "string"}, "comments": {"type": "string"}, }, "required": ["overall_score", "verdict"], }, template="Scored {{overall_score}}/100 ({{verdict}}): {{comments}}", ) ``` Call `register_quality_schema` again with a different `name` to declare a second quality schema; each name must be unique within the agent schema. ## Set the run’s purpose [Section titled “Set the run’s purpose”](#set-the-runs-purpose) Purpose is set when the instance is registered and defaults to `live` when omitted. In Python, pass it when creating the instance: ```python handle = await client.create_agent_instance( agent_version={"name": "My Agent"}, purpose="eval", ) ``` In TypeScript, `purpose` is an option on `startInstance` for code that drives the instance lifecycle directly through the core runtime: ```typescript import { createCore } from '@prefactor/core'; const core = createCore({ httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', agentSchema, }, }); core.agentManager.startInstance({ purpose: 'eval' }); ``` The provider integrations (LangChain, AI SDK, and the rest) start instances themselves and do not yet accept a purpose, so runs they register default to `live`. ## Record a quality payload [Section titled “Record a quality payload”](#record-a-quality-payload) Once your evaluation has produced a result, record it against the instance under the name of the quality schema it matches. Passing `None` (Python) or `null` (TypeScript) removes the recorded payload for that name; each change is recorded as a quality span. Other names on the same instance are left unchanged. In Python, from the instance handle or the client: ```python await handle.record_quality( name="summary_quality", payload={ "overall_score": 87, "verdict": "pass", "comments": "Accurate summary; minor tone drift.", }, ) # or, with just the instance id: await client.record_quality(instance_id, name="summary_quality", payload={...}) ``` In TypeScript, code that drives the instance lifecycle directly through the core runtime (the same `core` from [Set the run’s purpose](#set-the-runs-purpose)) can call the instance manager directly: ```typescript core.agentManager.recordQuality({ name: 'summary_quality', payload: { overall_score: 87, verdict: 'pass', comments: 'Accurate summary; minor tone drift.', }, }); ``` The `PrefactorClient` returned by `init()` (the entry point most integrations use) doesn’t expose `agentManager` directly. Evaluators usually run as a separate process after the fact anyway, so the common path — for `init()`-based integrations and for evaluators without SDK access at all — is the HTTP API: [POST /agent\_instance/{agent\_instance\_id}/record\_quality](/api/platform/operations/actionagentinstancerecordquality) with `name` and `payload`, using the instance ID from `prefactor.getAgentInstanceId()` and a deployment-scoped API token (deployment tokens are allowed to record quality for exactly this reason). `name` must match a quality schema name already declared on the instance’s agent schema version, and `payload` must be a JSON object (or `null` to remove that name). ## Worked example: two schemas on one agent [Section titled “Worked example: two schemas on one agent”](#worked-example-two-schemas-on-one-agent) A ticket-summarization agent is a good candidate for more than one quality schema: one schema scores how good the summary is, a second checks it didn’t surface anything it shouldn’t have. Here’s the whole path, from declaring both schemas to seeing two sections on the instance’s Quality tab. Register both quality schemas alongside the agent’s span types. This example uses the Python `SchemaRegistry`; the TypeScript `agentSchema.quality_schemas` array from [Declare quality schemas](#declare-quality-schemas) works the same way: ```python from prefactor_core.schema_registry import SchemaRegistry registry = SchemaRegistry() registry.register( "summarize_ticket", { "type": "object", "properties": {"ticket_id": {"type": "string"}}, "required": ["ticket_id"], }, ) registry.register_quality_schema( name="summary_quality", schema={ "type": "object", "properties": { "overall_score": {"type": "number", "minimum": 0, "maximum": 100}, "verdict": {"type": "string"}, }, "required": ["overall_score", "verdict"], }, template="Scored {{overall_score}}/100 ({{verdict}})", ) registry.register_quality_schema( name="policy_compliance", schema={ "type": "object", "properties": { "compliant": {"type": "boolean"}, "notes": {"type": "string"}, }, "required": ["compliant"], }, template="Compliant: {{compliant}} — {{notes}}", ) ``` `overall_score` is out of 100, so its schema adds `minimum` and `maximum` to enforce that range, rather than leaving it as an unconstrained `number`. Pass the registry into the client config and register the run. The agent’s own instrumentation records its spans as usual — see [Schemas and result schemas](/sdks/concepts-schemas) for that part — so it’s omitted here: ```python config = PrefactorCoreConfig( http_config=HttpClientConfig( api_url="https://app.prefactorai.com", api_token=os.environ["PREFACTOR_API_TOKEN"], ), schema_registry=registry, ) client = PrefactorCoreClient(config) await client.initialize() handle = await client.create_agent_instance( agent_version={"name": "Ticket summarizer"}, purpose="eval", ) # ... the agent runs, recording spans through its normal instrumentation ... await handle.finish() ``` Once the run finishes, an evaluator — an eval suite, a grading model, or a person — scores it against both schemas and records each payload by name. This can happen in the same process, or, as here, in a separate script that only has the instance ID: ```python await client.record_quality( handle.instance_id, name="summary_quality", payload={"overall_score": 88, "verdict": "pass"}, ) await client.record_quality( handle.instance_id, name="policy_compliance", payload={"compliant": True, "notes": "No customer PII in the summary."}, ) ``` Each call writes its own quality span on the instance, and the two names don’t interfere with each other. The instance’s [Quality tab](/admin-ui/agent-instance/quality) now shows a “Summary quality” section rendered as “Scored 88/100 (pass)”, and a separate “Policy compliance” section next to it. The same shape applies through TypeScript’s `recordQuality` or the HTTP API directly — see [Record a quality payload](#record-a-quality-payload) above. ## What you’ll see in the web app [Section titled “What you’ll see in the web app”](#what-youll-see-in-the-web-app) Each named quality schema with a recorded payload gets its own section on the [Agent › Instance › Quality tab](/admin-ui/agent-instance/quality), showing the rendered summary and the raw payload; the purpose is shown on the instance page and defaults to Live where your integration did not set one. A quality schema with no template shows the raw payload without a summary. ## Related [Section titled “Related”](#related) * [Quality and performance](/platform/quality-and-performance) — what quality evaluations are and how Prefactor records them. * [Schemas and result schemas](/sdks/concepts-schemas) — the agent schema that quality schemas live in. * [Instance](/platform/concepts/instance) — purpose, quality payloads, and the run-level record. # Getting started with the TypeScript SDK > Install the Prefactor TypeScript SDK and choose the package that matches your integration. The TypeScript SDK is split into a core runtime and integration packages. Start with the package that matches the app you are instrumenting. ## Links [Section titled “Links”](#links) * Source: [prefactordev/typescript-sdk](https://github.com/prefactordev/typescript-sdk) * DeepWiki: [prefactordev/typescript-sdk on DeepWiki](https://deepwiki.com/prefactordev/typescript-sdk) ## Choose a package [Section titled “Choose a package”](#choose-a-package) | Package | Use it when | Reference | | -------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | `@prefactor/core` | You want the core runtime, manual spans, or your own wrapper layer. | [Core API](/sdks/typescript-sdk/api/core) | | `@prefactor/langchain` | You are instrumenting LangChain applications. | [LangChain package](/sdks/typescript-sdk/api/packages/langchain) | | `@prefactor/ai` | You are instrumenting apps built on the Vercel AI SDK. | [AI package](/sdks/typescript-sdk/api/packages/ai) | | `@prefactor/claude` | You are instrumenting Claude-specific agent flows. | [Claude package](/sdks/typescript-sdk/api/packages/claude) | | `@prefactor/openclaw-prefactor-plugin` | You are integrating Prefactor into OpenClaw plugin workflows. | [OpenClaw plugin](/sdks/typescript-sdk/api/packages/openclaw-prefactor-plugin) | ## Installation [Section titled “Installation”](#installation) Install the package you need: ```bash npm install @prefactor/langchain ``` Or install a different package: ```bash npm install @prefactor/core npm install @prefactor/langchain npm install @prefactor/ai npm install @prefactor/claude npm install @prefactor/openclaw-prefactor-plugin ``` ## Quick start [Section titled “Quick start”](#quick-start) The SDK exposes three entry points. `init` from an integration package (such as `@prefactor/langchain`) returns middleware directly and is the right choice for most applications. `init` from `@prefactor/core` with a `provider` argument returns a `PrefactorClient` with access to `getMiddleware()`, `getTracer()`, and `shutdown()`. `createCore` from `@prefactor/core` is for manual instrumentation without a provider. Use the integration package `init` unless you need programmatic client access or custom spans. Most applications start with an integration package. This example uses the LangChain package: ```typescript import { init as initLangChain } from '@prefactor/langchain'; const middleware = initLangChain({ transportType: 'http', httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); ``` If you prefer the full options surface — providers, transports, and manual span control — use `init` from `@prefactor/core` directly. See the [API overview](/sdks/typescript-sdk/api/overview) for examples. If you want manual instrumentation or your own wrapper layer, start with `@prefactor/core`: ```typescript import { createCore } from '@prefactor/core'; const prefactor = createCore({ transportType: 'http', httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, }, }); ``` ## Next steps [Section titled “Next steps”](#next-steps) * [TypeScript SDK API overview](/sdks/typescript-sdk/api/overview) * [Core API](/sdks/typescript-sdk/api/core) * [LangChain package](/sdks/typescript-sdk/api/packages/langchain) * [AI package](/sdks/typescript-sdk/api/packages/ai) * [Claude package](/sdks/typescript-sdk/api/packages/claude) * [OpenClaw plugin](/sdks/typescript-sdk/api/packages/openclaw-prefactor-plugin) * [Schemas and result schemas](/sdks/concepts-schemas) * [Configuration and environment variables](/sdks/configuration) * [Handle instance termination](/sdks/handling-termination) * [Handle rate limiting](/sdks/handling-rate-limits) # Prefactor SDK for TypeScript **Prefactor TypeScript SDK** *** # Prefactor SDK for TypeScript [Section titled “Prefactor SDK for TypeScript”](#prefactor-sdk-for-typescript) Automatic observability for LangChain.js agents. Capture distributed traces of LLM calls, tool executions, and agent workflows with minimal integration effort. ## Links [Section titled “Links”](#links) * Docs: * DeepWiki: * GitHub: ## Features [Section titled “Features”](#features) * Automatic tracing of LLM calls with token usage * Tool execution tracking * Agent workflow visualization * Parent-child span relationships * Error tracking and debugging * Zero-overhead instrumentation * TypeScript type safety * HTTP transport with retry and queue controls ## Monorepo Structure [Section titled “Monorepo Structure”](#monorepo-structure) This repository is a Bun monorepo containing three packages: | Package | Description | | ------------------------------------------ | ------------------------------------------- | | [`@prefactor/core`](_media/core) | Framework-agnostic observability primitives | | [`@prefactor/langchain`](_media/langchain) | LangChain.js integration | | [`@prefactor/ai`](_media/ai) | Vercel AI SDK integration | Install `@prefactor/core` along with the adapter package for your framework. ## Installation [Section titled “Installation”](#installation) ### For LangChain.js users: [Section titled “For LangChain.js users:”](#for-langchainjs-users) ```bash npm install @prefactor/core @prefactor/langchain # or bun add @prefactor/core @prefactor/langchain ``` ### For Vercel AI SDK users: [Section titled “For Vercel AI SDK users:”](#for-vercel-ai-sdk-users) ```bash npm install @prefactor/core @prefactor/ai # or bun add @prefactor/core @prefactor/ai ``` ## Quick Start [Section titled “Quick Start”](#quick-start) ### For LangChain.js users: [Section titled “For LangChain.js users:”](#for-langchainjs-users-1) ```typescript import { createAgent, tool } from 'langchain'; import { z } from 'zod'; import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); // Create your agent with middleware const agent = createAgent({ model: 'claude-sonnet-4-5-20250929', tools: [], systemPrompt: 'You are a helpful assistant.', middleware: [prefactor.getMiddleware()], }); // All operations are automatically traced! const result = await agent.invoke({ messages: [{ role: 'user', content: 'What is 2+2?' }], }); console.log(result.messages[result.messages.length - 1].content); await prefactor.shutdown(); ``` Refer to the [Langchain specific documentation](_media/README.md) for more details. ### For Vercel AI SDK users: [Section titled “For Vercel AI SDK users:”](#for-vercel-ai-sdk-users-1) ```typescript import { init } from '@prefactor/core'; import { PrefactorAISDK } from '@prefactor/ai'; import { generateText, wrapLanguageModel } from 'ai'; import { anthropic } from '@ai-sdk/anthropic'; const prefactor = init({ provider: new PrefactorAISDK(), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); // Wrap your model with the middleware const model = wrapLanguageModel({ model: anthropic('claude-3-haiku-20240307'), middleware: prefactor.getMiddleware(), }); // All operations are automatically traced! const result = await generateText({ model, prompt: 'What is 2+2?', }); console.log(result.text); await prefactor.shutdown(); ``` Refer to the [Vercel AI SDK specific documentation](_media/README-1.md) for more details. ## Configuration [Section titled “Configuration”](#configuration) ### Environment Variables [Section titled “Environment Variables”](#environment-variables) The SDK can be configured using environment variables: * `PREFACTOR_API_URL`: API endpoint for HTTP transport * `PREFACTOR_API_TOKEN`: Authentication token for HTTP transport * `PREFACTOR_SAMPLE_RATE`: Sampling rate 0.0-1.0 (default: `1.0`) * `PREFACTOR_CAPTURE_INPUTS`: Capture span inputs (default: `true`) * `PREFACTOR_CAPTURE_OUTPUTS`: Capture span outputs (default: `true`) * `PREFACTOR_MAX_INPUT_LENGTH`: Max input string length (default: `10000`) * `PREFACTOR_MAX_OUTPUT_LENGTH`: Max output string length (default: `10000`) * `PREFACTOR_LOG_LEVEL`: `"debug"` | `"info"` | `"warn"` | `"error"` (default: `"info"`) ### Programmatic Configuration [Section titled “Programmatic Configuration”](#programmatic-configuration) ```typescript import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentId: 'my-agent', agentIdentifier: '1.0.0', }, }); // Custom sampling const prefactorWithSampling = init({ provider: new PrefactorLangChain(), sampleRate: 0.1, // Sample 10% of traces maxInputLength: 5000, maxOutputLength: 5000, httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); ``` ## Transports [Section titled “Transports”](#transports) ### HTTP Transport [Section titled “HTTP Transport”](#http-transport) The HTTP transport sends spans to a remote API endpoint with retry logic and queue-based processing. ```typescript import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentId: 'my-agent', agentIdentifier: '1.0.0', maxRetries: 3, requestTimeout: 30000, }, }); ``` ## API Reference [Section titled “API Reference”](#api-reference) ### `@prefactor/core` [Section titled “@prefactor/core”](#prefactorcore) #### `init(options: PrefactorOptions): PrefactorClient` [Section titled “init(options: PrefactorOptions): PrefactorClient”](#initoptions-prefactoroptions-prefactorclient) Initialize a process-wide Prefactor client and create provider middleware. **Parameters:** * `options.provider` - Provider implementation (for example `new PrefactorLangChain()`) * `options.httpConfig` - HTTP transport configuration **Returns:** * `PrefactorClient` with `getMiddleware()`, `getTracer()`, `withSpan()`, and `shutdown()` **Example:** ```typescript import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); ``` ### `@prefactor/ai` [Section titled “@prefactor/ai”](#prefactorai) #### `PrefactorAISDK` [Section titled “PrefactorAISDK”](#prefactoraisdk) Provider used with core `init` for Vercel AI SDK middleware. **Parameters:** * `options.middleware` - Optional middleware-specific config (e.g., `captureContent`) * `options.agentSchema` - Optional custom agent schema **Returns:** * Provider instance consumed by `@prefactor/core` `init` **Example:** ```typescript import { init } from '@prefactor/core'; import { PrefactorAISDK } from '@prefactor/ai'; const prefactor = init({ provider: new PrefactorAISDK({ middleware: { captureContent: false }, }), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); ``` ### `PrefactorClient.shutdown(): Promise` [Section titled “PrefactorClient.shutdown(): Promise\”](#prefactorclientshutdown-promisevoid) Flush pending spans and close connections. Call before application exit. **Example:** ```typescript import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, }, }); process.on('SIGTERM', async () => { await prefactor.shutdown(); process.exit(0); }); ``` ### `PrefactorClient.getTracer(): Tracer` [Section titled “PrefactorClient.getTracer(): Tracer”](#prefactorclientgettracer-tracer) Get the global tracer instance for manual instrumentation. **Returns:** * `Tracer` - Tracer instance **Example:** ```typescript import { init, SpanType } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, }, }); const tracer = prefactor.getTracer(); const span = tracer.startSpan({ name: 'custom-operation', spanType: SpanType.TOOL, inputs: { data: 'example' }, }); try { // ... do work ... tracer.endSpan(span, { outputs: { result: 'done' } }); } catch (error) { tracer.endSpan(span, { error }); } ``` ## Advanced Usage [Section titled “Advanced Usage”](#advanced-usage) ### Manual Instrumentation [Section titled “Manual Instrumentation”](#manual-instrumentation) For operations not automatically traced by the middleware: ```typescript import { getTracer, SpanType } from '@prefactor/langchain'; const tracer = getTracer(); const span = tracer.startSpan({ name: 'database-query', spanType: SpanType.TOOL, inputs: { query: 'SELECT * FROM users' }, metadata: { database: 'postgres' }, tags: ['database', 'query'], }); try { const result = await db.query('SELECT * FROM users'); tracer.endSpan(span, { outputs: { rowCount: result.rows.length } }); } catch (error) { tracer.endSpan(span, { error }); } ``` ### Context Propagation [Section titled “Context Propagation”](#context-propagation) The SDK automatically propagates span context through async operations using Node.js AsyncLocalStorage. Child spans automatically inherit the trace ID and parent span ID from the current context. ```typescript import { SpanContext } from '@prefactor/langchain'; // Get the current span (if any) const currentSpan = SpanContext.getCurrent(); // Child spans automatically use the current span as parent const child = tracer.startSpan({ name: 'child-operation', spanType: SpanType.TOOL, inputs: {}, parentSpanId: currentSpan?.spanId, traceId: currentSpan?.traceId, }); ``` ## TypeScript Support [Section titled “TypeScript Support”](#typescript-support) The SDK is written in TypeScript and provides full type definitions: ```typescript import type { Config, HttpTransportConfig, Span, SpanType, SpanStatus, TokenUsage, ErrorInfo } from '@prefactor/core'; const config: Config = { transportType: 'http', sampleRate: 1.0, captureInputs: true, captureOutputs: true, httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, }, }; ``` ## Examples [Section titled “Examples”](#examples) See the `examples/` directory for complete examples: * [`examples/langchain/simple-agent.ts`](_media/simple-agent.ts) - Full working example with LangChain * [`examples/langchain/termination-demo.ts`](_media/termination-demo.ts) - LangChain agent termination example * [`examples/ai-sdk/simple-agent.ts`](_media/simple-agent-1.ts) - Vercel AI SDK example with tools * [`examples/ai-sdk/custom-schema.ts`](_media/custom-schema.ts) - Vercel AI SDK example with a custom agent schema * [`examples/livekit/simple-session.ts`](_media/simple-session.ts) - LiveKit session example * [`examples/claude-agent/simple-agent.ts`](_media/simple-agent-2.ts) - Claude agent example ## Skills [Section titled “Skills”](#skills) This repo includes reusable skills for coding tools and AI agents. ### Install via skills CLI (recommended) [Section titled “Install via skills CLI (recommended)”](#install-via-skills-cli-recommended) ```bash # Install skills from this repository bunx skills add https://github.com/prefactordev/typescript-sdk/ ``` ### LLM instructions (Copy/Paste) [Section titled “LLM instructions (Copy/Paste)”](#llm-instructions-copypaste) Use this when a tool does not support direct skills installation yet: ```text Clone the skills repo to a temporary folder, copy the skill folders, then delete the clone. 1) git clone https://github.com/prefactordev/typescript-sdk /tmp/prefactor-skills 2) Copy the folders into your coding tool's local skills directory: - /tmp/prefactor-skills/skills 3) Delete the temporary clone: rm -rf /tmp/prefactor-skills ``` ## Architecture [Section titled “Architecture”](#architecture) The SDK consists of five main layers: 1. **Tracing Layer**: Span data models, Tracer for lifecycle management, Context propagation 2. **Transport Layer**: HTTP backend with resilient queueing for span emission 3. **Instrumentation Layer**: LangChain.js and Vercel AI SDK middleware integrations 4. **Configuration**: Environment variable support, validation with Zod 5. **Utilities**: Logging, serialization helpers ## Requirements [Section titled “Requirements”](#requirements) * Node.js >= 22.0.0 * TypeScript >= 5.0.0 (for TypeScript projects) * Bun >= 1.0.0 (optional, for development) * LangChain.js >= 1.0.0 (peer dependency for `@prefactor/langchain`) * AI SDK ^4.0.0 || ^5.0.0 || ^6.0.0 (peer dependency for `@prefactor/ai`) ## Development [Section titled “Development”](#development) This project uses Bun with mise for toolchain management. ```bash # Install toolchain mise install # Install dependencies (monorepo-wide) mise run install ``` ```bash # Build all packages mise run build # Run tests mise run test # Type check mise run typecheck # Lint mise run lint # Format mise run format # Run all checks (typecheck + lint + test) mise run check # Clean build artifacts mise run clean ``` ### Per-Package Commands [Section titled “Per-Package Commands”](#per-package-commands) ```bash # Build a specific package bun --filter @prefactor/core build # Run tests for a specific package bun test packages/core/tests/ ``` ## License [Section titled “License”](#license) MIT ## Support [Section titled “Support”](#support) * Documentation: * Issues: [GitHub Issues](https://github.com/prefactordev/typescript-sdk/issues) * Email: # @prefactor/ai [**Prefactor TypeScript SDK**](../index.md) *** [Prefactor TypeScript SDK](../modules.md) / @prefactor/ai # @prefactor/ai [Section titled “@prefactor/ai”](#prefactorai) Prefactor middleware integration for the Vercel AI SDK. ## `@prefactor/ai` overview [Section titled “@prefactor/ai overview”](#prefactorai-overview) `@prefactor/ai` connects Vercel AI SDK model calls to Prefactor tracing. It captures agent, model, and tool spans and sends them through your configured transport. Use this package as a provider for the core `init` function. ## Quick start [Section titled “Quick start”](#quick-start) ```ts import { init } from '@prefactor/core'; import { PrefactorAISDK } from '@prefactor/ai'; import { generateText, wrapLanguageModel } from 'ai'; import { anthropic } from '@ai-sdk/anthropic'; const prefactor = init({ provider: new PrefactorAISDK(), httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: 'chat-app-v1', }, }); const model = wrapLanguageModel({ model: anthropic('claude-3-haiku-20240307'), middleware: prefactor.getMiddleware(), }); const result = await generateText({ model, prompt: 'Hello!', }); await prefactor.shutdown(); ``` ## Functions [Section titled “Functions”](#functions) * [getTracer](functions/getTracer.md) * [init](functions/init.md) * [withSpan](functions/withSpan.md) ## Classes [Section titled “Classes”](#classes) * [PrefactorAISDK](classes/PrefactorAISDK.md) ## Interfaces [Section titled “Interfaces”](#interfaces) * [PrefactorAISDKOptions](interfaces/PrefactorAISDKOptions.md) * [MiddlewareConfig](interfaces/MiddlewareConfig.md) ## Type Aliases [Section titled “Type Aliases”](#type-aliases) * [ManualSpanOptions](type-aliases/ManualSpanOptions.md) ## Variables [Section titled “Variables”](#variables) * [DEFAULT\_AI\_AGENT\_SCHEMA](variables/DEFAULT_AI_AGENT_SCHEMA.md) # Class: PrefactorAISDK [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/ai](../index.md) / PrefactorAISDK # Class: PrefactorAISDK [Section titled “Class: PrefactorAISDK”](#class-prefactoraisdk) Defined in: [packages/ai/src/provider.ts:18](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L18) ## Implements [Section titled “Implements”](#implements) * `PrefactorProvider`<`LanguageModelMiddleware`> ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new PrefactorAISDK**(`options?`): `PrefactorAISDK` Defined in: [packages/ai/src/provider.ts:24](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L24) #### Parameters [Section titled “Parameters”](#parameters) ##### options? [Section titled “options?”](#options) [`PrefactorAISDKOptions`](../interfaces/PrefactorAISDKOptions.md) = `{}` #### Returns [Section titled “Returns”](#returns) `PrefactorAISDK` ## Methods [Section titled “Methods”](#methods) ### createMiddleware() [Section titled “createMiddleware()”](#createmiddleware) > **createMiddleware**(`tracer`, `agentManager`, `coreConfig`, `_getAbortSignal?`): `LanguageModelV3Middleware` Defined in: [packages/ai/src/provider.ts:28](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L28) Creates provider middleware bound to the core runtime services. #### Parameters [Section titled “Parameters”](#parameters-1) ##### tracer [Section titled “tracer”](#tracer) `Tracer` Runtime tracer used for span creation. ##### agentManager [Section titled “agentManager”](#agentmanager) `AgentInstanceManager` Runtime agent instance manager. ##### coreConfig [Section titled “coreConfig”](#coreconfig) ##### \_getAbortSignal? [Section titled “\_getAbortSignal?”](#_getabortsignal) () => `AbortSignal` #### Returns [Section titled “Returns”](#returns-1) `LanguageModelV3Middleware` Provider middleware consumed by upstream frameworks. #### Implementation of [Section titled “Implementation of”](#implementation-of) `PrefactorProvider.createMiddleware` *** ### shutdown() [Section titled “shutdown()”](#shutdown) > **shutdown**(): `void` Defined in: [packages/ai/src/provider.ts:57](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L57) Optional provider-level cleanup hook invoked during client shutdown. #### Returns [Section titled “Returns”](#returns-2) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-1) `PrefactorProvider.shutdown` *** ### getSdkHeaderEntry() [Section titled “getSdkHeaderEntry()”](#getsdkheaderentry) > **getSdkHeaderEntry**(): `string` Defined in: [packages/ai/src/provider.ts:67](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L67) Returns the SDK header entry to append to HTTP requests created by the core runtime. #### Returns [Section titled “Returns”](#returns-3) `string` Adapter-specific SDK identifier, or `undefined` to use the core header only. #### Implementation of [Section titled “Implementation of”](#implementation-of-2) `PrefactorProvider.getSdkHeaderEntry` *** ### normalizeAgentSchema() [Section titled “normalizeAgentSchema()”](#normalizeagentschema) > **normalizeAgentSchema**(`agentSchema`): `Record`<`string`, `unknown`> Defined in: [packages/ai/src/provider.ts:71](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L71) Normalizes a user- or provider-authored agent schema before core registers it. #### Parameters [Section titled “Parameters”](#parameters-2) ##### agentSchema [Section titled “agentSchema”](#agentschema) `Record`<`string`, `unknown`> Authored agent schema configuration. #### Returns [Section titled “Returns”](#returns-4) `Record`<`string`, `unknown`> Normalized schema, or `undefined` to leave the input unchanged. #### Implementation of [Section titled “Implementation of”](#implementation-of-3) `PrefactorProvider.normalizeAgentSchema` *** ### getDefaultAgentSchema() [Section titled “getDefaultAgentSchema()”](#getdefaultagentschema) > **getDefaultAgentSchema**(): `Record`<`string`, `unknown`> | `undefined` Defined in: [packages/ai/src/provider.ts:77](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L77) Provides a default agent schema when a user does not supply one. #### Returns [Section titled “Returns”](#returns-5) `Record`<`string`, `unknown`> | `undefined` Agent schema object, or `undefined` when no default is available. #### Implementation of [Section titled “Implementation of”](#implementation-of-4) `PrefactorProvider.getDefaultAgentSchema` # Function: getTracer() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/ai](../index.md) / getTracer # Function: getTracer() [Section titled “Function: getTracer()”](#function-gettracer) > **getTracer**(): `Tracer` Defined in: [packages/ai/src/init.ts:198](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L198) Get the current tracer instance. If no tracer has been created yet, this will call init() with default configuration. ## Returns [Section titled “Returns”](#returns) `Tracer` Tracer instance ## Example [Section titled “Example”](#example) ```typescript import { getTracer } from '@prefactor/ai'; const tracer = getTracer(); // Use for custom span creation const span = tracer.startSpan({ name: 'custom-operation', spanType: SpanType.CHAIN, }); ``` # Function: init() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/ai](../index.md) / init # Function: init() [Section titled “Function: init()”](#function-init) > **init**(`config?`, `middlewareConfig?`): `LanguageModelV3Middleware` Defined in: [packages/ai/src/init.ts:133](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L133) Initialize the Prefactor AI middleware and return it for use with wrapLanguageModel. This is the main entry point for the SDK. Call this function to create a middleware instance that you can pass to the Vercel AI SDK’s wrapLanguageModel function. ## Parameters [Section titled “Parameters”](#parameters) ### config? [Section titled “config?”](#config) `Partial`<{ }> Optional configuration object for transport settings ### middlewareConfig? [Section titled “middlewareConfig?”](#middlewareconfig) [`MiddlewareConfig`](../interfaces/MiddlewareConfig.md) Optional middleware-specific configuration ## Returns [Section titled “Returns”](#returns) `LanguageModelV3Middleware` Middleware object to use with wrapLanguageModel ## Examples [Section titled “Examples”](#examples) ```typescript import { init, shutdown } from '@prefactor/ai'; import { generateText, wrapLanguageModel } from 'ai'; import { anthropic } from '@ai-sdk/anthropic'; // Initialize with HTTP transport config const middleware = init({ transportType: 'http', httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); // Wrap your model with the middleware const model = wrapLanguageModel({ model: anthropic('claude-3-haiku-20240307'), middleware, }); const result = await generateText({ model, prompt: 'Hello!', }); await shutdown(); ``` ```typescript const middleware = init({ transportType: 'http', httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentId: process.env.PREFACTOR_AGENT_ID, agentIdentifier: '1.0.0', }, }); ``` ```typescript const middleware = init( { transportType: 'http', httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }, { captureContent: false } // Don't capture prompts/responses ); ``` # Function: withSpan() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/ai](../index.md) / withSpan # Function: withSpan() [Section titled “Function: withSpan()”](#function-withspan) > **withSpan**<`T`>(`options`, `fn`): `Promise`<`T`> Defined in: [packages/ai/src/init.ts:213](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L213) Wraps a function in a manual span using the shared core helper. ## Type Parameters [Section titled “Type Parameters”](#type-parameters) ### T [Section titled “T”](#t) `T` ## Parameters [Section titled “Parameters”](#parameters) ### options [Section titled “options”](#options) [`ManualSpanOptions`](../type-aliases/ManualSpanOptions.md) Manual span options. ### fn [Section titled “fn”](#fn) () => `T` | `Promise`<`T`> Function to execute in span context. ## Returns [Section titled “Returns”](#returns) `Promise`<`T`> Result from `fn`. # Interface: MiddlewareConfig [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/ai](../index.md) / MiddlewareConfig # Interface: MiddlewareConfig [Section titled “Interface: MiddlewareConfig”](#interface-middlewareconfig) Defined in: [packages/ai/src/types.ts:16](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/types.ts#L16) Configuration options for the Prefactor middleware. ## Properties [Section titled “Properties”](#properties) ### captureContent? [Section titled “captureContent?”](#capturecontent) > `optional` **captureContent**: `boolean` Defined in: [packages/ai/src/types.ts:22](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/types.ts#L22) Whether to capture prompt and response content in span inputs/outputs. Set to false to reduce data volume or for privacy reasons. #### Default [Section titled “Default”](#default) ```ts true ``` *** ### captureTools? [Section titled “captureTools?”](#capturetools) > `optional` **captureTools**: `boolean` Defined in: [packages/ai/src/types.ts:28](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/types.ts#L28) Whether to capture tool call information. #### Default [Section titled “Default”](#default-1) ```ts true ``` # Interface: PrefactorAISDKOptions [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/ai](../index.md) / PrefactorAISDKOptions # Interface: PrefactorAISDKOptions [Section titled “Interface: PrefactorAISDKOptions”](#interface-prefactoraisdkoptions) Defined in: [packages/ai/src/provider.ts:13](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L13) ## Properties [Section titled “Properties”](#properties) ### middleware? [Section titled “middleware?”](#middleware) > `optional` **middleware**: [`MiddlewareConfig`](MiddlewareConfig.md) Defined in: [packages/ai/src/provider.ts:14](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L14) *** ### agentSchema? [Section titled “agentSchema?”](#agentschema) > `optional` **agentSchema**: `Record`<`string`, `unknown`> Defined in: [packages/ai/src/provider.ts:15](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L15) # Type Alias: ManualSpanOptions [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/ai](../index.md) / ManualSpanOptions # Type Alias: ManualSpanOptions [Section titled “Type Alias: ManualSpanOptions”](#type-alias-manualspanoptions) > **ManualSpanOptions** = `object` Defined in: [packages/ai/src/init.ts:54](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L54) ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/ai/src/init.ts:56](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L56) Span name shown in traces. *** ### spanType [Section titled “spanType”](#spantype) > **spanType**: `string` Defined in: [packages/ai/src/init.ts:58](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L58) Provider-prefixed span type (for example `ai-sdk:llm`). *** ### inputs [Section titled “inputs”](#inputs) > **inputs**: `Record`<`string`, `unknown`> Defined in: [packages/ai/src/init.ts:60](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L60) Inputs recorded for the wrapped work. *** ### metadata? [Section titled “metadata?”](#metadata) > `optional` **metadata**: `Record`<`string`, `unknown`> Defined in: [packages/ai/src/init.ts:62](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L62) Optional additional metadata to attach to the span. # Variable: DEFAULT\_AI\_AGENT\_SCHEMA [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/ai](../index.md) / DEFAULT\_AI\_AGENT\_SCHEMA # Variable: DEFAULT\_AI\_AGENT\_SCHEMA [Section titled “Variable: DEFAULT\_AI\_AGENT\_SCHEMA”](#variable-default_ai_agent_schema) > `const` **DEFAULT\_AI\_AGENT\_SCHEMA**: `object` = `DEFAULT_AI_AGENT_SCHEMA_BASE` Defined in: [packages/ai/src/provider.ts:10](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L10) ## Type Declaration [Section titled “Type Declaration”](#type-declaration) ### external\_identifier [Section titled “external\_identifier”](#external_identifier) > `readonly` **external\_identifier**: `"ai-sdk-schema"` = `'ai-sdk-schema'` ### span\_schemas [Section titled “span\_schemas”](#span_schemas) > `readonly` **span\_schemas**: `object` #### span\_schemas.ai-sdk:agent [Section titled “span\_schemas.ai-sdk:agent”](#span_schemasai-sdkagent) > `readonly` **ai-sdk:agent**: `object` #### span\_schemas.ai-sdk:agent.type [Section titled “span\_schemas.ai-sdk:agent.type”](#span_schemasai-sdkagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.ai-sdk:agent.additionalProperties [Section titled “span\_schemas.ai-sdk:agent.additionalProperties”](#span_schemasai-sdkagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.ai-sdk:llm [Section titled “span\_schemas.ai-sdk:llm”](#span_schemasai-sdkllm) > `readonly` **ai-sdk:llm**: `object` #### span\_schemas.ai-sdk:llm.type [Section titled “span\_schemas.ai-sdk:llm.type”](#span_schemasai-sdkllmtype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.ai-sdk:llm.additionalProperties [Section titled “span\_schemas.ai-sdk:llm.additionalProperties”](#span_schemasai-sdkllmadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.ai-sdk:tool [Section titled “span\_schemas.ai-sdk:tool”](#span_schemasai-sdktool) > `readonly` **ai-sdk:tool**: `object` #### span\_schemas.ai-sdk:tool.type [Section titled “span\_schemas.ai-sdk:tool.type”](#span_schemasai-sdktooltype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.ai-sdk:tool.additionalProperties [Section titled “span\_schemas.ai-sdk:tool.additionalProperties”](#span_schemasai-sdktooladditionalproperties) > `readonly` **additionalProperties**: `true` = `true` ### span\_result\_schemas [Section titled “span\_result\_schemas”](#span_result_schemas) > `readonly` **span\_result\_schemas**: `object` #### span\_result\_schemas.ai-sdk:agent [Section titled “span\_result\_schemas.ai-sdk:agent”](#span_result_schemasai-sdkagent) > `readonly` **ai-sdk:agent**: `object` #### span\_result\_schemas.ai-sdk:agent.type [Section titled “span\_result\_schemas.ai-sdk:agent.type”](#span_result_schemasai-sdkagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.ai-sdk:agent.additionalProperties [Section titled “span\_result\_schemas.ai-sdk:agent.additionalProperties”](#span_result_schemasai-sdkagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.ai-sdk:llm [Section titled “span\_result\_schemas.ai-sdk:llm”](#span_result_schemasai-sdkllm) > `readonly` **ai-sdk:llm**: `object` #### span\_result\_schemas.ai-sdk:llm.type [Section titled “span\_result\_schemas.ai-sdk:llm.type”](#span_result_schemasai-sdkllmtype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.ai-sdk:llm.additionalProperties [Section titled “span\_result\_schemas.ai-sdk:llm.additionalProperties”](#span_result_schemasai-sdkllmadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.ai-sdk:tool [Section titled “span\_result\_schemas.ai-sdk:tool”](#span_result_schemasai-sdktool) > `readonly` **ai-sdk:tool**: `object` #### span\_result\_schemas.ai-sdk:tool.type [Section titled “span\_result\_schemas.ai-sdk:tool.type”](#span_result_schemasai-sdktooltype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.ai-sdk:tool.additionalProperties [Section titled “span\_result\_schemas.ai-sdk:tool.additionalProperties”](#span_result_schemasai-sdktooladditionalproperties) > `readonly` **additionalProperties**: `true` = `true` # @prefactor/claude [**Prefactor TypeScript SDK**](../index.md) *** [Prefactor TypeScript SDK](../modules.md) / @prefactor/claude # @prefactor/claude [Section titled “@prefactor/claude”](#prefactorclaude) Claude Agent SDK integration for Prefactor observability. Provides automatic tracing of Claude agent runs, LLM calls, tool executions, and subagent workflows via a traced `query` wrapper. ## `@prefactor/claude` overview [Section titled “@prefactor/claude overview”](#prefactorclaude-overview) `@prefactor/claude` connects Claude Agent SDK sessions to Prefactor tracing. It captures agent, LLM, tool, and subagent spans and sends them through your configured transport. Use this package as a provider for the core `init` function. ## Installation [Section titled “Installation”](#installation) ```bash npm install @prefactor/claude # or bun add @prefactor/claude ``` **Note:** This package requires `@prefactor/core` and `@anthropic-ai/claude-agent-sdk` as peer dependencies: ```bash npm install @prefactor/core @anthropic-ai/claude-agent-sdk # or bun add @prefactor/core @anthropic-ai/claude-agent-sdk ``` ## Quick Start [Section titled “Quick Start”](#quick-start) ```ts import { query } from '@anthropic-ai/claude-agent-sdk'; import { init } from '@prefactor/core'; import { PrefactorClaude } from '@prefactor/claude'; const prefactor = init({ provider: new PrefactorClaude({ query }), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: 'v1.0.0', }, }); const { tracedQuery } = prefactor.getMiddleware(); for await (const message of tracedQuery({ prompt: 'Explain this codebase', options: { allowedTools: ['Read', 'Glob', 'Grep'], }, })) { if ('result' in message) { console.log(message.result); } } await prefactor.shutdown(); ``` ## Exports [Section titled “Exports”](#exports) ### Provider [Section titled “Provider”](#provider) ```ts import { PrefactorClaude, DEFAULT_CLAUDE_AGENT_SCHEMA, } from '@prefactor/claude'; ``` ### Types [Section titled “Types”](#types) ```ts import type { ClaudeMiddleware, ClaudeQuery, JsonSchema, PrefactorClaudeOptions, ToolSchemaConfig, } from '@prefactor/claude'; ``` Core initialization and lifecycle utilities come from `@prefactor/core`: ```ts import { init, type PrefactorOptions, } from '@prefactor/core'; ``` ## Configuration [Section titled “Configuration”](#configuration) ### Environment Variables [Section titled “Environment Variables”](#environment-variables) The SDK can be configured using environment variables: * `PREFACTOR_API_URL`: API endpoint for HTTP transport * `PREFACTOR_API_TOKEN`: Authentication token for HTTP transport * `PREFACTOR_AGENT_ID`: Optional agent instance identifier * `PREFACTOR_SAMPLE_RATE`: Sampling rate 0.0-1.0 (default: `1.0`) * `PREFACTOR_CAPTURE_INPUTS`: Capture span inputs (default: `true`) * `PREFACTOR_CAPTURE_OUTPUTS`: Capture span outputs (default: `true`) * `PREFACTOR_MAX_INPUT_LENGTH`: Max input string length (default: `10000`) * `PREFACTOR_MAX_OUTPUT_LENGTH`: Max output string length (default: `10000`) * `PREFACTOR_LOG_LEVEL`: `"debug"` | `"info"` | `"warn"` | `"error"` (default: `"info"`) ### Programmatic Configuration [Section titled “Programmatic Configuration”](#programmatic-configuration) ```ts import { query } from '@anthropic-ai/claude-agent-sdk'; import { init } from '@prefactor/core'; import { PrefactorClaude, DEFAULT_CLAUDE_AGENT_SCHEMA } from '@prefactor/claude'; const prefactor = init({ provider: new PrefactorClaude({ query }), httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentId: 'my-agent', agentIdentifier: '1.0.0', agentName: 'My Claude Agent', agentDescription: 'A Claude-powered coding agent', agentSchema: { ...DEFAULT_CLAUDE_AGENT_SCHEMA, toolSchemas: { Read: { spanType: 'claude:tool:read', inputSchema: { type: 'object', properties: { file_path: { type: 'string' }, }, }, }, }, }, }, }); ``` Custom agent schemas should be passed through `httpConfig.agentSchema`, not the provider constructor. ## What Gets Traced [Section titled “What Gets Traced”](#what-gets-traced) The Claude integration automatically captures: * **Agent Runs**: Top-level agent spans for each traced query * **LLM Calls**: Model events, prompts, outputs, and usage when available * **Tool Executions**: Tool name, inputs, outputs, duration, and tool-specific span types * **Subagent Operations**: Child spans for nested Claude agent activity * **Errors**: Stream and execution failures with error details ## Requirements [Section titled “Requirements”](#requirements) * Node.js >= 22.0.0 * `@anthropic-ai/claude-agent-sdk` ^0.2.0 ## Classes [Section titled “Classes”](#classes) * [PrefactorClaude](classes/PrefactorClaude.md) ## Interfaces [Section titled “Interfaces”](#interfaces) * [PrefactorClaudeOptions](interfaces/PrefactorClaudeOptions.md) * [ClaudeMiddleware](interfaces/ClaudeMiddleware.md) ## Type Aliases [Section titled “Type Aliases”](#type-aliases) * [ClaudeQuery](type-aliases/ClaudeQuery.md) ## Variables [Section titled “Variables”](#variables) * [DEFAULT\_CLAUDE\_AGENT\_SCHEMA](variables/DEFAULT_CLAUDE_AGENT_SCHEMA.md) # Class: PrefactorClaude [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/claude](../index.md) / PrefactorClaude # Class: PrefactorClaude [Section titled “Class: PrefactorClaude”](#class-prefactorclaude) Defined in: [packages/claude/src/provider.ts:29](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L29) ## Implements [Section titled “Implements”](#implements) * `PrefactorProvider`<[`ClaudeMiddleware`](../interfaces/ClaudeMiddleware.md)> ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new PrefactorClaude**(`options`): `PrefactorClaude` Defined in: [packages/claude/src/provider.ts:35](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L35) #### Parameters [Section titled “Parameters”](#parameters) ##### options [Section titled “options”](#options) [`PrefactorClaudeOptions`](../interfaces/PrefactorClaudeOptions.md) #### Returns [Section titled “Returns”](#returns) `PrefactorClaude` ## Methods [Section titled “Methods”](#methods) ### createMiddleware() [Section titled “createMiddleware()”](#createmiddleware) > **createMiddleware**(`tracer`, `agentManager`, `coreConfig`, `_getAbortSignal?`): [`ClaudeMiddleware`](../interfaces/ClaudeMiddleware.md) Defined in: [packages/claude/src/provider.ts:39](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L39) Creates provider middleware bound to the core runtime services. #### Parameters [Section titled “Parameters”](#parameters-1) ##### tracer [Section titled “tracer”](#tracer) `Tracer` Runtime tracer used for span creation. ##### agentManager [Section titled “agentManager”](#agentmanager) `AgentInstanceManager` Runtime agent instance manager. ##### coreConfig [Section titled “coreConfig”](#coreconfig) ##### \_getAbortSignal? [Section titled “\_getAbortSignal?”](#_getabortsignal) () => `AbortSignal` #### Returns [Section titled “Returns”](#returns-1) [`ClaudeMiddleware`](../interfaces/ClaudeMiddleware.md) Provider middleware consumed by upstream frameworks. #### Implementation of [Section titled “Implementation of”](#implementation-of) `PrefactorProvider.createMiddleware` *** ### shutdown() [Section titled “shutdown()”](#shutdown) > **shutdown**(): `void` Defined in: [packages/claude/src/provider.ts:59](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L59) Optional provider-level cleanup hook invoked during client shutdown. #### Returns [Section titled “Returns”](#returns-2) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-1) `PrefactorProvider.shutdown` *** ### normalizeAgentSchema() [Section titled “normalizeAgentSchema()”](#normalizeagentschema) > **normalizeAgentSchema**(`agentSchema`): `Record`<`string`, `unknown`> Defined in: [packages/claude/src/provider.ts:70](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L70) Normalizes a user- or provider-authored agent schema before core registers it. #### Parameters [Section titled “Parameters”](#parameters-2) ##### agentSchema [Section titled “agentSchema”](#agentschema) `Record`<`string`, `unknown`> Authored agent schema configuration. #### Returns [Section titled “Returns”](#returns-3) `Record`<`string`, `unknown`> Normalized schema, or `undefined` to leave the input unchanged. #### Implementation of [Section titled “Implementation of”](#implementation-of-2) `PrefactorProvider.normalizeAgentSchema` *** ### getDefaultAgentSchema() [Section titled “getDefaultAgentSchema()”](#getdefaultagentschema) > **getDefaultAgentSchema**(): `Record`<`string`, `unknown`> | `undefined` Defined in: [packages/claude/src/provider.ts:76](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L76) Provides a default agent schema when a user does not supply one. #### Returns [Section titled “Returns”](#returns-4) `Record`<`string`, `unknown`> | `undefined` Agent schema object, or `undefined` when no default is available. #### Implementation of [Section titled “Implementation of”](#implementation-of-3) `PrefactorProvider.getDefaultAgentSchema` *** ### getSdkHeaderEntry() [Section titled “getSdkHeaderEntry()”](#getsdkheaderentry) > **getSdkHeaderEntry**(): `string` Defined in: [packages/claude/src/provider.ts:80](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L80) Returns the SDK header entry to append to HTTP requests created by the core runtime. #### Returns [Section titled “Returns”](#returns-5) `string` Adapter-specific SDK identifier, or `undefined` to use the core header only. #### Implementation of [Section titled “Implementation of”](#implementation-of-4) `PrefactorProvider.getSdkHeaderEntry` # Interface: ClaudeMiddleware [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/claude](../index.md) / ClaudeMiddleware # Interface: ClaudeMiddleware [Section titled “Interface: ClaudeMiddleware”](#interface-claudemiddleware) Defined in: [packages/claude/src/types.ts:15](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/types.ts#L15) Middleware returned by PrefactorClaude.createMiddleware(). ## Properties [Section titled “Properties”](#properties) ### tracedQuery() [Section titled “tracedQuery()”](#tracedquery) > **tracedQuery**: (…`args`) => `Query` Defined in: [packages/claude/src/types.ts:16](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/types.ts#L16) #### Parameters [Section titled “Parameters”](#parameters) ##### args [Section titled “args”](#args) …\[`object`] #### Returns [Section titled “Returns”](#returns) `Query` # Interface: PrefactorClaudeOptions [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/claude](../index.md) / PrefactorClaudeOptions # Interface: PrefactorClaudeOptions [Section titled “Interface: PrefactorClaudeOptions”](#interface-prefactorclaudeoptions) Defined in: [packages/claude/src/provider.ts:25](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L25) ## Properties [Section titled “Properties”](#properties) ### query() [Section titled “query()”](#query) > **query**: (`_params`) => `Query` Defined in: [packages/claude/src/provider.ts:26](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L26) #### Parameters [Section titled “Parameters”](#parameters) ##### \_params [Section titled “\_params”](#_params) ###### prompt [Section titled “prompt”](#prompt) `string` | `AsyncIterable`<`SDKUserMessage`, `any`, `any`> ###### options? [Section titled “options?”](#options) `Options` #### Returns [Section titled “Returns”](#returns) `Query` # Type Alias: ClaudeQuery [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/claude](../index.md) / ClaudeQuery # Type Alias: ClaudeQuery [Section titled “Type Alias: ClaudeQuery”](#type-alias-claudequery) > **ClaudeQuery** = `query` Defined in: [packages/claude/src/types.ts:10](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/types.ts#L10) # Variable: DEFAULT\_CLAUDE\_AGENT\_SCHEMA [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/claude](../index.md) / DEFAULT\_CLAUDE\_AGENT\_SCHEMA # Variable: DEFAULT\_CLAUDE\_AGENT\_SCHEMA [Section titled “Variable: DEFAULT\_CLAUDE\_AGENT\_SCHEMA”](#variable-default_claude_agent_schema) > `const` **DEFAULT\_CLAUDE\_AGENT\_SCHEMA**: `object` = `DEFAULT_CLAUDE_AGENT_SCHEMA_BASE` Defined in: [packages/claude/src/provider.ts:21](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L21) ## Type Declaration [Section titled “Type Declaration”](#type-declaration) ### external\_identifier [Section titled “external\_identifier”](#external_identifier) > `readonly` **external\_identifier**: `"claude-schema"` = `'claude-schema'` ### span\_schemas [Section titled “span\_schemas”](#span_schemas) > `readonly` **span\_schemas**: `object` #### span\_schemas.claude:agent [Section titled “span\_schemas.claude:agent”](#span_schemasclaudeagent) > `readonly` **claude:agent**: `object` #### span\_schemas.claude:agent.type [Section titled “span\_schemas.claude:agent.type”](#span_schemasclaudeagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.claude:agent.additionalProperties [Section titled “span\_schemas.claude:agent.additionalProperties”](#span_schemasclaudeagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.claude:llm [Section titled “span\_schemas.claude:llm”](#span_schemasclaudellm) > `readonly` **claude:llm**: `object` #### span\_schemas.claude:llm.type [Section titled “span\_schemas.claude:llm.type”](#span_schemasclaudellmtype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.claude:llm.additionalProperties [Section titled “span\_schemas.claude:llm.additionalProperties”](#span_schemasclaudellmadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.claude:tool [Section titled “span\_schemas.claude:tool”](#span_schemasclaudetool) > `readonly` **claude:tool**: `object` #### span\_schemas.claude:tool.type [Section titled “span\_schemas.claude:tool.type”](#span_schemasclaudetooltype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.claude:tool.additionalProperties [Section titled “span\_schemas.claude:tool.additionalProperties”](#span_schemasclaudetooladditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.claude:subagent [Section titled “span\_schemas.claude:subagent”](#span_schemasclaudesubagent) > `readonly` **claude:subagent**: `object` #### span\_schemas.claude:subagent.type [Section titled “span\_schemas.claude:subagent.type”](#span_schemasclaudesubagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.claude:subagent.additionalProperties [Section titled “span\_schemas.claude:subagent.additionalProperties”](#span_schemasclaudesubagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` ### span\_result\_schemas [Section titled “span\_result\_schemas”](#span_result_schemas) > `readonly` **span\_result\_schemas**: `object` #### span\_result\_schemas.claude:agent [Section titled “span\_result\_schemas.claude:agent”](#span_result_schemasclaudeagent) > `readonly` **claude:agent**: `object` #### span\_result\_schemas.claude:agent.type [Section titled “span\_result\_schemas.claude:agent.type”](#span_result_schemasclaudeagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.claude:agent.additionalProperties [Section titled “span\_result\_schemas.claude:agent.additionalProperties”](#span_result_schemasclaudeagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.claude:llm [Section titled “span\_result\_schemas.claude:llm”](#span_result_schemasclaudellm) > `readonly` **claude:llm**: `object` #### span\_result\_schemas.claude:llm.type [Section titled “span\_result\_schemas.claude:llm.type”](#span_result_schemasclaudellmtype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.claude:llm.additionalProperties [Section titled “span\_result\_schemas.claude:llm.additionalProperties”](#span_result_schemasclaudellmadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.claude:tool [Section titled “span\_result\_schemas.claude:tool”](#span_result_schemasclaudetool) > `readonly` **claude:tool**: `object` #### span\_result\_schemas.claude:tool.type [Section titled “span\_result\_schemas.claude:tool.type”](#span_result_schemasclaudetooltype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.claude:tool.additionalProperties [Section titled “span\_result\_schemas.claude:tool.additionalProperties”](#span_result_schemasclaudetooladditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.claude:subagent [Section titled “span\_result\_schemas.claude:subagent”](#span_result_schemasclaudesubagent) > `readonly` **claude:subagent**: `object` #### span\_result\_schemas.claude:subagent.type [Section titled “span\_result\_schemas.claude:subagent.type”](#span_result_schemasclaudesubagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.claude:subagent.additionalProperties [Section titled “span\_result\_schemas.claude:subagent.additionalProperties”](#span_result_schemasclaudesubagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` # @prefactor/core [**Prefactor TypeScript SDK**](../index.md) *** [Prefactor TypeScript SDK](../modules.md) / @prefactor/core # @prefactor/core [Section titled “@prefactor/core”](#prefactorcore) Shared runtime, tracing primitives, and transport abstractions for Prefactor SDK adapters. ## `@prefactor/core` overview [Section titled “@prefactor/core overview”](#prefactorcore-overview) `@prefactor/core` is the foundation for Prefactor integrations. Use it when you want direct control over tracing lifecycle, transport behavior, and custom instrumentation in your app. The package supports validated runtime configuration through `createConfig`, runtime initialization through `createCore`, manual instrumentation through `withSpan` and `Tracer.startSpan`, and graceful lifecycle handling with `shutdown` and `registerShutdownHandler`. ## Quick start: initialize runtime directly [Section titled “Quick start: initialize runtime directly”](#quick-start-initialize-runtime-directly) ```ts import { createConfig, createCore } from '@prefactor/core'; const config = createConfig({ transportType: 'http', httpConfig: { apiUrl: 'https://api.prefactor.ai', apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); const core = createCore(config); // core.tracer, core.agentManager, core.shutdown() ``` ## Example: instrument custom work [Section titled “Example: instrument custom work”](#example-instrument-custom-work) ```ts import { withSpan } from '@prefactor/core'; const result = await withSpan( { name: 'custom-operation', spanType: 'app:task', inputs: { jobId: 'job-123' }, }, async () => { return { ok: true }; } ); ``` ## Functions [Section titled “Functions”](#functions) * [getClient](functions/getClient.md) * [init](functions/init.md) * [createConfig](functions/createConfig.md) * [createCore](functions/createCore.md) * [registerShutdownHandler](functions/registerShutdownHandler.md) * [shutdown](functions/shutdown.md) * [buildRuntimeEnvironment](functions/buildRuntimeEnvironment.md) * [normalizeAgentToolSchemas](functions/normalizeAgentToolSchemas.md) * [resolveMappedSpanType](functions/resolveMappedSpanType.md) * [createSpanTypePrefixer](functions/createSpanTypePrefixer.md) * [withSpan](functions/withSpan.md) * [configureLogging](functions/configureLogging.md) * [getLogger](functions/getLogger.md) * [serializeValue](functions/serializeValue.md) * [truncateString](functions/truncateString.md) ## Classes [Section titled “Classes”](#classes) * [AgentInstanceManager](classes/AgentInstanceManager.md) * [PrefactorClient](classes/PrefactorClient.md) * [PrefactorFatalError](classes/PrefactorFatalError.md) * [PrefactorShutdownError](classes/PrefactorShutdownError.md) * [TerminationMonitor](classes/TerminationMonitor.md) * [SpanContext](classes/SpanContext.md) * [Tracer](classes/Tracer.md) * [AgentInstanceClient](classes/AgentInstanceClient.md) * [AgentSpanClient](classes/AgentSpanClient.md) * [HttpClient](classes/HttpClient.md) * [HttpClientError](classes/HttpClientError.md) * [HttpTransport](classes/HttpTransport.md) ## Enumerations [Section titled “Enumerations”](#enumerations) * [SpanStatus](enumerations/SpanStatus.md) ## Interfaces [Section titled “Interfaces”](#interfaces) * [ManualSpanOptions](interfaces/ManualSpanOptions.md) * [PrefactorOptions](interfaces/PrefactorOptions.md) * [PrefactorProvider](interfaces/PrefactorProvider.md) * [FailureHandlingConfig](interfaces/FailureHandlingConfig.md) * [ToolSchemaConfig](interfaces/ToolSchemaConfig.md) * [ActionProfile](interfaces/ActionProfile.md) * [DataCategories](interfaces/DataCategories.md) * [DataRisk](interfaces/DataRisk.md) * [ErrorInfo](interfaces/ErrorInfo.md) * [Span](interfaces/Span.md) * [TokenUsage](interfaces/TokenUsage.md) * [AgentSchemaVersion](interfaces/AgentSchemaVersion.md) * [QualitySchema](interfaces/QualitySchema.md) * [SpanTypeSchema](interfaces/SpanTypeSchema.md) * [EndSpanOptions](interfaces/EndSpanOptions.md) * [StartSpanOptions](interfaces/StartSpanOptions.md) * [HttpRequester](interfaces/HttpRequester.md) * [Transport](interfaces/Transport.md) ## Type Aliases [Section titled “Type Aliases”](#type-aliases) * [MiddlewareLike](type-aliases/MiddlewareLike.md) * [Config](type-aliases/Config.md) * [HttpTransportConfig](type-aliases/HttpTransportConfig.md) * [PartialHttpConfig](type-aliases/PartialHttpConfig.md) * [CoreRuntime](type-aliases/CoreRuntime.md) * [CreateCoreOptions](type-aliases/CreateCoreOptions.md) * [PrefactorFatalErrorKind](type-aliases/PrefactorFatalErrorKind.md) * [PrefactorShutdownDetails](type-aliases/PrefactorShutdownDetails.md) * [PrefactorShutdownErrorKind](type-aliases/PrefactorShutdownErrorKind.md) * [PrefactorTransportHealthState](type-aliases/PrefactorTransportHealthState.md) * [PrefactorTransportOperation](type-aliases/PrefactorTransportOperation.md) * [TerminationCallback](type-aliases/TerminationCallback.md) * [RuntimeEnvironment](type-aliases/RuntimeEnvironment.md) * [JsonSchema](type-aliases/JsonSchema.md) * [ActionProfileValue](type-aliases/ActionProfileValue.md) * [DataCategoryValue](type-aliases/DataCategoryValue.md) * [DataClassification](type-aliases/DataClassification.md) * [SpanType](type-aliases/SpanType.md) * [AgentInstanceFinishOptions](type-aliases/AgentInstanceFinishOptions.md) * [AgentInstanceRecordQualityPayload](type-aliases/AgentInstanceRecordQualityPayload.md) * [AgentInstanceRegisterPayload](type-aliases/AgentInstanceRegisterPayload.md) * [AgentInstanceResponse](type-aliases/AgentInstanceResponse.md) * [AgentInstanceStartOptions](type-aliases/AgentInstanceStartOptions.md) * [AgentSpanCreatePayload](type-aliases/AgentSpanCreatePayload.md) * [AgentSpanFinishOptions](type-aliases/AgentSpanFinishOptions.md) * [AgentSpanResponse](type-aliases/AgentSpanResponse.md) * [AgentSpanStatus](type-aliases/AgentSpanStatus.md) * [AgentInstanceOptions](type-aliases/AgentInstanceOptions.md) ## Variables [Section titled “Variables”](#variables) * [ConfigSchema](variables/ConfigSchema.md) * [HttpTransportConfigSchema](variables/HttpTransportConfigSchema.md) * [PartialHttpConfigSchema](variables/PartialHttpConfigSchema.md) * [SpanType](variables/SpanType.md) # Class: AgentInstanceClient [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentInstanceClient # Class: AgentInstanceClient [Section titled “Class: AgentInstanceClient”](#class-agentinstanceclient) Defined in: [packages/core/src/transport/http/agent-instance-client.ts:46](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L46) ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new AgentInstanceClient**(`httpClient`): `AgentInstanceClient` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:47](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L47) #### Parameters [Section titled “Parameters”](#parameters) ##### httpClient [Section titled “httpClient”](#httpclient) [`HttpRequester`](../interfaces/HttpRequester.md) #### Returns [Section titled “Returns”](#returns) `AgentInstanceClient` ## Methods [Section titled “Methods”](#methods) ### register() [Section titled “register()”](#register) > **register**(`payload`): `Promise`<[`AgentInstanceResponse`](../type-aliases/AgentInstanceResponse.md)> Defined in: [packages/core/src/transport/http/agent-instance-client.ts:49](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L49) #### Parameters [Section titled “Parameters”](#parameters-1) ##### payload [Section titled “payload”](#payload) [`AgentInstanceRegisterPayload`](../type-aliases/AgentInstanceRegisterPayload.md) #### Returns [Section titled “Returns”](#returns-1) `Promise`<[`AgentInstanceResponse`](../type-aliases/AgentInstanceResponse.md)> *** ### start() [Section titled “start()”](#start) > **start**(`agentInstanceId`, `options?`): `Promise`<[`AgentInstanceResponse`](../type-aliases/AgentInstanceResponse.md)> Defined in: [packages/core/src/transport/http/agent-instance-client.ts:56](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L56) #### Parameters [Section titled “Parameters”](#parameters-2) ##### agentInstanceId [Section titled “agentInstanceId”](#agentinstanceid) `string` ##### options? [Section titled “options?”](#options) [`AgentInstanceStartOptions`](../type-aliases/AgentInstanceStartOptions.md) #### Returns [Section titled “Returns”](#returns-2) `Promise`<[`AgentInstanceResponse`](../type-aliases/AgentInstanceResponse.md)> *** ### finish() [Section titled “finish()”](#finish) > **finish**(`agentInstanceId`, `options?`): `Promise`<[`AgentInstanceResponse`](../type-aliases/AgentInstanceResponse.md)> Defined in: [packages/core/src/transport/http/agent-instance-client.ts:67](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L67) #### Parameters [Section titled “Parameters”](#parameters-3) ##### agentInstanceId [Section titled “agentInstanceId”](#agentinstanceid-1) `string` ##### options? [Section titled “options?”](#options-1) [`AgentInstanceFinishOptions`](../type-aliases/AgentInstanceFinishOptions.md) #### Returns [Section titled “Returns”](#returns-3) `Promise`<[`AgentInstanceResponse`](../type-aliases/AgentInstanceResponse.md)> *** ### recordQuality() [Section titled “recordQuality()”](#recordquality) > **recordQuality**(`agentInstanceId`, `payload`): `Promise`<[`AgentInstanceResponse`](../type-aliases/AgentInstanceResponse.md)> Defined in: [packages/core/src/transport/http/agent-instance-client.ts:88](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L88) Records a named quality payload on an agent instance. A null payload removes the recorded value for that name. Other names are left unchanged. An idempotency key is auto-generated when omitted. #### Parameters [Section titled “Parameters”](#parameters-4) ##### agentInstanceId [Section titled “agentInstanceId”](#agentinstanceid-2) `string` Backend agent instance ID. ##### payload [Section titled “payload”](#payload-1) [`AgentInstanceRecordQualityPayload`](../type-aliases/AgentInstanceRecordQualityPayload.md) Quality schema name and payload (or null to remove). #### Returns [Section titled “Returns”](#returns-4) `Promise`<[`AgentInstanceResponse`](../type-aliases/AgentInstanceResponse.md)> The API response containing the updated instance details. # Class: AgentInstanceManager [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentInstanceManager # Class: AgentInstanceManager [Section titled “Class: AgentInstanceManager”](#class-agentinstancemanager) Defined in: [packages/core/src/agent/instance-manager.ts:20](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/agent/instance-manager.ts#L20) Coordinates agent instance lifecycle and schema registration for a transport. ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new AgentInstanceManager**(`transport`, `options`): `AgentInstanceManager` Defined in: [packages/core/src/agent/instance-manager.ts:24](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/agent/instance-manager.ts#L24) #### Parameters [Section titled “Parameters”](#parameters) ##### transport [Section titled “transport”](#transport) [`Transport`](../interfaces/Transport.md) ##### options [Section titled “options”](#options) `AgentInstanceManagerOptions` #### Returns [Section titled “Returns”](#returns) `AgentInstanceManager` ## Methods [Section titled “Methods”](#methods) ### ensureTokenValid() [Section titled “ensureTokenValid()”](#ensuretokenvalid) > **ensureTokenValid**(): `Promise`<`void`> Defined in: [packages/core/src/agent/instance-manager.ts:36](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/agent/instance-manager.ts#L36) Validates the configured API token against the Prefactor ping endpoint. Runs once per manager instance; subsequent calls return the same promise. #### Returns [Section titled “Returns”](#returns-1) `Promise`<`void`> #### Throws [Section titled “Throws”](#throws) When the token is invalid, expired, or unauthorized. *** ### registerSchema() [Section titled “registerSchema()”](#registerschema) > **registerSchema**(`schema`): `void` Defined in: [packages/core/src/agent/instance-manager.ts:45](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/agent/instance-manager.ts#L45) #### Parameters [Section titled “Parameters”](#parameters-1) ##### schema [Section titled “schema”](#schema) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-2) `void` *** ### startInstance() [Section titled “startInstance()”](#startinstance) > **startInstance**(`options?`): `void` Defined in: [packages/core/src/agent/instance-manager.ts:61](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/agent/instance-manager.ts#L61) #### Parameters [Section titled “Parameters”](#parameters-2) ##### options? [Section titled “options?”](#options-1) [`AgentInstanceOptions`](../type-aliases/AgentInstanceOptions.md) = `{}` #### Returns [Section titled “Returns”](#returns-3) `void` *** ### finishInstance() [Section titled “finishInstance()”](#finishinstance) > **finishInstance**(): `void` Defined in: [packages/core/src/agent/instance-manager.ts:70](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/agent/instance-manager.ts#L70) #### Returns [Section titled “Returns”](#returns-4) `void` *** ### recordQuality() [Section titled “recordQuality()”](#recordquality) > **recordQuality**(`options`): `void` Defined in: [packages/core/src/agent/instance-manager.ts:78](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/agent/instance-manager.ts#L78) Records a quality payload on the agent instance for a named quality schema. A null payload removes the recorded value for that name. #### Parameters [Section titled “Parameters”](#parameters-3) ##### options [Section titled “options”](#options-2) `AgentInstanceRecordQualityOptions` #### Returns [Section titled “Returns”](#returns-5) `void` *** ### getAgentInstanceId() [Section titled “getAgentInstanceId()”](#getagentinstanceid) > **getAgentInstanceId**(): `string` | `null` Defined in: [packages/core/src/agent/instance-manager.ts:85](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/agent/instance-manager.ts#L85) #### Returns [Section titled “Returns”](#returns-6) `string` | `null` # Class: AgentSpanClient [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentSpanClient # Class: AgentSpanClient [Section titled “Class: AgentSpanClient”](#class-agentspanclient) Defined in: [packages/core/src/transport/http/agent-span-client.ts:43](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L43) ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new AgentSpanClient**(`httpClient`): `AgentSpanClient` Defined in: [packages/core/src/transport/http/agent-span-client.ts:44](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L44) #### Parameters [Section titled “Parameters”](#parameters) ##### httpClient [Section titled “httpClient”](#httpclient) [`HttpRequester`](../interfaces/HttpRequester.md) #### Returns [Section titled “Returns”](#returns) `AgentSpanClient` ## Methods [Section titled “Methods”](#methods) ### create() [Section titled “create()”](#create) > **create**(`payload`): `Promise`<[`AgentSpanResponse`](../type-aliases/AgentSpanResponse.md)> Defined in: [packages/core/src/transport/http/agent-span-client.ts:46](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L46) #### Parameters [Section titled “Parameters”](#parameters-1) ##### payload [Section titled “payload”](#payload) [`AgentSpanCreatePayload`](../type-aliases/AgentSpanCreatePayload.md) #### Returns [Section titled “Returns”](#returns-1) `Promise`<[`AgentSpanResponse`](../type-aliases/AgentSpanResponse.md)> *** ### finish() [Section titled “finish()”](#finish) > **finish**(`spanId`, `timestamp`, `options?`): `Promise`<[`AgentSpanResponse`](../type-aliases/AgentSpanResponse.md)> Defined in: [packages/core/src/transport/http/agent-span-client.ts:53](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L53) #### Parameters [Section titled “Parameters”](#parameters-2) ##### spanId [Section titled “spanId”](#spanid) `string` ##### timestamp [Section titled “timestamp”](#timestamp) `string` ##### options? [Section titled “options?”](#options) [`AgentSpanFinishOptions`](../type-aliases/AgentSpanFinishOptions.md) = `{}` #### Returns [Section titled “Returns”](#returns-2) `Promise`<[`AgentSpanResponse`](../type-aliases/AgentSpanResponse.md)> # Class: HttpClient [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / HttpClient # Class: HttpClient [Section titled “Class: HttpClient”](#class-httpclient) Defined in: [packages/core/src/transport/http/http-client.ts:53](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L53) ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new HttpClient**(`config`, `dependencies?`): `HttpClient` Defined in: [packages/core/src/transport/http/http-client.ts:65](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L65) #### Parameters [Section titled “Parameters”](#parameters) ##### config [Section titled “config”](#config) ###### apiUrl [Section titled “apiUrl”](#apiurl) `string` = `...` API endpoint URL ###### apiToken [Section titled “apiToken”](#apitoken) `string` = `...` Authentication token ###### agentIdentifier [Section titled “agentIdentifier”](#agentidentifier) `string` = `...` Agent identifier (external identifier); defaults to v1.0.0 when omitted ###### requestTimeout [Section titled “requestTimeout”](#requesttimeout) `number` = `...` Request timeout in milliseconds ###### maxRetries [Section titled “maxRetries”](#maxretries) `number` = `...` Maximum number of retry attempts ###### initialRetryDelay [Section titled “initialRetryDelay”](#initialretrydelay) `number` = `...` Initial delay between retries in milliseconds ###### maxRetryDelay [Section titled “maxRetryDelay”](#maxretrydelay) `number` = `...` Maximum delay between retries in milliseconds ###### retryMultiplier [Section titled “retryMultiplier”](#retrymultiplier) `number` = `...` Multiplier for exponential backoff ###### retryOnStatusCodes [Section titled “retryOnStatusCodes”](#retryonstatuscodes) `number`\[] = `...` Status codes that should trigger retries ###### agentId? [Section titled “agentId?”](#agentid) `string` = `...` Optional agent instance identifier (internal ID) ###### agentName? [Section titled “agentName?”](#agentname) `string` = `...` Optional agent name ###### agentDescription? [Section titled “agentDescription?”](#agentdescription) `string` = `...` Optional agent description ###### agentSchema? [Section titled “agentSchema?”](#agentschema) `Record`<`string`, `unknown`> = `...` Optional agent schema for validation (full schema object) ##### dependencies? [Section titled “dependencies?”](#dependencies) `HttpClientDependencies` #### Returns [Section titled “Returns”](#returns) `HttpClient` ## Methods [Section titled “Methods”](#methods) ### request() [Section titled “request()”](#request) > **request**<`TResponse`>(`path`, `options?`): `Promise`<`TResponse`> Defined in: [packages/core/src/transport/http/http-client.ts:80](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L80) #### Type Parameters [Section titled “Type Parameters”](#type-parameters) ##### TResponse [Section titled “TResponse”](#tresponse) `TResponse` = `unknown` #### Parameters [Section titled “Parameters”](#parameters-1) ##### path [Section titled “path”](#path) `string` ##### options? [Section titled “options?”](#options) `HttpRequestOptions` = `{}` #### Returns [Section titled “Returns”](#returns-1) `Promise`<`TResponse`> # Class: HttpClientError [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / HttpClientError # Class: HttpClientError [Section titled “Class: HttpClientError”](#class-httpclienterror) Defined in: [packages/core/src/transport/http/http-client.ts:33](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L33) ## Extends [Section titled “Extends”](#extends) * `Error` ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new HttpClientError**(`message`, `options`): `HttpClientError` Defined in: [packages/core/src/transport/http/http-client.ts:41](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L41) #### Parameters [Section titled “Parameters”](#parameters) ##### message [Section titled “message”](#message) `string` ##### options [Section titled “options”](#options) `HttpClientErrorOptions` #### Returns [Section titled “Returns”](#returns) `HttpClientError` #### Overrides [Section titled “Overrides”](#overrides) `Error.constructor` ## Methods [Section titled “Methods”](#methods) ### captureStackTrace() [Section titled “captureStackTrace()”](#capturestacktrace) #### Call Signature [Section titled “Call Signature”](#call-signature) > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Defined in: node\_modules/.bun/@types+node\@20.19.37/node\_modules/@types/node/globals.d.ts:52 Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters [Section titled “Parameters”](#parameters-1) ###### targetObject [Section titled “targetObject”](#targetobject) `object` ###### constructorOpt? [Section titled “constructorOpt?”](#constructoropt) `Function` ##### Returns [Section titled “Returns”](#returns-1) `void` ##### Inherited from [Section titled “Inherited from”](#inherited-from) `Error.captureStackTrace` #### Call Signature [Section titled “Call Signature”](#call-signature-1) > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Defined in: node\_modules/.bun/bun-types\@1.3.14/node\_modules/bun-types/globals.d.ts:1042 Create .stack property on a target object ##### Parameters [Section titled “Parameters”](#parameters-2) ###### targetObject [Section titled “targetObject”](#targetobject-1) `object` ###### constructorOpt? [Section titled “constructorOpt?”](#constructoropt-1) `Function` ##### Returns [Section titled “Returns”](#returns-2) `void` ##### Inherited from [Section titled “Inherited from”](#inherited-from-1) `Error.captureStackTrace` *** ### prepareStackTrace() [Section titled “prepareStackTrace()”](#preparestacktrace) > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` Defined in: node\_modules/.bun/@types+node\@20.19.37/node\_modules/@types/node/globals.d.ts:56 #### Parameters [Section titled “Parameters”](#parameters-3) ##### err [Section titled “err”](#err) `Error` ##### stackTraces [Section titled “stackTraces”](#stacktraces) `CallSite`\[] #### Returns [Section titled “Returns”](#returns-3) `any` #### See [Section titled “See”](#see) #### Inherited from [Section titled “Inherited from”](#inherited-from-2) `Error.prepareStackTrace` *** ### isError() [Section titled “isError()”](#iserror) > `static` **isError**(`value`): `value is Error` Defined in: node\_modules/.bun/bun-types\@1.3.14/node\_modules/bun-types/globals.d.ts:1037 Check if a value is an instance of Error #### Parameters [Section titled “Parameters”](#parameters-4) ##### value [Section titled “value”](#value) `unknown` The value to check #### Returns [Section titled “Returns”](#returns-4) `value is Error` True if the value is an instance of Error, false otherwise #### Inherited from [Section titled “Inherited from”](#inherited-from-3) `Error.isError` ## Properties [Section titled “Properties”](#properties) ### stackTraceLimit [Section titled “stackTraceLimit”](#stacktracelimit) > `static` **stackTraceLimit**: `number` Defined in: node\_modules/.bun/@types+node\@20.19.37/node\_modules/@types/node/globals.d.ts:68 The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured *after* the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. #### Inherited from [Section titled “Inherited from”](#inherited-from-4) `Error.stackTraceLimit` *** ### url [Section titled “url”](#url) > `readonly` **url**: `string` Defined in: [packages/core/src/transport/http/http-client.ts:34](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L34) *** ### method [Section titled “method”](#method) > `readonly` **method**: `string` Defined in: [packages/core/src/transport/http/http-client.ts:35](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L35) *** ### status? [Section titled “status?”](#status) > `readonly` `optional` **status**: `number` Defined in: [packages/core/src/transport/http/http-client.ts:36](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L36) *** ### statusText? [Section titled “statusText?”](#statustext) > `readonly` `optional` **statusText**: `string` Defined in: [packages/core/src/transport/http/http-client.ts:37](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L37) *** ### responseBody? [Section titled “responseBody?”](#responsebody) > `readonly` `optional` **responseBody**: `unknown` Defined in: [packages/core/src/transport/http/http-client.ts:38](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L38) *** ### retryable [Section titled “retryable”](#retryable) > `readonly` **retryable**: `boolean` Defined in: [packages/core/src/transport/http/http-client.ts:39](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L39) *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: node\_modules/.bun/typescript\@5.9.3/node\_modules/typescript/lib/lib.es5.d.ts:1076 #### Inherited from [Section titled “Inherited from”](#inherited-from-5) `Error.name` *** ### message [Section titled “message”](#message-1) > **message**: `string` Defined in: node\_modules/.bun/typescript\@5.9.3/node\_modules/typescript/lib/lib.es5.d.ts:1077 #### Inherited from [Section titled “Inherited from”](#inherited-from-6) `Error.message` *** ### stack? [Section titled “stack?”](#stack) > `optional` **stack**: `string` Defined in: node\_modules/.bun/typescript\@5.9.3/node\_modules/typescript/lib/lib.es5.d.ts:1078 #### Inherited from [Section titled “Inherited from”](#inherited-from-7) `Error.stack` *** ### cause? [Section titled “cause?”](#cause) > `optional` **cause**: `unknown` Defined in: node\_modules/.bun/typescript\@5.9.3/node\_modules/typescript/lib/lib.es2022.error.d.ts:26 The cause of the error. #### Inherited from [Section titled “Inherited from”](#inherited-from-8) `Error.cause` # Class: HttpTransport [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / HttpTransport # Class: HttpTransport [Section titled “Class: HttpTransport”](#class-httptransport) Defined in: [packages/core/src/transport/http.ts:128](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L128) HTTP-backed transport that serializes span operations through an internal queue. ## Implements [Section titled “Implements”](#implements) * [`Transport`](../interfaces/Transport.md) ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new HttpTransport**(`config`, `options?`): `HttpTransport` Defined in: [packages/core/src/transport/http.ts:160](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L160) #### Parameters [Section titled “Parameters”](#parameters) ##### config [Section titled “config”](#config) ###### apiUrl [Section titled “apiUrl”](#apiurl) `string` = `...` API endpoint URL ###### apiToken [Section titled “apiToken”](#apitoken) `string` = `...` Authentication token ###### agentIdentifier [Section titled “agentIdentifier”](#agentidentifier) `string` = `...` Agent identifier (external identifier); defaults to v1.0.0 when omitted ###### requestTimeout [Section titled “requestTimeout”](#requesttimeout) `number` = `...` Request timeout in milliseconds ###### maxRetries [Section titled “maxRetries”](#maxretries) `number` = `...` Maximum number of retry attempts ###### initialRetryDelay [Section titled “initialRetryDelay”](#initialretrydelay) `number` = `...` Initial delay between retries in milliseconds ###### maxRetryDelay [Section titled “maxRetryDelay”](#maxretrydelay) `number` = `...` Maximum delay between retries in milliseconds ###### retryMultiplier [Section titled “retryMultiplier”](#retrymultiplier) `number` = `...` Multiplier for exponential backoff ###### retryOnStatusCodes [Section titled “retryOnStatusCodes”](#retryonstatuscodes) `number`\[] = `...` Status codes that should trigger retries ###### agentId? [Section titled “agentId?”](#agentid) `string` = `...` Optional agent instance identifier (internal ID) ###### agentName? [Section titled “agentName?”](#agentname) `string` = `...` Optional agent name ###### agentDescription? [Section titled “agentDescription?”](#agentdescription) `string` = `...` Optional agent description ###### agentSchema? [Section titled “agentSchema?”](#agentschema) `Record`<`string`, `unknown`> = `...` Optional agent schema for validation (full schema object) ##### options? [Section titled “options?”](#options) `HttpTransportOptions` #### Returns [Section titled “Returns”](#returns) `HttpTransport` ## Methods [Section titled “Methods”](#methods) ### registerControlSignalCallback() [Section titled “registerControlSignalCallback()”](#registercontrolsignalcallback) > **registerControlSignalCallback**(`fn`): `void` Defined in: [packages/core/src/transport/http.ts:188](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L188) Registers a callback that fires when any span response contains a termination control signal. Called by createCore to wire the monitor. #### Parameters [Section titled “Parameters”](#parameters-1) ##### fn [Section titled “fn”](#fn) (`reason`) => `void` #### Returns [Section titled “Returns”](#returns-1) `void` *** ### registerSchema() [Section titled “registerSchema()”](#registerschema) > **registerSchema**(`schema`): `void` Defined in: [packages/core/src/transport/http.ts:192](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L192) #### Parameters [Section titled “Parameters”](#parameters-2) ##### schema [Section titled “schema”](#schema) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-2) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of) [`Transport`](../interfaces/Transport.md).[`registerSchema`](../interfaces/Transport.md#registerschema) *** ### startAgentInstance() [Section titled “startAgentInstance()”](#startagentinstance) > **startAgentInstance**(`options?`): `void` Defined in: [packages/core/src/transport/http.ts:212](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L212) #### Parameters [Section titled “Parameters”](#parameters-3) ##### options? [Section titled “options?”](#options-1) [`AgentInstanceOptions`](../type-aliases/AgentInstanceOptions.md) #### Returns [Section titled “Returns”](#returns-3) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-1) [`Transport`](../interfaces/Transport.md).[`startAgentInstance`](../interfaces/Transport.md#startagentinstance) *** ### finishAgentInstance() [Section titled “finishAgentInstance()”](#finishagentinstance) > **finishAgentInstance**(): `void` Defined in: [packages/core/src/transport/http.ts:225](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L225) #### Returns [Section titled “Returns”](#returns-4) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-2) [`Transport`](../interfaces/Transport.md).[`finishAgentInstance`](../interfaces/Transport.md#finishagentinstance) *** ### recordQuality() [Section titled “recordQuality()”](#recordquality) > **recordQuality**(`payload`): `void` Defined in: [packages/core/src/transport/http.ts:246](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L246) Enqueues a record-quality action for the current agent instance. A null payload removes the recorded value for that name. The action is queued and retried like other transport actions. #### Parameters [Section titled “Parameters”](#parameters-4) ##### payload [Section titled “payload”](#payload) Quality schema name and payload (or null to remove). ###### name [Section titled “name”](#name) `string` ###### payload [Section titled “payload”](#payload-1) `Record`<`string`, `unknown`> | `null` #### Returns [Section titled “Returns”](#returns-5) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-3) [`Transport`](../interfaces/Transport.md).[`recordQuality`](../interfaces/Transport.md#recordquality) *** ### emit() [Section titled “emit()”](#emit) > **emit**(`span`): `void` Defined in: [packages/core/src/transport/http.ts:261](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L261) #### Parameters [Section titled “Parameters”](#parameters-5) ##### span [Section titled “span”](#span) [`Span`](../interfaces/Span.md) #### Returns [Section titled “Returns”](#returns-6) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-4) [`Transport`](../interfaces/Transport.md).[`emit`](../interfaces/Transport.md#emit) *** ### finishSpan() [Section titled “finishSpan()”](#finishspan) > **finishSpan**(`spanId`, `endTime`, `options?`): `void` Defined in: [packages/core/src/transport/http.ts:271](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L271) #### Parameters [Section titled “Parameters”](#parameters-6) ##### spanId [Section titled “spanId”](#spanid) `string` ##### endTime [Section titled “endTime”](#endtime) `number` ##### options? [Section titled “options?”](#options-2) `FinishSpanOptions` #### Returns [Section titled “Returns”](#returns-7) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-5) [`Transport`](../interfaces/Transport.md).[`finishSpan`](../interfaces/Transport.md#finishspan) *** ### assertUsable() [Section titled “assertUsable()”](#assertusable) > **assertUsable**(`operation`): `void` Defined in: [packages/core/src/transport/http.ts:285](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L285) #### Parameters [Section titled “Parameters”](#parameters-7) ##### operation [Section titled “operation”](#operation) [`PrefactorTransportOperation`](../type-aliases/PrefactorTransportOperation.md) #### Returns [Section titled “Returns”](#returns-8) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-6) [`Transport`](../interfaces/Transport.md).[`assertUsable`](../interfaces/Transport.md#assertusable) *** ### getHealthState() [Section titled “getHealthState()”](#gethealthstate) > **getHealthState**(): [`PrefactorTransportHealthState`](../type-aliases/PrefactorTransportHealthState.md) Defined in: [packages/core/src/transport/http.ts:296](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L296) #### Returns [Section titled “Returns”](#returns-9) [`PrefactorTransportHealthState`](../type-aliases/PrefactorTransportHealthState.md) #### Implementation of [Section titled “Implementation of”](#implementation-of-7) [`Transport`](../interfaces/Transport.md).[`getHealthState`](../interfaces/Transport.md#gethealthstate) *** ### getAgentInstanceId() [Section titled “getAgentInstanceId()”](#getagentinstanceid) > **getAgentInstanceId**(): `string` | `null` Defined in: [packages/core/src/transport/http.ts:300](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L300) #### Returns [Section titled “Returns”](#returns-10) `string` | `null` #### Implementation of [Section titled “Implementation of”](#implementation-of-8) [`Transport`](../interfaces/Transport.md).[`getAgentInstanceId`](../interfaces/Transport.md#getagentinstanceid) *** ### getHttpRequester() [Section titled “getHttpRequester()”](#gethttprequester) > **getHttpRequester**(): [`HttpRequester`](../interfaces/HttpRequester.md) Defined in: [packages/core/src/transport/http.ts:304](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L304) #### Returns [Section titled “Returns”](#returns-11) [`HttpRequester`](../interfaces/HttpRequester.md) #### Implementation of [Section titled “Implementation of”](#implementation-of-9) [`Transport`](../interfaces/Transport.md).[`getHttpRequester`](../interfaces/Transport.md#gethttprequester) *** ### validateToken() [Section titled “validateToken()”](#validatetoken) > **validateToken**(): `Promise`<`void`> Defined in: [packages/core/src/transport/http.ts:308](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L308) #### Returns [Section titled “Returns”](#returns-12) `Promise`<`void`> #### Implementation of [Section titled “Implementation of”](#implementation-of-10) [`Transport`](../interfaces/Transport.md).[`validateToken`](../interfaces/Transport.md#validatetoken) *** ### close() [Section titled “close()”](#close) > **close**(): `Promise`<`void`> Defined in: [packages/core/src/transport/http.ts:326](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L326) #### Returns [Section titled “Returns”](#returns-13) `Promise`<`void`> #### Implementation of [Section titled “Implementation of”](#implementation-of-11) [`Transport`](../interfaces/Transport.md).[`close`](../interfaces/Transport.md#close) # Class: PrefactorClient\ [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / PrefactorClient # Class: PrefactorClient\ [Section titled “Class: PrefactorClient\”](#class-prefactorclienttmiddleware) Defined in: [packages/core/src/client.ts:85](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L85) ## Type Parameters [Section titled “Type Parameters”](#type-parameters) ### TMiddleware [Section titled “TMiddleware”](#tmiddleware) `TMiddleware` = [`MiddlewareLike`](../type-aliases/MiddlewareLike.md) ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new PrefactorClient**<`TMiddleware`>(`core`, `middleware`, `provider`): `PrefactorClient`<`TMiddleware`> Defined in: [packages/core/src/client.ts:97](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L97) Creates a Prefactor client bound to a runtime and provider middleware. #### Parameters [Section titled “Parameters”](#parameters) ##### core [Section titled “core”](#core) [`CoreRuntime`](../type-aliases/CoreRuntime.md) Initialized core runtime. ##### middleware [Section titled “middleware”](#middleware) `TMiddleware` Provider middleware returned by the integration. ##### provider [Section titled “provider”](#provider) [`PrefactorProvider`](../interfaces/PrefactorProvider.md)<`TMiddleware`> Provider used to construct the client. #### Returns [Section titled “Returns”](#returns) `PrefactorClient`<`TMiddleware`> ## Methods [Section titled “Methods”](#methods) ### getTracer() [Section titled “getTracer()”](#gettracer) > **getTracer**(): [`Tracer`](Tracer.md) Defined in: [packages/core/src/client.ts:112](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L112) Returns the runtime tracer used by this client. #### Returns [Section titled “Returns”](#returns-1) [`Tracer`](Tracer.md) Active tracer instance. *** ### getMiddleware() [Section titled “getMiddleware()”](#getmiddleware) > **getMiddleware**(): `TMiddleware` Defined in: [packages/core/src/client.ts:121](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L121) Returns provider middleware created during initialization. #### Returns [Section titled “Returns”](#returns-2) `TMiddleware` Provider middleware object. *** ### getTerminationMonitor() [Section titled “getTerminationMonitor()”](#getterminationmonitor) > **getTerminationMonitor**(): [`TerminationMonitor`](TerminationMonitor.md) Defined in: [packages/core/src/client.ts:125](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L125) #### Returns [Section titled “Returns”](#returns-3) [`TerminationMonitor`](TerminationMonitor.md) *** ### getAgentInstanceId() [Section titled “getAgentInstanceId()”](#getagentinstanceid) > **getAgentInstanceId**(): `string` | `null` Defined in: [packages/core/src/client.ts:129](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L129) #### Returns [Section titled “Returns”](#returns-4) `string` | `null` *** ### finishCurrentRun() [Section titled “finishCurrentRun()”](#finishcurrentrun) > **finishCurrentRun**(): `void` Defined in: [packages/core/src/client.ts:141](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L141) Ends the current agent run and resets the termination monitor for the next run. Call this between runs in a long-running service loop. Finishes the active agent instance (if any), resets the termination monitor so a fresh AbortSignal is available, and invokes the provider’s `resetForNextRun` hook to clear any per-run middleware state. #### Returns [Section titled “Returns”](#returns-5) `void` *** ### withSpan() [Section titled “withSpan()”](#withspan) > **withSpan**<`T`>(`options`, `fn`): `Promise`<`T`> Defined in: [packages/core/src/client.ts:160](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L160) Runs a function within a manually-created span. #### Type Parameters [Section titled “Type Parameters”](#type-parameters-1) ##### T [Section titled “T”](#t) `T` #### Parameters [Section titled “Parameters”](#parameters-1) ##### options [Section titled “options”](#options) [`ManualSpanOptions`](../interfaces/ManualSpanOptions.md) Manual span options. ##### fn [Section titled “fn”](#fn) () => `T` | `Promise`<`T`> Function executed inside the created span. #### Returns [Section titled “Returns”](#returns-6) `Promise`<`T`> Result of `fn` as a promise. *** ### shutdown() [Section titled “shutdown()”](#shutdown) > **shutdown**(): `Promise`<`void`> Defined in: [packages/core/src/client.ts:180](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L180) Flushes pending telemetry and releases the global singleton reference. The global client reference is always cleared, even if shutdown fails. #### Returns [Section titled “Returns”](#returns-7) `Promise`<`void`> Promise that resolves when shutdown completes. # Class: PrefactorFatalError [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / PrefactorFatalError # Class: PrefactorFatalError [Section titled “Class: PrefactorFatalError”](#class-prefactorfatalerror) Defined in: [packages/core/src/errors.ts:30](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L30) ## Extends [Section titled “Extends”](#extends) * `Error` ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new PrefactorFatalError**(`kind`, `message`, `options`): `PrefactorFatalError` Defined in: [packages/core/src/errors.ts:37](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L37) #### Parameters [Section titled “Parameters”](#parameters) ##### kind [Section titled “kind”](#kind) [`PrefactorFatalErrorKind`](../type-aliases/PrefactorFatalErrorKind.md) ##### message [Section titled “message”](#message) `string` ##### options [Section titled “options”](#options) `PrefactorErrorOptions` #### Returns [Section titled “Returns”](#returns) `PrefactorFatalError` #### Overrides [Section titled “Overrides”](#overrides) `Error.constructor` ## Methods [Section titled “Methods”](#methods) ### captureStackTrace() [Section titled “captureStackTrace()”](#capturestacktrace) #### Call Signature [Section titled “Call Signature”](#call-signature) > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Defined in: node\_modules/.bun/@types+node\@20.19.37/node\_modules/@types/node/globals.d.ts:52 Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters [Section titled “Parameters”](#parameters-1) ###### targetObject [Section titled “targetObject”](#targetobject) `object` ###### constructorOpt? [Section titled “constructorOpt?”](#constructoropt) `Function` ##### Returns [Section titled “Returns”](#returns-1) `void` ##### Inherited from [Section titled “Inherited from”](#inherited-from) `Error.captureStackTrace` #### Call Signature [Section titled “Call Signature”](#call-signature-1) > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Defined in: node\_modules/.bun/bun-types\@1.3.14/node\_modules/bun-types/globals.d.ts:1042 Create .stack property on a target object ##### Parameters [Section titled “Parameters”](#parameters-2) ###### targetObject [Section titled “targetObject”](#targetobject-1) `object` ###### constructorOpt? [Section titled “constructorOpt?”](#constructoropt-1) `Function` ##### Returns [Section titled “Returns”](#returns-2) `void` ##### Inherited from [Section titled “Inherited from”](#inherited-from-1) `Error.captureStackTrace` *** ### prepareStackTrace() [Section titled “prepareStackTrace()”](#preparestacktrace) > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` Defined in: node\_modules/.bun/@types+node\@20.19.37/node\_modules/@types/node/globals.d.ts:56 #### Parameters [Section titled “Parameters”](#parameters-3) ##### err [Section titled “err”](#err) `Error` ##### stackTraces [Section titled “stackTraces”](#stacktraces) `CallSite`\[] #### Returns [Section titled “Returns”](#returns-3) `any` #### See [Section titled “See”](#see) #### Inherited from [Section titled “Inherited from”](#inherited-from-2) `Error.prepareStackTrace` *** ### isError() [Section titled “isError()”](#iserror) > `static` **isError**(`value`): `value is Error` Defined in: node\_modules/.bun/bun-types\@1.3.14/node\_modules/bun-types/globals.d.ts:1037 Check if a value is an instance of Error #### Parameters [Section titled “Parameters”](#parameters-4) ##### value [Section titled “value”](#value) `unknown` The value to check #### Returns [Section titled “Returns”](#returns-4) `value is Error` True if the value is an instance of Error, false otherwise #### Inherited from [Section titled “Inherited from”](#inherited-from-3) `Error.isError` ## Properties [Section titled “Properties”](#properties) ### stackTraceLimit [Section titled “stackTraceLimit”](#stacktracelimit) > `static` **stackTraceLimit**: `number` Defined in: node\_modules/.bun/@types+node\@20.19.37/node\_modules/@types/node/globals.d.ts:68 The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured *after* the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. #### Inherited from [Section titled “Inherited from”](#inherited-from-4) `Error.stackTraceLimit` *** ### kind [Section titled “kind”](#kind-1) > `readonly` **kind**: [`PrefactorFatalErrorKind`](../type-aliases/PrefactorFatalErrorKind.md) Defined in: [packages/core/src/errors.ts:31](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L31) *** ### operation [Section titled “operation”](#operation) > `readonly` **operation**: [`PrefactorTransportOperation`](../type-aliases/PrefactorTransportOperation.md) Defined in: [packages/core/src/errors.ts:32](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L32) *** ### status? [Section titled “status?”](#status) > `readonly` `optional` **status**: `number` Defined in: [packages/core/src/errors.ts:33](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L33) *** ### responseBody? [Section titled “responseBody?”](#responsebody) > `readonly` `optional` **responseBody**: `unknown` Defined in: [packages/core/src/errors.ts:34](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L34) *** ### consecutiveFailures [Section titled “consecutiveFailures”](#consecutivefailures) > `readonly` **consecutiveFailures**: `number` Defined in: [packages/core/src/errors.ts:35](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L35) *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: node\_modules/.bun/typescript\@5.9.3/node\_modules/typescript/lib/lib.es5.d.ts:1076 #### Inherited from [Section titled “Inherited from”](#inherited-from-5) `Error.name` *** ### message [Section titled “message”](#message-1) > **message**: `string` Defined in: node\_modules/.bun/typescript\@5.9.3/node\_modules/typescript/lib/lib.es5.d.ts:1077 #### Inherited from [Section titled “Inherited from”](#inherited-from-6) `Error.message` *** ### stack? [Section titled “stack?”](#stack) > `optional` **stack**: `string` Defined in: node\_modules/.bun/typescript\@5.9.3/node\_modules/typescript/lib/lib.es5.d.ts:1078 #### Inherited from [Section titled “Inherited from”](#inherited-from-7) `Error.stack` *** ### cause? [Section titled “cause?”](#cause) > `optional` **cause**: `unknown` Defined in: node\_modules/.bun/typescript\@5.9.3/node\_modules/typescript/lib/lib.es2022.error.d.ts:26 The cause of the error. #### Inherited from [Section titled “Inherited from”](#inherited-from-8) `Error.cause` # Class: PrefactorShutdownError [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / PrefactorShutdownError # Class: PrefactorShutdownError [Section titled “Class: PrefactorShutdownError”](#class-prefactorshutdownerror) Defined in: [packages/core/src/errors.ts:56](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L56) ## Extends [Section titled “Extends”](#extends) * `Error` ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new PrefactorShutdownError**(`kind`, `message`, `options`): `PrefactorShutdownError` Defined in: [packages/core/src/errors.ts:64](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L64) #### Parameters [Section titled “Parameters”](#parameters) ##### kind [Section titled “kind”](#kind) [`PrefactorShutdownErrorKind`](../type-aliases/PrefactorShutdownErrorKind.md) ##### message [Section titled “message”](#message) `string` ##### options [Section titled “options”](#options) `PrefactorErrorOptions` & `object` #### Returns [Section titled “Returns”](#returns) `PrefactorShutdownError` #### Overrides [Section titled “Overrides”](#overrides) `Error.constructor` ## Methods [Section titled “Methods”](#methods) ### captureStackTrace() [Section titled “captureStackTrace()”](#capturestacktrace) #### Call Signature [Section titled “Call Signature”](#call-signature) > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Defined in: node\_modules/.bun/@types+node\@20.19.37/node\_modules/@types/node/globals.d.ts:52 Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ##### Parameters [Section titled “Parameters”](#parameters-1) ###### targetObject [Section titled “targetObject”](#targetobject) `object` ###### constructorOpt? [Section titled “constructorOpt?”](#constructoropt) `Function` ##### Returns [Section titled “Returns”](#returns-1) `void` ##### Inherited from [Section titled “Inherited from”](#inherited-from) `Error.captureStackTrace` #### Call Signature [Section titled “Call Signature”](#call-signature-1) > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Defined in: node\_modules/.bun/bun-types\@1.3.14/node\_modules/bun-types/globals.d.ts:1042 Create .stack property on a target object ##### Parameters [Section titled “Parameters”](#parameters-2) ###### targetObject [Section titled “targetObject”](#targetobject-1) `object` ###### constructorOpt? [Section titled “constructorOpt?”](#constructoropt-1) `Function` ##### Returns [Section titled “Returns”](#returns-2) `void` ##### Inherited from [Section titled “Inherited from”](#inherited-from-1) `Error.captureStackTrace` *** ### prepareStackTrace() [Section titled “prepareStackTrace()”](#preparestacktrace) > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` Defined in: node\_modules/.bun/@types+node\@20.19.37/node\_modules/@types/node/globals.d.ts:56 #### Parameters [Section titled “Parameters”](#parameters-3) ##### err [Section titled “err”](#err) `Error` ##### stackTraces [Section titled “stackTraces”](#stacktraces) `CallSite`\[] #### Returns [Section titled “Returns”](#returns-3) `any` #### See [Section titled “See”](#see) #### Inherited from [Section titled “Inherited from”](#inherited-from-2) `Error.prepareStackTrace` *** ### isError() [Section titled “isError()”](#iserror) > `static` **isError**(`value`): `value is Error` Defined in: node\_modules/.bun/bun-types\@1.3.14/node\_modules/bun-types/globals.d.ts:1037 Check if a value is an instance of Error #### Parameters [Section titled “Parameters”](#parameters-4) ##### value [Section titled “value”](#value) `unknown` The value to check #### Returns [Section titled “Returns”](#returns-4) `value is Error` True if the value is an instance of Error, false otherwise #### Inherited from [Section titled “Inherited from”](#inherited-from-3) `Error.isError` ## Properties [Section titled “Properties”](#properties) ### stackTraceLimit [Section titled “stackTraceLimit”](#stacktracelimit) > `static` **stackTraceLimit**: `number` Defined in: node\_modules/.bun/@types+node\@20.19.37/node\_modules/@types/node/globals.d.ts:68 The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured *after* the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. #### Inherited from [Section titled “Inherited from”](#inherited-from-4) `Error.stackTraceLimit` *** ### kind [Section titled “kind”](#kind-1) > `readonly` **kind**: [`PrefactorShutdownErrorKind`](../type-aliases/PrefactorShutdownErrorKind.md) Defined in: [packages/core/src/errors.ts:57](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L57) *** ### operation [Section titled “operation”](#operation) > `readonly` **operation**: [`PrefactorTransportOperation`](../type-aliases/PrefactorTransportOperation.md) Defined in: [packages/core/src/errors.ts:58](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L58) *** ### status? [Section titled “status?”](#status) > `readonly` `optional` **status**: `number` Defined in: [packages/core/src/errors.ts:59](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L59) *** ### responseBody? [Section titled “responseBody?”](#responsebody) > `readonly` `optional` **responseBody**: `unknown` Defined in: [packages/core/src/errors.ts:60](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L60) *** ### consecutiveFailures [Section titled “consecutiveFailures”](#consecutivefailures) > `readonly` **consecutiveFailures**: `number` Defined in: [packages/core/src/errors.ts:61](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L61) *** ### details [Section titled “details”](#details) > `readonly` **details**: [`PrefactorShutdownDetails`](../type-aliases/PrefactorShutdownDetails.md) Defined in: [packages/core/src/errors.ts:62](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L62) *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: node\_modules/.bun/typescript\@5.9.3/node\_modules/typescript/lib/lib.es5.d.ts:1076 #### Inherited from [Section titled “Inherited from”](#inherited-from-5) `Error.name` *** ### message [Section titled “message”](#message-1) > **message**: `string` Defined in: node\_modules/.bun/typescript\@5.9.3/node\_modules/typescript/lib/lib.es5.d.ts:1077 #### Inherited from [Section titled “Inherited from”](#inherited-from-6) `Error.message` *** ### stack? [Section titled “stack?”](#stack) > `optional` **stack**: `string` Defined in: node\_modules/.bun/typescript\@5.9.3/node\_modules/typescript/lib/lib.es5.d.ts:1078 #### Inherited from [Section titled “Inherited from”](#inherited-from-7) `Error.stack` *** ### cause? [Section titled “cause?”](#cause) > `optional` **cause**: `unknown` Defined in: node\_modules/.bun/typescript\@5.9.3/node\_modules/typescript/lib/lib.es2022.error.d.ts:26 The cause of the error. #### Inherited from [Section titled “Inherited from”](#inherited-from-8) `Error.cause` # Class: SpanContext [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / SpanContext # Class: SpanContext [Section titled “Class: SpanContext”](#class-spancontext) Defined in: [packages/core/src/tracing/context.ts:33](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/context.ts#L33) SpanContext manages the current span in async execution contexts. This enables automatic parent-child span relationships without manual tracking. Uses Node.js AsyncLocalStorage which provides async-safe context propagation. ## Example [Section titled “Example”](#example) ```typescript const span = tracer.startSpan({ name: 'parent', ... }); await SpanContext.runAsync(span, async () => { // Inside this function, getCurrent() returns the parent span const parent = SpanContext.getCurrent(); const child = tracer.startSpan({ name: 'child', parentSpanId: parent?.spanId, traceId: parent?.traceId, }); // ... }); ``` ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new SpanContext**(): `SpanContext` #### Returns [Section titled “Returns”](#returns) `SpanContext` ## Methods [Section titled “Methods”](#methods) ### getCurrent() [Section titled “getCurrent()”](#getcurrent) > `static` **getCurrent**(): [`Span`](../interfaces/Span.md) | `undefined` Defined in: [packages/core/src/tracing/context.ts:39](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/context.ts#L39) Get the current span from the async context #### Returns [Section titled “Returns”](#returns-1) [`Span`](../interfaces/Span.md) | `undefined` The current span, or undefined if no span is active *** ### getStack() [Section titled “getStack()”](#getstack) > `static` **getStack**(): [`Span`](../interfaces/Span.md)\[] Defined in: [packages/core/src/tracing/context.ts:47](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/context.ts#L47) Get the full span stack from the async context #### Returns [Section titled “Returns”](#returns-2) [`Span`](../interfaces/Span.md)\[] *** ### enter() [Section titled “enter()”](#enter) > `static` **enter**(`span`): `void` Defined in: [packages/core/src/tracing/context.ts:54](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/context.ts#L54) Push a span onto the stack for the current async context #### Parameters [Section titled “Parameters”](#parameters) ##### span [Section titled “span”](#span) [`Span`](../interfaces/Span.md) #### Returns [Section titled “Returns”](#returns-3) `void` *** ### exit() [Section titled “exit()”](#exit) > `static` **exit**(): `void` Defined in: [packages/core/src/tracing/context.ts:62](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/context.ts#L62) Pop the current span from the stack for the current async context #### Returns [Section titled “Returns”](#returns-4) `void` *** ### run() [Section titled “run()”](#run) > `static` **run**<`T`>(`span`, `fn`): `T` Defined in: [packages/core/src/tracing/context.ts:75](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/context.ts#L75) Run a synchronous function with the given span as the current context #### Type Parameters [Section titled “Type Parameters”](#type-parameters) ##### T [Section titled “T”](#t) `T` #### Parameters [Section titled “Parameters”](#parameters-1) ##### span [Section titled “span”](#span-1) [`Span`](../interfaces/Span.md) The span to set as current ##### fn [Section titled “fn”](#fn) () => `T` The function to execute #### Returns [Section titled “Returns”](#returns-5) `T` The return value of the function *** ### runAsync() [Section titled “runAsync()”](#runasync) > `static` **runAsync**<`T`>(`span`, `fn`): `Promise`<`T`> Defined in: [packages/core/src/tracing/context.ts:93](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/context.ts#L93) Run an asynchronous function with the given span as the current context #### Type Parameters [Section titled “Type Parameters”](#type-parameters-1) ##### T [Section titled “T”](#t-1) `T` #### Parameters [Section titled “Parameters”](#parameters-2) ##### span [Section titled “span”](#span-2) [`Span`](../interfaces/Span.md) The span to set as current ##### fn [Section titled “fn”](#fn-1) () => `Promise`<`T`> The async function to execute #### Returns [Section titled “Returns”](#returns-6) `Promise`<`T`> A promise resolving to the return value of the function *** ### clear() [Section titled “clear()”](#clear) > `static` **clear**(): `void` Defined in: [packages/core/src/tracing/context.ts:107](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/context.ts#L107) Clear the current context (primarily for testing) #### Returns [Section titled “Returns”](#returns-7) `void` # Class: TerminationMonitor [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / TerminationMonitor # Class: TerminationMonitor [Section titled “Class: TerminationMonitor”](#class-terminationmonitor) Defined in: [packages/core/src/monitoring/termination-monitor.ts:22](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/monitoring/termination-monitor.ts#L22) Monitors a p2 agent instance for external termination. Primary detection: the transport calls `detectTermination()` whenever a span create or finish response contains a control signal. This is fast (detected on the next span API response) and has zero overhead. Fallback detection: slow polling at `pollIntervalMs` (default 30s) covers idle agents that are not actively emitting spans. ## Accessors [Section titled “Accessors”](#accessors) ### signal [Section titled “signal”](#signal) #### Get Signature [Section titled “Get Signature”](#get-signature) > **get** **signal**(): `AbortSignal` Defined in: [packages/core/src/monitoring/termination-monitor.ts:94](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/monitoring/termination-monitor.ts#L94) ##### Returns [Section titled “Returns”](#returns) `AbortSignal` *** ### terminated [Section titled “terminated”](#terminated) #### Get Signature [Section titled “Get Signature”](#get-signature-1) > **get** **terminated**(): `boolean` Defined in: [packages/core/src/monitoring/termination-monitor.ts:98](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/monitoring/termination-monitor.ts#L98) ##### Returns [Section titled “Returns”](#returns-1) `boolean` ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new TerminationMonitor**(`httpClient`, `getAgentInstanceId`, `pollIntervalMs?`): `TerminationMonitor` Defined in: [packages/core/src/monitoring/termination-monitor.ts:37](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/monitoring/termination-monitor.ts#L37) #### Parameters [Section titled “Parameters”](#parameters) ##### httpClient [Section titled “httpClient”](#httpclient) [`HttpRequester`](../interfaces/HttpRequester.md) ##### getAgentInstanceId [Section titled “getAgentInstanceId”](#getagentinstanceid) () => `string` | `null` ##### pollIntervalMs? [Section titled “pollIntervalMs?”](#pollintervalms) `number` = `30_000` #### Returns [Section titled “Returns”](#returns-2) `TerminationMonitor` ## Methods [Section titled “Methods”](#methods) ### detectTermination() [Section titled “detectTermination()”](#detecttermination) > **detectTermination**(`reason`): `void` Defined in: [packages/core/src/monitoring/termination-monitor.ts:47](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/monitoring/termination-monitor.ts#L47) Primary termination path — called by the transport when a span response contains a control signal. No polling latency. #### Parameters [Section titled “Parameters”](#parameters-1) ##### reason [Section titled “reason”](#reason) `string` | `null` #### Returns [Section titled “Returns”](#returns-3) `void` *** ### sync() [Section titled “sync()”](#sync) > **sync**(): `void` Defined in: [packages/core/src/monitoring/termination-monitor.ts:57](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/monitoring/termination-monitor.ts#L57) Drives the fallback poll lifecycle. Call periodically (e.g., every 1s) to start or stop polling based on whether an agent instance ID is known. #### Returns [Section titled “Returns”](#returns-4) `void` *** ### onTerminated() [Section titled “onTerminated()”](#onterminated) > **onTerminated**(`callback`): () => `void` Defined in: [packages/core/src/monitoring/termination-monitor.ts:87](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/monitoring/termination-monitor.ts#L87) #### Parameters [Section titled “Parameters”](#parameters-2) ##### callback [Section titled “callback”](#callback) [`TerminationCallback`](../type-aliases/TerminationCallback.md) #### Returns [Section titled “Returns”](#returns-5) > (): `void` ##### Returns [Section titled “Returns”](#returns-6) `void` *** ### reset() [Section titled “reset()”](#reset) > **reset**(): `void` Defined in: [packages/core/src/monitoring/termination-monitor.ts:107](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/monitoring/termination-monitor.ts#L107) Resets the monitor for a new agent run. Clears terminated state, creates a fresh AbortSignal, and stops any in-progress fallback polling. Registered callbacks are preserved. #### Returns [Section titled “Returns”](#returns-7) `void` *** ### destroy() [Section titled “destroy()”](#destroy) > **destroy**(): `void` Defined in: [packages/core/src/monitoring/termination-monitor.ts:117](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/monitoring/termination-monitor.ts#L117) #### Returns [Section titled “Returns”](#returns-8) `void` # Class: Tracer [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / Tracer # Class: Tracer [Section titled “Class: Tracer”](#class-tracer) Defined in: [packages/core/src/tracing/tracer.ts:69](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L69) Tracer manages the lifecycle of spans. The tracer is responsible for: * Creating spans with unique IDs * Managing span lifecycle (start/end) * Delegating to the transport layer for span emission * Handling agent instance lifecycle ## Example [Section titled “Example”](#example) ```typescript const tracer = new Tracer(transport); const span = tracer.startSpan({ name: 'llm-call', spanType: SpanType.LLM, inputs: { prompt: 'Hello' } }); try { // ... do work ... tracer.endSpan(span, { outputs: { response: 'Hi!' } }); } catch (error) { tracer.endSpan(span, { error }); } ``` ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new Tracer**(`transport`, `partition?`): `Tracer` Defined in: [packages/core/src/tracing/tracer.ts:78](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L78) Initialize the tracer. #### Parameters [Section titled “Parameters”](#parameters) ##### transport [Section titled “transport”](#transport) [`Transport`](../interfaces/Transport.md) The transport to use for emitting spans ##### partition? [Section titled “partition?”](#partition) `number` The partition for ID generation. If not provided, a random partition will be generated. #### Returns [Section titled “Returns”](#returns) `Tracer` ## Methods [Section titled “Methods”](#methods) ### startSpan() [Section titled “startSpan()”](#startspan) > **startSpan**(`options`): [`Span`](../interfaces/Span.md) Defined in: [packages/core/src/tracing/tracer.ts:91](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L91) Start a new span #### Parameters [Section titled “Parameters”](#parameters-1) ##### options [Section titled “options”](#options) [`StartSpanOptions`](../interfaces/StartSpanOptions.md) Span configuration options #### Returns [Section titled “Returns”](#returns-1) [`Span`](../interfaces/Span.md) The created span *** ### endSpan() [Section titled “endSpan()”](#endspan) > **endSpan**(`span`, `options?`): `void` Defined in: [packages/core/src/tracing/tracer.ts:132](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L132) End a span and emit it to the transport #### Parameters [Section titled “Parameters”](#parameters-2) ##### span [Section titled “span”](#span) [`Span`](../interfaces/Span.md) The span to end ##### options? [Section titled “options?”](#options-1) [`EndSpanOptions`](../interfaces/EndSpanOptions.md) End span options (outputs, error, token usage) #### Returns [Section titled “Returns”](#returns-2) `void` *** ### close() [Section titled “close()”](#close) > **close**(): `Promise`<`void`> Defined in: [packages/core/src/tracing/tracer.ts:173](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L173) Close the tracer and flush any pending spans #### Returns [Section titled “Returns”](#returns-3) `Promise`<`void`> Promise that resolves when the tracer is closed *** ### startAgentInstance() [Section titled “startAgentInstance()”](#startagentinstance) > **startAgentInstance**(): `void` Defined in: [packages/core/src/tracing/tracer.ts:177](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L177) #### Returns [Section titled “Returns”](#returns-4) `void` *** ### finishAgentInstance() [Section titled “finishAgentInstance()”](#finishagentinstance) > **finishAgentInstance**(): `void` Defined in: [packages/core/src/tracing/tracer.ts:185](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L185) #### Returns [Section titled “Returns”](#returns-5) `void` # Enumeration: SpanStatus [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / SpanStatus # Enumeration: SpanStatus [Section titled “Enumeration: SpanStatus”](#enumeration-spanstatus) Defined in: [packages/core/src/tracing/span.ts:29](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L29) Status of a span ## Enumeration Members [Section titled “Enumeration Members”](#enumeration-members) ### RUNNING [Section titled “RUNNING”](#running) > **RUNNING**: `"running"` Defined in: [packages/core/src/tracing/span.ts:30](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L30) *** ### SUCCESS [Section titled “SUCCESS”](#success) > **SUCCESS**: `"success"` Defined in: [packages/core/src/tracing/span.ts:31](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L31) *** ### ERROR [Section titled “ERROR”](#error) > **ERROR**: `"error"` Defined in: [packages/core/src/tracing/span.ts:32](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L32) # Function: buildRuntimeEnvironment() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / buildRuntimeEnvironment # Function: buildRuntimeEnvironment() [Section titled “Function: buildRuntimeEnvironment()”](#function-buildruntimeenvironment) > **buildRuntimeEnvironment**(`sdkHeaderEntry?`): [`RuntimeEnvironment`](../type-aliases/RuntimeEnvironment.md) Defined in: [packages/core/src/runtime-environment.ts:32](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/runtime-environment.ts#L32) Builds the `runtime_environment` object for `agent_version` registration. Parses `sdkHeaderEntry` (a space-separated list of `"pkg@ver"` tokens set by upstream adaptors) into `agent_sdk` entries, stripping the core SDK self-entry. Always includes `prefactor_sdk`, `os`, and `runtime`. ## Parameters [Section titled “Parameters”](#parameters) ### sdkHeaderEntry? [Section titled “sdkHeaderEntry?”](#sdkheaderentry) `string` Space-separated SDK header string set by upstream adaptors (e.g. `"@prefactor/langchain@2.0.0"`). The core self-entry (`@prefactor/core@...`) is automatically stripped from `agent_sdk`. ## Returns [Section titled “Returns”](#returns) [`RuntimeEnvironment`](../type-aliases/RuntimeEnvironment.md) Runtime environment metadata for the `agent_version` payload. # Function: configureLogging() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / configureLogging # Function: configureLogging() [Section titled “Function: configureLogging()”](#function-configurelogging) > **configureLogging**(): `void` Defined in: [packages/core/src/utils/logging.ts:76](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/utils/logging.ts#L76) Configure logging based on environment variables ## Returns [Section titled “Returns”](#returns) `void` # Function: createConfig() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / createConfig # Function: createConfig() [Section titled “Function: createConfig()”](#function-createconfig) > **createConfig**(`options?`): `object` Defined in: [packages/core/src/config.ts:135](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/config.ts#L135) Creates a validated configuration object by merging provided options with environment variables and defaults. ## Parameters [Section titled “Parameters”](#parameters) ### options? [Section titled “options?”](#options) `Partial`<{ `transportType`: `"http"`; `sampleRate`: `number`; `captureInputs`: `boolean`; `captureOutputs`: `boolean`; `maxInputLength`: `number`; `maxOutputLength`: `number`; `httpConfig?`: { `apiUrl`: `string`; `apiToken`: `string`; `agentId?`: `string`; `agentIdentifier?`: `string`; `agentName?`: `string`; `agentDescription?`: `string`; `agentSchema?`: `Record`<`string`, `unknown`>; `requestTimeout?`: `number`; `maxRetries?`: `number`; `initialRetryDelay?`: `number`; `maxRetryDelay?`: `number`; `retryMultiplier?`: `number`; `retryOnStatusCodes?`: `number`\[]; }; `failureHandling?`: { `onFatalError?`: (`error`) => `void`; }; }> Partial configuration options ## Returns [Section titled “Returns”](#returns) Validated configuration object ### transportType [Section titled “transportType”](#transporttype) > **transportType**: `"http"` Transport type to use for span emission ### sampleRate [Section titled “sampleRate”](#samplerate) > **sampleRate**: `number` Sampling rate (0.0 to 1.0) ### captureInputs [Section titled “captureInputs”](#captureinputs) > **captureInputs**: `boolean` Whether to capture span inputs ### captureOutputs [Section titled “captureOutputs”](#captureoutputs) > **captureOutputs**: `boolean` Whether to capture span outputs ### maxInputLength [Section titled “maxInputLength”](#maxinputlength) > **maxInputLength**: `number` Maximum length for input strings ### maxOutputLength [Section titled “maxOutputLength”](#maxoutputlength) > **maxOutputLength**: `number` Maximum length for output strings ### httpConfig? [Section titled “httpConfig?”](#httpconfig) > `optional` **httpConfig**: `object` HTTP transport configuration (required if transportType is ‘http’) #### httpConfig.apiUrl [Section titled “httpConfig.apiUrl”](#httpconfigapiurl) > **apiUrl**: `string` #### httpConfig.apiToken [Section titled “httpConfig.apiToken”](#httpconfigapitoken) > **apiToken**: `string` #### httpConfig.agentId? [Section titled “httpConfig.agentId?”](#httpconfigagentid) > `optional` **agentId**: `string` #### httpConfig.agentIdentifier? [Section titled “httpConfig.agentIdentifier?”](#httpconfigagentidentifier) > `optional` **agentIdentifier**: `string` #### httpConfig.agentName? [Section titled “httpConfig.agentName?”](#httpconfigagentname) > `optional` **agentName**: `string` #### httpConfig.agentDescription? [Section titled “httpConfig.agentDescription?”](#httpconfigagentdescription) > `optional` **agentDescription**: `string` #### httpConfig.agentSchema? [Section titled “httpConfig.agentSchema?”](#httpconfigagentschema) > `optional` **agentSchema**: `Record`<`string`, `unknown`> #### httpConfig.requestTimeout? [Section titled “httpConfig.requestTimeout?”](#httpconfigrequesttimeout) > `optional` **requestTimeout**: `number` #### httpConfig.maxRetries? [Section titled “httpConfig.maxRetries?”](#httpconfigmaxretries) > `optional` **maxRetries**: `number` #### httpConfig.initialRetryDelay? [Section titled “httpConfig.initialRetryDelay?”](#httpconfiginitialretrydelay) > `optional` **initialRetryDelay**: `number` #### httpConfig.maxRetryDelay? [Section titled “httpConfig.maxRetryDelay?”](#httpconfigmaxretrydelay) > `optional` **maxRetryDelay**: `number` #### httpConfig.retryMultiplier? [Section titled “httpConfig.retryMultiplier?”](#httpconfigretrymultiplier) > `optional` **retryMultiplier**: `number` #### httpConfig.retryOnStatusCodes? [Section titled “httpConfig.retryOnStatusCodes?”](#httpconfigretryonstatuscodes) > `optional` **retryOnStatusCodes**: `number`\[] ### failureHandling? [Section titled “failureHandling?”](#failurehandling) > `optional` **failureHandling**: `object` Optional failure handling callbacks. #### failureHandling.onFatalError()? [Section titled “failureHandling.onFatalError()?”](#failurehandlingonfatalerror) > `optional` **onFatalError**: (`error`) => `void` ##### Parameters [Section titled “Parameters”](#parameters-1) ###### error [Section titled “error”](#error) [`PrefactorFatalError`](../classes/PrefactorFatalError.md) ##### Returns [Section titled “Returns”](#returns-1) `void` ## Throws [Section titled “Throws”](#throws) If configuration is invalid ## Example [Section titled “Example”](#example) ```typescript const config = createConfig({ transportType: 'http', httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, } }); ``` # Function: createCore() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / createCore # Function: createCore() [Section titled “Function: createCore()”](#function-createcore) > **createCore**(`config`, `options?`): [`CoreRuntime`](../type-aliases/CoreRuntime.md) Defined in: [packages/core/src/create-core.ts:30](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/create-core.ts#L30) Creates a fully initialized core runtime from validated SDK configuration. ## Parameters [Section titled “Parameters”](#parameters) ### config [Section titled “config”](#config) Resolved SDK configuration. #### transportType [Section titled “transportType”](#transporttype) `"http"` = `...` Transport type to use for span emission #### sampleRate [Section titled “sampleRate”](#samplerate) `number` = `...` Sampling rate (0.0 to 1.0) #### captureInputs [Section titled “captureInputs”](#captureinputs) `boolean` = `...` Whether to capture span inputs #### captureOutputs [Section titled “captureOutputs”](#captureoutputs) `boolean` = `...` Whether to capture span outputs #### maxInputLength [Section titled “maxInputLength”](#maxinputlength) `number` = `...` Maximum length for input strings #### maxOutputLength [Section titled “maxOutputLength”](#maxoutputlength) `number` = `...` Maximum length for output strings #### httpConfig? [Section titled “httpConfig?”](#httpconfig) { `apiUrl`: `string`; `apiToken`: `string`; `agentId?`: `string`; `agentIdentifier?`: `string`; `agentName?`: `string`; `agentDescription?`: `string`; `agentSchema?`: `Record`<`string`, `unknown`>; `requestTimeout?`: `number`; `maxRetries?`: `number`; `initialRetryDelay?`: `number`; `maxRetryDelay?`: `number`; `retryMultiplier?`: `number`; `retryOnStatusCodes?`: `number`\[]; } = `...` HTTP transport configuration (required if transportType is ‘http’) #### httpConfig.apiUrl [Section titled “httpConfig.apiUrl”](#httpconfigapiurl) `string` = `...` #### httpConfig.apiToken [Section titled “httpConfig.apiToken”](#httpconfigapitoken) `string` = `...` #### httpConfig.agentId? [Section titled “httpConfig.agentId?”](#httpconfigagentid) `string` = `...` #### httpConfig.agentIdentifier? [Section titled “httpConfig.agentIdentifier?”](#httpconfigagentidentifier) `string` = `...` #### httpConfig.agentName? [Section titled “httpConfig.agentName?”](#httpconfigagentname) `string` = `...` #### httpConfig.agentDescription? [Section titled “httpConfig.agentDescription?”](#httpconfigagentdescription) `string` = `...` #### httpConfig.agentSchema? [Section titled “httpConfig.agentSchema?”](#httpconfigagentschema) `Record`<`string`, `unknown`> = `...` #### httpConfig.requestTimeout? [Section titled “httpConfig.requestTimeout?”](#httpconfigrequesttimeout) `number` = `...` #### httpConfig.maxRetries? [Section titled “httpConfig.maxRetries?”](#httpconfigmaxretries) `number` = `...` #### httpConfig.initialRetryDelay? [Section titled “httpConfig.initialRetryDelay?”](#httpconfiginitialretrydelay) `number` = `...` #### httpConfig.maxRetryDelay? [Section titled “httpConfig.maxRetryDelay?”](#httpconfigmaxretrydelay) `number` = `...` #### httpConfig.retryMultiplier? [Section titled “httpConfig.retryMultiplier?”](#httpconfigretrymultiplier) `number` = `...` #### httpConfig.retryOnStatusCodes? [Section titled “httpConfig.retryOnStatusCodes?”](#httpconfigretryonstatuscodes) `number`\[] = `...` #### failureHandling? [Section titled “failureHandling?”](#failurehandling) { `onFatalError?`: (`error`) => `void`; } = `...` Optional failure handling callbacks. #### failureHandling.onFatalError? [Section titled “failureHandling.onFatalError?”](#failurehandlingonfatalerror) (`error`) => `void` = `...` ### options? [Section titled “options?”](#options) [`CreateCoreOptions`](../type-aliases/CreateCoreOptions.md) = `{}` Optional runtime construction options. ## Returns [Section titled “Returns”](#returns) [`CoreRuntime`](../type-aliases/CoreRuntime.md) Runtime containing tracer, agent manager, and shutdown function. # Function: createSpanTypePrefixer() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / createSpanTypePrefixer # Function: createSpanTypePrefixer() [Section titled “Function: createSpanTypePrefixer()”](#function-createspantypeprefixer) > **createSpanTypePrefixer**(`namespace`): (`spanType`) => `string` Defined in: [packages/core/src/tracing/span.ts:22](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L22) Creates a helper that prefixes span types with a package/provider namespace. ## Parameters [Section titled “Parameters”](#parameters) ### namespace [Section titled “namespace”](#namespace) `string` Namespace to prepend, such as `langchain`. ## Returns [Section titled “Returns”](#returns) Function that produces `${namespace}:${spanType}`. > (`spanType`): `string` ### Parameters [Section titled “Parameters”](#parameters-1) #### spanType [Section titled “spanType”](#spantype) `string` ### Returns [Section titled “Returns”](#returns-1) `string` # Function: getClient() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / getClient # Function: getClient() [Section titled “Function: getClient()”](#function-getclient) > **getClient**(): [`PrefactorClient`](../classes/PrefactorClient.md)<`unknown`> | `null` Defined in: [packages/core/src/client.ts:299](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L299) Returns the currently initialized global Prefactor client, if any. ## Returns [Section titled “Returns”](#returns) [`PrefactorClient`](../classes/PrefactorClient.md)<`unknown`> | `null` Active global client or `null`. # Function: getLogger() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / getLogger # Function: getLogger() [Section titled “Function: getLogger()”](#function-getlogger) > **getLogger**(`namespace`): `Logger` Defined in: [packages/core/src/utils/logging.ts:69](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/utils/logging.ts#L69) Get a logger instance for a specific namespace ## Parameters [Section titled “Parameters”](#parameters) ### namespace [Section titled “namespace”](#namespace) `string` The namespace for this logger ## Returns [Section titled “Returns”](#returns) `Logger` Logger instance # Function: init() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / init # Function: init() [Section titled “Function: init()”](#function-init) > **init**<`TMiddleware`>(`options`): [`PrefactorClient`](../classes/PrefactorClient.md)<`TMiddleware`> Defined in: [packages/core/src/client.ts:221](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L221) Initializes and returns the process-wide Prefactor client singleton. Repeated calls return the same client instance until it is shut down. ## Type Parameters [Section titled “Type Parameters”](#type-parameters) ### TMiddleware [Section titled “TMiddleware”](#tmiddleware) `TMiddleware` = `unknown` ## Parameters [Section titled “Parameters”](#parameters) ### options [Section titled “options”](#options) [`PrefactorOptions`](../interfaces/PrefactorOptions.md)<`TMiddleware`> Initialization options. ## Returns [Section titled “Returns”](#returns) [`PrefactorClient`](../classes/PrefactorClient.md)<`TMiddleware`> Global Prefactor client instance. # Function: normalizeAgentToolSchemas() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / normalizeAgentToolSchemas # Function: normalizeAgentToolSchemas() [Section titled “Function: normalizeAgentToolSchemas()”](#function-normalizeagenttoolschemas) > **normalizeAgentToolSchemas**(`agentSchema`, `__namedParameters`): `NormalizedAgentToolSchemas` Defined in: [packages/core/src/tool-schema.ts:18](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tool-schema.ts#L18) ## Parameters [Section titled “Parameters”](#parameters) ### agentSchema [Section titled “agentSchema”](#agentschema) `Record`<`string`, `unknown`> | `undefined` ### \_\_namedParameters [Section titled “\_\_namedParameters”](#__namedparameters) #### defaultAgentSchema [Section titled “defaultAgentSchema”](#defaultagentschema) `Record`<`string`, `unknown`> #### providerName [Section titled “providerName”](#providername) `string` ## Returns [Section titled “Returns”](#returns) `NormalizedAgentToolSchemas` # Function: registerShutdownHandler() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / registerShutdownHandler # Function: registerShutdownHandler() [Section titled “Function: registerShutdownHandler()”](#function-registershutdownhandler) > **registerShutdownHandler**(`key`, `handler`): () => `void` Defined in: [packages/core/src/lifecycle.ts:23](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/lifecycle.ts#L23) Registers a shutdown hook for package-level cleanup. ## Parameters [Section titled “Parameters”](#parameters) ### key [Section titled “key”](#key) `string` Unique identifier for the handler. ### handler [Section titled “handler”](#handler) () => `void` | `Promise`<`void`> Cleanup callback executed during `shutdown()`. ## Returns [Section titled “Returns”](#returns) Function that unregisters the handler. > (): `void` ### Returns [Section titled “Returns”](#returns-1) `void` # Function: resolveMappedSpanType() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / resolveMappedSpanType # Function: resolveMappedSpanType() [Section titled “Function: resolveMappedSpanType()”](#function-resolvemappedspantype) > **resolveMappedSpanType**(`toolName`, `toolSpanTypes`, `defaultSpanType`): `string` Defined in: [packages/core/src/tool-schema.ts:36](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tool-schema.ts#L36) ## Parameters [Section titled “Parameters”](#parameters) ### toolName [Section titled “toolName”](#toolname) `string` ### toolSpanTypes [Section titled “toolSpanTypes”](#toolspantypes) `Record`<`string`, `string`> | `undefined` ### defaultSpanType [Section titled “defaultSpanType”](#defaultspantype) `string` ## Returns [Section titled “Returns”](#returns) `string` # Function: serializeValue() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / serializeValue # Function: serializeValue() [Section titled “Function: serializeValue()”](#function-serializevalue) > **serializeValue**(`value`, `maxLength?`): `unknown` Defined in: [packages/core/src/utils/serialization.ts:29](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/utils/serialization.ts#L29) Serialize a value for JSON output, handling non-serializable types and truncating long strings ## Parameters [Section titled “Parameters”](#parameters) ### value [Section titled “value”](#value) `unknown` Value to serialize ### maxLength? [Section titled “maxLength?”](#maxlength) Maximum length for strings (null for no truncation) `number` | `null` ## Returns [Section titled “Returns”](#returns) `unknown` Serialized value ## Example [Section titled “Example”](#example) ```typescript const serialized = serializeValue({ message: 'Hello'.repeat(1000) }, 100); // Result: { message: 'HelloHelloHello... [truncated]' } ``` # Function: shutdown() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / shutdown # Function: shutdown() [Section titled “Function: shutdown()”](#function-shutdown) > **shutdown**(): `Promise`<`void`> Defined in: [packages/core/src/lifecycle.ts:34](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/lifecycle.ts#L34) Executes all registered shutdown hooks and then closes the active runtime. ## Returns [Section titled “Returns”](#returns) `Promise`<`void`> # Function: truncateString() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / truncateString # Function: truncateString() [Section titled “Function: truncateString()”](#function-truncatestring) > **truncateString**(`value`, `maxLength`): `string` Defined in: [packages/core/src/utils/serialization.ts:8](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/utils/serialization.ts#L8) Truncate a string to a maximum length, adding an ellipsis if truncated ## Parameters [Section titled “Parameters”](#parameters) ### value [Section titled “value”](#value) `string` The string to truncate ### maxLength [Section titled “maxLength”](#maxlength) `number` Maximum length ## Returns [Section titled “Returns”](#returns) `string` Truncated string # Function: withSpan() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / withSpan # Function: withSpan() [Section titled “Function: withSpan()”](#function-withspan) Wraps sync/async work in a span and automatically captures outputs or errors. ## Call Signature [Section titled “Call Signature”](#call-signature) > **withSpan**<`T`>(`tracer`, `options`, `fn`): `Promise`<`T`> Defined in: [packages/core/src/tracing/with-span.ts:12](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/with-span.ts#L12) Runs work inside a new span using an explicit tracer. ### Type Parameters [Section titled “Type Parameters”](#type-parameters) #### T [Section titled “T”](#t) `T` ### Parameters [Section titled “Parameters”](#parameters) #### tracer [Section titled “tracer”](#tracer) [`Tracer`](../classes/Tracer.md) Tracer to use for span lifecycle. #### options [Section titled “options”](#options) [`StartSpanOptions`](../interfaces/StartSpanOptions.md) Span creation options. #### fn [Section titled “fn”](#fn) () => `T` | `Promise`<`T`> Work to execute within the span context. ### Returns [Section titled “Returns”](#returns) `Promise`<`T`> ## Call Signature [Section titled “Call Signature”](#call-signature-1) > **withSpan**<`T`>(`options`, `fn`): `Promise`<`T`> Defined in: [packages/core/src/tracing/with-span.ts:26](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/with-span.ts#L26) Runs work inside a new span using the globally active tracer. Throws when no active tracer exists. ### Type Parameters [Section titled “Type Parameters”](#type-parameters-1) #### T [Section titled “T”](#t-1) `T` ### Parameters [Section titled “Parameters”](#parameters-1) #### options [Section titled “options”](#options-1) [`StartSpanOptions`](../interfaces/StartSpanOptions.md) Span creation options. #### fn [Section titled “fn”](#fn-1) () => `T` | `Promise`<`T`> Work to execute within the span context. ### Returns [Section titled “Returns”](#returns-1) `Promise`<`T`> # Interface: ActionProfile [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / ActionProfile # Interface: ActionProfile [Section titled “Interface: ActionProfile”](#interface-actionprofile) Defined in: [packages/core/src/tracing/data-risk.ts:25](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L25) Describes which data-mutating or communicating actions a span type is permitted to perform. ## Properties [Section titled “Properties”](#properties) ### create\_data [Section titled “create\_data”](#create_data) > **create\_data**: [`ActionProfileValue`](../type-aliases/ActionProfileValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:26](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L26) *** ### read\_data [Section titled “read\_data”](#read_data) > **read\_data**: [`ActionProfileValue`](../type-aliases/ActionProfileValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:27](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L27) *** ### update\_data [Section titled “update\_data”](#update_data) > **update\_data**: [`ActionProfileValue`](../type-aliases/ActionProfileValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:28](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L28) *** ### destroy\_data [Section titled “destroy\_data”](#destroy_data) > **destroy\_data**: [`ActionProfileValue`](../type-aliases/ActionProfileValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:29](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L29) *** ### financial\_transactions [Section titled “financial\_transactions”](#financial_transactions) > **financial\_transactions**: [`ActionProfileValue`](../type-aliases/ActionProfileValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:30](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L30) *** ### external\_communication [Section titled “external\_communication”](#external_communication) > **external\_communication**: [`ActionProfileValue`](../type-aliases/ActionProfileValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:31](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L31) # Interface: AgentSchemaVersion [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentSchemaVersion # Interface: AgentSchemaVersion [Section titled “Interface: AgentSchemaVersion”](#interface-agentschemaversion) Defined in: [packages/core/src/tracing/span-schema.ts:52](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L52) Agent schema version payload sent during agent instance registration. Contains the set of span type schemas that define this agent’s tracing contract. ## Properties [Section titled “Properties”](#properties) ### external\_identifier [Section titled “external\_identifier”](#external_identifier) > **external\_identifier**: `string` Defined in: [packages/core/src/tracing/span-schema.ts:54](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L54) External identifier for this schema version (e.g. a semver string or content hash). *** ### span\_type\_schemas [Section titled “span\_type\_schemas”](#span_type_schemas) > **span\_type\_schemas**: [`SpanTypeSchema`](SpanTypeSchema.md)\[] Defined in: [packages/core/src/tracing/span-schema.ts:56](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L56) Array of span type schema definitions. *** ### quality\_schemas? [Section titled “quality\_schemas?”](#quality_schemas) > `optional` **quality\_schemas**: [`QualitySchema`](QualitySchema.md)\[] Defined in: [packages/core/src/tracing/span-schema.ts:58](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L58) Named quality schemas for instance evaluations. # Interface: DataCategories [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / DataCategories # Interface: DataCategories [Section titled “Interface: DataCategories”](#interface-datacategories) Defined in: [packages/core/src/tracing/data-risk.ts:37](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L37) Classifies the sensitivity of data flowing through a span’s params or results. ## Properties [Section titled “Properties”](#properties) ### classification [Section titled “classification”](#classification) > **classification**: [`DataClassification`](../type-aliases/DataClassification.md) Defined in: [packages/core/src/tracing/data-risk.ts:38](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L38) *** ### personal\_identifiers [Section titled “personal\_identifiers”](#personal_identifiers) > **personal\_identifiers**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:39](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L39) *** ### contact\_information [Section titled “contact\_information”](#contact_information) > **contact\_information**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:40](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L40) *** ### financial\_information [Section titled “financial\_information”](#financial_information) > **financial\_information**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:41](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L41) *** ### health\_and\_medical [Section titled “health\_and\_medical”](#health_and_medical) > **health\_and\_medical**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:42](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L42) *** ### criminal\_justice [Section titled “criminal\_justice”](#criminal_justice) > **criminal\_justice**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:43](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L43) *** ### authentication\_and\_secrets [Section titled “authentication\_and\_secrets”](#authentication_and_secrets) > **authentication\_and\_secrets**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:44](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L44) *** ### organisational\_confidential [Section titled “organisational\_confidential”](#organisational_confidential) > **organisational\_confidential**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:45](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L45) *** ### minors\_data [Section titled “minors\_data”](#minors_data) > **minors\_data**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:46](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L46) *** ### location\_and\_tracking [Section titled “location\_and\_tracking”](#location_and_tracking) > **location\_and\_tracking**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:47](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L47) *** ### behavioural\_and\_inferred [Section titled “behavioural\_and\_inferred”](#behavioural_and_inferred) > **behavioural\_and\_inferred**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:48](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L48) *** ### gdpr\_racial\_or\_ethnic\_origin [Section titled “gdpr\_racial\_or\_ethnic\_origin”](#gdpr_racial_or_ethnic_origin) > **gdpr\_racial\_or\_ethnic\_origin**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:49](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L49) *** ### gdpr\_political\_opinions [Section titled “gdpr\_political\_opinions”](#gdpr_political_opinions) > **gdpr\_political\_opinions**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:50](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L50) *** ### gdpr\_religious\_or\_philosophical\_beliefs [Section titled “gdpr\_religious\_or\_philosophical\_beliefs”](#gdpr_religious_or_philosophical_beliefs) > **gdpr\_religious\_or\_philosophical\_beliefs**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:51](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L51) *** ### gdpr\_trade\_union\_membership [Section titled “gdpr\_trade\_union\_membership”](#gdpr_trade_union_membership) > **gdpr\_trade\_union\_membership**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:52](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L52) *** ### gdpr\_genetic\_data [Section titled “gdpr\_genetic\_data”](#gdpr_genetic_data) > **gdpr\_genetic\_data**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:53](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L53) *** ### gdpr\_biometric\_for\_identification [Section titled “gdpr\_biometric\_for\_identification”](#gdpr_biometric_for_identification) > **gdpr\_biometric\_for\_identification**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:54](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L54) *** ### gdpr\_sex\_life\_or\_sexual\_orientation [Section titled “gdpr\_sex\_life\_or\_sexual\_orientation”](#gdpr_sex_life_or_sexual_orientation) > **gdpr\_sex\_life\_or\_sexual\_orientation**: [`DataCategoryValue`](../type-aliases/DataCategoryValue.md) Defined in: [packages/core/src/tracing/data-risk.ts:55](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L55) # Interface: DataRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / DataRisk # Interface: DataRisk [Section titled “Interface: DataRisk”](#interface-datarisk) Defined in: [packages/core/src/tracing/data-risk.ts:62](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L62) Risk metadata for a span type, describing allowed actions and data categories present in its params and results. ## Properties [Section titled “Properties”](#properties) ### action\_profile [Section titled “action\_profile”](#action_profile) > **action\_profile**: [`ActionProfile`](ActionProfile.md) Defined in: [packages/core/src/tracing/data-risk.ts:63](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L63) *** ### params\_data\_categories [Section titled “params\_data\_categories”](#params_data_categories) > **params\_data\_categories**: [`DataCategories`](DataCategories.md) Defined in: [packages/core/src/tracing/data-risk.ts:64](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L64) *** ### result\_data\_categories [Section titled “result\_data\_categories”](#result_data_categories) > **result\_data\_categories**: [`DataCategories`](DataCategories.md) Defined in: [packages/core/src/tracing/data-risk.ts:65](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L65) # Interface: EndSpanOptions [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / EndSpanOptions # Interface: EndSpanOptions [Section titled “Interface: EndSpanOptions”](#interface-endspanoptions) Defined in: [packages/core/src/tracing/tracer.ts:31](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L31) Options for ending a span ## Properties [Section titled “Properties”](#properties) ### outputs? [Section titled “outputs?”](#outputs) > `optional` **outputs**: `Record`<`string`, `unknown`> Defined in: [packages/core/src/tracing/tracer.ts:33](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L33) Output data from the operation *** ### error? [Section titled “error?”](#error) > `optional` **error**: `Error` Defined in: [packages/core/src/tracing/tracer.ts:36](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L36) Error that occurred (if any) *** ### tokenUsage? [Section titled “tokenUsage?”](#tokenusage) > `optional` **tokenUsage**: [`TokenUsage`](TokenUsage.md) Defined in: [packages/core/src/tracing/tracer.ts:39](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L39) Token usage information (for LLM calls) # Interface: ErrorInfo [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / ErrorInfo # Interface: ErrorInfo [Section titled “Interface: ErrorInfo”](#interface-errorinfo) Defined in: [packages/core/src/tracing/span.ts:47](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L47) Error information captured when a span fails ## Properties [Section titled “Properties”](#properties) ### errorType [Section titled “errorType”](#errortype) > **errorType**: `string` Defined in: [packages/core/src/tracing/span.ts:48](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L48) *** ### message [Section titled “message”](#message) > **message**: `string` Defined in: [packages/core/src/tracing/span.ts:49](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L49) *** ### stacktrace [Section titled “stacktrace”](#stacktrace) > **stacktrace**: `string` Defined in: [packages/core/src/tracing/span.ts:50](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L50) # Interface: FailureHandlingConfig [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / FailureHandlingConfig # Interface: FailureHandlingConfig [Section titled “Interface: FailureHandlingConfig”](#interface-failurehandlingconfig) Defined in: [packages/core/src/errors.ts:80](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L80) ## Properties [Section titled “Properties”](#properties) ### onFatalError()? [Section titled “onFatalError()?”](#onfatalerror) > `optional` **onFatalError**: (`error`) => `void` Defined in: [packages/core/src/errors.ts:81](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L81) #### Parameters [Section titled “Parameters”](#parameters) ##### error [Section titled “error”](#error) [`PrefactorFatalError`](../classes/PrefactorFatalError.md) #### Returns [Section titled “Returns”](#returns) `void` # Interface: HttpRequester [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / HttpRequester # Interface: HttpRequester [Section titled “Interface: HttpRequester”](#interface-httprequester) Defined in: [packages/core/src/transport/http/http-client.ts:19](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L19) ## Methods [Section titled “Methods”](#methods) ### request() [Section titled “request()”](#request) > **request**<`TResponse`>(`path`, `options?`): `Promise`<`TResponse`> Defined in: [packages/core/src/transport/http/http-client.ts:20](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/http-client.ts#L20) #### Type Parameters [Section titled “Type Parameters”](#type-parameters) ##### TResponse [Section titled “TResponse”](#tresponse) `TResponse` = `unknown` #### Parameters [Section titled “Parameters”](#parameters) ##### path [Section titled “path”](#path) `string` ##### options? [Section titled “options?”](#options) `HttpRequestOptions` #### Returns [Section titled “Returns”](#returns) `Promise`<`TResponse`> # Interface: ManualSpanOptions [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / ManualSpanOptions # Interface: ManualSpanOptions [Section titled “Interface: ManualSpanOptions”](#interface-manualspanoptions) Defined in: [packages/core/src/client.ts:14](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L14) Options for creating a manual span around custom code. ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/core/src/client.ts:16](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L16) Human-readable span name. *** ### spanType [Section titled “spanType”](#spantype) > **spanType**: `string` Defined in: [packages/core/src/client.ts:18](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L18) Provider-specific span type identifier. *** ### inputs [Section titled “inputs”](#inputs) > **inputs**: `Record`<`string`, `unknown`> Defined in: [packages/core/src/client.ts:20](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L20) Captured input payload for the span. *** ### metadata? [Section titled “metadata?”](#metadata) > `optional` **metadata**: `Record`<`string`, `unknown`> Defined in: [packages/core/src/client.ts:22](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L22) Optional metadata associated with the span. # Interface: PrefactorOptions\ [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / PrefactorOptions # Interface: PrefactorOptions\ [Section titled “Interface: PrefactorOptions\”](#interface-prefactoroptionstmiddleware) Defined in: [packages/core/src/client.ts:204](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L204) Options for initializing the global Prefactor client. ## Type Parameters [Section titled “Type Parameters”](#type-parameters) ### TMiddleware [Section titled “TMiddleware”](#tmiddleware) `TMiddleware` = [`MiddlewareLike`](../type-aliases/MiddlewareLike.md) ## Properties [Section titled “Properties”](#properties) ### provider [Section titled “provider”](#provider) > **provider**: [`PrefactorProvider`](PrefactorProvider.md)<`TMiddleware`> Defined in: [packages/core/src/client.ts:206](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L206) Provider integration used to create middleware and defaults. *** ### httpConfig? [Section titled “httpConfig?”](#httpconfig) > `optional` **httpConfig**: `object` Defined in: [packages/core/src/client.ts:208](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L208) Optional HTTP configuration overrides for the runtime config. #### apiUrl [Section titled “apiUrl”](#apiurl) > **apiUrl**: `string` #### apiToken [Section titled “apiToken”](#apitoken) > **apiToken**: `string` #### agentId? [Section titled “agentId?”](#agentid) > `optional` **agentId**: `string` #### agentIdentifier? [Section titled “agentIdentifier?”](#agentidentifier) > `optional` **agentIdentifier**: `string` #### agentName? [Section titled “agentName?”](#agentname) > `optional` **agentName**: `string` #### agentDescription? [Section titled “agentDescription?”](#agentdescription) > `optional` **agentDescription**: `string` #### agentSchema? [Section titled “agentSchema?”](#agentschema) > `optional` **agentSchema**: `Record`<`string`, `unknown`> #### requestTimeout? [Section titled “requestTimeout?”](#requesttimeout) > `optional` **requestTimeout**: `number` #### maxRetries? [Section titled “maxRetries?”](#maxretries) > `optional` **maxRetries**: `number` #### initialRetryDelay? [Section titled “initialRetryDelay?”](#initialretrydelay) > `optional` **initialRetryDelay**: `number` #### maxRetryDelay? [Section titled “maxRetryDelay?”](#maxretrydelay) > `optional` **maxRetryDelay**: `number` #### retryMultiplier? [Section titled “retryMultiplier?”](#retrymultiplier) > `optional` **retryMultiplier**: `number` #### retryOnStatusCodes? [Section titled “retryOnStatusCodes?”](#retryonstatuscodes) > `optional` **retryOnStatusCodes**: `number`\[] *** ### failureHandling? [Section titled “failureHandling?”](#failurehandling) > `optional` **failureHandling**: `object` Defined in: [packages/core/src/client.ts:210](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L210) Optional failure handling callbacks for transport errors. #### onFatalError()? [Section titled “onFatalError()?”](#onfatalerror) > `optional` **onFatalError**: (`error`) => `void` ##### Parameters [Section titled “Parameters”](#parameters) ###### error [Section titled “error”](#error) [`PrefactorFatalError`](../classes/PrefactorFatalError.md) ##### Returns [Section titled “Returns”](#returns) `void` # Interface: PrefactorProvider\ [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / PrefactorProvider # Interface: PrefactorProvider\ [Section titled “Interface: PrefactorProvider\”](#interface-prefactorprovidertmiddleware) Defined in: [packages/core/src/client.ts:33](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L33) Provider integration contract for Prefactor SDK clients. ## Type Parameters [Section titled “Type Parameters”](#type-parameters) ### TMiddleware [Section titled “TMiddleware”](#tmiddleware) `TMiddleware` = [`MiddlewareLike`](../type-aliases/MiddlewareLike.md) ## Methods [Section titled “Methods”](#methods) ### createMiddleware() [Section titled “createMiddleware()”](#createmiddleware) > **createMiddleware**(`tracer`, `agentManager`, `config`, `getAbortSignal?`): `TMiddleware` Defined in: [packages/core/src/client.ts:44](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L44) Creates provider middleware bound to the core runtime services. #### Parameters [Section titled “Parameters”](#parameters) ##### tracer [Section titled “tracer”](#tracer) [`Tracer`](../classes/Tracer.md) Runtime tracer used for span creation. ##### agentManager [Section titled “agentManager”](#agentmanager) [`AgentInstanceManager`](../classes/AgentInstanceManager.md) Runtime agent instance manager. ##### config [Section titled “config”](#config) Resolved SDK configuration. ###### transportType [Section titled “transportType”](#transporttype) `"http"` = `...` Transport type to use for span emission ###### sampleRate [Section titled “sampleRate”](#samplerate) `number` = `...` Sampling rate (0.0 to 1.0) ###### captureInputs [Section titled “captureInputs”](#captureinputs) `boolean` = `...` Whether to capture span inputs ###### captureOutputs [Section titled “captureOutputs”](#captureoutputs) `boolean` = `...` Whether to capture span outputs ###### maxInputLength [Section titled “maxInputLength”](#maxinputlength) `number` = `...` Maximum length for input strings ###### maxOutputLength [Section titled “maxOutputLength”](#maxoutputlength) `number` = `...` Maximum length for output strings ###### httpConfig? [Section titled “httpConfig?”](#httpconfig) { `apiUrl`: `string`; `apiToken`: `string`; `agentId?`: `string`; `agentIdentifier?`: `string`; `agentName?`: `string`; `agentDescription?`: `string`; `agentSchema?`: `Record`<`string`, `unknown`>; `requestTimeout?`: `number`; `maxRetries?`: `number`; `initialRetryDelay?`: `number`; `maxRetryDelay?`: `number`; `retryMultiplier?`: `number`; `retryOnStatusCodes?`: `number`\[]; } = `...` HTTP transport configuration (required if transportType is ‘http’) ###### httpConfig.apiUrl [Section titled “httpConfig.apiUrl”](#httpconfigapiurl) `string` = `...` ###### httpConfig.apiToken [Section titled “httpConfig.apiToken”](#httpconfigapitoken) `string` = `...` ###### httpConfig.agentId? [Section titled “httpConfig.agentId?”](#httpconfigagentid) `string` = `...` ###### httpConfig.agentIdentifier? [Section titled “httpConfig.agentIdentifier?”](#httpconfigagentidentifier) `string` = `...` ###### httpConfig.agentName? [Section titled “httpConfig.agentName?”](#httpconfigagentname) `string` = `...` ###### httpConfig.agentDescription? [Section titled “httpConfig.agentDescription?”](#httpconfigagentdescription) `string` = `...` ###### httpConfig.agentSchema? [Section titled “httpConfig.agentSchema?”](#httpconfigagentschema) `Record`<`string`, `unknown`> = `...` ###### httpConfig.requestTimeout? [Section titled “httpConfig.requestTimeout?”](#httpconfigrequesttimeout) `number` = `...` ###### httpConfig.maxRetries? [Section titled “httpConfig.maxRetries?”](#httpconfigmaxretries) `number` = `...` ###### httpConfig.initialRetryDelay? [Section titled “httpConfig.initialRetryDelay?”](#httpconfiginitialretrydelay) `number` = `...` ###### httpConfig.maxRetryDelay? [Section titled “httpConfig.maxRetryDelay?”](#httpconfigmaxretrydelay) `number` = `...` ###### httpConfig.retryMultiplier? [Section titled “httpConfig.retryMultiplier?”](#httpconfigretrymultiplier) `number` = `...` ###### httpConfig.retryOnStatusCodes? [Section titled “httpConfig.retryOnStatusCodes?”](#httpconfigretryonstatuscodes) `number`\[] = `...` ###### failureHandling? [Section titled “failureHandling?”](#failurehandling) { `onFatalError?`: (`error`) => `void`; } = `...` Optional failure handling callbacks. ###### failureHandling.onFatalError? [Section titled “failureHandling.onFatalError?”](#failurehandlingonfatalerror) (`error`) => `void` = `...` ##### getAbortSignal? [Section titled “getAbortSignal?”](#getabortsignal) () => `AbortSignal` Returns the AbortSignal for the current run. Called on each check so a fresh signal is returned after `monitor.reset()`. #### Returns [Section titled “Returns”](#returns) `TMiddleware` Provider middleware consumed by upstream frameworks. ## Properties [Section titled “Properties”](#properties) ### shutdown()? [Section titled “shutdown()?”](#shutdown) > `optional` **shutdown**: () => `void` | `Promise`<`void`> Defined in: [packages/core/src/client.ts:53](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L53) Optional provider-level cleanup hook invoked during client shutdown. #### Returns [Section titled “Returns”](#returns-1) `void` | `Promise`<`void`> *** ### resetForNextRun()? [Section titled “resetForNextRun()?”](#resetfornextrun) > `optional` **resetForNextRun**: () => `void` Defined in: [packages/core/src/client.ts:58](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L58) Optional hook called between agent runs to reset per-run middleware state (e.g. finish the current agent instance and clear instance-started flags). #### Returns [Section titled “Returns”](#returns-2) `void` *** ### getSdkHeaderEntry()? [Section titled “getSdkHeaderEntry()?”](#getsdkheaderentry) > `optional` **getSdkHeaderEntry**: () => `string` | `undefined` Defined in: [packages/core/src/client.ts:64](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L64) Returns the SDK header entry to append to HTTP requests created by the core runtime. #### Returns [Section titled “Returns”](#returns-3) `string` | `undefined` Adapter-specific SDK identifier, or `undefined` to use the core header only. *** ### normalizeAgentSchema()? [Section titled “normalizeAgentSchema()?”](#normalizeagentschema) > `optional` **normalizeAgentSchema**: (`agentSchema`) => `Record`<`string`, `unknown`> | `undefined` Defined in: [packages/core/src/client.ts:71](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L71) Normalizes a user- or provider-authored agent schema before core registers it. #### Parameters [Section titled “Parameters”](#parameters-1) ##### agentSchema [Section titled “agentSchema”](#agentschema) `Record`<`string`, `unknown`> Authored agent schema configuration. #### Returns [Section titled “Returns”](#returns-4) `Record`<`string`, `unknown`> | `undefined` Normalized schema, or `undefined` to leave the input unchanged. *** ### getDefaultAgentSchema()? [Section titled “getDefaultAgentSchema()?”](#getdefaultagentschema) > `optional` **getDefaultAgentSchema**: () => `Record`<`string`, `unknown`> | `undefined` Defined in: [packages/core/src/client.ts:79](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L79) Provides a default agent schema when a user does not supply one. #### Returns [Section titled “Returns”](#returns-5) `Record`<`string`, `unknown`> | `undefined` Agent schema object, or `undefined` when no default is available. # Interface: QualitySchema [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / QualitySchema # Interface: QualitySchema [Section titled “Interface: QualitySchema”](#interface-qualityschema) Defined in: [packages/core/src/tracing/span-schema.ts:33](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L33) Named schema definition for a quality evaluation. Each entry in `AgentSchemaVersion.quality_schemas` carries a name (the key used when recording quality payloads on an agent instance) alongside the JSON schema, optional display metadata, and data-risk fields. Rendered through the same template machinery as span type schemas. ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/core/src/tracing/span-schema.ts:35](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L35) Schema name — the key used when recording quality payloads. *** ### schema [Section titled “schema”](#schema) > **schema**: [`JsonSchema`](../type-aliases/JsonSchema.md) Defined in: [packages/core/src/tracing/span-schema.ts:37](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L37) JSON Schema describing the quality payload shape. *** ### title? [Section titled “title?”](#title) > `optional` **title**: `string` Defined in: [packages/core/src/tracing/span-schema.ts:39](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L39) Human-readable title. Defaults to `name` when omitted. *** ### description? [Section titled “description?”](#description) > `optional` **description**: `string` Defined in: [packages/core/src/tracing/span-schema.ts:41](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L41) Optional human-readable description. *** ### template? [Section titled “template?”](#template) > `optional` **template**: `string` Defined in: [packages/core/src/tracing/span-schema.ts:43](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L43) Liquid template for rendering the quality payload as a human-readable summary. *** ### data\_risk? [Section titled “data\_risk?”](#data_risk) > `optional` **data\_risk**: [`DataRisk`](DataRisk.md) Defined in: [packages/core/src/tracing/span-schema.ts:45](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L45) Risk metadata describing data sensitivity for quality payloads. # Interface: Span [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / Span # Interface: Span [Section titled “Interface: Span”](#interface-span) Defined in: [packages/core/src/tracing/span.ts:56](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L56) A span represents a single operation in a trace ## Properties [Section titled “Properties”](#properties) ### spanId [Section titled “spanId”](#spanid) > **spanId**: `string` Defined in: [packages/core/src/tracing/span.ts:58](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L58) Unique identifier for this span *** ### parentSpanId [Section titled “parentSpanId”](#parentspanid) > **parentSpanId**: `string` | `null` Defined in: [packages/core/src/tracing/span.ts:61](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L61) ID of the parent span, or null if this is a root span *** ### traceId [Section titled “traceId”](#traceid) > **traceId**: `string` Defined in: [packages/core/src/tracing/span.ts:64](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L64) Trace ID shared by all spans in a single trace *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/core/src/tracing/span.ts:67](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L67) Human-readable name for this span *** ### spanType [Section titled “spanType”](#spantype) > **spanType**: `string` Defined in: [packages/core/src/tracing/span.ts:70](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L70) Type of operation this span represents *** ### startTime [Section titled “startTime”](#starttime) > **startTime**: `number` Defined in: [packages/core/src/tracing/span.ts:73](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L73) Start time in milliseconds since Unix epoch *** ### endTime [Section titled “endTime”](#endtime) > **endTime**: `number` | `null` Defined in: [packages/core/src/tracing/span.ts:76](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L76) End time in milliseconds since Unix epoch, or null if still running *** ### status [Section titled “status”](#status) > **status**: [`SpanStatus`](../enumerations/SpanStatus.md) Defined in: [packages/core/src/tracing/span.ts:79](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L79) Current status of the span *** ### inputs [Section titled “inputs”](#inputs) > **inputs**: `Record`<`string`, `unknown`> Defined in: [packages/core/src/tracing/span.ts:82](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L82) Input data for this operation *** ### outputs [Section titled “outputs”](#outputs) > **outputs**: `Record`<`string`, `unknown`> | `null` Defined in: [packages/core/src/tracing/span.ts:85](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L85) Output data from this operation, or null if not completed *** ### tokenUsage [Section titled “tokenUsage”](#tokenusage) > **tokenUsage**: [`TokenUsage`](TokenUsage.md) | `null` Defined in: [packages/core/src/tracing/span.ts:88](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L88) Token usage for LLM calls, or null if not applicable *** ### error [Section titled “error”](#error) > **error**: [`ErrorInfo`](ErrorInfo.md) | `null` Defined in: [packages/core/src/tracing/span.ts:91](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L91) Error information if the span failed, or null if successful *** ### metadata [Section titled “metadata”](#metadata) > **metadata**: `Record`<`string`, `unknown`> Defined in: [packages/core/src/tracing/span.ts:94](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L94) Additional metadata about this span *** ### sensitiveEncoding? [Section titled “sensitiveEncoding?”](#sensitiveencoding) > `optional` **sensitiveEncoding**: `boolean` Defined in: [packages/core/src/tracing/span.ts:97](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L97) When true, instructs the backend to encode this span’s sensitive content. # Interface: SpanTypeSchema [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / SpanTypeSchema # Interface: SpanTypeSchema [Section titled “Interface: SpanTypeSchema”](#interface-spantypeschema) Defined in: [packages/core/src/tracing/span-schema.ts:7](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L7) Schema definition for a span type, including its params/result schemas and optional risk metadata. ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/core/src/tracing/span-schema.ts:9](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L9) Unique name for this span type (e.g. `langchain:llm`, `myapp:tool:search`). *** ### params\_schema [Section titled “params\_schema”](#params_schema) > **params\_schema**: [`JsonSchema`](../type-aliases/JsonSchema.md) Defined in: [packages/core/src/tracing/span-schema.ts:11](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L11) JSON Schema describing the span’s input params. *** ### result\_schema? [Section titled “result\_schema?”](#result_schema) > `optional` **result\_schema**: [`JsonSchema`](../type-aliases/JsonSchema.md) Defined in: [packages/core/src/tracing/span-schema.ts:13](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L13) JSON Schema describing the span’s result payload. *** ### template? [Section titled “template?”](#template) > `optional` **template**: `string` | `null` Defined in: [packages/core/src/tracing/span-schema.ts:15](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L15) Liquid template for rendering the span’s params as a human-readable summary. *** ### result\_template? [Section titled “result\_template?”](#result_template) > `optional` **result\_template**: `string` | `null` Defined in: [packages/core/src/tracing/span-schema.ts:17](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L17) Liquid template for rendering the span’s result as a human-readable summary. *** ### description? [Section titled “description?”](#description) > `optional` **description**: `string` Defined in: [packages/core/src/tracing/span-schema.ts:19](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L19) Human-readable description of what this span type represents. *** ### data\_risk? [Section titled “data\_risk?”](#data_risk) > `optional` **data\_risk**: [`DataRisk`](DataRisk.md) Defined in: [packages/core/src/tracing/span-schema.ts:21](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span-schema.ts#L21) Risk metadata describing data sensitivity and permitted actions for this span type. # Interface: StartSpanOptions [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / StartSpanOptions # Interface: StartSpanOptions [Section titled “Interface: StartSpanOptions”](#interface-startspanoptions) Defined in: [packages/core/src/tracing/tracer.ts:11](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L11) Options for starting a new span ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/core/src/tracing/tracer.ts:13](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L13) Name of the span *** ### spanType [Section titled “spanType”](#spantype) > **spanType**: `string` Defined in: [packages/core/src/tracing/tracer.ts:16](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L16) Type of operation this span represents *** ### inputs [Section titled “inputs”](#inputs) > **inputs**: `Record`<`string`, `unknown`> Defined in: [packages/core/src/tracing/tracer.ts:19](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L19) Input data for this operation *** ### metadata? [Section titled “metadata?”](#metadata) > `optional` **metadata**: `Record`<`string`, `unknown`> Defined in: [packages/core/src/tracing/tracer.ts:22](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L22) Additional metadata (optional) *** ### sensitiveEncoding? [Section titled “sensitiveEncoding?”](#sensitiveencoding) > `optional` **sensitiveEncoding**: `boolean` Defined in: [packages/core/src/tracing/tracer.ts:25](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/tracer.ts#L25) When true, instructs the backend to encode this span’s sensitive content. # Interface: TokenUsage [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / TokenUsage # Interface: TokenUsage [Section titled “Interface: TokenUsage”](#interface-tokenusage) Defined in: [packages/core/src/tracing/span.ts:38](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L38) Token usage information for LLM calls ## Properties [Section titled “Properties”](#properties) ### promptTokens [Section titled “promptTokens”](#prompttokens) > **promptTokens**: `number` Defined in: [packages/core/src/tracing/span.ts:39](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L39) *** ### completionTokens [Section titled “completionTokens”](#completiontokens) > **completionTokens**: `number` Defined in: [packages/core/src/tracing/span.ts:40](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L40) *** ### totalTokens [Section titled “totalTokens”](#totaltokens) > **totalTokens**: `number` Defined in: [packages/core/src/tracing/span.ts:41](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L41) # Interface: ToolSchemaConfig [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / ToolSchemaConfig # Interface: ToolSchemaConfig [Section titled “Interface: ToolSchemaConfig”](#interface-toolschemaconfig) Defined in: [packages/core/src/tool-schema.ts:5](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tool-schema.ts#L5) ## Properties [Section titled “Properties”](#properties) ### spanType [Section titled “spanType”](#spantype) > **spanType**: `string` Defined in: [packages/core/src/tool-schema.ts:6](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tool-schema.ts#L6) *** ### inputSchema [Section titled “inputSchema”](#inputschema) > **inputSchema**: [`JsonSchema`](../type-aliases/JsonSchema.md) Defined in: [packages/core/src/tool-schema.ts:7](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tool-schema.ts#L7) # Interface: Transport [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / Transport # Interface: Transport [Section titled “Interface: Transport”](#interface-transport) Defined in: [packages/core/src/transport/http.ts:86](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L86) Transport contract used by the tracer and runtime. ## Methods [Section titled “Methods”](#methods) ### emit() [Section titled “emit()”](#emit) > **emit**(`span`): `void` Defined in: [packages/core/src/transport/http.ts:87](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L87) #### Parameters [Section titled “Parameters”](#parameters) ##### span [Section titled “span”](#span) [`Span`](Span.md) #### Returns [Section titled “Returns”](#returns) `void` *** ### finishSpan() [Section titled “finishSpan()”](#finishspan) > **finishSpan**(`spanId`, `endTime`, `options?`): `void` Defined in: [packages/core/src/transport/http.ts:89](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L89) #### Parameters [Section titled “Parameters”](#parameters-1) ##### spanId [Section titled “spanId”](#spanid) `string` ##### endTime [Section titled “endTime”](#endtime) `number` ##### options? [Section titled “options?”](#options) `FinishSpanOptions` #### Returns [Section titled “Returns”](#returns-1) `void` *** ### startAgentInstance() [Section titled “startAgentInstance()”](#startagentinstance) > **startAgentInstance**(`options?`): `void` Defined in: [packages/core/src/transport/http.ts:91](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L91) #### Parameters [Section titled “Parameters”](#parameters-2) ##### options? [Section titled “options?”](#options-1) [`AgentInstanceOptions`](../type-aliases/AgentInstanceOptions.md) #### Returns [Section titled “Returns”](#returns-2) `void` *** ### finishAgentInstance() [Section titled “finishAgentInstance()”](#finishagentinstance) > **finishAgentInstance**(): `void` Defined in: [packages/core/src/transport/http.ts:93](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L93) #### Returns [Section titled “Returns”](#returns-3) `void` *** ### recordQuality() [Section titled “recordQuality()”](#recordquality) > **recordQuality**(`payload`): `void` Defined in: [packages/core/src/transport/http.ts:99](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L99) Records a quality payload on the agent instance for a named quality schema. A null payload removes the recorded value for that name. #### Parameters [Section titled “Parameters”](#parameters-3) ##### payload [Section titled “payload”](#payload) ###### name [Section titled “name”](#name) `string` ###### payload [Section titled “payload”](#payload-1) `Record`<`string`, `unknown`> | `null` #### Returns [Section titled “Returns”](#returns-4) `void` *** ### registerSchema() [Section titled “registerSchema()”](#registerschema) > **registerSchema**(`schema`): `void` Defined in: [packages/core/src/transport/http.ts:101](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L101) #### Parameters [Section titled “Parameters”](#parameters-4) ##### schema [Section titled “schema”](#schema) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-5) `void` *** ### assertUsable() [Section titled “assertUsable()”](#assertusable) > **assertUsable**(`operation`): `void` Defined in: [packages/core/src/transport/http.ts:103](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L103) #### Parameters [Section titled “Parameters”](#parameters-5) ##### operation [Section titled “operation”](#operation) [`PrefactorTransportOperation`](../type-aliases/PrefactorTransportOperation.md) #### Returns [Section titled “Returns”](#returns-6) `void` *** ### getHealthState() [Section titled “getHealthState()”](#gethealthstate) > **getHealthState**(): [`PrefactorTransportHealthState`](../type-aliases/PrefactorTransportHealthState.md) Defined in: [packages/core/src/transport/http.ts:105](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L105) #### Returns [Section titled “Returns”](#returns-7) [`PrefactorTransportHealthState`](../type-aliases/PrefactorTransportHealthState.md) *** ### close() [Section titled “close()”](#close) > **close**(): `void` | `Promise`<`void`> Defined in: [packages/core/src/transport/http.ts:107](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L107) #### Returns [Section titled “Returns”](#returns-8) `void` | `Promise`<`void`> *** ### getAgentInstanceId() [Section titled “getAgentInstanceId()”](#getagentinstanceid) > **getAgentInstanceId**(): `string` | `null` Defined in: [packages/core/src/transport/http.ts:109](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L109) #### Returns [Section titled “Returns”](#returns-9) `string` | `null` *** ### getHttpRequester() [Section titled “getHttpRequester()”](#gethttprequester) > **getHttpRequester**(): [`HttpRequester`](HttpRequester.md) Defined in: [packages/core/src/transport/http.ts:111](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L111) #### Returns [Section titled “Returns”](#returns-10) [`HttpRequester`](HttpRequester.md) *** ### validateToken() [Section titled “validateToken()”](#validatetoken) > **validateToken**(): `Promise`<`void`> Defined in: [packages/core/src/transport/http.ts:113](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L113) #### Returns [Section titled “Returns”](#returns-11) `Promise`<`void`> # Type Alias: ActionProfileValue [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / ActionProfileValue # Type Alias: ActionProfileValue [Section titled “Type Alias: ActionProfileValue”](#type-alias-actionprofilevalue) > **ActionProfileValue** = `"unknown"` | `"allowed"` | `"disallowed"` Defined in: [packages/core/src/tracing/data-risk.ts:4](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L4) Risk action profile values. # Type Alias: AgentInstanceFinishOptions [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentInstanceFinishOptions # Type Alias: AgentInstanceFinishOptions [Section titled “Type Alias: AgentInstanceFinishOptions”](#type-alias-agentinstancefinishoptions) > **AgentInstanceFinishOptions** = `object` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:32](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L32) ## Properties [Section titled “Properties”](#properties) ### status? [Section titled “status?”](#status) > `optional` **status**: `"complete"` | `"failed"` | `"cancelled"` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:33](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L33) *** ### timestamp? [Section titled “timestamp?”](#timestamp) > `optional` **timestamp**: `string` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:34](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L34) *** ### idempotency\_key? [Section titled “idempotency\_key?”](#idempotency_key) > `optional` **idempotency\_key**: `string` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:35](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L35) # Type Alias: AgentInstanceOptions [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentInstanceOptions # Type Alias: AgentInstanceOptions [Section titled “Type Alias: AgentInstanceOptions”](#type-alias-agentinstanceoptions) > **AgentInstanceOptions** = `object` Defined in: [packages/core/src/transport/http.ts:33](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L33) ## Properties [Section titled “Properties”](#properties) ### agentId? [Section titled “agentId?”](#agentid) > `optional` **agentId**: `string` Defined in: [packages/core/src/transport/http.ts:35](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L35) Existing backend agent id, when available. *** ### agentIdentifier? [Section titled “agentIdentifier?”](#agentidentifier) > `optional` **agentIdentifier**: `string` Defined in: [packages/core/src/transport/http.ts:37](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L37) External agent version identifier. *** ### agentName? [Section titled “agentName?”](#agentname) > `optional` **agentName**: `string` Defined in: [packages/core/src/transport/http.ts:39](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L39) Human-readable agent name. *** ### agentDescription? [Section titled “agentDescription?”](#agentdescription) > `optional` **agentDescription**: `string` Defined in: [packages/core/src/transport/http.ts:41](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L41) Human-readable agent description. *** ### purpose? [Section titled “purpose?”](#purpose) > `optional` **purpose**: `"live"` | `"smoke_test"` | `"eval"` Defined in: [packages/core/src/transport/http.ts:43](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http.ts#L43) Why this instance ran: ‘live’ for an actual agent run, ‘smoke\_test’ for a pipeline check, or ‘eval’ for an evaluation run. Omit to let the API default to ‘live’. # Type Alias: AgentInstanceRecordQualityPayload [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentInstanceRecordQualityPayload # Type Alias: AgentInstanceRecordQualityPayload [Section titled “Type Alias: AgentInstanceRecordQualityPayload”](#type-alias-agentinstancerecordqualitypayload) > **AgentInstanceRecordQualityPayload** = `object` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:38](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L38) ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:40](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L40) Quality schema name (key in the agent schema version quality\_schemas). *** ### payload [Section titled “payload”](#payload) > **payload**: `Record`<`string`, `unknown`> | `null` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:42](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L42) Quality payload for this name, or null to remove the recorded payload. *** ### idempotency\_key? [Section titled “idempotency\_key?”](#idempotency_key) > `optional` **idempotency\_key**: `string` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:43](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L43) # Type Alias: AgentInstanceRegisterPayload [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentInstanceRegisterPayload # Type Alias: AgentInstanceRegisterPayload [Section titled “Type Alias: AgentInstanceRegisterPayload”](#type-alias-agentinstanceregisterpayload) > **AgentInstanceRegisterPayload** = `object` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:6](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L6) ## Properties [Section titled “Properties”](#properties) ### agent\_id? [Section titled “agent\_id?”](#agent_id) > `optional` **agent\_id**: `string` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:7](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L7) *** ### environment\_id? [Section titled “environment\_id?”](#environment_id) > `optional` **environment\_id**: `string` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:8](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L8) *** ### purpose? [Section titled “purpose?”](#purpose) > `optional` **purpose**: `"live"` | `"smoke_test"` | `"eval"` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:10](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L10) Why this instance ran: ‘live’ for an actual agent run, ‘smoke\_test’ for a pipeline check, or ‘eval’ for an evaluation run. Omit to let the API default to ‘live’. *** ### agent\_version? [Section titled “agent\_version?”](#agent_version) > `optional` **agent\_version**: `object` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:11](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L11) #### external\_identifier [Section titled “external\_identifier”](#external_identifier) > **external\_identifier**: `string` #### name [Section titled “name”](#name) > **name**: `string` #### description [Section titled “description”](#description) > **description**: `string` #### runtime\_environment? [Section titled “runtime\_environment?”](#runtime_environment) > `optional` **runtime\_environment**: [`RuntimeEnvironment`](RuntimeEnvironment.md) *** ### agent\_schema\_version? [Section titled “agent\_schema\_version?”](#agent_schema_version) > `optional` **agent\_schema\_version**: [`AgentSchemaVersion`](../interfaces/AgentSchemaVersion.md) Defined in: [packages/core/src/transport/http/agent-instance-client.ts:17](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L17) *** ### idempotency\_key? [Section titled “idempotency\_key?”](#idempotency_key) > `optional` **idempotency\_key**: `string` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:18](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L18) # Type Alias: AgentInstanceResponse [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentInstanceResponse # Type Alias: AgentInstanceResponse [Section titled “Type Alias: AgentInstanceResponse”](#type-alias-agentinstanceresponse) > **AgentInstanceResponse** = `object` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:21](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L21) ## Properties [Section titled “Properties”](#properties) ### details? [Section titled “details?”](#details) > `optional` **details**: `object` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:22](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L22) #### id? [Section titled “id?”](#id) > `optional` **id**: `string` # Type Alias: AgentInstanceStartOptions [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentInstanceStartOptions # Type Alias: AgentInstanceStartOptions [Section titled “Type Alias: AgentInstanceStartOptions”](#type-alias-agentinstancestartoptions) > **AgentInstanceStartOptions** = `object` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:27](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L27) ## Properties [Section titled “Properties”](#properties) ### timestamp? [Section titled “timestamp?”](#timestamp) > `optional` **timestamp**: `string` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:28](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L28) *** ### idempotency\_key? [Section titled “idempotency\_key?”](#idempotency_key) > `optional` **idempotency\_key**: `string` Defined in: [packages/core/src/transport/http/agent-instance-client.ts:29](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-instance-client.ts#L29) # Type Alias: AgentSpanCreatePayload [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentSpanCreatePayload # Type Alias: AgentSpanCreatePayload [Section titled “Type Alias: AgentSpanCreatePayload”](#type-alias-agentspancreatepayload) > **AgentSpanCreatePayload** = `object` Defined in: [packages/core/src/transport/http/agent-span-client.ts:15](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L15) ## Properties [Section titled “Properties”](#properties) ### details [Section titled “details”](#details) > **details**: `object` Defined in: [packages/core/src/transport/http/agent-span-client.ts:16](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L16) #### agent\_instance\_id [Section titled “agent\_instance\_id”](#agent_instance_id) > **agent\_instance\_id**: `string` | `null` #### schema\_name [Section titled “schema\_name”](#schema_name) > **schema\_name**: `string` #### status [Section titled “status”](#status) > **status**: [`AgentSpanStatus`](AgentSpanStatus.md) #### payload [Section titled “payload”](#payload) > **payload**: `Record`<`string`, `unknown`> #### result\_payload? [Section titled “result\_payload?”](#result_payload) > `optional` **result\_payload**: `Record`<`string`, `unknown`> #### parent\_span\_id [Section titled “parent\_span\_id”](#parent_span_id) > **parent\_span\_id**: `string` | `null` #### started\_at [Section titled “started\_at”](#started_at) > **started\_at**: `string` #### finished\_at [Section titled “finished\_at”](#finished_at) > **finished\_at**: `string` | `null` #### sensitive\_encoding? [Section titled “sensitive\_encoding?”](#sensitive_encoding) > `optional` **sensitive\_encoding**: `boolean` *** ### idempotency\_key? [Section titled “idempotency\_key?”](#idempotency_key) > `optional` **idempotency\_key**: `string` Defined in: [packages/core/src/transport/http/agent-span-client.ts:27](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L27) # Type Alias: AgentSpanFinishOptions [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentSpanFinishOptions # Type Alias: AgentSpanFinishOptions [Section titled “Type Alias: AgentSpanFinishOptions”](#type-alias-agentspanfinishoptions) > **AgentSpanFinishOptions** = `object` Defined in: [packages/core/src/transport/http/agent-span-client.ts:8](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L8) ## Properties [Section titled “Properties”](#properties) ### status? [Section titled “status?”](#status) > `optional` **status**: `AgentSpanFinishStatus` Defined in: [packages/core/src/transport/http/agent-span-client.ts:9](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L9) *** ### result\_payload? [Section titled “result\_payload?”](#result_payload) > `optional` **result\_payload**: `Record`<`string`, `unknown`> Defined in: [packages/core/src/transport/http/agent-span-client.ts:10](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L10) *** ### idempotency\_key? [Section titled “idempotency\_key?”](#idempotency_key) > `optional` **idempotency\_key**: `string` Defined in: [packages/core/src/transport/http/agent-span-client.ts:11](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L11) *** ### sensitive\_encoding? [Section titled “sensitive\_encoding?”](#sensitive_encoding) > `optional` **sensitive\_encoding**: `boolean` Defined in: [packages/core/src/transport/http/agent-span-client.ts:12](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L12) # Type Alias: AgentSpanResponse [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentSpanResponse # Type Alias: AgentSpanResponse [Section titled “Type Alias: AgentSpanResponse”](#type-alias-agentspanresponse) > **AgentSpanResponse** = `object` Defined in: [packages/core/src/transport/http/agent-span-client.ts:35](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L35) ## Properties [Section titled “Properties”](#properties) ### details? [Section titled “details?”](#details) > `optional` **details**: `object` Defined in: [packages/core/src/transport/http/agent-span-client.ts:36](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L36) #### id? [Section titled “id?”](#id) > `optional` **id**: `string` #### started\_at? [Section titled “started\_at?”](#started_at) > `optional` **started\_at**: `string` *** ### control? [Section titled “control?”](#control) > `optional` **control**: `AgentSpanControlSignal` Defined in: [packages/core/src/transport/http/agent-span-client.ts:40](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L40) # Type Alias: AgentSpanStatus [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / AgentSpanStatus # Type Alias: AgentSpanStatus [Section titled “Type Alias: AgentSpanStatus”](#type-alias-agentspanstatus) > **AgentSpanStatus** = `"active"` | `"complete"` | `"failed"` Defined in: [packages/core/src/transport/http/agent-span-client.ts:4](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/transport/http/agent-span-client.ts#L4) # Type Alias: Config [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / Config # Type Alias: Config [Section titled “Type Alias: Config”](#type-alias-config) > **Config** = `z.infer`<*typeof* [`ConfigSchema`](../variables/ConfigSchema.md)> Defined in: [packages/core/src/config.ts:114](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/config.ts#L114) # Type Alias: CoreRuntime [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / CoreRuntime # Type Alias: CoreRuntime [Section titled “Type Alias: CoreRuntime”](#type-alias-coreruntime) > **CoreRuntime** = `object` Defined in: [packages/core/src/create-core.ts:11](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/create-core.ts#L11) ## Properties [Section titled “Properties”](#properties) ### tracer [Section titled “tracer”](#tracer) > **tracer**: [`Tracer`](../classes/Tracer.md) Defined in: [packages/core/src/create-core.ts:12](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/create-core.ts#L12) *** ### agentManager [Section titled “agentManager”](#agentmanager) > **agentManager**: [`AgentInstanceManager`](../classes/AgentInstanceManager.md) Defined in: [packages/core/src/create-core.ts:13](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/create-core.ts#L13) *** ### terminationMonitor [Section titled “terminationMonitor”](#terminationmonitor) > **terminationMonitor**: [`TerminationMonitor`](../classes/TerminationMonitor.md) Defined in: [packages/core/src/create-core.ts:14](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/create-core.ts#L14) *** ### shutdown() [Section titled “shutdown()”](#shutdown) > **shutdown**: () => `Promise`<`void`> Defined in: [packages/core/src/create-core.ts:15](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/create-core.ts#L15) #### Returns [Section titled “Returns”](#returns) `Promise`<`void`> # Type Alias: CreateCoreOptions [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / CreateCoreOptions # Type Alias: CreateCoreOptions [Section titled “Type Alias: CreateCoreOptions”](#type-alias-createcoreoptions) > **CreateCoreOptions** = `object` Defined in: [packages/core/src/create-core.ts:18](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/create-core.ts#L18) ## Properties [Section titled “Properties”](#properties) ### sdkHeaderEntry? [Section titled “sdkHeaderEntry?”](#sdkheaderentry) > `optional` **sdkHeaderEntry**: `string` Defined in: [packages/core/src/create-core.ts:20](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/create-core.ts#L20) Optional adapter identifier appended ahead of the core SDK header. # Type Alias: DataCategoryValue [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / DataCategoryValue # Type Alias: DataCategoryValue [Section titled “Type Alias: DataCategoryValue”](#type-alias-datacategoryvalue) > **DataCategoryValue** = `"unknown"` | `"included"` | `"excluded"` Defined in: [packages/core/src/tracing/data-risk.ts:20](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L20) Presence indicator for a data category within a span’s params or results. # Type Alias: DataClassification [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / DataClassification # Type Alias: DataClassification [Section titled “Type Alias: DataClassification”](#type-alias-dataclassification) > **DataClassification** = `"unknown"` | `"public"` | `"internal"` | `"confidential"` | `"restricted"` | `"secret"` Defined in: [packages/core/src/tracing/data-risk.ts:9](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/data-risk.ts#L9) Data classification levels, from least to most sensitive. # Type Alias: HttpTransportConfig [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / HttpTransportConfig # Type Alias: HttpTransportConfig [Section titled “Type Alias: HttpTransportConfig”](#type-alias-httptransportconfig) > **HttpTransportConfig** = `z.infer`<*typeof* [`HttpTransportConfigSchema`](../variables/HttpTransportConfigSchema.md)> Defined in: [packages/core/src/config.ts:54](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/config.ts#L54) # Type Alias: JsonSchema [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / JsonSchema # Type Alias: JsonSchema [Section titled “Type Alias: JsonSchema”](#type-alias-jsonschema) > **JsonSchema** = `Record`<`string`, `unknown`> Defined in: [packages/core/src/tool-schema.ts:3](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tool-schema.ts#L3) # Type Alias: MiddlewareLike [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / MiddlewareLike # Type Alias: MiddlewareLike [Section titled “Type Alias: MiddlewareLike”](#type-alias-middlewarelike) > **MiddlewareLike** = `unknown` Defined in: [packages/core/src/client.ts:28](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/client.ts#L28) Provider middleware value exposed by integrations. # Type Alias: PartialHttpConfig [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / PartialHttpConfig # Type Alias: PartialHttpConfig [Section titled “Type Alias: PartialHttpConfig”](#type-alias-partialhttpconfig) > **PartialHttpConfig** = `z.infer`<*typeof* [`PartialHttpConfigSchema`](../variables/PartialHttpConfigSchema.md)> Defined in: [packages/core/src/config.ts:75](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/config.ts#L75) # Type Alias: PrefactorFatalErrorKind [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / PrefactorFatalErrorKind # Type Alias: PrefactorFatalErrorKind [Section titled “Type Alias: PrefactorFatalErrorKind”](#type-alias-prefactorfatalerrorkind) > **PrefactorFatalErrorKind** = `"auth"` | `"contract"` | `"schema_drift"` | `"queue_closed"` | `"retry_exhausted"` Defined in: [packages/core/src/errors.ts:1](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L1) # Type Alias: PrefactorShutdownDetails [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / PrefactorShutdownDetails # Type Alias: PrefactorShutdownDetails [Section titled “Type Alias: PrefactorShutdownDetails”](#type-alias-prefactorshutdowndetails) > **PrefactorShutdownDetails** = `object` Defined in: [packages/core/src/errors.ts:48](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L48) ## Properties [Section titled “Properties”](#properties) ### droppedAfterClose [Section titled “droppedAfterClose”](#droppedafterclose) > **droppedAfterClose**: `number` Defined in: [packages/core/src/errors.ts:49](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L49) *** ### cancelledScheduledRetries [Section titled “cancelledScheduledRetries”](#cancelledscheduledretries) > **cancelledScheduledRetries**: `number` Defined in: [packages/core/src/errors.ts:50](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L50) *** ### unresolvedPendingFinishes [Section titled “unresolvedPendingFinishes”](#unresolvedpendingfinishes) > **unresolvedPendingFinishes**: `number` Defined in: [packages/core/src/errors.ts:51](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L51) *** ### unresolvedParentReferences [Section titled “unresolvedParentReferences”](#unresolvedparentreferences) > **unresolvedParentReferences**: `number` Defined in: [packages/core/src/errors.ts:52](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L52) *** ### partialTelemetryEvents [Section titled “partialTelemetryEvents”](#partialtelemetryevents) > **partialTelemetryEvents**: `number` Defined in: [packages/core/src/errors.ts:53](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L53) # Type Alias: PrefactorShutdownErrorKind [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / PrefactorShutdownErrorKind # Type Alias: PrefactorShutdownErrorKind [Section titled “Type Alias: PrefactorShutdownErrorKind”](#type-alias-prefactorshutdownerrorkind) > **PrefactorShutdownErrorKind** = `"partial_telemetry"` | `"dropped_on_shutdown"` Defined in: [packages/core/src/errors.ts:8](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L8) # Type Alias: PrefactorTransportHealthState [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / PrefactorTransportHealthState # Type Alias: PrefactorTransportHealthState [Section titled “Type Alias: PrefactorTransportHealthState”](#type-alias-prefactortransporthealthstate) > **PrefactorTransportHealthState** = `"healthy"` | `"degraded"` | `"fatal"` | `"closed"` Defined in: [packages/core/src/errors.ts:20](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L20) # Type Alias: PrefactorTransportOperation [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / PrefactorTransportOperation # Type Alias: PrefactorTransportOperation [Section titled “Type Alias: PrefactorTransportOperation”](#type-alias-prefactortransportoperation) > **PrefactorTransportOperation** = `"token_validate"` | `"agent_register"` | `"agent_start"` | `"agent_finish"` | `"agent_record_quality"` | `"span_create"` | `"span_finish"` | `"shutdown"` Defined in: [packages/core/src/errors.ts:10](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/errors.ts#L10) # Type Alias: RuntimeEnvironment [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / RuntimeEnvironment # Type Alias: RuntimeEnvironment [Section titled “Type Alias: RuntimeEnvironment”](#type-alias-runtimeenvironment) > **RuntimeEnvironment** = `object` Defined in: [packages/core/src/runtime-environment.ts:9](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/runtime-environment.ts#L9) Runtime environment metadata reported at agent registration. Mirrors the `runtime_environment` field of the Prefactor API’s `agent_version` payload. ## Properties [Section titled “Properties”](#properties) ### agent\_sdk [Section titled “agent\_sdk”](#agent_sdk) > **agent\_sdk**: `string`\[] Defined in: [packages/core/src/runtime-environment.ts:11](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/runtime-environment.ts#L11) Upstream agent framework packages (e.g. `["@prefactor/langchain@2.0.0"]`). *** ### os [Section titled “os”](#os) > **os**: `string` Defined in: [packages/core/src/runtime-environment.ts:13](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/runtime-environment.ts#L13) Host operating system name (e.g. `"linux"`, `"darwin"`, `"windows"`). *** ### prefactor\_sdk [Section titled “prefactor\_sdk”](#prefactor_sdk) > **prefactor\_sdk**: `string`\[] Defined in: [packages/core/src/runtime-environment.ts:15](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/runtime-environment.ts#L15) Prefactor SDK packages in use (e.g. `["@prefactor/core@1.0.0"]`). *** ### runtime [Section titled “runtime”](#runtime) > **runtime**: `string` Defined in: [packages/core/src/runtime-environment.ts:17](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/runtime-environment.ts#L17) JavaScript runtime and version (e.g. `"node@22.12.0"`, `"bun@1.2.3"`). # Type Alias: SpanType [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / SpanType # Type Alias: SpanType [Section titled “Type Alias: SpanType”](#type-alias-spantype) > **SpanType** = *typeof* [`SpanType`](../variables/SpanType.md)\[keyof *typeof* [`SpanType`](../variables/SpanType.md)] | `string` Defined in: [packages/core/src/tracing/span.ts:4](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L4) String union of built-in span types plus custom provider-prefixed values. # Type Alias: TerminationCallback() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / TerminationCallback # Type Alias: TerminationCallback() [Section titled “Type Alias: TerminationCallback()”](#type-alias-terminationcallback) > **TerminationCallback** = (`reason`) => `void` Defined in: [packages/core/src/monitoring/termination-monitor.ts:4](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/monitoring/termination-monitor.ts#L4) ## Parameters [Section titled “Parameters”](#parameters) ### reason [Section titled “reason”](#reason) `string` | `null` ## Returns [Section titled “Returns”](#returns) `void` # Variable: ConfigSchema [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / ConfigSchema # Variable: ConfigSchema [Section titled “Variable: ConfigSchema”](#variable-configschema) > `const` **ConfigSchema**: `ZodObject`<{ `transportType`: `ZodDefault`<`ZodEnum`<{ `http`: `"http"`; }>>; `sampleRate`: `ZodDefault`<`ZodNumber`>; `captureInputs`: `ZodDefault`<`ZodBoolean`>; `captureOutputs`: `ZodDefault`<`ZodBoolean`>; `maxInputLength`: `ZodDefault`<`ZodNumber`>; `maxOutputLength`: `ZodDefault`<`ZodNumber`>; `httpConfig`: `ZodOptional`<`ZodObject`<{ `apiUrl`: `ZodString`; `apiToken`: `ZodString`; `agentId`: `ZodOptional`<`ZodString`>; `agentIdentifier`: `ZodOptional`<`ZodString`>; `agentName`: `ZodOptional`<`ZodString`>; `agentDescription`: `ZodOptional`<`ZodString`>; `agentSchema`: `ZodOptional`<`ZodRecord`<`ZodString`, `ZodUnknown`>>; `requestTimeout`: `ZodOptional`<`ZodNumber`>; `maxRetries`: `ZodOptional`<`ZodNumber`>; `initialRetryDelay`: `ZodOptional`<`ZodNumber`>; `maxRetryDelay`: `ZodOptional`<`ZodNumber`>; `retryMultiplier`: `ZodOptional`<`ZodNumber`>; `retryOnStatusCodes`: `ZodOptional`<`ZodArray`<`ZodNumber`>>; }, `$strip`>>; `failureHandling`: `ZodOptional`<`ZodObject`<{ `onFatalError`: `ZodOptional`<`ZodCustom`<(`error`) => `void`, (`error`) => `void`>>; }, `$strip`>>; }, `$strip`> Defined in: [packages/core/src/config.ts:80](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/config.ts#L80) Main SDK configuration schema # Variable: HttpTransportConfigSchema [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / HttpTransportConfigSchema # Variable: HttpTransportConfigSchema [Section titled “Variable: HttpTransportConfigSchema”](#variable-httptransportconfigschema) > `const` **HttpTransportConfigSchema**: `ZodObject`<{ `apiUrl`: `ZodString`; `apiToken`: `ZodString`; `agentId`: `ZodOptional`<`ZodString`>; `agentIdentifier`: `ZodDefault`<`ZodString`>; `agentName`: `ZodOptional`<`ZodString`>; `agentDescription`: `ZodOptional`<`ZodString`>; `agentSchema`: `ZodOptional`<`ZodRecord`<`ZodString`, `ZodUnknown`>>; `requestTimeout`: `ZodDefault`<`ZodNumber`>; `maxRetries`: `ZodDefault`<`ZodNumber`>; `initialRetryDelay`: `ZodDefault`<`ZodNumber`>; `maxRetryDelay`: `ZodDefault`<`ZodNumber`>; `retryMultiplier`: `ZodDefault`<`ZodNumber`>; `retryOnStatusCodes`: `ZodDefault`<`ZodArray`<`ZodNumber`>>; }, `$strip`> Defined in: [packages/core/src/config.ts:13](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/config.ts#L13) Configuration schema for HTTP transport # Variable: PartialHttpConfigSchema [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / PartialHttpConfigSchema # Variable: PartialHttpConfigSchema [Section titled “Variable: PartialHttpConfigSchema”](#variable-partialhttpconfigschema) > `const` **PartialHttpConfigSchema**: `ZodObject`<{ `apiUrl`: `ZodString`; `apiToken`: `ZodString`; `agentId`: `ZodOptional`<`ZodString`>; `agentIdentifier`: `ZodOptional`<`ZodString`>; `agentName`: `ZodOptional`<`ZodString`>; `agentDescription`: `ZodOptional`<`ZodString`>; `agentSchema`: `ZodOptional`<`ZodRecord`<`ZodString`, `ZodUnknown`>>; `requestTimeout`: `ZodOptional`<`ZodNumber`>; `maxRetries`: `ZodOptional`<`ZodNumber`>; `initialRetryDelay`: `ZodOptional`<`ZodNumber`>; `maxRetryDelay`: `ZodOptional`<`ZodNumber`>; `retryMultiplier`: `ZodOptional`<`ZodNumber`>; `retryOnStatusCodes`: `ZodOptional`<`ZodArray`<`ZodNumber`>>; }, `$strip`> Defined in: [packages/core/src/config.ts:59](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/config.ts#L59) Partial HTTP config schema for user input (before defaults are applied) # Variable: SpanType [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/core](../index.md) / SpanType # Variable: SpanType [Section titled “Variable: SpanType”](#variable-spantype) > `const` **SpanType**: `object` Defined in: [packages/core/src/tracing/span.ts:4](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/core/src/tracing/span.ts#L4) Types of spans that can be traced ## Type Declaration [Section titled “Type Declaration”](#type-declaration) ### AGENT [Section titled “AGENT”](#agent) > `readonly` **AGENT**: `"agent"` = `'agent'` ### LLM [Section titled “LLM”](#llm) > `readonly` **LLM**: `"llm"` = `'llm'` ### TOOL [Section titled “TOOL”](#tool) > `readonly` **TOOL**: `"tool"` = `'tool'` ### CHAIN [Section titled “CHAIN”](#chain) > `readonly` **CHAIN**: `"chain"` = `'chain'` # @prefactor/langchain [**Prefactor TypeScript SDK**](../index.md) *** [Prefactor TypeScript SDK](../modules.md) / @prefactor/langchain # @prefactor/langchain [Section titled “@prefactor/langchain”](#prefactorlangchain) LangChain adapter package exposing Prefactor initialization helpers and middleware. ## `@prefactor/langchain` overview [Section titled “@prefactor/langchain overview”](#prefactorlangchain-overview) `@prefactor/langchain` adds Prefactor tracing to LangChain middleware so agent, model, chain, and tool activity is captured automatically. Use this package as a provider for the core `init` function. ## Quick start [Section titled “Quick start”](#quick-start) ```ts import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; import { createAgent } from 'langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: 'https://api.prefactor.ai', apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: 'support-bot-v1', }, }); const agent = createAgent({ model: 'claude-sonnet-4-5-20250929', tools: [], middleware: [prefactor.getMiddleware()], }); ``` ## Classes [Section titled “Classes”](#classes) * [PrefactorLangChain](classes/PrefactorLangChain.md) ## Interfaces [Section titled “Interfaces”](#interfaces) * [PrefactorLangChainOptions](interfaces/PrefactorLangChainOptions.md) ## Variables [Section titled “Variables”](#variables) * [DEFAULT\_LANGCHAIN\_AGENT\_SCHEMA](variables/DEFAULT_LANGCHAIN_AGENT_SCHEMA.md) # Class: PrefactorLangChain [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/langchain](../index.md) / PrefactorLangChain # Class: PrefactorLangChain [Section titled “Class: PrefactorLangChain”](#class-prefactorlangchain) Defined in: [packages/langchain/src/provider.ts:17](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L17) ## Implements [Section titled “Implements”](#implements) * `PrefactorProvider`<`AgentMiddleware`> ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new PrefactorLangChain**(`options?`): `PrefactorLangChain` Defined in: [packages/langchain/src/provider.ts:22](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L22) #### Parameters [Section titled “Parameters”](#parameters) ##### options? [Section titled “options?”](#options) [`PrefactorLangChainOptions`](../interfaces/PrefactorLangChainOptions.md) = `{}` #### Returns [Section titled “Returns”](#returns) `PrefactorLangChain` ## Methods [Section titled “Methods”](#methods) ### createMiddleware() [Section titled “createMiddleware()”](#createmiddleware) > **createMiddleware**(`tracer`, `agentManager`, `coreConfig`, `getAbortSignal?`): `AgentMiddleware` Defined in: [packages/langchain/src/provider.ts:26](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L26) Creates provider middleware bound to the core runtime services. #### Parameters [Section titled “Parameters”](#parameters-1) ##### tracer [Section titled “tracer”](#tracer) `Tracer` Runtime tracer used for span creation. ##### agentManager [Section titled “agentManager”](#agentmanager) `AgentInstanceManager` Runtime agent instance manager. ##### coreConfig [Section titled “coreConfig”](#coreconfig) ##### getAbortSignal? [Section titled “getAbortSignal?”](#getabortsignal) () => `AbortSignal` Returns the AbortSignal for the current run. Called on each check so a fresh signal is returned after `monitor.reset()`. #### Returns [Section titled “Returns”](#returns-1) `AgentMiddleware` Provider middleware consumed by upstream frameworks. #### Implementation of [Section titled “Implementation of”](#implementation-of) `PrefactorProvider.createMiddleware` *** ### resetForNextRun() [Section titled “resetForNextRun()”](#resetfornextrun) > **resetForNextRun**(): `void` Defined in: [packages/langchain/src/provider.ts:72](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L72) Optional hook called between agent runs to reset per-run middleware state (e.g. finish the current agent instance and clear instance-started flags). #### Returns [Section titled “Returns”](#returns-2) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-1) `PrefactorProvider.resetForNextRun` *** ### shutdown() [Section titled “shutdown()”](#shutdown) > **shutdown**(): `void` Defined in: [packages/langchain/src/provider.ts:76](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L76) Optional provider-level cleanup hook invoked during client shutdown. #### Returns [Section titled “Returns”](#returns-3) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-2) `PrefactorProvider.shutdown` *** ### getSdkHeaderEntry() [Section titled “getSdkHeaderEntry()”](#getsdkheaderentry) > **getSdkHeaderEntry**(): `string` Defined in: [packages/langchain/src/provider.ts:81](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L81) Returns the SDK header entry to append to HTTP requests created by the core runtime. #### Returns [Section titled “Returns”](#returns-4) `string` Adapter-specific SDK identifier, or `undefined` to use the core header only. #### Implementation of [Section titled “Implementation of”](#implementation-of-3) `PrefactorProvider.getSdkHeaderEntry` *** ### normalizeAgentSchema() [Section titled “normalizeAgentSchema()”](#normalizeagentschema) > **normalizeAgentSchema**(`agentSchema`): `Record`<`string`, `unknown`> Defined in: [packages/langchain/src/provider.ts:85](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L85) Normalizes a user- or provider-authored agent schema before core registers it. #### Parameters [Section titled “Parameters”](#parameters-2) ##### agentSchema [Section titled “agentSchema”](#agentschema) `Record`<`string`, `unknown`> Authored agent schema configuration. #### Returns [Section titled “Returns”](#returns-5) `Record`<`string`, `unknown`> Normalized schema, or `undefined` to leave the input unchanged. #### Implementation of [Section titled “Implementation of”](#implementation-of-4) `PrefactorProvider.normalizeAgentSchema` *** ### getDefaultAgentSchema() [Section titled “getDefaultAgentSchema()”](#getdefaultagentschema) > **getDefaultAgentSchema**(): `Record`<`string`, `unknown`> | `undefined` Defined in: [packages/langchain/src/provider.ts:91](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L91) Provides a default agent schema when a user does not supply one. #### Returns [Section titled “Returns”](#returns-6) `Record`<`string`, `unknown`> | `undefined` Agent schema object, or `undefined` when no default is available. #### Implementation of [Section titled “Implementation of”](#implementation-of-5) `PrefactorProvider.getDefaultAgentSchema` # Interface: PrefactorLangChainOptions [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/langchain](../index.md) / PrefactorLangChainOptions # Interface: PrefactorLangChainOptions [Section titled “Interface: PrefactorLangChainOptions”](#interface-prefactorlangchainoptions) Defined in: [packages/langchain/src/provider.ts:13](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L13) ## Properties [Section titled “Properties”](#properties) ### agentSchema? [Section titled “agentSchema?”](#agentschema) > `optional` **agentSchema**: `Record`<`string`, `unknown`> Defined in: [packages/langchain/src/provider.ts:14](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L14) # Variable: DEFAULT\_LANGCHAIN\_AGENT\_SCHEMA [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/langchain](../index.md) / DEFAULT\_LANGCHAIN\_AGENT\_SCHEMA # Variable: DEFAULT\_LANGCHAIN\_AGENT\_SCHEMA [Section titled “Variable: DEFAULT\_LANGCHAIN\_AGENT\_SCHEMA”](#variable-default_langchain_agent_schema) > `const` **DEFAULT\_LANGCHAIN\_AGENT\_SCHEMA**: `object` = `DEFAULT_LANGCHAIN_AGENT_SCHEMA_BASE` Defined in: [packages/langchain/src/provider.ts:10](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L10) ## Type Declaration [Section titled “Type Declaration”](#type-declaration) ### external\_identifier [Section titled “external\_identifier”](#external_identifier) > `readonly` **external\_identifier**: `"langchain-schema"` = `'langchain-schema'` ### span\_schemas [Section titled “span\_schemas”](#span_schemas) > `readonly` **span\_schemas**: `object` #### span\_schemas.langchain:agent [Section titled “span\_schemas.langchain:agent”](#span_schemaslangchainagent) > `readonly` **langchain:agent**: `object` #### span\_schemas.langchain:agent.type [Section titled “span\_schemas.langchain:agent.type”](#span_schemaslangchainagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.langchain:agent.additionalProperties [Section titled “span\_schemas.langchain:agent.additionalProperties”](#span_schemaslangchainagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.langchain:llm [Section titled “span\_schemas.langchain:llm”](#span_schemaslangchainllm) > `readonly` **langchain:llm**: `object` #### span\_schemas.langchain:llm.type [Section titled “span\_schemas.langchain:llm.type”](#span_schemaslangchainllmtype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.langchain:llm.additionalProperties [Section titled “span\_schemas.langchain:llm.additionalProperties”](#span_schemaslangchainllmadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.langchain:tool [Section titled “span\_schemas.langchain:tool”](#span_schemaslangchaintool) > `readonly` **langchain:tool**: `object` #### span\_schemas.langchain:tool.type [Section titled “span\_schemas.langchain:tool.type”](#span_schemaslangchaintooltype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.langchain:tool.additionalProperties [Section titled “span\_schemas.langchain:tool.additionalProperties”](#span_schemaslangchaintooladditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.langchain:chain [Section titled “span\_schemas.langchain:chain”](#span_schemaslangchainchain) > `readonly` **langchain:chain**: `object` #### span\_schemas.langchain:chain.type [Section titled “span\_schemas.langchain:chain.type”](#span_schemaslangchainchaintype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.langchain:chain.additionalProperties [Section titled “span\_schemas.langchain:chain.additionalProperties”](#span_schemaslangchainchainadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` ### span\_result\_schemas [Section titled “span\_result\_schemas”](#span_result_schemas) > `readonly` **span\_result\_schemas**: `object` #### span\_result\_schemas.langchain:agent [Section titled “span\_result\_schemas.langchain:agent”](#span_result_schemaslangchainagent) > `readonly` **langchain:agent**: `object` #### span\_result\_schemas.langchain:agent.type [Section titled “span\_result\_schemas.langchain:agent.type”](#span_result_schemaslangchainagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.langchain:agent.additionalProperties [Section titled “span\_result\_schemas.langchain:agent.additionalProperties”](#span_result_schemaslangchainagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.langchain:llm [Section titled “span\_result\_schemas.langchain:llm”](#span_result_schemaslangchainllm) > `readonly` **langchain:llm**: `object` #### span\_result\_schemas.langchain:llm.type [Section titled “span\_result\_schemas.langchain:llm.type”](#span_result_schemaslangchainllmtype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.langchain:llm.additionalProperties [Section titled “span\_result\_schemas.langchain:llm.additionalProperties”](#span_result_schemaslangchainllmadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.langchain:tool [Section titled “span\_result\_schemas.langchain:tool”](#span_result_schemaslangchaintool) > `readonly` **langchain:tool**: `object` #### span\_result\_schemas.langchain:tool.type [Section titled “span\_result\_schemas.langchain:tool.type”](#span_result_schemaslangchaintooltype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.langchain:tool.additionalProperties [Section titled “span\_result\_schemas.langchain:tool.additionalProperties”](#span_result_schemaslangchaintooladditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.langchain:chain [Section titled “span\_result\_schemas.langchain:chain”](#span_result_schemaslangchainchain) > `readonly` **langchain:chain**: `object` #### span\_result\_schemas.langchain:chain.type [Section titled “span\_result\_schemas.langchain:chain.type”](#span_result_schemaslangchainchaintype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.langchain:chain.additionalProperties [Section titled “span\_result\_schemas.langchain:chain.additionalProperties”](#span_result_schemaslangchainchainadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` # Prefactor TypeScript SDK [**Prefactor TypeScript SDK**](index.md) *** # Prefactor TypeScript SDK [Section titled “Prefactor TypeScript SDK”](#prefactor-typescript-sdk) ## Modules [Section titled “Modules”](#modules) ### Core [Section titled “Core”](#core) * [@prefactor/core](core/index.md) ### Packages [Section titled “Packages”](#packages) * [@prefactor/langchain](packages/langchain/index.md) * [@prefactor/ai](packages/ai/index.md) * [@prefactor/claude](packages/claude/index.md) * [@prefactor/openclaw-prefactor-plugin](packages/openclaw-prefactor-plugin/index.md) # @prefactor/openclaw-prefactor-plugin [**Prefactor TypeScript SDK**](../index.md) *** [Prefactor TypeScript SDK](../modules.md) / @prefactor/openclaw-prefactor-plugin # @prefactor/openclaw-prefactor-plugin [Section titled “@prefactor/openclaw-prefactor-plugin”](#prefactoropenclaw-prefactor-plugin) OpenClaw plugin for Prefactor observability. Provides automatic tracing of agent lifecycle events including sessions, user interactions, agent runs, and tool calls. ## `@prefactor/openclaw-prefactor-plugin` overview [Section titled “@prefactor/openclaw-prefactor-plugin overview”](#prefactoropenclaw-prefactor-plugin-overview) This plugin hooks into OpenClaw’s lifecycle events to create a hierarchical span structure for distributed tracing. The span hierarchy follows: ```plaintext session (24hr lifetime, root span) └─ user_interaction (5min idle timeout) ├─ user_message (instant, auto-closed) ├─ agent_run (child of interaction) │ ├─ tool_call (concurrent, children of agent_run) │ └─ tool_call └─ assistant_response (instant, auto-closed) ``` ## Hook handlers [Section titled “Hook handlers”](#hook-handlers) The plugin registers 14 hooks that automatically create and manage spans: * **Gateway**: `gateway_start`, `gateway_stop` * **Session**: `session_start`, `session_end` * **Agent**: `before_agent_start`, `agent_end` * **Compaction**: `before_compaction`, `after_compaction` * **Tool**: `before_tool_call`, `after_tool_call`, `tool_result_persist` * **Message**: `message_received`, `message_sending`, `message_sent` ## Span types [Section titled “Span types”](#span-types) * `openclaw:session` - Root span for the OpenClaw session (24hr lifetime) * `openclaw:user_interaction` - User interaction context (5min idle timeout) * `openclaw:user_message` - Inbound user message event * `openclaw:agent_run` - Agent execution run * `openclaw:tool_call` - Tool execution (supports concurrent calls) * `openclaw:assistant_response` - Assistant response event ## Exports [Section titled “Exports”](#exports) * [Agent](interfaces/Agent.md) - HTTP client for Prefactor API (span CRUD, instance lifecycle) * [SessionStateManager](interfaces/SessionStateManager.md) - Manages span hierarchy and timeouts per session * [Logger](interfaces/Logger.md) - Structured logger for plugin diagnostics * [register](functions/default.md) - Plugin entry point (used by OpenClaw, not imported directly) ## Functions [Section titled “Functions”](#functions) * [default](functions/default.md) * [createAgent](functions/createAgent.md) * [createRiskConfig](functions/createRiskConfig.md) * [createLogger](functions/createLogger.md) * [createSessionStateManager](functions/createSessionStateManager.md) * [getAllSupportedToolDefinitions](functions/getAllSupportedToolDefinitions.md) * [getToolDefinition](functions/getToolDefinition.md) * [getToolInputSchema](functions/getToolInputSchema.md) * [isSupportedTool](functions/isSupportedTool.md) * [normalizeToolName](functions/normalizeToolName.md) * [buildToolSpanSchema](functions/buildToolSpanSchema.md) * [createToolSpanInputs](functions/createToolSpanInputs.md) * [createToolSpanOutputs](functions/createToolSpanOutputs.md) * [createToolSpanResultPayload](functions/createToolSpanResultPayload.md) ## Interfaces [Section titled “Interfaces”](#interfaces) * [Agent](interfaces/Agent.md) * [AgentConfig](interfaces/AgentConfig.md) * [Logger](interfaces/Logger.md) * [SessionStateManager](interfaces/SessionStateManager.md) * [ToolDefinition](interfaces/ToolDefinition.md) ## Type Aliases [Section titled “Type Aliases”](#type-aliases) * [LogLevel](type-aliases/LogLevel.md) ## Variables [Section titled “Variables”](#variables) * [agentRunRisk](variables/agentRunRisk.md) * [agentThinkingRisk](variables/agentThinkingRisk.md) * [assistantResponseRisk](variables/assistantResponseRisk.md) * [defaultSpanTypeRiskConfigs](variables/defaultSpanTypeRiskConfigs.md) * [sessionRisk](variables/sessionRisk.md) * [toolBrowserRisk](variables/toolBrowserRisk.md) * [toolEditRisk](variables/toolEditRisk.md) * [toolExecRisk](variables/toolExecRisk.md) * [toolReadRisk](variables/toolReadRisk.md) * [toolRisk](variables/toolRisk.md) * [toolWebFetchRisk](variables/toolWebFetchRisk.md) * [toolWebSearchRisk](variables/toolWebSearchRisk.md) * [toolWriteRisk](variables/toolWriteRisk.md) * [userInteractionRisk](variables/userInteractionRisk.md) * [userMessageRisk](variables/userMessageRisk.md) * [SUPPORTED\_TOOL\_DEFINITIONS](variables/SUPPORTED_TOOL_DEFINITIONS.md) * [TOOL\_ALIAS\_MAP](variables/TOOL_ALIAS_MAP.md) * [GENERIC\_OBJECT\_SCHEMA](variables/GENERIC_OBJECT_SCHEMA.md) # Function: buildToolSpanSchema() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / buildToolSpanSchema # Function: buildToolSpanSchema() [Section titled “Function: buildToolSpanSchema()”](#function-buildtoolspanschema) > **buildToolSpanSchema**(`inputSchema`): `JsonSchema` Defined in: [packages/openclaw-prefactor-plugin/src/tool-span-contract.ts:104](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-span-contract.ts#L104) Builds a complete JSON schema for a tool span. ## Parameters [Section titled “Parameters”](#parameters) ### inputSchema [Section titled “inputSchema”](#inputschema) `JsonSchema` JSON Schema for the tool’s input parameters ## Returns [Section titled “Returns”](#returns) `JsonSchema` Complete tool span schema # Function: createAgent() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createAgent # Function: createAgent() [Section titled “Function: createAgent()”](#function-createagent) > **createAgent**(`config`, `logger`): [`Agent`](../interfaces/Agent.md) Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:873](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L873) Creates and returns a fully initialised [Agent](../interfaces/Agent.md) instance. On construction the Agent starts a background flush loop (every 30 s) that retries any previously failed network operations. No immediate network calls are made; the first API request occurs when a span is created or an AgentInstance is registered for a session. ## Parameters [Section titled “Parameters”](#parameters) ### config [Section titled “config”](#config) [`AgentConfig`](../interfaces/AgentConfig.md) [AgentConfig](../interfaces/AgentConfig.md) with API URL, token, agent ID, and optional retry/timeout settings. ### logger [Section titled “logger”](#logger) [`Logger`](../interfaces/Logger.md) Logger instance for structured diagnostic output. ## Returns [Section titled “Returns”](#returns) [`Agent`](../interfaces/Agent.md) A new [Agent](../interfaces/Agent.md) ready to manage sessions and spans. # Function: createLogger() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createLogger # Function: createLogger() [Section titled “Function: createLogger()”](#function-createlogger) > **createLogger**(`level?`): [`Logger`](../interfaces/Logger.md) Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:55](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L55) ## Parameters [Section titled “Parameters”](#parameters) ### level? [Section titled “level?”](#level) [`LogLevel`](../type-aliases/LogLevel.md) = `'info'` ## Returns [Section titled “Returns”](#returns) [`Logger`](../interfaces/Logger.md) # Function: createRiskConfig() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createRiskConfig # Function: createRiskConfig() [Section titled “Function: createRiskConfig()”](#function-createriskconfig) > **createRiskConfig**(`userConfigs?`): `Record`<`string`, `DataRisk`> Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:341](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L341) Creates a merged risk configuration by combining default configs with user-provided overrides. User overrides take precedence over defaults. ## Parameters [Section titled “Parameters”](#parameters) ### userConfigs? [Section titled “userConfigs?”](#userconfigs) `Record`<`string`, `DataRisk`> User-provided risk configurations to merge with defaults ## Returns [Section titled “Returns”](#returns) `Record`<`string`, `DataRisk`> Merged risk configuration # Function: createSessionStateManager() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createSessionStateManager # Function: createSessionStateManager() [Section titled “Function: createSessionStateManager()”](#function-createsessionstatemanager) > **createSessionStateManager**(`agent`, `logger`, `config?`): [`SessionStateManager`](../interfaces/SessionStateManager.md) Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:766](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L766) ## Parameters [Section titled “Parameters”](#parameters) ### agent [Section titled “agent”](#agent) [`Agent`](../interfaces/Agent.md) | `null` ### logger [Section titled “logger”](#logger) [`Logger`](../interfaces/Logger.md) ### config? [Section titled “config?”](#config) `Partial`<`SessionManagerConfig`> ## Returns [Section titled “Returns”](#returns) [`SessionStateManager`](../interfaces/SessionStateManager.md) # Function: createToolSpanInputs() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createToolSpanInputs # Function: createToolSpanInputs() [Section titled “Function: createToolSpanInputs()”](#function-createtoolspaninputs) > **createToolSpanInputs**(`params`): `Record`<`string`, `unknown`> Defined in: [packages/openclaw-prefactor-plugin/src/tool-span-contract.ts:69](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-span-contract.ts#L69) Creates structured inputs for a tool call span. ## Parameters [Section titled “Parameters”](#parameters) ### params [Section titled “params”](#params) Tool call parameters #### toolName [Section titled “toolName”](#toolname) `string` #### toolCallId? [Section titled “toolCallId?”](#toolcallid) `string` #### input? [Section titled “input?”](#input) `unknown` ## Returns [Section titled “Returns”](#returns) `Record`<`string`, `unknown`> Structured span inputs following OpenClaw tool-span-contract # Function: createToolSpanOutputs() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createToolSpanOutputs # Function: createToolSpanOutputs() [Section titled “Function: createToolSpanOutputs()”](#function-createtoolspanoutputs) > **createToolSpanOutputs**(`output`): `object` Defined in: [packages/openclaw-prefactor-plugin/src/tool-span-contract.ts:92](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-span-contract.ts#L92) Creates structured outputs for a tool call span. ## Parameters [Section titled “Parameters”](#parameters) ### output [Section titled “output”](#output) `unknown` Raw tool output ## Returns [Section titled “Returns”](#returns) `object` Structured span outputs ### output [Section titled “output”](#output-1) > **output**: `unknown` # Function: createToolSpanResultPayload() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createToolSpanResultPayload # Function: createToolSpanResultPayload() [Section titled “Function: createToolSpanResultPayload()”](#function-createtoolspanresultpayload) > **createToolSpanResultPayload**(`output`, `isError`): `Record`<`string`, `unknown`> Defined in: [packages/openclaw-prefactor-plugin/src/tool-span-contract.ts:179](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-span-contract.ts#L179) Creates a tool span result payload for finishing a span. ## Parameters [Section titled “Parameters”](#parameters) ### output [Section titled “output”](#output) `unknown` Tool output ### isError [Section titled “isError”](#iserror) `boolean` Whether the tool execution resulted in an error ## Returns [Section titled “Returns”](#returns) `Record`<`string`, `unknown`> Result payload for span finish # Function: default() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / default # Function: default() [Section titled “Function: default()”](#function-default) > **default**(`api`): `void` Defined in: [packages/openclaw-prefactor-plugin/src/index.ts:78](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/index.ts#L78) ## Parameters [Section titled “Parameters”](#parameters) ### api [Section titled “api”](#api) `OpenClawPluginApi` ## Returns [Section titled “Returns”](#returns) `void` # Function: getAllSupportedToolDefinitions() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / getAllSupportedToolDefinitions # Function: getAllSupportedToolDefinitions() [Section titled “Function: getAllSupportedToolDefinitions()”](#function-getallsupportedtooldefinitions) > **getAllSupportedToolDefinitions**(): `Record`<`string`, [`ToolDefinition`](../interfaces/ToolDefinition.md)> Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:423](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L423) Gets all tool definitions for schema registration. Used when building the agent schema version. ## Returns [Section titled “Returns”](#returns) `Record`<`string`, [`ToolDefinition`](../interfaces/ToolDefinition.md)> # Function: getToolDefinition() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / getToolDefinition # Function: getToolDefinition() [Section titled “Function: getToolDefinition()”](#function-gettooldefinition) > **getToolDefinition**(`toolName`): [`ToolDefinition`](../interfaces/ToolDefinition.md) | `undefined` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:397](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L397) Gets the tool definition for a given tool name. Handles both canonical names and aliases. Returns undefined for unknown tools. ## Parameters [Section titled “Parameters”](#parameters) ### toolName [Section titled “toolName”](#toolname) `string` ## Returns [Section titled “Returns”](#returns) [`ToolDefinition`](../interfaces/ToolDefinition.md) | `undefined` # Function: getToolInputSchema() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / getToolInputSchema # Function: getToolInputSchema() [Section titled “Function: getToolInputSchema()”](#function-gettoolinputschema) > **getToolInputSchema**(`toolName`): `JsonSchema` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:406](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L406) Gets the input schema for a tool. Returns a generic object schema for unknown tools. ## Parameters [Section titled “Parameters”](#parameters) ### toolName [Section titled “toolName”](#toolname) `string` ## Returns [Section titled “Returns”](#returns) `JsonSchema` # Function: isSupportedTool() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / isSupportedTool # Function: isSupportedTool() [Section titled “Function: isSupportedTool()”](#function-issupportedtool) > **isSupportedTool**(`toolName`): `boolean` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:414](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L414) Checks if a tool is one of the supported tools with a defined schema. ## Parameters [Section titled “Parameters”](#parameters) ### toolName [Section titled “toolName”](#toolname) `string` ## Returns [Section titled “Returns”](#returns) `boolean` # Function: normalizeToolName() [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / normalizeToolName # Function: normalizeToolName() [Section titled “Function: normalizeToolName()”](#function-normalizetoolname) > **normalizeToolName**(`toolName`): `string` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:388](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L388) Normalizes a tool name to its canonical form. Falls back to the original name if no mapping exists. ## Parameters [Section titled “Parameters”](#parameters) ### toolName [Section titled “toolName”](#toolname) `string` ## Returns [Section titled “Returns”](#returns) `string` # Interface: Agent [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / Agent # Interface: Agent [Section titled “Interface: Agent”](#interface-agent) Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:157](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L157) HTTP client that manages AgentInstance lifecycle and span CRUD against the Prefactor API. Supports multiple concurrent sessions, each backed by its own AgentInstance, and automatically retries failed operations via a background replay queue. ## Param [Section titled “Param”](#param) [AgentConfig](AgentConfig.md) with connection and retry settings. ## Param [Section titled “Param”](#param-1) Logger instance used for structured diagnostic output. Key public methods: * [Agent.createSpan](#createspan) — Creates a span under the given session, registering an AgentInstance first if one does not yet exist. * [Agent.finishSpan](#finishspan) — Marks a span as finished; queues the operation for retry on failure. * [Agent.finishAgentInstance](#finishagentinstance) — Completes the AgentInstance for a session. * [Agent.flushQueue](#flushqueue) — Replays any queued operations that previously failed. * [Agent.stop](#stop) — Stops the background flush loop. * [Agent.emergencyCleanup](#emergencycleanup) — Tears down all sessions and clears the queue. ## Methods [Section titled “Methods”](#methods) ### resolveToolSpanType() [Section titled “resolveToolSpanType()”](#resolvetoolspantype) > **resolveToolSpanType**(`toolName`): `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:429](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L429) Resolves a tool name to its span type. Returns the specific span type for supported tools, or the generic fallback. #### Parameters [Section titled “Parameters”](#parameters) ##### toolName [Section titled “toolName”](#toolname) `string` #### Returns [Section titled “Returns”](#returns) `string` *** ### stop() [Section titled “stop()”](#stop) > **stop**(): `void` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:470](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L470) #### Returns [Section titled “Returns”](#returns-1) `void` *** ### emergencyCleanup() [Section titled “emergencyCleanup()”](#emergencycleanup) > **emergencyCleanup**(): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:477](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L477) #### Returns [Section titled “Returns”](#returns-2) `Promise`<`void`> *** ### finishAgentInstance() [Section titled “finishAgentInstance()”](#finishagentinstance) > **finishAgentInstance**(`sessionKey`, `status?`): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:592](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L592) #### Parameters [Section titled “Parameters”](#parameters-1) ##### sessionKey [Section titled “sessionKey”](#sessionkey) `string` ##### status? [Section titled “status?”](#status) `"complete"` | `"failed"` | `"cancelled"` #### Returns [Section titled “Returns”](#returns-3) `Promise`<`void`> *** ### createSpan() [Section titled “createSpan()”](#createspan) > **createSpan**(`sessionKey`, `schemaName`, `payload`, `parentSpanId?`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:643](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L643) #### Parameters [Section titled “Parameters”](#parameters-2) ##### sessionKey [Section titled “sessionKey”](#sessionkey-1) `string` ##### schemaName [Section titled “schemaName”](#schemaname) `string` ##### payload [Section titled “payload”](#payload) `Record`<`string`, `unknown`> ##### parentSpanId? [Section titled “parentSpanId?”](#parentspanid) `string` | `null` #### Returns [Section titled “Returns”](#returns-4) `Promise`<`string` | `null`> *** ### finishSpan() [Section titled “finishSpan()”](#finishspan) > **finishSpan**(`sessionKey`, `spanId`, `status?`, `resultPayload?`): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:735](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L735) #### Parameters [Section titled “Parameters”](#parameters-3) ##### sessionKey [Section titled “sessionKey”](#sessionkey-2) `string` ##### spanId [Section titled “spanId”](#spanid) `string` ##### status? [Section titled “status?”](#status-1) `"complete"` | `"failed"` | `"cancelled"` ##### resultPayload? [Section titled “resultPayload?”](#resultpayload) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-5) `Promise`<`void`> *** ### flushQueue() [Section titled “flushQueue()”](#flushqueue) > **flushQueue**(): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:775](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L775) #### Returns [Section titled “Returns”](#returns-6) `Promise`<`void`> # Interface: AgentConfig [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / AgentConfig # Interface: AgentConfig [Section titled “Interface: AgentConfig”](#interface-agentconfig) Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:124](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L124) Configuration for the Prefactor Agent HTTP client. ## Properties [Section titled “Properties”](#properties) ### apiUrl [Section titled “apiUrl”](#apiurl) > **apiUrl**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:125](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L125) Base URL of the Prefactor API. *** ### apiToken [Section titled “apiToken”](#apitoken) > **apiToken**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:126](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L126) Bearer token used to authenticate API requests. *** ### agentId [Section titled “agentId”](#agentid) > **agentId**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:127](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L127) Unique identifier for this agent in the Prefactor backend. *** ### maxRetries? [Section titled “maxRetries?”](#maxretries) > `optional` **maxRetries**: `number` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:128](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L128) Maximum number of retry attempts for failed HTTP requests. Defaults to `3`. *** ### initialRetryDelay? [Section titled “initialRetryDelay?”](#initialretrydelay) > `optional` **initialRetryDelay**: `number` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:129](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L129) Initial delay in milliseconds before the first retry, doubled on each subsequent attempt. Defaults to `1000`. *** ### requestTimeout? [Section titled “requestTimeout?”](#requesttimeout) > `optional` **requestTimeout**: `number` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:130](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L130) HTTP request timeout in milliseconds. Defaults to `30000`. *** ### openclawVersion? [Section titled “openclawVersion?”](#openclawversion) > `optional` **openclawVersion**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:131](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L131) Version string of the OpenClaw runtime (used in the agent version identifier). *** ### pluginVersion? [Section titled “pluginVersion?”](#pluginversion) > `optional` **pluginVersion**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:132](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L132) Version string of the Prefactor plugin (used in the agent and schema version identifiers). *** ### userAgentVersion? [Section titled “userAgentVersion?”](#useragentversion) > `optional` **userAgentVersion**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:133](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L133) Caller-supplied version tag appended to the agent version identifier. *** ### userAgentName? [Section titled “userAgentName?”](#useragentname) > `optional` **userAgentName**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:134](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L134) Human-readable name for this agent shown in the Prefactor UI. Defaults to `"OpenClaw Agent"`. *** ### spanTypeRiskConfigs? [Section titled “spanTypeRiskConfigs?”](#spantyperiskconfigs) > `optional` **spanTypeRiskConfigs**: `Record`<`string`, `DataRisk`> Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:135](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L135) # Interface: Logger [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / Logger # Interface: Logger [Section titled “Interface: Logger”](#interface-logger) Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:6](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L6) ## Methods [Section titled “Methods”](#methods) ### debug() [Section titled “debug()”](#debug) > **debug**(`event`, `data`): `void` Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:26](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L26) #### Parameters [Section titled “Parameters”](#parameters) ##### event [Section titled “event”](#event) `string` ##### data [Section titled “data”](#data) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns) `void` *** ### info() [Section titled “info()”](#info) > **info**(`event`, `data`): `void` Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:32](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L32) #### Parameters [Section titled “Parameters”](#parameters-1) ##### event [Section titled “event”](#event-1) `string` ##### data [Section titled “data”](#data-1) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-1) `void` *** ### warn() [Section titled “warn()”](#warn) > **warn**(`event`, `data`): `void` Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:38](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L38) #### Parameters [Section titled “Parameters”](#parameters-2) ##### event [Section titled “event”](#event-2) `string` ##### data [Section titled “data”](#data-2) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-2) `void` *** ### error() [Section titled “error()”](#error) > **error**(`event`, `data`): `void` Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:44](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L44) #### Parameters [Section titled “Parameters”](#parameters-3) ##### event [Section titled “event”](#event-3) `string` ##### data [Section titled “data”](#data-3) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-3) `void` *** ### setLevel() [Section titled “setLevel()”](#setlevel) > **setLevel**(`level`): `void` Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:50](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L50) #### Parameters [Section titled “Parameters”](#parameters-4) ##### level [Section titled “level”](#level) [`LogLevel`](../type-aliases/LogLevel.md) #### Returns [Section titled “Returns”](#returns-4) `void` # Interface: SessionStateManager [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / SessionStateManager # Interface: SessionStateManager [Section titled “Interface: SessionStateManager”](#interface-sessionstatemanager) Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:63](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L63) ## Methods [Section titled “Methods”](#methods) ### stop() [Section titled “stop()”](#stop) > **stop**(): `void` Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:102](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L102) #### Returns [Section titled “Returns”](#returns) `void` *** ### createSessionSpan() [Section titled “createSessionSpan()”](#createsessionspan) > **createSessionSpan**(`sessionKey`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:133](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L133) #### Parameters [Section titled “Parameters”](#parameters) ##### sessionKey [Section titled “sessionKey”](#sessionkey) `string` #### Returns [Section titled “Returns”](#returns-1) `Promise`<`string` | `null`> *** ### closeSessionSpan() [Section titled “closeSessionSpan()”](#closesessionspan) > **closeSessionSpan**(`sessionKey`): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:137](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L137) #### Parameters [Section titled “Parameters”](#parameters-1) ##### sessionKey [Section titled “sessionKey”](#sessionkey-1) `string` #### Returns [Section titled “Returns”](#returns-2) `Promise`<`void`> *** ### createOrGetInteractionSpan() [Section titled “createOrGetInteractionSpan()”](#createorgetinteractionspan) > **createOrGetInteractionSpan**(`sessionKey`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:141](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L141) #### Parameters [Section titled “Parameters”](#parameters-2) ##### sessionKey [Section titled “sessionKey”](#sessionkey-2) `string` #### Returns [Section titled “Returns”](#returns-3) `Promise`<`string` | `null`> *** ### closeInteractionSpan() [Section titled “closeInteractionSpan()”](#closeinteractionspan) > **closeInteractionSpan**(`sessionKey`, `status?`): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:145](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L145) #### Parameters [Section titled “Parameters”](#parameters-3) ##### sessionKey [Section titled “sessionKey”](#sessionkey-3) `string` ##### status? [Section titled “status?”](#status) `"complete"` | `"failed"` | `"cancelled"` #### Returns [Section titled “Returns”](#returns-4) `Promise`<`void`> *** ### createUserMessageSpan() [Section titled “createUserMessageSpan()”](#createusermessagespan) > **createUserMessageSpan**(`sessionKey`, `payload`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:152](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L152) #### Parameters [Section titled “Parameters”](#parameters-4) ##### sessionKey [Section titled “sessionKey”](#sessionkey-4) `string` ##### payload [Section titled “payload”](#payload) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-5) `Promise`<`string` | `null`> *** ### createAgentRunSpan() [Section titled “createAgentRunSpan()”](#createagentrunspan) > **createAgentRunSpan**(`sessionKey`, `payload`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:159](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L159) #### Parameters [Section titled “Parameters”](#parameters-5) ##### sessionKey [Section titled “sessionKey”](#sessionkey-5) `string` ##### payload [Section titled “payload”](#payload-1) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-6) `Promise`<`string` | `null`> *** ### closeAgentRunSpan() [Section titled “closeAgentRunSpan()”](#closeagentrunspan) > **closeAgentRunSpan**(`sessionKey`, `status?`): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:166](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L166) #### Parameters [Section titled “Parameters”](#parameters-6) ##### sessionKey [Section titled “sessionKey”](#sessionkey-6) `string` ##### status? [Section titled “status?”](#status-1) `"complete"` | `"failed"` | `"cancelled"` #### Returns [Section titled “Returns”](#returns-7) `Promise`<`void`> *** ### createToolCallSpan() [Section titled “createToolCallSpan()”](#createtoolcallspan) > **createToolCallSpan**(`sessionKey`, `toolName`, `payload`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:173](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L173) #### Parameters [Section titled “Parameters”](#parameters-7) ##### sessionKey [Section titled “sessionKey”](#sessionkey-7) `string` ##### toolName [Section titled “toolName”](#toolname) `string` ##### payload [Section titled “payload”](#payload-2) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-8) `Promise`<`string` | `null`> *** ### closeToolCallSpanWithResult() [Section titled “closeToolCallSpanWithResult()”](#closetoolcallspanwithresult) > **closeToolCallSpanWithResult**(`sessionKey`, `toolCallId`, `toolName`, `resultText`, `isError`): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:183](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L183) #### Parameters [Section titled “Parameters”](#parameters-8) ##### sessionKey [Section titled “sessionKey”](#sessionkey-8) `string` ##### toolCallId [Section titled “toolCallId”](#toolcallid) `string` ##### toolName [Section titled “toolName”](#toolname-1) `string` ##### resultText [Section titled “resultText”](#resulttext) `string` | `undefined` ##### isError [Section titled “isError”](#iserror) `boolean` #### Returns [Section titled “Returns”](#returns-9) `Promise`<`void`> *** ### createAssistantResponseSpan() [Section titled “createAssistantResponseSpan()”](#createassistantresponsespan) > **createAssistantResponseSpan**(`sessionKey`, `text`, `tokens`, `metadata?`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:195](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L195) #### Parameters [Section titled “Parameters”](#parameters-9) ##### sessionKey [Section titled “sessionKey”](#sessionkey-9) `string` ##### text [Section titled “text”](#text) `string` ##### tokens [Section titled “tokens”](#tokens) { `input?`: `number`; `output?`: `number`; `cacheRead?`: `number`; `cacheWrite?`: `number`; `total?`: `number`; } | `undefined` ##### metadata? [Section titled “metadata?”](#metadata) ###### provider? [Section titled “provider?”](#provider) `string` ###### model? [Section titled “model?”](#model) `string` #### Returns [Section titled “Returns”](#returns-10) `Promise`<`string` | `null`> *** ### createAgentThinkingSpan() [Section titled “createAgentThinkingSpan()”](#createagentthinkingspan) > **createAgentThinkingSpan**(`sessionKey`, `thinking`, `tokens`, `metadata?`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:208](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L208) #### Parameters [Section titled “Parameters”](#parameters-10) ##### sessionKey [Section titled “sessionKey”](#sessionkey-10) `string` ##### thinking [Section titled “thinking”](#thinking) `string` ##### tokens [Section titled “tokens”](#tokens-1) { `input?`: `number`; `output?`: `number`; `cacheRead?`: `number`; `cacheWrite?`: `number`; `total?`: `number`; } | `undefined` ##### metadata? [Section titled “metadata?”](#metadata-1) ###### provider? [Section titled “provider?”](#provider-1) `string` ###### model? [Section titled “model?”](#model-1) `string` ###### signature? [Section titled “signature?”](#signature) `string` #### Returns [Section titled “Returns”](#returns-11) `Promise`<`string` | `null`> *** ### cleanupAllSessions() [Section titled “cleanupAllSessions()”](#cleanupallsessions) > **cleanupAllSessions**(): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:221](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L221) #### Returns [Section titled “Returns”](#returns-12) `Promise`<`void`> *** ### getSessionState() [Section titled “getSessionState()”](#getsessionstate) > **getSessionState**(`sessionKey`): `SessionSpanState` | `undefined` Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:243](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L243) #### Parameters [Section titled “Parameters”](#parameters-11) ##### sessionKey [Section titled “sessionKey”](#sessionkey-11) `string` #### Returns [Section titled “Returns”](#returns-13) `SessionSpanState` | `undefined` *** ### getAllSessionKeys() [Section titled “getAllSessionKeys()”](#getallsessionkeys) > **getAllSessionKeys**(): `string`\[] Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:247](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L247) #### Returns [Section titled “Returns”](#returns-14) `string`\[] *** ### hasActiveInteraction() [Section titled “hasActiveInteraction()”](#hasactiveinteraction) > **hasActiveInteraction**(`sessionKey`): `boolean` Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:251](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L251) #### Parameters [Section titled “Parameters”](#parameters-12) ##### sessionKey [Section titled “sessionKey”](#sessionkey-12) `string` #### Returns [Section titled “Returns”](#returns-15) `boolean` # Interface: ToolDefinition [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / ToolDefinition # Interface: ToolDefinition [Section titled “Interface: ToolDefinition”](#interface-tooldefinition) Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:9](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L9) Input schemas for supported OpenClaw tools. These define the expected parameters for each tool to enable proper validation and structured span capture. ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:10](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L10) *** ### description [Section titled “description”](#description) > **description**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:11](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L11) *** ### inputSchema [Section titled “inputSchema”](#inputschema) > **inputSchema**: `JsonSchema` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:12](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L12) *** ### aliases? [Section titled “aliases?”](#aliases) > `optional` **aliases**: `string`\[] Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:13](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L13) # Type Alias: LogLevel [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / LogLevel # Type Alias: LogLevel [Section titled “Type Alias: LogLevel”](#type-alias-loglevel) > **LogLevel** = `"debug"` | `"info"` | `"warn"` | `"error"` Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:4](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L4) # Variable: agentRunRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / agentRunRisk # Variable: agentRunRisk [Section titled “Variable: agentRunRisk”](#variable-agentrunrisk) > `const` **agentRunRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:64](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L64) Default risk profile for openclaw:agent\_run span. Agent runs orchestrate operations but don’t directly handle data mutations. # Variable: agentThinkingRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / agentThinkingRisk # Variable: agentThinkingRisk [Section titled “Variable: agentThinkingRisk”](#variable-agentthinkingrisk) > `const` **agentThinkingRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:81](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L81) Default risk profile for openclaw:agent\_thinking span. Thinking spans contain reasoning that may reference organizational confidential data. # Variable: assistantResponseRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / assistantResponseRisk # Variable: assistantResponseRisk [Section titled “Variable: assistantResponseRisk”](#variable-assistantresponserisk) > `const` **assistantResponseRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:98](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L98) Default risk profile for openclaw:assistant\_response span. Assistant responses may contain organizational confidential information from context. # Variable: defaultSpanTypeRiskConfigs [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / defaultSpanTypeRiskConfigs # Variable: defaultSpanTypeRiskConfigs [Section titled “Variable: defaultSpanTypeRiskConfigs”](#variable-defaultspantyperiskconfigs) > `const` **defaultSpanTypeRiskConfigs**: `Record`<`string`, `DataRisk`> Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:317](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L317) Complete default risk configuration for all OpenClaw span types. This configuration is used when registering the agent schema version. # Variable: GENERIC\_OBJECT\_SCHEMA [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / GENERIC\_OBJECT\_SCHEMA # Variable: GENERIC\_OBJECT\_SCHEMA [Section titled “Variable: GENERIC\_OBJECT\_SCHEMA”](#variable-generic_object_schema) > `const` **GENERIC\_OBJECT\_SCHEMA**: `object` Defined in: [packages/openclaw-prefactor-plugin/src/tool-span-contract.ts:6](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-span-contract.ts#L6) Generic object schema for flexible metadata. ## Type Declaration [Section titled “Type Declaration”](#type-declaration) ### type [Section titled “type”](#type) > **type**: `"object"` ### additionalProperties [Section titled “additionalProperties”](#additionalproperties) > **additionalProperties**: `boolean` = `true` # Variable: sessionRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / sessionRisk # Variable: sessionRisk [Section titled “Variable: sessionRisk”](#variable-sessionrisk) > `const` **sessionRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:115](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L115) Default risk profile for openclaw:session span. Session spans track lifecycle but contain minimal data. # Variable: SUPPORTED\_TOOL\_DEFINITIONS [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / SUPPORTED\_TOOL\_DEFINITIONS # Variable: SUPPORTED\_TOOL\_DEFINITIONS [Section titled “Variable: SUPPORTED\_TOOL\_DEFINITIONS”](#variable-supported_tool_definitions) > `const` **SUPPORTED\_TOOL\_DEFINITIONS**: `Record`<`string`, [`ToolDefinition`](../interfaces/ToolDefinition.md)> Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:20](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L20) Map of canonical tool names to their definitions. Aliases are normalized to canonical names during span creation. # Variable: TOOL\_ALIAS\_MAP [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / TOOL\_ALIAS\_MAP # Variable: TOOL\_ALIAS\_MAP [Section titled “Variable: TOOL\_ALIAS\_MAP”](#variable-tool_alias_map) > `const` **TOOL\_ALIAS\_MAP**: `Record`<`string`, `string`> Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:365](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L365) Map of tool aliases to their canonical names. Used for normalizing tool names during span creation. # Variable: toolBrowserRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolBrowserRisk # Variable: toolBrowserRisk [Section titled “Variable: toolBrowserRisk”](#variable-toolbrowserrisk) > `const` **toolBrowserRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:300](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L300) Default risk profile for openclaw:tool:browser span. Browser automation interacts with external web services. # Variable: toolEditRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolEditRisk # Variable: toolEditRisk [Section titled “Variable: toolEditRisk”](#variable-tooleditrisk) > `const` **toolEditRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:216](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L216) Default risk profile for openclaw:tool:edit span. Edit operations modify data which may include organizational confidential info and secrets. # Variable: toolExecRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolExecRisk # Variable: toolExecRisk [Section titled “Variable: toolExecRisk”](#variable-toolexecrisk) > `const` **toolExecRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:241](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L241) Default risk profile for openclaw:tool:exec span. Shell execution is high-risk - can access secrets and execute arbitrary commands. # Variable: toolReadRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolReadRisk # Variable: toolReadRisk [Section titled “Variable: toolReadRisk”](#variable-toolreadrisk) > `const` **toolReadRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:166](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L166) Default risk profile for openclaw:tool:read span. Read operations access filesystem data which may include organizational confidential info and secrets. # Variable: toolRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolRisk # Variable: toolRisk [Section titled “Variable: toolRisk”](#variable-toolrisk) > `const` **toolRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:149](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L149) Default risk profile for openclaw:tool span (generic fallback). Generic tool calls have unknown risk until specific tool is identified. # Variable: toolWebFetchRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolWebFetchRisk # Variable: toolWebFetchRisk [Section titled “Variable: toolWebFetchRisk”](#variable-toolwebfetchrisk) > `const` **toolWebFetchRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:283](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L283) Default risk profile for openclaw:tool:web\_fetch span. Web fetch retrieves public content from external URLs. # Variable: toolWebSearchRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolWebSearchRisk # Variable: toolWebSearchRisk [Section titled “Variable: toolWebSearchRisk”](#variable-toolwebsearchrisk) > `const` **toolWebSearchRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:266](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L266) Default risk profile for openclaw:tool:web\_search span. Web search sends queries to external services but doesn’t typically include sensitive data. # Variable: toolWriteRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolWriteRisk # Variable: toolWriteRisk [Section titled “Variable: toolWriteRisk”](#variable-toolwriterisk) > `const` **toolWriteRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:191](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L191) Default risk profile for openclaw:tool:write span. Write operations create data which may include organizational confidential info. # Variable: userInteractionRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / userInteractionRisk # Variable: userInteractionRisk [Section titled “Variable: userInteractionRisk”](#variable-userinteractionrisk) > `const` **userInteractionRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:132](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L132) Default risk profile for openclaw:user\_interaction span. User interactions may involve organizational confidential data. # Variable: userMessageRisk [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / userMessageRisk # Variable: userMessageRisk [Section titled “Variable: userMessageRisk”](#variable-usermessagerisk) > `const` **userMessageRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:47](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L47) Default risk profile for openclaw:user\_message span. User messages may contain any type of data including organizational confidential information. # Prefactor SDK for TypeScript **Prefactor TypeScript SDK** *** # Prefactor SDK for TypeScript [Section titled “Prefactor SDK for TypeScript”](#prefactor-sdk-for-typescript) Automatic observability for LangChain.js agents. Capture distributed traces of LLM calls, tool executions, and agent workflows with minimal integration effort. ## Links [Section titled “Links”](#links) * Docs: * DeepWiki: * GitHub: ## Features [Section titled “Features”](#features) * Automatic tracing of LLM calls with token usage * Tool execution tracking * Agent workflow visualization * Parent-child span relationships * Error tracking and debugging * Zero-overhead instrumentation * TypeScript type safety * HTTP transport with retry and queue controls ## Monorepo Structure [Section titled “Monorepo Structure”](#monorepo-structure) This repository is a Bun monorepo containing three packages: | Package | Description | | ------------------------------------------ | ------------------------------------------- | | [`@prefactor/core`](_media/core) | Framework-agnostic observability primitives | | [`@prefactor/langchain`](_media/langchain) | LangChain.js integration | | [`@prefactor/ai`](_media/ai) | Vercel AI SDK integration | Install `@prefactor/core` along with the adapter package for your framework. ## Installation [Section titled “Installation”](#installation) ### For LangChain.js users: [Section titled “For LangChain.js users:”](#for-langchainjs-users) ```bash npm install @prefactor/core @prefactor/langchain # or bun add @prefactor/core @prefactor/langchain ``` ### For Vercel AI SDK users: [Section titled “For Vercel AI SDK users:”](#for-vercel-ai-sdk-users) ```bash npm install @prefactor/core @prefactor/ai # or bun add @prefactor/core @prefactor/ai ``` ## Quick Start [Section titled “Quick Start”](#quick-start) ### For LangChain.js users: [Section titled “For LangChain.js users:”](#for-langchainjs-users-1) ```typescript import { createAgent, tool } from 'langchain'; import { z } from 'zod'; import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); // Create your agent with middleware const agent = createAgent({ model: 'claude-sonnet-4-5-20250929', tools: [], systemPrompt: 'You are a helpful assistant.', middleware: [prefactor.getMiddleware()], }); // All operations are automatically traced! const result = await agent.invoke({ messages: [{ role: 'user', content: 'What is 2+2?' }], }); console.log(result.messages[result.messages.length - 1].content); await prefactor.shutdown(); ``` Refer to the [Langchain specific documentation](_media/README.md) for more details. ### For Vercel AI SDK users: [Section titled “For Vercel AI SDK users:”](#for-vercel-ai-sdk-users-1) ```typescript import { init } from '@prefactor/core'; import { PrefactorAISDK } from '@prefactor/ai'; import { generateText, wrapLanguageModel } from 'ai'; import { anthropic } from '@ai-sdk/anthropic'; const prefactor = init({ provider: new PrefactorAISDK(), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); // Wrap your model with the middleware const model = wrapLanguageModel({ model: anthropic('claude-3-haiku-20240307'), middleware: prefactor.getMiddleware(), }); // All operations are automatically traced! const result = await generateText({ model, prompt: 'What is 2+2?', }); console.log(result.text); await prefactor.shutdown(); ``` Refer to the [Vercel AI SDK specific documentation](_media/README-1.md) for more details. ## Configuration [Section titled “Configuration”](#configuration) ### Environment Variables [Section titled “Environment Variables”](#environment-variables) The SDK can be configured using environment variables: * `PREFACTOR_API_URL`: API endpoint for HTTP transport * `PREFACTOR_API_TOKEN`: Authentication token for HTTP transport * `PREFACTOR_SAMPLE_RATE`: Sampling rate 0.0-1.0 (default: `1.0`) * `PREFACTOR_CAPTURE_INPUTS`: Capture span inputs (default: `true`) * `PREFACTOR_CAPTURE_OUTPUTS`: Capture span outputs (default: `true`) * `PREFACTOR_MAX_INPUT_LENGTH`: Max input string length (default: `10000`) * `PREFACTOR_MAX_OUTPUT_LENGTH`: Max output string length (default: `10000`) * `PREFACTOR_LOG_LEVEL`: `"debug"` | `"info"` | `"warn"` | `"error"` (default: `"info"`) ### Programmatic Configuration [Section titled “Programmatic Configuration”](#programmatic-configuration) ```typescript import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentId: 'my-agent', agentIdentifier: '1.0.0', }, }); // Custom sampling const prefactorWithSampling = init({ provider: new PrefactorLangChain(), sampleRate: 0.1, // Sample 10% of traces maxInputLength: 5000, maxOutputLength: 5000, httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); ``` ## Transports [Section titled “Transports”](#transports) ### HTTP Transport [Section titled “HTTP Transport”](#http-transport) The HTTP transport sends spans to a remote API endpoint with retry logic and queue-based processing. ```typescript import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentId: 'my-agent', agentIdentifier: '1.0.0', maxRetries: 3, requestTimeout: 30000, }, }); ``` ## API Reference [Section titled “API Reference”](#api-reference) ### `@prefactor/core` [Section titled “@prefactor/core”](#prefactorcore) #### `init(options: PrefactorOptions): PrefactorClient` [Section titled “init(options: PrefactorOptions): PrefactorClient”](#initoptions-prefactoroptions-prefactorclient) Initialize a process-wide Prefactor client and create provider middleware. **Parameters:** * `options.provider` - Provider implementation (for example `new PrefactorLangChain()`) * `options.httpConfig` - HTTP transport configuration **Returns:** * `PrefactorClient` with `getMiddleware()`, `getTracer()`, `withSpan()`, and `shutdown()` **Example:** ```typescript import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); ``` ### `@prefactor/ai` [Section titled “@prefactor/ai”](#prefactorai) #### `PrefactorAISDK` [Section titled “PrefactorAISDK”](#prefactoraisdk) Provider used with core `init` for Vercel AI SDK middleware. **Parameters:** * `options.middleware` - Optional middleware-specific config (e.g., `captureContent`) * `options.agentSchema` - Optional custom agent schema **Returns:** * Provider instance consumed by `@prefactor/core` `init` **Example:** ```typescript import { init } from '@prefactor/core'; import { PrefactorAISDK } from '@prefactor/ai'; const prefactor = init({ provider: new PrefactorAISDK({ middleware: { captureContent: false }, }), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); ``` ### `PrefactorClient.shutdown(): Promise` [Section titled “PrefactorClient.shutdown(): Promise\”](#prefactorclientshutdown-promisevoid) Flush pending spans and close connections. Call before application exit. **Example:** ```typescript import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, }, }); process.on('SIGTERM', async () => { await prefactor.shutdown(); process.exit(0); }); ``` ### `PrefactorClient.getTracer(): Tracer` [Section titled “PrefactorClient.getTracer(): Tracer”](#prefactorclientgettracer-tracer) Get the global tracer instance for manual instrumentation. **Returns:** * `Tracer` - Tracer instance **Example:** ```typescript import { init, SpanType } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, }, }); const tracer = prefactor.getTracer(); const span = tracer.startSpan({ name: 'custom-operation', spanType: SpanType.TOOL, inputs: { data: 'example' }, }); try { // ... do work ... tracer.endSpan(span, { outputs: { result: 'done' } }); } catch (error) { tracer.endSpan(span, { error }); } ``` ## Advanced Usage [Section titled “Advanced Usage”](#advanced-usage) ### Manual Instrumentation [Section titled “Manual Instrumentation”](#manual-instrumentation) For operations not automatically traced by the middleware: ```typescript import { getTracer, SpanType } from '@prefactor/langchain'; const tracer = getTracer(); const span = tracer.startSpan({ name: 'database-query', spanType: SpanType.TOOL, inputs: { query: 'SELECT * FROM users' }, metadata: { database: 'postgres' }, tags: ['database', 'query'], }); try { const result = await db.query('SELECT * FROM users'); tracer.endSpan(span, { outputs: { rowCount: result.rows.length } }); } catch (error) { tracer.endSpan(span, { error }); } ``` ### Context Propagation [Section titled “Context Propagation”](#context-propagation) The SDK automatically propagates span context through async operations using Node.js AsyncLocalStorage. Child spans automatically inherit the trace ID and parent span ID from the current context. ```typescript import { SpanContext } from '@prefactor/langchain'; // Get the current span (if any) const currentSpan = SpanContext.getCurrent(); // Child spans automatically use the current span as parent const child = tracer.startSpan({ name: 'child-operation', spanType: SpanType.TOOL, inputs: {}, parentSpanId: currentSpan?.spanId, traceId: currentSpan?.traceId, }); ``` ## TypeScript Support [Section titled “TypeScript Support”](#typescript-support) The SDK is written in TypeScript and provides full type definitions: ```typescript import type { Config, HttpTransportConfig, Span, SpanType, SpanStatus, TokenUsage, ErrorInfo } from '@prefactor/core'; const config: Config = { transportType: 'http', sampleRate: 1.0, captureInputs: true, captureOutputs: true, httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, }, }; ``` ## Examples [Section titled “Examples”](#examples) See the `examples/` directory for complete examples: * [`examples/langchain/simple-agent.ts`](_media/simple-agent.ts) - Full working example with LangChain * [`examples/langchain/termination-demo.ts`](_media/termination-demo.ts) - LangChain agent termination example * [`examples/ai-sdk/simple-agent.ts`](_media/simple-agent-1.ts) - Vercel AI SDK example with tools * [`examples/ai-sdk/custom-schema.ts`](_media/custom-schema.ts) - Vercel AI SDK example with a custom agent schema * [`examples/livekit/simple-session.ts`](_media/simple-session.ts) - LiveKit session example * [`examples/claude-agent/simple-agent.ts`](_media/simple-agent-2.ts) - Claude agent example ## Skills [Section titled “Skills”](#skills) This repo includes reusable skills for coding tools and AI agents. ### Install via skills CLI (recommended) [Section titled “Install via skills CLI (recommended)”](#install-via-skills-cli-recommended) ```bash # Install skills from this repository bunx skills add https://github.com/prefactordev/typescript-sdk/ ``` ### LLM instructions (Copy/Paste) [Section titled “LLM instructions (Copy/Paste)”](#llm-instructions-copypaste) Use this when a tool does not support direct skills installation yet: ```text Clone the skills repo to a temporary folder, copy the skill folders, then delete the clone. 1) git clone https://github.com/prefactordev/typescript-sdk /tmp/prefactor-skills 2) Copy the folders into your coding tool's local skills directory: - /tmp/prefactor-skills/skills 3) Delete the temporary clone: rm -rf /tmp/prefactor-skills ``` ## Architecture [Section titled “Architecture”](#architecture) The SDK consists of five main layers: 1. **Tracing Layer**: Span data models, Tracer for lifecycle management, Context propagation 2. **Transport Layer**: HTTP backend with resilient queueing for span emission 3. **Instrumentation Layer**: LangChain.js and Vercel AI SDK middleware integrations 4. **Configuration**: Environment variable support, validation with Zod 5. **Utilities**: Logging, serialization helpers ## Requirements [Section titled “Requirements”](#requirements) * Node.js >= 22.0.0 * TypeScript >= 5.0.0 (for TypeScript projects) * Bun >= 1.0.0 (optional, for development) * LangChain.js >= 1.0.0 (peer dependency for `@prefactor/langchain`) * AI SDK ^4.0.0 || ^5.0.0 || ^6.0.0 (peer dependency for `@prefactor/ai`) ## Development [Section titled “Development”](#development) This project uses Bun with mise for toolchain management. ```bash # Install toolchain mise install # Install dependencies (monorepo-wide) mise run install ``` ```bash # Build all packages mise run build # Run tests mise run test # Type check mise run typecheck # Lint mise run lint # Format mise run format # Run all checks (typecheck + lint + test) mise run check # Clean build artifacts mise run clean ``` ### Per-Package Commands [Section titled “Per-Package Commands”](#per-package-commands) ```bash # Build a specific package bun --filter @prefactor/core build # Run tests for a specific package bun test packages/core/tests/ ``` ## License [Section titled “License”](#license) MIT ## Support [Section titled “Support”](#support) * Documentation: * Issues: [GitHub Issues](https://github.com/prefactordev/typescript-sdk/issues) * Email: # @prefactor/ai [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / @prefactor/ai # @prefactor/ai [Section titled “@prefactor/ai”](#prefactorai) Prefactor middleware integration for the Vercel AI SDK. ## `@prefactor/ai` overview [Section titled “@prefactor/ai overview”](#prefactorai-overview) `@prefactor/ai` connects Vercel AI SDK model calls to Prefactor tracing. It captures agent, model, and tool spans and sends them through your configured transport. Use this package as a provider for the core `init` function. ## Quick start [Section titled “Quick start”](#quick-start) ```ts import { init } from '@prefactor/core'; import { PrefactorAISDK } from '@prefactor/ai'; import { generateText, wrapLanguageModel } from 'ai'; import { anthropic } from '@ai-sdk/anthropic'; const prefactor = init({ provider: new PrefactorAISDK(), httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: 'chat-app-v1', }, }); const model = wrapLanguageModel({ model: anthropic('claude-3-haiku-20240307'), middleware: prefactor.getMiddleware(), }); const result = await generateText({ model, prompt: 'Hello!', }); await prefactor.shutdown(); ``` ## Functions [Section titled “Functions”](#functions) * [getTracer](functions/getTracer.md) * [init](functions/init.md) * [withSpan](functions/withSpan.md) ## Classes [Section titled “Classes”](#classes) * [PrefactorAISDK](classes/PrefactorAISDK.md) ## Interfaces [Section titled “Interfaces”](#interfaces) * [PrefactorAISDKOptions](interfaces/PrefactorAISDKOptions.md) * [MiddlewareConfig](interfaces/MiddlewareConfig.md) ## Type Aliases [Section titled “Type Aliases”](#type-aliases) * [ManualSpanOptions](type-aliases/ManualSpanOptions.md) ## Variables [Section titled “Variables”](#variables) * [DEFAULT\_AI\_AGENT\_SCHEMA](variables/DEFAULT_AI_AGENT_SCHEMA.md) # Class: PrefactorAISDK [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/ai](../index.md) / PrefactorAISDK # Class: PrefactorAISDK [Section titled “Class: PrefactorAISDK”](#class-prefactoraisdk) Defined in: [packages/ai/src/provider.ts:18](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L18) ## Implements [Section titled “Implements”](#implements) * `PrefactorProvider`<`LanguageModelMiddleware`> ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new PrefactorAISDK**(`options?`): `PrefactorAISDK` Defined in: [packages/ai/src/provider.ts:24](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L24) #### Parameters [Section titled “Parameters”](#parameters) ##### options? [Section titled “options?”](#options) [`PrefactorAISDKOptions`](../interfaces/PrefactorAISDKOptions.md) = `{}` #### Returns [Section titled “Returns”](#returns) `PrefactorAISDK` ## Methods [Section titled “Methods”](#methods) ### createMiddleware() [Section titled “createMiddleware()”](#createmiddleware) > **createMiddleware**(`tracer`, `agentManager`, `coreConfig`, `_getAbortSignal?`): `LanguageModelV3Middleware` Defined in: [packages/ai/src/provider.ts:28](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L28) Creates provider middleware bound to the core runtime services. #### Parameters [Section titled “Parameters”](#parameters-1) ##### tracer [Section titled “tracer”](#tracer) `Tracer` Runtime tracer used for span creation. ##### agentManager [Section titled “agentManager”](#agentmanager) `AgentInstanceManager` Runtime agent instance manager. ##### coreConfig [Section titled “coreConfig”](#coreconfig) ##### \_getAbortSignal? [Section titled “\_getAbortSignal?”](#_getabortsignal) () => `AbortSignal` #### Returns [Section titled “Returns”](#returns-1) `LanguageModelV3Middleware` Provider middleware consumed by upstream frameworks. #### Implementation of [Section titled “Implementation of”](#implementation-of) `PrefactorProvider.createMiddleware` *** ### shutdown() [Section titled “shutdown()”](#shutdown) > **shutdown**(): `void` Defined in: [packages/ai/src/provider.ts:57](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L57) Optional provider-level cleanup hook invoked during client shutdown. #### Returns [Section titled “Returns”](#returns-2) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-1) `PrefactorProvider.shutdown` *** ### getSdkHeaderEntry() [Section titled “getSdkHeaderEntry()”](#getsdkheaderentry) > **getSdkHeaderEntry**(): `string` Defined in: [packages/ai/src/provider.ts:67](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L67) Returns the SDK header entry to append to HTTP requests created by the core runtime. #### Returns [Section titled “Returns”](#returns-3) `string` Adapter-specific SDK identifier, or `undefined` to use the core header only. #### Implementation of [Section titled “Implementation of”](#implementation-of-2) `PrefactorProvider.getSdkHeaderEntry` *** ### normalizeAgentSchema() [Section titled “normalizeAgentSchema()”](#normalizeagentschema) > **normalizeAgentSchema**(`agentSchema`): `Record`<`string`, `unknown`> Defined in: [packages/ai/src/provider.ts:71](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L71) Normalizes a user- or provider-authored agent schema before core registers it. #### Parameters [Section titled “Parameters”](#parameters-2) ##### agentSchema [Section titled “agentSchema”](#agentschema) `Record`<`string`, `unknown`> Authored agent schema configuration. #### Returns [Section titled “Returns”](#returns-4) `Record`<`string`, `unknown`> Normalized schema, or `undefined` to leave the input unchanged. #### Implementation of [Section titled “Implementation of”](#implementation-of-3) `PrefactorProvider.normalizeAgentSchema` *** ### getDefaultAgentSchema() [Section titled “getDefaultAgentSchema()”](#getdefaultagentschema) > **getDefaultAgentSchema**(): `Record`<`string`, `unknown`> | `undefined` Defined in: [packages/ai/src/provider.ts:77](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L77) Provides a default agent schema when a user does not supply one. #### Returns [Section titled “Returns”](#returns-5) `Record`<`string`, `unknown`> | `undefined` Agent schema object, or `undefined` when no default is available. #### Implementation of [Section titled “Implementation of”](#implementation-of-4) `PrefactorProvider.getDefaultAgentSchema` # Function: getTracer() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/ai](../index.md) / getTracer # Function: getTracer() [Section titled “Function: getTracer()”](#function-gettracer) > **getTracer**(): `Tracer` Defined in: [packages/ai/src/init.ts:198](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L198) Get the current tracer instance. If no tracer has been created yet, this will call init() with default configuration. ## Returns [Section titled “Returns”](#returns) `Tracer` Tracer instance ## Example [Section titled “Example”](#example) ```typescript import { getTracer } from '@prefactor/ai'; const tracer = getTracer(); // Use for custom span creation const span = tracer.startSpan({ name: 'custom-operation', spanType: SpanType.CHAIN, }); ``` # Function: init() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/ai](../index.md) / init # Function: init() [Section titled “Function: init()”](#function-init) > **init**(`config?`, `middlewareConfig?`): `LanguageModelV3Middleware` Defined in: [packages/ai/src/init.ts:133](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L133) Initialize the Prefactor AI middleware and return it for use with wrapLanguageModel. This is the main entry point for the SDK. Call this function to create a middleware instance that you can pass to the Vercel AI SDK’s wrapLanguageModel function. ## Parameters [Section titled “Parameters”](#parameters) ### config? [Section titled “config?”](#config) `Partial`<{ }> Optional configuration object for transport settings ### middlewareConfig? [Section titled “middlewareConfig?”](#middlewareconfig) [`MiddlewareConfig`](../interfaces/MiddlewareConfig.md) Optional middleware-specific configuration ## Returns [Section titled “Returns”](#returns) `LanguageModelV3Middleware` Middleware object to use with wrapLanguageModel ## Examples [Section titled “Examples”](#examples) ```typescript import { init, shutdown } from '@prefactor/ai'; import { generateText, wrapLanguageModel } from 'ai'; import { anthropic } from '@ai-sdk/anthropic'; // Initialize with HTTP transport config const middleware = init({ transportType: 'http', httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }); // Wrap your model with the middleware const model = wrapLanguageModel({ model: anthropic('claude-3-haiku-20240307'), middleware, }); const result = await generateText({ model, prompt: 'Hello!', }); await shutdown(); ``` ```typescript const middleware = init({ transportType: 'http', httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentId: process.env.PREFACTOR_AGENT_ID, agentIdentifier: '1.0.0', }, }); ``` ```typescript const middleware = init( { transportType: 'http', httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: '1.0.0', }, }, { captureContent: false } // Don't capture prompts/responses ); ``` # Function: withSpan() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/ai](../index.md) / withSpan # Function: withSpan() [Section titled “Function: withSpan()”](#function-withspan) > **withSpan**<`T`>(`options`, `fn`): `Promise`<`T`> Defined in: [packages/ai/src/init.ts:213](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L213) Wraps a function in a manual span using the shared core helper. ## Type Parameters [Section titled “Type Parameters”](#type-parameters) ### T [Section titled “T”](#t) `T` ## Parameters [Section titled “Parameters”](#parameters) ### options [Section titled “options”](#options) [`ManualSpanOptions`](../type-aliases/ManualSpanOptions.md) Manual span options. ### fn [Section titled “fn”](#fn) () => `T` | `Promise`<`T`> Function to execute in span context. ## Returns [Section titled “Returns”](#returns) `Promise`<`T`> Result from `fn`. # Interface: MiddlewareConfig [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/ai](../index.md) / MiddlewareConfig # Interface: MiddlewareConfig [Section titled “Interface: MiddlewareConfig”](#interface-middlewareconfig) Defined in: [packages/ai/src/types.ts:16](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/types.ts#L16) Configuration options for the Prefactor middleware. ## Properties [Section titled “Properties”](#properties) ### captureContent? [Section titled “captureContent?”](#capturecontent) > `optional` **captureContent**: `boolean` Defined in: [packages/ai/src/types.ts:22](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/types.ts#L22) Whether to capture prompt and response content in span inputs/outputs. Set to false to reduce data volume or for privacy reasons. #### Default [Section titled “Default”](#default) ```ts true ``` *** ### captureTools? [Section titled “captureTools?”](#capturetools) > `optional` **captureTools**: `boolean` Defined in: [packages/ai/src/types.ts:28](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/types.ts#L28) Whether to capture tool call information. #### Default [Section titled “Default”](#default-1) ```ts true ``` # Interface: PrefactorAISDKOptions [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/ai](../index.md) / PrefactorAISDKOptions # Interface: PrefactorAISDKOptions [Section titled “Interface: PrefactorAISDKOptions”](#interface-prefactoraisdkoptions) Defined in: [packages/ai/src/provider.ts:13](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L13) ## Properties [Section titled “Properties”](#properties) ### middleware? [Section titled “middleware?”](#middleware) > `optional` **middleware**: [`MiddlewareConfig`](MiddlewareConfig.md) Defined in: [packages/ai/src/provider.ts:14](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L14) *** ### agentSchema? [Section titled “agentSchema?”](#agentschema) > `optional` **agentSchema**: `Record`<`string`, `unknown`> Defined in: [packages/ai/src/provider.ts:15](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L15) # Type Alias: ManualSpanOptions [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/ai](../index.md) / ManualSpanOptions # Type Alias: ManualSpanOptions [Section titled “Type Alias: ManualSpanOptions”](#type-alias-manualspanoptions) > **ManualSpanOptions** = `object` Defined in: [packages/ai/src/init.ts:54](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L54) ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/ai/src/init.ts:56](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L56) Span name shown in traces. *** ### spanType [Section titled “spanType”](#spantype) > **spanType**: `string` Defined in: [packages/ai/src/init.ts:58](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L58) Provider-prefixed span type (for example `ai-sdk:llm`). *** ### inputs [Section titled “inputs”](#inputs) > **inputs**: `Record`<`string`, `unknown`> Defined in: [packages/ai/src/init.ts:60](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L60) Inputs recorded for the wrapped work. *** ### metadata? [Section titled “metadata?”](#metadata) > `optional` **metadata**: `Record`<`string`, `unknown`> Defined in: [packages/ai/src/init.ts:62](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/init.ts#L62) Optional additional metadata to attach to the span. # Variable: DEFAULT\_AI\_AGENT\_SCHEMA [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/ai](../index.md) / DEFAULT\_AI\_AGENT\_SCHEMA # Variable: DEFAULT\_AI\_AGENT\_SCHEMA [Section titled “Variable: DEFAULT\_AI\_AGENT\_SCHEMA”](#variable-default_ai_agent_schema) > `const` **DEFAULT\_AI\_AGENT\_SCHEMA**: `object` = `DEFAULT_AI_AGENT_SCHEMA_BASE` Defined in: [packages/ai/src/provider.ts:10](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/ai/src/provider.ts#L10) ## Type Declaration [Section titled “Type Declaration”](#type-declaration) ### external\_identifier [Section titled “external\_identifier”](#external_identifier) > `readonly` **external\_identifier**: `"ai-sdk-schema"` = `'ai-sdk-schema'` ### span\_schemas [Section titled “span\_schemas”](#span_schemas) > `readonly` **span\_schemas**: `object` #### span\_schemas.ai-sdk:agent [Section titled “span\_schemas.ai-sdk:agent”](#span_schemasai-sdkagent) > `readonly` **ai-sdk:agent**: `object` #### span\_schemas.ai-sdk:agent.type [Section titled “span\_schemas.ai-sdk:agent.type”](#span_schemasai-sdkagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.ai-sdk:agent.additionalProperties [Section titled “span\_schemas.ai-sdk:agent.additionalProperties”](#span_schemasai-sdkagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.ai-sdk:llm [Section titled “span\_schemas.ai-sdk:llm”](#span_schemasai-sdkllm) > `readonly` **ai-sdk:llm**: `object` #### span\_schemas.ai-sdk:llm.type [Section titled “span\_schemas.ai-sdk:llm.type”](#span_schemasai-sdkllmtype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.ai-sdk:llm.additionalProperties [Section titled “span\_schemas.ai-sdk:llm.additionalProperties”](#span_schemasai-sdkllmadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.ai-sdk:tool [Section titled “span\_schemas.ai-sdk:tool”](#span_schemasai-sdktool) > `readonly` **ai-sdk:tool**: `object` #### span\_schemas.ai-sdk:tool.type [Section titled “span\_schemas.ai-sdk:tool.type”](#span_schemasai-sdktooltype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.ai-sdk:tool.additionalProperties [Section titled “span\_schemas.ai-sdk:tool.additionalProperties”](#span_schemasai-sdktooladditionalproperties) > `readonly` **additionalProperties**: `true` = `true` ### span\_result\_schemas [Section titled “span\_result\_schemas”](#span_result_schemas) > `readonly` **span\_result\_schemas**: `object` #### span\_result\_schemas.ai-sdk:agent [Section titled “span\_result\_schemas.ai-sdk:agent”](#span_result_schemasai-sdkagent) > `readonly` **ai-sdk:agent**: `object` #### span\_result\_schemas.ai-sdk:agent.type [Section titled “span\_result\_schemas.ai-sdk:agent.type”](#span_result_schemasai-sdkagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.ai-sdk:agent.additionalProperties [Section titled “span\_result\_schemas.ai-sdk:agent.additionalProperties”](#span_result_schemasai-sdkagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.ai-sdk:llm [Section titled “span\_result\_schemas.ai-sdk:llm”](#span_result_schemasai-sdkllm) > `readonly` **ai-sdk:llm**: `object` #### span\_result\_schemas.ai-sdk:llm.type [Section titled “span\_result\_schemas.ai-sdk:llm.type”](#span_result_schemasai-sdkllmtype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.ai-sdk:llm.additionalProperties [Section titled “span\_result\_schemas.ai-sdk:llm.additionalProperties”](#span_result_schemasai-sdkllmadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.ai-sdk:tool [Section titled “span\_result\_schemas.ai-sdk:tool”](#span_result_schemasai-sdktool) > `readonly` **ai-sdk:tool**: `object` #### span\_result\_schemas.ai-sdk:tool.type [Section titled “span\_result\_schemas.ai-sdk:tool.type”](#span_result_schemasai-sdktooltype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.ai-sdk:tool.additionalProperties [Section titled “span\_result\_schemas.ai-sdk:tool.additionalProperties”](#span_result_schemasai-sdktooladditionalproperties) > `readonly` **additionalProperties**: `true` = `true` # @prefactor/claude [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / @prefactor/claude # @prefactor/claude [Section titled “@prefactor/claude”](#prefactorclaude) Claude Agent SDK integration for Prefactor observability. Provides automatic tracing of Claude agent runs, LLM calls, tool executions, and subagent workflows via a traced `query` wrapper. ## `@prefactor/claude` overview [Section titled “@prefactor/claude overview”](#prefactorclaude-overview) `@prefactor/claude` connects Claude Agent SDK sessions to Prefactor tracing. It captures agent, LLM, tool, and subagent spans and sends them through your configured transport. Use this package as a provider for the core `init` function. ## Installation [Section titled “Installation”](#installation) ```bash npm install @prefactor/claude # or bun add @prefactor/claude ``` **Note:** This package requires `@prefactor/core` and `@anthropic-ai/claude-agent-sdk` as peer dependencies: ```bash npm install @prefactor/core @anthropic-ai/claude-agent-sdk # or bun add @prefactor/core @anthropic-ai/claude-agent-sdk ``` ## Quick Start [Section titled “Quick Start”](#quick-start) ```ts import { query } from '@anthropic-ai/claude-agent-sdk'; import { init } from '@prefactor/core'; import { PrefactorClaude } from '@prefactor/claude'; const prefactor = init({ provider: new PrefactorClaude({ query }), httpConfig: { apiUrl: process.env.PREFACTOR_API_URL!, apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: 'v1.0.0', }, }); const { tracedQuery } = prefactor.getMiddleware(); for await (const message of tracedQuery({ prompt: 'Explain this codebase', options: { allowedTools: ['Read', 'Glob', 'Grep'], }, })) { if ('result' in message) { console.log(message.result); } } await prefactor.shutdown(); ``` ## Exports [Section titled “Exports”](#exports) ### Provider [Section titled “Provider”](#provider) ```ts import { PrefactorClaude, DEFAULT_CLAUDE_AGENT_SCHEMA, } from '@prefactor/claude'; ``` ### Types [Section titled “Types”](#types) ```ts import type { ClaudeMiddleware, ClaudeQuery, JsonSchema, PrefactorClaudeOptions, ToolSchemaConfig, } from '@prefactor/claude'; ``` Core initialization and lifecycle utilities come from `@prefactor/core`: ```ts import { init, type PrefactorOptions, } from '@prefactor/core'; ``` ## Configuration [Section titled “Configuration”](#configuration) ### Environment Variables [Section titled “Environment Variables”](#environment-variables) The SDK can be configured using environment variables: * `PREFACTOR_API_URL`: API endpoint for HTTP transport * `PREFACTOR_API_TOKEN`: Authentication token for HTTP transport * `PREFACTOR_AGENT_ID`: Optional agent instance identifier * `PREFACTOR_SAMPLE_RATE`: Sampling rate 0.0-1.0 (default: `1.0`) * `PREFACTOR_CAPTURE_INPUTS`: Capture span inputs (default: `true`) * `PREFACTOR_CAPTURE_OUTPUTS`: Capture span outputs (default: `true`) * `PREFACTOR_MAX_INPUT_LENGTH`: Max input string length (default: `10000`) * `PREFACTOR_MAX_OUTPUT_LENGTH`: Max output string length (default: `10000`) * `PREFACTOR_LOG_LEVEL`: `"debug"` | `"info"` | `"warn"` | `"error"` (default: `"info"`) ### Programmatic Configuration [Section titled “Programmatic Configuration”](#programmatic-configuration) ```ts import { query } from '@anthropic-ai/claude-agent-sdk'; import { init } from '@prefactor/core'; import { PrefactorClaude, DEFAULT_CLAUDE_AGENT_SCHEMA } from '@prefactor/claude'; const prefactor = init({ provider: new PrefactorClaude({ query }), httpConfig: { apiUrl: 'https://app.prefactorai.com', apiToken: process.env.PREFACTOR_API_TOKEN!, agentId: 'my-agent', agentIdentifier: '1.0.0', agentName: 'My Claude Agent', agentDescription: 'A Claude-powered coding agent', agentSchema: { ...DEFAULT_CLAUDE_AGENT_SCHEMA, toolSchemas: { Read: { spanType: 'claude:tool:read', inputSchema: { type: 'object', properties: { file_path: { type: 'string' }, }, }, }, }, }, }, }); ``` Custom agent schemas should be passed through `httpConfig.agentSchema`, not the provider constructor. ## What Gets Traced [Section titled “What Gets Traced”](#what-gets-traced) The Claude integration automatically captures: * **Agent Runs**: Top-level agent spans for each traced query * **LLM Calls**: Model events, prompts, outputs, and usage when available * **Tool Executions**: Tool name, inputs, outputs, duration, and tool-specific span types * **Subagent Operations**: Child spans for nested Claude agent activity * **Errors**: Stream and execution failures with error details ## Requirements [Section titled “Requirements”](#requirements) * Node.js >= 22.0.0 * `@anthropic-ai/claude-agent-sdk` ^0.2.0 ## Classes [Section titled “Classes”](#classes) * [PrefactorClaude](classes/PrefactorClaude.md) ## Interfaces [Section titled “Interfaces”](#interfaces) * [PrefactorClaudeOptions](interfaces/PrefactorClaudeOptions.md) * [ClaudeMiddleware](interfaces/ClaudeMiddleware.md) ## Type Aliases [Section titled “Type Aliases”](#type-aliases) * [ClaudeQuery](type-aliases/ClaudeQuery.md) ## Variables [Section titled “Variables”](#variables) * [DEFAULT\_CLAUDE\_AGENT\_SCHEMA](variables/DEFAULT_CLAUDE_AGENT_SCHEMA.md) # Class: PrefactorClaude [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/claude](../index.md) / PrefactorClaude # Class: PrefactorClaude [Section titled “Class: PrefactorClaude”](#class-prefactorclaude) Defined in: [packages/claude/src/provider.ts:29](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L29) ## Implements [Section titled “Implements”](#implements) * `PrefactorProvider`<[`ClaudeMiddleware`](../interfaces/ClaudeMiddleware.md)> ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new PrefactorClaude**(`options`): `PrefactorClaude` Defined in: [packages/claude/src/provider.ts:35](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L35) #### Parameters [Section titled “Parameters”](#parameters) ##### options [Section titled “options”](#options) [`PrefactorClaudeOptions`](../interfaces/PrefactorClaudeOptions.md) #### Returns [Section titled “Returns”](#returns) `PrefactorClaude` ## Methods [Section titled “Methods”](#methods) ### createMiddleware() [Section titled “createMiddleware()”](#createmiddleware) > **createMiddleware**(`tracer`, `agentManager`, `coreConfig`, `_getAbortSignal?`): [`ClaudeMiddleware`](../interfaces/ClaudeMiddleware.md) Defined in: [packages/claude/src/provider.ts:39](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L39) Creates provider middleware bound to the core runtime services. #### Parameters [Section titled “Parameters”](#parameters-1) ##### tracer [Section titled “tracer”](#tracer) `Tracer` Runtime tracer used for span creation. ##### agentManager [Section titled “agentManager”](#agentmanager) `AgentInstanceManager` Runtime agent instance manager. ##### coreConfig [Section titled “coreConfig”](#coreconfig) ##### \_getAbortSignal? [Section titled “\_getAbortSignal?”](#_getabortsignal) () => `AbortSignal` #### Returns [Section titled “Returns”](#returns-1) [`ClaudeMiddleware`](../interfaces/ClaudeMiddleware.md) Provider middleware consumed by upstream frameworks. #### Implementation of [Section titled “Implementation of”](#implementation-of) `PrefactorProvider.createMiddleware` *** ### shutdown() [Section titled “shutdown()”](#shutdown) > **shutdown**(): `void` Defined in: [packages/claude/src/provider.ts:59](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L59) Optional provider-level cleanup hook invoked during client shutdown. #### Returns [Section titled “Returns”](#returns-2) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-1) `PrefactorProvider.shutdown` *** ### normalizeAgentSchema() [Section titled “normalizeAgentSchema()”](#normalizeagentschema) > **normalizeAgentSchema**(`agentSchema`): `Record`<`string`, `unknown`> Defined in: [packages/claude/src/provider.ts:70](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L70) Normalizes a user- or provider-authored agent schema before core registers it. #### Parameters [Section titled “Parameters”](#parameters-2) ##### agentSchema [Section titled “agentSchema”](#agentschema) `Record`<`string`, `unknown`> Authored agent schema configuration. #### Returns [Section titled “Returns”](#returns-3) `Record`<`string`, `unknown`> Normalized schema, or `undefined` to leave the input unchanged. #### Implementation of [Section titled “Implementation of”](#implementation-of-2) `PrefactorProvider.normalizeAgentSchema` *** ### getDefaultAgentSchema() [Section titled “getDefaultAgentSchema()”](#getdefaultagentschema) > **getDefaultAgentSchema**(): `Record`<`string`, `unknown`> | `undefined` Defined in: [packages/claude/src/provider.ts:76](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L76) Provides a default agent schema when a user does not supply one. #### Returns [Section titled “Returns”](#returns-4) `Record`<`string`, `unknown`> | `undefined` Agent schema object, or `undefined` when no default is available. #### Implementation of [Section titled “Implementation of”](#implementation-of-3) `PrefactorProvider.getDefaultAgentSchema` *** ### getSdkHeaderEntry() [Section titled “getSdkHeaderEntry()”](#getsdkheaderentry) > **getSdkHeaderEntry**(): `string` Defined in: [packages/claude/src/provider.ts:80](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L80) Returns the SDK header entry to append to HTTP requests created by the core runtime. #### Returns [Section titled “Returns”](#returns-5) `string` Adapter-specific SDK identifier, or `undefined` to use the core header only. #### Implementation of [Section titled “Implementation of”](#implementation-of-4) `PrefactorProvider.getSdkHeaderEntry` # Interface: ClaudeMiddleware [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/claude](../index.md) / ClaudeMiddleware # Interface: ClaudeMiddleware [Section titled “Interface: ClaudeMiddleware”](#interface-claudemiddleware) Defined in: [packages/claude/src/types.ts:15](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/types.ts#L15) Middleware returned by PrefactorClaude.createMiddleware(). ## Properties [Section titled “Properties”](#properties) ### tracedQuery() [Section titled “tracedQuery()”](#tracedquery) > **tracedQuery**: (…`args`) => `Query` Defined in: [packages/claude/src/types.ts:16](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/types.ts#L16) #### Parameters [Section titled “Parameters”](#parameters) ##### args [Section titled “args”](#args) …\[`object`] #### Returns [Section titled “Returns”](#returns) `Query` # Interface: PrefactorClaudeOptions [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/claude](../index.md) / PrefactorClaudeOptions # Interface: PrefactorClaudeOptions [Section titled “Interface: PrefactorClaudeOptions”](#interface-prefactorclaudeoptions) Defined in: [packages/claude/src/provider.ts:25](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L25) ## Properties [Section titled “Properties”](#properties) ### query() [Section titled “query()”](#query) > **query**: (`_params`) => `Query` Defined in: [packages/claude/src/provider.ts:26](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L26) #### Parameters [Section titled “Parameters”](#parameters) ##### \_params [Section titled “\_params”](#_params) ###### prompt [Section titled “prompt”](#prompt) `string` | `AsyncIterable`<`SDKUserMessage`, `any`, `any`> ###### options? [Section titled “options?”](#options) `Options` #### Returns [Section titled “Returns”](#returns) `Query` # Type Alias: ClaudeQuery [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/claude](../index.md) / ClaudeQuery # Type Alias: ClaudeQuery [Section titled “Type Alias: ClaudeQuery”](#type-alias-claudequery) > **ClaudeQuery** = `query` Defined in: [packages/claude/src/types.ts:10](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/types.ts#L10) # Variable: DEFAULT\_CLAUDE\_AGENT\_SCHEMA [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/claude](../index.md) / DEFAULT\_CLAUDE\_AGENT\_SCHEMA # Variable: DEFAULT\_CLAUDE\_AGENT\_SCHEMA [Section titled “Variable: DEFAULT\_CLAUDE\_AGENT\_SCHEMA”](#variable-default_claude_agent_schema) > `const` **DEFAULT\_CLAUDE\_AGENT\_SCHEMA**: `object` = `DEFAULT_CLAUDE_AGENT_SCHEMA_BASE` Defined in: [packages/claude/src/provider.ts:21](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/claude/src/provider.ts#L21) ## Type Declaration [Section titled “Type Declaration”](#type-declaration) ### external\_identifier [Section titled “external\_identifier”](#external_identifier) > `readonly` **external\_identifier**: `"claude-schema"` = `'claude-schema'` ### span\_schemas [Section titled “span\_schemas”](#span_schemas) > `readonly` **span\_schemas**: `object` #### span\_schemas.claude:agent [Section titled “span\_schemas.claude:agent”](#span_schemasclaudeagent) > `readonly` **claude:agent**: `object` #### span\_schemas.claude:agent.type [Section titled “span\_schemas.claude:agent.type”](#span_schemasclaudeagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.claude:agent.additionalProperties [Section titled “span\_schemas.claude:agent.additionalProperties”](#span_schemasclaudeagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.claude:llm [Section titled “span\_schemas.claude:llm”](#span_schemasclaudellm) > `readonly` **claude:llm**: `object` #### span\_schemas.claude:llm.type [Section titled “span\_schemas.claude:llm.type”](#span_schemasclaudellmtype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.claude:llm.additionalProperties [Section titled “span\_schemas.claude:llm.additionalProperties”](#span_schemasclaudellmadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.claude:tool [Section titled “span\_schemas.claude:tool”](#span_schemasclaudetool) > `readonly` **claude:tool**: `object` #### span\_schemas.claude:tool.type [Section titled “span\_schemas.claude:tool.type”](#span_schemasclaudetooltype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.claude:tool.additionalProperties [Section titled “span\_schemas.claude:tool.additionalProperties”](#span_schemasclaudetooladditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.claude:subagent [Section titled “span\_schemas.claude:subagent”](#span_schemasclaudesubagent) > `readonly` **claude:subagent**: `object` #### span\_schemas.claude:subagent.type [Section titled “span\_schemas.claude:subagent.type”](#span_schemasclaudesubagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.claude:subagent.additionalProperties [Section titled “span\_schemas.claude:subagent.additionalProperties”](#span_schemasclaudesubagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` ### span\_result\_schemas [Section titled “span\_result\_schemas”](#span_result_schemas) > `readonly` **span\_result\_schemas**: `object` #### span\_result\_schemas.claude:agent [Section titled “span\_result\_schemas.claude:agent”](#span_result_schemasclaudeagent) > `readonly` **claude:agent**: `object` #### span\_result\_schemas.claude:agent.type [Section titled “span\_result\_schemas.claude:agent.type”](#span_result_schemasclaudeagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.claude:agent.additionalProperties [Section titled “span\_result\_schemas.claude:agent.additionalProperties”](#span_result_schemasclaudeagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.claude:llm [Section titled “span\_result\_schemas.claude:llm”](#span_result_schemasclaudellm) > `readonly` **claude:llm**: `object` #### span\_result\_schemas.claude:llm.type [Section titled “span\_result\_schemas.claude:llm.type”](#span_result_schemasclaudellmtype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.claude:llm.additionalProperties [Section titled “span\_result\_schemas.claude:llm.additionalProperties”](#span_result_schemasclaudellmadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.claude:tool [Section titled “span\_result\_schemas.claude:tool”](#span_result_schemasclaudetool) > `readonly` **claude:tool**: `object` #### span\_result\_schemas.claude:tool.type [Section titled “span\_result\_schemas.claude:tool.type”](#span_result_schemasclaudetooltype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.claude:tool.additionalProperties [Section titled “span\_result\_schemas.claude:tool.additionalProperties”](#span_result_schemasclaudetooladditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.claude:subagent [Section titled “span\_result\_schemas.claude:subagent”](#span_result_schemasclaudesubagent) > `readonly` **claude:subagent**: `object` #### span\_result\_schemas.claude:subagent.type [Section titled “span\_result\_schemas.claude:subagent.type”](#span_result_schemasclaudesubagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.claude:subagent.additionalProperties [Section titled “span\_result\_schemas.claude:subagent.additionalProperties”](#span_result_schemasclaudesubagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` # @prefactor/langchain [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / @prefactor/langchain # @prefactor/langchain [Section titled “@prefactor/langchain”](#prefactorlangchain) LangChain adapter package exposing Prefactor initialization helpers and middleware. ## `@prefactor/langchain` overview [Section titled “@prefactor/langchain overview”](#prefactorlangchain-overview) `@prefactor/langchain` adds Prefactor tracing to LangChain middleware so agent, model, chain, and tool activity is captured automatically. Use this package as a provider for the core `init` function. ## Quick start [Section titled “Quick start”](#quick-start) ```ts import { init } from '@prefactor/core'; import { PrefactorLangChain } from '@prefactor/langchain'; import { createAgent } from 'langchain'; const prefactor = init({ provider: new PrefactorLangChain(), httpConfig: { apiUrl: 'https://api.prefactor.ai', apiToken: process.env.PREFACTOR_API_TOKEN!, agentIdentifier: 'support-bot-v1', }, }); const agent = createAgent({ model: 'claude-sonnet-4-5-20250929', tools: [], middleware: [prefactor.getMiddleware()], }); ``` ## Classes [Section titled “Classes”](#classes) * [PrefactorLangChain](classes/PrefactorLangChain.md) ## Interfaces [Section titled “Interfaces”](#interfaces) * [PrefactorLangChainOptions](interfaces/PrefactorLangChainOptions.md) ## Variables [Section titled “Variables”](#variables) * [DEFAULT\_LANGCHAIN\_AGENT\_SCHEMA](variables/DEFAULT_LANGCHAIN_AGENT_SCHEMA.md) # Class: PrefactorLangChain [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/langchain](../index.md) / PrefactorLangChain # Class: PrefactorLangChain [Section titled “Class: PrefactorLangChain”](#class-prefactorlangchain) Defined in: [packages/langchain/src/provider.ts:17](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L17) ## Implements [Section titled “Implements”](#implements) * `PrefactorProvider`<`AgentMiddleware`> ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new PrefactorLangChain**(`options?`): `PrefactorLangChain` Defined in: [packages/langchain/src/provider.ts:22](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L22) #### Parameters [Section titled “Parameters”](#parameters) ##### options? [Section titled “options?”](#options) [`PrefactorLangChainOptions`](../interfaces/PrefactorLangChainOptions.md) = `{}` #### Returns [Section titled “Returns”](#returns) `PrefactorLangChain` ## Methods [Section titled “Methods”](#methods) ### createMiddleware() [Section titled “createMiddleware()”](#createmiddleware) > **createMiddleware**(`tracer`, `agentManager`, `coreConfig`, `getAbortSignal?`): `AgentMiddleware` Defined in: [packages/langchain/src/provider.ts:26](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L26) Creates provider middleware bound to the core runtime services. #### Parameters [Section titled “Parameters”](#parameters-1) ##### tracer [Section titled “tracer”](#tracer) `Tracer` Runtime tracer used for span creation. ##### agentManager [Section titled “agentManager”](#agentmanager) `AgentInstanceManager` Runtime agent instance manager. ##### coreConfig [Section titled “coreConfig”](#coreconfig) ##### getAbortSignal? [Section titled “getAbortSignal?”](#getabortsignal) () => `AbortSignal` Returns the AbortSignal for the current run. Called on each check so a fresh signal is returned after `monitor.reset()`. #### Returns [Section titled “Returns”](#returns-1) `AgentMiddleware` Provider middleware consumed by upstream frameworks. #### Implementation of [Section titled “Implementation of”](#implementation-of) `PrefactorProvider.createMiddleware` *** ### resetForNextRun() [Section titled “resetForNextRun()”](#resetfornextrun) > **resetForNextRun**(): `void` Defined in: [packages/langchain/src/provider.ts:72](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L72) Optional hook called between agent runs to reset per-run middleware state (e.g. finish the current agent instance and clear instance-started flags). #### Returns [Section titled “Returns”](#returns-2) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-1) `PrefactorProvider.resetForNextRun` *** ### shutdown() [Section titled “shutdown()”](#shutdown) > **shutdown**(): `void` Defined in: [packages/langchain/src/provider.ts:76](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L76) Optional provider-level cleanup hook invoked during client shutdown. #### Returns [Section titled “Returns”](#returns-3) `void` #### Implementation of [Section titled “Implementation of”](#implementation-of-2) `PrefactorProvider.shutdown` *** ### getSdkHeaderEntry() [Section titled “getSdkHeaderEntry()”](#getsdkheaderentry) > **getSdkHeaderEntry**(): `string` Defined in: [packages/langchain/src/provider.ts:81](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L81) Returns the SDK header entry to append to HTTP requests created by the core runtime. #### Returns [Section titled “Returns”](#returns-4) `string` Adapter-specific SDK identifier, or `undefined` to use the core header only. #### Implementation of [Section titled “Implementation of”](#implementation-of-3) `PrefactorProvider.getSdkHeaderEntry` *** ### normalizeAgentSchema() [Section titled “normalizeAgentSchema()”](#normalizeagentschema) > **normalizeAgentSchema**(`agentSchema`): `Record`<`string`, `unknown`> Defined in: [packages/langchain/src/provider.ts:85](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L85) Normalizes a user- or provider-authored agent schema before core registers it. #### Parameters [Section titled “Parameters”](#parameters-2) ##### agentSchema [Section titled “agentSchema”](#agentschema) `Record`<`string`, `unknown`> Authored agent schema configuration. #### Returns [Section titled “Returns”](#returns-5) `Record`<`string`, `unknown`> Normalized schema, or `undefined` to leave the input unchanged. #### Implementation of [Section titled “Implementation of”](#implementation-of-4) `PrefactorProvider.normalizeAgentSchema` *** ### getDefaultAgentSchema() [Section titled “getDefaultAgentSchema()”](#getdefaultagentschema) > **getDefaultAgentSchema**(): `Record`<`string`, `unknown`> | `undefined` Defined in: [packages/langchain/src/provider.ts:91](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L91) Provides a default agent schema when a user does not supply one. #### Returns [Section titled “Returns”](#returns-6) `Record`<`string`, `unknown`> | `undefined` Agent schema object, or `undefined` when no default is available. #### Implementation of [Section titled “Implementation of”](#implementation-of-5) `PrefactorProvider.getDefaultAgentSchema` # Interface: PrefactorLangChainOptions [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/langchain](../index.md) / PrefactorLangChainOptions # Interface: PrefactorLangChainOptions [Section titled “Interface: PrefactorLangChainOptions”](#interface-prefactorlangchainoptions) Defined in: [packages/langchain/src/provider.ts:13](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L13) ## Properties [Section titled “Properties”](#properties) ### agentSchema? [Section titled “agentSchema?”](#agentschema) > `optional` **agentSchema**: `Record`<`string`, `unknown`> Defined in: [packages/langchain/src/provider.ts:14](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L14) # Variable: DEFAULT\_LANGCHAIN\_AGENT\_SCHEMA [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/langchain](../index.md) / DEFAULT\_LANGCHAIN\_AGENT\_SCHEMA # Variable: DEFAULT\_LANGCHAIN\_AGENT\_SCHEMA [Section titled “Variable: DEFAULT\_LANGCHAIN\_AGENT\_SCHEMA”](#variable-default_langchain_agent_schema) > `const` **DEFAULT\_LANGCHAIN\_AGENT\_SCHEMA**: `object` = `DEFAULT_LANGCHAIN_AGENT_SCHEMA_BASE` Defined in: [packages/langchain/src/provider.ts:10](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/langchain/src/provider.ts#L10) ## Type Declaration [Section titled “Type Declaration”](#type-declaration) ### external\_identifier [Section titled “external\_identifier”](#external_identifier) > `readonly` **external\_identifier**: `"langchain-schema"` = `'langchain-schema'` ### span\_schemas [Section titled “span\_schemas”](#span_schemas) > `readonly` **span\_schemas**: `object` #### span\_schemas.langchain:agent [Section titled “span\_schemas.langchain:agent”](#span_schemaslangchainagent) > `readonly` **langchain:agent**: `object` #### span\_schemas.langchain:agent.type [Section titled “span\_schemas.langchain:agent.type”](#span_schemaslangchainagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.langchain:agent.additionalProperties [Section titled “span\_schemas.langchain:agent.additionalProperties”](#span_schemaslangchainagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.langchain:llm [Section titled “span\_schemas.langchain:llm”](#span_schemaslangchainllm) > `readonly` **langchain:llm**: `object` #### span\_schemas.langchain:llm.type [Section titled “span\_schemas.langchain:llm.type”](#span_schemaslangchainllmtype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.langchain:llm.additionalProperties [Section titled “span\_schemas.langchain:llm.additionalProperties”](#span_schemaslangchainllmadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.langchain:tool [Section titled “span\_schemas.langchain:tool”](#span_schemaslangchaintool) > `readonly` **langchain:tool**: `object` #### span\_schemas.langchain:tool.type [Section titled “span\_schemas.langchain:tool.type”](#span_schemaslangchaintooltype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.langchain:tool.additionalProperties [Section titled “span\_schemas.langchain:tool.additionalProperties”](#span_schemaslangchaintooladditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_schemas.langchain:chain [Section titled “span\_schemas.langchain:chain”](#span_schemaslangchainchain) > `readonly` **langchain:chain**: `object` #### span\_schemas.langchain:chain.type [Section titled “span\_schemas.langchain:chain.type”](#span_schemaslangchainchaintype) > `readonly` **type**: `"object"` = `'object'` #### span\_schemas.langchain:chain.additionalProperties [Section titled “span\_schemas.langchain:chain.additionalProperties”](#span_schemaslangchainchainadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` ### span\_result\_schemas [Section titled “span\_result\_schemas”](#span_result_schemas) > `readonly` **span\_result\_schemas**: `object` #### span\_result\_schemas.langchain:agent [Section titled “span\_result\_schemas.langchain:agent”](#span_result_schemaslangchainagent) > `readonly` **langchain:agent**: `object` #### span\_result\_schemas.langchain:agent.type [Section titled “span\_result\_schemas.langchain:agent.type”](#span_result_schemaslangchainagenttype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.langchain:agent.additionalProperties [Section titled “span\_result\_schemas.langchain:agent.additionalProperties”](#span_result_schemaslangchainagentadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.langchain:llm [Section titled “span\_result\_schemas.langchain:llm”](#span_result_schemaslangchainllm) > `readonly` **langchain:llm**: `object` #### span\_result\_schemas.langchain:llm.type [Section titled “span\_result\_schemas.langchain:llm.type”](#span_result_schemaslangchainllmtype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.langchain:llm.additionalProperties [Section titled “span\_result\_schemas.langchain:llm.additionalProperties”](#span_result_schemaslangchainllmadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.langchain:tool [Section titled “span\_result\_schemas.langchain:tool”](#span_result_schemaslangchaintool) > `readonly` **langchain:tool**: `object` #### span\_result\_schemas.langchain:tool.type [Section titled “span\_result\_schemas.langchain:tool.type”](#span_result_schemaslangchaintooltype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.langchain:tool.additionalProperties [Section titled “span\_result\_schemas.langchain:tool.additionalProperties”](#span_result_schemaslangchaintooladditionalproperties) > `readonly` **additionalProperties**: `true` = `true` #### span\_result\_schemas.langchain:chain [Section titled “span\_result\_schemas.langchain:chain”](#span_result_schemaslangchainchain) > `readonly` **langchain:chain**: `object` #### span\_result\_schemas.langchain:chain.type [Section titled “span\_result\_schemas.langchain:chain.type”](#span_result_schemaslangchainchaintype) > `readonly` **type**: `"object"` = `'object'` #### span\_result\_schemas.langchain:chain.additionalProperties [Section titled “span\_result\_schemas.langchain:chain.additionalProperties”](#span_result_schemaslangchainchainadditionalproperties) > `readonly` **additionalProperties**: `true` = `true` # @prefactor/openclaw-prefactor-plugin [**Prefactor TypeScript SDK**](../../index.md) *** [Prefactor TypeScript SDK](../../modules.md) / @prefactor/openclaw-prefactor-plugin # @prefactor/openclaw-prefactor-plugin [Section titled “@prefactor/openclaw-prefactor-plugin”](#prefactoropenclaw-prefactor-plugin) OpenClaw plugin for Prefactor observability. Provides automatic tracing of agent lifecycle events including sessions, user interactions, agent runs, and tool calls. ## `@prefactor/openclaw-prefactor-plugin` overview [Section titled “@prefactor/openclaw-prefactor-plugin overview”](#prefactoropenclaw-prefactor-plugin-overview) This plugin hooks into OpenClaw’s lifecycle events to create a hierarchical span structure for distributed tracing. The span hierarchy follows: ```plaintext session (24hr lifetime, root span) └─ user_interaction (5min idle timeout) ├─ user_message (instant, auto-closed) ├─ agent_run (child of interaction) │ ├─ tool_call (concurrent, children of agent_run) │ └─ tool_call └─ assistant_response (instant, auto-closed) ``` ## Hook handlers [Section titled “Hook handlers”](#hook-handlers) The plugin registers 14 hooks that automatically create and manage spans: * **Gateway**: `gateway_start`, `gateway_stop` * **Session**: `session_start`, `session_end` * **Agent**: `before_agent_start`, `agent_end` * **Compaction**: `before_compaction`, `after_compaction` * **Tool**: `before_tool_call`, `after_tool_call`, `tool_result_persist` * **Message**: `message_received`, `message_sending`, `message_sent` ## Span types [Section titled “Span types”](#span-types) * `openclaw:session` - Root span for the OpenClaw session (24hr lifetime) * `openclaw:user_interaction` - User interaction context (5min idle timeout) * `openclaw:user_message` - Inbound user message event * `openclaw:agent_run` - Agent execution run * `openclaw:tool_call` - Tool execution (supports concurrent calls) * `openclaw:assistant_response` - Assistant response event ## Exports [Section titled “Exports”](#exports) * [Agent](interfaces/Agent.md) - HTTP client for Prefactor API (span CRUD, instance lifecycle) * [SessionStateManager](interfaces/SessionStateManager.md) - Manages span hierarchy and timeouts per session * [Logger](interfaces/Logger.md) - Structured logger for plugin diagnostics * [register](functions/default.md) - Plugin entry point (used by OpenClaw, not imported directly) ## Functions [Section titled “Functions”](#functions) * [default](functions/default.md) * [createAgent](functions/createAgent.md) * [createRiskConfig](functions/createRiskConfig.md) * [createLogger](functions/createLogger.md) * [createSessionStateManager](functions/createSessionStateManager.md) * [getAllSupportedToolDefinitions](functions/getAllSupportedToolDefinitions.md) * [getToolDefinition](functions/getToolDefinition.md) * [getToolInputSchema](functions/getToolInputSchema.md) * [isSupportedTool](functions/isSupportedTool.md) * [normalizeToolName](functions/normalizeToolName.md) * [buildToolSpanSchema](functions/buildToolSpanSchema.md) * [createToolSpanInputs](functions/createToolSpanInputs.md) * [createToolSpanOutputs](functions/createToolSpanOutputs.md) * [createToolSpanResultPayload](functions/createToolSpanResultPayload.md) ## Interfaces [Section titled “Interfaces”](#interfaces) * [Agent](interfaces/Agent.md) * [AgentConfig](interfaces/AgentConfig.md) * [Logger](interfaces/Logger.md) * [SessionStateManager](interfaces/SessionStateManager.md) * [ToolDefinition](interfaces/ToolDefinition.md) ## Type Aliases [Section titled “Type Aliases”](#type-aliases) * [LogLevel](type-aliases/LogLevel.md) ## Variables [Section titled “Variables”](#variables) * [agentRunRisk](variables/agentRunRisk.md) * [agentThinkingRisk](variables/agentThinkingRisk.md) * [assistantResponseRisk](variables/assistantResponseRisk.md) * [defaultSpanTypeRiskConfigs](variables/defaultSpanTypeRiskConfigs.md) * [sessionRisk](variables/sessionRisk.md) * [toolBrowserRisk](variables/toolBrowserRisk.md) * [toolEditRisk](variables/toolEditRisk.md) * [toolExecRisk](variables/toolExecRisk.md) * [toolReadRisk](variables/toolReadRisk.md) * [toolRisk](variables/toolRisk.md) * [toolWebFetchRisk](variables/toolWebFetchRisk.md) * [toolWebSearchRisk](variables/toolWebSearchRisk.md) * [toolWriteRisk](variables/toolWriteRisk.md) * [userInteractionRisk](variables/userInteractionRisk.md) * [userMessageRisk](variables/userMessageRisk.md) * [SUPPORTED\_TOOL\_DEFINITIONS](variables/SUPPORTED_TOOL_DEFINITIONS.md) * [TOOL\_ALIAS\_MAP](variables/TOOL_ALIAS_MAP.md) * [GENERIC\_OBJECT\_SCHEMA](variables/GENERIC_OBJECT_SCHEMA.md) # Function: buildToolSpanSchema() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / buildToolSpanSchema # Function: buildToolSpanSchema() [Section titled “Function: buildToolSpanSchema()”](#function-buildtoolspanschema) > **buildToolSpanSchema**(`inputSchema`): `JsonSchema` Defined in: [packages/openclaw-prefactor-plugin/src/tool-span-contract.ts:104](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-span-contract.ts#L104) Builds a complete JSON schema for a tool span. ## Parameters [Section titled “Parameters”](#parameters) ### inputSchema [Section titled “inputSchema”](#inputschema) `JsonSchema` JSON Schema for the tool’s input parameters ## Returns [Section titled “Returns”](#returns) `JsonSchema` Complete tool span schema # Function: createAgent() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createAgent # Function: createAgent() [Section titled “Function: createAgent()”](#function-createagent) > **createAgent**(`config`, `logger`): [`Agent`](../interfaces/Agent.md) Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:873](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L873) Creates and returns a fully initialised [Agent](../interfaces/Agent.md) instance. On construction the Agent starts a background flush loop (every 30 s) that retries any previously failed network operations. No immediate network calls are made; the first API request occurs when a span is created or an AgentInstance is registered for a session. ## Parameters [Section titled “Parameters”](#parameters) ### config [Section titled “config”](#config) [`AgentConfig`](../interfaces/AgentConfig.md) [AgentConfig](../interfaces/AgentConfig.md) with API URL, token, agent ID, and optional retry/timeout settings. ### logger [Section titled “logger”](#logger) [`Logger`](../interfaces/Logger.md) Logger instance for structured diagnostic output. ## Returns [Section titled “Returns”](#returns) [`Agent`](../interfaces/Agent.md) A new [Agent](../interfaces/Agent.md) ready to manage sessions and spans. # Function: createLogger() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createLogger # Function: createLogger() [Section titled “Function: createLogger()”](#function-createlogger) > **createLogger**(`level?`): [`Logger`](../interfaces/Logger.md) Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:55](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L55) ## Parameters [Section titled “Parameters”](#parameters) ### level? [Section titled “level?”](#level) [`LogLevel`](../type-aliases/LogLevel.md) = `'info'` ## Returns [Section titled “Returns”](#returns) [`Logger`](../interfaces/Logger.md) # Function: createRiskConfig() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createRiskConfig # Function: createRiskConfig() [Section titled “Function: createRiskConfig()”](#function-createriskconfig) > **createRiskConfig**(`userConfigs?`): `Record`<`string`, `DataRisk`> Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:341](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L341) Creates a merged risk configuration by combining default configs with user-provided overrides. User overrides take precedence over defaults. ## Parameters [Section titled “Parameters”](#parameters) ### userConfigs? [Section titled “userConfigs?”](#userconfigs) `Record`<`string`, `DataRisk`> User-provided risk configurations to merge with defaults ## Returns [Section titled “Returns”](#returns) `Record`<`string`, `DataRisk`> Merged risk configuration # Function: createSessionStateManager() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createSessionStateManager # Function: createSessionStateManager() [Section titled “Function: createSessionStateManager()”](#function-createsessionstatemanager) > **createSessionStateManager**(`agent`, `logger`, `config?`): [`SessionStateManager`](../interfaces/SessionStateManager.md) Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:766](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L766) ## Parameters [Section titled “Parameters”](#parameters) ### agent [Section titled “agent”](#agent) [`Agent`](../interfaces/Agent.md) | `null` ### logger [Section titled “logger”](#logger) [`Logger`](../interfaces/Logger.md) ### config? [Section titled “config?”](#config) `Partial`<`SessionManagerConfig`> ## Returns [Section titled “Returns”](#returns) [`SessionStateManager`](../interfaces/SessionStateManager.md) # Function: createToolSpanInputs() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createToolSpanInputs # Function: createToolSpanInputs() [Section titled “Function: createToolSpanInputs()”](#function-createtoolspaninputs) > **createToolSpanInputs**(`params`): `Record`<`string`, `unknown`> Defined in: [packages/openclaw-prefactor-plugin/src/tool-span-contract.ts:69](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-span-contract.ts#L69) Creates structured inputs for a tool call span. ## Parameters [Section titled “Parameters”](#parameters) ### params [Section titled “params”](#params) Tool call parameters #### toolName [Section titled “toolName”](#toolname) `string` #### toolCallId? [Section titled “toolCallId?”](#toolcallid) `string` #### input? [Section titled “input?”](#input) `unknown` ## Returns [Section titled “Returns”](#returns) `Record`<`string`, `unknown`> Structured span inputs following OpenClaw tool-span-contract # Function: createToolSpanOutputs() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createToolSpanOutputs # Function: createToolSpanOutputs() [Section titled “Function: createToolSpanOutputs()”](#function-createtoolspanoutputs) > **createToolSpanOutputs**(`output`): `object` Defined in: [packages/openclaw-prefactor-plugin/src/tool-span-contract.ts:92](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-span-contract.ts#L92) Creates structured outputs for a tool call span. ## Parameters [Section titled “Parameters”](#parameters) ### output [Section titled “output”](#output) `unknown` Raw tool output ## Returns [Section titled “Returns”](#returns) `object` Structured span outputs ### output [Section titled “output”](#output-1) > **output**: `unknown` # Function: createToolSpanResultPayload() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / createToolSpanResultPayload # Function: createToolSpanResultPayload() [Section titled “Function: createToolSpanResultPayload()”](#function-createtoolspanresultpayload) > **createToolSpanResultPayload**(`output`, `isError`): `Record`<`string`, `unknown`> Defined in: [packages/openclaw-prefactor-plugin/src/tool-span-contract.ts:179](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-span-contract.ts#L179) Creates a tool span result payload for finishing a span. ## Parameters [Section titled “Parameters”](#parameters) ### output [Section titled “output”](#output) `unknown` Tool output ### isError [Section titled “isError”](#iserror) `boolean` Whether the tool execution resulted in an error ## Returns [Section titled “Returns”](#returns) `Record`<`string`, `unknown`> Result payload for span finish # Function: default() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / default # Function: default() [Section titled “Function: default()”](#function-default) > **default**(`api`): `void` Defined in: [packages/openclaw-prefactor-plugin/src/index.ts:78](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/index.ts#L78) ## Parameters [Section titled “Parameters”](#parameters) ### api [Section titled “api”](#api) `OpenClawPluginApi` ## Returns [Section titled “Returns”](#returns) `void` # Function: getAllSupportedToolDefinitions() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / getAllSupportedToolDefinitions # Function: getAllSupportedToolDefinitions() [Section titled “Function: getAllSupportedToolDefinitions()”](#function-getallsupportedtooldefinitions) > **getAllSupportedToolDefinitions**(): `Record`<`string`, [`ToolDefinition`](../interfaces/ToolDefinition.md)> Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:423](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L423) Gets all tool definitions for schema registration. Used when building the agent schema version. ## Returns [Section titled “Returns”](#returns) `Record`<`string`, [`ToolDefinition`](../interfaces/ToolDefinition.md)> # Function: getToolDefinition() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / getToolDefinition # Function: getToolDefinition() [Section titled “Function: getToolDefinition()”](#function-gettooldefinition) > **getToolDefinition**(`toolName`): [`ToolDefinition`](../interfaces/ToolDefinition.md) | `undefined` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:397](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L397) Gets the tool definition for a given tool name. Handles both canonical names and aliases. Returns undefined for unknown tools. ## Parameters [Section titled “Parameters”](#parameters) ### toolName [Section titled “toolName”](#toolname) `string` ## Returns [Section titled “Returns”](#returns) [`ToolDefinition`](../interfaces/ToolDefinition.md) | `undefined` # Function: getToolInputSchema() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / getToolInputSchema # Function: getToolInputSchema() [Section titled “Function: getToolInputSchema()”](#function-gettoolinputschema) > **getToolInputSchema**(`toolName`): `JsonSchema` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:406](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L406) Gets the input schema for a tool. Returns a generic object schema for unknown tools. ## Parameters [Section titled “Parameters”](#parameters) ### toolName [Section titled “toolName”](#toolname) `string` ## Returns [Section titled “Returns”](#returns) `JsonSchema` # Function: isSupportedTool() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / isSupportedTool # Function: isSupportedTool() [Section titled “Function: isSupportedTool()”](#function-issupportedtool) > **isSupportedTool**(`toolName`): `boolean` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:414](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L414) Checks if a tool is one of the supported tools with a defined schema. ## Parameters [Section titled “Parameters”](#parameters) ### toolName [Section titled “toolName”](#toolname) `string` ## Returns [Section titled “Returns”](#returns) `boolean` # Function: normalizeToolName() [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / normalizeToolName # Function: normalizeToolName() [Section titled “Function: normalizeToolName()”](#function-normalizetoolname) > **normalizeToolName**(`toolName`): `string` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:388](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L388) Normalizes a tool name to its canonical form. Falls back to the original name if no mapping exists. ## Parameters [Section titled “Parameters”](#parameters) ### toolName [Section titled “toolName”](#toolname) `string` ## Returns [Section titled “Returns”](#returns) `string` # Interface: Agent [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / Agent # Interface: Agent [Section titled “Interface: Agent”](#interface-agent) Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:157](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L157) HTTP client that manages AgentInstance lifecycle and span CRUD against the Prefactor API. Supports multiple concurrent sessions, each backed by its own AgentInstance, and automatically retries failed operations via a background replay queue. ## Param [Section titled “Param”](#param) [AgentConfig](AgentConfig.md) with connection and retry settings. ## Param [Section titled “Param”](#param-1) Logger instance used for structured diagnostic output. Key public methods: * [Agent.createSpan](#createspan) — Creates a span under the given session, registering an AgentInstance first if one does not yet exist. * [Agent.finishSpan](#finishspan) — Marks a span as finished; queues the operation for retry on failure. * [Agent.finishAgentInstance](#finishagentinstance) — Completes the AgentInstance for a session. * [Agent.flushQueue](#flushqueue) — Replays any queued operations that previously failed. * [Agent.stop](#stop) — Stops the background flush loop. * [Agent.emergencyCleanup](#emergencycleanup) — Tears down all sessions and clears the queue. ## Methods [Section titled “Methods”](#methods) ### resolveToolSpanType() [Section titled “resolveToolSpanType()”](#resolvetoolspantype) > **resolveToolSpanType**(`toolName`): `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:429](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L429) Resolves a tool name to its span type. Returns the specific span type for supported tools, or the generic fallback. #### Parameters [Section titled “Parameters”](#parameters) ##### toolName [Section titled “toolName”](#toolname) `string` #### Returns [Section titled “Returns”](#returns) `string` *** ### stop() [Section titled “stop()”](#stop) > **stop**(): `void` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:470](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L470) #### Returns [Section titled “Returns”](#returns-1) `void` *** ### emergencyCleanup() [Section titled “emergencyCleanup()”](#emergencycleanup) > **emergencyCleanup**(): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:477](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L477) #### Returns [Section titled “Returns”](#returns-2) `Promise`<`void`> *** ### finishAgentInstance() [Section titled “finishAgentInstance()”](#finishagentinstance) > **finishAgentInstance**(`sessionKey`, `status?`): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:592](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L592) #### Parameters [Section titled “Parameters”](#parameters-1) ##### sessionKey [Section titled “sessionKey”](#sessionkey) `string` ##### status? [Section titled “status?”](#status) `"complete"` | `"failed"` | `"cancelled"` #### Returns [Section titled “Returns”](#returns-3) `Promise`<`void`> *** ### createSpan() [Section titled “createSpan()”](#createspan) > **createSpan**(`sessionKey`, `schemaName`, `payload`, `parentSpanId?`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:643](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L643) #### Parameters [Section titled “Parameters”](#parameters-2) ##### sessionKey [Section titled “sessionKey”](#sessionkey-1) `string` ##### schemaName [Section titled “schemaName”](#schemaname) `string` ##### payload [Section titled “payload”](#payload) `Record`<`string`, `unknown`> ##### parentSpanId? [Section titled “parentSpanId?”](#parentspanid) `string` | `null` #### Returns [Section titled “Returns”](#returns-4) `Promise`<`string` | `null`> *** ### finishSpan() [Section titled “finishSpan()”](#finishspan) > **finishSpan**(`sessionKey`, `spanId`, `status?`, `resultPayload?`): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:735](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L735) #### Parameters [Section titled “Parameters”](#parameters-3) ##### sessionKey [Section titled “sessionKey”](#sessionkey-2) `string` ##### spanId [Section titled “spanId”](#spanid) `string` ##### status? [Section titled “status?”](#status-1) `"complete"` | `"failed"` | `"cancelled"` ##### resultPayload? [Section titled “resultPayload?”](#resultpayload) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-5) `Promise`<`void`> *** ### flushQueue() [Section titled “flushQueue()”](#flushqueue) > **flushQueue**(): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:775](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L775) #### Returns [Section titled “Returns”](#returns-6) `Promise`<`void`> # Interface: AgentConfig [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / AgentConfig # Interface: AgentConfig [Section titled “Interface: AgentConfig”](#interface-agentconfig) Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:124](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L124) Configuration for the Prefactor Agent HTTP client. ## Properties [Section titled “Properties”](#properties) ### apiUrl [Section titled “apiUrl”](#apiurl) > **apiUrl**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:125](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L125) Base URL of the Prefactor API. *** ### apiToken [Section titled “apiToken”](#apitoken) > **apiToken**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:126](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L126) Bearer token used to authenticate API requests. *** ### agentId [Section titled “agentId”](#agentid) > **agentId**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:127](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L127) Unique identifier for this agent in the Prefactor backend. *** ### maxRetries? [Section titled “maxRetries?”](#maxretries) > `optional` **maxRetries**: `number` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:128](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L128) Maximum number of retry attempts for failed HTTP requests. Defaults to `3`. *** ### initialRetryDelay? [Section titled “initialRetryDelay?”](#initialretrydelay) > `optional` **initialRetryDelay**: `number` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:129](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L129) Initial delay in milliseconds before the first retry, doubled on each subsequent attempt. Defaults to `1000`. *** ### requestTimeout? [Section titled “requestTimeout?”](#requesttimeout) > `optional` **requestTimeout**: `number` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:130](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L130) HTTP request timeout in milliseconds. Defaults to `30000`. *** ### openclawVersion? [Section titled “openclawVersion?”](#openclawversion) > `optional` **openclawVersion**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:131](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L131) Version string of the OpenClaw runtime (used in the agent version identifier). *** ### pluginVersion? [Section titled “pluginVersion?”](#pluginversion) > `optional` **pluginVersion**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:132](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L132) Version string of the Prefactor plugin (used in the agent and schema version identifiers). *** ### userAgentVersion? [Section titled “userAgentVersion?”](#useragentversion) > `optional` **userAgentVersion**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:133](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L133) Caller-supplied version tag appended to the agent version identifier. *** ### userAgentName? [Section titled “userAgentName?”](#useragentname) > `optional` **userAgentName**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:134](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L134) Human-readable name for this agent shown in the Prefactor UI. Defaults to `"OpenClaw Agent"`. *** ### spanTypeRiskConfigs? [Section titled “spanTypeRiskConfigs?”](#spantyperiskconfigs) > `optional` **spanTypeRiskConfigs**: `Record`<`string`, `DataRisk`> Defined in: [packages/openclaw-prefactor-plugin/src/agent.ts:135](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/agent.ts#L135) # Interface: Logger [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / Logger # Interface: Logger [Section titled “Interface: Logger”](#interface-logger) Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:6](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L6) ## Methods [Section titled “Methods”](#methods) ### debug() [Section titled “debug()”](#debug) > **debug**(`event`, `data`): `void` Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:26](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L26) #### Parameters [Section titled “Parameters”](#parameters) ##### event [Section titled “event”](#event) `string` ##### data [Section titled “data”](#data) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns) `void` *** ### info() [Section titled “info()”](#info) > **info**(`event`, `data`): `void` Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:32](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L32) #### Parameters [Section titled “Parameters”](#parameters-1) ##### event [Section titled “event”](#event-1) `string` ##### data [Section titled “data”](#data-1) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-1) `void` *** ### warn() [Section titled “warn()”](#warn) > **warn**(`event`, `data`): `void` Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:38](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L38) #### Parameters [Section titled “Parameters”](#parameters-2) ##### event [Section titled “event”](#event-2) `string` ##### data [Section titled “data”](#data-2) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-2) `void` *** ### error() [Section titled “error()”](#error) > **error**(`event`, `data`): `void` Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:44](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L44) #### Parameters [Section titled “Parameters”](#parameters-3) ##### event [Section titled “event”](#event-3) `string` ##### data [Section titled “data”](#data-3) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-3) `void` *** ### setLevel() [Section titled “setLevel()”](#setlevel) > **setLevel**(`level`): `void` Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:50](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L50) #### Parameters [Section titled “Parameters”](#parameters-4) ##### level [Section titled “level”](#level) [`LogLevel`](../type-aliases/LogLevel.md) #### Returns [Section titled “Returns”](#returns-4) `void` # Interface: SessionStateManager [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / SessionStateManager # Interface: SessionStateManager [Section titled “Interface: SessionStateManager”](#interface-sessionstatemanager) Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:63](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L63) ## Methods [Section titled “Methods”](#methods) ### stop() [Section titled “stop()”](#stop) > **stop**(): `void` Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:102](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L102) #### Returns [Section titled “Returns”](#returns) `void` *** ### createSessionSpan() [Section titled “createSessionSpan()”](#createsessionspan) > **createSessionSpan**(`sessionKey`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:133](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L133) #### Parameters [Section titled “Parameters”](#parameters) ##### sessionKey [Section titled “sessionKey”](#sessionkey) `string` #### Returns [Section titled “Returns”](#returns-1) `Promise`<`string` | `null`> *** ### closeSessionSpan() [Section titled “closeSessionSpan()”](#closesessionspan) > **closeSessionSpan**(`sessionKey`): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:137](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L137) #### Parameters [Section titled “Parameters”](#parameters-1) ##### sessionKey [Section titled “sessionKey”](#sessionkey-1) `string` #### Returns [Section titled “Returns”](#returns-2) `Promise`<`void`> *** ### createOrGetInteractionSpan() [Section titled “createOrGetInteractionSpan()”](#createorgetinteractionspan) > **createOrGetInteractionSpan**(`sessionKey`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:141](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L141) #### Parameters [Section titled “Parameters”](#parameters-2) ##### sessionKey [Section titled “sessionKey”](#sessionkey-2) `string` #### Returns [Section titled “Returns”](#returns-3) `Promise`<`string` | `null`> *** ### closeInteractionSpan() [Section titled “closeInteractionSpan()”](#closeinteractionspan) > **closeInteractionSpan**(`sessionKey`, `status?`): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:145](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L145) #### Parameters [Section titled “Parameters”](#parameters-3) ##### sessionKey [Section titled “sessionKey”](#sessionkey-3) `string` ##### status? [Section titled “status?”](#status) `"complete"` | `"failed"` | `"cancelled"` #### Returns [Section titled “Returns”](#returns-4) `Promise`<`void`> *** ### createUserMessageSpan() [Section titled “createUserMessageSpan()”](#createusermessagespan) > **createUserMessageSpan**(`sessionKey`, `payload`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:152](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L152) #### Parameters [Section titled “Parameters”](#parameters-4) ##### sessionKey [Section titled “sessionKey”](#sessionkey-4) `string` ##### payload [Section titled “payload”](#payload) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-5) `Promise`<`string` | `null`> *** ### createAgentRunSpan() [Section titled “createAgentRunSpan()”](#createagentrunspan) > **createAgentRunSpan**(`sessionKey`, `payload`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:159](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L159) #### Parameters [Section titled “Parameters”](#parameters-5) ##### sessionKey [Section titled “sessionKey”](#sessionkey-5) `string` ##### payload [Section titled “payload”](#payload-1) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-6) `Promise`<`string` | `null`> *** ### closeAgentRunSpan() [Section titled “closeAgentRunSpan()”](#closeagentrunspan) > **closeAgentRunSpan**(`sessionKey`, `status?`): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:166](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L166) #### Parameters [Section titled “Parameters”](#parameters-6) ##### sessionKey [Section titled “sessionKey”](#sessionkey-6) `string` ##### status? [Section titled “status?”](#status-1) `"complete"` | `"failed"` | `"cancelled"` #### Returns [Section titled “Returns”](#returns-7) `Promise`<`void`> *** ### createToolCallSpan() [Section titled “createToolCallSpan()”](#createtoolcallspan) > **createToolCallSpan**(`sessionKey`, `toolName`, `payload`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:173](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L173) #### Parameters [Section titled “Parameters”](#parameters-7) ##### sessionKey [Section titled “sessionKey”](#sessionkey-7) `string` ##### toolName [Section titled “toolName”](#toolname) `string` ##### payload [Section titled “payload”](#payload-2) `Record`<`string`, `unknown`> #### Returns [Section titled “Returns”](#returns-8) `Promise`<`string` | `null`> *** ### closeToolCallSpanWithResult() [Section titled “closeToolCallSpanWithResult()”](#closetoolcallspanwithresult) > **closeToolCallSpanWithResult**(`sessionKey`, `toolCallId`, `toolName`, `resultText`, `isError`): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:183](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L183) #### Parameters [Section titled “Parameters”](#parameters-8) ##### sessionKey [Section titled “sessionKey”](#sessionkey-8) `string` ##### toolCallId [Section titled “toolCallId”](#toolcallid) `string` ##### toolName [Section titled “toolName”](#toolname-1) `string` ##### resultText [Section titled “resultText”](#resulttext) `string` | `undefined` ##### isError [Section titled “isError”](#iserror) `boolean` #### Returns [Section titled “Returns”](#returns-9) `Promise`<`void`> *** ### createAssistantResponseSpan() [Section titled “createAssistantResponseSpan()”](#createassistantresponsespan) > **createAssistantResponseSpan**(`sessionKey`, `text`, `tokens`, `metadata?`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:195](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L195) #### Parameters [Section titled “Parameters”](#parameters-9) ##### sessionKey [Section titled “sessionKey”](#sessionkey-9) `string` ##### text [Section titled “text”](#text) `string` ##### tokens [Section titled “tokens”](#tokens) { `input?`: `number`; `output?`: `number`; `cacheRead?`: `number`; `cacheWrite?`: `number`; `total?`: `number`; } | `undefined` ##### metadata? [Section titled “metadata?”](#metadata) ###### provider? [Section titled “provider?”](#provider) `string` ###### model? [Section titled “model?”](#model) `string` #### Returns [Section titled “Returns”](#returns-10) `Promise`<`string` | `null`> *** ### createAgentThinkingSpan() [Section titled “createAgentThinkingSpan()”](#createagentthinkingspan) > **createAgentThinkingSpan**(`sessionKey`, `thinking`, `tokens`, `metadata?`): `Promise`<`string` | `null`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:208](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L208) #### Parameters [Section titled “Parameters”](#parameters-10) ##### sessionKey [Section titled “sessionKey”](#sessionkey-10) `string` ##### thinking [Section titled “thinking”](#thinking) `string` ##### tokens [Section titled “tokens”](#tokens-1) { `input?`: `number`; `output?`: `number`; `cacheRead?`: `number`; `cacheWrite?`: `number`; `total?`: `number`; } | `undefined` ##### metadata? [Section titled “metadata?”](#metadata-1) ###### provider? [Section titled “provider?”](#provider-1) `string` ###### model? [Section titled “model?”](#model-1) `string` ###### signature? [Section titled “signature?”](#signature) `string` #### Returns [Section titled “Returns”](#returns-11) `Promise`<`string` | `null`> *** ### cleanupAllSessions() [Section titled “cleanupAllSessions()”](#cleanupallsessions) > **cleanupAllSessions**(): `Promise`<`void`> Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:221](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L221) #### Returns [Section titled “Returns”](#returns-12) `Promise`<`void`> *** ### getSessionState() [Section titled “getSessionState()”](#getsessionstate) > **getSessionState**(`sessionKey`): `SessionSpanState` | `undefined` Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:243](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L243) #### Parameters [Section titled “Parameters”](#parameters-11) ##### sessionKey [Section titled “sessionKey”](#sessionkey-11) `string` #### Returns [Section titled “Returns”](#returns-13) `SessionSpanState` | `undefined` *** ### getAllSessionKeys() [Section titled “getAllSessionKeys()”](#getallsessionkeys) > **getAllSessionKeys**(): `string`\[] Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:247](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L247) #### Returns [Section titled “Returns”](#returns-14) `string`\[] *** ### hasActiveInteraction() [Section titled “hasActiveInteraction()”](#hasactiveinteraction) > **hasActiveInteraction**(`sessionKey`): `boolean` Defined in: [packages/openclaw-prefactor-plugin/src/session-state.ts:251](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/session-state.ts#L251) #### Parameters [Section titled “Parameters”](#parameters-12) ##### sessionKey [Section titled “sessionKey”](#sessionkey-12) `string` #### Returns [Section titled “Returns”](#returns-15) `boolean` # Interface: ToolDefinition [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / ToolDefinition # Interface: ToolDefinition [Section titled “Interface: ToolDefinition”](#interface-tooldefinition) Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:9](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L9) Input schemas for supported OpenClaw tools. These define the expected parameters for each tool to enable proper validation and structured span capture. ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:10](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L10) *** ### description [Section titled “description”](#description) > **description**: `string` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:11](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L11) *** ### inputSchema [Section titled “inputSchema”](#inputschema) > **inputSchema**: `JsonSchema` Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:12](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L12) *** ### aliases? [Section titled “aliases?”](#aliases) > `optional` **aliases**: `string`\[] Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:13](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L13) # Type Alias: LogLevel [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / LogLevel # Type Alias: LogLevel [Section titled “Type Alias: LogLevel”](#type-alias-loglevel) > **LogLevel** = `"debug"` | `"info"` | `"warn"` | `"error"` Defined in: [packages/openclaw-prefactor-plugin/src/logger.ts:4](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/logger.ts#L4) # Variable: agentRunRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / agentRunRisk # Variable: agentRunRisk [Section titled “Variable: agentRunRisk”](#variable-agentrunrisk) > `const` **agentRunRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:64](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L64) Default risk profile for openclaw:agent\_run span. Agent runs orchestrate operations but don’t directly handle data mutations. # Variable: agentThinkingRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / agentThinkingRisk # Variable: agentThinkingRisk [Section titled “Variable: agentThinkingRisk”](#variable-agentthinkingrisk) > `const` **agentThinkingRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:81](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L81) Default risk profile for openclaw:agent\_thinking span. Thinking spans contain reasoning that may reference organizational confidential data. # Variable: assistantResponseRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / assistantResponseRisk # Variable: assistantResponseRisk [Section titled “Variable: assistantResponseRisk”](#variable-assistantresponserisk) > `const` **assistantResponseRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:98](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L98) Default risk profile for openclaw:assistant\_response span. Assistant responses may contain organizational confidential information from context. # Variable: defaultSpanTypeRiskConfigs [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / defaultSpanTypeRiskConfigs # Variable: defaultSpanTypeRiskConfigs [Section titled “Variable: defaultSpanTypeRiskConfigs”](#variable-defaultspantyperiskconfigs) > `const` **defaultSpanTypeRiskConfigs**: `Record`<`string`, `DataRisk`> Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:317](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L317) Complete default risk configuration for all OpenClaw span types. This configuration is used when registering the agent schema version. # Variable: GENERIC\_OBJECT\_SCHEMA [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / GENERIC\_OBJECT\_SCHEMA # Variable: GENERIC\_OBJECT\_SCHEMA [Section titled “Variable: GENERIC\_OBJECT\_SCHEMA”](#variable-generic_object_schema) > `const` **GENERIC\_OBJECT\_SCHEMA**: `object` Defined in: [packages/openclaw-prefactor-plugin/src/tool-span-contract.ts:6](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-span-contract.ts#L6) Generic object schema for flexible metadata. ## Type Declaration [Section titled “Type Declaration”](#type-declaration) ### type [Section titled “type”](#type) > **type**: `"object"` ### additionalProperties [Section titled “additionalProperties”](#additionalproperties) > **additionalProperties**: `boolean` = `true` # Variable: sessionRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / sessionRisk # Variable: sessionRisk [Section titled “Variable: sessionRisk”](#variable-sessionrisk) > `const` **sessionRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:115](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L115) Default risk profile for openclaw:session span. Session spans track lifecycle but contain minimal data. # Variable: SUPPORTED\_TOOL\_DEFINITIONS [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / SUPPORTED\_TOOL\_DEFINITIONS # Variable: SUPPORTED\_TOOL\_DEFINITIONS [Section titled “Variable: SUPPORTED\_TOOL\_DEFINITIONS”](#variable-supported_tool_definitions) > `const` **SUPPORTED\_TOOL\_DEFINITIONS**: `Record`<`string`, [`ToolDefinition`](../interfaces/ToolDefinition.md)> Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:20](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L20) Map of canonical tool names to their definitions. Aliases are normalized to canonical names during span creation. # Variable: TOOL\_ALIAS\_MAP [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / TOOL\_ALIAS\_MAP # Variable: TOOL\_ALIAS\_MAP [Section titled “Variable: TOOL\_ALIAS\_MAP”](#variable-tool_alias_map) > `const` **TOOL\_ALIAS\_MAP**: `Record`<`string`, `string`> Defined in: [packages/openclaw-prefactor-plugin/src/tool-definitions.ts:365](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/tool-definitions.ts#L365) Map of tool aliases to their canonical names. Used for normalizing tool names during span creation. # Variable: toolBrowserRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolBrowserRisk # Variable: toolBrowserRisk [Section titled “Variable: toolBrowserRisk”](#variable-toolbrowserrisk) > `const` **toolBrowserRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:300](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L300) Default risk profile for openclaw:tool:browser span. Browser automation interacts with external web services. # Variable: toolEditRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolEditRisk # Variable: toolEditRisk [Section titled “Variable: toolEditRisk”](#variable-tooleditrisk) > `const` **toolEditRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:216](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L216) Default risk profile for openclaw:tool:edit span. Edit operations modify data which may include organizational confidential info and secrets. # Variable: toolExecRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolExecRisk # Variable: toolExecRisk [Section titled “Variable: toolExecRisk”](#variable-toolexecrisk) > `const` **toolExecRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:241](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L241) Default risk profile for openclaw:tool:exec span. Shell execution is high-risk - can access secrets and execute arbitrary commands. # Variable: toolReadRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolReadRisk # Variable: toolReadRisk [Section titled “Variable: toolReadRisk”](#variable-toolreadrisk) > `const` **toolReadRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:166](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L166) Default risk profile for openclaw:tool:read span. Read operations access filesystem data which may include organizational confidential info and secrets. # Variable: toolRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolRisk # Variable: toolRisk [Section titled “Variable: toolRisk”](#variable-toolrisk) > `const` **toolRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:149](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L149) Default risk profile for openclaw:tool span (generic fallback). Generic tool calls have unknown risk until specific tool is identified. # Variable: toolWebFetchRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolWebFetchRisk # Variable: toolWebFetchRisk [Section titled “Variable: toolWebFetchRisk”](#variable-toolwebfetchrisk) > `const` **toolWebFetchRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:283](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L283) Default risk profile for openclaw:tool:web\_fetch span. Web fetch retrieves public content from external URLs. # Variable: toolWebSearchRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolWebSearchRisk # Variable: toolWebSearchRisk [Section titled “Variable: toolWebSearchRisk”](#variable-toolwebsearchrisk) > `const` **toolWebSearchRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:266](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L266) Default risk profile for openclaw:tool:web\_search span. Web search sends queries to external services but doesn’t typically include sensitive data. # Variable: toolWriteRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / toolWriteRisk # Variable: toolWriteRisk [Section titled “Variable: toolWriteRisk”](#variable-toolwriterisk) > `const` **toolWriteRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:191](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L191) Default risk profile for openclaw:tool:write span. Write operations create data which may include organizational confidential info. # Variable: userInteractionRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / userInteractionRisk # Variable: userInteractionRisk [Section titled “Variable: userInteractionRisk”](#variable-userinteractionrisk) > `const` **userInteractionRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:132](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L132) Default risk profile for openclaw:user\_interaction span. User interactions may involve organizational confidential data. # Variable: userMessageRisk [**Prefactor TypeScript SDK**](../../../index.md) *** [Prefactor TypeScript SDK](../../../modules.md) / [@prefactor/openclaw-prefactor-plugin](../index.md) / userMessageRisk # Variable: userMessageRisk [Section titled “Variable: userMessageRisk”](#variable-usermessagerisk) > `const` **userMessageRisk**: `DataRisk` Defined in: [packages/openclaw-prefactor-plugin/src/data-risk-config.ts:47](https://github.com/prefactordev/typescript-sdk/blob/231423a775642bec119a2db45acf108c6383d05d/packages/openclaw-prefactor-plugin/src/data-risk-config.ts#L47) Default risk profile for openclaw:user\_message span. User messages may contain any type of data including organizational confidential information.