agentos-sdk-python 1.0.0__py3-none-any.whl → 1.1.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.
- agentos_sdk/__init__.py +76 -0
- agentos_sdk/clients/__init__.py +4 -0
- agentos_sdk/clients/harnesskit.py +384 -0
- agentos_sdk/clients/modelkit.py +98 -1
- agentos_sdk/clients/notifykit.py +47 -0
- agentos_sdk/normalizers.py +44 -9
- agentos_sdk/protocol.py +409 -2
- agentos_sdk/sdk.py +250 -0
- agentos_sdk/transport.py +8 -2
- {agentos_sdk_python-1.0.0.dist-info → agentos_sdk_python-1.1.0.dist-info}/METADATA +241 -5
- agentos_sdk_python-1.1.0.dist-info/RECORD +23 -0
- {agentos_sdk_python-1.0.0.dist-info → agentos_sdk_python-1.1.0.dist-info}/WHEEL +1 -1
- agentos_sdk_python-1.0.0.dist-info/RECORD +0 -21
- {agentos_sdk_python-1.0.0.dist-info → agentos_sdk_python-1.1.0.dist-info}/licenses/LICENSE +0 -0
agentos_sdk/__init__.py
CHANGED
|
@@ -12,8 +12,46 @@ from .protocol import (
|
|
|
12
12
|
AppBundle,
|
|
13
13
|
AppEvent,
|
|
14
14
|
AppEventType,
|
|
15
|
+
AppModel,
|
|
16
|
+
AppModelCapabilities,
|
|
17
|
+
AppModelRegistration,
|
|
18
|
+
AppModelUpdate,
|
|
19
|
+
AppModelWriteResult,
|
|
20
|
+
DecisionAnswer,
|
|
21
|
+
DecisionChoiceQuestion,
|
|
22
|
+
DecisionNoulQuestion,
|
|
23
|
+
DecisionQuestion,
|
|
24
|
+
DecisionQuestionType,
|
|
25
|
+
DecisionRequest,
|
|
26
|
+
DecisionResponse,
|
|
27
|
+
DecisionScoreQuestion,
|
|
28
|
+
DecisionUsage,
|
|
29
|
+
HarnessKitCommand,
|
|
30
|
+
HarnessKitCommandReceipt,
|
|
31
|
+
HarnessKitEngineId,
|
|
32
|
+
HarnessKitEngineSwitchResult,
|
|
33
|
+
HarnessKitEvent,
|
|
34
|
+
HarnessKitHealth,
|
|
35
|
+
HarnessKitLlmConfig,
|
|
36
|
+
HarnessKitOperationalSnapshot,
|
|
37
|
+
HarnessKitRunAccepted,
|
|
38
|
+
HarnessKitRunError,
|
|
39
|
+
HarnessKitRunRequest,
|
|
40
|
+
HarnessKitRunResult,
|
|
41
|
+
HarnessKitRuntimeInfo,
|
|
42
|
+
HarnessKitRunUsage,
|
|
43
|
+
HarnessKitThreadDeleteResult,
|
|
44
|
+
HarnessKitThreadMessage,
|
|
45
|
+
HarnessKitThreadRenameResult,
|
|
46
|
+
HarnessKitThreadSnapshot,
|
|
15
47
|
HistoryTurnStatus,
|
|
16
48
|
HistoryTurnSummary,
|
|
49
|
+
Modality,
|
|
50
|
+
ModelTask,
|
|
51
|
+
NotifyKitEvent,
|
|
52
|
+
NotifyKitLevel,
|
|
53
|
+
NotifyKitNotification,
|
|
54
|
+
NotifyKitPublishResult,
|
|
17
55
|
OpenToolAvailability,
|
|
18
56
|
OpenToolProvisionFailure,
|
|
19
57
|
OpenToolProvisionSuccess,
|
|
@@ -44,10 +82,48 @@ __all__ = [
|
|
|
44
82
|
"AppBundle",
|
|
45
83
|
"AppEvent",
|
|
46
84
|
"AppEventType",
|
|
85
|
+
"AppModel",
|
|
86
|
+
"AppModelCapabilities",
|
|
87
|
+
"AppModelRegistration",
|
|
88
|
+
"AppModelUpdate",
|
|
89
|
+
"AppModelWriteResult",
|
|
90
|
+
"DecisionAnswer",
|
|
91
|
+
"DecisionChoiceQuestion",
|
|
92
|
+
"DecisionNoulQuestion",
|
|
93
|
+
"DecisionQuestion",
|
|
94
|
+
"DecisionQuestionType",
|
|
95
|
+
"DecisionRequest",
|
|
96
|
+
"DecisionResponse",
|
|
97
|
+
"DecisionScoreQuestion",
|
|
98
|
+
"DecisionUsage",
|
|
47
99
|
"EventType",
|
|
48
100
|
"FunctionCallLifecycleError",
|
|
101
|
+
"HarnessKitCommand",
|
|
102
|
+
"HarnessKitCommandReceipt",
|
|
103
|
+
"HarnessKitEngineId",
|
|
104
|
+
"HarnessKitEngineSwitchResult",
|
|
105
|
+
"HarnessKitEvent",
|
|
106
|
+
"HarnessKitHealth",
|
|
107
|
+
"HarnessKitLlmConfig",
|
|
108
|
+
"HarnessKitOperationalSnapshot",
|
|
109
|
+
"HarnessKitRunAccepted",
|
|
110
|
+
"HarnessKitRunError",
|
|
111
|
+
"HarnessKitRunRequest",
|
|
112
|
+
"HarnessKitRunResult",
|
|
113
|
+
"HarnessKitRunUsage",
|
|
114
|
+
"HarnessKitRuntimeInfo",
|
|
115
|
+
"HarnessKitThreadDeleteResult",
|
|
116
|
+
"HarnessKitThreadMessage",
|
|
117
|
+
"HarnessKitThreadRenameResult",
|
|
118
|
+
"HarnessKitThreadSnapshot",
|
|
49
119
|
"HistoryTurnStatus",
|
|
50
120
|
"HistoryTurnSummary",
|
|
121
|
+
"Modality",
|
|
122
|
+
"ModelTask",
|
|
123
|
+
"NotifyKitEvent",
|
|
124
|
+
"NotifyKitLevel",
|
|
125
|
+
"NotifyKitNotification",
|
|
126
|
+
"NotifyKitPublishResult",
|
|
51
127
|
"OpenToolAvailability",
|
|
52
128
|
"OpenToolProvisionFailure",
|
|
53
129
|
"OpenToolProvisionSuccess",
|
agentos_sdk/clients/__init__.py
CHANGED
|
@@ -3,7 +3,9 @@ from .appkit import AppKitClient
|
|
|
3
3
|
from .authkit import AuthKitClient
|
|
4
4
|
from .cronkit import CronKitClient
|
|
5
5
|
from .discoverykit import DiscoveryKitClient
|
|
6
|
+
from .harnesskit import HarnessKitClient
|
|
6
7
|
from .modelkit import ModelKitClient
|
|
8
|
+
from .notifykit import NotifyKitClient
|
|
7
9
|
from .systemkit import SystemKitClient
|
|
8
10
|
from .toolkit import ToolKitClient
|
|
9
11
|
from .transferkit import TransferKitClient
|
|
@@ -14,7 +16,9 @@ __all__ = [
|
|
|
14
16
|
"AuthKitClient",
|
|
15
17
|
"CronKitClient",
|
|
16
18
|
"DiscoveryKitClient",
|
|
19
|
+
"HarnessKitClient",
|
|
17
20
|
"ModelKitClient",
|
|
21
|
+
"NotifyKitClient",
|
|
18
22
|
"SystemKitClient",
|
|
19
23
|
"ToolKitClient",
|
|
20
24
|
"TransferKitClient",
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from collections.abc import AsyncGenerator, Awaitable, Callable, Mapping
|
|
6
|
+
from contextlib import aclosing
|
|
7
|
+
from typing import Any, cast
|
|
8
|
+
from urllib.parse import parse_qsl, quote, unquote, urlencode
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from agentos_sdk.protocol import (
|
|
13
|
+
HarnessKitCommandReceipt,
|
|
14
|
+
HarnessKitEngineId,
|
|
15
|
+
HarnessKitEngineSwitchResult,
|
|
16
|
+
HarnessKitEvent,
|
|
17
|
+
HarnessKitHealth,
|
|
18
|
+
HarnessKitOperationalSnapshot,
|
|
19
|
+
HarnessKitRunAccepted,
|
|
20
|
+
HarnessKitRunResult,
|
|
21
|
+
HarnessKitRuntimeInfo,
|
|
22
|
+
HarnessKitThreadDeleteResult,
|
|
23
|
+
HarnessKitThreadRenameResult,
|
|
24
|
+
HarnessKitThreadSnapshot,
|
|
25
|
+
)
|
|
26
|
+
from agentos_sdk.transport import ApiClient, ApiError, _clean_query, iter_sse
|
|
27
|
+
|
|
28
|
+
_URL_SCHEME = re.compile(r"^[a-z][a-z\d+.-]*://", re.IGNORECASE)
|
|
29
|
+
_MALFORMED_PERCENT = re.compile(r"%(?![0-9A-Fa-f]{2})")
|
|
30
|
+
_PATH_END = re.compile(r"[?#]")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class HarnessKitClient:
|
|
34
|
+
"""HTTP client for the authenticated AgentOS HarnessKit gateway (``/harnesskit/*``).
|
|
35
|
+
|
|
36
|
+
Every method takes the AppKit ``bearer_token`` explicitly; use
|
|
37
|
+
``AgentOSSDK.harnesskit`` to have it attached and refreshed automatically.
|
|
38
|
+
Request bodies and responses are plain dicts, so fields the Harness adds
|
|
39
|
+
later pass through untouched.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, api_client: ApiClient | None = None) -> None:
|
|
43
|
+
self.api_client = api_client or ApiClient()
|
|
44
|
+
|
|
45
|
+
async def health(self, bearer_token: str) -> HarnessKitHealth:
|
|
46
|
+
"""Check whether the Harness runtime is reachable (``GET /healthz``)."""
|
|
47
|
+
return await self.request(bearer_token, "/healthz")
|
|
48
|
+
|
|
49
|
+
async def get_runtime(self, bearer_token: str) -> HarnessKitRuntimeInfo:
|
|
50
|
+
"""Read the active Harness runtime engine (``GET /v1/runtime/harness-engine``)."""
|
|
51
|
+
return await self.request(bearer_token, "/v1/runtime/harness-engine")
|
|
52
|
+
|
|
53
|
+
async def switch_engine(
|
|
54
|
+
self, bearer_token: str, engine: HarnessKitEngineId
|
|
55
|
+
) -> HarnessKitEngineSwitchResult:
|
|
56
|
+
"""Request an engine switch (``POST /v1/runtime/harness-engine``)."""
|
|
57
|
+
return await self.request(
|
|
58
|
+
bearer_token,
|
|
59
|
+
"/v1/runtime/harness-engine",
|
|
60
|
+
method="POST",
|
|
61
|
+
data={"engine": engine},
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
async def list_threads(self, bearer_token: str) -> list[HarnessKitThreadSnapshot]:
|
|
65
|
+
"""List saved threads. An absent ``threads`` field yields an empty list."""
|
|
66
|
+
response = await self.request(bearer_token, "/v1/threads")
|
|
67
|
+
threads = response.get("threads") if isinstance(response, dict) else None
|
|
68
|
+
return threads if isinstance(threads, list) else []
|
|
69
|
+
|
|
70
|
+
async def get_thread(self, bearer_token: str, thread_id: str) -> HarnessKitThreadSnapshot:
|
|
71
|
+
"""Read one thread snapshot (``GET /v1/threads/{threadId}``)."""
|
|
72
|
+
return await self.request(bearer_token, _thread_path(thread_id))
|
|
73
|
+
|
|
74
|
+
async def rename_thread(
|
|
75
|
+
self, bearer_token: str, thread_id: str, title: str
|
|
76
|
+
) -> HarnessKitThreadRenameResult:
|
|
77
|
+
"""Set a thread title (``PATCH /v1/threads/{threadId}``)."""
|
|
78
|
+
return await self.request(
|
|
79
|
+
bearer_token,
|
|
80
|
+
_thread_path(thread_id),
|
|
81
|
+
method="PATCH",
|
|
82
|
+
data={"title": title},
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
async def delete_thread(
|
|
86
|
+
self, bearer_token: str, thread_id: str
|
|
87
|
+
) -> HarnessKitThreadDeleteResult:
|
|
88
|
+
"""Delete an idle thread (``DELETE /v1/threads/{threadId}``)."""
|
|
89
|
+
return await self.request(bearer_token, _thread_path(thread_id), method="DELETE")
|
|
90
|
+
|
|
91
|
+
async def start_run(
|
|
92
|
+
self, bearer_token: str, thread_id: str, request: Mapping[str, Any]
|
|
93
|
+
) -> HarnessKitRunAccepted:
|
|
94
|
+
"""Start a run on a thread (``POST /v1/threads/{threadId}/runs``).
|
|
95
|
+
|
|
96
|
+
The path ``thread_id`` always replaces any ``threadId`` in ``request``.
|
|
97
|
+
"""
|
|
98
|
+
return await self.request(
|
|
99
|
+
bearer_token,
|
|
100
|
+
f"{_thread_path(thread_id)}/runs",
|
|
101
|
+
method="POST",
|
|
102
|
+
data={**dict(request), "threadId": thread_id},
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
async def submit_command(
|
|
106
|
+
self, bearer_token: str, thread_id: str, command: Mapping[str, Any]
|
|
107
|
+
) -> HarnessKitCommandReceipt:
|
|
108
|
+
"""Submit a work or control command (``POST /v1/threads/{threadId}/commands``).
|
|
109
|
+
|
|
110
|
+
A rejected command is answered with HTTP 400 and a receipt body rather
|
|
111
|
+
than an error envelope; that receipt is returned instead of raising.
|
|
112
|
+
Any other failure raises ``ApiError``.
|
|
113
|
+
"""
|
|
114
|
+
try:
|
|
115
|
+
return await self.request(
|
|
116
|
+
bearer_token,
|
|
117
|
+
f"{_thread_path(thread_id)}/commands",
|
|
118
|
+
method="POST",
|
|
119
|
+
data={**dict(command), "threadId": thread_id},
|
|
120
|
+
)
|
|
121
|
+
except ApiError as error:
|
|
122
|
+
if _is_command_receipt(error.data):
|
|
123
|
+
return error.data
|
|
124
|
+
raise
|
|
125
|
+
|
|
126
|
+
async def open_events(
|
|
127
|
+
self,
|
|
128
|
+
bearer_token: str,
|
|
129
|
+
thread_id: str,
|
|
130
|
+
*,
|
|
131
|
+
after_sequence: int = 0,
|
|
132
|
+
run_id: str | None = None,
|
|
133
|
+
) -> httpx.Response:
|
|
134
|
+
"""Open the raw SSE response of a thread event stream.
|
|
135
|
+
|
|
136
|
+
The caller owns the response and must close it, or hand it to
|
|
137
|
+
``iter_harness_events``. Raises ``ValueError`` when ``after_sequence`` is
|
|
138
|
+
not a non-negative integer.
|
|
139
|
+
"""
|
|
140
|
+
validate_after_sequence(after_sequence)
|
|
141
|
+
return await self.request_stream(
|
|
142
|
+
bearer_token,
|
|
143
|
+
f"{_thread_path(thread_id)}/events",
|
|
144
|
+
query={"afterSequence": after_sequence, "runId": run_id},
|
|
145
|
+
headers={"accept": "text/event-stream"},
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
def events(
|
|
149
|
+
self,
|
|
150
|
+
bearer_token: str,
|
|
151
|
+
thread_id: str,
|
|
152
|
+
*,
|
|
153
|
+
after_sequence: int = 0,
|
|
154
|
+
run_id: str | None = None,
|
|
155
|
+
) -> AsyncGenerator[HarnessKitEvent, None]:
|
|
156
|
+
"""Stream typed events of a thread (``GET /v1/threads/{threadId}/events``).
|
|
157
|
+
|
|
158
|
+
Resume after a disconnect by passing the last processed ``sequence`` as
|
|
159
|
+
``after_sequence`` (validated immediately, ``ValueError`` otherwise). The
|
|
160
|
+
connection opens on first iteration; call ``aclose()`` on the returned
|
|
161
|
+
generator to stop early.
|
|
162
|
+
"""
|
|
163
|
+
validate_after_sequence(after_sequence)
|
|
164
|
+
return stream_harness_events(
|
|
165
|
+
lambda: self.open_events(
|
|
166
|
+
bearer_token, thread_id, after_sequence=after_sequence, run_id=run_id
|
|
167
|
+
)
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
async def get_run_result(self, bearer_token: str, run_id: str) -> HarnessKitRunResult:
|
|
171
|
+
"""Read the current or terminal result of a run (``GET /v1/runs/{runId}/result``)."""
|
|
172
|
+
return await self.request(
|
|
173
|
+
bearer_token, f"/v1/runs/{_segment(run_id, 'run_id')}/result"
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
async def get_operational_snapshot(
|
|
177
|
+
self, bearer_token: str
|
|
178
|
+
) -> HarnessKitOperationalSnapshot:
|
|
179
|
+
"""Read the runtime operational snapshot (``GET /v1/ops/snapshot``).
|
|
180
|
+
|
|
181
|
+
Raises ``ApiError`` with status 501 when the engine has no such reader.
|
|
182
|
+
"""
|
|
183
|
+
return await self.request(bearer_token, "/v1/ops/snapshot")
|
|
184
|
+
|
|
185
|
+
async def request(
|
|
186
|
+
self,
|
|
187
|
+
bearer_token: str,
|
|
188
|
+
path: str,
|
|
189
|
+
*,
|
|
190
|
+
method: str | None = None,
|
|
191
|
+
query: Mapping[str, Any] | None = None,
|
|
192
|
+
data: Any = None,
|
|
193
|
+
headers: Mapping[str, str] | None = None,
|
|
194
|
+
) -> Any:
|
|
195
|
+
"""Call a Harness endpoint by its path relative to the Harness API root.
|
|
196
|
+
|
|
197
|
+
``path`` may omit the ``/harnesskit`` prefix and may carry its own query
|
|
198
|
+
string; keys in ``query`` override the same keys there. Absolute URLs and
|
|
199
|
+
dot segments are rejected with ``ValueError``; a caller-supplied
|
|
200
|
+
``authorization`` header is replaced by the bearer token.
|
|
201
|
+
"""
|
|
202
|
+
target, params = _gateway_target(path, query)
|
|
203
|
+
return await self.api_client.request(
|
|
204
|
+
target,
|
|
205
|
+
method=method,
|
|
206
|
+
query=params,
|
|
207
|
+
data=data,
|
|
208
|
+
headers=_auth_headers(bearer_token, headers),
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
async def request_stream(
|
|
212
|
+
self,
|
|
213
|
+
bearer_token: str,
|
|
214
|
+
path: str,
|
|
215
|
+
*,
|
|
216
|
+
method: str | None = None,
|
|
217
|
+
query: Mapping[str, Any] | None = None,
|
|
218
|
+
data: Any = None,
|
|
219
|
+
headers: Mapping[str, str] | None = None,
|
|
220
|
+
) -> httpx.Response:
|
|
221
|
+
"""Open a streaming Harness endpoint. The caller must close the response.
|
|
222
|
+
|
|
223
|
+
``path`` and ``query`` follow the same rules as ``request``.
|
|
224
|
+
"""
|
|
225
|
+
target, params = _gateway_target(path, query)
|
|
226
|
+
return await self.api_client.request_stream(
|
|
227
|
+
target,
|
|
228
|
+
method=method,
|
|
229
|
+
query=params,
|
|
230
|
+
data=data,
|
|
231
|
+
headers=_auth_headers(bearer_token, headers),
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
getRuntime = get_runtime
|
|
235
|
+
switchEngine = switch_engine
|
|
236
|
+
listThreads = list_threads
|
|
237
|
+
getThread = get_thread
|
|
238
|
+
renameThread = rename_thread
|
|
239
|
+
deleteThread = delete_thread
|
|
240
|
+
startRun = start_run
|
|
241
|
+
submitCommand = submit_command
|
|
242
|
+
openEvents = open_events
|
|
243
|
+
getRunResult = get_run_result
|
|
244
|
+
getOperationalSnapshot = get_operational_snapshot
|
|
245
|
+
requestStream = request_stream
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def validate_after_sequence(after_sequence: int) -> int:
|
|
249
|
+
"""Return ``after_sequence`` or raise ``ValueError`` unless it is a non-negative integer."""
|
|
250
|
+
if (
|
|
251
|
+
isinstance(after_sequence, bool)
|
|
252
|
+
or not isinstance(after_sequence, int)
|
|
253
|
+
or after_sequence < 0
|
|
254
|
+
):
|
|
255
|
+
raise ValueError("HarnessKit after_sequence must be a non-negative integer.")
|
|
256
|
+
return after_sequence
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
async def iter_harness_events(
|
|
260
|
+
response: httpx.Response,
|
|
261
|
+
) -> AsyncGenerator[HarnessKitEvent, None]:
|
|
262
|
+
"""Decode the SSE ``data`` frames of an opened Harness events response.
|
|
263
|
+
|
|
264
|
+
Frames without data (comments, keep-alives) are skipped. A frame that is not
|
|
265
|
+
a JSON object raises ``ValueError`` naming the SSE event. The response is
|
|
266
|
+
closed when the generator finishes, fails or is closed early.
|
|
267
|
+
"""
|
|
268
|
+
try:
|
|
269
|
+
async with aclosing(iter_sse(response)) as frames:
|
|
270
|
+
async for frame in frames:
|
|
271
|
+
if not frame.data:
|
|
272
|
+
continue
|
|
273
|
+
try:
|
|
274
|
+
decoded = json.loads(frame.data)
|
|
275
|
+
except ValueError as error:
|
|
276
|
+
raise ValueError(
|
|
277
|
+
f'Invalid HarnessKit SSE event "{frame.event}": {error}'
|
|
278
|
+
) from error
|
|
279
|
+
if not isinstance(decoded, dict):
|
|
280
|
+
# Bad payload data, not a caller type error: keep one exception
|
|
281
|
+
# type (``ValueError``) for every malformed frame.
|
|
282
|
+
raise ValueError( # noqa: TRY004
|
|
283
|
+
f'Invalid HarnessKit SSE event "{frame.event}": expected a JSON object'
|
|
284
|
+
)
|
|
285
|
+
yield cast(HarnessKitEvent, decoded)
|
|
286
|
+
finally:
|
|
287
|
+
await response.aclose()
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
async def stream_harness_events(
|
|
291
|
+
open_response: Callable[[], Awaitable[httpx.Response]],
|
|
292
|
+
) -> AsyncGenerator[HarnessKitEvent, None]:
|
|
293
|
+
"""Open a Harness events response lazily and yield its decoded events."""
|
|
294
|
+
response = await open_response()
|
|
295
|
+
try:
|
|
296
|
+
async with aclosing(iter_harness_events(response)) as events:
|
|
297
|
+
async for event in events:
|
|
298
|
+
yield event
|
|
299
|
+
finally:
|
|
300
|
+
await response.aclose()
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def to_gateway_path(path: str) -> str:
|
|
304
|
+
"""Map a Harness-relative path to its ``/harnesskit/*`` gateway path."""
|
|
305
|
+
if not isinstance(path, str):
|
|
306
|
+
raise TypeError("HarnessKit path must be a string.")
|
|
307
|
+
trimmed = path.strip()
|
|
308
|
+
if not trimmed or _URL_SCHEME.match(trimmed):
|
|
309
|
+
raise ValueError("HarnessKit path must be a non-empty relative API path.")
|
|
310
|
+
normalized = trimmed if trimmed.startswith("/") else f"/{trimmed}"
|
|
311
|
+
if normalized == "/harnesskit":
|
|
312
|
+
relative = "/"
|
|
313
|
+
elif normalized.startswith("/harnesskit/"):
|
|
314
|
+
relative = normalized[len("/harnesskit") :]
|
|
315
|
+
else:
|
|
316
|
+
relative = normalized
|
|
317
|
+
for segment in _PATH_END.split(relative, maxsplit=1)[0].split("/"):
|
|
318
|
+
if _decode_segment(segment) in {".", ".."}:
|
|
319
|
+
raise ValueError("HarnessKit path cannot contain dot segments.")
|
|
320
|
+
return f"/harnesskit{relative}"
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _gateway_target(
|
|
324
|
+
path: str, query: Mapping[str, Any] | None
|
|
325
|
+
) -> tuple[str, Mapping[str, Any] | None]:
|
|
326
|
+
"""Resolve ``path`` and ``query`` into the gateway path and extra query params.
|
|
327
|
+
|
|
328
|
+
A query string already present in ``path`` is kept, with same-named keys in
|
|
329
|
+
``query`` taking precedence. It is folded into the returned path because the
|
|
330
|
+
transport sends ``query`` as the complete query string.
|
|
331
|
+
"""
|
|
332
|
+
# Fragments are never sent to the server.
|
|
333
|
+
target, _, raw_query = to_gateway_path(path).split("#", 1)[0].partition("?")
|
|
334
|
+
if not raw_query:
|
|
335
|
+
return target, query
|
|
336
|
+
explicit = _clean_query(query)
|
|
337
|
+
if not explicit:
|
|
338
|
+
return f"{target}?{raw_query}", None
|
|
339
|
+
kept = [
|
|
340
|
+
(name, value)
|
|
341
|
+
for name, value in parse_qsl(raw_query, keep_blank_values=True)
|
|
342
|
+
if name not in explicit
|
|
343
|
+
]
|
|
344
|
+
return f"{target}?{urlencode([*kept, *explicit.items()])}", None
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _decode_segment(segment: str) -> str:
|
|
348
|
+
# Mirror ``decodeURIComponent``: malformed escapes and invalid UTF-8 both fail.
|
|
349
|
+
if _MALFORMED_PERCENT.search(segment):
|
|
350
|
+
raise ValueError("HarnessKit path contains invalid URL encoding.")
|
|
351
|
+
try:
|
|
352
|
+
return unquote(segment, errors="strict")
|
|
353
|
+
except UnicodeDecodeError as error:
|
|
354
|
+
raise ValueError("HarnessKit path contains invalid URL encoding.") from error
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _segment(value: str, name: str) -> str:
|
|
358
|
+
# ``quote`` leaves dots untouched, so ``..`` would otherwise climb out of the
|
|
359
|
+
# intended route when the URL is resolved.
|
|
360
|
+
if not isinstance(value, str) or not value or value in {".", ".."}:
|
|
361
|
+
raise ValueError(f"HarnessKit {name} must be a non-empty string other than '.' or '..'.")
|
|
362
|
+
return quote(value, safe="")
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _thread_path(thread_id: str) -> str:
|
|
366
|
+
return f"/v1/threads/{_segment(thread_id, 'thread_id')}"
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _auth_headers(
|
|
370
|
+
bearer_token: str, headers: Mapping[str, str] | None = None
|
|
371
|
+
) -> dict[str, str]:
|
|
372
|
+
result = {
|
|
373
|
+
name: value for name, value in (headers or {}).items() if name.lower() != "authorization"
|
|
374
|
+
}
|
|
375
|
+
result["authorization"] = f"Bearer {bearer_token}"
|
|
376
|
+
return result
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _is_command_receipt(value: Any) -> bool:
|
|
380
|
+
return (
|
|
381
|
+
isinstance(value, dict)
|
|
382
|
+
and isinstance(value.get("commandId"), str)
|
|
383
|
+
and isinstance(value.get("status"), str)
|
|
384
|
+
)
|
agentos_sdk/clients/modelkit.py
CHANGED
|
@@ -3,8 +3,13 @@ from __future__ import annotations
|
|
|
3
3
|
import json
|
|
4
4
|
from pathlib import Path
|
|
5
5
|
from typing import Any, AsyncIterator, Mapping
|
|
6
|
+
from urllib.parse import quote
|
|
6
7
|
|
|
7
|
-
from agentos_sdk.normalizers import
|
|
8
|
+
from agentos_sdk.normalizers import (
|
|
9
|
+
normalize_app_model,
|
|
10
|
+
normalize_model_info,
|
|
11
|
+
serialize_chat_request,
|
|
12
|
+
)
|
|
8
13
|
from agentos_sdk.transport import ApiClient, iter_sse
|
|
9
14
|
|
|
10
15
|
|
|
@@ -108,13 +113,38 @@ class ModelKitTtsClient:
|
|
|
108
113
|
listVoices = list_voices
|
|
109
114
|
|
|
110
115
|
|
|
116
|
+
class ModelKitDecisionClient:
|
|
117
|
+
"""Typed-question decisions via ``POST /modelkit/decision``.
|
|
118
|
+
|
|
119
|
+
Decision models (``task: "decision"``, llama.cpp ``/v1/systemone``) score
|
|
120
|
+
caller-provided options instead of generating text. No app token needed.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
def __init__(self, api_client: ApiClient) -> None:
|
|
124
|
+
self.api_client = api_client
|
|
125
|
+
|
|
126
|
+
async def create(self, request: Mapping[str, Any]) -> dict[str, Any]:
|
|
127
|
+
return await self.api_client.request(
|
|
128
|
+
"/modelkit/decision",
|
|
129
|
+
method="POST",
|
|
130
|
+
data=dict(request),
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
111
134
|
class ModelKitClient:
|
|
135
|
+
"""Task-oriented ModelKit client.
|
|
136
|
+
|
|
137
|
+
App-model write methods take the AppKit ``bearer_token`` explicitly; use
|
|
138
|
+
``AgentOSSDK.modelkit`` to have it attached and refreshed automatically.
|
|
139
|
+
"""
|
|
140
|
+
|
|
112
141
|
def __init__(self, api_client: ApiClient | None = None) -> None:
|
|
113
142
|
self.api_client = api_client or ApiClient()
|
|
114
143
|
self.chat = ModelKitChatClient(self.api_client)
|
|
115
144
|
self.embedding = ModelKitEmbeddingClient(self.api_client)
|
|
116
145
|
self.asr = ModelKitAsrClient(self.api_client)
|
|
117
146
|
self.tts = ModelKitTtsClient(self.api_client)
|
|
147
|
+
self.decision = ModelKitDecisionClient(self.api_client)
|
|
118
148
|
|
|
119
149
|
async def list_models(self) -> list[dict[str, Any]]:
|
|
120
150
|
data = await self.api_client.request("/modelkit/models")
|
|
@@ -123,5 +153,72 @@ class ModelKitClient:
|
|
|
123
153
|
async def list_models_by_task(self, task: str) -> list[dict[str, Any]]:
|
|
124
154
|
return [model for model in await self.list_models() if model["task"] == task]
|
|
125
155
|
|
|
156
|
+
async def list_app_models(self) -> list[dict[str, Any]]:
|
|
157
|
+
"""List models registered by apps (``GET /modelkit/app-models``).
|
|
158
|
+
|
|
159
|
+
Public endpoint, no token required. Disabled models are included; check
|
|
160
|
+
``isDisabled``.
|
|
161
|
+
"""
|
|
162
|
+
data = await self.api_client.request("/modelkit/app-models")
|
|
163
|
+
return [normalize_app_model(item) for item in data]
|
|
164
|
+
|
|
165
|
+
async def register_app_model(
|
|
166
|
+
self, bearer_token: str, request: Mapping[str, Any]
|
|
167
|
+
) -> dict[str, Any]:
|
|
168
|
+
"""Register (or replace) an app model (``POST /modelkit/app-models``).
|
|
169
|
+
|
|
170
|
+
Re-registering an id owned by the same app replaces it (``updated`` is
|
|
171
|
+
true). Raises ``ApiError`` with status 401 (missing/invalid token), 403
|
|
172
|
+
(``appBundleId`` mismatch), 409 (id owned by another app) or 400
|
|
173
|
+
(invalid body, unknown ``task``).
|
|
174
|
+
"""
|
|
175
|
+
return await self.api_client.request(
|
|
176
|
+
"/modelkit/app-models",
|
|
177
|
+
method="POST",
|
|
178
|
+
headers=_auth(bearer_token),
|
|
179
|
+
data=dict(request),
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
async def update_app_model(
|
|
183
|
+
self, bearer_token: str, model_id: str, request: Mapping[str, Any]
|
|
184
|
+
) -> dict[str, Any]:
|
|
185
|
+
"""Partially update an owned app model (``PUT /modelkit/app-models/<id>``)."""
|
|
186
|
+
return await self.api_client.request(
|
|
187
|
+
_app_model_path(model_id),
|
|
188
|
+
method="PUT",
|
|
189
|
+
headers=_auth(bearer_token),
|
|
190
|
+
data=dict(request),
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
async def unregister_app_model(self, bearer_token: str, model_id: str) -> dict[str, Any]:
|
|
194
|
+
"""Remove an owned app model (``DELETE /modelkit/app-models/<id>``)."""
|
|
195
|
+
return await self.api_client.request(
|
|
196
|
+
_app_model_path(model_id),
|
|
197
|
+
method="DELETE",
|
|
198
|
+
headers=_auth(bearer_token),
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
async def toggle_app_model(self, bearer_token: str, model_id: str) -> dict[str, Any]:
|
|
202
|
+
"""Flip an owned app model between enabled and disabled
|
|
203
|
+
(``POST /modelkit/app-models/<id>/toggle``)."""
|
|
204
|
+
return await self.api_client.request(
|
|
205
|
+
f"{_app_model_path(model_id)}/toggle",
|
|
206
|
+
method="POST",
|
|
207
|
+
headers=_auth(bearer_token),
|
|
208
|
+
)
|
|
209
|
+
|
|
126
210
|
listModels = list_models
|
|
127
211
|
listModelsByTask = list_models_by_task
|
|
212
|
+
listAppModels = list_app_models
|
|
213
|
+
registerAppModel = register_app_model
|
|
214
|
+
updateAppModel = update_app_model
|
|
215
|
+
unregisterAppModel = unregister_app_model
|
|
216
|
+
toggleAppModel = toggle_app_model
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _app_model_path(model_id: str) -> str:
|
|
220
|
+
return f"/modelkit/app-models/{quote(model_id, safe='')}"
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _auth(token: str) -> dict[str, str]:
|
|
224
|
+
return {"authorization": f"Bearer {token}"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from agentos_sdk.protocol import NotifyKitPublishResult
|
|
7
|
+
from agentos_sdk.transport import ApiClient
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class NotifyKitClient:
|
|
11
|
+
"""Client for the AgentOS NotifyKit gateway (``/notifykit/*``).
|
|
12
|
+
|
|
13
|
+
NotifyKit is content-only: an App provides ``eventType``, ``title``,
|
|
14
|
+
``message`` and an optional ``subjectId``. Priority, grouping, deduplication
|
|
15
|
+
and presentation are platform policy decisions and cannot be set here.
|
|
16
|
+
|
|
17
|
+
``bearer_token`` is the AppKit token; use ``AgentOSSDK.notifykit`` to have it
|
|
18
|
+
attached and refreshed automatically.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(self, api_client: ApiClient | None = None) -> None:
|
|
22
|
+
self.api_client = api_client or ApiClient()
|
|
23
|
+
|
|
24
|
+
async def publish(
|
|
25
|
+
self, bearer_token: str, request: Mapping[str, Any]
|
|
26
|
+
) -> NotifyKitPublishResult:
|
|
27
|
+
"""Submit an App event to the notification center (``POST /notifykit/notifications``).
|
|
28
|
+
|
|
29
|
+
The response carries the platform-owned notification record and its
|
|
30
|
+
aggregate ``count``: repeated events with the same ``subjectId`` (or the
|
|
31
|
+
same content within a short window) are collapsed into one item.
|
|
32
|
+
|
|
33
|
+
Raises ``ApiError`` with status 401 (missing/invalid token), 400 (invalid
|
|
34
|
+
body, for example an ``eventType`` that is not a lowercase dotted name) or
|
|
35
|
+
429 when the App exceeded its rate limit; for 429 ``error.data`` contains
|
|
36
|
+
``retryAfterSeconds``.
|
|
37
|
+
"""
|
|
38
|
+
return await self.api_client.request(
|
|
39
|
+
"/notifykit/notifications",
|
|
40
|
+
method="POST",
|
|
41
|
+
headers=_auth(bearer_token),
|
|
42
|
+
data=dict(request),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _auth(token: str) -> dict[str, str]:
|
|
47
|
+
return {"authorization": f"Bearer {token}"}
|