open-agent-docs 0.3.0__py3-none-any.whl

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,335 @@
1
+ """事件流(SSE):工作区事件(workspaces.events)和 Agent 的通知(agent.notifications.stream)。
2
+
3
+ ```python
4
+ with client.workspaces.events(ws) as events: # 进 with 就连上了:之后发生的事件不会漏
5
+ for ev in events: # ev.name、ev.id、ev.data(按事件名解析成模型)
6
+ if ev.name == "page.created":
7
+ print(ev.data.title)
8
+
9
+ async with aclient.workspaces.events(ws) as events:
10
+ async for ev in events: ...
11
+ ```
12
+
13
+ - 标准 SSE:event、data(多行拼起来)、id;冒号开头的是心跳
14
+ - 断了自动重连:1 秒起翻倍、最多 30 秒,带 Last-Event-ID;连上后重置。401、403、404 不重连,抛错
15
+ - resync 事件照常给(意思是“落下了,重新拉一遍”)
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import json
21
+ import threading
22
+ from typing import Any, AsyncIterator, Awaitable, Callable, Dict, Iterator, List, Optional, cast
23
+
24
+ import httpx
25
+ import pydantic
26
+
27
+ from ._errors import APIConnectionError, APIError
28
+ from ._generated.models import EVENT_MODELS, AgentNotification
29
+
30
+ __all__ = ["Event", "EventStream", "AsyncEventStream", "SSEDecoder", "parse_event_data"]
31
+
32
+ RECONNECT_INITIAL = 1.0
33
+ """第一次重连等几秒(之后翻倍)"""
34
+ RECONNECT_MAX = 30.0
35
+ FATAL_STATUS = (401, 403, 404)
36
+
37
+
38
+ class Event:
39
+ """一条事件。data 按事件名解析成模型(page.created → Page……),不认识的给原始 JSON。"""
40
+
41
+ __slots__ = ("name", "id", "data", "raw")
42
+
43
+ def __init__(self, name: str, data: Any, id: Optional[str] = None, raw: str = "") -> None:
44
+ self.name = name
45
+ """事件名(event: 那一行,没有就是 message)"""
46
+ self.data = data
47
+ self.id = id
48
+ """事件的 id(Agent 的流里是通知编号)"""
49
+ self.raw = raw
50
+ """data 的原文"""
51
+
52
+ def __repr__(self) -> str:
53
+ return f"Event(name={self.name!r}, id={self.id!r}, data={self.data!r})"
54
+
55
+
56
+ def parse_event_data(kind: str, name: str, raw: str) -> Any:
57
+ """事件的 data → 模型(不是 JSON 给字符串,对不上模型给原始 JSON)"""
58
+ try:
59
+ data: Any = json.loads(raw) if raw else None
60
+ except ValueError:
61
+ return raw
62
+ model = AgentNotification if kind == "agent" else EVENT_MODELS.get(name)
63
+ if model is None or not isinstance(data, dict):
64
+ return data
65
+ obj = cast(Dict[str, Any], data)
66
+ try:
67
+ return model.model_validate(obj)
68
+ except pydantic.ValidationError:
69
+ return obj
70
+
71
+
72
+ class SSEDecoder:
73
+ """一行一行喂进来,攒够一条(空行)吐一条 (name, data, id)。"""
74
+
75
+ def __init__(self) -> None:
76
+ self._name = ""
77
+ self._data: List[str] = []
78
+ self._id: Optional[str] = None
79
+ self.last_id: Optional[str] = None
80
+ """最近一条带 id 的事件的 id(重连时带成 Last-Event-ID)"""
81
+
82
+ def feed(self, line: str) -> "Optional[tuple[str, str, Optional[str]]]":
83
+ line = line.rstrip("\r\n")
84
+ if line == "":
85
+ if self._id is not None:
86
+ self.last_id = self._id
87
+ out = None
88
+ if self._data:
89
+ out = (self._name or "message", "\n".join(self._data), self._id if self._id is not None else self.last_id)
90
+ self._name, self._data, self._id = "", [], None
91
+ return out
92
+ if line.startswith(":"):
93
+ return None # 心跳
94
+ k, sep, v = line.partition(":")
95
+ if sep and v.startswith(" "):
96
+ v = v[1:]
97
+ if k == "event":
98
+ self._name = v
99
+ elif k == "data":
100
+ self._data.append(v)
101
+ elif k == "id":
102
+ if "\0" not in v:
103
+ self._id = v
104
+ # retry 和别的字段:不管
105
+ return None
106
+
107
+
108
+ class _Lines:
109
+ """文本块 → 行(\\n、\\r\\n、\\r 都算行尾);没完的那段留到下一块"""
110
+
111
+ def __init__(self) -> None:
112
+ self._buf = ""
113
+
114
+ def feed(self, chunk: str) -> List[str]:
115
+ buf = self._buf + chunk
116
+ out: List[str] = []
117
+ start = 0
118
+ i = 0
119
+ n = len(buf)
120
+ while i < n:
121
+ ch = buf[i]
122
+ if ch == "\n":
123
+ out.append(buf[start:i])
124
+ start = i = i + 1
125
+ elif ch == "\r":
126
+ if i + 1 == n:
127
+ break # 可能是 \r\n:等下一块
128
+ out.append(buf[start:i])
129
+ i += 2 if buf[i + 1] == "\n" else 1
130
+ start = i
131
+ else:
132
+ i += 1
133
+ self._buf = buf[start:]
134
+ return out
135
+
136
+ def flush(self) -> List[str]:
137
+ rest, self._buf = self._buf, ""
138
+ return [rest.rstrip("\r")] if rest else []
139
+
140
+
141
+ def _is_fatal(e: BaseException) -> bool:
142
+ return isinstance(e, APIError) and e.status in FATAL_STATUS
143
+
144
+
145
+ class _Base:
146
+ def __init__(self, kind: str) -> None:
147
+ self._kind = kind
148
+ self._decoder = SSEDecoder()
149
+ self._closed = False
150
+ # 下次连之前要不要先等(连失败过、或者断过)
151
+ self._wait_first = False
152
+
153
+ @property
154
+ def last_event_id(self) -> Optional[str]:
155
+ """最近收到的事件 id(断了重连从这里接着收)"""
156
+ return self._decoder.last_id
157
+
158
+ @property
159
+ def closed(self) -> bool:
160
+ return self._closed
161
+
162
+ def _event(self, got: "tuple[str, str, Optional[str]]") -> Event:
163
+ name, raw, eid = got
164
+ return Event(name, parse_event_data(self._kind, name, raw), eid, raw)
165
+
166
+
167
+ class EventStream(_Base):
168
+ """同步的事件流:迭代器 + 上下文管理器。"""
169
+
170
+ def __init__(self, connect: Callable[[Optional[str]], httpx.Response], kind: str) -> None:
171
+ super().__init__(kind)
172
+ self._connect = connect
173
+ self._response: Optional[httpx.Response] = None
174
+ self._stop = threading.Event()
175
+ self._gen: Optional[Iterator[Event]] = None
176
+
177
+ def connect(self) -> "EventStream":
178
+ """现在就连上(进 with 时自动调);连不上的话迭代时接着重连,401 / 403 / 404 直接抛。"""
179
+ if self._response is None and not self._closed:
180
+ try:
181
+ self._response = self._connect(self.last_event_id)
182
+ except (APIError, APIConnectionError) as e:
183
+ if _is_fatal(e):
184
+ raise
185
+ self._wait_first = True
186
+ return self
187
+
188
+ def __enter__(self) -> "EventStream":
189
+ return self.connect()
190
+
191
+ def __exit__(self, *exc: object) -> None:
192
+ self.close()
193
+
194
+ def __iter__(self) -> Iterator[Event]:
195
+ return self
196
+
197
+ def __next__(self) -> Event:
198
+ if self._gen is None:
199
+ self._gen = self._run()
200
+ return next(self._gen)
201
+
202
+ def _run(self) -> Iterator[Event]:
203
+ backoff = RECONNECT_INITIAL
204
+ while not self._closed:
205
+ if self._response is None:
206
+ if self._wait_first:
207
+ if self._stop.wait(backoff):
208
+ return
209
+ backoff = min(RECONNECT_MAX, backoff * 2)
210
+ try:
211
+ self._response = self._connect(self.last_event_id)
212
+ except (APIError, APIConnectionError) as e:
213
+ if _is_fatal(e):
214
+ raise
215
+ self._wait_first = True
216
+ continue
217
+ # 连上了:等待时间重置;之后断了要先等一下再连
218
+ backoff = RECONNECT_INITIAL
219
+ self._wait_first = True
220
+ resp = self._response
221
+ lines = _Lines()
222
+ try:
223
+ for chunk in resp.iter_text():
224
+ for line in lines.feed(chunk):
225
+ got = self._decoder.feed(line)
226
+ if got is not None:
227
+ yield self._event(got)
228
+ if self._closed:
229
+ return
230
+ except (httpx.TransportError, httpx.StreamError):
231
+ pass # 断了:重连
232
+ finally:
233
+ resp.close()
234
+ self._response = None
235
+
236
+ def close(self) -> None:
237
+ """关掉(别的线程里调也行)"""
238
+ self._closed = True
239
+ self._stop.set()
240
+ if self._response is not None:
241
+ try:
242
+ self._response.close()
243
+ except Exception: # noqa: BLE001
244
+ pass
245
+
246
+
247
+ class AsyncEventStream(_Base):
248
+ """异步的事件流:async 迭代器 + async 上下文管理器。"""
249
+
250
+ def __init__(self, connect: Callable[[Optional[str]], Awaitable[httpx.Response]], kind: str) -> None:
251
+ super().__init__(kind)
252
+ self._connect = connect
253
+ self._response: Optional[httpx.Response] = None
254
+ self._gen: Optional[AsyncIterator[Event]] = None
255
+ self._stop: Optional[asyncio.Event] = None
256
+
257
+ async def connect(self) -> "AsyncEventStream":
258
+ """现在就连上(进 async with 时自动调)"""
259
+ if self._response is None and not self._closed:
260
+ try:
261
+ self._response = await self._connect(self.last_event_id)
262
+ except (APIError, APIConnectionError) as e:
263
+ if _is_fatal(e):
264
+ raise
265
+ self._wait_first = True
266
+ return self
267
+
268
+ async def __aenter__(self) -> "AsyncEventStream":
269
+ return await self.connect()
270
+
271
+ async def __aexit__(self, *exc: object) -> None:
272
+ await self.close()
273
+
274
+ def __aiter__(self) -> AsyncIterator[Event]:
275
+ return self
276
+
277
+ async def __anext__(self) -> Event:
278
+ if self._gen is None:
279
+ self._gen = self._run()
280
+ return await self._gen.__anext__()
281
+
282
+ async def _sleep(self, s: float) -> bool:
283
+ """等 s 秒;中间关了返回 True"""
284
+ if self._stop is None:
285
+ self._stop = asyncio.Event()
286
+ if self._closed:
287
+ return True
288
+ try:
289
+ await asyncio.wait_for(self._stop.wait(), s)
290
+ return True
291
+ except asyncio.TimeoutError:
292
+ return self._closed
293
+
294
+ async def _run(self) -> AsyncIterator[Event]:
295
+ backoff = RECONNECT_INITIAL
296
+ while not self._closed:
297
+ if self._response is None:
298
+ if self._wait_first:
299
+ if await self._sleep(backoff):
300
+ return
301
+ backoff = min(RECONNECT_MAX, backoff * 2)
302
+ try:
303
+ self._response = await self._connect(self.last_event_id)
304
+ except (APIError, APIConnectionError) as e:
305
+ if _is_fatal(e):
306
+ raise
307
+ self._wait_first = True
308
+ continue
309
+ backoff = RECONNECT_INITIAL
310
+ self._wait_first = True
311
+ resp = self._response
312
+ lines = _Lines()
313
+ try:
314
+ async for chunk in resp.aiter_text():
315
+ for line in lines.feed(chunk):
316
+ got = self._decoder.feed(line)
317
+ if got is not None:
318
+ yield self._event(got)
319
+ if self._closed:
320
+ return
321
+ except (httpx.TransportError, httpx.StreamError):
322
+ pass
323
+ finally:
324
+ await resp.aclose()
325
+ self._response = None
326
+
327
+ async def close(self) -> None:
328
+ self._closed = True
329
+ if self._stop is not None:
330
+ self._stop.set()
331
+ if self._response is not None:
332
+ try:
333
+ await self._response.aclose()
334
+ except Exception: # noqa: BLE001
335
+ pass
@@ -0,0 +1,35 @@
1
+ """NOT_GIVEN 哨兵:区分“没给”(不发这个字段)和 None(发 null)。"""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Optional
5
+
6
+ __all__ = ["NotGiven", "NOT_GIVEN"]
7
+
8
+
9
+ class NotGiven:
10
+ """没给。可选参数的默认值:不发这个字段;要发 null 就明确传 None。
11
+
12
+ ```python
13
+ client.pages.update(pid, after=None) # 发 {"after": null}:放到最前
14
+ client.pages.update(pid, title="新") # 只发 title
15
+ ```
16
+ """
17
+
18
+ _instance: Optional["NotGiven"] = None
19
+
20
+ def __new__(cls) -> "NotGiven":
21
+ if cls._instance is None:
22
+ cls._instance = super().__new__(cls)
23
+ return cls._instance
24
+
25
+ def __bool__(self) -> bool:
26
+ return False
27
+
28
+ def __repr__(self) -> str:
29
+ return "NOT_GIVEN"
30
+
31
+ def __reduce__(self) -> Any:
32
+ return "NOT_GIVEN"
33
+
34
+
35
+ NOT_GIVEN = NotGiven()
@@ -0,0 +1,15 @@
1
+ from __future__ import annotations
2
+
3
+ from urllib.parse import quote
4
+
5
+ __all__ = ["quote_path", "encode_uri_component"]
6
+
7
+
8
+ def quote_path(v: object) -> str:
9
+ """路径里的一段:全都百分号编码(/ 也编)。"""
10
+ return quote(str(v), safe="")
11
+
12
+
13
+ def encode_uri_component(s: str) -> str:
14
+ """和 JS 的 encodeURIComponent 一样(UTF-8,A-Z a-z 0-9 - _ . ! ~ * ' ( ) 不编)。"""
15
+ return quote(s, safe="-_.!~*'()")
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"
@@ -0,0 +1,85 @@
1
+ """webhook 验签:服务器 POST 给 Agent 的通知带 X-OAD-Timestamp(毫秒)和
2
+ X-OAD-Signature: sha256=<hex(HMAC-SHA256(secret, "<时间戳>.<正文>"))>。"""
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ import re
9
+ import time
10
+ from typing import Any, Iterable, Mapping, Optional, Tuple, Union, cast
11
+
12
+ import pydantic
13
+
14
+ from ._errors import WebhookVerificationError
15
+ from ._generated.models import AgentNotification
16
+
17
+ __all__ = ["verify_webhook"]
18
+
19
+ _SIG = re.compile(r"sha256=([0-9a-fA-F]{64})")
20
+
21
+ Headers = Union[Mapping[str, str], Iterable[Tuple[str, str]]]
22
+
23
+
24
+ def _header(headers: Headers, name: str) -> Optional[str]:
25
+ items: Iterable[Tuple[str, str]]
26
+ if isinstance(headers, Mapping):
27
+ m = cast(Mapping[str, str], headers)
28
+ # Starlette、Flask、httpx 的头本身就不分大小写;普通 dict 这里自己找
29
+ try:
30
+ v = m.get(name)
31
+ except Exception: # noqa: BLE001
32
+ v = None
33
+ if v is not None:
34
+ return v
35
+ items = m.items()
36
+ else:
37
+ items = headers
38
+ for k, v in items:
39
+ if k.lower() == name:
40
+ return v
41
+ return None
42
+
43
+
44
+ def verify_webhook(
45
+ secret: str,
46
+ headers: Headers,
47
+ body: Union[bytes, str],
48
+ tolerance: float = 300,
49
+ now: Optional[float] = None,
50
+ ) -> AgentNotification:
51
+ """验 webhook 的签名,对了返回解析好的 AgentNotification;不对抛 WebhookVerificationError(kind 是
52
+ signature / stale / malformed)。
53
+
54
+ - headers:请求头(任意映射,名字大小写不论);body:原始字节(用框架给的原始正文,别解析了再序列化)
55
+ - 时间戳和现在差超过 tolerance 秒(前后都算)算 stale,防重放
56
+ - now:“现在”(秒,像 time.time()),测试用
57
+ """
58
+ ts = _header(headers, "x-oad-timestamp")
59
+ sig = _header(headers, "x-oad-signature")
60
+ if ts is None or sig is None:
61
+ raise WebhookVerificationError("malformed", "缺 X-OAD-Timestamp 或 X-OAD-Signature 头")
62
+ ts = ts.strip()
63
+ if not re.fullmatch(r"-?[0-9]+", ts):
64
+ raise WebhookVerificationError("malformed", "X-OAD-Timestamp 不是整数(毫秒)")
65
+ m = _SIG.fullmatch(sig.strip())
66
+ if not m:
67
+ raise WebhookVerificationError("malformed", "X-OAD-Signature 应该是 sha256=<64 位十六进制>")
68
+ raw = body.encode("utf-8") if isinstance(body, str) else bytes(body)
69
+ want = hmac.new(secret.encode("utf-8"), ts.encode("ascii") + b"." + raw, hashlib.sha256).hexdigest()
70
+ if not hmac.compare_digest(want, m.group(1).lower()):
71
+ raise WebhookVerificationError("signature", "签名不对(密钥不对,或者正文被改过)")
72
+ now_s = time.time() if now is None else now
73
+ if abs(now_s - int(ts) / 1000.0) > tolerance:
74
+ raise WebhookVerificationError("stale", f"时间戳和现在差了超过 {tolerance:g} 秒")
75
+ try:
76
+ data: Any = json.loads(raw)
77
+ except ValueError as e:
78
+ raise WebhookVerificationError("malformed", "正文不是 JSON") from e
79
+ try:
80
+ return AgentNotification.model_validate(data)
81
+ except pydantic.ValidationError:
82
+ # 签名是对的:内容就是服务器发的。缺字段(老服务器、测试用的小正文)也照样给出来,不认的字段留着
83
+ if isinstance(data, dict):
84
+ return AgentNotification.model_construct(**data) # pyright: ignore[reportUnknownArgumentType]
85
+ raise WebhookVerificationError("malformed", "正文不是 JSON 对象") from None
File without changes
@@ -0,0 +1,3 @@
1
+ """接口的模型(生成的)。`oad.Page` 和 `oad.types.Page` 是同一个。"""
2
+ from ._generated.models import * # noqa: F403
3
+ from ._generated.models import __all__ as __all__ # noqa: PLC0414