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