agent-control-panel 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. agent_control_panel-0.1.0/.gitignore +9 -0
  2. agent_control_panel-0.1.0/CHANGELOG.md +32 -0
  3. agent_control_panel-0.1.0/LICENSE +202 -0
  4. agent_control_panel-0.1.0/PKG-INFO +245 -0
  5. agent_control_panel-0.1.0/README.md +219 -0
  6. agent_control_panel-0.1.0/SECURITY.md +24 -0
  7. agent_control_panel-0.1.0/pyproject.toml +83 -0
  8. agent_control_panel-0.1.0/src/agent_control_panel/__init__.py +102 -0
  9. agent_control_panel-0.1.0/src/agent_control_panel/_content.py +138 -0
  10. agent_control_panel-0.1.0/src/agent_control_panel/_control.py +202 -0
  11. agent_control_panel-0.1.0/src/agent_control_panel/_http.py +99 -0
  12. agent_control_panel-0.1.0/src/agent_control_panel/_lifecycle.py +131 -0
  13. agent_control_panel-0.1.0/src/agent_control_panel/_reporter.py +182 -0
  14. agent_control_panel-0.1.0/src/agent_control_panel/_transport.py +86 -0
  15. agent_control_panel-0.1.0/src/agent_control_panel/_version.py +1 -0
  16. agent_control_panel-0.1.0/src/agent_control_panel/_webhook.py +62 -0
  17. agent_control_panel-0.1.0/src/agent_control_panel/client.py +328 -0
  18. agent_control_panel-0.1.0/src/agent_control_panel/errors.py +16 -0
  19. agent_control_panel-0.1.0/src/agent_control_panel/py.typed +0 -0
  20. agent_control_panel-0.1.0/src/agent_control_panel/signature.py +168 -0
  21. agent_control_panel-0.1.0/src/agent_control_panel/tokens.py +115 -0
  22. agent_control_panel-0.1.0/tests/__init__.py +0 -0
  23. agent_control_panel-0.1.0/tests/conftest.py +69 -0
  24. agent_control_panel-0.1.0/tests/contract/vectors.json +1861 -0
  25. agent_control_panel-0.1.0/tests/e2e/__init__.py +0 -0
  26. agent_control_panel-0.1.0/tests/e2e/agent.py +83 -0
  27. agent_control_panel-0.1.0/tests/test_client_options.py +104 -0
  28. agent_control_panel-0.1.0/tests/test_content.py +139 -0
  29. agent_control_panel-0.1.0/tests/test_contract.py +157 -0
  30. agent_control_panel-0.1.0/tests/test_heartbeat_and_control.py +257 -0
  31. agent_control_panel-0.1.0/tests/test_prompt_and_redirects.py +192 -0
  32. agent_control_panel-0.1.0/tests/test_reporting.py +233 -0
  33. agent_control_panel-0.1.0/tests/test_threads_and_exit.py +172 -0
  34. agent_control_panel-0.1.0/tests/test_tokens.py +72 -0
  35. agent_control_panel-0.1.0/tests/test_webhook.py +111 -0
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv*/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .mypy_cache/
8
+ .pytest_cache/
9
+ .ruff_cache/
@@ -0,0 +1,32 @@
1
+ # Changelog
2
+
3
+ All notable changes to the Python SDK. Versions stay `0.x` until the wire contract is proven with real
4
+ customers; after the first public release, contract changes are additive only (clients live inside customer
5
+ apps). The wire contract is the same as the Node SDK (`agent-control-panel` on npm).
6
+
7
+ ## 0.1.0 (2026-09-29)
8
+
9
+ First release, with the same behaviour and wire contract as the Node SDK 0.3.0:
10
+
11
+ - `create_client(...)` with the same validation: `https` only (plain `http` for loopback hosts, or with
12
+ `allow_insecure_http=True` for local development), credentials trimmed, refuses to start without a
13
+ webhook secret, `ACP_DISABLE_CONTROL=1` honoured.
14
+ - Fail-open reporting: `report_run` buffers and never raises; batched flushes with retry and jitter; the
15
+ oldest runs are dropped past `max_buffer`. Heartbeats and flushes run on daemon threads; pending runs are
16
+ flushed on interpreter exit.
17
+ - `wrap_agent_run` / `wrap_agent_run_async`: refuse to run while paused or stopped (`AgentPausedError`),
18
+ report tokens and the answer text (`extract_text`: OpenAI Chat and Responses, Anthropic, Gemini, `text`;
19
+ reads keys and attributes only, never calls methods), accept `user_input` and `full_input`, and re-raise
20
+ your exception unchanged.
21
+ - Run content: full fields are sent as JSON text cut to 100,000 characters (counted in UTF-16 units, as ACP
22
+ does) and flagged `full_input_truncated` / `full_output_truncated`; large flushes are split into requests
23
+ under 4 MB. `capture_content=False` sends metadata only, from `wrap_agent_run` and `report_run` alike.
24
+ - Remote control: `handle_webhook` / `webhook_response` verify signature v2 (timestamp + nonce, 300 s skew,
25
+ single-use nonces, previous secret during rotation) and apply pause, resume, stop, restart,
26
+ `update_model` and `update_prompt`. Durable pause and model swaps through the heartbeat reply, with the
27
+ same rules: a hold set locally is never released by ACP, and replies older than the last applied command
28
+ are ignored.
29
+ - `fetch_prompt()` with a 60 s cache and fallback to the last prompt.
30
+ - Zero runtime dependencies; typed (`py.typed`); Python 3.10+.
31
+ - Redirects are never followed (the API key is never sent to another host); a 3xx is logged with its target
32
+ so you know which URL to update.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,245 @@
1
+ Metadata-Version: 2.5
2
+ Name: agent-control-panel
3
+ Version: 0.1.0
4
+ Summary: Agent Control Panel SDK for Python: fail-open reporting and remote control for AI agents
5
+ Project-URL: Homepage, https://github.com/Saadtamari/agent-control-panel-python#readme
6
+ Project-URL: Source, https://github.com/Saadtamari/agent-control-panel-python
7
+ Project-URL: Issues, https://github.com/Saadtamari/agent-control-panel-python/issues
8
+ Project-URL: Changelog, https://github.com/Saadtamari/agent-control-panel-python/blob/main/CHANGELOG.md
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: agents,ai,anthropic,control-plane,llm,observability,openai
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+
27
+ # Agent Control Panel SDK for Python
28
+
29
+ Connect an AI agent that already runs in your app to [Agent Control Panel](https://acp.skaigroup.tech)
30
+ (ACP): report every run (tokens, model, latency, errors, the answer) and let your team **pause, resume, stop,
31
+ restart, swap the model or push an approved prompt** without redeploying.
32
+
33
+ - **Fail-open.** If ACP is slow or down, your agent keeps working. Reporting is buffered and retried on a
34
+ background thread; nothing the SDK does raises into your code (except `AgentPausedError`, on purpose).
35
+ - **Signed control.** Commands are HMAC-SHA256 signed with a timestamp and a single-use nonce; unsigned,
36
+ replayed, stale or wrong-agent commands are rejected.
37
+ - **Durable pause and model swaps.** A pause or a model swap set in ACP survives restarts, extra workers and
38
+ missed webhooks: every heartbeat reply carries the state ACP holds, and the client adopts it.
39
+ - **Zero runtime dependencies.** Python 3.10+, standard library only, fully typed (`py.typed`).
40
+
41
+ Same behaviour and wire contract as the Node SDK (`agent-control-panel` on npm); both are tested against
42
+ the same contract vectors.
43
+
44
+ ```bash
45
+ pip install agent-control-panel
46
+ ```
47
+
48
+ ## Quickstart
49
+
50
+ ```python
51
+ import os
52
+ from agent_control_panel import AgentPausedError, create_client
53
+
54
+ acp = create_client(
55
+ url=os.environ["ACP_URL"], # your control panel URL
56
+ api_key=os.environ["ACP_API_KEY"], # shown once when the key is created
57
+ agent_id=os.environ["ACP_AGENT_ID"], # from the app page in ACP
58
+ webhook_secret=os.environ["ACP_WEBHOOK_SECRET"],
59
+ )
60
+ acp.start() # heartbeats every 30 s, flushes every 5 s, on daemon threads
61
+
62
+ def handle(question: str) -> str:
63
+ try:
64
+ return acp.wrap_agent_run(
65
+ lambda: my_agent(question, system_prompt=acp.fetch_prompt() or DEFAULT_PROMPT),
66
+ user_input=question,
67
+ model_used=acp.get_effective_model("gpt-4o-mini"),
68
+ )
69
+ except AgentPausedError:
70
+ return "This assistant is paused. Please try again later."
71
+ ```
72
+
73
+ `wrap_agent_run` records duration, success or error, token usage and the answer text, read from the
74
+ response objects of the OpenAI, Anthropic and Google Gemini SDKs (and plain dicts of the same shape). For
75
+ anything else, return a string or call `report_run(...)` yourself. While the agent is paused or stopped it
76
+ raises `AgentPausedError` **without calling your function**, so a pause really stops model calls.
77
+
78
+ ACP's quality reviews, Test Lab and error explanations read the user input, the full input and the output,
79
+ so pass `user_input` and `full_input` for accurate results (each field is kept up to 100,000 characters). To
80
+ send metadata only, create the client with `capture_content=False`.
81
+
82
+ ### OpenAI
83
+
84
+ ```python
85
+ from openai import OpenAI
86
+
87
+ openai = OpenAI()
88
+
89
+ def answer(question: str) -> str:
90
+ model = acp.get_effective_model("gpt-4o-mini")
91
+ messages = [
92
+ {"role": "system", "content": acp.fetch_prompt() or "You are a helpful assistant."},
93
+ {"role": "user", "content": question},
94
+ ]
95
+ completion = acp.wrap_agent_run(
96
+ lambda: openai.chat.completions.create(model=model, messages=messages),
97
+ user_input=question,
98
+ full_input=messages,
99
+ model_used=model,
100
+ )
101
+ return completion.choices[0].message.content or ""
102
+ ```
103
+
104
+ ### Anthropic (async)
105
+
106
+ ```python
107
+ import asyncio
108
+ from anthropic import AsyncAnthropic
109
+
110
+ claude = AsyncAnthropic()
111
+
112
+ async def answer(question: str) -> str:
113
+ model = acp.get_effective_model("claude-sonnet-4-5")
114
+ system = await asyncio.to_thread(acp.fetch_prompt) # fetch_prompt blocks up to 5 s
115
+ messages = [{"role": "user", "content": question}]
116
+ message = await acp.wrap_agent_run_async(
117
+ lambda: claude.messages.create(model=model, max_tokens=1024, system=system, messages=messages),
118
+ user_input=question,
119
+ full_input=messages,
120
+ model_used=model,
121
+ )
122
+ return "".join(block.text for block in message.content if block.type == "text")
123
+ ```
124
+
125
+ Anthropic prompt-cache tokens are counted as input tokens.
126
+
127
+ ## Receive control commands
128
+
129
+ ACP sends signed commands to `<Deployed URL>/api/acp/webhook` (set the Deployed URL on the app page).
130
+ Pass the **raw request body** (bytes), not re-serialised JSON: the signature covers the exact bytes.
131
+ `webhook_response` returns the HTTP status (200 applied, 409 for another agent's command, 401 otherwise) and
132
+ a JSON body.
133
+
134
+ **FastAPI**
135
+
136
+ ```python
137
+ from fastapi import FastAPI, Request
138
+ from fastapi.responses import JSONResponse
139
+
140
+ app = FastAPI()
141
+
142
+ @app.post("/api/acp/webhook")
143
+ async def acp_webhook(request: Request) -> JSONResponse:
144
+ status, body = acp.webhook_response(request.headers, await request.body())
145
+ return JSONResponse(body, status_code=status)
146
+ ```
147
+
148
+ **Flask**
149
+
150
+ ```python
151
+ from flask import Flask, jsonify, request
152
+
153
+ app = Flask(__name__)
154
+
155
+ @app.post("/api/acp/webhook")
156
+ def acp_webhook():
157
+ status, body = acp.webhook_response(request.headers, request.get_data())
158
+ return jsonify(body), status
159
+ ```
160
+
161
+ **Django**
162
+
163
+ ```python
164
+ from django.http import JsonResponse
165
+ from django.views.decorators.csrf import csrf_exempt
166
+ from django.views.decorators.http import require_POST
167
+
168
+ @csrf_exempt # ACP requests are authenticated by their HMAC signature, not a CSRF token
169
+ @require_POST
170
+ def acp_webhook(request):
171
+ status, body = acp.webhook_response(request.headers, request.body)
172
+ return JsonResponse(body, status=status)
173
+ ```
174
+
175
+ No public URL (local development, a worker, a cron job)? Control still works: pause, stop, resume and model
176
+ swaps arrive with the next heartbeat (within 30 s), and prompt changes are fetched before each run.
177
+
178
+ ## API
179
+
180
+ | Member | What it does |
181
+ |---|---|
182
+ | `create_client(...)` | `url`, `api_key`, `agent_id`, `webhook_secret` (required); `webhook_secret_prev` during rotation; `heartbeat_seconds` (30), `flush_seconds` (5), `flush_at` (50), `max_buffer` (200); `logger`; `disable_control`; `capture_content` (default `True`; `False` = metadata only); `allow_insecure_http` (development only); `transport` (for tests). `url` must be https (or http to localhost). Raises `ValueError` for a missing credential or an insecure URL. |
183
+ | `start()` / `stop(timeout=10)` | Start heartbeats and background flushing / flush everything and stop, giving up after `timeout`. The threads never keep your process alive; pending runs are flushed at interpreter exit. `with create_client(...) as acp:` does both. |
184
+ | `wrap_agent_run(fn, *, user_input, full_input, input_summary, model_used)` | Run `fn()`, report it (with the answer text from the result), re-raise its exception unchanged. Raises `AgentPausedError` while paused or stopped. |
185
+ | `wrap_agent_run_async(fn, ...)` | The same for coroutines: `await acp.wrap_agent_run_async(lambda: client.create(...))`. |
186
+ | `report_run(status, **fields)` | Report a run yourself (tokens, model, timings, summaries, `user_input`, `full_input`, `full_output`, `error_message`, `trigger`, optional `dedupe_key`). Buffered; never raises. |
187
+ | `extract_text(result)` / `extract_tokens(result)` | The answer text / token counts of an OpenAI, Anthropic or Gemini response, or `None`. |
188
+ | `fetch_prompt()` | The agent's current prompt from ACP (composed with its skills), cached 60 s; falls back to the last prompt on any error. |
189
+ | `get_effective_model(fallback)` | The model ACP asked for (after a model swap), else `fallback`. |
190
+ | `status` | `idle`, `running`, `paused` or `stopped`. |
191
+ | `handle_webhook(headers, raw_body)` / `webhook_response(...)` | Verify and apply a signed command / the same as an HTTP status and JSON body. |
192
+ | `apply_command(command, payload=None)` | Apply a command locally (e.g. your own kill switch). A pause set this way is never lifted by ACP. |
193
+
194
+ ## Security
195
+
196
+ - Never commit `ACP_API_KEY` or `ACP_WEBHOOK_SECRET`; keep them in your platform's secrets.
197
+ - `ACP_DISABLE_CONTROL=1` (or `disable_control=True`) ignores every control command while reporting keeps
198
+ working: a local kill switch that does not depend on ACP.
199
+ - Rotate the webhook secret in ACP, then set the old one as `webhook_secret_prev` until every instance has
200
+ the new one.
201
+ - Commands are accepted only within 5 minutes of their timestamp and only once (nonce cache, safe across
202
+ threads).
203
+ - Run content (user input, full input, the answer) is sent to ACP by default, cut to 100,000 characters per
204
+ field. Leave out anything you must not share, or use `capture_content=False` for metadata only.
205
+ - Redirects are never followed: requests carry the API key, so a redirect is logged with where ACP moved
206
+ ("ACP moved to ...; update your url") and the request fails open.
207
+ - TLS certificates are verified with the system's default trust store.
208
+
209
+ ## Troubleshooting
210
+
211
+ | Log line | Meaning | Fix |
212
+ |---|---|---|
213
+ | `-> 401: ACP rejected the API key` | The key is wrong, revoked or expired. | Rotate the key on the app page, copy the full key from the dialog, set `ACP_API_KEY`. |
214
+ | `ACP moved to https://...; update your url` | ACP answered with a redirect. | Set `ACP_URL` to the address in the message. |
215
+ | `reason: bad_signature` in the webhook answer | `ACP_WEBHOOK_SECRET` differs from the app's secret in ACP, or the body was re-serialised before verification. | Reveal the secret on the app page and set it again; pass the raw body. |
216
+ | `control rejected: command for agent ... reached agent ...` | Several agents share one webhook URL but this client is configured for another agent. | One client (and `agent_id`) per agent. |
217
+ | `CERTIFICATE_VERIFY_FAILED` | Python cannot find root certificates (common with python.org installers on macOS). | Run "Install Certificates.command" from the Python folder, or install your OS's CA bundle. |
218
+
219
+ Warnings are logged to the `agent_control_panel` logger and reach stderr unless you configure logging.
220
+
221
+ **Forking servers (gunicorn with `--preload`, multiprocessing).** Threads do not survive `fork()`. The SDK
222
+ resets itself in the child and restarts its threads on the next report, and runs buffered before the fork
223
+ stay with the parent. Creating the client in each worker (e.g. gunicorn's `post_fork` hook) is simplest.
224
+
225
+ **Serverless and short scripts.** Call `acp.stop()` (or use `with create_client(...) as acp:`) before the
226
+ function returns so buffered runs are sent; frozen containers do not run exit hooks.
227
+
228
+ ## Development
229
+
230
+ ```bash
231
+ python -m venv .venv && . .venv/bin/activate
232
+ pip install --require-hashes -r requirements-dev.txt
233
+ ruff check src tests && ruff format --check src tests && mypy && pytest
234
+ python -m build
235
+ ```
236
+
237
+ The SDK is developed in the Agent Control Panel repository, next to the server it talks to, so contract
238
+ changes are tested on both sides together (`tests/contract/vectors.json` is generated there). This public
239
+ repository receives one commit per release. Issues and pull requests are welcome here; accepted changes are
240
+ applied upstream and ship in the next release.
241
+
242
+ ## License
243
+
244
+ [Apache License 2.0](LICENSE). It includes an explicit patent grant from contributors, and ends that grant
245
+ for anyone who sues over patents in the SDK.