open-agent-docs 0.3.0__tar.gz → 0.3.1__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 (26) hide show
  1. open_agent_docs-0.3.1/PKG-INFO +274 -0
  2. open_agent_docs-0.3.0/README.en.md → open_agent_docs-0.3.1/README.md +4 -4
  3. open_agent_docs-0.3.0/README.md → open_agent_docs-0.3.1/README.zh-CN.md +4 -4
  4. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/pyproject.toml +7 -5
  5. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_generated/models.py +4 -0
  6. open_agent_docs-0.3.1/src/open_agent_docs/_version.py +1 -0
  7. open_agent_docs-0.3.0/PKG-INFO +0 -266
  8. open_agent_docs-0.3.0/src/open_agent_docs/_version.py +0 -1
  9. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/.gitignore +0 -0
  10. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/__init__.py +0 -0
  11. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_base_client.py +0 -0
  12. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_client.py +0 -0
  13. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_embed.py +0 -0
  14. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_errors.py +0 -0
  15. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_files.py +0 -0
  16. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_generated/__init__.py +0 -0
  17. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_generated/resources.py +0 -0
  18. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_models.py +0 -0
  19. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_pagination.py +0 -0
  20. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_server.py +0 -0
  21. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_sse.py +0 -0
  22. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_types.py +0 -0
  23. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_utils.py +0 -0
  24. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/_webhook.py +0 -0
  25. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/py.typed +0 -0
  26. {open_agent_docs-0.3.0 → open_agent_docs-0.3.1}/src/open_agent_docs/types.py +0 -0
@@ -0,0 +1,274 @@
1
+ Metadata-Version: 2.5
2
+ Name: open-agent-docs
3
+ Version: 0.3.1
4
+ Summary: Python SDK for Open Agent Docs: sync and async clients, event streams, webhook verification, JWT signing, local server launcher
5
+ Project-URL: Homepage, https://github.com/kadaliao/open-agent-docs
6
+ Project-URL: Source, https://github.com/kadaliao/open-agent-docs/tree/main/sdks/python
7
+ Project-URL: Documentation, https://github.com/kadaliao/open-agent-docs/blob/main/sdks/python/README.md
8
+ Project-URL: 简体中文 (Chinese), https://github.com/kadaliao/open-agent-docs/blob/main/sdks/python/README.zh-CN.md
9
+ License-Expression: MIT
10
+ Classifier: Framework :: AsyncIO
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.9
15
+ Requires-Dist: httpx>=0.27
16
+ Requires-Dist: pydantic>=2
17
+ Provides-Extra: server
18
+ Requires-Dist: open-agent-docs-server==0.3.1; extra == 'server'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # open-agent-docs (Python SDK)
22
+
23
+ English | [简体中文](https://github.com/kadaliao/open-agent-docs/blob/main/sdks/python/README.zh-CN.md)
24
+
25
+ The Python client for [Open Agent Docs](https://github.com/kadaliao/open-agent-docs): sync and async clients with the same methods,
26
+ pydantic v2 models, event streams, webhook verification, JWT signing, embed URLs and a local server launcher.
27
+ Dependencies: just `httpx` and `pydantic`. Python 3.9+.
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ pip install open-agent-docs
33
+ pip install "open-agent-docs[server]" # plus the in-process server (oad.start() won't need to download a binary)
34
+ ```
35
+
36
+ ## Create a client
37
+
38
+ ```python
39
+ import open_agent_docs as oad
40
+
41
+ client = oad.Client(base_url="https://docs.example.com", token="oad_…")
42
+ client = oad.Client() # reads OAD_BASE_URL (default http://127.0.0.1:8848) and OAD_TOKEN
43
+ ```
44
+
45
+ `token` can be an agent token (`oad_…`), a session token, or a JWT signed by the host when the server runs with `OAD_AUTH=jwt`. Other options:
46
+
47
+ | Option | Default | Meaning |
48
+ | --- | --- | --- |
49
+ | `timeout` | 60 | Per-request timeout in seconds; event streams only use it for connecting |
50
+ | `max_retries` | 2 | Retries on 429, 502/503/504 and connection failures (POST/PATCH aren't retried on 5xx) |
51
+ | `locale` | none | `zh` / `en`: language of server error messages |
52
+ | `headers` | none | Extra headers on every request |
53
+ | `header_secret` / `jwt_secret` | none | Calling on behalf of users, see below |
54
+ | `jwt_issuer`, `jwt_audience`, `jwt_ttl` | none, none, 3600 | Put into the JWT that `with_user` signs |
55
+ | `http_client` | none | Your own `httpx.Client` (proxies, certificates…) |
56
+
57
+ Method names map one-to-one to the API (see the dotted names in [sdks/operations.json](https://github.com/kadaliao/open-agent-docs/blob/main/sdks/operations.json)): `client.pages.versions.list(...)`,
58
+ `client.me.get()`, `client.search(ws, q=...)`… Path parameters are positional, everything else is keyword-only.
59
+
60
+ ## Create a page and write Markdown
61
+
62
+ ```python
63
+ ws = client.default_workspace() # first workspace in /me (fetched once per client)
64
+ page = client.pages.create(ws, title="Weekly", markdown="# This week\n\n- Shipped the Python SDK") # creates, then writes the body
65
+
66
+ content = client.pages.content.get(page.id) # content.markdown, content.version
67
+ client.pages.content.replace(page.id, markdown=content.markdown + "\nMore", base=content.version)
68
+ client.pages.update(page.id, title="Week 47")
69
+ client.pages.update(page.id, after=None) # explicitly send null: move to the top
70
+ for p in client.pages.list(ws):
71
+ print(p.id, p.title)
72
+ ```
73
+
74
+ Optional arguments you leave out aren't sent; pass `None` to send `null` (`oad.NOT_GIVEN` means "not given").
75
+
76
+ Paginated endpoints (`pages.versions.list`, `me.notifications.list`, `trash.list`…) return an `oad.CursorPage`; iterating it walks every page:
77
+
78
+ ```python
79
+ page = client.pages.versions.list(page_id, limit=20)
80
+ page.items, page.next_cursor, page.has_next_page() # this page
81
+ for v in page: # follows the cursor automatically
82
+ print(v.id, v.label)
83
+ ```
84
+
85
+ Uploads and downloads:
86
+
87
+ ```python
88
+ f = client.files.upload(ws, b"hello", "a.txt") # also a pathlib.Path, an open file, or (name, bytes, type)
89
+ data = client.files.download(f.id) # bytes
90
+ db = client.databases.import_csv(ws, "name,qty\napple,3\n", title="Fruit")
91
+ ```
92
+
93
+ ## Async
94
+
95
+ ```python
96
+ async with oad.AsyncClient() as client:
97
+ ws = await client.default_workspace()
98
+ page = await client.pages.create(ws, title="Weekly")
99
+ async for v in client.pages.versions.list(page.id): # pagination: async for directly (await it for one page)
100
+ ...
101
+ ```
102
+
103
+ ## Calling on behalf of a user (host backends)
104
+
105
+ The host does its own login; its backend calls Open Agent Docs as the current user. Run the server with `OAD_AUTH=header` + `OAD_HEADER_SECRET`,
106
+ or `OAD_AUTH=jwt` + `OAD_JWT_SECRET`:
107
+
108
+ ```python
109
+ admin = oad.Client(base_url=..., header_secret=SECRET) # or jwt_secret=SECRET
110
+ u = admin.with_user("u-42", name="Ming Wang", email="x@example.com")
111
+ u.pages.list(u.default_workspace())
112
+ ```
113
+
114
+ `with_user` returns a new client (sharing the connection pool and settings); the original is unchanged. Header mode sends `X-OAD-Secret`
115
+ and `X-OAD-User-Id / -Name / -Email`; JWT mode signs an HS256 JWT (cached until 60 seconds before it expires), and `workspaces=["ws1"]`
116
+ or `[{"id": "ws1", "role": "viewer"}]` goes into the claims.
117
+
118
+ With FastAPI:
119
+
120
+ ```python
121
+ from fastapi import Depends, FastAPI, Request
122
+ import open_agent_docs as oad
123
+
124
+ app = FastAPI()
125
+ docs = oad.AsyncClient(base_url="http://127.0.0.1:8848", header_secret=SECRET) # one for the whole app
126
+
127
+ async def docs_for(request: Request) -> oad.AsyncClient:
128
+ user = await my_current_user(request) # the host's own login
129
+ return docs.with_user(user.id, name=user.name, email=user.email)
130
+
131
+ @app.post("/notes")
132
+ async def create_note(title: str, text: str, d: oad.AsyncClient = Depends(docs_for)):
133
+ page = await d.pages.create(await d.default_workspace(), title=title, markdown=text)
134
+ return {"id": page.id}
135
+ ```
136
+
137
+ Full example (in-process server, two users): [examples/python-inprocess](https://github.com/kadaliao/open-agent-docs/tree/main/examples/python-inprocess).
138
+
139
+ ## Embedding: sign a JWT, build the iframe URL
140
+
141
+ ```python
142
+ token = oad.sign_jwt(SECRET, "u-42", name="Ming Wang", workspaces=["ws1"], ttl=3600) # HS256, standard library only
143
+ url = oad.embed_url("https://docs.example.com", page_id, theme="dark", token=token)
144
+ # https://docs.example.com/p/<id>?embed=1&theme=dark#token=… (the token is after #: it never reaches server logs)
145
+ ```
146
+
147
+ For RS256 / ES256 use your own JWT library; claims: `sub`, `name`, `email`, `workspaces`, `iat`, `exp`, `iss`, `aud`.
148
+
149
+ ## Events
150
+
151
+ ```python
152
+ with client.workspaces.events(ws) as events: # connected once inside `with`: nothing after this is missed
153
+ for ev in events: # ev.name, ev.id, ev.data
154
+ if ev.name == "page.created":
155
+ print("new page", ev.data.title) # data is parsed by event name (Page…); unknown events give raw JSON
156
+ elif ev.name == "resync":
157
+ ... # fell behind: reload
158
+ ```
159
+
160
+ Reconnects automatically (1 s doubling up to 30 s, with `Last-Event-ID`); 401, 403 and 404 don't reconnect and raise.
161
+ `events.close()` from another thread stops it. Async: `async with client.workspaces.events(ws) as events: async for ev in events: ...`.
162
+
163
+ Agent notifications (fetch → handle → ack):
164
+
165
+ ```python
166
+ bot = oad.Client(token=AGENT_TOKEN)
167
+ with bot.agent.notifications.stream() as stream: # replays unacked ones, then pushes live; each data is an AgentNotification
168
+ for ev in stream:
169
+ note = ev.data
170
+ reply = handle(note.prompt) # prompt can be sent to your agent as a message
171
+ bot.threads.reply(note.thread_id, body=reply)
172
+ bot.agent.notifications.ack(ids=[note.id]) # ack after handling: unacked ones are replayed on reconnect
173
+ ```
174
+
175
+ Without a long-lived connection: `bot.agent.notifications.list(wait=30)` (long polling, returns one page).
176
+
177
+ ## Webhooks
178
+
179
+ When an agent has a webhook URL, the server POSTs notifications to it with `X-OAD-Timestamp` and `X-OAD-Signature`. Verify with the
180
+ `webhook_secret` you got when creating the agent:
181
+
182
+ ```python
183
+ note = oad.verify_webhook(WEBHOOK_SECRET, headers, raw_body) # returns an AgentNotification
184
+ # raises oad.WebhookVerificationError, e.kind is signature / stale / malformed; timestamps more than 300 s off are stale
185
+ ```
186
+
187
+ Always pass the raw body bytes (don't parse and re-serialize). FastAPI:
188
+
189
+ ```python
190
+ from fastapi import FastAPI, HTTPException, Request
191
+
192
+ @app.post("/oad-webhook")
193
+ async def webhook(request: Request):
194
+ try:
195
+ note = oad.verify_webhook(WEBHOOK_SECRET, request.headers, await request.body())
196
+ except oad.WebhookVerificationError as e:
197
+ raise HTTPException(401, e.kind)
198
+ background_tasks.add_task(handle, note) # answer 2xx quickly, do slow work in the background
199
+ return {"ok": True}
200
+ ```
201
+
202
+ Flask:
203
+
204
+ ```python
205
+ from flask import Flask, abort, request
206
+
207
+ @app.post("/oad-webhook")
208
+ def webhook():
209
+ try:
210
+ note = oad.verify_webhook(WEBHOOK_SECRET, request.headers, request.get_data())
211
+ except oad.WebhookVerificationError:
212
+ abort(401)
213
+ queue.put(note)
214
+ return {"ok": True}
215
+ ```
216
+
217
+ ## Run a server locally
218
+
219
+ ```python
220
+ with oad.start(data_dir="./data", auth="header", header_secret=SECRET) as server:
221
+ client = oad.Client(base_url=server.url, header_secret=SECRET)
222
+ ...
223
+ # stopped when leaving `with` (returns after pages are saved); or server = oad.start(...); ...; server.close()
224
+ ```
225
+
226
+ - Keyword arguments become environment variables: `data_dir` → `OAD_DATA_DIR`, `auth` → `OAD_AUTH`… (same as the command line, see
227
+ docs/en/configuration.md); without `port` a free port is picked.
228
+ - With `open-agent-docs[server]` installed it runs inside the Python process (Rust, its own threads, doesn't hold the GIL).
229
+ - Otherwise it runs the binary: `binary=` → `OAD_BINARY` → cache (`~/Library/Caches/open-agent-docs/v<version>/`,
230
+ `~/.cache/open-agent-docs/v<version>/`) → download from the GitHub release (checked against that release's `SHA256SUMS`).
231
+ macOS 11+ (arm64, x86_64) and Linux (x86_64, aarch64, glibc 2.34+: Ubuntu 22.04+, Debian 12+, RHEL 9+) are supported; use Docker on older systems and elsewhere ([system requirements](https://github.com/kadaliao/open-agent-docs/blob/main/docs/en/quickstart.md#system-requirements)). The `[server]` in-process server has the same requirements; on older Linux pip finds no wheel to install.
232
+
233
+ ## Errors
234
+
235
+ ```python
236
+ try:
237
+ client.pages.get("nope")
238
+ except oad.NotFoundError as e:
239
+ print(e.status, e.code, e.message) # 404 not_found …
240
+ except oad.RateLimitError as e:
241
+ time.sleep(e.retry_after or 1)
242
+ except oad.APIError as e: # any other server error: e.status, e.code, e.message, e.request_id
243
+ ...
244
+ except oad.APIConnectionError: # couldn't connect (oad.APITimeoutError for timeouts)
245
+ ...
246
+ ```
247
+
248
+ | Status | Class |
249
+ | --- | --- |
250
+ | 400 | `BadRequestError` |
251
+ | 401 | `AuthenticationError` |
252
+ | 403 | `PermissionDeniedError` |
253
+ | 404 | `NotFoundError` |
254
+ | 409 | `ConflictError` (e.g. a stale `base` version) |
255
+ | 410 | `GoneError` |
256
+ | 413 | `TooLargeError` |
257
+ | 429 | `RateLimitError` (`retry_after`) |
258
+ | 502 | `BadGatewayError` |
259
+ | other 5xx | `InternalServerError` (`BadGatewayError` is a subclass) |
260
+
261
+ Every error derives from `oad.OADError`; bad configuration raises `oad.ConfigurationError`.
262
+
263
+ ## Development
264
+
265
+ ```sh
266
+ cd sdks/python
267
+ uv venv .venv && uv pip install --python .venv/bin/python -e . pytest pytest-asyncio pyright
268
+ python codegen/generate.py # regenerate src/open_agent_docs/_generated/ after changing docs/openapi.json or sdks/operations.json
269
+ python codegen/generate.py --check # is the generated code up to date (tests/test_codegen.py checks too)
270
+ .venv/bin/python -m pytest # unit tests; with OAD_BINARY set also the scenario tests (tests/conformance, S1–S15)
271
+ .venv/bin/pyright # type check (strict)
272
+ ```
273
+
274
+ Models and resource classes are generated (don't edit them by hand); the hand-written runtime lives in `src/open_agent_docs/_*.py`.
@@ -1,6 +1,6 @@
1
1
  # open-agent-docs (Python SDK)
2
2
 
3
- [中文](README.md)
3
+ English | [简体中文](https://github.com/kadaliao/open-agent-docs/blob/main/sdks/python/README.zh-CN.md)
4
4
 
5
5
  The Python client for [Open Agent Docs](https://github.com/kadaliao/open-agent-docs): sync and async clients with the same methods,
6
6
  pydantic v2 models, event streams, webhook verification, JWT signing, embed URLs and a local server launcher.
@@ -34,7 +34,7 @@ client = oad.Client() # reads OAD_BASE_URL (default http://127.0.0.1:
34
34
  | `jwt_issuer`, `jwt_audience`, `jwt_ttl` | none, none, 3600 | Put into the JWT that `with_user` signs |
35
35
  | `http_client` | none | Your own `httpx.Client` (proxies, certificates…) |
36
36
 
37
- Method names map one-to-one to the API (see the dotted names in [sdks/operations.json](../operations.json)): `client.pages.versions.list(...)`,
37
+ Method names map one-to-one to the API (see the dotted names in [sdks/operations.json](https://github.com/kadaliao/open-agent-docs/blob/main/sdks/operations.json)): `client.pages.versions.list(...)`,
38
38
  `client.me.get()`, `client.search(ws, q=...)`… Path parameters are positional, everything else is keyword-only.
39
39
 
40
40
  ## Create a page and write Markdown
@@ -114,7 +114,7 @@ async def create_note(title: str, text: str, d: oad.AsyncClient = Depends(docs_f
114
114
  return {"id": page.id}
115
115
  ```
116
116
 
117
- Full example (in-process server, two users): [examples/python-inprocess](../../examples/python-inprocess).
117
+ Full example (in-process server, two users): [examples/python-inprocess](https://github.com/kadaliao/open-agent-docs/tree/main/examples/python-inprocess).
118
118
 
119
119
  ## Embedding: sign a JWT, build the iframe URL
120
120
 
@@ -208,7 +208,7 @@ with oad.start(data_dir="./data", auth="header", header_secret=SECRET) as server
208
208
  - With `open-agent-docs[server]` installed it runs inside the Python process (Rust, its own threads, doesn't hold the GIL).
209
209
  - Otherwise it runs the binary: `binary=` → `OAD_BINARY` → cache (`~/Library/Caches/open-agent-docs/v<version>/`,
210
210
  `~/.cache/open-agent-docs/v<version>/`) → download from the GitHub release (checked against that release's `SHA256SUMS`).
211
- macOS (arm64, x86_64) and Linux (x86_64, aarch64) are supported; use Docker elsewhere.
211
+ macOS 11+ (arm64, x86_64) and Linux (x86_64, aarch64, glibc 2.34+: Ubuntu 22.04+, Debian 12+, RHEL 9+) are supported; use Docker on older systems and elsewhere ([system requirements](https://github.com/kadaliao/open-agent-docs/blob/main/docs/en/quickstart.md#system-requirements)). The `[server]` in-process server has the same requirements; on older Linux pip finds no wheel to install.
212
212
 
213
213
  ## Errors
214
214
 
@@ -1,6 +1,6 @@
1
1
  # open-agent-docs(Python SDK)
2
2
 
3
- [English](README.en.md)
3
+ [English](https://github.com/kadaliao/open-agent-docs/blob/main/sdks/python/README.md) | 简体中文
4
4
 
5
5
  [Open Agent Docs](https://github.com/kadaliao/open-agent-docs) 的 Python 客户端:同步、异步两套一样的方法,模型是 pydantic v2,
6
6
  带事件流、webhook 验签、签 JWT、嵌入地址和本地起服务器。依赖只有 `httpx` 和 `pydantic`,Python 3.9 起。
@@ -33,7 +33,7 @@ client = oad.Client() # 读环境变量 OAD_BASE_URL(默认 http://
33
33
  | `jwt_issuer`、`jwt_audience`、`jwt_ttl` | 无、无、3600 | `with_user` 签 JWT 时写进去 |
34
34
  | `http_client` | 无 | 自己的 `httpx.Client`(代理、证书之类) |
35
35
 
36
- 方法名和接口一一对应(点路径见 [sdks/operations.json](../operations.json)):`client.pages.versions.list(...)`、`client.me.get()`、`client.search(ws, q=...)`……
36
+ 方法名和接口一一对应(点路径见 [sdks/operations.json](https://github.com/kadaliao/open-agent-docs/blob/main/sdks/operations.json)):`client.pages.versions.list(...)`、`client.me.get()`、`client.search(ws, q=...)`……
37
37
  路径参数按顺序是位置参数,别的都是关键字参数。
38
38
 
39
39
  ## 建页面、写 Markdown
@@ -111,7 +111,7 @@ async def create_note(title: str, text: str, d: oad.AsyncClient = Depends(docs_f
111
111
  return {"id": page.id}
112
112
  ```
113
113
 
114
- 完整的例子(进程内起服务器、两个用户):[examples/python-inprocess](../../examples/python-inprocess)。
114
+ 完整的例子(进程内起服务器、两个用户):[examples/python-inprocess](https://github.com/kadaliao/open-agent-docs/tree/main/examples/python-inprocess)。
115
115
 
116
116
  ## 嵌入:签 JWT、iframe 地址
117
117
 
@@ -202,7 +202,7 @@ with oad.start(data_dir="./data", auth="header", header_secret=SECRET) as server
202
202
  - 关键字参数转成环境变量:`data_dir` → `OAD_DATA_DIR`、`auth` → `OAD_AUTH`……(和命令行一样,见 docs/zh/configuration.md);不给 `port` 挑一个空端口。
203
203
  - 装了 `open-agent-docs[server]` 就在进程里跑(Rust,自己的线程,不占 GIL)。
204
204
  - 没装就跑二进制:`binary=` → 环境变量 `OAD_BINARY` → 缓存(`~/Library/Caches/open-agent-docs/v<版本>/`、`~/.cache/open-agent-docs/v<版本>/`)→
205
- 从 GitHub 发布页下载(用同一个 release 的 `SHA256SUMS` 校验)。支持 macOS(arm64、x86_64)和 Linux(x86_64、aarch64),别的平台用 Docker。
205
+ 从 GitHub 发布页下载(用同一个 release 的 `SHA256SUMS` 校验)。支持 macOS 11+(arm64、x86_64)和 Linux(x86_64、aarch64,glibc 2.34 起:Ubuntu 22.04+、Debian 12+、RHEL 9+),更老的系统和别的平台用 Docker,见[系统要求](https://github.com/kadaliao/open-agent-docs/blob/main/docs/zh/quickstart.md#系统要求)。`[server]` 的进程内服务器要求一样;更老的 Linux 上 pip 找不到能装的包。
206
206
 
207
207
  ## 错误
208
208
 
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "open-agent-docs"
7
- version = "0.3.0"
8
- description = "Open Agent Docs 的 Python SDK:同步 / 异步客户端、事件流、webhook 验签、JWT、本地起服务器"
7
+ version = "0.3.1"
8
+ description = "Python SDK for Open Agent Docs: sync and async clients, event streams, webhook verification, JWT signing, local server launcher"
9
9
  readme = "README.md"
10
10
  license = "MIT"
11
11
  requires-python = ">=3.9"
@@ -18,8 +18,8 @@ classifiers = [
18
18
  ]
19
19
 
20
20
  [project.optional-dependencies]
21
- # 进程内跑服务器(Rust,PyO3):oad.start() 就不用下载二进制了
22
- server = ["open-agent-docs-server==0.3.0"]
21
+ # the in-process server (Rust, PyO3): oad.start() then needs no binary download
22
+ server = ["open-agent-docs-server==0.3.1"]
23
23
 
24
24
  [dependency-groups]
25
25
  # 跑测试和类型检查用(uv run 默认带上)
@@ -28,12 +28,14 @@ dev = ["pytest>=8", "pytest-asyncio>=0.24", "pyright>=1.1.400"]
28
28
  [project.urls]
29
29
  Homepage = "https://github.com/kadaliao/open-agent-docs"
30
30
  Source = "https://github.com/kadaliao/open-agent-docs/tree/main/sdks/python"
31
+ Documentation = "https://github.com/kadaliao/open-agent-docs/blob/main/sdks/python/README.md"
32
+ "简体中文 (Chinese)" = "https://github.com/kadaliao/open-agent-docs/blob/main/sdks/python/README.zh-CN.md"
31
33
 
32
34
  [tool.hatch.build.targets.wheel]
33
35
  packages = ["src/open_agent_docs"]
34
36
 
35
37
  [tool.hatch.build.targets.sdist]
36
- include = ["src/open_agent_docs", "README.md", "README.en.md", "pyproject.toml"]
38
+ include = ["src/open_agent_docs", "README.md", "README.zh-CN.md", "pyproject.toml"]
37
39
 
38
40
  [tool.pytest.ini_options]
39
41
  testpaths = ["tests"]
@@ -247,6 +247,10 @@ class AuthConfigBody(BaseModel):
247
247
  """
248
248
  mode: AuthMode
249
249
  """登录方式:local(账号密码)/ header(宿主反代带身份头)/ none(不登录,单人)/ jwt(宿主签的 JWT)"""
250
+ needs_admin: Optional[bool] = None
251
+ """账号密码登录(local)而服务器上一个账号也没有:谁都登录不了,要先建管理员
252
+ (`open-agent-docs user add`,或设 `OAD_ADMIN_EMAIL` / `OAD_ADMIN_PASSWORD` 后重启)。旧版服务器没有这个字段
253
+ """
250
254
  signup: SignupMode
251
255
  timezone: str
252
256
  """服务器的时区(IANA 名字)"""
@@ -0,0 +1 @@
1
+ __version__ = "0.3.1"
@@ -1,266 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: open-agent-docs
3
- Version: 0.3.0
4
- Summary: Open Agent Docs 的 Python SDK:同步 / 异步客户端、事件流、webhook 验签、JWT、本地起服务器
5
- Project-URL: Homepage, https://github.com/kadaliao/open-agent-docs
6
- Project-URL: Source, https://github.com/kadaliao/open-agent-docs/tree/main/sdks/python
7
- License-Expression: MIT
8
- Classifier: Framework :: AsyncIO
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: Programming Language :: Python :: 3 :: Only
11
- Classifier: Typing :: Typed
12
- Requires-Python: >=3.9
13
- Requires-Dist: httpx>=0.27
14
- Requires-Dist: pydantic>=2
15
- Provides-Extra: server
16
- Requires-Dist: open-agent-docs-server==0.3.0; extra == 'server'
17
- Description-Content-Type: text/markdown
18
-
19
- # open-agent-docs(Python SDK)
20
-
21
- [English](README.en.md)
22
-
23
- [Open Agent Docs](https://github.com/kadaliao/open-agent-docs) 的 Python 客户端:同步、异步两套一样的方法,模型是 pydantic v2,
24
- 带事件流、webhook 验签、签 JWT、嵌入地址和本地起服务器。依赖只有 `httpx` 和 `pydantic`,Python 3.9 起。
25
-
26
- ## 安装
27
-
28
- ```sh
29
- pip install open-agent-docs
30
- pip install "open-agent-docs[server]" # 再加上进程内的服务器(oad.start() 就不用下载二进制了)
31
- ```
32
-
33
- ## 建客户端
34
-
35
- ```python
36
- import open_agent_docs as oad
37
-
38
- client = oad.Client(base_url="https://docs.example.com", token="oad_…")
39
- client = oad.Client() # 读环境变量 OAD_BASE_URL(默认 http://127.0.0.1:8848)、OAD_TOKEN
40
- ```
41
-
42
- `token` 可以是 Agent 的 token(`oad_…`)、登录后的会话令牌,或者 `OAD_AUTH=jwt` 时宿主签的 JWT。其它参数:
43
-
44
- | 参数 | 默认 | 说明 |
45
- | --- | --- | --- |
46
- | `timeout` | 60 | 单个请求的超时(秒);事件流只管连接 |
47
- | `max_retries` | 2 | 429、502/503/504、连不上时重试几次(POST、PATCH 遇到 5xx 不重试) |
48
- | `locale` | 无 | `zh` / `en`:服务器错误信息的语言 |
49
- | `headers` | 无 | 每个请求额外带的头 |
50
- | `header_secret` / `jwt_secret` | 无 | 替用户调,见下面 |
51
- | `jwt_issuer`、`jwt_audience`、`jwt_ttl` | 无、无、3600 | `with_user` 签 JWT 时写进去 |
52
- | `http_client` | 无 | 自己的 `httpx.Client`(代理、证书之类) |
53
-
54
- 方法名和接口一一对应(点路径见 [sdks/operations.json](../operations.json)):`client.pages.versions.list(...)`、`client.me.get()`、`client.search(ws, q=...)`……
55
- 路径参数按顺序是位置参数,别的都是关键字参数。
56
-
57
- ## 建页面、写 Markdown
58
-
59
- ```python
60
- ws = client.default_workspace() # /me 里的第一个工作区(每个客户端只取一次)
61
- page = client.pages.create(ws, title="周报", markdown="# 本周\n\n- 上线了 Python SDK") # 建完再写正文,两步
62
-
63
- content = client.pages.content.get(page.id) # content.markdown、content.version
64
- client.pages.content.replace(page.id, markdown=content.markdown + "\n更多", base=content.version)
65
- client.pages.update(page.id, title="第 47 周")
66
- client.pages.update(page.id, after=None) # 明确发 null:放到最前
67
- for p in client.pages.list(ws):
68
- print(p.id, p.title)
69
- ```
70
-
71
- 可选参数不传就不发;要发 `null` 就传 `None`(`oad.NOT_GIVEN` 是“没给”)。
72
-
73
- 翻页的接口(`pages.versions.list`、`me.notifications.list`、`trash.list`……)返回一页 `oad.CursorPage`,直接 `for` 就会逐条取完所有页:
74
-
75
- ```python
76
- page = client.pages.versions.list(page_id, limit=20)
77
- page.items, page.next_cursor, page.has_next_page() # 这一页
78
- for v in page: # 自动带 cursor 取后面的
79
- print(v.id, v.label)
80
- ```
81
-
82
- 上传、下载:
83
-
84
- ```python
85
- f = client.files.upload(ws, b"hello", "a.txt") # 也可以是 pathlib.Path、打开的文件、(文件名, bytes, 类型)
86
- data = client.files.download(f.id) # bytes
87
- db = client.databases.import_csv(ws, "名字,数量\n苹果,3\n", title="水果")
88
- ```
89
-
90
- ## 异步
91
-
92
- ```python
93
- async with oad.AsyncClient() as client:
94
- ws = await client.default_workspace()
95
- page = await client.pages.create(ws, title="周报")
96
- async for v in client.pages.versions.list(page.id): # 翻页:直接 async for(await 它拿第一页)
97
- ...
98
- ```
99
-
100
- ## 替用户调(宿主后端)
101
-
102
- 宿主自己做登录,后端以当前用户的身份调 Open Agent Docs。服务器配 `OAD_AUTH=header` + `OAD_HEADER_SECRET`,或者 `OAD_AUTH=jwt` + `OAD_JWT_SECRET`:
103
-
104
- ```python
105
- admin = oad.Client(base_url=..., header_secret=SECRET) # 或 jwt_secret=SECRET
106
- u = admin.with_user("u-42", name="王小明", email="x@example.com")
107
- u.pages.list(u.default_workspace())
108
- ```
109
-
110
- `with_user` 返回一个新的客户端(共享连接池和配置),原来的不变。header 模式带 `X-OAD-Secret`、`X-OAD-User-Id / -Name / -Email`;
111
- JWT 模式签一个 HS256 的 JWT(缓存到过期前 60 秒),`workspaces=["ws1"]` 或 `[{"id": "ws1", "role": "viewer"}]` 写进 claims。
112
-
113
- FastAPI 里:
114
-
115
- ```python
116
- from fastapi import Depends, FastAPI, Request
117
- import open_agent_docs as oad
118
-
119
- app = FastAPI()
120
- docs = oad.AsyncClient(base_url="http://127.0.0.1:8848", header_secret=SECRET) # 全局一个
121
-
122
- async def docs_for(request: Request) -> oad.AsyncClient:
123
- user = await my_current_user(request) # 宿主自己的登录
124
- return docs.with_user(user.id, name=user.name, email=user.email)
125
-
126
- @app.post("/notes")
127
- async def create_note(title: str, text: str, d: oad.AsyncClient = Depends(docs_for)):
128
- page = await d.pages.create(await d.default_workspace(), title=title, markdown=text)
129
- return {"id": page.id}
130
- ```
131
-
132
- 完整的例子(进程内起服务器、两个用户):[examples/python-inprocess](../../examples/python-inprocess)。
133
-
134
- ## 嵌入:签 JWT、iframe 地址
135
-
136
- ```python
137
- token = oad.sign_jwt(SECRET, "u-42", name="王小明", workspaces=["ws1"], ttl=3600) # HS256,只用标准库
138
- url = oad.embed_url("https://docs.example.com", page_id, theme="dark", token=token)
139
- # https://docs.example.com/p/<id>?embed=1&theme=dark#token=… (token 在 # 后面:不进服务器日志)
140
- ```
141
-
142
- 要 RS256 / ES256 的用自己的 JWT 库签,claims:`sub`、`name`、`email`、`workspaces`、`iat`、`exp`、`iss`、`aud`。
143
-
144
- ## 事件
145
-
146
- ```python
147
- with client.workspaces.events(ws) as events: # 进 with 就连上了:之后发生的事件不会漏
148
- for ev in events: # ev.name、ev.id、ev.data
149
- if ev.name == "page.created":
150
- print("新页面", ev.data.title) # data 按事件名解析成模型(Page……),不认识的给原始 JSON
151
- elif ev.name == "resync":
152
- ... # 落下了:重新拉一遍
153
- ```
154
-
155
- 断了自动重连(1 秒起翻倍、最多 30 秒,带 `Last-Event-ID`);401、403、404 不重连,直接抛错。别的线程里 `events.close()` 能让它停下。
156
- 异步版:`async with client.workspaces.events(ws) as events: async for ev in events: ...`。
157
-
158
- Agent 收通知(取 → 处理 → 确认):
159
-
160
- ```python
161
- bot = oad.Client(token=AGENT_TOKEN)
162
- with bot.agent.notifications.stream() as stream: # 先补发没确认的,再实时推;每条 data 是 AgentNotification
163
- for ev in stream:
164
- note = ev.data
165
- reply = handle(note.prompt) # prompt 可以直接当消息发给你的 Agent
166
- bot.threads.reply(note.thread_id, body=reply)
167
- bot.agent.notifications.ack(ids=[note.id]) # 处理完再确认:断了重连会补发没确认的
168
- ```
169
-
170
- 不想开长连接就轮询:`bot.agent.notifications.list(wait=30)`(长轮询,返回一页)。
171
-
172
- ## Webhook
173
-
174
- Agent 配了 webhook 地址时,服务器把通知 POST 过去,带 `X-OAD-Timestamp`、`X-OAD-Signature`。用建 Agent 时给的 `webhook_secret` 验:
175
-
176
- ```python
177
- note = oad.verify_webhook(WEBHOOK_SECRET, headers, raw_body) # 返回 AgentNotification
178
- # 不对抛 oad.WebhookVerificationError,e.kind 是 signature / stale / malformed;时间戳差超过 300 秒算 stale
179
- ```
180
-
181
- 一定用原始的正文字节(别解析了再序列化)。FastAPI:
182
-
183
- ```python
184
- from fastapi import FastAPI, HTTPException, Request
185
-
186
- @app.post("/oad-webhook")
187
- async def webhook(request: Request):
188
- try:
189
- note = oad.verify_webhook(WEBHOOK_SECRET, request.headers, await request.body())
190
- except oad.WebhookVerificationError as e:
191
- raise HTTPException(401, e.kind)
192
- background_tasks.add_task(handle, note) # 尽快回 2xx,慢活放后台
193
- return {"ok": True}
194
- ```
195
-
196
- Flask:
197
-
198
- ```python
199
- from flask import Flask, abort, request
200
-
201
- @app.post("/oad-webhook")
202
- def webhook():
203
- try:
204
- note = oad.verify_webhook(WEBHOOK_SECRET, request.headers, request.get_data())
205
- except oad.WebhookVerificationError:
206
- abort(401)
207
- queue.put(note)
208
- return {"ok": True}
209
- ```
210
-
211
- ## 本地起服务器
212
-
213
- ```python
214
- with oad.start(data_dir="./data", auth="header", header_secret=SECRET) as server:
215
- client = oad.Client(base_url=server.url, header_secret=SECRET)
216
- ...
217
- # 退出 with 时关掉(页面都存好再返回);或者 server = oad.start(...); ...; server.close()
218
- ```
219
-
220
- - 关键字参数转成环境变量:`data_dir` → `OAD_DATA_DIR`、`auth` → `OAD_AUTH`……(和命令行一样,见 docs/zh/configuration.md);不给 `port` 挑一个空端口。
221
- - 装了 `open-agent-docs[server]` 就在进程里跑(Rust,自己的线程,不占 GIL)。
222
- - 没装就跑二进制:`binary=` → 环境变量 `OAD_BINARY` → 缓存(`~/Library/Caches/open-agent-docs/v<版本>/`、`~/.cache/open-agent-docs/v<版本>/`)→
223
- 从 GitHub 发布页下载(用同一个 release 的 `SHA256SUMS` 校验)。支持 macOS(arm64、x86_64)和 Linux(x86_64、aarch64),别的平台用 Docker。
224
-
225
- ## 错误
226
-
227
- ```python
228
- try:
229
- client.pages.get("nope")
230
- except oad.NotFoundError as e:
231
- print(e.status, e.code, e.message) # 404 not_found 页面 nope 不存在
232
- except oad.RateLimitError as e:
233
- time.sleep(e.retry_after or 1)
234
- except oad.APIError as e: # 服务器回的别的错误:e.status、e.code、e.message、e.request_id
235
- ...
236
- except oad.APIConnectionError: # 连不上(oad.APITimeoutError 是超时)
237
- ...
238
- ```
239
-
240
- | 状态码 | 类 |
241
- | --- | --- |
242
- | 400 | `BadRequestError` |
243
- | 401 | `AuthenticationError` |
244
- | 403 | `PermissionDeniedError` |
245
- | 404 | `NotFoundError` |
246
- | 409 | `ConflictError`(比如 `base` 版本对不上) |
247
- | 410 | `GoneError` |
248
- | 413 | `TooLargeError` |
249
- | 429 | `RateLimitError`(`retry_after`) |
250
- | 502 | `BadGatewayError` |
251
- | 其它 5xx | `InternalServerError`(`BadGatewayError` 是它的子类) |
252
-
253
- 所有错误的基类是 `oad.OADError`;配置不对是 `oad.ConfigurationError`。
254
-
255
- ## 开发
256
-
257
- ```sh
258
- cd sdks/python
259
- uv venv .venv && uv pip install --python .venv/bin/python -e . pytest pytest-asyncio pyright
260
- python codegen/generate.py # 改了 docs/openapi.json 或 sdks/operations.json 后重新生成(src/open_agent_docs/_generated/)
261
- python codegen/generate.py --check # 生成的是不是最新的(tests/test_codegen.py 也会查)
262
- .venv/bin/python -m pytest # 单元测试;设了 OAD_BINARY 还跑场景测试(tests/conformance,S1–S15)
263
- .venv/bin/pyright # 类型检查(strict)
264
- ```
265
-
266
- 模型和资源类是生成的(别手改),手写的运行时在 `src/open_agent_docs/_*.py`。
@@ -1 +0,0 @@
1
- __version__ = "0.3.0"