treg-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.
- treg_sdk-0.1.0/.gitignore +117 -0
- treg_sdk-0.1.0/PKG-INFO +112 -0
- treg_sdk-0.1.0/README.md +98 -0
- treg_sdk-0.1.0/pyproject.toml +33 -0
- treg_sdk-0.1.0/src/treg_sdk/__init__.py +24 -0
- treg_sdk-0.1.0/src/treg_sdk/_client.py +495 -0
- treg_sdk-0.1.0/src/treg_sdk/_version.py +1 -0
- treg_sdk-0.1.0/src/treg_sdk/py.typed +0 -0
- treg_sdk-0.1.0/tests/test_client.py +227 -0
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
.venv/
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.pyc
|
|
4
|
+
*.db
|
|
5
|
+
*.db-wal
|
|
6
|
+
*.db-shm
|
|
7
|
+
*.sqlite
|
|
8
|
+
*.sqlite3
|
|
9
|
+
*.sqlite*-wal
|
|
10
|
+
*.sqlite*-shm
|
|
11
|
+
*.bak
|
|
12
|
+
.env
|
|
13
|
+
.env.*
|
|
14
|
+
.secret/
|
|
15
|
+
.secrets/
|
|
16
|
+
.pytest_cache/
|
|
17
|
+
dist/
|
|
18
|
+
/.playwright-cli
|
|
19
|
+
scripts/.dev-home/
|
|
20
|
+
.claude/
|
|
21
|
+
.superdesign/
|
|
22
|
+
/videos
|
|
23
|
+
docs/proposals/
|
|
24
|
+
# Launch/marketing drafts and UI scratch. Useful locally, not part of the product, and a draft
|
|
25
|
+
# published by accident reads as a claim we made on purpose.
|
|
26
|
+
docs/hn-launch-post.md
|
|
27
|
+
/prototypes/
|
|
28
|
+
|
|
29
|
+
# Video-production skills. They belong to how we make launch material, not to treg, and they carry
|
|
30
|
+
# ~3.6MB of third-party font and brand assets — including CD Projekt Red fan-kit files whose own
|
|
31
|
+
# terms forbid commercial use. Nothing here should ship in a public repo for a commercial service.
|
|
32
|
+
.agents/skills/embedded-captions/
|
|
33
|
+
.agents/skills/faceless-explainer/
|
|
34
|
+
.agents/skills/general-video/
|
|
35
|
+
.agents/skills/hyperframes*/
|
|
36
|
+
.agents/skills/media-use/
|
|
37
|
+
.agents/skills/motion-graphics/
|
|
38
|
+
.agents/skills/music-to-video/
|
|
39
|
+
.agents/skills/pr-to-video/
|
|
40
|
+
.agents/skills/product-launch-video/
|
|
41
|
+
.agents/skills/remotion-to-hyperframes/
|
|
42
|
+
.agents/skills/slideshow/
|
|
43
|
+
.agents/skills/talking-head-recut/
|
|
44
|
+
.agents/skills/video-craft/
|
|
45
|
+
.agents/skills/figma/
|
|
46
|
+
!/.claude/
|
|
47
|
+
/.claude/*
|
|
48
|
+
!/.claude/skills
|
|
49
|
+
skills-lock.json
|
|
50
|
+
|
|
51
|
+
# Local planning / handoffs — private, never committed.
|
|
52
|
+
.context/
|
|
53
|
+
# Agent-skill specs and plans default to docs/superpowers/; they are working notes, not the design
|
|
54
|
+
# record, and belong in .context/ like any other plan.
|
|
55
|
+
docs/superpowers/
|
|
56
|
+
|
|
57
|
+
# Working docs that are plans/audits, not the shipped design record — they go stale the day
|
|
58
|
+
# after they are written and read as commitments they are not.
|
|
59
|
+
docs/PLATFORM-BALANCE-PLAN.md
|
|
60
|
+
docs/context/interface/*-plan.md
|
|
61
|
+
docs/context/interface/*-audit-*.md
|
|
62
|
+
docs/assets/restyle-*.png
|
|
63
|
+
docs/context/interface/*-proposal.md
|
|
64
|
+
.codegraph/
|
|
65
|
+
|
|
66
|
+
# e2e harness scratch (see e2e-server.sh) — the DB is disposable, never commit it.
|
|
67
|
+
e2e.db*
|
|
68
|
+
|
|
69
|
+
# Generated usage dashboards — regenerate with scripts/usage_report.py, never commit.
|
|
70
|
+
/reports/
|
|
71
|
+
|
|
72
|
+
# Review scratch: a prompt handed to an external reviewer, and its runner. Useful while a branch is
|
|
73
|
+
# in review, meaningless after it merges.
|
|
74
|
+
/.codex-review-prompt.md
|
|
75
|
+
/.codex-review.sh
|
|
76
|
+
|
|
77
|
+
# Scratch file used to compose commit messages (heredocs are blocked in this harness).
|
|
78
|
+
/.git-commit-msg
|
|
79
|
+
|
|
80
|
+
# Loopany loop specs and run records live on the machines that run the loops,
|
|
81
|
+
# not in the product repo (Jason, 2026-08-25).
|
|
82
|
+
/loopany/
|
|
83
|
+
.DS_Store
|
|
84
|
+
|
|
85
|
+
# Never in git, never in the sdist (see [tool.hatch.build.targets.sdist])
|
|
86
|
+
docs/evidence/
|
|
87
|
+
.import_linter_cache/
|
|
88
|
+
body.json
|
|
89
|
+
|
|
90
|
+
# Test screenshots — regenerated on demand, not versioned.
|
|
91
|
+
tests/screenshots/
|
|
92
|
+
|
|
93
|
+
# ArcTerm session boards and carry files (private, per machine)
|
|
94
|
+
.arcterm/
|
|
95
|
+
# Arena production statistics belong in the database, never a bundled snapshot.
|
|
96
|
+
/src/treg/web/enrich-arena/insights.json
|
|
97
|
+
|
|
98
|
+
# ArcTerm writes this local backup beside CLAUDE.md; it is not project content.
|
|
99
|
+
CLAUDE.md.arcterm-bak
|
|
100
|
+
# Frontend dependencies, build output and browser test artifacts.
|
|
101
|
+
node_modules
|
|
102
|
+
/src/treg/web/dashboard/
|
|
103
|
+
/frontend/test-results/
|
|
104
|
+
/frontend/playwright-report/
|
|
105
|
+
|
|
106
|
+
# Global Vue runtime copied from the npm lockfile during the frontend build.
|
|
107
|
+
/src/treg/web/vendor/*.js
|
|
108
|
+
/src/treg/web/vendor/LICENSE
|
|
109
|
+
|
|
110
|
+
# Go CLI build output
|
|
111
|
+
/cli/dist/
|
|
112
|
+
|
|
113
|
+
# Page videos live in the public media bucket (scripts/publish_page_media.py); only their
|
|
114
|
+
# manifest, src/treg/web/media-videos.json, is committed.
|
|
115
|
+
src/treg/web/media/**/*.mp4
|
|
116
|
+
src/treg/web/media/**/*.webm
|
|
117
|
+
src/treg/web/media/**/*.mov
|
treg_sdk-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: treg-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: treg SDK: call the tool catalog and your own tools, and let your customers connect their accounts and call tools as them.
|
|
5
|
+
Project-URL: Homepage, https://treg.to
|
|
6
|
+
Project-URL: Source, https://github.com/superdesigndev/treg/tree/main/packages/sdk-python
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Keywords: agents,mcp,oauth,sdk,tools,treg
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Requires-Dist: httpx<1,>=0.24
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# treg-sdk
|
|
16
|
+
|
|
17
|
+
The treg SDK for Python 3.9+, sync (`Treg`) and async (`AsyncTreg`).
|
|
18
|
+
|
|
19
|
+
- Call any catalog tool or one of your team's own tools, with no provider key in your code.
|
|
20
|
+
- Let **your customers** connect their own accounts (Instagram, Facebook Pages, Search Console,
|
|
21
|
+
Google Analytics, Meta Ads, ...) through treg's approved apps, then call tools **as one of them**.
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install treg-sdk
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Use an org-scoped token (`treg org agent-new <name>`), on your backend only. A token pinned to a tag
|
|
28
|
+
cannot act for your customers. `Treg()` reads
|
|
29
|
+
`TREG_TOKEN` and `TREG_URL` from the environment.
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from treg_sdk import Treg
|
|
33
|
+
|
|
34
|
+
treg = Treg()
|
|
35
|
+
r = treg.call("google-search-console.sites")
|
|
36
|
+
print(r.data, r.call_id, r.cost_micro)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Your customers' accounts
|
|
40
|
+
|
|
41
|
+
**1. Once:** ask treg to turn this on for your team. Then a team admin lists the hosts treg may send customers back to:
|
|
42
|
+
`PATCH /orgs/<team id>/settings {"connect_return_hosts": ["app.example.com"]}`.
|
|
43
|
+
|
|
44
|
+
**2. Make a consent link on your backend** and send the customer to it. Use your own id for them.
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
link = treg.end_users.connect(
|
|
48
|
+
"cust_42", "instagram",
|
|
49
|
+
return_url="https://app.example.com/integrations/done",
|
|
50
|
+
label="Ana's bakery",
|
|
51
|
+
)
|
|
52
|
+
# redirect the customer to link["consent_url"] (it works once, for link["expires_in_seconds"])
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
**3. Read the outcome** when treg sends the customer back:
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from treg_sdk import parse_connect_return
|
|
59
|
+
|
|
60
|
+
parse_connect_return(request_url) # ConnectReturn(status="connected" | "failed", provider, reason)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
**4. Call a catalog tool as that customer.** On an account provider only their
|
|
64
|
+
connection serves the call, never your team's. Search and data tools run on your team's key or balance.
|
|
65
|
+
Send `meta` too (`{"customer": "cust_42"}`): spend and limits per customer read only these tags.
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
ana = treg.for_end_user("cust_42")
|
|
69
|
+
sites = ana.call("google-search-console.sites")
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
**Manage them:**
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
treg.end_users.list(q="cust", provider="instagram", attention=True)
|
|
76
|
+
for c in treg.end_users.iterate():
|
|
77
|
+
print(c["end_user"], c["providers"])
|
|
78
|
+
treg.end_users.get("cust_42") # connections, status, expiry
|
|
79
|
+
treg.end_users.disconnect("cust_42", "instagram")
|
|
80
|
+
treg.end_users.remove("cust_42")
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
**An agent with MCP:** give the runtime this config. The model cannot choose or change the account.
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
cfg = treg.for_end_user("cust_42").mcp_config() # {"url": ..., "headers": {...}}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Async
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from treg_sdk import AsyncTreg
|
|
93
|
+
|
|
94
|
+
async with AsyncTreg() as treg:
|
|
95
|
+
r = await treg.for_end_user("cust_42").call("google-search-console.sites")
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Errors
|
|
99
|
+
|
|
100
|
+
Any non-2xx answer raises `TregError` with `status`, `code` (treg's error kind, for example
|
|
101
|
+
`end_user_not_connected` or `route_max_cost`; `None` for the provider's own error), `body` and
|
|
102
|
+
`call_id`.
|
|
103
|
+
|
|
104
|
+
## Call options
|
|
105
|
+
|
|
106
|
+
`params`, `json` or `content`, `method`, `end_user`, `meta` (tags for spend and limits per customer),
|
|
107
|
+
`max_cost_usd` (refuse the call when its hold would pass this many USD), `idempotency_key`,
|
|
108
|
+
`headers`.
|
|
109
|
+
|
|
110
|
+
Leave `end_user` out for a call on your team's own account. A missing id (`None`) raises an error.
|
|
111
|
+
|
|
112
|
+
The full guide: https://treg.to/integrate.md
|
treg_sdk-0.1.0/README.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# treg-sdk
|
|
2
|
+
|
|
3
|
+
The treg SDK for Python 3.9+, sync (`Treg`) and async (`AsyncTreg`).
|
|
4
|
+
|
|
5
|
+
- Call any catalog tool or one of your team's own tools, with no provider key in your code.
|
|
6
|
+
- Let **your customers** connect their own accounts (Instagram, Facebook Pages, Search Console,
|
|
7
|
+
Google Analytics, Meta Ads, ...) through treg's approved apps, then call tools **as one of them**.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install treg-sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Use an org-scoped token (`treg org agent-new <name>`), on your backend only. A token pinned to a tag
|
|
14
|
+
cannot act for your customers. `Treg()` reads
|
|
15
|
+
`TREG_TOKEN` and `TREG_URL` from the environment.
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from treg_sdk import Treg
|
|
19
|
+
|
|
20
|
+
treg = Treg()
|
|
21
|
+
r = treg.call("google-search-console.sites")
|
|
22
|
+
print(r.data, r.call_id, r.cost_micro)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Your customers' accounts
|
|
26
|
+
|
|
27
|
+
**1. Once:** ask treg to turn this on for your team. Then a team admin lists the hosts treg may send customers back to:
|
|
28
|
+
`PATCH /orgs/<team id>/settings {"connect_return_hosts": ["app.example.com"]}`.
|
|
29
|
+
|
|
30
|
+
**2. Make a consent link on your backend** and send the customer to it. Use your own id for them.
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
link = treg.end_users.connect(
|
|
34
|
+
"cust_42", "instagram",
|
|
35
|
+
return_url="https://app.example.com/integrations/done",
|
|
36
|
+
label="Ana's bakery",
|
|
37
|
+
)
|
|
38
|
+
# redirect the customer to link["consent_url"] (it works once, for link["expires_in_seconds"])
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
**3. Read the outcome** when treg sends the customer back:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from treg_sdk import parse_connect_return
|
|
45
|
+
|
|
46
|
+
parse_connect_return(request_url) # ConnectReturn(status="connected" | "failed", provider, reason)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
**4. Call a catalog tool as that customer.** On an account provider only their
|
|
50
|
+
connection serves the call, never your team's. Search and data tools run on your team's key or balance.
|
|
51
|
+
Send `meta` too (`{"customer": "cust_42"}`): spend and limits per customer read only these tags.
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
ana = treg.for_end_user("cust_42")
|
|
55
|
+
sites = ana.call("google-search-console.sites")
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
**Manage them:**
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
treg.end_users.list(q="cust", provider="instagram", attention=True)
|
|
62
|
+
for c in treg.end_users.iterate():
|
|
63
|
+
print(c["end_user"], c["providers"])
|
|
64
|
+
treg.end_users.get("cust_42") # connections, status, expiry
|
|
65
|
+
treg.end_users.disconnect("cust_42", "instagram")
|
|
66
|
+
treg.end_users.remove("cust_42")
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
**An agent with MCP:** give the runtime this config. The model cannot choose or change the account.
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
cfg = treg.for_end_user("cust_42").mcp_config() # {"url": ..., "headers": {...}}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Async
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
from treg_sdk import AsyncTreg
|
|
79
|
+
|
|
80
|
+
async with AsyncTreg() as treg:
|
|
81
|
+
r = await treg.for_end_user("cust_42").call("google-search-console.sites")
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Errors
|
|
85
|
+
|
|
86
|
+
Any non-2xx answer raises `TregError` with `status`, `code` (treg's error kind, for example
|
|
87
|
+
`end_user_not_connected` or `route_max_cost`; `None` for the provider's own error), `body` and
|
|
88
|
+
`call_id`.
|
|
89
|
+
|
|
90
|
+
## Call options
|
|
91
|
+
|
|
92
|
+
`params`, `json` or `content`, `method`, `end_user`, `meta` (tags for spend and limits per customer),
|
|
93
|
+
`max_cost_usd` (refuse the call when its hold would pass this many USD), `idempotency_key`,
|
|
94
|
+
`headers`.
|
|
95
|
+
|
|
96
|
+
Leave `end_user` out for a call on your team's own account. A missing id (`None`) raises an error.
|
|
97
|
+
|
|
98
|
+
The full guide: https://treg.to/integrate.md
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "treg-sdk"
|
|
3
|
+
dynamic = ["version"]
|
|
4
|
+
description = "treg SDK: call the tool catalog and your own tools, and let your customers connect their accounts and call tools as them."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
requires-python = ">=3.9"
|
|
8
|
+
dependencies = ["httpx>=0.24,<1"]
|
|
9
|
+
keywords = ["treg", "sdk", "oauth", "agents", "tools", "mcp"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Programming Language :: Python :: 3",
|
|
12
|
+
"Typing :: Typed",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://treg.to"
|
|
17
|
+
Source = "https://github.com/superdesigndev/treg/tree/main/packages/sdk-python"
|
|
18
|
+
|
|
19
|
+
[build-system]
|
|
20
|
+
requires = ["hatchling>=1.26"]
|
|
21
|
+
build-backend = "hatchling.build"
|
|
22
|
+
|
|
23
|
+
[tool.hatch.version]
|
|
24
|
+
path = "src/treg_sdk/_version.py"
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.wheel]
|
|
27
|
+
packages = ["src/treg_sdk"]
|
|
28
|
+
|
|
29
|
+
[dependency-groups]
|
|
30
|
+
dev = ["pytest>=8", "pytest-asyncio>=0.23"]
|
|
31
|
+
|
|
32
|
+
[tool.pytest.ini_options]
|
|
33
|
+
asyncio_mode = "auto"
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""treg SDK: call the tool catalog and your own tools, and let your customers connect their own
|
|
2
|
+
accounts through treg's apps, then call tools as one of them."""
|
|
3
|
+
|
|
4
|
+
from ._client import (
|
|
5
|
+
DEFAULT_BASE_URL,
|
|
6
|
+
AsyncTreg,
|
|
7
|
+
CallResult,
|
|
8
|
+
ConnectReturn,
|
|
9
|
+
Treg,
|
|
10
|
+
TregError,
|
|
11
|
+
parse_connect_return,
|
|
12
|
+
)
|
|
13
|
+
from ._version import __version__
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"DEFAULT_BASE_URL",
|
|
17
|
+
"AsyncTreg",
|
|
18
|
+
"CallResult",
|
|
19
|
+
"ConnectReturn",
|
|
20
|
+
"Treg",
|
|
21
|
+
"TregError",
|
|
22
|
+
"parse_connect_return",
|
|
23
|
+
"__version__",
|
|
24
|
+
]
|
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any, AsyncIterator, Iterator, Mapping, Optional, Sequence, Union
|
|
8
|
+
from urllib.parse import parse_qs, quote, unquote, urlsplit
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from ._version import __version__
|
|
13
|
+
|
|
14
|
+
DEFAULT_BASE_URL = "https://treg.to"
|
|
15
|
+
DEFAULT_TIMEOUT = 120.0
|
|
16
|
+
|
|
17
|
+
QueryValue = Union[str, int, float, bool, None, Sequence[Union[str, int, float, bool]]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TregError(Exception):
|
|
21
|
+
"""A non-2xx answer: treg's own refusal (``code`` is its kind) or the provider's error,
|
|
22
|
+
relayed as the provider sent it (``code`` is None)."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, status: int, body: Any, headers: httpx.Headers):
|
|
25
|
+
self.status = status
|
|
26
|
+
self.body = body
|
|
27
|
+
self.headers = headers
|
|
28
|
+
self.code = _error_code(body)
|
|
29
|
+
self.call_id = headers.get("x-treg-call-id")
|
|
30
|
+
super().__init__(f"treg {status}{' ' + self.code if self.code else ''}: {_error_text(body)}")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _error_code(body: Any) -> Optional[str]:
|
|
34
|
+
if isinstance(body, dict):
|
|
35
|
+
if isinstance(body.get("error"), str):
|
|
36
|
+
return body["error"]
|
|
37
|
+
detail = body.get("detail")
|
|
38
|
+
if isinstance(detail, dict) and isinstance(detail.get("error"), str):
|
|
39
|
+
return detail["error"]
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _error_text(body: Any) -> str:
|
|
44
|
+
if isinstance(body, str):
|
|
45
|
+
return body[:300]
|
|
46
|
+
if isinstance(body, dict):
|
|
47
|
+
detail = body.get("detail", body.get("message", body.get("error")))
|
|
48
|
+
if isinstance(detail, str):
|
|
49
|
+
return detail
|
|
50
|
+
if isinstance(detail, dict):
|
|
51
|
+
text = detail.get("detail", detail.get("message"))
|
|
52
|
+
if isinstance(text, str):
|
|
53
|
+
return text
|
|
54
|
+
return json.dumps(body, default=repr)[:300]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class CallResult:
|
|
59
|
+
status: int
|
|
60
|
+
headers: httpx.Headers
|
|
61
|
+
data: Any
|
|
62
|
+
"""The parsed JSON body, text, or ``bytes`` for anything else (audio, images, files)."""
|
|
63
|
+
"""The parsed JSON body, or the text when the answer is not JSON."""
|
|
64
|
+
call_id: Optional[str]
|
|
65
|
+
"""Store this: ``calls.get(call_id)`` and ``calls.result(call_id)`` resolve it later."""
|
|
66
|
+
cost_micro: int
|
|
67
|
+
"""What this call cost in micro-USD (1e-6 USD); 0 when it was not billed."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass
|
|
71
|
+
class ConnectReturn:
|
|
72
|
+
status: str
|
|
73
|
+
provider: Optional[str]
|
|
74
|
+
reason: Optional[str]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def parse_connect_return(url: str) -> Optional[ConnectReturn]:
|
|
78
|
+
"""Read the outcome treg appends to your ``return_url`` when it sends your customer back."""
|
|
79
|
+
params = parse_qs(urlsplit(url).query)
|
|
80
|
+
status = (params.get("treg_connect") or [None])[0]
|
|
81
|
+
if status not in ("connected", "failed"):
|
|
82
|
+
return None
|
|
83
|
+
return ConnectReturn(status=status, provider=(params.get("provider") or [None])[0],
|
|
84
|
+
reason=(params.get("reason") or [None])[0])
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _seg(value: str) -> str:
|
|
88
|
+
"""One id as one path segment: ``.`` and ``..`` would name another path."""
|
|
89
|
+
if value in ("", ".", ".."):
|
|
90
|
+
raise ValueError(f"not an id: {value!r}")
|
|
91
|
+
return quote(value, safe="")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _call_path(target: str) -> str:
|
|
95
|
+
"""``/call/<target>``, refusing a ``.`` or ``..`` segment at any depth of percent-encoding: it
|
|
96
|
+
would send the token to another route. URL parsing may read ``\\`` as ``/`` and drop tabs,
|
|
97
|
+
newlines and outer spaces."""
|
|
98
|
+
rest = target.lstrip("/")
|
|
99
|
+
path = re.split(r"[?#]", rest, maxsplit=1)[0]
|
|
100
|
+
for _ in range(4):
|
|
101
|
+
if not path or any(re.sub(r"[\x00-\x20]", "", s) in (".", "..") for s in re.split(r"[/\\]", path)):
|
|
102
|
+
break
|
|
103
|
+
decoded = unquote(path)
|
|
104
|
+
if decoded == path:
|
|
105
|
+
return "/call/" + rest
|
|
106
|
+
path = decoded
|
|
107
|
+
raise ValueError(f"not a tool or path: {target!r}")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _query(params: Optional[Mapping[str, QueryValue]]) -> list[tuple[str, str]]:
|
|
111
|
+
out: list[tuple[str, str]] = []
|
|
112
|
+
for key, value in (params or {}).items():
|
|
113
|
+
if value is None:
|
|
114
|
+
continue
|
|
115
|
+
for v in value if isinstance(value, (list, tuple)) else [value]:
|
|
116
|
+
out.append((key, ("true" if v else "false") if isinstance(v, bool) else str(v)))
|
|
117
|
+
return out
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# An answer of any other type (audio, images, files) stays bytes.
|
|
121
|
+
_TEXT = re.compile(r"^text/|[/+]xml|javascript|urlencoded|yaml")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _parse(response: httpx.Response) -> Any:
|
|
125
|
+
if not response.content:
|
|
126
|
+
return None
|
|
127
|
+
content_type = response.headers.get("content-type", "text/plain").lower()
|
|
128
|
+
if "json" in content_type:
|
|
129
|
+
try:
|
|
130
|
+
return response.json()
|
|
131
|
+
except ValueError:
|
|
132
|
+
return response.text
|
|
133
|
+
return response.text if _TEXT.search(content_type) else response.content
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# The default of ``end_user``: a team call. None is a missing id, and raises.
|
|
137
|
+
_TEAM: Any = object()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _end_user_id(value: str) -> str:
|
|
141
|
+
"""A missing id must not turn a customer's call into a call on the team's own account."""
|
|
142
|
+
if not isinstance(value, str) or not value.strip():
|
|
143
|
+
raise ValueError("end_user must be your customer's id, not blank")
|
|
144
|
+
return value
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _call_headers(end_user, meta, max_cost_usd, idempotency_key, headers) -> httpx.Headers:
|
|
148
|
+
# Case-insensitive, so a header the caller spelled another way is replaced, never sent beside.
|
|
149
|
+
out = httpx.Headers(dict(headers or {}))
|
|
150
|
+
if end_user is not _TEAM:
|
|
151
|
+
out["X-Treg-End-User"] = _end_user_id(end_user)
|
|
152
|
+
if meta:
|
|
153
|
+
out["X-Treg-Meta"] = ", ".join(f"{k}={v}" for k, v in meta.items())
|
|
154
|
+
if max_cost_usd is not None:
|
|
155
|
+
out["X-Treg-Route-Max-Cost"] = str(max_cost_usd)
|
|
156
|
+
if idempotency_key:
|
|
157
|
+
out["Idempotency-Key"] = idempotency_key
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _result(response: httpx.Response) -> CallResult:
|
|
162
|
+
return CallResult(status=response.status_code, headers=response.headers, data=_parse(response),
|
|
163
|
+
call_id=response.headers.get("x-treg-call-id"),
|
|
164
|
+
cost_micro=int(response.headers.get("x-treg-cost-micro") or 0))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _connect_body(provider, capability, return_url, label) -> dict:
|
|
168
|
+
body = {"provider": provider, "capability": capability, "return_url": return_url, "label": label}
|
|
169
|
+
return {k: v for k, v in body.items() if v is not None}
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _list_params(after, limit, q, provider, attention) -> dict:
|
|
173
|
+
return {"after": after, "limit": limit, "q": q or None, "provider": provider or None,
|
|
174
|
+
"attention": "true" if attention else None}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class _Base:
|
|
178
|
+
def __init__(self, token: Optional[str], base_url: Optional[str], org: Optional[str],
|
|
179
|
+
headers: Optional[Mapping[str, str]]):
|
|
180
|
+
self.token = token if token is not None else os.environ.get("TREG_TOKEN", "")
|
|
181
|
+
self.base_url = (base_url or os.environ.get("TREG_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
182
|
+
self.org = org
|
|
183
|
+
self._headers = httpx.Headers({"User-Agent": f"treg-sdk-python/{__version__}"})
|
|
184
|
+
self._headers.update(dict(headers or {}))
|
|
185
|
+
if self.token:
|
|
186
|
+
self._headers["X-Treg-Token"] = self.token
|
|
187
|
+
if org:
|
|
188
|
+
self._headers["X-Treg-Org"] = org
|
|
189
|
+
|
|
190
|
+
def mcp_config(self, end_user: str = _TEAM) -> dict:
|
|
191
|
+
"""The MCP server address and headers for an agent runtime. With ``end_user``, every tool
|
|
192
|
+
call acts as that customer; the model cannot pick or change the account."""
|
|
193
|
+
headers = {"Authorization": f"Bearer {self.token}"}
|
|
194
|
+
if self.org:
|
|
195
|
+
headers["X-Treg-Org"] = self.org
|
|
196
|
+
if end_user is not _TEAM:
|
|
197
|
+
headers["X-Treg-End-User"] = _end_user_id(end_user)
|
|
198
|
+
return {"url": f"{self.base_url}/mcp/", "headers": headers}
|
|
199
|
+
|
|
200
|
+
def _build(self, method: str, path: str, *, params=None, json_body=None, content=None,
|
|
201
|
+
headers=None) -> dict:
|
|
202
|
+
merged = self._headers.copy()
|
|
203
|
+
merged.update(headers)
|
|
204
|
+
# httpx's own `params` would replace a query already in the path.
|
|
205
|
+
url = self.base_url + path.partition("#")[0]
|
|
206
|
+
if query := str(httpx.QueryParams(_query(params))):
|
|
207
|
+
url += ("&" if "?" in url else "?") + query
|
|
208
|
+
# Never follow a redirect: it would resend X-Treg-Token to wherever an upstream points.
|
|
209
|
+
kwargs: dict[str, Any] = {"method": method, "url": url, "headers": merged,
|
|
210
|
+
"follow_redirects": False}
|
|
211
|
+
if content is not None:
|
|
212
|
+
kwargs["content"] = content
|
|
213
|
+
elif json_body is not None:
|
|
214
|
+
kwargs["content"] = json.dumps(json_body).encode()
|
|
215
|
+
merged.setdefault("Content-Type", "application/json")
|
|
216
|
+
return kwargs
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _checked(response: httpx.Response) -> httpx.Response:
|
|
220
|
+
if response.status_code >= 400:
|
|
221
|
+
raise TregError(response.status_code, _parse(response), response.headers)
|
|
222
|
+
return response
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class Treg(_Base):
|
|
226
|
+
"""treg client. ``Treg()`` reads ``TREG_TOKEN`` and ``TREG_URL`` from the environment.
|
|
227
|
+
|
|
228
|
+
Call tools with ``call``; manage your customers' connections with ``end_users``."""
|
|
229
|
+
|
|
230
|
+
def __init__(self, token: Optional[str] = None, *, base_url: Optional[str] = None,
|
|
231
|
+
org: Optional[str] = None, headers: Optional[Mapping[str, str]] = None,
|
|
232
|
+
timeout: float = DEFAULT_TIMEOUT, http_client: Optional[httpx.Client] = None):
|
|
233
|
+
super().__init__(token, base_url, org, headers)
|
|
234
|
+
self._http = http_client or httpx.Client(timeout=timeout)
|
|
235
|
+
self.end_users = EndUsers(self)
|
|
236
|
+
self.catalog = Catalog(self)
|
|
237
|
+
self.calls = Calls(self)
|
|
238
|
+
|
|
239
|
+
def __enter__(self) -> "Treg":
|
|
240
|
+
return self
|
|
241
|
+
|
|
242
|
+
def __exit__(self, *exc) -> None:
|
|
243
|
+
self.close()
|
|
244
|
+
|
|
245
|
+
def close(self) -> None:
|
|
246
|
+
self._http.close()
|
|
247
|
+
|
|
248
|
+
def _request(self, method: str, path: str, **kwargs) -> httpx.Response:
|
|
249
|
+
return _checked(self._http.request(**self._build(method, path, **kwargs)))
|
|
250
|
+
|
|
251
|
+
def _json(self, method: str, path: str, **kwargs) -> Any:
|
|
252
|
+
return _parse(self._request(method, path, **kwargs))
|
|
253
|
+
|
|
254
|
+
def call(self, target: str, *, method: Optional[str] = None,
|
|
255
|
+
params: Optional[Mapping[str, QueryValue]] = None, json: Any = None,
|
|
256
|
+
content: Optional[bytes] = None, end_user: str = _TEAM,
|
|
257
|
+
meta: Optional[Mapping[str, str]] = None, max_cost_usd: Optional[float] = None,
|
|
258
|
+
idempotency_key: Optional[str] = None,
|
|
259
|
+
headers: Optional[Mapping[str, str]] = None) -> CallResult:
|
|
260
|
+
"""Call a catalog tool by id (``google-search-console.sites``), a provider path or one of
|
|
261
|
+
your own tools. ``end_user`` acts as one of your customers; leave it out for a team call
|
|
262
|
+
(None raises). Raises ``TregError`` on any
|
|
263
|
+
non-2xx answer, the provider's errors included."""
|
|
264
|
+
verb = method or ("POST" if json is not None or content is not None else "GET")
|
|
265
|
+
return _result(self._request(
|
|
266
|
+
verb.upper(), _call_path(target), params=params, json_body=json,
|
|
267
|
+
content=content,
|
|
268
|
+
headers=_call_headers(end_user, meta, max_cost_usd, idempotency_key, headers)))
|
|
269
|
+
|
|
270
|
+
def for_end_user(self, end_user: str) -> "EndUserClient":
|
|
271
|
+
"""A client whose every call acts as one of your customers."""
|
|
272
|
+
return EndUserClient(self, end_user)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class EndUserClient:
|
|
276
|
+
def __init__(self, client: Treg, end_user: str):
|
|
277
|
+
self._client = client
|
|
278
|
+
self.end_user = _end_user_id(end_user)
|
|
279
|
+
|
|
280
|
+
def call(self, target: str, **kwargs) -> CallResult:
|
|
281
|
+
return self._client.call(target, end_user=self.end_user, **kwargs)
|
|
282
|
+
|
|
283
|
+
def connect(self, provider: str, **kwargs) -> dict:
|
|
284
|
+
return self._client.end_users.connect(self.end_user, provider, **kwargs)
|
|
285
|
+
|
|
286
|
+
def get(self) -> dict:
|
|
287
|
+
return self._client.end_users.get(self.end_user)
|
|
288
|
+
|
|
289
|
+
def disconnect(self, provider: str) -> dict:
|
|
290
|
+
return self._client.end_users.disconnect(self.end_user, provider)
|
|
291
|
+
|
|
292
|
+
def remove(self) -> dict:
|
|
293
|
+
return self._client.end_users.remove(self.end_user)
|
|
294
|
+
|
|
295
|
+
def mcp_config(self) -> dict:
|
|
296
|
+
return self._client.mcp_config(end_user=self.end_user)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class EndUsers:
|
|
300
|
+
"""Your customers ("end users") and the accounts they connected through treg's apps."""
|
|
301
|
+
|
|
302
|
+
def __init__(self, client: Treg):
|
|
303
|
+
self._client = client
|
|
304
|
+
|
|
305
|
+
def connect(self, end_user: str, provider: str, *, capability: Optional[str] = None,
|
|
306
|
+
return_url: Optional[str] = None, label: Optional[str] = None) -> dict:
|
|
307
|
+
"""A one-time consent link (``consent_url``) for this customer. Make it on your backend."""
|
|
308
|
+
return self._client._json("POST", f"/end-users/{_seg(end_user)}/connect",
|
|
309
|
+
json_body=_connect_body(provider, capability, return_url, label))
|
|
310
|
+
|
|
311
|
+
def list(self, *, after: Optional[str] = None, limit: Optional[int] = None, q: str = "",
|
|
312
|
+
provider: str = "", attention: bool = False) -> dict:
|
|
313
|
+
"""One page, oldest first: ``end_users``, ``total`` and ``next`` (pass it as ``after``)."""
|
|
314
|
+
return self._client._json("GET", "/end-users",
|
|
315
|
+
params=_list_params(after, limit, q, provider, attention))
|
|
316
|
+
|
|
317
|
+
def iterate(self, *, limit: Optional[int] = None, q: str = "", provider: str = "",
|
|
318
|
+
attention: bool = False) -> Iterator[dict]:
|
|
319
|
+
"""Every match, page by page."""
|
|
320
|
+
after = None
|
|
321
|
+
while True:
|
|
322
|
+
page = self.list(after=after, limit=limit, q=q, provider=provider, attention=attention)
|
|
323
|
+
yield from page["end_users"]
|
|
324
|
+
after = page.get("next")
|
|
325
|
+
if not after:
|
|
326
|
+
return
|
|
327
|
+
|
|
328
|
+
def get(self, end_user: str) -> dict:
|
|
329
|
+
"""The customer's connections, with status and expiry. No token material."""
|
|
330
|
+
return self._client._json("GET", f"/end-users/{_seg(end_user)}")
|
|
331
|
+
|
|
332
|
+
def disconnect(self, end_user: str, provider: str) -> dict:
|
|
333
|
+
"""Forget the customer's connection to one provider. It is not revoked at the platform."""
|
|
334
|
+
return self._client._json(
|
|
335
|
+
"DELETE", f"/end-users/{_seg(end_user)}/connections/{_seg(provider)}")
|
|
336
|
+
|
|
337
|
+
def remove(self, end_user: str) -> dict:
|
|
338
|
+
"""Forget the customer and every connection they made."""
|
|
339
|
+
return self._client._json("DELETE", f"/end-users/{_seg(end_user)}")
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
class Catalog:
|
|
343
|
+
def __init__(self, client: Treg):
|
|
344
|
+
self._client = client
|
|
345
|
+
|
|
346
|
+
def search(self, q: str, *, limit: Optional[int] = None) -> dict:
|
|
347
|
+
"""Find tools by the job they do. Each result has an id and a price."""
|
|
348
|
+
return self._client._json("GET", "/catalog/search", params={"q": q, "limit": limit})
|
|
349
|
+
|
|
350
|
+
def get(self, endpoint_id: str) -> dict:
|
|
351
|
+
"""One tool: its parameters, method and an example."""
|
|
352
|
+
return self._client._json("GET", f"/catalog/endpoints/{_seg(endpoint_id)}")
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
class Calls:
|
|
356
|
+
def __init__(self, client: Treg):
|
|
357
|
+
self._client = client
|
|
358
|
+
|
|
359
|
+
def get(self, call_id: str) -> dict:
|
|
360
|
+
"""The record of one call by its ``X-Treg-Call-Id``."""
|
|
361
|
+
return self._client._json("GET", f"/calls/{_seg(call_id)}")
|
|
362
|
+
|
|
363
|
+
def result(self, call_id: str) -> Any:
|
|
364
|
+
"""The stored answer of a successful catalog call whose answer you lost."""
|
|
365
|
+
return self._client._json("GET", f"/calls/{_seg(call_id)}/result")
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
# ---- async -------------------------------------------------------------------------------------
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
class AsyncTreg(_Base):
|
|
372
|
+
"""The same client for asyncio."""
|
|
373
|
+
|
|
374
|
+
def __init__(self, token: Optional[str] = None, *, base_url: Optional[str] = None,
|
|
375
|
+
org: Optional[str] = None, headers: Optional[Mapping[str, str]] = None,
|
|
376
|
+
timeout: float = DEFAULT_TIMEOUT, http_client: Optional[httpx.AsyncClient] = None):
|
|
377
|
+
super().__init__(token, base_url, org, headers)
|
|
378
|
+
self._http = http_client or httpx.AsyncClient(timeout=timeout)
|
|
379
|
+
self.end_users = AsyncEndUsers(self)
|
|
380
|
+
self.catalog = AsyncCatalog(self)
|
|
381
|
+
self.calls = AsyncCalls(self)
|
|
382
|
+
|
|
383
|
+
async def __aenter__(self) -> "AsyncTreg":
|
|
384
|
+
return self
|
|
385
|
+
|
|
386
|
+
async def __aexit__(self, *exc) -> None:
|
|
387
|
+
await self.close()
|
|
388
|
+
|
|
389
|
+
async def close(self) -> None:
|
|
390
|
+
await self._http.aclose()
|
|
391
|
+
|
|
392
|
+
async def _request(self, method: str, path: str, **kwargs) -> httpx.Response:
|
|
393
|
+
return _checked(await self._http.request(**self._build(method, path, **kwargs)))
|
|
394
|
+
|
|
395
|
+
async def _json(self, method: str, path: str, **kwargs) -> Any:
|
|
396
|
+
return _parse(await self._request(method, path, **kwargs))
|
|
397
|
+
|
|
398
|
+
async def call(self, target: str, *, method: Optional[str] = None,
|
|
399
|
+
params: Optional[Mapping[str, QueryValue]] = None, json: Any = None,
|
|
400
|
+
content: Optional[bytes] = None, end_user: str = _TEAM,
|
|
401
|
+
meta: Optional[Mapping[str, str]] = None, max_cost_usd: Optional[float] = None,
|
|
402
|
+
idempotency_key: Optional[str] = None,
|
|
403
|
+
headers: Optional[Mapping[str, str]] = None) -> CallResult:
|
|
404
|
+
verb = method or ("POST" if json is not None or content is not None else "GET")
|
|
405
|
+
return _result(await self._request(
|
|
406
|
+
verb.upper(), _call_path(target), params=params, json_body=json,
|
|
407
|
+
content=content,
|
|
408
|
+
headers=_call_headers(end_user, meta, max_cost_usd, idempotency_key, headers)))
|
|
409
|
+
|
|
410
|
+
def for_end_user(self, end_user: str) -> "AsyncEndUserClient":
|
|
411
|
+
return AsyncEndUserClient(self, end_user)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
class AsyncEndUserClient:
|
|
415
|
+
def __init__(self, client: AsyncTreg, end_user: str):
|
|
416
|
+
self._client = client
|
|
417
|
+
self.end_user = _end_user_id(end_user)
|
|
418
|
+
|
|
419
|
+
async def call(self, target: str, **kwargs) -> CallResult:
|
|
420
|
+
return await self._client.call(target, end_user=self.end_user, **kwargs)
|
|
421
|
+
|
|
422
|
+
async def connect(self, provider: str, **kwargs) -> dict:
|
|
423
|
+
return await self._client.end_users.connect(self.end_user, provider, **kwargs)
|
|
424
|
+
|
|
425
|
+
async def get(self) -> dict:
|
|
426
|
+
return await self._client.end_users.get(self.end_user)
|
|
427
|
+
|
|
428
|
+
async def disconnect(self, provider: str) -> dict:
|
|
429
|
+
return await self._client.end_users.disconnect(self.end_user, provider)
|
|
430
|
+
|
|
431
|
+
async def remove(self) -> dict:
|
|
432
|
+
return await self._client.end_users.remove(self.end_user)
|
|
433
|
+
|
|
434
|
+
def mcp_config(self) -> dict:
|
|
435
|
+
return self._client.mcp_config(end_user=self.end_user)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
class AsyncEndUsers:
|
|
439
|
+
def __init__(self, client: AsyncTreg):
|
|
440
|
+
self._client = client
|
|
441
|
+
|
|
442
|
+
async def connect(self, end_user: str, provider: str, *, capability: Optional[str] = None,
|
|
443
|
+
return_url: Optional[str] = None, label: Optional[str] = None) -> dict:
|
|
444
|
+
return await self._client._json(
|
|
445
|
+
"POST", f"/end-users/{_seg(end_user)}/connect",
|
|
446
|
+
json_body=_connect_body(provider, capability, return_url, label))
|
|
447
|
+
|
|
448
|
+
async def list(self, *, after: Optional[str] = None, limit: Optional[int] = None, q: str = "",
|
|
449
|
+
provider: str = "", attention: bool = False) -> dict:
|
|
450
|
+
return await self._client._json("GET", "/end-users",
|
|
451
|
+
params=_list_params(after, limit, q, provider, attention))
|
|
452
|
+
|
|
453
|
+
async def iterate(self, *, limit: Optional[int] = None, q: str = "", provider: str = "",
|
|
454
|
+
attention: bool = False) -> AsyncIterator[dict]:
|
|
455
|
+
after = None
|
|
456
|
+
while True:
|
|
457
|
+
page = await self.list(after=after, limit=limit, q=q, provider=provider,
|
|
458
|
+
attention=attention)
|
|
459
|
+
for end_user in page["end_users"]:
|
|
460
|
+
yield end_user
|
|
461
|
+
after = page.get("next")
|
|
462
|
+
if not after:
|
|
463
|
+
return
|
|
464
|
+
|
|
465
|
+
async def get(self, end_user: str) -> dict:
|
|
466
|
+
return await self._client._json("GET", f"/end-users/{_seg(end_user)}")
|
|
467
|
+
|
|
468
|
+
async def disconnect(self, end_user: str, provider: str) -> dict:
|
|
469
|
+
return await self._client._json(
|
|
470
|
+
"DELETE", f"/end-users/{_seg(end_user)}/connections/{_seg(provider)}")
|
|
471
|
+
|
|
472
|
+
async def remove(self, end_user: str) -> dict:
|
|
473
|
+
return await self._client._json("DELETE", f"/end-users/{_seg(end_user)}")
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
class AsyncCatalog:
|
|
477
|
+
def __init__(self, client: AsyncTreg):
|
|
478
|
+
self._client = client
|
|
479
|
+
|
|
480
|
+
async def search(self, q: str, *, limit: Optional[int] = None) -> dict:
|
|
481
|
+
return await self._client._json("GET", "/catalog/search", params={"q": q, "limit": limit})
|
|
482
|
+
|
|
483
|
+
async def get(self, endpoint_id: str) -> dict:
|
|
484
|
+
return await self._client._json("GET", f"/catalog/endpoints/{_seg(endpoint_id)}")
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
class AsyncCalls:
|
|
488
|
+
def __init__(self, client: AsyncTreg):
|
|
489
|
+
self._client = client
|
|
490
|
+
|
|
491
|
+
async def get(self, call_id: str) -> dict:
|
|
492
|
+
return await self._client._json("GET", f"/calls/{_seg(call_id)}")
|
|
493
|
+
|
|
494
|
+
async def result(self, call_id: str) -> Any:
|
|
495
|
+
return await self._client._json("GET", f"/calls/{_seg(call_id)}/result")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
File without changes
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from treg_sdk import AsyncTreg, Treg, TregError, parse_connect_return
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _client(handler, cls=Treg, **kwargs):
|
|
10
|
+
transport = httpx.MockTransport(handler)
|
|
11
|
+
http = (httpx.AsyncClient if cls is AsyncTreg else httpx.Client)(transport=transport)
|
|
12
|
+
return cls("tok", base_url="https://example.test/", http_client=http, **kwargs)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_a_call_sends_token_params_and_end_user_and_reads_cost_and_call_id():
|
|
16
|
+
seen = []
|
|
17
|
+
|
|
18
|
+
def handler(request):
|
|
19
|
+
seen.append(request)
|
|
20
|
+
return httpx.Response(200, json={"siteEntry": []},
|
|
21
|
+
headers={"x-treg-call-id": "c_1", "x-treg-cost-micro": "1500"})
|
|
22
|
+
|
|
23
|
+
r = _client(handler).call(
|
|
24
|
+
"google-search-console.sites", params={"dims": ["query", "page"], "skip": None, "on": True},
|
|
25
|
+
end_user="cust_42", meta={"customer": "cust_42", "feature": "seo"}, max_cost_usd=0.5,
|
|
26
|
+
idempotency_key="k1")
|
|
27
|
+
assert (r.data, r.call_id, r.cost_micro) == ({"siteEntry": []}, "c_1", 1500)
|
|
28
|
+
[req] = seen
|
|
29
|
+
assert req.method == "GET"
|
|
30
|
+
assert req.url.path == "/call/google-search-console.sites"
|
|
31
|
+
assert req.url.params.get_list("dims") == ["query", "page"]
|
|
32
|
+
assert "skip" not in req.url.params and req.url.params["on"] == "true"
|
|
33
|
+
assert req.headers["x-treg-token"] == "tok"
|
|
34
|
+
assert req.headers["x-treg-end-user"] == "cust_42"
|
|
35
|
+
assert req.headers["x-treg-meta"] == "customer=cust_42, feature=seo"
|
|
36
|
+
assert req.headers["x-treg-route-max-cost"] == "0.5"
|
|
37
|
+
assert req.headers["idempotency-key"] == "k1"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_a_json_body_makes_a_post():
|
|
41
|
+
seen = []
|
|
42
|
+
|
|
43
|
+
def handler(request):
|
|
44
|
+
seen.append(request)
|
|
45
|
+
return httpx.Response(200, json={})
|
|
46
|
+
|
|
47
|
+
_client(handler).call("acme/v1/things", json={"a": 1})
|
|
48
|
+
assert seen[0].method == "POST"
|
|
49
|
+
assert json.loads(seen[0].content) == {"a": 1}
|
|
50
|
+
assert seen[0].headers["content-type"] == "application/json"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_a_refusal_raises_with_tregs_error_kind_and_call_id():
|
|
54
|
+
def handler(request):
|
|
55
|
+
return httpx.Response(404, json={"error": "end_user_not_connected",
|
|
56
|
+
"detail": "cust_9 has not connected"},
|
|
57
|
+
headers={"x-treg-call-id": "c_2"})
|
|
58
|
+
|
|
59
|
+
with pytest.raises(TregError) as info:
|
|
60
|
+
_client(handler).for_end_user("cust_9").call("google-search-console.sites")
|
|
61
|
+
assert (info.value.status, info.value.code, info.value.call_id) == (
|
|
62
|
+
404, "end_user_not_connected", "c_2")
|
|
63
|
+
assert "cust_9 has not connected" in str(info.value)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_a_refusal_inside_detail_shows_its_message_not_json():
|
|
67
|
+
refused = {"detail": {"error": "end_users_disabled", "message": "not turned on"}}
|
|
68
|
+
with pytest.raises(TregError) as info:
|
|
69
|
+
_client(lambda request: httpx.Response(403, json=refused)).end_users.connect("c", "x")
|
|
70
|
+
assert str(info.value) == "treg 403 end_users_disabled: not turned on"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_end_users_connect_list_read_and_remove():
|
|
74
|
+
seen = []
|
|
75
|
+
|
|
76
|
+
def handler(request):
|
|
77
|
+
seen.append(request)
|
|
78
|
+
if request.url.path == "/end-users":
|
|
79
|
+
if "after" not in request.url.params:
|
|
80
|
+
return httpx.Response(200, json={"end_users": [{"end_user": "a"}], "total": 2,
|
|
81
|
+
"next": "7"})
|
|
82
|
+
return httpx.Response(200, json={"end_users": [{"end_user": "b"}], "total": 2,
|
|
83
|
+
"next": None})
|
|
84
|
+
return httpx.Response(200, json={"consent_url": "https://consent"})
|
|
85
|
+
|
|
86
|
+
treg = _client(handler)
|
|
87
|
+
link = treg.end_users.connect("cust/42", "instagram", return_url="https://app.example.com/done",
|
|
88
|
+
label="Ana")
|
|
89
|
+
assert link["consent_url"] == "https://consent"
|
|
90
|
+
assert seen[0].url.raw_path == b"/end-users/cust%2F42/connect"
|
|
91
|
+
assert json.loads(seen[0].content) == {"provider": "instagram",
|
|
92
|
+
"return_url": "https://app.example.com/done",
|
|
93
|
+
"label": "Ana"}
|
|
94
|
+
assert [e["end_user"] for e in treg.end_users.iterate(attention=True, q="cu")] == ["a", "b"]
|
|
95
|
+
assert seen[1].url.params["attention"] == "true" and seen[2].url.params["after"] == "7"
|
|
96
|
+
treg.end_users.disconnect("cust_42", "instagram")
|
|
97
|
+
treg.end_users.remove("cust_42")
|
|
98
|
+
assert [(r.method, r.url.path) for r in seen[3:]] == [
|
|
99
|
+
("DELETE", "/end-users/cust_42/connections/instagram"), ("DELETE", "/end-users/cust_42")]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
async def test_the_async_client_does_the_same():
|
|
103
|
+
seen = []
|
|
104
|
+
|
|
105
|
+
def handler(request):
|
|
106
|
+
seen.append(request)
|
|
107
|
+
if request.url.path == "/end-users":
|
|
108
|
+
return httpx.Response(200, json={"end_users": [{"end_user": "a"}], "total": 1,
|
|
109
|
+
"next": None})
|
|
110
|
+
return httpx.Response(200, json={"ok": True}, headers={"x-treg-call-id": "c_3"})
|
|
111
|
+
|
|
112
|
+
async with _client(handler, cls=AsyncTreg) as treg:
|
|
113
|
+
r = await treg.for_end_user("cust_42").call("google-search-console.sites")
|
|
114
|
+
assert r.call_id == "c_3" and seen[0].headers["x-treg-end-user"] == "cust_42"
|
|
115
|
+
assert [e["end_user"] async for e in treg.end_users.iterate()] == ["a"]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_mcp_config_carries_the_end_user():
|
|
119
|
+
treg = Treg("tok", base_url="https://example.test", org="acme")
|
|
120
|
+
assert treg.for_end_user("cust_42").mcp_config() == {
|
|
121
|
+
"url": "https://example.test/mcp/",
|
|
122
|
+
"headers": {"Authorization": "Bearer tok", "X-Treg-Org": "acme",
|
|
123
|
+
"X-Treg-End-User": "cust_42"},
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def test_parse_connect_return():
|
|
128
|
+
back = parse_connect_return(
|
|
129
|
+
"https://app.example.com/done?x=1&treg_connect=failed&provider=instagram&reason=denied")
|
|
130
|
+
assert (back.status, back.provider, back.reason) == ("failed", "instagram", "denied")
|
|
131
|
+
assert parse_connect_return("https://app.example.com/done") is None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def test_a_redirect_is_returned_never_followed_with_the_token():
|
|
135
|
+
seen = []
|
|
136
|
+
|
|
137
|
+
def handler(request):
|
|
138
|
+
seen.append(request)
|
|
139
|
+
if request.url.host == "elsewhere.example":
|
|
140
|
+
return httpx.Response(200, json={"stolen": True})
|
|
141
|
+
return httpx.Response(302, headers={"location": "https://elsewhere.example/x"})
|
|
142
|
+
|
|
143
|
+
transport = httpx.MockTransport(handler)
|
|
144
|
+
treg = Treg("tok", base_url="https://example.test",
|
|
145
|
+
http_client=httpx.Client(transport=transport, follow_redirects=True))
|
|
146
|
+
r = treg.call("acme/v1/go")
|
|
147
|
+
assert r.status == 302 and len(seen) == 1
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@pytest.mark.parametrize("blank", ["", " "])
|
|
151
|
+
def test_a_blank_end_user_never_becomes_a_team_call(blank):
|
|
152
|
+
treg = _client(lambda request: pytest.fail("sent"))
|
|
153
|
+
for act in (lambda: treg.call("x.y", end_user=blank), lambda: treg.mcp_config(end_user=blank),
|
|
154
|
+
lambda: treg.for_end_user(blank), lambda: treg.for_end_user(None)):
|
|
155
|
+
with pytest.raises(ValueError):
|
|
156
|
+
act()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def test_the_chosen_end_user_replaces_a_header_spelled_another_way():
|
|
160
|
+
seen = []
|
|
161
|
+
|
|
162
|
+
def handler(request):
|
|
163
|
+
seen.append(request)
|
|
164
|
+
return httpx.Response(200, json={})
|
|
165
|
+
|
|
166
|
+
_client(handler, headers={"x-treg-end-user": "cust_A"}).for_end_user("cust_B").call(
|
|
167
|
+
"x.y", headers={"X-TREG-END-USER": "cust_C"})
|
|
168
|
+
assert seen[0].headers.get_list("x-treg-end-user") == ["cust_B"]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def test_a_binary_answer_keeps_its_bytes():
|
|
172
|
+
audio = b"\xff\xfb\x00\x80"
|
|
173
|
+
r = _client(lambda request: httpx.Response(
|
|
174
|
+
200, content=audio, headers={"content-type": "audio/mpeg"})).call("x.tts")
|
|
175
|
+
assert r.data == audio
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def test_a_missing_end_user_raises_instead_of_calling_as_the_team():
|
|
179
|
+
seen = []
|
|
180
|
+
|
|
181
|
+
def handler(request):
|
|
182
|
+
seen.append(request)
|
|
183
|
+
return httpx.Response(200, json={})
|
|
184
|
+
|
|
185
|
+
treg = _client(handler)
|
|
186
|
+
for end_user in (None, "", " "):
|
|
187
|
+
with pytest.raises(ValueError):
|
|
188
|
+
treg.call("a.b", end_user=end_user)
|
|
189
|
+
with pytest.raises(ValueError):
|
|
190
|
+
treg.mcp_config(end_user=end_user)
|
|
191
|
+
assert seen == []
|
|
192
|
+
treg.call("a.b")
|
|
193
|
+
assert "x-treg-end-user" not in seen[0].headers
|
|
194
|
+
assert "X-Treg-End-User" not in treg.mcp_config()["headers"]
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
@pytest.mark.parametrize("target", [
|
|
198
|
+
"", "/", "?x=1", ".", "..", "../orgs", "a/../../orgs", "a/./b", "%2e%2e/orgs", "a/%2E./../b",
|
|
199
|
+
"%252e%252e/orgs", "a%2f..%2f..%2forgs", "..\\orgs", "a\\..\\..\\orgs", ".\t./orgs", ".\n./orgs",
|
|
200
|
+
"a/.. ", "%2525252525252e",
|
|
201
|
+
])
|
|
202
|
+
def test_a_call_never_leaves_its_route(target):
|
|
203
|
+
with pytest.raises(ValueError):
|
|
204
|
+
_client(lambda request: pytest.fail("sent")).call(target)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@pytest.mark.parametrize("target", [
|
|
208
|
+
"google-search-console.sites", "acme/items/", "acme/a..b/...", "gsc/sites/https%3A%2F%2Fa.com%2F", "acme/x?up=../y",
|
|
209
|
+
])
|
|
210
|
+
def test_a_plain_target_is_sent_as_written(target):
|
|
211
|
+
sent = _client(lambda request: httpx.Response(200, text=request.url.raw_path.decode())).call(target)
|
|
212
|
+
assert sent.data == "/call/" + target
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def test_a_query_in_the_target_is_kept():
|
|
216
|
+
treg = _client(lambda request: httpx.Response(200, json=request.url.params.multi_items()))
|
|
217
|
+
assert treg.call("tool?x=1").data == [["x", "1"]]
|
|
218
|
+
assert treg.call("tool?x=1#top", params={"x": "a b", "y": 2}).data == [["x", "1"], ["x", "a b"], ["y", "2"]]
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@pytest.mark.parametrize("bad", [".", "..", ""])
|
|
222
|
+
def test_an_id_of_dots_or_no_id_is_refused(bad):
|
|
223
|
+
treg = _client(lambda request: pytest.fail("sent"))
|
|
224
|
+
for use in (treg.end_users.get, treg.end_users.remove, lambda i: treg.end_users.connect(i, "x"),
|
|
225
|
+
lambda i: treg.end_users.disconnect("cust_1", i), treg.catalog.get, treg.calls.get, treg.calls.result):
|
|
226
|
+
with pytest.raises(ValueError):
|
|
227
|
+
use(bad)
|