Your agent gets better at its own job. You don't run the training.
A continual-learning loop around the agent you already have. Ship one line: your agent keeps running in your process, behind your firewall, on your credentials, unchanged. The model it calls and the prompt it runs keep improving, and a person on your side approves every change.
# 1 · install (zero runtime dependencies)$ openclaw plugins install @percepteye/agent-flywheel
$ npx @percepteye/agent-flywheel login
# 2 · let it read the conversation
{ "plugins": { "entries": { "agent-flywheel": {
"hooks": { "allowConversationAccess": true } } } } }
# 3 · restart OpenClaw. No code changes.✓approved prompt + model applied in production
# already on OpenTelemetry? nothing to install$ export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=\
"$PERCEPTEYE_CONTROL_PLANE_URL/agents/my-agent/otlp/v1/traces"$ export OTEL_EXPORTER_OTLP_TRACES_HEADERS=\
"Authorization=Bearer%20$PERCEPTEYE_API_KEY"$ export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/protobuf
✓GenAI spans in · improvement rounds start from them
0lines changed in your agent
0inbound ports, containers or GPUs
1 · 0runtime deps, Python · Node
2,306tests across both SDKs, 0 skips
The loop
Register once. Then it turns on its own.
Every lane is opened from your side. The better agent generates better evidence, which is what makes it a flywheel rather than a pipeline.
Runs practice tasks, records every tool outcome, captures the turns you serve, picks up the approved model and prompt
Writes tasks from your agent's real tools, grades every run, trains the policy, evolves the system prompt, measures each candidate against what you run today
You bring
pip install agent-flywheel or npm install @percepteye/agent-flywheel
An email address. Free plan, no credit card
Your agent (unchanged)
→ SDK / plugin records tool outcomes and turns
→ outbound HTTPS to the control plane
→ Mission Control: tasks → grading → training → evaluation
→ a person approves in Decisions
→ your agent picks up the approved model and prompt
Your agent keeps running where it runs today, behind your firewall, on your credentials. There is no container to build, no GPU to provision, and no inbound port to open: every connection is opened from your side.
Three things it gives you
An agent that improves in place. A policy trained on this agent's own work: its prompt, its tools, its failure modes. Not a generic model.
A system prompt that keeps evolving. Mission Control evolves your prompt from your agent's own traces and keeps improving it as new traces arrive. See Prompt optimization.
Honest evidence. Every tool call is recorded as ok, failed or unknown. unknown is never rounded up to ok. See Outcomes.
Nothing reaches your users until a person approves it. See Approvals.
Pick your integration
You have
Use
Start here
A Python agent (LangChain, LangGraph, Google ADK, or custom)
Connect your first agent to Agent Flywheel with the Python SDK, the Node SDK, the OpenClaw plugin, or DeepSeek Harness.
Start your first Agent Flywheel integration
Integration
Best fit
Capability boundary
Python SDK
A Python agent built by an importable module:attr factory, or any CLI agent
Practice tasks (serve()), production capture (attach()), approved model and prompt handed back for you to apply
Node SDK
A JavaScript or TypeScript agent on Node >=22.22.3: Vercel AI SDK, LangChain.js, LangGraph.js, or your own loop
Production capture (fw.turn()), practice tasks (fw.serve()), approved model and prompt handed to your agent on each turn
OpenClaw
An OpenClaw agent on Node >=22.22.3
Full workflow: recording, practice tasks, production capture, and the approved prompt and model applied for you. Needs conversation access enabled in OpenClaw
DeepSeek Harness
A dsh agent on Node >=22.22.3
Records tool outcomes only. No practice tasks, no production capture, no prompt or model changes
Every path has the same shape: get a key, install, start your agent.
1. Get a key
Sign up at launch.percepteye.ai, choose Add our SDK to your agent's code, name your agent, and copy its pefw_ key. The key is shown once and is scoped to that one agent. The name you give is the agent_id your code reports.
You can also get the key from the terminal once the package is installed (step 2):
Either command prints a short code and opens the browser with it filled in. Sign in, check the code matches, and click Approve. The key is stored in ~/.percepteye/credentials.json (mode 0600) and both SDKs read the same file.
2. Install and start
Python SDK
Install the SDK. Python 3.10 to 3.13. One runtime dependency, httpx.
shell
pipinstallagent-flywheel
exportPERCEPTEYE_API_KEY=pefw_...
exportPERCEPTEYE_AGENT_MODE=training# unset means production: serve() runs nothing
Note
Training takes two switches, one on each side. PERCEPTEYE_AGENT_MODE=training on your process says it may run practice tasks. Allow practice runs on the agent in Mission Control (an org admin turns it on) says the platform may send them. With either one off, no practice task runs, and the side that is off says so. Point a training process at a test or sandbox backend: it runs generated tasks through your agent's real tools.
Serve your agent. Pass an importable factory so each practice task rebuilds your agent in a fresh child process:
python
importagent_flywheelasfwfw.serve("my_package.agent:build",agent_id="my-coding-agent",input_shape="text",# "text", "messages" or "dict"max_rollouts=8,# bound your first run)
serve() claims practice tasks, runs them, reports outcomes, and blocks until it stops. Everything that can be misconfigured is checked before the first task and raises there.
Tip
Practice tasks are real runs on your real credentials. Bound the first one with max_rollouts=8 and point artifacts_dir= somewhere you don't mind it writing.
A CLI agent? Pass its command line instead. The task arrives on stdin:
Already serving users? Use attach() to record the turns you serve instead.
Node SDK
Install the SDK. Node 22.22.3 or later. Zero runtime dependencies, and TypeScript declarations included.
shell
npm install @percepteye/agent-flywheel
export PERCEPTEYE_API_KEY=pefw_... # from https://launch.percepteye.ai/onboard/agent-sdk
export PERCEPTEYE_AGENT_ID=support-agent # the name you gave the agent there
Wrap each turn you serve.fw.turn(input, fn) runs your agent and returns what it returns. It records the user's message, every tool call, and the answer.
runAgent is your agent. Its tool calls are recorded by the adapter for its framework, or by recordToolCall() where your tools run. Once a person approves a better system prompt and model, fn is handed both: t.systemPrompt(yours) and t.model.
Let it practise in a separate process pointed at a test or sandbox backend, with PERCEPTEYE_AGENT_MODE=training:
In a practice task t.model is always set, and your agent must call it. See Node SDK.
OpenClaw
Install the plugin. No import, no wrapper process, no sidecar.
shell
openclawpluginsinstall@percepteye/agent-flywheel
exportPERCEPTEYE_API_KEY=pefw_...
exportPERCEPTEYE_AGENT_MODE=training# for practice tasks; unset means production
Enable conversation access in your OpenClaw config. Installing the plugin does not grant it.
This lets the plugin read your agent's answer, describe your agent, and point your agent at the approved model. Without it the plugin refuses to claim practice tasks and says so once at startup.
Restart OpenClaw. The startup line says which state the plugin is in. If your host runs more than one agent, set agentId (see Node SDK configuration).
DeepSeek Harness is record-only. It writes tool outcomes to PERCEPTEYE_TRAJECTORY_DIR and, with that unset, writes nothing. It does not claim practice tasks, capture production turns, or apply prompt or model changes.
3. Watch the first lap land
The dashboard marks your agent Connected on its first call. From there:
Allow practice runs on the agent's page if this process runs practice tasks.
Allow learning. On the agent's page, turn on Let us learn from its conversations, including the message text. Until both permissions are on, nothing is uploaded.
Start improving. Click Start improving on the agent's page.
Approve the winner in Decisions when a candidate beats your current best.
How evidence is captured, tasks generated, outcomes graded, candidates trained, and approved behavior delivered back to your agent.
Agent Flywheel architecture
YOUR INFRASTRUCTURE │ PERCEPTEYE CONTROL PLANE
│
your agent (unchanged) │
↕ SDK or plugin │
├─ describe the agent (once) ───────►│ register; tasks from your real tool surface
├─ claim a practice task ───────────►│ lease + heartbeat
├─ run it, record outcomes │
├─ report trajectory + answer ──────►│ grade → dataset → train → evaluate
├─ upload served turns (opt-in) ────►│ learn from production; evolve the prompt
└─ read /policy/current, ◄──────────┤ serve what a person approved
/prompt/current │
│
every arrow is opened from your side │ no inbound port, no listening socket
The SDK or plugin never reproduces server-side work. Task generation, grading, training, prompt optimization and evaluation run on PerceptEye's GPUs.
Agent Flywheel lifecycle
⓪ Describe. Once at startup, the SDK reads the shape of your agent from inside its own process: the system prompt it really assembled, the tools it really registered (names, descriptions, JSON Schemas), provider and model, and sub-agents to depth 4. Never your tools' source, their return values, your credentials or your data. Turn it off with introspect=False or PERCEPTEYE_INTROSPECT=0. An agent nothing can read declares itself with describe=.
① Claim. In training mode, your process long-polls for a practice task (a rollout). Leases heartbeat while the task runs. Results held from earlier runs are delivered before new work is claimed.
② Run. Each task runs in a fresh child process with its own environment and a single-use credential. Your agent is unchanged.
③ Record. Every tool call lands as ok, failed or unknown, from adapters that observe from the outside or from an explicit record_tool_call(). Artifacts are collected on every path, including timeouts and non-zero exits.
④ Grade and train. Tasks generated from your real tool surface are graded against compiled checks. Graded runs become the dataset; the policy is trained and each candidate is measured against the model you run today.
⑤ Improve. A person approves the candidate in Decisions. Your production agent picks up the approved model and prompt. The next lap runs on the better agent, which generates better evidence.
Runtime and operator responsibilities
Runtime integration (SDK or plugin)
Operator (dashboard or mck_ key)
Primary role
Produce evidence; apply what was approved
Decide what trains and what ships
Data source
Your agent's own runs and served turns
What the runtime sent
Training and promotion
Never trains, never promotes
Starts rounds, approves or rejects candidates
Local training
None
None: training runs on the control plane
Runtime method reference
Method
Python
Node plugin
Purpose
Practice tasks
serve()
Training mode (OpenClaw)
Claim graded tasks, run them, report outcomes
Production capture
attach()
Production mode (OpenClaw)
Record the turns you already serve; upload only once enabled
Explicit outcome
record_tool_call()
Shell append to tool_calls.jsonl
Record a verdict you know
Approved model
apply_current_policy(), policy_source()
Applied automatically
Point your agent at the approved endpoint
Approved prompt
current_prompt(), prompt_decision()
Applied automatically
Swap in the approved system prompt
Outcome statuses
Status
Meaning
ok
Observed success
failed
Observed failure
unknown
No trustworthy verdict. Legal, expected, and never counted as a success
Every tool call is recorded as ok, failed or unknown. Why the third value exists, and how to record a verdict you know.
Why three values
Transcripts lie about tool outcomes. Two shapes cause most of it:
A tool that swallows its own exception. A LangChain tool with handle_tool_error=True returns a string that reads like a normal result, and nothing in the transcript separates it from a success.
A permission denial returned as HTTP 200. The body explains the refusal; the status says fine.
Scoring either as a success teaches the model that the failure was fine. So the SDKs add a third value, unknown, and refuse to round it up.
The three values
Value
What it asserts
status_code
Graders
ok
An observed success
Integer or null
Read it as success
failed
An observed failure
Integer or null
Read it as failure
unknown
Nothing observed a verdict
Forced to null
Outcome-dependent checks abstain
There is no fourth value and no default. Anything else raises ContractViolation.
A status is not an outcome.status_code is recorded only when you actually observed one. A status may confirm or contradict an observed outcome; it may never manufacture one. For unknown, the SDK also strips status fields (status_code, status, http_status, code, statusCode) and HTTP nnn text from the recorded output, so a scorer cannot recover a status through a side channel.
Note
An agent with zero instrumentation and no adapter that can classify its calls reports unknown for all of them. That is the honest floor, not an error.
What unknown costs
It lowers the grade available to a run; it does not exclude the run. Checks that grade "did this call land" have nothing to read and abstain. A run is excluded automatically for tool reasons only when every call was an observed failed.
Record a verdict you know
Adapters are best-effort. record_tool_call() is the always-available ground truth:
python
fromagent_flywheelimportrecord_tool_callrecord_tool_call("charge_card",{"amount":4200},outcome="ok",status_code=201)# A permission denial your API returned as HTTP 200: both halves are true.record_tool_call("charge_card",{"amount":4200},outcome="failed",status_code=200,error="app_auth_error")
Argument
Notes
name, arguments
The tool and the arguments it was called with
outcome, status_code
Keyword-only and required. You cannot record half an outcome by forgetting one
output, error, error_class
What came back, free-text error, exception class name
latency_ms
Optional timing
agent_name
Which agent in a multi-agent system made the call. None means unattributed
tool_call_id
The id the model assigned, the join key back to the completion
entity_ids
The identity a write produced, so the control plane can read it back. Never the body
Outside a practice task, record_tool_call() is a no-op, so it can sit in a production code path unconditionally.
From a shell or another language, append one JSON line per call to $PERCEPTEYE_TRAJECTORY_DIR/tool_calls.jsonl:
json
{"name":"exec","arguments":{"command":"exit 3"},"outcome":"failed","status_code":null,"error":"(Command exited with code 3)","error_class":"ToolError","latency_ms":155,"agent_name":"main","tool_call_id":"call_percepteye_1"}
Both SDKs write and read this same format.
None is not []
Value
Meaning
tool_calls = None
"I did not report tool calls"
tool_calls = []
"I observed zero tool calls", a positive claim
A line that cannot be parsed, such as a write truncated by a timeout, is counted in tool_calls_omitted_count rather than dropped.
See your agent's real failure rate
With nothing but local recording, you can read your agent's true tool-failure rate. No account and no network needed:
shell
agent-flywheelreport# most recent session
agent-flywheelreportpath/to/trajectory
Documentation/Core Concepts
Training and production modes
One variable decides whether a deployment runs practice tasks or serves users. The same image does either.
shell
PERCEPTEYE_AGENT_MODE=training
PERCEPTEYE_AGENT_MODE=production# the default when unset
Training is always an explicit choice. Since 0.4.0, a deployment that never set the variable is a production deployment, in both SDKs. A training process runs tasks written for your agent through its real tools, so point it at a test or sandbox backend, never the one your users depend on.
Note
Training also needs a second switch, one on each side. PERCEPTEYE_AGENT_MODE=training on your process says it may run practice tasks. Allow practice runs on the agent in Mission Control (an org admin turns it on) says the platform may send them. With either one off, no practice task runs, and the side that is off says so. Point a training process at a test or sandbox backend: it runs generated tasks through your agent's real tools.
What each mode does
Python SDK
training
production (default)
Pick it for
A machine you're happy to lend to practice tasks
The deployment serving your users
fw.serve(...)
Claims and runs practice tasks
Returns 0 immediately, before opening any connection
Needs a key
Yes
No
fw.attach(...)
Works
Works: this is the production surface
Note
The switch gates serve() only. It does not gate attach(), because attach() is the production surface.
Node plugin (OpenClaw)
training
production (default)
Records tool outcomes locally
Yes
Yes
Alters a tool result
Never
Never
Claims practice tasks and starts turns
Yes
No
Captures the turns you serve
n/a
Yes
Uploads them
n/a
Only once an operator enables it
Applies the approved system prompt
No
Yes. Off with PERCEPTEYE_APPLY_PROMPT=0
Points your agent at the approved model
No
Yes, with allowConversationAccess. Off with PERCEPTEYE_APPLY_MODEL=0
In production the practice-task hooks are not registered at all. Production is not observe-only: applying an approved prompt and model changes what your agent does. What it guarantees is that it claims no work and starts no turn.
In training, neither the prompt nor the model is applied. A practice task is evidence about your agent as configured; changing it mid-flight would move the behavior with no training behind it.
Accepted spellings
An unrecognized value raises (Python) rather than guessing, because a typo that silently picked training would keep spending your credentials.
Means training
Means production
training, train, rollout, fine-tuning
production, prod, serving
In Python, mode= in code beats the variable, then PERCEPTEYE_AGENT_MODE, then production; the startup line says when code overrode the variable. In the Node plugin, config beats the environment, and an unreadable value degrades to production and says so.
Get the trained model without contributing
A deployment can run no practice tasks and upload nothing, and still use what training produced:
python
importagent_flywheelasfwkw=fw.apply_current_policy(agent_id="my-agent")ifkw:# {} means keep your current configurationclient=OpenAI(base_url=kw["base_url"],api_key=kw["api_key"])model=kw["model"]
exportPERCEPTEYE_CAPTURE=0# register nothing, record nothing, claim nothingexportPERCEPTEYE_APPLY_PROMPT=0# keep recording, leave the system prompt aloneexportPERCEPTEYE_APPLY_MODEL=0# keep recording, leave the model alone
Each guarantee is the absence of the hook subscription, not a branch inside a handler.
Documentation/Core Concepts
Approvals
Nothing reaches your users until a person approves it. How the model and the prompt are each gated, and how to roll back.
The model
Your agent keeps serving the model it runs today, the champion, until all three of these hold. Each one fails closed back to the champion.
A person with the operator role moves that agent onto the candidate from the dashboard (Agent tab → Try the candidate). It is an explicit, role-gated call on that one agent. Your agent's own pefw_ key cannot make it. Moving back (Move back to champion) is the same call, which is what makes rollback fast enough to use during an incident.
The candidate's certification did not go against it. A verdict of regressed, inconclusive or escalated makes it unservable.
It is deployed somewhere your agent can call. A stored artifact (gs://, s3://, file://) is refused rather than handed out as a model name. Both SDKs re-check this on your side.
The prompt
A separate chain with its own approval. Each winning prompt arrives in Decisions as one prompt-pair delivery: the prompt, the checkpoint it was certified with, and a 2×2 evaluation (base or tuned model × your prompt or the new one). Only a delivery with status approved or delivered is ever served, and both SDKs re-check that status before the text is applied.
Model promotion, prompt-pair delivery and research promotion are classed as irreversible decisions. Only the explicit approve or reject control resolves them. A reply such as "sure, go ahead" in a chat or a document is recorded as answered, never as approved.
What runs on its own
Starting optimization rounds, certifying a winner and assembling a delivery are automatic by default. GET /api/v2/autonomy/flags shows each setting. Approval is never automatic: "auto" means the next candidate is ready and waiting, not that it ships itself.
Approve, reject, withdraw
Action
In the dashboard
Over the API (mck_ key)
Approve
Decisions → Approve
POST /api/v2/approvals/{approval_id}/approve
Reject
Decisions → Reject
Reject control in Decisions
Withdraw an approved prompt
Prompts → the prompt → Versions of this prompt → Withdraw
POST /api/v2/prompt-deliveries/{delivery_id}/withdraw
Roll back the model
Agent page → Move back to champion
Operator role, dashboard only
A withdrawn prompt stops being served at once. The previously approved prompt serves again, or, if there is none, running agents return to their own prompt within one refresh. A withdrawn prompt cannot be approved back; approve a newer delivery instead.
You can also stop applying on your side at any time: don't apply the served prompt (Python), or set PERCEPTEYE_APPLY_PROMPT=0 / PERCEPTEYE_APPLY_MODEL=0 (Node).
Which credential each integration uses, how to get it, and how the SDKs resolve it.
Choose a credential
There are two kinds of key. They are not interchangeable, and most integrations need only one.
Purpose
Environment variable
Prefix
Used by
Your agent talks to the control plane
PERCEPTEYE_API_KEY
pefw_
Python SDK, Node plugin, OpenTelemetry push
Operator automation: runs, eligibility, approvals
PERCEPTEYE_MC_API_KEY
mck_
CustomerApiClient (Python and Node), the Agent Training Skill, the Claude Code plugin
shell
PERCEPTEYE_API_KEY=pefw_...# agent keyPERCEPTEYE_MC_API_KEY=mck_...# customer-automation key, only if you automate Mission Control
The customer API client refuses a pefw_ key before sending anything.
Note
OpenClaw's conversation access (hooks.allowConversationAccess) is a host permission, not a credential. A valid key does not grant it. See the Node SDK.
Agent keys (pefw_)
One key per agent. A pefw_ key is bound to the agent name it was created for. A key made for a different agent is refused (this key is bound to a different flywheel).
Shown once. Copy it when you create it. If you lose it, create a new one: Agents → your agent → Get a new key.
Expires after 180 days. Revoke a key in Settings → Agent keys → Revoke.
Only an organization admin can create an agent and its key.
Get one in the dashboard
New mission → Your AI agent → Add our SDK to your agent's code → name the agent → Create agent and get my key. The name is the agent id your code reports.
The command prints a short code and opens launch.percepteye.ai with the code filled in. Sign up or sign in, check the code matches, and click Approve. Add --no-browser to print the link instead of opening it.
The key is stored in ~/.percepteye/credentials.json (or $PERCEPTEYE_HOME/credentials.json), mode 0600, for that one agent on that one control plane. Both SDKs read and write the same file, so a key stored by either serves both.
shell
agent-flywheellogout--agent-idmy-agent# forget it on this machine
npx@percepteye/agent-flywheellogout--agent-idmy-agent
Logging out forgets the key locally. Revoking it in Settings stops it everywhere.
How the key is resolved
Order
Python SDK
Node plugin
1
api_key= argument
apiKey in the plugin config
2
PERCEPTEYE_API_KEY
PERCEPTEYE_API_KEY
3
Key stored by login for this agent on this control plane
Key stored by login for this agentId on this control plane
When a stored key is used, the SDK says so once. A stored key is consent to send, exactly as the variable is.
With no key at all:
Python serve() offers to create one when a person is at the terminal: No PerceptEye key found for agent 'my-agent'. Create one now (free)? [Y/n]. It never asks in CI, with PERCEPTEYE_NO_PROMPT=1, or when stdin or stderr is not a terminal; there it raises before the first practice task, naming agent-flywheel login and the sign-up page.
Python attach() keeps your agent running and records on disk; px.upload_refusal says why nothing is sent.
The Node plugin records locally and sends nothing. Its startup line says so.
Customer-automation keys (mck_)
Get one from the dashboard's Settings, or with pe login. Pass it as api_key= / apiKey, or set PERCEPTEYE_MC_API_KEY. It authorizes the Mission Control API under /api/v2 on the same origin as the control plane: see the Mission Control API.
The control-plane URL
The URL has a default, so the key is the only thing your environment must supply.
Order
Source
1
control_plane_url= (Python) or controlPlaneUrl (Node config)
2
PERCEPTEYE_CONTROL_PLANE_URL
3
https://launch.percepteye.ai/api/flywheel/v1
agent-flywheel status prints the URL the Python SDK resolved.
Where your key is sent
Never in a request body. Both SDKs replace any pefw_ key found in a body, for example one a tool printed, with pefw_[REDACTED].
Only to the control plane's own gateway. When an approved model is served, your pefw_ key is used for that endpoint only if the control plane names PERCEPTEYE_API_KEY for it and the endpoint sits at your control plane's own origin. Any other endpoint's credential comes from your own configuration.
Never to disk by the SDK, apart from credentials.json written by login. Practice-task lease tokens stay in memory.
Secure credential handling
Never paste a key into a chat or commit it to a repository.
Prefer your host's secret handling: in OpenClaw, put apiKey in the plugin config rather than the shell environment.
Revoke a key you suspect has leaked in Settings → Agent keys.
Documentation/Guides
Production capture
Record the turns your agent already serves, and upload them only after an operator enables it.
Capture is opt-in, twice
Permission
What it allows
Default
Send us its conversations
Upload each turn: the steps, which tools were called, what the agent decided
Off
Include the message text
Also record and upload what the model saw: system prompt, history, tool definitions, every tool result, as one OpenTelemetry GenAI trace (genai_trace)
Off
Both are switched on together in setup with Let us learn from its conversations, including the message text, and shown separately on the agent's page. Learning needs both. Only an organization admin can change them, and your agent notices without a restart.
Until upload is allowed, turns accumulate on your own disk and go nowhere. The model-content tier is granted only while exactly one active Product declares the agent.
Python: attach()
python
importagent_flywheelasfwpx=fw.attach(agent_id="support-agent",trajectory_root="/var/lib/percepteye")withpx.turn(task_id=case_id,conversation_id=conv_id,input_text=user_text)asturn_id:reply=agent.invoke(user_text)# your agent, unmodifiedpx.record_answer(turn_id,reply)# after the scope closes
It captures. It never reroutes. Adapters bind with no endpoint, so attaching cannot redirect production traffic. Everything fails open: an unreachable control plane costs the observation and nothing else.
Declare turn boundaries.turn() is a context manager that yields the turn id. Give every turn of one conversation the same conversation_id.
Pass the text yourself.input_text= and record_answer() carry your end user's message and your answer, which no adapter can tell apart from the rest of a model call. A turn with no answer is held back from the 32-turn upload.
task_id= is optional correlation for your own case, job or ticket. It grants no training eligibility.
Model content is observed automatically for LangChain, LangGraph and Google ADK agents when the second permission is on. For any other agent, push its OpenTelemetry traces.
When turns are sent
Once upload is allowed, answered turns go every 32 turns on a short-lived daemon thread, and an atexit hook sends the rest. Uploads never raise into your process and never block a turn. While upload is not allowed, the SDK re-reads the permission before each batch, so no restart is needed.
python
px.may_upload# live answerpx.upload_refusal# the sentence explaining a Falsepx.may_capture_model_contentpx.model_content_refusalpx.flush()# send nowpx.close()# unbind and send what is waiting
Your copy on disk
Every turn is a directory under trajectory_root. Uploading does not delete it. Left alone it grows roughly 2.4 GB per million recording turns, so bound it:
python
px=fw.attach(agent_id="a",trajectory_root="/var/lib/percepteye",retention_turns=50_000)# keep the most recent 50k turnspx.prune(keep_last=10_000)px.prune(older_than_s=7*24*3600)
PERCEPTEYE_AGENT_MODE does not gate attach(). To stop capture, don't call it, or pass register=False to keep everything local.
With a key set, the plugin registers your agent at startup, then asks whether it may upload. Each turn is written as one directory:
$PERCEPTEYE_CAPTURE_DIR/<runId>/ # default ~/.percepteye/captured
turns.jsonl # {"kind":"task"|"answer","text","turn_id","conversation_id","task_id"}
conversation_id
task_id # optional correlation id
tool_calls.jsonl
genai_observation.jsonl # only under the model-content tier
This is the same on-disk format the Python SDK writes. Turns upload every 32 turns and at gateway shutdown, once enabled. If the control plane refuses a batch (consent withdrawn, or the key lost its scope), the plugin stops uploading, says why, and keeps the turns on disk.
Recording model content needs hooks.allowConversationAccess: true. A run the plugin cannot reconstruct faithfully records no model boundary rather than a guessed one.
Personal data
Everything received is scanned for email addresses, phone numbers, card numbers, US social security numbers and IP addresses. In tool-call records a match is masked. In messages and model content it is kept as sent, and that turn is never learned from. The SDKs mask nothing on your side.
Production turns are advisory
Production turns were produced by whatever you run, so they inform training rather than being graded as practice tasks are. Training capacity comes from serve() or the plugin's training mode.
Workflow rules
Declare your Product's workflow rules once per start: prose rules a person would tell a new colleague, used as training guidance for the decisions they apply to. They never change what your agent is served.
python
px=fw.attach(agent_id="support-agent",trajectory_root="/var/lib/percepteye",rules=["Before issuing a refund, confirm the order number with the customer."])
In the Node plugin, set rules in the plugin config. None / unset sends nothing, [] retracts, and the last writer wins. A refusal never stops your agent: read px.rulebook_refusal (Python) or the startup warning (Node).
Documentation/Guides
Apply the approved model and prompt
Pick up the model and system prompt a person approved, with no redeploy, and roll back the same way.
Python SDK
The Python SDK hands the approved pair back; your code applies it. Use these in the process serving your users, never inside serve().
The model, once at startup
python
importagent_flywheelasfwfromopenaiimportOpenAIkw=fw.apply_current_policy(agent_id="support-agent")ifkw:# {} means keep your current configurationclient=OpenAI(base_url=kw["base_url"],api_key=kw["api_key"])model=kw["model"]
One GET /policy/current. No registration, no practice tasks, no capture. It returns {} for every reason it cannot act (nothing approved, no key, unreachable control plane, a stored-file address such as gs://) and logs which on the agent_flywheel logger. It never raises into your startup. set_env=True also exports OPENAI_BASE_URL and OPENAI_API_KEY.
The model and prompt, per turn
A one-shot read means a rollback would wait for your next deploy. policy_source() keeps up:
python
policy=fw.policy_source(agent_id="support-agent",ttl_s=300)defhandle(user_text):snap=policy.current()# call per turn; a cache read between refreshesifsnap.changed:# rebuild only on an actual changeifsnap.withdrawn:client,model=build_my_own_client()else:client=OpenAI(base_url=snap.base_url,api_key=snap.api_key)model=snap.model# Fall back to YOUR prompt, not the last one applied: a withdrawn prompt must stop running.system_prompt=snap.prompt.textifsnap.prompt.applyelseMY_PROMPT...
Nothing polls in the background. The refresh runs inside your current() call once the TTL expires. Default TTL is 300 s; the control plane's hint wins; the floor is 30 s; ±10% jitter per handle.
Serve-stale, always. After its first success, a failed refresh keeps the last good snapshot. snap.stale_for_s is the number to alert on; snap.last_refresh_ok is False while refreshes fail.
A withdrawal is given back. When a person rolls the agent back with nothing to serve, snap.withdrawn is True and on_change fires. Go back to your own configuration.
serving_generation moves whenever anything to run moves, the prompt included. Use it to cycle replicas.
The prompt, on its own
python
served=fw.current_prompt(agent_id="support-agent")decision=fw.prompt_decision(served)ifdecision.apply:system_prompt=decision.textelse:log.info("keeping the current prompt: %s",decision.reason)
prompt_decision() refuses, naming the cause, when:
It refuses when
Because
No text to apply
Nothing approved yet, or the control plane could not answer
stale_baseline is true
Your own baseline prompt changed after the pair was certified
status is not approved or delivered
Only a version a person approved is applied
sha256 and model_prompt_checksum differ
The pair disagrees with itself
text is None on every refusal, never "", so a refusal can never blank your agent's prompt. The SDK never applies a prompt for you.
Node plugin (OpenClaw)
In production mode the plugin applies both halves for you:
The model. At startup it reads GET /policy/current, registers a provider percepteye-flywheel whose transport points at the served base_url, and names it from before_model_resolve. Needs hooks.allowConversationAccess: true. Read once: restart to pick up a new model.
The prompt. It reads GET /prompt/current and replaces the prompt your host assembled, every attempt. At most once per ttl_s (never faster than 30 s) it re-reads /policy/current in the background of a turn; a changed prompt_generation fetches the new text. The turn that noticed keeps its prompt; the next turn runs the new one.
Both apply to this agent's own served turns only: never a subagent, a scheduled (cron) turn, or another agent in the same gateway. If identity cannot be established, nothing is applied.
The pair check is the line worth reading. When both halves land, the startup log confirms the approved prompt is running on the checkpoint it was certified with. When only one lands, it warns and names which half is missing and why.
What stops each half
Prompt not applied
Model not applied
No API key
No API key
PERCEPTEYE_APPLY_PROMPT=0
PERCEPTEYE_APPLY_MODEL=0
Empty answer: nothing approved
allowConversationAccess missing
withdrawn
Host refused the provider registration
stale_baseline
The model was withdrawn
Status not approved/delivered
No endpoint served (champion arm, or candidate not deployed)
Prompt checksum and checkpoint disagree
An archive reference (gs://, s3://) as the model
Each refusal is logged with its own reason. An unreachable control plane costs the improvement and nothing else.
How long a new approval takes
About one ttl_s plus one turn after approval, with no redeploy (Python policy_source() and the Node prompt half). The Node model half and Python apply_current_policy() take effect on the next restart.
Roll back
Move the agent back to champion on its page, or withdraw the prompt in Prompts. See Approvals.
Documentation/Guides
Prompt optimization
Mission Control evolves your agent's system prompt from its own traces, keeps improving it as traces arrive, and ships the approved one back beside the model.
How it works
Evolutionary, not one-shot. Each generation proposes edits to your prompt as diffs against your own baseline, never a rewrite from nothing, grounded in where your agent actually failed. A candidate whose diff does not apply cleanly is rejected.
Multi-objective. Every candidate is scored on several separate axes. The Pareto frontier is kept rather than blending scores into one number, and what the frontier got wrong feeds the next generation.
Learned from your agent's own decisions. A prompt run replays your agent's recorded decisions, so it needs the model-content permission (Include the message text). Nothing is re-run against your users.
It keeps improving while you decide. Each new round starts with the candidate already waiting as the bar to beat. It is replaced only by a prompt that measures better, and the older waiting one is retired from your queue. An approval already granted is never taken back.
Certified, then approved. The winner is certified in a full-scale run, paired with the checkpoint it was measured on, and sent to Decisions as one prompt-pair delivery with a 2×2 evaluation (base or tuned model × your prompt or the new one).
Is my agent ready?
python
fromagent_flywheel.customer_apiimportCustomerApiClientwithCustomerApiClient()asmc:# needs an mck_ keypath=mc.training_eligibility(agent_id="agent_123")["prompt_optimization"]# path["mode"], path["can_run"], path["needs"]runs=mc.list_runs(include_prompt_evolutions=True)
Nothing is pushed into your agent. Your process pulls:
Per turn, policy_source().current() (Python) or the plugin's prompt hook (Node) uses a cached answer. When ttl_s expires, it re-reads GET /policy/current.
The policy carries prompt_generation, naming the approval being served. Only when it changes does the SDK fetch the text from GET /prompt/current.
The text is checked (approved status, unchanged baseline, matching checksum) and applied at the start of the next turn. A turn never changes prompt halfway.
An empty answer or a failed read changes nothing. A withdrawal is the one answer that takes the prompt away, and your own prompt runs from the next turn.
The bytes served are pinned at approval: a later round can never change what an approval already covers. Approval is never automatic. See Approvals.
Documentation/Guides
OpenTelemetry push
Already exporting OpenTelemetry GenAI spans? Point your exporter or Collector at the control plane instead of installing an SDK.
If your agent already records its model calls as OpenTelemetry spans in the GenAI semantic conventions, with message content, point its OTLP exporter or your Collector at the control plane. Nothing to install.
Push or SDK?
Push spans when
Use an SDK when
The agent is already instrumented with OpenTelemetry
You also want practice tasks: generated tasks your agent works through and that are graded
The SDK can't be installed where the agent runs
You want the approved model and prompt applied for you (Node) or handed back (Python)
Send each conversation one way only. Pushed spans and uploaded turns are both kept, so the same traffic sent both ways is learned from twice.
Note
Many instrumentations record message content only when you switch it on. Without it there is nothing to learn from.
1. Add the agent
In the dashboard: New mission → Your AI agent → Also send us the traces your agent already exports → name the agent → Create agent and get my key. This registers the agent, gives it a pefw_ key, opens its Permissions step, and shows its endpoint.
Turn on both permissions (conversations, and message text). Until both are on, every push is answered 403 and nothing in it is read.
Registering over the API instead, for an agent that never runs an SDK:
num_consumers: 1 avoids 429s from a Collector sending several requests at once.
3. See it arrive
The agent's Agent tab counts the spans pushed, beside turns uploaded by an SDK, and how many of each are kept but not learned from, and why.
What the endpoint accepts and answers
Status
Meaning
Retry?
200
ExportTraceServiceResponse; partial_success counts spans not kept and says why
—
400
Not an OTLP trace export
No
403
Consent not given (production_capture_not_enabled, model_content_capture_not_enabled), or the key belongs to another agent
No
415
Send application/x-protobuf or application/json, gzip or uncompressed
No
429
Your organization is over its rate; Retry-After set
Yes, automatically
503
Control plane busy; Retry-After set
Yes, automatically
507
Request too large for this host's disk
No
There is no size cap. Batches, as the batch processor and Collector send by default, are learned from soonest.
Personal data
Message content is scanned for personal data. A request whose spans hold any is kept and excluded from training, and partial_success says so. Spans carrying an SDK rollout marker (percepteye.rollout.id) are rejected: practice tasks reach the control plane through the SDK.
Exporting from the SDKs
The SDKs can also emit into your own tracing:
Python:pip install "agent-flywheel[otel]" emits each outcome as a span into your registered TracerProvider (the API only; it never installs an SDK). Spans carry the GenAI conventions plus percepteye.tool.outcome; an unknown leaves the span status unset.
Node:@opentelemetry/api is an optional peer dependency, used through @percepteye/agent-flywheel/tracing.
Documentation/Guides
CLI agents
Run practice tasks for any command-line agent, in any language, with no change to the binary.
A list or tuple means the agent is a process. Nothing is imported, and the agent is already isolated in its own process.
How the task arrives
Channel
When
Notes
stdin
Always, unless fw.TASK is in the argv
Written, then closed
PERCEPTEYE_TURN_INPUT
Always
Inert unless your CLI reads it
An argv position
Only where fw.TASK appears
Every occurrence is substituted; stdin then gets ""
fw.TASK is a sentinel object, not the string "{task}". The argv is passed to the OS as a list, never through a shell.
Warning
Anything in an argv is visible to other users through ps. Use fw.TASK only when your CLI cannot read stdin or an environment variable.
What comes back
For an ordinary command, trimmed stdout is the final answer.
What happened
Exclusion
Reported
Exit 0
None
Yes
Non-zero exit
agent_exit_nonzero, with the last 1500 characters of stderr
Yes, carrying the exclusion
Killed on the deadline
deadline_exceeded
Yes, carrying the exclusion
Binary could not start
flywheel_crash
No: the task is abandoned
Excluded is not discarded: the work product is recorded, and the control plane knows not to train on it. On a clean exit or a timeout, stderr is discarded.
The working directory is the run
Each run starts in its own directory, <artifacts_dir>/_percepteye/<rollout_id>, also passed as PERCEPTEYE_TRAJECTORY_DIR. Every file your agent leaves there is collected as an artifact (symlinks are never followed). artifacts_dir= defaults to ./.percepteye-artifacts: point it outside any checkout, because a CLI agent has a real shell.
The child's environment
Variable
Value
PERCEPTEYE_ROLLOUT_ID
This run's id
PERCEPTEYE_TRAJECTORY_DIR
This run's directory, also the working directory
PERCEPTEYE_TURN_INPUT
The task
PERCEPTEYE_TASK_ID
The id of the task this run was handed (your own id for a task you registered)
PERCEPTEYE_HOSTED_URL
Base for non-policy models through the gateway; append the provider, e.g. /openrouter
Your environment otherwise passes through, except that the PERCEPTEYE_ namespace is never inherited (your long-lived key stays in the parent), and provider variables the gateway cannot serve (Azure, Gemini/Vertex, Bedrock's bearer token, OpenAI-compatible resellers) are removed. serve() warns at startup if it finds any.
Your agent must sample through an OpenAI-compatible client, because the per-run gateway speaks that API and records the model calls.
If your agent reads other variable names, declare them:
If a task carries a completion gate and your binary takes one, name its flag: gate_flag="--autonomous-gate".
Timeouts
rollout_timeout_s (default 900) is capped by the run's remaining budget less a 10 s margin. On expiry the whole process group is killed with SIGKILL, so a shell, compiler or test runner your agent spawned cannot hold the run open.
Tool outcomes with no instrumentation
Append from a shell. One JSON object per line; name and outcome are required.
Or parse the event stream your CLI already prints with an explicit command_output_adapter. Without one, stdout is only the final text and no tool evidence is inferred. The generic OpenTelemetry GenAI format (gen_ai.tool.start / gen_ai.tool.end) can be reused by a small adapter of your own. An end event with no error flag is unknown, never ok.
If anything was written to tool_calls.jsonl, including [], the stream parse is not consulted.
Report your own grade
An agent backed by its own environment can grade itself. Write one JSON object to $PERCEPTEYE_TRAJECTORY_DIR/outcome.json before exiting:
Both keys are optional. Only a finite number is read as reward and only a boolean as success; anything else is ignored, never coerced.
How a CLI agent is described
A CLI agent has no object to read, so at startup serve() runs it once with the warm-up prompt Reply with the single word: ready against a local observer that forwards nothing, and reads the system prompt and tools from the completion request. It takes well under a second.
fw.serve(entrypoint,# "module:attr", an argv list, or (inprocess only) an object*,agent_id:str,input_shape:str,# "text" | "messages" | "dict"**options,)->int
Claims practice tasks, runs each in a fresh child process, reports outcomes, and blocks until it stops. It runs only with PERCEPTEYE_AGENT_MODE=training (or mode="training"): unset means production, where it prints one line and returns 0 before opening any connection. Practice also needs Allow practice runs on the agent in Mission Control; serve() says so at registration when it is off.
Argument
Default
What it does
entrypoint
required
"module:attr", an argv list, or a constructed object (inprocess only)
agent_id
required
The agent this process serves for. The key is bound to it
input_shape
required
"text", "messages" or "dict". Declared, never inferred
mode
None
Overrides PERCEPTEYE_AGENT_MODE. Unset everywhere means production
transport
"attach"
The only value in contract flywheel/1
control_plane_url
None
Then PERCEPTEYE_CONTROL_PLANE_URL, then https://launch.percepteye.ai/api/flywheel/v1
api_key
None
Then PERCEPTEYE_API_KEY, then the key stored by agent-flywheel login
artifacts_dir
None
Defaults to ./.percepteye-artifacts. Point it outside any checkout
isolation
"subprocess"
Or "inprocess" (capped at concurrency=1, no real timeout)
concurrency
1
Tasks in flight. One claim asks for at most 16
rollout_timeout_s
900.0
Local ceiling on one task
max_rollouts
None
Stop after this many complete. The only clean exit
Agent discovery. Also gated by PERCEPTEYE_INTROSPECT
describe
None
{"system_prompt", "tools", "model"} for an agent nothing can read. Wins over reflection
rules
None
Your Product's workflow rules, one prose rule per string. None sends nothing, [] retracts
gate_flag
None
How a CLI binary spells its completion-gate option
endpoint_env
None
(url_var, key_var) your agent reads its endpoint from
command_output_adapter
None
Interpret a CLI's structured stdout. Without one, stdout is final text
reports_tool_calls
False
Assert that a per-call outcome is reported for every call
execution_snapshot
None
Adapter-owned prepare/attest/release lifecycle for exact execution identity
attested_execution_components
None
{name: lowercase_sha256} evidence for execution identity
volatile_command_values
None
Command options whose value is transport, not identity, e.g. ("--daemon-socket",)
harness_snapshot
None
Deprecated alias for execution_snapshot
Everything that can be misconfigured is checked before the first task, in this order: mode, transport, URL and key, /health and contract flywheel/1, unroutable provider variables, entrypoint, isolation. Each raises there, never mid-run.
Entrypoints
"module:attr" resolves to
What happens
A class
Instantiated with no arguments
A zero-argument factory
Called; its return value is the agent
An object with invoke / run / execute / chat
Used as-is
A function taking the task
Treated as a factory, so it raises TypeError. Wrap it in a class or factory
The method is probed in order: invoke, run, execute, chat, __call__. async def is awaited. Resolution happens once at startup and raises there, listing what was available.
input_shape
Your entrypoint receives
"text"
"the task description"
"messages"
[{"role": "user", "content": "the task description"}]
max_rollouts=N is the only clean exit. Nothing in the package catches SIGINT or SIGTERM: Ctrl-C drains in-flight tasks first (up to rollout_timeout_s); SIGTERM orphans them and the control plane reclaims them by lease expiry. Revoking the key does not stop the loop; it keeps retrying and emitting claim_failed.
A result is never silently lost
Each outcome is written to a durable outbox under artifacts_dir before it is sent, and held results are delivered before the next claim, including by a later process over the same directory. A permanent refusal is retired (renamed, never deleted) and you are told where. No bearer credential is written to disk.
Events
on_event is the only way to see the delivery path. Wire it in production.
Event
When
Payload
claim_empty
A claim returned no work
poll_after_ms
claim_failed
The claim itself failed
error
rollout_start
A claimed task began
rollout_id
rollout_reported
The result was accepted
rollout_id, grade, duplicate, exclusion
rollout_crash
The task raised and was abandoned
rollout_id, error
report_failed
The work happened; delivering it did not
rollout_id, error
artifact_failed
Collecting artifacts failed; still reported, excluded from training
rollout_id, name, error
lease_lost
The lease lapsed or was taken back
rollout_id
heartbeat_failed
A renewal could not be delivered
rollout_id, error
serve_failed
The SDK failed while running a task; still reported
The per-call ceiling exceeds the episode's remaining time (once)
worst_case_call_s, child_s
outcome_spooled
Result held in the outbox
rollout_id, reason, path
outcome_spool_failed
Could not write to the outbox; delivery attempted anyway
rollout_id, error
outcome_undeliverable
Refused permanently; retired, never deleted
rollout_id, status, error, path
outcome_unrebuildable
A held result could not be read back; moved aside
rollout_id, error, path
outcome_abandoned_in_outbox
A held result older than seven days; kept, no longer retried
rollout_id, age_s, path
drain_failed
Delivering held results failed; claiming continues
error
delivery_brake
Three permanent refusals in a row; claiming stops
consecutive_permanent_refusals, outbox
claim_empty versus claim_failed tells an empty queue from a broken route. The callback runs synchronously on three different threads; keep it cheap. Exceptions it raises are swallowed.
With register=True, startup makes POST /agents (as mode: "production") then GET /policy/current, plus POST /agents/{agent_id}/rulebook in the background when rules= is given. Everything fails open.
Returns {"base_url", "api_key", "model"} or {} (keep your configuration). Never raises into startup. set_env=True exports OPENAI_BASE_URL and OPENAI_API_KEY.
Lower level: current_policy(agent_id=...) returns the raw /policy/current body; endpoint_kwargs(policy, *, api_key=None, flywheel_key=None, control_plane_url=None) turns a body into client arguments; is_withdrawn(policy) and is_archive_ref(model) are the checks it applies.
policy_source()
python
src=fw.policy_source(*,agent_id,ttl_s=300.0,control_plane_url=None,api_key=None,on_change=None)snap=src.current()# call per turn
PolicySnapshot field
Meaning
base_url, api_key, model
What to run; empty when nothing is deployed
changed
True on the one snapshot that first reports a change
withdrawn
True when a person rolled back with nothing to serve: return to your own configuration
prompt
A PromptDecision for the approved prompt served now
stale_for_s
0.0 while refreshes succeed; seconds past the TTL while they fail
last_refresh_ok
False after a failed attempt
serving_generation
Moves when anything to run moves, the prompt included
snap.as_kwargs() returns the apply_current_policy() shape. TTL floor is 30 s; the server's ttl_s hint wins over yours; ±10% jitter; one refresh attempt of 1 s. PolicySource is a context manager.
served fields: name, version, text, sha256, candidate_kind, status, model_prompt_checksum, stale_baseline. prompt_decision() refuses when there is no text, the baseline is stale, the status is not approved/delivered, or the checksums disagree. text is None on every refusal. See Apply the approved model and prompt.
current_capture()
python
matchfw.current_capture():case("rollout",rid):...# inside a serve() practice taskcase("turn",tid):...# inside attach().turn()caseNone:...# neither
Warning
current_rollout_id() returns the turn id inside attach().turn(), so it is not a practice-versus-production test. Use current_capture().
current_mode() and resolve_mode(explicit=None) return the resolved mode.
Inside a practice task
New in 0.4.0, for agents backed by their own environment: a benchmark harness, a simulator, a test suite.
python
task=fw.current_task_id()# the task this rollout was handed, or Noneurl=fw.hosted_model_url("openrouter")# a NON-policy model, or None outside a rolloutsim=OpenAI(base_url=url,api_key=os.environ["OPENAI_API_KEY"])
Function
Returns
current_task_id()
For a task you registered with the control plane, your own id, so your environment can start and grade exactly that task. For a generated task, its opaque id. Inside attach().turn(), the turn's task_id. Child processes read PERCEPTEYE_TASK_ID
hosted_model_url(provider)
Where this rollout reaches a model that is not the policy under training (a user simulator, a judge, an embedding model) through Mission Control's gateway. Providers include openai, anthropic, gemini, vertex, openrouter. For OpenAI-compatible providers it is an OpenAI client's base URL as is. Child processes read PERCEPTEYE_HOSTED_URL
Inside a rollout every OpenAI or Anthropic call is the policy's, whatever model you name. Calls through hosted_model_url() are your organization's own, paid as hosted calls, and never recorded as training rows.
A Python entrypoint reports its own grade by returning a RolloutOutput with reward and success. A command agent writes $PERCEPTEYE_TRAJECTORY_DIR/outcome.json instead: see CLI agents.
Adapters
Adapter
Distribution
Covers
ok
failed
langchain
langchain-core >=0.3,<2
LangChain and LangGraph
ToolMessage with status="success"
Raised, or status="error"
adk
google-adk >=1,<3
Google ADK
Never reported
Raised, or a dict with a truthy "error"
Everything else is unknown. status_code is always null from an adapter. No adapter imports its framework until it binds, so adapters add no dependencies.
adapters=
Behavior
"auto"
Bind every built-in whose framework is installed
[]
Bind nothing
["langchain"]
Require it; raises RoutingNotInstallable if it cannot bind
Ship your own adapter as one entry-point factory in the agent_flywheel.adapters group. It must not import its framework at module scope, must report unknown rather than guess, and must fail loudly at bind time.
Customer API client
python
fromagent_flywheel.customer_apiimportCustomerApiClient,CustomerRefusalwithCustomerApiClient()asmc:# mck_ key: api_key= or PERCEPTEYE_MC_API_KEYruns=mc.list_runs(product_id="prod_123",include_prompt_evolutions=True)elig=mc.training_eligibility(agent_id="agent_123")sets=mc.list_eval_sets(product_id="prod_123",limit=20)sec=mc.hillclimb_security("run_123")
A refusal raises CustomerRefusal with code, message, customer_message, customer_words, remediation, fault_owner, retryable. Show plain_words to a person. Customer contract 1.31.0.
Errors
Exception
Raised when
FlywheelError
Base class
ConfigurationError
Anything misconfigured, before the first task
EntrypointError
The entrypoint does not resolve, or input_shape is invalid
RoutingNotInstallable
A named adapter cannot bind. Carries reason: AdapterFrameworkAbsent, VersionOutOfRange, SymbolMissing
ModeNotAvailable
A transport this contract does not speak
ContractViolation
A record the wire contract forbids, such as an outcome other than the three
Starts a device login for that one agent: prints a short code and opens launch.percepteye.ai with the code filled in. After you sign in and click Approve, the pefw_ key is stored in $PERCEPTEYE_HOME/credentials.json (default ~/.percepteye, mode 0600). The Node plugin reads the same file.
Option
Default
--agent-id
$PERCEPTEYE_AGENT_ID
--control-plane-url
$PERCEPTEYE_CONTROL_PLANE_URL, else the hosted control plane
Forgets the stored key. The key stays valid until it is revoked in Settings → Agent keys.
report
shell
agent-flywheelreport[DIRECTORY]
Reads a trajectory directory (default: the most recent session) and prints the real tool-failure rate. unknown calls are reported, never counted as successes. Works with no account and no network.
install-hooks
shell
agent-flywheelinstall-hooks[--force]
Installs the goose host plugin that records each tool call's outcome to the trajectory. --force replaces a plugin directory this command did not install. With a key set and PERCEPTEYE_AGENT_MODE resolving to training, the goose hook also claims a practice task at SessionStart and reports the session at Stop; in production it only records. The command says which applies and names the control-plane URL it resolved.
status
shell
agent-flywheelstatus
Reports whether the host plugin is installed and current, the control-plane URL, and whether practice tasks would be claimed.
Exit codes
Code
Meaning
0
Success
1
The command failed, for example a login that was not approved
2
A configuration error, such as an unreadable PERCEPTEYE_AGENT_MODE; the message names the variable and every accepted spelling
Documentation/SDK Reference
Node SDK
Reference for @percepteye/agent-flywheel: the framework API for any JavaScript or TypeScript agent, and the plugin for OpenClaw and DeepSeek Harness. Install, frameworks, modes, configuration and on-disk formats.
Node 22.22.3 or later. Zero runtime dependencies, and TypeScript declarations included. Then get the agent's key: sign up at launch.percepteye.ai, name the agent and pick Node. The key is shown once and is scoped to that one agent.
shell
export PERCEPTEYE_API_KEY=pefw_... # from https://launch.percepteye.ai/onboard/agent-sdk
export PERCEPTEYE_AGENT_ID=support-agent # the name you gave the agent there
fw.turn(input, fn) runs your agent and returns what it returns. It records the user's message, every tool call, and the answer. A person can approve a better system prompt and model for the agent, and fn is then handed both: t.systemPrompt(yours) returns the approved prompt (or yours), and t.model is the approved endpoint (or null, so keep yours). runAgent is your agent with three lines changed:
ts
import { generateText, stepCountIs, wrapLanguageModel } from "ai";
import { createOpenAI } from "@ai-sdk/openai";
import { flywheelMiddleware, flywheelTools } from "@percepteye/agent-flywheel/ai-sdk";
import type { FlywheelTurn } from "@percepteye/agent-flywheel";
async function runAgent(t: FlywheelTurn) {
const provider = t.model
? createOpenAI({ baseURL: t.model.baseURL, apiKey: t.model.apiKey ?? undefined }).chat(t.model.model!)
: createOpenAI().chat("gpt-4.1-mini"); // your own model
const { text } = await generateText({
model: wrapLanguageModel({ model: provider, middleware: flywheelMiddleware() }),
system: t.systemPrompt("You are a support agent for Acme."), // yours, or the approved one
tools: flywheelTools(tools), // records every call
prompt: t.input,
stopWhen: stepCountIs(8),
abortSignal: t.signal,
});
return text;
}
Let it practise
The same function runs the graded tasks the control plane writes for your agent from its real tools. Run it in a separate process pointed at a test or sandbox backend, because rollouts are real runs on your real tools:
fw.serve(fn) claims one task at a time and hands it to fn as t.input. In a rollout, t.model is always set: it is the checkpoint being trained, served through that rollout's own gateway, and your agent must call it. A call that throws is reported as a failed attempt, never dropped. t.signal aborts if the control plane revokes the rollout or its deadline passes.
Important
Training takes two switches, one on each side. PERCEPTEYE_AGENT_MODE=training on this process says it may run practice tasks. Allow practice runs on the agent in Mission Control (an org admin) says the platform may send them. With either off, no practice task runs: fw.serve() refuses in production mode and names the switch.
Frameworks
Framework
What you add
Records tool outcomes
Describes the agent (prompt, tools, model)
Vercel AI SDK (ai 5, 6, 7)
flywheelTools(tools) and flywheelMiddleware() from @percepteye/agent-flywheel/ai-sdk
Neither adapter imports its framework: both are plain objects in the shapes the framework already accepts, so they add no dependency and no version pin.
LangChain.js and LangGraph.js. Create the handler inside the turn, so it is bound to that turn:
ts
import { ChatOpenAI } from "@langchain/openai";
import { createAgent } from "langchain";
import { flywheelCallbacks } from "@percepteye/agent-flywheel/langchain";
const answer = await fw.turn(message, async (t) => {
const model = t.model
? new ChatOpenAI({ model: t.model.model!, apiKey: t.model.apiKey ?? undefined,
configuration: { baseURL: t.model.baseURL } })
: new ChatOpenAI({ model: "gpt-4.1-mini" });
const agent = createAgent({ model, tools, systemPrompt: t.systemPrompt("You are a support agent for Acme.") });
const out = await agent.invoke({ messages: [{ role: "user", content: t.input }] },
{ callbacks: [flywheelCallbacks()], signal: t.signal });
return String(out.messages.at(-1)?.content ?? "");
});
Anything else. Record each tool call where it runs. Say the outcome when you know it, because only you can know that an HTTP 200 was a permission denial:
recordToolCall is a no-op outside a turn, so it can stay in code that also runs outside the flywheel. Leave outcome out and it is read from error and result: an error is failed, and a returned value is unknown, never ok.
OpenClaw and DeepSeek Harness
The same package loads as a plugin into OpenClaw and DeepSeek Harness, where the harness fires the hooks and you write no code. Both uses share one set of lanes: the framework API is a small in-process host for the same plugin.
No import, no wrapper process, no sidecar. Start your agent the way you always did. Requires OpenClaw plugin API >=2026.7.1.
Without a key, the plugin records locally and sends nothing, forever. Add a key to start contributing:
shell
exportPERCEPTEYE_API_KEY=pefw_...
# or, from the terminal:
npx@percepteye/agent-flywheellogin--agent-idmy-agent
Harness support
Harness
Records outcomes
Practice tasks
Production capture
Applies approved prompt
Applies approved model
OpenClaw
after_tool_call
Training mode
Yes
before_prompt_build
before_model_resolve + a registered provider
DeepSeek Harness
tools/result
—
—
—
—
Every recording hook is incapable of altering a run: OpenClaw's after_tool_call returns void, and dsh's tools/result is @mode emit over deep-frozen objects. Tool-result mutation seams are never used.
OpenClaw
Conversation access. Set this in your OpenClaw config:
It enables three things OpenClaw classes as conversation hooks: reading your agent's answer (agent_end), describing your agent (llm_input), and pointing it at the approved model (before_model_resolve). Without it, the plugin refuses to claim practice tasks and says which capability is missing. Applying the approved prompt does not need it; allowPromptInjection: false blocks that half from the host side.
Multiple agents on one host. Set agentId to the agent this install serves. On a host running several agents with none named, the plugin applies nothing and says so, because guessing would swap a bystander's prompt.
Practice tasks need mode: training and Allow practice runs on in Mission Control; the runner says which switch is off. They run in a dedicated percepteye-rollout-* session, never one you are using. If the host closes that seam, the plugin falls back to delivering the task into the next turn you start.
No llm_call_count. OpenClaw's llm_input / llm_output hooks bracket a whole attempt, not each provider call, so the plugin reports no count rather than guess.
DeepSeek Harness
Record-only in every mode. Outcomes are appended to $PERCEPTEYE_TRAJECTORY_DIR/tool_calls.jsonl; with that unset, nothing is written. DeepSeek Harness exposes no seam for handing a task to a running agent.
Modes
training
production (default)
Records tool outcomes locally
Yes
Yes
Claims practice tasks, starts turns
Yes
No (hooks not registered)
Captures the turns you serve
n/a
Yes; uploads once an operator enables it
Applies the approved prompt and model
No
Yes
Both halves apply only to this agent's own served turns: never a subagent, a scheduled turn, or another agent in the same gateway. See Modes and Apply the approved model and prompt.
Configuration
Scalar settings go in your OpenClaw config under plugins.entries.agent-flywheel.config, or in the environment. Config wins over the environment, except for introspect, where an opt-out from either side stands.
Config key
Environment variable
Default
What it decides
apiKey
PERCEPTEYE_API_KEY
None, then the key login stored for this agentId
The consent boundary. Without it nothing leaves the machine
mode
PERCEPTEYE_AGENT_MODE
production
Set training for practice tasks. An unreadable value degrades to production and says so
agentId
PERCEPTEYE_AGENT_ID
openclaw
The agent name reported, and whose approved pair is applied
controlPlaneUrl
PERCEPTEYE_CONTROL_PLANE_URL
https://launch.percepteye.ai/api/flywheel/v1
The control plane
capture
PERCEPTEYE_CAPTURE
On
0/false/no/off registers no hooks and records nothing
applyPrompt
PERCEPTEYE_APPLY_PROMPT
On
0 subscribes no prompt hook and does not fetch the prompt
applyModel
PERCEPTEYE_APPLY_MODEL
On
0 subscribes no model hook and registers no provider
introspect
PERCEPTEYE_INTROSPECT
On
0 registers the agent with no description (your opt-out)
retentionTurns
—
None
Keep only the most recent N captured turns on disk
describe
— (config only)
None
The agent's system_prompt, tools and model, for what the plugin cannot observe
rules
— (config only)
None
Your Product's workflow rules. Unset sends nothing; [] retracts
executionSnapshot
— (config only)
None
Adapter-owned SHA-256 execution evidence. Missing or invalid evidence abstains
Directories:
Variable
Default
Holds
PERCEPTEYE_HOME
~/.percepteye
Everything the package writes, including credentials.json
PERCEPTEYE_CAPTURE_DIR
$PERCEPTEYE_HOME/captured
Production turn capture
PERCEPTEYE_TRAJECTORY_DIR
Unset
Where a training run's outcomes are appended. Whoever runs the task sets it; the plugin only reads it
describe
OpenClaw's llm_input carries no tool list, so on its own the plugin registers an agent whose tools are unknown, and no task can be generated for it. Declare them:
json
"plugins":{"entries":{"agent-flywheel":{"config":{"describe":{"system_prompt":"You triage support tickets.","tools":[{"name":"lookup_ticket","description":"Read one ticket.","input_schema":{"type":"object","properties":{"id":{"type":"string"}}},"read_only":true}]}}}}}
tools accepts OpenAI function specs, Anthropic tools, or {name, description, input_schema, read_only}.
model is a name or {model_name, provider, temperature, max_tokens}.
What you declare wins over what was observed. It anchors no execution identity.
A bad declaration is dropped with a warning; it never stops the plugin.
It is the Python SDK's describe=, read by the same rules.
rules
json
"plugins":{"entries":{"agent-flywheel":{"config":{"rules":["Before issuing a refund, confirm the order number with the customer.","Escalate to a human when the customer asks to close their account."]}}}}
Declared once per start to POST /agents/{id}/rulebook, filed under the one Product that declares this agent, and used as training guidance. Never added to your served prompt. A refusal costs the rules and nothing else; read it as rulebookRefusal on the handle register() returns, or in the startup warning.
What it writes
One JSON object per executed tool call, appended to tool_calls.jsonl, the same format the Python SDK writes:
json
{"name":"exec","arguments":{"command":"exit 3"},"outcome":"failed","status_code":null,"error":"(Command exited with code 3)","error_class":"ToolError","latency_ms":155,"agent_name":"main","tool_call_id":"call_percepteye_1"}
The training outbox
In training mode, each result the control plane has not acknowledged sits under $PERCEPTEYE_HOME/outbox/<agentId>/. It is written before the report is sent and removed when it lands; held results are delivered before the next claim.
Suffix
Meaning
(none)
Not recorded yet; retried before every claim
.refused-lease-lost
The lease is gone (what a 410 becomes)
.refused-contract
The SDK could not carry the payload
.refused-400, -404, -409, -422
Other final statuses
.stale
Aged out after seven days; kept
A refused file is renamed, never deleted, and a warning names its path. 401, 403 and unrecognized statuses keep retrying. No credential is ever written there.
agentId defaults to openclaw. After login, restart OpenClaw: the plugin reads the stored key when the gateway starts, whenever PERCEPTEYE_API_KEY and apiKey are unset.
Package exports
Import
Contents
@percepteye/agent-flywheel
The framework API (flywheel, recordToolCall, currentTurn, ToolCallBlocked) and the plugin (register)
@percepteye/agent-flywheel/ai-sdk
Vercel AI SDK adapter (flywheelTools, flywheelMiddleware)
@percepteye/agent-flywheel/langchain
LangChain.js and LangGraph.js adapter (flywheelCallbacks)
@percepteye/agent-flywheel/customer-api
CustomerApiClient, CustomerRefusal
@percepteye/agent-flywheel/trajectory
Trajectory reader
@percepteye/agent-flywheel/classify
Outcome classification
@percepteye/agent-flywheel/dsh
DeepSeek Harness integration
@percepteye/agent-flywheel/tracing
OpenTelemetry emission (@opentelemetry/api is an optional peer dependency)
Customer API client
js
import{CustomerApiClient}from"@percepteye/agent-flywheel/customer-api";constmc=newCustomerApiClient();// mck_ key: apiKey or PERCEPTEYE_MC_API_KEYconstruns=awaitmc.listRuns({productId:"prod_123",includePromptEvolutions:true});constelig=awaitmc.trainingEligibility({agentId:"agent_123"});constsets=awaitmc.listEvalSets({productId:"prod_123",limit:20});constsec=awaitmc.getHillclimbSecurity("run_123");
A refusal throws CustomerRefusal with code, refusalMessage, customerMessage, customerWords, remediation, faultOwner, retryable. Show plainWords to a person.
Python or Node?
Node SDK
Python SDK
You have
A JavaScript or TypeScript agent, or an OpenClaw / DeepSeek Harness agent
A Python agent, or a CLI agent you launch yourself
You install
npm install @percepteye/agent-flywheel
pip install agent-flywheel
Production
fw.turn(input, fn) around each turn
attach() and a turn per answer
Training
fw.serve(fn)
serve("module:factory")
Adapters
Vercel AI SDK, LangChain.js / LangGraph.js
LangChain, LangGraph, Google ADK
The approved prompt and model
Handed to your agent as t.systemPrompt() and t.model (applied for you in a harness)
Handed back by current_prompt() and apply_current_policy()
Pick one per agent, never both.
Documentation/Advanced
Integrations
Choose the integration that fits your agent's host, from in-process SDK capture to harness plugins, local hooks and OpenTelemetry push.
Choose by integration surface
Surface
Recommended when
Boundary
Python SDK
A Python agent, or any CLI agent you launch yourself
Runs in your process. Practice tasks, production capture, approved pair handed back
Node SDK
A JavaScript or TypeScript agent
Runs in your process. Production capture with fw.turn(), practice tasks with fw.serve(), approved pair handed to your agent
Node SDK as a plugin: OpenClaw
An OpenClaw agent
Full workflow, applied for you. Needs conversation access
Node SDK as a plugin: DeepSeek Harness
A dsh agent
Records tool outcomes only
goose hook
A goose agent
Installed by agent-flywheel install-hooks. Records outcomes; claims practice tasks only with PERCEPTEYE_AGENT_MODE=training
OpenTelemetry push
An agent already exporting GenAI spans
No install. Production traffic only, no practice tasks
Agent Skill / Claude Code plugin
An operator managing training from an agent client
Server-side, approval-gated training. Uses an mck_ key
One entry-point factory in the agent_flywheel.adapters group
None
Method
Purpose
serve()
Practice tasks
attach()
Production capture
record_tool_call()
One explicit tool outcome
The zero-instrumentation claim is enforced by a test: a LangChain agent with no agent_flywheel import still reports every tool call.
Node plugin
OpenClaw: tool outcome recording, practice tasks, production capture, and applying the approved prompt and model. Conversation access must be enabled explicitly.
shell
openclawpluginsinstall@percepteye/agent-flywheel
DeepSeek Harness: records tools/result outcomes only. No practice tasks, no production capture, no prompt or model changes.
To run practice tasks for a DeepSeek Harness agent, serve it as a CLI agent through the Python SDK, with endpoint_env=("DEEPSEEK_BASE_URL", "DEEPSEEK_API_KEY"). See CLI agents.
The goose plugin records each tool call's outcome. With a key set and training mode, it also claims a practice task at SessionStart and reports the session as its result at Stop. In production it only records. Worked example.
goose and Gemini CLI hooks (standalone)
The standalone hooks package installs into goose or Gemini CLI without the Python SDK:
The hooks use only the Python standard library and write trajectory-compatible tool_calls.jsonl. Set PERCEPTEYE_TRAJECTORY_DIR to choose the output directory; without it the recorder stays inert. Local only: no upload, no practice tasks, no model or prompt changes.
Host event
Outcome
goose PostToolUse
ok
goose PostToolUseFailure
failed
Gemini CLI AfterTool with an error
failed
Gemini CLI AfterTool without an error
unknown
Failure-rate reporting excludes unknown from the denominator.
OpenTelemetry
Push GenAI spans to POST $PERCEPTEYE_CONTROL_PLANE_URL/agents/<agent_id>/otlp/v1/traces with the agent's pefw_ key. See OpenTelemetry push.
Agent Skills
Canonical Agent Skill
percepteye-agent-training lets an operator manage Mission Control training from Codex, Cursor, Gemini CLI, GitHub Copilot and VS Code, Claude, and other Agent Skills clients. It uses OpenTelemetry GenAI traces or SDK data, launches and monitors server-side training, and handles approval, results and promotion. It does not train locally, and every promotion stays approval-gated.
Claude Code marketplace plugin
A distribution wrapper for the canonical skill, not a separate SDK.
Invoke it with /percepteye:percepteye-agent-training. Requires Python >=3.9, HTTPS access to Mission Control, and an account. It uses a customer-automation key (mck_): see Authentication.
Documentation/Advanced
Configuration reference
Every environment variable the Python SDK and Node plugin read, with defaults and precedence.
Environment variables
Variable
Python
Node
Default
Meaning
PERCEPTEYE_API_KEY
✓
✓
None
The agent's pefw_ key. Without it nothing is sent
PERCEPTEYE_CONTROL_PLANE_URL
✓
✓
https://launch.percepteye.ai/api/flywheel/v1
Control-plane base URL
PERCEPTEYE_AGENT_MODE
✓
✓
production
production or training. Training is always explicit. See Modes
PERCEPTEYE_AGENT_ID
CLI only
✓
Node: openclaw
Default agent for login/logout, and the Node plugin's agent name
PERCEPTEYE_INTROSPECT
✓
✓
On
0, false, no or off disables agent discovery. A typo leaves it on
PERCEPTEYE_HOME
✓
✓
~/.percepteye
Where captured turns, the outbox and credentials.json live
PERCEPTEYE_NO_PROMPT
✓
Unset
Any value stops serve() offering to create a key in a terminal
PERCEPTEYE_MC_API_KEY
✓
✓
None
Customer-automation mck_ key for the customer API client
PERCEPTEYE_CAPTURE
✓
On
0 registers no hooks and records nothing
PERCEPTEYE_APPLY_PROMPT
✓
On
0 leaves the system prompt alone
PERCEPTEYE_APPLY_MODEL
✓
On
0 leaves the model alone
PERCEPTEYE_CAPTURE_DIR
✓
$PERCEPTEYE_HOME/captured
Production turn capture directory
PERCEPTEYE_TRAJECTORY_DIR
✓
✓
Set per task
This task's directory. Append outcomes to tool_calls.jsonl there
PERCEPTEYE_ROLLOUT_ID
Set by the SDK
This task's id, for tagging your own logs
PERCEPTEYE_TURN_INPUT
Set by the SDK
The task text, for a command entrypoint
PERCEPTEYE_TASK_ID
Set by the SDK
The id of the task this run was handed
PERCEPTEYE_HOSTED_URL
Set by the SDK
Gateway base for non-policy models inside a run
Only PERCEPTEYE_AGENT_MODE and PERCEPTEYE_INTROSPECT change the Python SDK's behavior; the rest are addresses, credentials and locations.
Precedence
Setting
Python
Node
Key
api_key= → PERCEPTEYE_API_KEY → stored key
apiKey → PERCEPTEYE_API_KEY → stored key
URL
control_plane_url= → env → default
controlPlaneUrl → env → default
Mode
mode= → env → production
mode → env → production
Introspection
introspect= AND env: either off disables
Config or env: either off disables
In Python, an unreadable mode raises. In Node, it degrades to production and says so.
The one variable the SDK writes
apply_current_policy(set_env=True) exports OPENAI_BASE_URL and OPENAI_API_KEY. It is off by default.
Files on disk
Path
Written by
Contents
$PERCEPTEYE_HOME/credentials.json
login (both SDKs)
Stored pefw_ keys, mode 0600
$PERCEPTEYE_HOME/captured/<runId>/
Node, production
Captured turns
$PERCEPTEYE_HOME/outbox/<agentId>/
Node, training
Results not yet acknowledged
<trajectory_root>/<turn_id>/
Python attach()
Captured turns
<artifacts_dir>/_percepteye/<rollout_id>/
Python serve()
Per-task working directory and trajectory
Network
Every connection is outbound HTTPS to your control-plane URL. There is no listening socket in either package, so no inbound firewall rule, DNS record or certificate is needed.
Python transport setting
Value
Exposed
Claim long-poll
25 s
No
Requested lease
30 min
No
HTTP timeout
30 s
No
Documentation/Advanced
Wire contract
The flywheel/1 schema both SDKs share, what an agent may assert, and how a practice task can be excluded.
One file is the authority
schema/flywheel-1.json is the wire contract. The Python repository owns it; the Node repository carries a copy, and tests in both hold their types to it. serve() refuses to start unless the control plane's /health lists flywheel/1 in contract_versions_supported.
Absence is never collapsed into zero
Value
Meaning
tool_calls: null
"I did not report tool calls"
tool_calls: []
"I observed zero tool calls", a positive claim
outcome: "unknown"
No verdict observed. Implies status_code: null in the schema itself
Tool call record
Field
Required
Notes
name
Yes
A call with no resolvable name is dropped, never invented
outcome
Yes
ok, failed or unknown
arguments
Object
status_code
Integer only when observed; null for unknown
output, error, error_class
Bodies over 4000 characters keep both ends, with a marker counting what was elided
latency_ms
Number
agent_name
null means unattributed
tool_call_id
The id the model assigned
entity_ids
The identity a write produced, never the body
Exclusions
A practice task can carry one exclusion reason. Excluded results are still reported, so the work product is recorded, but they are not trained on.
Reason
Meaning
flywheel_crash
The SDK's fault: an isolation child exited non-zero, returned an unparseable result, or received no payload
substrate_unavailable
Every tool call was an observed failed, and at least one was made
credential_expired
The lease lapsed mid-run and the child was stopped
deadline_exceeded
The entrypoint, child or command exceeded its budget
entrypoint_error
The Python entrypoint raised: nothing usable ran, so the work is worth retrying
agent_exit_nonzero
A command entrypoint ran and exited non-zero: a real attempt that training should see
cancelled
Control-plane vocabulary for work it withdrew. Never emitted by the SDKs
capacity
Control-plane vocabulary for work it could not place. Never emitted by the SDKs
unknown outcomes are not an exclusion; they lower the grade available.
Execution identity
When discovery exactly observes the prompt, tools, model configuration and sub-agent tree, and an execution adapter attests the rest, each task is stamped with agent_fingerprint.execution_sha256. Discovery disabled, unreadable or lossy means the field is absent, and consumers that need it refuse rather than train on an unknown agent. Your own describe= declaration never anchors an execution identity.
Control-plane endpoints the SDKs call
All relative to the control-plane URL, all opened from your side.
Method and path
Called by
Purpose
GET /health
serve()
Contract check before the first task
POST /agents
serve(), attach(), Node plugin
Register the agent and its description
POST /rollouts/claim
serve(), Node training
Long-poll for practice tasks
POST /rollouts/{id}/heartbeat
Training
Renew the lease
POST /rollouts/{id}/result
Training
Report the trajectory and answer
POST /rollouts/{id}/abandon
Training
Give back a task that crashed
GET /agents/{id}/capture
Production
May this agent upload?
POST /turns
Production
Upload captured turns, at most 64 per request
POST /agents/{id}/rulebook
When rules is set
Declare the Product's workflow rules
GET /policy/current
Production readers
The approved model
GET /prompt/current
Production readers
The approved system prompt
POST /agents/{id}/otlp/v1/traces
Your OpenTelemetry exporter
Push GenAI spans
See the Control plane API for the endpoints you might call directly.
API Reference/Endpoints
Control plane API
The control-plane endpoints you may call directly with an agent key, outside the SDKs.
Use the agent's own pefw_ key. A key bound to a different agent is refused. The full list of endpoints the SDKs use is in the Wire contract.
Register an agent
POST /agents
Registers an agent so its permissions can be switched on. The SDKs do this at startup; call it yourself only for an agent that never runs an SDK, such as one that only pushes OpenTelemetry spans.
production for a serving agent; the SDK's serve() sends rollout
discovered_agent
object or null
null records that the agent describes nothing about itself. Omitting the key is read as an opt-out of introspection
Push OpenTelemetry traces
POST /agents/{agent_id}/otlp/v1/traces
Accepts an OTLP ExportTraceServiceRequest as application/x-protobuf or application/json, optionally Content-Encoding: gzip. Both of the agent's permissions must be on.
Status
Meaning
200
ExportTraceServiceResponse; partial_success counts spans not kept and says why
400
Not an OTLP trace export
403
production_capture_not_enabled, model_content_capture_not_enabled, or a key for another agent
415
Unsupported content type or encoding
429
Organization over its rate; honor Retry-After
503
Control plane busy; honor Retry-After
507
Request too large for the host's disk; body is a google.rpc.Status
Returns the policy the agent should run. Fields the SDKs act on:
Field
Meaning
endpoint.base_url
OpenAI-compatible base URL of the approved model
endpoint.model
Model name to send
endpoint.api_key_env
The variable whose value authenticates to that endpoint
withdrawn
true when a person rolled back with nothing to serve: use your own configuration
serving_generation
Changes whenever anything to run changes
prompt_generation
Names the prompt approval being served
ttl_s
Suggested refresh interval; the SDKs never refresh faster than 30 s
Treat an empty body, a missing endpoint, or a gs://, s3:// or file:// model as "keep your current configuration".
Get the approved prompt
GET /prompt/current
Field
Meaning
name, version, text
The approved prompt
sha256
Prompt identity
candidate_kind, status
e.g. replacement, approved
model_prompt_checksum
The prompt identity stamped on the model it was certified with
stale_baseline
true when your own baseline prompt changed after certification
Apply text only when status is approved or delivered, stale_baseline is false, and sha256 matches model_prompt_checksum when both are present. This is the rule prompt_decision() and the Node plugin implement.
Declare workflow rules
POST /agents/{agent_id}/rulebook
Declares your Product's workflow rules, as rules= does. A list of prose strings; [] retracts. Refusals include 409 rulebook_unattributed (no Product, or more than one, declares the agent) and 422 rulebook_invalid (names the rule's index and the cause).
API Reference/Endpoints
Mission Control API
The customer-automation API under /api/v2 for runs, eligibility, evaluation sets, approvals and prompt deliveries.
Base URL and authentication
The API lives on the same origin as the control plane, under /api/v2:
It needs a customer-automation key (mck_), from pe login or the dashboard's Settings. An agent key (pefw_) is refused. In code, use the CustomerApiClient in Python or Node.
Refusals
A refused request returns a body with code, message, customer_message, customer_words, remediation, fault_owner and retryable. The clients raise it as CustomerRefusal; show its plain words to a person.
Health
GET /health. customer_contract_versions_supported lists the contract majors the server speaks. CustomerApiClient.supports_contract() checks it.
Runs
GET /runs
Query parameter
Notes
status
Filter by status
limit, offset
Paging. Paging past the server's depth is refused run_page_too_deep; use started_before
started_after, started_before
Time window
product_id
One Product's runs
include_background
Include background runs
include_prompt_evolutions
Each prompt evolution as one row (prompt_evolution set) in place of its arms
Each run names what it was for (target_id, target_kind, target_name), and certifies_run_id / chain_parent_run_id place it in its chain.
Training eligibility
GET /training/eligibility?agent_id=... or ?product_id=...
prompt_optimization says whether prompt runs are on and, for that agent or Product: mode (live, offline or null), can_run, needs, message, preparation_run_id, algorithms, affordable, model_under_test, and security.
Evaluation sets
GET /eval-sets?product_id=...&limit=...&offset=...
Security measurement
GET /hillclimbs/{run_id}/security. The run's security measurement; measurement.state is its state.
The response's context.completion is confirmed, or refused with the reason. Only this explicit control (or Approve in Decisions) resolves an irreversible decision. See Approvals.
Prompt deliveries
GET /prompt-deliveries lists deliveries with status: pending_approval, approved, delivered, superseded (with superseded_by), or withdrawn.
POST /prompt-deliveries/{delivery_id}/withdraw stops an approved prompt being served at once.
shell
curl-XPOST"$MC/api/v2/prompt-deliveries/$DELIVERY_ID/withdraw"\-H"Authorization: Bearer $MCK"-H"Content-Type: application/json"\-d'{"reason": "answers got too long"}'
A withdrawn prompt cannot be approved back into service; approve a newer delivery instead.
Autonomy flags
GET /autonomy/flags shows whether optimization rounds, certification and delivery assembly run automatically. Approval is never automatic.
Product rulebook
PUT /products/{product_id}/rulebook sets a Product's workflow rules, writing the same versions as the SDKs' rules=. Whichever wrote last is in force, and every write is audited.
Help Center/Help Center
Help Center
Answers, fixes and dashboard walkthroughs for Agent Flywheel.
FAQ: your data, how your agent gets better, and how to stop it.
Troubleshooting: find what you see, with the cause and the fix.
Short answers about your data, how your agent gets better, and how to use and stop Agent Flywheel.
Your data
What do you receive?
Only what you switch on. Your end users' turns cross only after an operator enables capture for that agent, which is off by default. Message text and what the model saw is a second, separate permission, also off by default. Never your tools' source code, and never your credentials. See Production capture.
What do you keep, and for how long?
What your agent sends: its turns, its traces, and the results of practice tasks. Nothing is deleted by default. After your organization's retention window (90 days unless an admin changes it), older content is also copied to an archive. An admin can ask us to delete content older than the window in Settings → Rollout retention. Each improvement round keeps the conversations it learned from and was tested on.
Your own copy on disk is yours; nothing deletes it unless you ask.
What do you do with personal data?
We scan everything we receive for email addresses, phone numbers, card numbers, US social security numbers and IP addresses. In tool-call records a match is masked. In messages, answers and what the model saw, it is kept as sent and that turn is never learned from. The SDKs mask nothing on your side.
Does my agent's code leave my machine?
No. Your agent runs where it runs today, on your credentials. Agent discovery sends its shape (system prompt, tool names, descriptions and schemas, provider and model), never your tools' source or return values. Turn it off with introspect=False or PERCEPTEYE_INTROSPECT=0.
Do I need to open a port, run a container, or provide a GPU?
No. Neither package has a listening socket, so there is no inbound firewall rule, DNS record or certificate. Training runs on PerceptEye's GPUs.
Getting better
How does my agent get better?
Mission Control learns from its real work. Each new version is tested against your agent's current best on conversations it has never seen; a version that does better comes to you in Decisions. The system prompt evolves too. See Prompt optimization.
Who decides what my users get?
You do. A new model or prompt reaches your agent only after a person approves it with an explicit approve control. A reply such as "sure, go ahead" is never read as an approval. See Approvals.
How is this different from an eval platform?
An eval platform measures. This also improves: each round produces a new version of your agent, tested against the current best, for you to approve, delivered as an endpoint your agent already knows how to call.
Using it
Do I have to change my agent?
No. LangChain, LangGraph and Google ADK calls are observed by adapters, with no Agent Flywheel code inside your agent. The OpenClaw plugin loads beside your agent. Your serving code wraps each turn in px.turn() if you use Python production capture.
What if my agent is built some other way?
If it exports OpenTelemetry GenAI traces with message content, push them. A command-line agent in any language can run practice tasks through serve() with an argv list: see CLI agents.
What does it install?
Python: one runtime dependency, httpx. Adapters import their framework only when they bind. Node: zero runtime dependencies.
How do I stop it?
Python: stop calling attach(), or pass register=False to keep capture local. serve() runs only with PERCEPTEYE_AGENT_MODE=training; unset or production, it returns at once. max_rollouts= is the clean way to end a training run.
Node:PERCEPTEYE_CAPTURE=0 registers nothing; PERCEPTEYE_APPLY_PROMPT=0 and PERCEPTEYE_APPLY_MODEL=0 stop each half of the approved pair.
Either: switch the agent's permission off in the dashboard. No restart needed.
What does unknown mean?
A tool call nobody observed succeeding or failing. It is never rounded up to ok. See Outcomes.
Python or Node?
Python for a Python agent or a command-line agent you launch yourself. Node for an OpenClaw or DeepSeek Harness agent. Never both for one agent.
What license is this under?
MIT, for both packages.
Help Center/Help Center
Troubleshooting
Find what you see. Each answer names the cause and the fix.
Python: read px.upload_refusal and px.model_content_refusal, wire serve(on_event=...), and let your logging show the agent_flywheel logger and Python warnings.
Node: read the plugin's startup line and warnings in the OpenClaw log.
The dashboard never sees your agent connect
No key in your agent's environment. Python serve() raises before the first task, naming agent-flywheel login and the sign-up page. attach() keeps running and records on disk. The Node plugin records locally and its startup line says no key is set.
The URL points somewhere else. Unset, it is the hosted control plane. agent-flywheel status prints the URL the Python SDK resolved.
Your network blocks it. Every connection is outbound HTTPS to the control-plane URL. Allow it.
The key was revoked, or is more than 180 days old. Create a new one: Agents → your agent → Get a new key.
Node: you restarted nothing after login. The plugin reads a stored key when the gateway starts.
serve() will not start
serve() checks everything before its first task and raises ConfigurationError naming the cause:
Message is about
Fix
The mode
Set PERCEPTEYE_AGENT_MODE to training or production
A missing key
export PERCEPTEYE_API_KEY=pefw_... or run agent-flywheel login
The entrypoint
Use an importable "module:attr" factory; check the method list in the error
The contract
The control plane's /health does not list flywheel/1; check the URL
A named adapter
Install its framework, or drop it from adapters=
serve() returns at once
Since 0.4.0, an unset PERCEPTEYE_AGENT_MODE means production, where serve() prints one line and returns 0. Set PERCEPTEYE_AGENT_MODE=training on the process meant to run practice tasks.
Practice tasks never arrive
Allow practice runs is off for the agent in Mission Control. serve() (Python) and the rollout runner (Node) say so at registration. An org admin turns it on on the agent's page.
practice_needs_a_training_process from Mission Control: no training process has checked in. Start one with PERCEPTEYE_AGENT_MODE=training.
serve() runs but nothing happens
Wire on_event. Without it an empty queue and a broken claim route look identical.
claim_empty repeating: the queue is empty. Generate tasks from the agent's page: Advanced → Generate tasks and run them.
claim_failed repeating: the claim route is broken, often a revoked key. The loop keeps retrying; fix the key.
delivery_brake: three results in a row were refused permanently, so claiming stopped. Check the paths named in outcome_undeliverable.
OpenClaw won't claim practice tasks
The plugin needs hooks.allowConversationAccess: true and says so once at startup. It also claims nothing unless PERCEPTEYE_AGENT_MODE=training (production is the default), when Allow practice runs is off, or when PERCEPTEYE_CAPTURE=0.
Nothing arrives in the dashboard
Nothing has been sent yet. Turns go every 32 turns and at exit. Python: px.flush() sends now.
production capture is not enabled for this agent. Turn on the agent's permission. No restart needed.
this key is bound to a different flywheel. The agent id in your code and the name the key was made for differ. Use the same id, or get a key for this agent.
this agent is not registered. Start it once with its key. Python attach() registers unless register=False.
this flywheel key does not carry the 'turn.report' scope. The key predates conversation upload. Replace it.
Conversations arrive, but there is nothing to learn from
No message text was sent. Learning needs the second permission and the model calls themselves. Python records model calls for LangChain, LangGraph and Google ADK only; for anything else, push OpenTelemetry traces.
this agent's production turns are attributed to no Product. The agent must belong to exactly one agent or Product in your dashboard.
Kept but not learned from: the turns contain personal data, or hold no final answer. Python: call px.record_answer(turn_id, text) for each turn.
flywheel_capture_has_no_decision_points. Nothing that has arrived holds a decision to learn from yet. Let more conversations arrive.
Pushed traces are refused
Status
Fix
403 production_capture_not_enabled or model_content_capture_not_enabled
Turn on both permissions
415
Send application/x-protobuf or application/json, gzip or uncompressed
400
The body is not an OTLP trace export. Upload trace files instead of pushing them
Pushes succeed, nothing to learn from
The spans carry no message content. Switch it on in your instrumentation
Requests fail with 429
Your organization is over a rate limit. The SDKs wait and retry. If it persists, send fewer, larger requests; give a Collector's exporter a batch processor and sending_queue: num_consumers: 1.
Your agent is not running the approved version
Not approved yet, or not serving yet. Approve in Decisions.
Python apply_current_policy() returned {}. It logs why on the agent_flywheel logger: nothing approved, no key, unreachable control plane, or a stored-file address (gs://, s3://, file://).
Python policy_source() still serves the old model. It refreshes about every five minutes. snap.stale_for_s > 0 means refreshes are failing.
The prompt did not change. Python never applies a prompt for you: fw.prompt_decision(...).reason says why it may not be applied. Node logs a reason for each half it did not apply.
Node: only one half applied. The startup pair check names which half is missing and why. The model half needs allowConversationAccess and a host that accepts the percepteye-flywheel provider.
Node: the model did not change after approval. The model is read once at startup. Restart to pick up a new one.
Help Center/Help Center
In the dashboard
Every Mission Control click path the docs mention, in one place.
Create a workspace
An email, a password and a six-digit code that confirms the address.
Get your key
New mission → Your AI agent → under How should we get your agent's conversations?, choose Add our SDK to your agent's code → name the agent → Create agent and get my key.
The name is the agent id your code reports. The pefw_ key is shown once and belongs to that one agent. Copy it into your agent's environment as PERCEPTEYE_API_KEY. The status panel shows when the agent's first call arrives, then asks for permission and offers Start improving.
Only an organization admin can create an agent and its key. A key expires after 180 days.
Replace a lost key
Agents → your agent → Get a new key. The old key keeps working until it expires or you revoke it: Settings → Agent keys → Revoke.
Send us its OpenTelemetry traces
New mission → Your AI agent → Also send us the traces your agent already exports → name the agent → Create agent and get my key. Then choose I run an OpenTelemetry Collector or My agent exports directly and copy what it shows, including the agent's endpoint.
Connect your observability provider
New mission → Your AI agent → Connect your observability provider. We read your agent's traces from the provider they already go to; nothing changes in your agent.
Upload a trace file
New mission → Your AI agent → Upload a trace file: an OpenTelemetry export of your agent's traces.
Allow us to learn from its conversations
During setup, one checkbox: Let us learn from its conversations, including the message text. It switches on two permissions, shown separately on the agent's page:
Send us its conversations: the steps of each conversation, which tools were called, what the agent decided.
Include the message text: the words of each message, and what the model saw.
Learning needs both. Switch them off at any time on the agent's page; your agent notices without a restart. Only an organization admin can change them.
See what arrived
Your agent's page → Agent tab → What it has sent us to learn from: turns sent by the SDK and spans pushed over OpenTelemetry, and how many of each are kept but not learned from, and why.
Start improving
Start improving, at the end of setup or on your agent's page. It needs the permission on. If the round is paid from your credits, it shows the most it can cost before it starts.
Run practice tasks
Your agent's page → Advanced → Generate tasks and run them, or Generate, run and improve. Tasks are written from your agent's own tools and system prompt. Your agent works through them while a process runs with PERCEPTEYE_AGENT_MODE=training, which you set explicitly.
Allow practice runs
Your agent's page → Allow practice runs. The platform sends practice tasks only while this is on, and only to a process running in training mode. Only an organization admin can change it.
Approve the winner in Decisions
Decisions, in the sidebar. A new version arrives only after it has beaten your agent's current best on conversations it has never seen. Approve or reject; nothing else decides.
Try a new version on one agent
Your agent's page → Agent tab → Try the candidate. Move back to champion undoes it.
Withdraw an approved prompt
Prompts → the prompt → Versions of this prompt → Withdraw.
Choose what we keep
Settings → Rollout retention. Off, the default, deletes nothing. On asks us to delete content older than the number of days you set. Only an organization admin can change it.
Changelog/Release History
Changelog
What changed in Agent Flywheel, by release. The Python SDK and the Node SDK ship the same version number in the same release.
0.5.0
Added
The Node SDK works with any JavaScript or TypeScript agent.npm install @percepteye/agent-flywheel, then flywheel(), fw.turn() around each turn you serve and fw.serve() for practice tasks, with adapters for the Vercel AI SDK (@percepteye/agent-flywheel/ai-sdk) and LangChain.js / LangGraph.js (@percepteye/agent-flywheel/langchain), and recordToolCall() for anything else. The OpenClaw and DeepSeek Harness plugin is unchanged. See Node SDK.
A customer can report how a turn or a conversation actually turned out:report_outcome() (Python) and reportOutcome() (Node), with resolved, escalated, reopened, abandoned, thumbs_up or thumbs_down. Outcomes wait on disk and are uploaded with the turns.
An outcome can name the episode it is the outcome of, and one turn of an episode can be given feedback. Both SDKs, same wire.
A rollout's report can say what the agent's own environment checked, how the episode ended and which seeds it ran under.
Requires
Mission Control must serve POST /api/flywheel/v1/outcomes. Against an older server, reported outcomes stay queued and are retried for up to a week.
0.4.0
Changed
An unset PERCEPTEYE_AGENT_MODE now means production; training is an explicit choice.serve() with no mode set prints its production line and returns without opening a connection. Set PERCEPTEYE_AGENT_MODE=training on the process meant to run practice tasks. Both SDKs, same default. Upgrading: add the variable to every training deployment.
Practice takes two switches, and the SDK names the one that is off. When the agent's Allow practice runs switch in Mission Control is off, serve() (Python) and the rollout runner (Node) say so at registration. Mission Control refuses a practice round with practice_needs_a_training_process when no training process has checked in.
Added
An environment-backed agent knows the task it was handed:current_task_id() and PERCEPTEYE_TASK_ID. A rollout's tool spans carry that task id in both SDKs.
A rollout can reach non-policy models:hosted_model_url(provider) and PERCEPTEYE_HOSTED_URL, for a user simulator, a judge or an embedding model. For OpenAI-compatible providers the URL is an OpenAI client's base as is.
A command agent reports its own grade by writing $PERCEPTEYE_TRAJECTORY_DIR/outcome.json.
0.3.0
Added
Get a key without leaving the terminal.agent-flywheel login --agent-id X and npx @percepteye/agent-flywheel login start a device login, print a short code, open launch.percepteye.ai, and store the approved pefw_ key in $PERCEPTEYE_HOME/credentials.json (0600), a file both SDKs share. logout forgets it. Resolution order: explicit key, then PERCEPTEYE_API_KEY, then the stored key.
serve() offers a key in a terminal. With no key and a person at the terminal, it asks Create one now (free)? [Y/n]. Never in CI, with PERCEPTEYE_NO_PROMPT=1, or without a terminal.
No pefw_ key in any request body. Both SDKs replace one they find with pefw_[REDACTED].
Changed
Every missing-key refusal says where a key comes from, naming agent-flywheel login and the sign-up page.
0.2.0
Added
The control-plane URL has a default:https://launch.percepteye.ai/api/flywheel/v1. The key is the one thing that can be missing.
What the model saw, under its own consent tier. With the model-content permission, the LangChain and Google ADK adapters observe each model call inside an attach() turn and upload it as one OpenTelemetry GenAI trace (genai_trace). Off by default; without the grant nothing is recorded, not even to disk.
rules= on serve() and attach() declares the Product's workflow rules once after registration. None sends nothing; [] retracts.
A withdrawn model is given back. When a person rolls an agent back with nothing to serve, the control plane answers withdrawn: true and policy_source() reverts to your own configuration, firing on_change. Upgrading: check snap.withdrawn in an on_change callback before building a client.
Changed
The goose hook claims practice tasks only in training mode.
attach(retention_turns=...) refuses a value that is not a whole number 0 or more.
Your flywheel key opens only the control plane's own gateway. A pefw_ key goes to an endpoint only when the control plane names PERCEPTEYE_API_KEY for it and it sits at your control plane's origin. endpoint_kwargs() gains flywheel_key= and control_plane_url=. Upgrading: an agent pointed at a self-hosted endpoint without the gateway projection keeps its own configuration.
A policy_source() refresh that cannot reach the control plane is a failed refresh:last_refresh_ok goes False and stale_for_s grows while the last good snapshot stands.
Bounded tool and error bodies keep both ends, 4000 characters each, with a marker counting what was elided.
Artifacts travel only in the rollout report.
A rollout's outcome is never lost: every terminal path reports, and model calls are bounded by a ceiling derived from the episode budget.
A per-process socket no longer changes the agent's execution identity (volatile_command_values).
The Prime adapter seals its kernel against the serving shell's Python environment.
0.1.2, 0.1.1, 0.1.0
First releases. agent-flywheel 0.1.0 was published to PyPI on 2026-09-14. See the v0.1.0 to v0.1.2 tags.