backloop-sdk 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.
@@ -0,0 +1,8 @@
1
+ node_modules/
2
+ dist/
3
+ data/
4
+ __pycache__/
5
+ *.egg-info/
6
+ .venv/
7
+ .env
8
+ .DS_Store
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.5
2
+ Name: backloop-sdk
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Agent Feedback Protocol: validate, send and receive structured feedback from AI agents.
5
+ Project-URL: Homepage, https://trybackloop.com
6
+ Project-URL: Specification, https://trybackloop.com/spec/
7
+ Project-URL: Repository, https://github.com/guimsh/agent-feedback-protocol
8
+ Project-URL: Issues, https://github.com/guimsh/agent-feedback-protocol/issues
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: agent-feedback-protocol,ai-agents,api,feedback,llm,mcp
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Topic :: Software Development :: Libraries
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.9
19
+ Provides-Extra: fastapi
20
+ Requires-Dist: fastapi>=0.100; extra == 'fastapi'
21
+ Provides-Extra: flask
22
+ Requires-Dist: flask>=2.0; extra == 'flask'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # backloop-sdk
26
+
27
+ Python SDK for the [Agent Feedback Protocol](https://trybackloop.com/spec/): AI agents `POST` structured feedback to `/feedback` on the services they use, so those services learn what agents were trying to do when they got stuck.
28
+
29
+ - Standard library only (Python 3.9+). Optional FastAPI and Flask helpers.
30
+ - Validates against the protocol's [JSON Schemas](https://github.com/guimsh/agent-feedback-protocol/tree/main/spec).
31
+ - Mirrors the TypeScript SDK (`@backloop/sdk`): same validation messages, error codes and redaction.
32
+
33
+ ```sh
34
+ pip install backloop-sdk # import backloop
35
+ pip install "backloop-sdk[fastapi]" # or [flask]
36
+ ```
37
+
38
+ ## Agents: send feedback
39
+
40
+ ```python
41
+ from backloop import FeedbackClient
42
+
43
+ client = FeedbackClient("https://api.example.com", api_key=API_KEY, session_id="task_42")
44
+
45
+ result = client.try_submit({ # never raises: feedback must not break the task
46
+ "type": "missing_capability",
47
+ "goal": "Find companies currently hiring GTM engineers",
48
+ "endpoint": "/companies/search",
49
+ "method": "GET",
50
+ "message": "No hiring-role filter is available",
51
+ "outcome": "blocked",
52
+ "suggestion": "Add a hiring_role query parameter",
53
+ })
54
+ if result.ok and "known_issue" in result.ack:
55
+ print("Already tracked:", result.ack["known_issue"]["title"])
56
+ ```
57
+
58
+ `submit()` does the same but raises `FeedbackError(message, code, status, details)`. Both redact secrets, card numbers and emails before sending, and retry once on `429`/`5xx`. Use `FeedbackClient.from_discovery(base_url)` to find the endpoint through `/.well-known/agent-feedback`, or `feedback_url_from_link(response.headers["link"], url)` to read it from an error response.
59
+
60
+ Give your agent the tool and the instructions:
61
+
62
+ ```python
63
+ from backloop import AGENT_FEEDBACK_INSTRUCTIONS, feedback_tool
64
+
65
+ tools = [feedback_tool()] # {"name": "submit_feedback", "description", "input_schema"}
66
+ # When the model calls it: client.try_submit(tool_use.input)
67
+ ```
68
+
69
+ ## Services: receive feedback
70
+
71
+ ```python
72
+ from backloop import FeedbackHandler, forward_to, hash_account
73
+
74
+ handler = FeedbackHandler(
75
+ on_record=forward_to("https://collector.example.com", ingest_key=INGEST_KEY), # or your own callable
76
+ service="acme-companies-api",
77
+ identify=lambda request: hash_account(current_account_id(request), SECRET) if authenticated(request) else None,
78
+ )
79
+ ```
80
+
81
+ FastAPI or Flask:
82
+
83
+ ```python
84
+ from backloop import fastapi_router, flask_blueprint
85
+
86
+ app.include_router(fastapi_router(handler)) # FastAPI
87
+ app.register_blueprint(flask_blueprint(handler)) # Flask
88
+ ```
89
+
90
+ Both serve `POST /feedback` and `GET /.well-known/agent-feedback`. Any other framework calls the handler directly:
91
+
92
+ ```python
93
+ status, body, headers = handler.handle_submit(raw_body, content_type, account, client_ip)
94
+ document = handler.discovery("https://api.example.com")
95
+ ```
96
+
97
+ `on_record(record)` stores or forwards each accepted record. Return `{"known_issue": {...}}` to pass a tracked issue back to the agent. If it raises, the agent gets `503`. Add `feedback_link_header()` as a `Link` header on your API's error responses so agents find the endpoint.
98
+
99
+ ## Utilities
100
+
101
+ ```python
102
+ from backloop import validate_submission, format_issues, redact
103
+
104
+ result = validate_submission(payload)
105
+ if not result.valid:
106
+ print(format_issues(result.issues)) # "goal: is required; type: must be one of: ..."
107
+
108
+ redact({"note": "auth failed with Bearer 9f8e7d6c5b4a", "password": "hunter2"})
109
+ # {"note": "auth failed with [REDACTED]", "password": "[REDACTED]"}
110
+ ```
111
+
112
+ ## Development
113
+
114
+ ```sh
115
+ python3 -m unittest discover -s tests -t .
116
+ ```
117
+
118
+ The tests run the shared conformance suite in `spec/conformance`. `src/backloop/_generated.py` is generated from `spec/` by `scripts/sync-schema.mjs`; don't edit it by hand.
119
+
120
+ License: Apache-2.0
@@ -0,0 +1,96 @@
1
+ # backloop-sdk
2
+
3
+ Python SDK for the [Agent Feedback Protocol](https://trybackloop.com/spec/): AI agents `POST` structured feedback to `/feedback` on the services they use, so those services learn what agents were trying to do when they got stuck.
4
+
5
+ - Standard library only (Python 3.9+). Optional FastAPI and Flask helpers.
6
+ - Validates against the protocol's [JSON Schemas](https://github.com/guimsh/agent-feedback-protocol/tree/main/spec).
7
+ - Mirrors the TypeScript SDK (`@backloop/sdk`): same validation messages, error codes and redaction.
8
+
9
+ ```sh
10
+ pip install backloop-sdk # import backloop
11
+ pip install "backloop-sdk[fastapi]" # or [flask]
12
+ ```
13
+
14
+ ## Agents: send feedback
15
+
16
+ ```python
17
+ from backloop import FeedbackClient
18
+
19
+ client = FeedbackClient("https://api.example.com", api_key=API_KEY, session_id="task_42")
20
+
21
+ result = client.try_submit({ # never raises: feedback must not break the task
22
+ "type": "missing_capability",
23
+ "goal": "Find companies currently hiring GTM engineers",
24
+ "endpoint": "/companies/search",
25
+ "method": "GET",
26
+ "message": "No hiring-role filter is available",
27
+ "outcome": "blocked",
28
+ "suggestion": "Add a hiring_role query parameter",
29
+ })
30
+ if result.ok and "known_issue" in result.ack:
31
+ print("Already tracked:", result.ack["known_issue"]["title"])
32
+ ```
33
+
34
+ `submit()` does the same but raises `FeedbackError(message, code, status, details)`. Both redact secrets, card numbers and emails before sending, and retry once on `429`/`5xx`. Use `FeedbackClient.from_discovery(base_url)` to find the endpoint through `/.well-known/agent-feedback`, or `feedback_url_from_link(response.headers["link"], url)` to read it from an error response.
35
+
36
+ Give your agent the tool and the instructions:
37
+
38
+ ```python
39
+ from backloop import AGENT_FEEDBACK_INSTRUCTIONS, feedback_tool
40
+
41
+ tools = [feedback_tool()] # {"name": "submit_feedback", "description", "input_schema"}
42
+ # When the model calls it: client.try_submit(tool_use.input)
43
+ ```
44
+
45
+ ## Services: receive feedback
46
+
47
+ ```python
48
+ from backloop import FeedbackHandler, forward_to, hash_account
49
+
50
+ handler = FeedbackHandler(
51
+ on_record=forward_to("https://collector.example.com", ingest_key=INGEST_KEY), # or your own callable
52
+ service="acme-companies-api",
53
+ identify=lambda request: hash_account(current_account_id(request), SECRET) if authenticated(request) else None,
54
+ )
55
+ ```
56
+
57
+ FastAPI or Flask:
58
+
59
+ ```python
60
+ from backloop import fastapi_router, flask_blueprint
61
+
62
+ app.include_router(fastapi_router(handler)) # FastAPI
63
+ app.register_blueprint(flask_blueprint(handler)) # Flask
64
+ ```
65
+
66
+ Both serve `POST /feedback` and `GET /.well-known/agent-feedback`. Any other framework calls the handler directly:
67
+
68
+ ```python
69
+ status, body, headers = handler.handle_submit(raw_body, content_type, account, client_ip)
70
+ document = handler.discovery("https://api.example.com")
71
+ ```
72
+
73
+ `on_record(record)` stores or forwards each accepted record. Return `{"known_issue": {...}}` to pass a tracked issue back to the agent. If it raises, the agent gets `503`. Add `feedback_link_header()` as a `Link` header on your API's error responses so agents find the endpoint.
74
+
75
+ ## Utilities
76
+
77
+ ```python
78
+ from backloop import validate_submission, format_issues, redact
79
+
80
+ result = validate_submission(payload)
81
+ if not result.valid:
82
+ print(format_issues(result.issues)) # "goal: is required; type: must be one of: ..."
83
+
84
+ redact({"note": "auth failed with Bearer 9f8e7d6c5b4a", "password": "hunter2"})
85
+ # {"note": "auth failed with [REDACTED]", "password": "[REDACTED]"}
86
+ ```
87
+
88
+ ## Development
89
+
90
+ ```sh
91
+ python3 -m unittest discover -s tests -t .
92
+ ```
93
+
94
+ The tests run the shared conformance suite in `spec/conformance`. `src/backloop/_generated.py` is generated from `spec/` by `scripts/sync-schema.mjs`; don't edit it by hand.
95
+
96
+ License: Apache-2.0
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "backloop-sdk"
7
+ version = "0.1.0"
8
+ description = "Python SDK for the Agent Feedback Protocol: validate, send and receive structured feedback from AI agents."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.9"
12
+ dependencies = []
13
+ keywords = ["ai-agents", "feedback", "api", "mcp", "llm", "agent-feedback-protocol"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Topic :: Software Development :: Libraries",
20
+ "Typing :: Typed",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://trybackloop.com"
25
+ Specification = "https://trybackloop.com/spec/"
26
+ Repository = "https://github.com/guimsh/agent-feedback-protocol"
27
+ Issues = "https://github.com/guimsh/agent-feedback-protocol/issues"
28
+
29
+ [project.optional-dependencies]
30
+ fastapi = ["fastapi>=0.100"]
31
+ flask = ["flask>=2.0"]
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["src/backloop"]
35
+
36
+ [tool.hatch.build.targets.sdist]
37
+ include = ["src/backloop", "tests", "README.md", "pyproject.toml"]
@@ -0,0 +1,98 @@
1
+ """Python SDK for the Agent Feedback Protocol: validate, send and receive structured feedback from AI agents."""
2
+
3
+ from ._generated import (
4
+ ACK_SCHEMA,
5
+ AGENT_FEEDBACK_INSTRUCTIONS,
6
+ FEEDBACK_SCHEMA,
7
+ FEEDBACK_TOOL_DESCRIPTION,
8
+ RECORD_SCHEMA,
9
+ )
10
+ from .client import FeedbackClient, FeedbackError, SubmitResult, feedback_url_from_link
11
+ from .forward import ForwardError, MemorySink, fan_out, forward_to, memory_sink
12
+ from .ids import hash_account, new_id
13
+ from .integrations import fastapi_router, flask_blueprint
14
+ from .redact import REDACTED, redact, redact_string
15
+ from .server import (
16
+ FeedbackHandler,
17
+ HandlerResponse,
18
+ OnRecordResult,
19
+ error_response,
20
+ feedback_link_header,
21
+ )
22
+ from .tool import FEEDBACK_TOOL_NAME, feedback_tool, feedback_tool_input_schema
23
+ from .types import (
24
+ DEFAULT_MAX_BYTES,
25
+ FEEDBACK_TYPES,
26
+ LINK_REL,
27
+ OUTCOMES,
28
+ SPEC_VERSION,
29
+ WELL_KNOWN_PATH,
30
+ AgentInfo,
31
+ DiscoveryDocument,
32
+ Evidence,
33
+ FeedbackAck,
34
+ FeedbackRecord,
35
+ FeedbackSubmission,
36
+ KnownIssue,
37
+ ValidationIssue,
38
+ )
39
+ from .validate import (
40
+ ValidationResult,
41
+ format_issues,
42
+ validate_ack,
43
+ validate_record,
44
+ validate_submission,
45
+ )
46
+
47
+ __version__ = "0.1.0"
48
+
49
+ __all__ = [
50
+ "ACK_SCHEMA",
51
+ "AGENT_FEEDBACK_INSTRUCTIONS",
52
+ "DEFAULT_MAX_BYTES",
53
+ "FEEDBACK_SCHEMA",
54
+ "FEEDBACK_TOOL_DESCRIPTION",
55
+ "FEEDBACK_TOOL_NAME",
56
+ "FEEDBACK_TYPES",
57
+ "LINK_REL",
58
+ "OUTCOMES",
59
+ "RECORD_SCHEMA",
60
+ "REDACTED",
61
+ "SPEC_VERSION",
62
+ "WELL_KNOWN_PATH",
63
+ "AgentInfo",
64
+ "DiscoveryDocument",
65
+ "Evidence",
66
+ "FeedbackAck",
67
+ "FeedbackClient",
68
+ "FeedbackError",
69
+ "FeedbackHandler",
70
+ "FeedbackRecord",
71
+ "FeedbackSubmission",
72
+ "ForwardError",
73
+ "HandlerResponse",
74
+ "KnownIssue",
75
+ "MemorySink",
76
+ "OnRecordResult",
77
+ "SubmitResult",
78
+ "ValidationIssue",
79
+ "ValidationResult",
80
+ "error_response",
81
+ "fan_out",
82
+ "fastapi_router",
83
+ "feedback_link_header",
84
+ "feedback_tool",
85
+ "feedback_tool_input_schema",
86
+ "feedback_url_from_link",
87
+ "flask_blueprint",
88
+ "format_issues",
89
+ "forward_to",
90
+ "hash_account",
91
+ "memory_sink",
92
+ "new_id",
93
+ "redact",
94
+ "redact_string",
95
+ "validate_ack",
96
+ "validate_record",
97
+ "validate_submission",
98
+ ]
@@ -0,0 +1,12 @@
1
+ # Generated by scripts/sync-schema.mjs from spec/. Do not edit by hand.
2
+ import json
3
+
4
+ FEEDBACK_SCHEMA = json.loads("{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\",\"$id\":\"https://trybackloop.com/schemas/agent-feedback/0.1/feedback.schema.json\",\"title\":\"Agent Feedback Submission\",\"description\":\"Structured feedback an AI agent sends to a service when something prevents or complicates its task. Agent Feedback Protocol v0.1.\",\"type\":\"object\",\"required\":[\"type\",\"goal\",\"message\"],\"additionalProperties\":false,\"properties\":{\"spec_version\":{\"description\":\"Protocol version the agent is speaking. Defaults to \\\"0.1\\\" when omitted.\",\"type\":\"string\",\"const\":\"0.1\"},\"type\":{\"description\":\"Category of the problem.\",\"type\":\"string\",\"enum\":[\"missing_capability\",\"bug\",\"unclear_documentation\",\"unexpected_response\",\"unhelpful_error\",\"performance\",\"other\"]},\"goal\":{\"description\":\"What the agent (or its user) was trying to accomplish, in plain language. Describe the task, not the API call.\",\"type\":\"string\",\"minLength\":1,\"maxLength\":1000},\"message\":{\"description\":\"What prevented or complicated the task.\",\"type\":\"string\",\"minLength\":1,\"maxLength\":4000},\"endpoint\":{\"description\":\"The operation involved: an HTTP path template (\\\"/companies/search\\\") or a tool name (\\\"search_companies\\\").\",\"type\":\"string\",\"minLength\":1,\"maxLength\":512},\"method\":{\"description\":\"HTTP method, when the endpoint is an HTTP path.\",\"type\":\"string\",\"enum\":[\"GET\",\"POST\",\"PUT\",\"PATCH\",\"DELETE\",\"HEAD\",\"OPTIONS\"]},\"outcome\":{\"description\":\"What happened to the task. blocked: the task could not be completed. degraded: completed, but worse or slower than it should have been. completed: completed fine; the feedback is a suggestion.\",\"type\":\"string\",\"enum\":[\"blocked\",\"degraded\",\"completed\"]},\"workaround\":{\"description\":\"Whether the agent found a workaround.\",\"type\":\"boolean\"},\"workaround_description\":{\"description\":\"The workaround the agent used, if any.\",\"type\":\"string\",\"maxLength\":2000},\"expected\":{\"description\":\"What the agent expected to find or happen.\",\"type\":\"string\",\"maxLength\":2000},\"suggestion\":{\"description\":\"A concrete change that would have let the agent succeed.\",\"type\":\"string\",\"maxLength\":2000},\"request_id\":{\"description\":\"The service's request ID for a related call, to join feedback with logs.\",\"type\":\"string\",\"maxLength\":256},\"session_id\":{\"description\":\"Opaque ID shared by all feedback from one agent task run. Used to de-duplicate retries.\",\"type\":\"string\",\"maxLength\":256},\"agent\":{\"description\":\"Self-reported information about the agent.\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"name\":{\"type\":\"string\",\"maxLength\":128},\"version\":{\"type\":\"string\",\"maxLength\":64},\"model\":{\"type\":\"string\",\"maxLength\":128},\"framework\":{\"type\":\"string\",\"maxLength\":128}}},\"evidence\":{\"description\":\"Sanitized details of the failing interaction. Never include credentials or personal data.\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"status_code\":{\"type\":\"integer\",\"minimum\":100,\"maximum\":599},\"request\":{\"description\":\"Parameters or body the agent sent, with secrets removed.\",\"type\":\"object\"},\"response_excerpt\":{\"description\":\"The relevant part of the response.\",\"type\":\"string\",\"maxLength\":4000}}},\"metadata\":{\"description\":\"Free-form extra data. Services may ignore it.\",\"type\":\"object\"}}}")
5
+
6
+ RECORD_SCHEMA = json.loads("{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\",\"$id\":\"https://trybackloop.com/schemas/agent-feedback/0.1/record.schema.json\",\"title\":\"Agent Feedback Record\",\"description\":\"A feedback submission after the receiving service has accepted it: the agent's submission plus server-side context. This is what services store and forward to collectors.\",\"type\":\"object\",\"required\":[\"id\",\"received_at\",\"feedback\"],\"additionalProperties\":false,\"properties\":{\"id\":{\"description\":\"Unique ID assigned by the receiving service.\",\"type\":\"string\",\"minLength\":1,\"maxLength\":128},\"received_at\":{\"description\":\"RFC 3339 timestamp of when the service accepted the submission.\",\"type\":\"string\",\"format\":\"date-time\"},\"service\":{\"description\":\"Name of the service that received the feedback.\",\"type\":\"string\",\"maxLength\":128},\"account\":{\"description\":\"Opaque, stable identifier of the customer account the agent authenticated as. Services should hash or pseudonymize it.\",\"type\":\"string\",\"maxLength\":256},\"source\":{\"description\":\"Channel the feedback arrived through.\",\"type\":\"string\",\"enum\":[\"http\",\"mcp\",\"sdk\",\"other\"]},\"feedback\":{\"$ref\":\"feedback.schema.json\"}}}")
7
+
8
+ ACK_SCHEMA = json.loads("{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\",\"$id\":\"https://trybackloop.com/schemas/agent-feedback/0.1/ack.schema.json\",\"title\":\"Agent Feedback Acknowledgement\",\"description\":\"Body of a 202 response to POST /feedback.\",\"type\":\"object\",\"required\":[\"id\",\"status\",\"received_at\"],\"properties\":{\"id\":{\"type\":\"string\"},\"status\":{\"type\":\"string\",\"const\":\"accepted\"},\"received_at\":{\"type\":\"string\",\"format\":\"date-time\"},\"known_issue\":{\"description\":\"Present when the service already tracks this problem. Agents can use it to stop retrying or to apply a known workaround.\",\"type\":\"object\",\"required\":[\"id\",\"title\",\"status\"],\"properties\":{\"id\":{\"type\":\"string\"},\"title\":{\"type\":\"string\"},\"status\":{\"type\":\"string\",\"enum\":[\"acknowledged\",\"planned\",\"in_progress\",\"fixed\",\"wont_fix\"]},\"url\":{\"type\":\"string\"},\"workaround\":{\"type\":\"string\"}}}}}")
9
+
10
+ AGENT_FEEDBACK_INSTRUCTIONS = "## Reporting feedback to the services you use\n\nThe services you call accept structured feedback through `POST /feedback` (or the `submit_feedback` tool). Your reports go to the engineers who build the service and are used to fix what got in your way. Use it.\n\n**Submit feedback when something prevented or complicated your task:**\n- a capability you needed does not exist (a filter, field, endpoint or bulk operation);\n- the documentation was missing, ambiguous or wrong, and you had to guess;\n- a response was surprising or inconsistent with the docs;\n- an error message did not tell you how to fix the request;\n- the service behaved incorrectly;\n- latency, rate limits or pagination made the task impractical.\n\n**Don't submit feedback** for your own mistakes that the service reported clearly, for things you have not tried, or more than once for the same problem in the same task.\n\n**Write it like this:**\n- `goal`: what you or your user were trying to accomplish, in plain language. \"Find companies currently hiring GTM engineers\", not \"call /companies/search\".\n- `message`: what got in the way, specifically. \"No hiring-role filter is available; `q` only matches company names.\"\n- `type`: `missing_capability`, `bug`, `unclear_documentation`, `unexpected_response`, `unhelpful_error`, `performance` or `other`.\n- Fill `endpoint`, `outcome` (`blocked`, `degraded` or `completed`), `workaround`, `expected` and `suggestion` when you know them. A concrete suggestion is the most useful thing you can give.\n- Reuse the same `session_id` for every report in one task.\n\n**Never include** credentials, API keys, tokens, passwords, personal data, or your user's private content. Describe the shape of a request, not its secrets.\n\n**Keep going.** Submitting feedback is best effort. Send it, then continue with the task or a workaround. If the response contains `known_issue`, the problem is already tracked: tell your user if it matters, and use the workaround if one is given."
11
+
12
+ FEEDBACK_TOOL_DESCRIPTION = "Report a problem with this service to its engineering team. Call this when something prevented or complicated your task: a missing capability (filter, field, endpoint), unclear or wrong documentation, a surprising response, an unhelpful error, a bug, or impractical performance. Describe your goal in plain language, say specifically what got in the way, and include a concrete suggestion if you have one. Report each distinct problem once per task. Never include credentials, personal data or your user's private content. This is best effort: after calling it, continue with your task."
@@ -0,0 +1,50 @@
1
+ """Minimal urllib wrapper: returns every HTTP status instead of raising on 4xx/5xx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import urllib.error
7
+ import urllib.parse
8
+ import urllib.request
9
+ from typing import Any, Dict, Mapping, Optional, Tuple
10
+
11
+ Response = Tuple[int, Mapping[str, str], bytes]
12
+
13
+
14
+ def request(
15
+ url: str,
16
+ method: str = "GET",
17
+ body: Optional[bytes] = None,
18
+ headers: Optional[Dict[str, str]] = None,
19
+ timeout: float = 10.0,
20
+ ) -> Response:
21
+ """Send a request and return ``(status, headers, body)``.
22
+
23
+ Network failures (connection refused, timeouts, bad URLs) raise. Like
24
+ fetch, only http(s) URLs are allowed: urllib would also open file:// URLs.
25
+ """
26
+ if urllib.parse.urlsplit(url).scheme.lower() not in ("http", "https"):
27
+ raise ValueError(f"Unsupported URL: {url}")
28
+ req = urllib.request.Request(url, data=body, method=method, headers=headers or {})
29
+ try:
30
+ with urllib.request.urlopen(req, timeout=timeout) as res:
31
+ return res.status, res.headers, res.read()
32
+ except urllib.error.HTTPError as e:
33
+ try:
34
+ raw = e.read() # reading to the end also releases the connection
35
+ except Exception:
36
+ raw = b""
37
+ return e.code, e.headers, raw
38
+
39
+
40
+ def parse_json(raw: bytes) -> Any:
41
+ """Parse a JSON body, or return None when it is not JSON."""
42
+ try:
43
+ return json.loads(raw)
44
+ except ValueError:
45
+ return None
46
+
47
+
48
+ def dumps(value: Any) -> bytes:
49
+ """Compact UTF-8 JSON, like ``JSON.stringify``."""
50
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")