pal-runtime 0.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.
pal/client.py ADDED
@@ -0,0 +1,2246 @@
1
+ """HTTP client for the PAL API (mirrors the TypeScript SDK client)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import os
8
+ import random
9
+ import uuid
10
+ from collections.abc import AsyncIterator
11
+ from dataclasses import dataclass, field
12
+ from typing import Any
13
+ from urllib.parse import quote
14
+
15
+ import httpx
16
+
17
+ from pal.errors import PalApiError, PalPolicyDeniedError, PalPolicyVersionConflictError
18
+ from pal.types import (
19
+ AgentInfo,
20
+ ConnectorInfo,
21
+ ConnectorResult,
22
+ ExecStreamEvent,
23
+ Run,
24
+ Session,
25
+ SessionMessage,
26
+ StreamEvent,
27
+ VmForkResult,
28
+ VmPauseResult,
29
+ VmResumeResult,
30
+ )
31
+
32
+ # Bounded exponential backoff with full jitter, mirroring
33
+ # packages/bridge-core/src/retry.ts. Only 429/503 and network-layer
34
+ # failures are transient; 4xx auth/validation errors are never retried.
35
+ _RETRY_MAX_ATTEMPTS = 3
36
+ _RETRY_BASE_DELAY_S = 0.5
37
+ _RETRY_MAX_DELAY_S = 4.0
38
+ _RETRYABLE_STATUS = {429, 503}
39
+
40
+
41
+ def _retry_backoff_s(attempt: int) -> float:
42
+ ceiling = min(_RETRY_MAX_DELAY_S, _RETRY_BASE_DELAY_S * 2**attempt)
43
+ return random.uniform(0, ceiling)
44
+
45
+
46
+ def _api_error(status: int, body: str) -> PalApiError:
47
+ """Build the most specific PalApiError for a non-2xx response."""
48
+ try:
49
+ env = json.loads(body)
50
+ except ValueError:
51
+ env = None
52
+ if isinstance(env, dict):
53
+ if status == 403 and env.get("code") == "agent_policy_denied":
54
+ return PalPolicyDeniedError(
55
+ status,
56
+ body,
57
+ kind=str(env.get("kind", "")),
58
+ target=str(env.get("target", "")),
59
+ message=str(env.get("error", "")),
60
+ )
61
+ if status == 409 and env.get("code") == "version_conflict":
62
+ return PalPolicyVersionConflictError(status, body)
63
+ return PalApiError(status, body)
64
+
65
+
66
+ class PalClient:
67
+ """Async HTTP client for the PAL platform API.
68
+
69
+ Usage::
70
+
71
+ client = PalClient() # reads PAL_API_URL / PAL_API_KEY
72
+ agent = await client.agents.create(name="my-agent")
73
+ run = await client.runs.create(agent="my-agent", input={"q": "hi"})
74
+
75
+ async for event in client.runs.events(run.id):
76
+ print(event.kind, event.data)
77
+ """
78
+
79
+ def __init__(
80
+ self,
81
+ base_url: str | None = None,
82
+ api_key: str | None = None,
83
+ *,
84
+ timeout: float = 30.0,
85
+ route_strategy: str | None = None,
86
+ ) -> None:
87
+ self.base_url = (base_url or os.environ.get("PAL_API_URL") or "http://localhost:8080").rstrip("/")
88
+ self._api_key = api_key or os.environ.get("PAL_API_KEY") or ""
89
+ self._timeout = timeout
90
+ self._route_strategy = route_strategy or os.environ.get("PAL_ROUTE_STRATEGY") or "auto"
91
+ self._client: httpx.AsyncClient | None = None
92
+
93
+ # Bind sub-resource namespaces
94
+ self.agents = self._Agents(self)
95
+ self.runs = self._Runs(self)
96
+ self.sessions = self._Sessions(self)
97
+ self.connectors = self._Connectors(self)
98
+ self.budgets = self._Budgets(self)
99
+ self.triggers = self._Triggers(self)
100
+ self.evals = self._Evals(self)
101
+ self.experiments = self._Experiments(self)
102
+ self.marketplace = self._Marketplace(self)
103
+ self.mcp = self._MCP(self)
104
+ self.receipts = self._Receipts(self)
105
+ self.feedback = self._Feedback(self)
106
+ self.rehearsals = self._Rehearsals(self)
107
+ self.debug = self._Debug(self)
108
+ self.support = self._Support(self)
109
+ self.a2a = self._A2A(self)
110
+ self.runtime = self._Runtime(self)
111
+
112
+ # ------------------------------------------------------------------
113
+ # Lifecycle
114
+ # ------------------------------------------------------------------
115
+
116
+ async def _get_client(self) -> httpx.AsyncClient:
117
+ if self._client is None or self._client.is_closed:
118
+ self._client = httpx.AsyncClient(
119
+ base_url=self.base_url,
120
+ timeout=self._timeout,
121
+ headers=self._headers(),
122
+ )
123
+ return self._client
124
+
125
+ async def close(self) -> None:
126
+ if self._client and not self._client.is_closed:
127
+ await self._client.aclose()
128
+ self._client = None
129
+
130
+ async def __aenter__(self) -> PalClient:
131
+ return self
132
+
133
+ async def __aexit__(self, *exc: Any) -> None:
134
+ await self.close()
135
+
136
+ # ------------------------------------------------------------------
137
+ # Internal helpers
138
+ # ------------------------------------------------------------------
139
+
140
+ def _headers(self) -> dict[str, str]:
141
+ h: dict[str, str] = {"Content-Type": "application/json"}
142
+ if self._api_key:
143
+ h["Authorization"] = f"Bearer {self._api_key}"
144
+ if self._route_strategy and self._route_strategy != "auto":
145
+ h["X-Pal-Route-Strategy"] = self._route_strategy
146
+ return h
147
+
148
+ async def _request(
149
+ self,
150
+ method: str,
151
+ path: str,
152
+ *,
153
+ body: Any = None,
154
+ params: dict[str, Any] | None = None,
155
+ ) -> Any:
156
+ kwargs: dict[str, Any] = {}
157
+ if body is not None:
158
+ kwargs["content"] = json.dumps(body)
159
+ if params:
160
+ # Filter out None values
161
+ kwargs["params"] = {k: str(v) for k, v in params.items() if v is not None}
162
+
163
+ for attempt in range(_RETRY_MAX_ATTEMPTS):
164
+ client = await self._get_client()
165
+ try:
166
+ resp = await client.request(method, path, **kwargs)
167
+ except httpx.TransportError:
168
+ if attempt + 1 >= _RETRY_MAX_ATTEMPTS:
169
+ raise
170
+ await asyncio.sleep(_retry_backoff_s(attempt))
171
+ continue
172
+
173
+ if resp.is_success:
174
+ if resp.status_code == 204 or not resp.content:
175
+ return None
176
+ return resp.json()
177
+
178
+ if resp.status_code in _RETRYABLE_STATUS and attempt + 1 < _RETRY_MAX_ATTEMPTS:
179
+ await asyncio.sleep(_retry_backoff_s(attempt))
180
+ continue
181
+
182
+ raise _api_error(resp.status_code, resp.text)
183
+
184
+ @staticmethod
185
+ def _items(data: Any, key: str) -> list[Any]:
186
+ """Normalize a list response.
187
+
188
+ The control-plane list endpoints return a BARE JSON array
189
+ (writeJSON(w, 200, <slice>)); a wrapped ``{key: [...]}`` shape is
190
+ accepted too for forward-compat. Anything else yields [].
191
+ """
192
+ if isinstance(data, list):
193
+ return data
194
+ if isinstance(data, dict):
195
+ items = data.get(key, [])
196
+ return items if isinstance(items, list) else []
197
+ return []
198
+
199
+ async def _sse_stream(
200
+ self,
201
+ method: str,
202
+ path: str,
203
+ *,
204
+ body: Any = None,
205
+ params: dict[str, Any] | None = None,
206
+ ) -> AsyncIterator[StreamEvent]:
207
+ """Open an SSE connection and yield parsed StreamEvents."""
208
+ client = await self._get_client()
209
+ headers = {**self._headers(), "Accept": "text/event-stream"}
210
+ kwargs: dict[str, Any] = {"headers": headers}
211
+ if body is not None:
212
+ kwargs["content"] = json.dumps(body)
213
+ if params:
214
+ kwargs["params"] = {k: str(v) for k, v in params.items() if v is not None}
215
+
216
+ async with client.stream(method, path, **kwargs) as resp:
217
+ if not resp.is_success:
218
+ body_text = await resp.aread()
219
+ raise PalApiError(resp.status_code, body_text.decode("utf-8", errors="replace"))
220
+
221
+ buffer = ""
222
+ async for chunk in resp.aiter_text():
223
+ buffer += chunk
224
+ while "\n" in buffer:
225
+ line, buffer = buffer.split("\n", 1)
226
+ line = line.strip()
227
+ if line.startswith("data: "):
228
+ data_str = line[6:].strip()
229
+ if data_str == "[DONE]":
230
+ return
231
+ try:
232
+ event = StreamEvent.model_validate_json(data_str)
233
+ yield event
234
+ if event.kind == "end":
235
+ return
236
+ except Exception:
237
+ # Skip malformed events
238
+ pass
239
+
240
+ # ------------------------------------------------------------------
241
+ # agents namespace
242
+ # ------------------------------------------------------------------
243
+
244
+ class _Agents:
245
+ def __init__(self, client: PalClient) -> None:
246
+ self._c = client
247
+
248
+ async def create(
249
+ self,
250
+ *,
251
+ name: str,
252
+ description: str = "",
253
+ labels: dict[str, str] | None = None,
254
+ ) -> AgentInfo:
255
+ data = await self._c._request(
256
+ "POST",
257
+ "/v1/agents",
258
+ body={
259
+ "name": name,
260
+ "description": description,
261
+ "labels": labels or {},
262
+ },
263
+ )
264
+ return AgentInfo.model_validate(data)
265
+
266
+ async def get(self, name: str) -> AgentInfo:
267
+ data = await self._c._request("GET", f"/v1/agents/{name}")
268
+ return AgentInfo.model_validate(data)
269
+
270
+ async def list(
271
+ self,
272
+ *,
273
+ page_size: int = 50,
274
+ page_token: str | None = None,
275
+ ) -> AgentListResponse:
276
+ data = await self._c._request(
277
+ "GET",
278
+ "/v1/agents",
279
+ params={
280
+ "pageSize": page_size,
281
+ "pageToken": page_token,
282
+ },
283
+ )
284
+ agents = [AgentInfo.model_validate(a) for a in PalClient._items(data, "agents")]
285
+ token = data.get("nextPageToken") if isinstance(data, dict) else None
286
+ return AgentListResponse(agents=agents, next_page_token=token)
287
+
288
+ async def delete(self, name: str) -> None:
289
+ await self._c._request("DELETE", f"/v1/agents/{name}")
290
+
291
+ # -- policy + identity (ADR 0055) --------------------------------
292
+
293
+ async def get_policy(self, name: str) -> AgentPolicyResult:
294
+ """Get the agent's policy (GET /v1/agents/{name}/policy)."""
295
+ data = await self._c._request("GET", f"/v1/agents/{quote(name, safe='')}/policy")
296
+ return AgentPolicyResult.from_dict(data or {})
297
+
298
+ async def put_policy(self, name: str, policy: dict[str, Any]) -> AgentPolicyResult:
299
+ """Replace the policy (PUT /v1/agents/{name}/policy).
300
+
301
+ ``policy`` must carry the ``version`` last read. Raises
302
+ PalPolicyVersionConflictError on 409.
303
+ """
304
+ data = await self._c._request("PUT", f"/v1/agents/{quote(name, safe='')}/policy", body=policy)
305
+ return AgentPolicyResult.from_dict(data or {})
306
+
307
+ async def propose_policy(self, name: str) -> PolicyProposal:
308
+ """Least-privilege proposal; never persisted (POST /v1/agents/{name}/policy/propose)."""
309
+ data = await self._c._request("POST", f"/v1/agents/{quote(name, safe='')}/policy/propose")
310
+ return PolicyProposal.from_dict(data or {})
311
+
312
+ async def get_identity(self, name: str) -> AgentIdentity:
313
+ """Get the agent's identity (GET /v1/agents/{name}/identity)."""
314
+ data = await self._c._request("GET", f"/v1/agents/{quote(name, safe='')}/identity")
315
+ return AgentIdentity.from_dict(data or {})
316
+
317
+ async def rotate_identity(self, name: str) -> AgentIdentity:
318
+ """Rotate the signing key (POST /v1/agents/{name}/identity/rotate)."""
319
+ data = await self._c._request("POST", f"/v1/agents/{quote(name, safe='')}/identity/rotate", body={})
320
+ return AgentIdentity.from_dict(data or {})
321
+
322
+ async def revoke_identity(self, name: str, reason: str = "") -> AgentIdentity:
323
+ """Revoke the identity (POST /v1/agents/{name}/identity/revoke)."""
324
+ data = await self._c._request(
325
+ "POST", f"/v1/agents/{quote(name, safe='')}/identity/revoke", body={"reason": reason}
326
+ )
327
+ return AgentIdentity.from_dict(data or {})
328
+
329
+ async def mint_token(self, name: str, audience: str, run_id: str | None = None) -> AgentToken:
330
+ """Mint a short-lived agent token (admin only; POST /v1/agents/{name}/identity/token)."""
331
+ body: dict[str, Any] = {"audience": audience}
332
+ if run_id:
333
+ body["runId"] = run_id
334
+ data = await self._c._request("POST", f"/v1/agents/{quote(name, safe='')}/identity/token", body=body)
335
+ return AgentToken.from_dict(data or {})
336
+
337
+ async def list_audit(self, name: str, *, limit: int | None = None, event: str | None = None) -> AgentAuditList:
338
+ """List audit events + chain integrity (GET /v1/agents/{name}/audit)."""
339
+ data = await self._c._request(
340
+ "GET",
341
+ f"/v1/agents/{quote(name, safe='')}/audit",
342
+ params={"limit": limit, "event": event},
343
+ )
344
+ return AgentAuditList.from_dict(data or {})
345
+
346
+ # ------------------------------------------------------------------
347
+ # runs namespace
348
+ # ------------------------------------------------------------------
349
+
350
+ class _Runs:
351
+ def __init__(self, client: PalClient) -> None:
352
+ self._c = client
353
+
354
+ async def create(
355
+ self,
356
+ *,
357
+ agent: str,
358
+ input: Any,
359
+ stream: bool = False,
360
+ labels: dict[str, str] | None = None,
361
+ idempotency_key: str | None = None,
362
+ ) -> Run | AsyncIterator[StreamEvent]:
363
+ payload: dict[str, Any] = {
364
+ # Handler decodes camelCase `agentName` (rest.go CreateRun);
365
+ # snake_case is silently dropped → an agent-less run.
366
+ "agentName": agent,
367
+ "input": input,
368
+ "labels": labels or {},
369
+ }
370
+ if idempotency_key:
371
+ payload["idempotency_key"] = idempotency_key
372
+
373
+ if stream:
374
+ payload["stream"] = True
375
+ return self._c._sse_stream("POST", "/v1/runs", body=payload)
376
+
377
+ data = await self._c._request("POST", "/v1/runs", body=payload)
378
+ return Run.model_validate(data)
379
+
380
+ async def get(self, id: str) -> Run:
381
+ data = await self._c._request("GET", f"/v1/runs/{id}")
382
+ return Run.model_validate(data)
383
+
384
+ async def list(
385
+ self,
386
+ *,
387
+ agent: str | None = None,
388
+ status: str | None = None,
389
+ page_size: int = 50,
390
+ page_token: str | None = None,
391
+ ) -> RunListResponse:
392
+ data = await self._c._request(
393
+ "GET",
394
+ "/v1/runs",
395
+ params={
396
+ "agent": agent,
397
+ "status": status,
398
+ "pageSize": page_size,
399
+ "pageToken": page_token,
400
+ },
401
+ )
402
+ runs = [Run.model_validate(r) for r in PalClient._items(data, "runs")]
403
+ token = data.get("nextPageToken") if isinstance(data, dict) else None
404
+ return RunListResponse(runs=runs, next_page_token=token)
405
+
406
+ async def cancel(self, id: str, reason: str = "") -> Run:
407
+ data = await self._c._request("POST", f"/v1/runs/{id}/cancel", body={"reason": reason})
408
+ return Run.model_validate(data)
409
+
410
+ def events(
411
+ self,
412
+ run_id: str,
413
+ *,
414
+ from_seq: int = 0,
415
+ live: bool = True,
416
+ ) -> AsyncIterator[StreamEvent]:
417
+ return self._c._sse_stream(
418
+ "GET",
419
+ f"/v1/runs/{run_id}/events",
420
+ params={"from_seq": from_seq, "live": live},
421
+ )
422
+
423
+ async def signal(self, run_id: str, name: str, value: Any = None) -> None:
424
+ await self._c._request(
425
+ "POST",
426
+ f"/v1/runs/{run_id}/signals/{name}",
427
+ body={"value": value},
428
+ )
429
+
430
+ async def forecast(self, agent_name: str, input: str) -> ForecastResult:
431
+ """Forecast tokens/cost/confidence for a prospective run.
432
+
433
+ Returns a ForecastResult with ``would_exceed_budget`` set to True
434
+ when a budget policy would block execution.
435
+ """
436
+ data = await self._c._request(
437
+ "POST",
438
+ "/v1/runs/forecast",
439
+ body={
440
+ "agentName": agent_name,
441
+ "input": input,
442
+ },
443
+ )
444
+ return ForecastResult(
445
+ agent_name=data.get("agentName", agent_name),
446
+ model=data.get("model", ""),
447
+ provider=data.get("provider", ""),
448
+ estimated_tokens_in=data.get("estimatedTokensIn", 0),
449
+ estimated_tokens_out=data.get("estimatedTokensOut", 0),
450
+ estimated_cost_usd=data.get("estimatedCostUsd", 0.0),
451
+ confidence=data.get("confidence", 0.0),
452
+ would_exceed_budget=data.get("wouldExceedBudget", False),
453
+ block_reason=data.get("blockReason"),
454
+ reasoning=data.get("reasoning"),
455
+ )
456
+
457
+ # ------------------------------------------------------------------
458
+ # sessions namespace
459
+ # ------------------------------------------------------------------
460
+
461
+ class _Sessions:
462
+ def __init__(self, client: PalClient) -> None:
463
+ self._c = client
464
+
465
+ async def create(
466
+ self,
467
+ *,
468
+ agent: str,
469
+ metadata: dict[str, Any] | None = None,
470
+ ) -> Session:
471
+ """Create a new interactive session for an agent."""
472
+ data = await self._c._request(
473
+ "POST",
474
+ "/v1/sessions",
475
+ body={
476
+ # Handler decodes camelCase `agentName` (sessions.go
477
+ # CreateSession:79); snake_case is silently dropped.
478
+ "agentName": agent,
479
+ "metadata": metadata or {},
480
+ },
481
+ )
482
+ return Session.model_validate(data)
483
+
484
+ async def get(self, session_id: str) -> Session:
485
+ """Retrieve a session by ID."""
486
+ data = await self._c._request("GET", f"/v1/sessions/{session_id}")
487
+ return Session.model_validate(data)
488
+
489
+ async def list(
490
+ self,
491
+ *,
492
+ agent: str | None = None,
493
+ status: str | None = None,
494
+ page_size: int = 50,
495
+ page_token: str | None = None,
496
+ ) -> SessionListResponse:
497
+ """List sessions, optionally filtered by agent or status."""
498
+ data = await self._c._request(
499
+ "GET",
500
+ "/v1/sessions",
501
+ params={
502
+ "agent": agent,
503
+ "status": status,
504
+ "pageSize": page_size,
505
+ "pageToken": page_token,
506
+ },
507
+ )
508
+ sessions = [Session.model_validate(s) for s in PalClient._items(data, "sessions")]
509
+ token = data.get("nextPageToken") if isinstance(data, dict) else None
510
+ return SessionListResponse(sessions=sessions, next_page_token=token)
511
+
512
+ async def send_message(
513
+ self,
514
+ session_id: str,
515
+ *,
516
+ content: str,
517
+ role: str = "user",
518
+ ) -> SessionMessage:
519
+ """Send a message to a session and get the agent's response."""
520
+ data = await self._c._request(
521
+ "POST",
522
+ f"/v1/sessions/{session_id}/messages",
523
+ body={"content": content, "role": role},
524
+ )
525
+ return SessionMessage.model_validate(data)
526
+
527
+ def stream_events(
528
+ self,
529
+ session_id: str,
530
+ *,
531
+ from_seq: int = 0,
532
+ ) -> AsyncIterator[StreamEvent]:
533
+ """Stream events from a session (SSE)."""
534
+ return self._c._sse_stream(
535
+ "GET",
536
+ f"/v1/sessions/{session_id}/events",
537
+ params={"from_seq": from_seq},
538
+ )
539
+
540
+ async def stop(self, session_id: str) -> None:
541
+ """Stop a running session (POST /v1/sessions/{id}/stop)."""
542
+ await self._c._request("POST", f"/v1/sessions/{session_id}/stop")
543
+
544
+ async def delete(self, session_id: str) -> None:
545
+ """Delete a session (DELETE /v1/sessions/{id}).
546
+
547
+ Previously named ``close``; this is the correct server route.
548
+ """
549
+ await self._c._request("DELETE", f"/v1/sessions/{session_id}")
550
+
551
+ # Backward-compat alias — was using wrong route (POST /{id}/close).
552
+ # Now delegates to delete() which uses DELETE /v1/sessions/{id}.
553
+ async def close(self, session_id: str) -> None:
554
+ """Deprecated alias for delete(). Kept for backward compatibility."""
555
+ await self.delete(session_id)
556
+
557
+ # ------------------------------------------------------------------
558
+ # connectors namespace
559
+ # ------------------------------------------------------------------
560
+
561
+ class _Connectors:
562
+ def __init__(self, client: PalClient) -> None:
563
+ self._c = client
564
+
565
+ async def list(
566
+ self,
567
+ *,
568
+ page_size: int = 50,
569
+ page_token: str | None = None,
570
+ ) -> ConnectorListResponse:
571
+ """List installed connectors."""
572
+ data = await self._c._request(
573
+ "GET",
574
+ "/v1/connectors",
575
+ params={
576
+ "pageSize": page_size,
577
+ "pageToken": page_token,
578
+ },
579
+ )
580
+ items = [ConnectorInfo.model_validate(c) for c in PalClient._items(data, "connectors")]
581
+ token = data.get("nextPageToken") if isinstance(data, dict) else None
582
+ return ConnectorListResponse(connectors=items, next_page_token=token)
583
+
584
+ async def get(self, connector_id: str) -> ConnectorInfo:
585
+ """Get details for an installed connector."""
586
+ data = await self._c._request("GET", f"/v1/connectors/{connector_id}")
587
+ return ConnectorInfo.model_validate(data)
588
+
589
+ async def execute(
590
+ self,
591
+ connector_id: str,
592
+ action: str,
593
+ params: dict[str, Any] | None = None,
594
+ ) -> ConnectorResult:
595
+ """Execute a connector action.
596
+
597
+ The action name is passed as a query parameter per the server contract
598
+ (GET/POST /v1/connectors/{connectorId}/execute?action={action}).
599
+
600
+ Example::
601
+
602
+ result = await client.connectors.execute(
603
+ "slack", "send_message",
604
+ params={"channel": "#general", "text": "Hello from PAL!"},
605
+ )
606
+ """
607
+ data = await self._c._request(
608
+ "POST",
609
+ f"/v1/connectors/{connector_id}/execute",
610
+ body={"params": params or {}},
611
+ params={"action": action},
612
+ )
613
+ return ConnectorResult.model_validate(data)
614
+
615
+ async def list_actions(self, connector_id: str) -> list[dict[str, Any]]:
616
+ """List available actions for a connector."""
617
+ data = await self._c._request("GET", f"/v1/connectors/{connector_id}/actions")
618
+ return data.get("actions", [])
619
+
620
+ # ------------------------------------------------------------------
621
+ # budgets namespace
622
+ # ------------------------------------------------------------------
623
+
624
+ class _Budgets:
625
+ def __init__(self, client: PalClient) -> None:
626
+ self._c = client
627
+
628
+ async def upsert(
629
+ self,
630
+ agent_name: str,
631
+ *,
632
+ max_cost_usd_per_day: float | None = None,
633
+ max_cost_usd_per_run: float | None = None,
634
+ max_runs_per_day: int | None = None,
635
+ tool_limits: dict[str, int] | None = None,
636
+ hard_fail: bool = False,
637
+ notify_at_pct: int | None = None,
638
+ ) -> BudgetResult:
639
+ """Upsert a per-agent budget policy (PUT /v1/agents/{name}/budget)."""
640
+ body: dict[str, Any] = {"agentName": agent_name, "hardFail": hard_fail}
641
+ if max_cost_usd_per_day is not None:
642
+ body["maxCostUsdPerDay"] = max_cost_usd_per_day
643
+ if max_cost_usd_per_run is not None:
644
+ body["maxCostUsdPerRun"] = max_cost_usd_per_run
645
+ if max_runs_per_day is not None:
646
+ body["maxRunsPerDay"] = max_runs_per_day
647
+ if tool_limits:
648
+ body["toolLimits"] = tool_limits
649
+ if notify_at_pct is not None:
650
+ body["notifyAtPct"] = notify_at_pct
651
+ data = await self._c._request("PUT", f"/v1/agents/{agent_name}/budget", body=body)
652
+ return BudgetResult.from_dict(data or body)
653
+
654
+ async def get(self, agent_name: str) -> BudgetResult:
655
+ """Get the budget configured for an agent (GET /v1/agents/{name}/budget)."""
656
+ data = await self._c._request("GET", f"/v1/agents/{agent_name}/budget")
657
+ return BudgetResult.from_dict(data)
658
+
659
+ async def delete(self, agent_name: str) -> None:
660
+ """Remove a budget from an agent (DELETE /v1/agents/{name}/budget)."""
661
+ await self._c._request("DELETE", f"/v1/agents/{agent_name}/budget")
662
+
663
+ async def list_all(self) -> list[BudgetResult]:
664
+ """List all budgets for the tenant (GET /v1/budgets)."""
665
+ data = await self._c._request("GET", "/v1/budgets")
666
+ return [BudgetResult.from_dict(b) for b in (data or [])]
667
+
668
+ # ------------------------------------------------------------------
669
+ # triggers namespace (inbound webhooks, ADR 0028)
670
+ # ------------------------------------------------------------------
671
+
672
+ class _Triggers:
673
+ """Inbound webhook triggers. A provider POSTs signed deliveries to
674
+ ``base_url + trigger["hookPath"]``; each verified delivery starts a run."""
675
+
676
+ def __init__(self, client: PalClient) -> None:
677
+ self._c = client
678
+
679
+ async def create(
680
+ self,
681
+ agent_name: str,
682
+ *,
683
+ provider: str,
684
+ secret: str | None = None,
685
+ input_template: dict[str, Any] | None = None,
686
+ ) -> dict[str, Any]:
687
+ """Create a trigger (POST /v1/agents/{name}/triggers). ``secret`` is in
688
+ the response only when PAL generated it — store it then."""
689
+ body: dict[str, Any] = {"provider": provider}
690
+ if secret is not None:
691
+ body["secret"] = secret
692
+ if input_template is not None:
693
+ body["inputTemplate"] = input_template
694
+ data: dict[str, Any] = await self._c._request("POST", f"/v1/agents/{agent_name}/triggers", body=body)
695
+ return data
696
+
697
+ async def list(self, agent_name: str) -> list[dict[str, Any]]:
698
+ """List an agent's triggers (GET /v1/agents/{name}/triggers). Never includes secrets."""
699
+ return await self._c._request("GET", f"/v1/agents/{agent_name}/triggers") or []
700
+
701
+ async def get(self, trigger_id: str) -> dict[str, Any]:
702
+ """Get one trigger (GET /v1/triggers/{id})."""
703
+ data: dict[str, Any] = await self._c._request("GET", f"/v1/triggers/{trigger_id}")
704
+ return data
705
+
706
+ async def update(
707
+ self,
708
+ trigger_id: str,
709
+ *,
710
+ enabled: bool | None = None,
711
+ secret: str | None = None,
712
+ input_template: dict[str, Any] | None = None,
713
+ clear_input_template: bool = False,
714
+ ) -> dict[str, Any]:
715
+ """Update a trigger (PATCH /v1/triggers/{id})."""
716
+ body: dict[str, Any] = {}
717
+ if enabled is not None:
718
+ body["enabled"] = enabled
719
+ if secret is not None:
720
+ body["secret"] = secret
721
+ if clear_input_template:
722
+ body["inputTemplate"] = None
723
+ elif input_template is not None:
724
+ body["inputTemplate"] = input_template
725
+ data: dict[str, Any] = await self._c._request("PATCH", f"/v1/triggers/{trigger_id}", body=body)
726
+ return data
727
+
728
+ async def delete(self, trigger_id: str) -> None:
729
+ """Delete a trigger (DELETE /v1/triggers/{id})."""
730
+ await self._c._request("DELETE", f"/v1/triggers/{trigger_id}")
731
+
732
+ # ------------------------------------------------------------------
733
+ # evals namespace
734
+ # ------------------------------------------------------------------
735
+
736
+ class _Evals:
737
+ def __init__(self, client: PalClient) -> None:
738
+ self._c = client
739
+
740
+ async def upsert_suite(
741
+ self,
742
+ agent_name: str,
743
+ name: str,
744
+ cases: list[dict[str, Any]],
745
+ *,
746
+ description: str = "",
747
+ ) -> str:
748
+ """Create or update an eval suite. Returns the suite ID."""
749
+ data = await self._c._request(
750
+ "POST",
751
+ "/v1/eval-suites",
752
+ body={
753
+ "agentName": agent_name,
754
+ "name": name,
755
+ "description": description,
756
+ "cases": cases,
757
+ },
758
+ )
759
+ return (data or {}).get("id", "")
760
+
761
+ async def list_suites(self, agent_name: str | None = None) -> list[dict[str, Any]]:
762
+ """List eval suites, optionally filtered by agent."""
763
+ data = await self._c._request(
764
+ "GET",
765
+ "/v1/eval-suites",
766
+ params={
767
+ "agentName": agent_name,
768
+ },
769
+ )
770
+ return data or []
771
+
772
+ async def get_suite(self, suite_id: str) -> dict[str, Any]:
773
+ """Get a single eval suite by ID."""
774
+ data = await self._c._request("GET", f"/v1/eval-suites/{suite_id}")
775
+ return data or {}
776
+
777
+ async def delete_suite(self, suite_id: str) -> None:
778
+ """Delete an eval suite."""
779
+ await self._c._request("DELETE", f"/v1/eval-suites/{suite_id}")
780
+
781
+ async def record_run(
782
+ self,
783
+ suite_id: str,
784
+ case_results: list[dict[str, Any]],
785
+ *,
786
+ agent_version: str = "",
787
+ commit_sha: str = "",
788
+ branch: str = "",
789
+ duration_ms: int = 0,
790
+ total_cost_usd: float = 0.0,
791
+ ) -> EvalRunResult:
792
+ """Submit eval case results. Returns HTTP 422 if regressed vs. baseline."""
793
+ data = await self._c._request(
794
+ "POST",
795
+ "/v1/eval-runs",
796
+ body={
797
+ "suiteId": suite_id,
798
+ "agentVersion": agent_version,
799
+ "commitSha": commit_sha,
800
+ "branch": branch,
801
+ "durationMs": duration_ms,
802
+ "totalCostUsd": total_cost_usd,
803
+ "caseResults": case_results,
804
+ },
805
+ )
806
+ return EvalRunResult.from_dict(data or {})
807
+
808
+ async def run_suite(
809
+ self,
810
+ suite_id: str,
811
+ *,
812
+ branch: str = "",
813
+ commit_sha: str = "",
814
+ agent_version: str = "",
815
+ samples: int | None = None,
816
+ judge_samples: int | None = None,
817
+ judge_model: str = "",
818
+ max_cost_usd: float | None = None,
819
+ cases: list[str] | None = None,
820
+ set_baseline: bool = False,
821
+ ) -> EvalSuiteRunResult:
822
+ """Run a suite hermetically on the server (mocked tools, LLM judge; ADR 0052).
823
+
824
+ A regression is HTTP 422 with a full result body: it is RETURNED with
825
+ ``regressed=True`` rather than raised, so callers can report per-case
826
+ detail and then fail CI. Other errors (400/402/503) raise ``PalApiError``.
827
+ """
828
+ payload: dict[str, Any] = {
829
+ "branch": branch,
830
+ "commitSha": commit_sha,
831
+ "agentVersion": agent_version,
832
+ "samples": samples,
833
+ "judgeSamples": judge_samples,
834
+ "judgeModel": judge_model,
835
+ "maxCostUsd": max_cost_usd,
836
+ "cases": cases,
837
+ "setBaseline": set_baseline or None,
838
+ }
839
+ body = {k: v for k, v in payload.items() if v not in (None, "", [])}
840
+ try:
841
+ data = await self._c._request("POST", f"/v1/eval-suites/{quote(suite_id, safe='')}/run", body=body)
842
+ except PalApiError as e:
843
+ if e.status != 422:
844
+ raise
845
+ try:
846
+ data = json.loads(e.body)
847
+ except ValueError:
848
+ raise e from None
849
+ data["regressed"] = True
850
+ return EvalSuiteRunResult.from_dict(data or {})
851
+
852
+ async def generate_suite(
853
+ self, agent_name: str, *, goal: str = "", max_cases: int | None = None
854
+ ) -> GeneratedEvalSuite:
855
+ """Draft a suite from the agent's instructions, runs and feedback.
856
+
857
+ Never saved: approve by passing ``result.draft`` fields to ``upsert_suite``.
858
+ """
859
+ body: dict[str, Any] = {"agentName": agent_name}
860
+ if goal:
861
+ body["goal"] = goal
862
+ if max_cases:
863
+ body["maxCases"] = max_cases
864
+ data = await self._c._request("POST", "/v1/eval-suites/generate", body=body)
865
+ return GeneratedEvalSuite.from_dict(data or {})
866
+
867
+ async def calibrate_judge(
868
+ self,
869
+ agent_name: str,
870
+ *,
871
+ rubric: str = "",
872
+ judge_model: str = "",
873
+ limit: int | None = None,
874
+ ) -> EvalCalibration:
875
+ """Re-judge runs that carry human feedback; reports agreement and Cohen's kappa."""
876
+ body: dict[str, Any] = {"agentName": agent_name}
877
+ if rubric:
878
+ body["rubric"] = rubric
879
+ if judge_model:
880
+ body["judgeModel"] = judge_model
881
+ if limit:
882
+ body["limit"] = limit
883
+ data = await self._c._request("POST", "/v1/eval-judge/calibrate", body=body)
884
+ return EvalCalibration.from_dict(data or {})
885
+
886
+ async def list_runs(
887
+ self,
888
+ *,
889
+ suite_id: str | None = None,
890
+ agent_name: str | None = None,
891
+ branch: str | None = None,
892
+ ) -> list[dict[str, Any]]:
893
+ """List eval runs."""
894
+ data = await self._c._request(
895
+ "GET",
896
+ "/v1/eval-runs",
897
+ params={
898
+ "suiteId": suite_id,
899
+ "agentName": agent_name,
900
+ "branch": branch,
901
+ },
902
+ )
903
+ return data or []
904
+
905
+ async def set_baseline(self, agent_name: str, branch: str, eval_run_id: str) -> None:
906
+ """Pin an eval run as the baseline for a branch."""
907
+ await self._c._request(
908
+ "POST",
909
+ "/v1/eval-baselines",
910
+ body={
911
+ "agentName": agent_name,
912
+ "branch": branch,
913
+ "evalRunId": eval_run_id,
914
+ },
915
+ )
916
+
917
+ async def get_baseline(self, agent_name: str, branch: str) -> dict[str, Any]:
918
+ """Get the pinned baseline for (agent, branch)."""
919
+ data = await self._c._request(
920
+ "GET",
921
+ "/v1/eval-baselines",
922
+ params={
923
+ "agentName": agent_name,
924
+ "branch": branch,
925
+ },
926
+ )
927
+ return data or {}
928
+
929
+ # ------------------------------------------------------------------
930
+ # experiments namespace
931
+ # ------------------------------------------------------------------
932
+
933
+ class _Experiments:
934
+ def __init__(self, client: PalClient) -> None:
935
+ self._c = client
936
+
937
+ async def create(
938
+ self,
939
+ agent_name: str,
940
+ name: str,
941
+ *,
942
+ variant_a_version: str,
943
+ variant_b_version: str,
944
+ traffic_split_b: int = 50,
945
+ eval_suite_id: str = "",
946
+ auto_promote: bool = False,
947
+ min_runs_to_promote: int = 0,
948
+ ) -> dict[str, Any]:
949
+ """Create an A/B experiment (POST /v1/experiments)."""
950
+ data = await self._c._request(
951
+ "POST",
952
+ "/v1/experiments",
953
+ body={
954
+ "agentName": agent_name,
955
+ "name": name,
956
+ "variantAVersion": variant_a_version,
957
+ "variantBVersion": variant_b_version,
958
+ "trafficSplitB": traffic_split_b,
959
+ "evalSuiteId": eval_suite_id,
960
+ "autoPromote": auto_promote,
961
+ "minRunsToPromote": min_runs_to_promote,
962
+ },
963
+ )
964
+ return data or {}
965
+
966
+ async def list(self) -> list[dict[str, Any]]:
967
+ """List all experiments."""
968
+ data = await self._c._request("GET", "/v1/experiments")
969
+ return data or []
970
+
971
+ async def get(self, experiment_id: str) -> dict[str, Any]:
972
+ """Get a single experiment."""
973
+ data = await self._c._request("GET", f"/v1/experiments/{experiment_id}")
974
+ return data or {}
975
+
976
+ async def record_outcome(
977
+ self,
978
+ experiment_id: str,
979
+ variant: str,
980
+ score: float,
981
+ ) -> None:
982
+ """Record a per-run outcome score for a variant (0..1).
983
+
984
+ The control plane updates rolling stats and may auto-promote a winner.
985
+ """
986
+ await self._c._request(
987
+ "POST",
988
+ f"/v1/experiments/{experiment_id}/record",
989
+ body={
990
+ "variant": variant,
991
+ "score": score,
992
+ },
993
+ )
994
+
995
+ async def conclude(
996
+ self,
997
+ experiment_id: str,
998
+ winner: str,
999
+ promote: bool = False,
1000
+ ) -> None:
1001
+ """Manually conclude an experiment and optionally promote the winner."""
1002
+ await self._c._request(
1003
+ "POST",
1004
+ f"/v1/experiments/{experiment_id}/conclude",
1005
+ body={
1006
+ "winner": winner,
1007
+ "promote": promote,
1008
+ },
1009
+ )
1010
+
1011
+ # ------------------------------------------------------------------
1012
+ # marketplace namespace
1013
+ # ------------------------------------------------------------------
1014
+
1015
+ class _Marketplace:
1016
+ def __init__(self, client: PalClient) -> None:
1017
+ self._c = client
1018
+
1019
+ async def list(
1020
+ self,
1021
+ *,
1022
+ category: str | None = None,
1023
+ query: str | None = None,
1024
+ ) -> list[dict[str, Any]]:
1025
+ """List published marketplace agents."""
1026
+ data = await self._c._request(
1027
+ "GET",
1028
+ "/v1/marketplace",
1029
+ params={
1030
+ "category": category,
1031
+ "q": query,
1032
+ },
1033
+ )
1034
+ return data or []
1035
+
1036
+ async def get(self, slug: str) -> dict[str, Any]:
1037
+ """Get a marketplace entry by slug."""
1038
+ data = await self._c._request("GET", f"/v1/marketplace/{slug}")
1039
+ return data or {}
1040
+
1041
+ async def publish(
1042
+ self,
1043
+ agent_name: str,
1044
+ slug: str,
1045
+ category: str,
1046
+ tags: list[str] | None = None,
1047
+ ) -> dict[str, Any]:
1048
+ """Publish a tenant-local agent to the marketplace."""
1049
+ data = await self._c._request(
1050
+ "POST",
1051
+ "/v1/marketplace/publish",
1052
+ body={
1053
+ "agentName": agent_name,
1054
+ "slug": slug,
1055
+ "category": category,
1056
+ "tags": tags or [],
1057
+ },
1058
+ )
1059
+ return data or {}
1060
+
1061
+ async def fork(self, slug: str, new_name: str) -> AgentInfo:
1062
+ """Fork a marketplace agent into the caller's tenant."""
1063
+ data = await self._c._request(
1064
+ "POST",
1065
+ f"/v1/marketplace/{slug}/fork",
1066
+ body={
1067
+ "name": new_name,
1068
+ },
1069
+ )
1070
+ return AgentInfo.model_validate(data)
1071
+
1072
+ async def star(self, slug: str) -> None:
1073
+ """Star a marketplace agent."""
1074
+ await self._c._request("POST", f"/v1/marketplace/{slug}/star")
1075
+
1076
+ async def unstar(self, slug: str) -> None:
1077
+ """Unstar a marketplace agent."""
1078
+ await self._c._request("DELETE", f"/v1/marketplace/{slug}/star")
1079
+
1080
+ # ------------------------------------------------------------------
1081
+ # mcp namespace
1082
+ # ------------------------------------------------------------------
1083
+
1084
+ class _MCP:
1085
+ def __init__(self, client: PalClient) -> None:
1086
+ self._c = client
1087
+
1088
+ async def list_servers(
1089
+ self,
1090
+ *,
1091
+ category: str | None = None,
1092
+ query: str | None = None,
1093
+ ) -> list[dict[str, Any]]:
1094
+ """List curated MCP servers (GET /v1/mcp/servers)."""
1095
+ data = await self._c._request(
1096
+ "GET",
1097
+ "/v1/mcp/servers",
1098
+ params={
1099
+ "category": category,
1100
+ "q": query,
1101
+ },
1102
+ )
1103
+ return data or []
1104
+
1105
+ async def get_server(self, slug: str) -> dict[str, Any]:
1106
+ """Get a single MCP server entry."""
1107
+ data = await self._c._request("GET", f"/v1/mcp/servers/{slug}")
1108
+ return data or {}
1109
+
1110
+ async def attach(
1111
+ self,
1112
+ agent_name: str,
1113
+ slug: str,
1114
+ config: dict[str, Any] | None = None,
1115
+ ) -> None:
1116
+ """Attach an MCP server (catalog or tenant) to an agent.
1117
+
1118
+ ``config={"vmId": ...}`` is required for stdio catalog servers.
1119
+ """
1120
+ await self._c._request(
1121
+ "POST",
1122
+ f"/v1/agents/{agent_name}/mcp-servers",
1123
+ body={
1124
+ "serverSlug": slug,
1125
+ "config": config or {},
1126
+ },
1127
+ )
1128
+
1129
+ async def detach(self, agent_name: str, slug: str) -> None:
1130
+ """Detach an MCP server from an agent."""
1131
+ await self._c._request("DELETE", f"/v1/agents/{agent_name}/mcp-servers/{slug}")
1132
+
1133
+ async def list_attachments(self, agent_name: str) -> list[dict[str, Any]]:
1134
+ """List MCP servers attached to an agent."""
1135
+ data = await self._c._request("GET", f"/v1/agents/{agent_name}/mcp-servers")
1136
+ return data or []
1137
+
1138
+ async def list_attachment_tools(self, agent_name: str, slug: str) -> dict[str, Any]:
1139
+ """Live tools/list of an attached server (also a connection test)."""
1140
+ data = await self._c._request("GET", f"/v1/agents/{agent_name}/mcp-servers/{slug}/tools")
1141
+ return data or {}
1142
+
1143
+ async def create_server(
1144
+ self,
1145
+ slug: str,
1146
+ url: str,
1147
+ auth_type: str,
1148
+ *,
1149
+ name: str | None = None,
1150
+ description: str | None = None,
1151
+ ) -> dict[str, Any]:
1152
+ """Register a tenant (BYO) remote MCP server; auth_type: none|bearer|oauth."""
1153
+ body: dict[str, Any] = {"slug": slug, "url": url, "authType": auth_type}
1154
+ if name:
1155
+ body["name"] = name
1156
+ if description:
1157
+ body["description"] = description
1158
+ data = await self._c._request("POST", "/v1/mcp/tenant-servers", body=body)
1159
+ return data or {}
1160
+
1161
+ async def list_tenant_servers(self) -> list[dict[str, Any]]:
1162
+ """List tenant-registered MCP servers."""
1163
+ data = await self._c._request("GET", "/v1/mcp/tenant-servers")
1164
+ return data or []
1165
+
1166
+ async def delete_server(self, slug: str) -> None:
1167
+ """Remove a tenant-registered MCP server."""
1168
+ await self._c._request("DELETE", f"/v1/mcp/tenant-servers/{slug}")
1169
+
1170
+ async def list_credentials(self) -> list[dict[str, Any]]:
1171
+ """List stored credential metadata (secrets are never returned)."""
1172
+ data = await self._c._request("GET", "/v1/mcp/credentials")
1173
+ return data or []
1174
+
1175
+ async def put_bearer(self, slug: str, token: str) -> dict[str, Any]:
1176
+ """Store a static bearer token for an MCP server."""
1177
+ data = await self._c._request("PUT", f"/v1/mcp/credentials/{slug}", body={"token": token})
1178
+ return data or {}
1179
+
1180
+ async def delete_credential(self, slug: str) -> None:
1181
+ """Remove the stored credential for an MCP server."""
1182
+ await self._c._request("DELETE", f"/v1/mcp/credentials/{slug}")
1183
+
1184
+ async def oauth_start(
1185
+ self,
1186
+ server_slug: str,
1187
+ *,
1188
+ scope: str | None = None,
1189
+ client_id: str | None = None,
1190
+ client_secret: str | None = None,
1191
+ ) -> dict[str, Any]:
1192
+ """Begin OAuth 2.1 (PKCE); returns {authorizationUrl, redirectUri, expiresAt}."""
1193
+ body: dict[str, Any] = {"serverSlug": server_slug}
1194
+ if scope:
1195
+ body["scope"] = scope
1196
+ if client_id:
1197
+ body["clientId"] = client_id
1198
+ if client_secret:
1199
+ body["clientSecret"] = client_secret
1200
+ data = await self._c._request("POST", "/v1/mcp/oauth/start", body=body)
1201
+ return data or {}
1202
+
1203
+ async def oauth_callback(self, code: str, state: str) -> dict[str, Any]:
1204
+ """Complete OAuth with the code/state the authorization server returned."""
1205
+ data = await self._c._request("POST", "/v1/mcp/oauth/callback", body={"code": code, "state": state})
1206
+ return data or {}
1207
+
1208
+ # ------------------------------------------------------------------
1209
+ # receipts namespace
1210
+ # ------------------------------------------------------------------
1211
+
1212
+ class _Receipts:
1213
+ def __init__(self, client: PalClient) -> None:
1214
+ self._c = client
1215
+
1216
+ async def issue(self, run_id: str) -> dict[str, Any]:
1217
+ """Issue and persist a signed receipt for a completed run."""
1218
+ data = await self._c._request("POST", f"/v1/runs/{run_id}/receipt")
1219
+ return data or {}
1220
+
1221
+ async def verify(self, receipt: dict[str, Any]) -> ReceiptVerifyResult:
1222
+ """Verify a receipt signature (no auth required)."""
1223
+ data = await self._c._request("POST", "/v1/runs/receipts/verify", body=receipt)
1224
+ return ReceiptVerifyResult(
1225
+ valid=data.get("valid", False),
1226
+ reason=data.get("reason"),
1227
+ run_id=data.get("runId"),
1228
+ issued_at=data.get("issuedAt"),
1229
+ tenant_id=data.get("tenantId"),
1230
+ )
1231
+
1232
+ # ------------------------------------------------------------------
1233
+ # feedback namespace
1234
+ # ------------------------------------------------------------------
1235
+
1236
+ class _Feedback:
1237
+ def __init__(self, client: PalClient) -> None:
1238
+ self._c = client
1239
+
1240
+ async def submit(
1241
+ self,
1242
+ run_id: str,
1243
+ *,
1244
+ score: int,
1245
+ comment: str = "",
1246
+ preferred_output: str = "",
1247
+ source: str = "sdk",
1248
+ ) -> None:
1249
+ """Submit human feedback for a run (score 1..5)."""
1250
+ await self._c._request(
1251
+ "POST",
1252
+ f"/v1/runs/{run_id}/feedback",
1253
+ body={
1254
+ "score": score,
1255
+ "comment": comment,
1256
+ "preferredOutput": preferred_output,
1257
+ "source": source,
1258
+ },
1259
+ )
1260
+
1261
+ async def list_for_run(self, run_id: str) -> list[dict[str, Any]]:
1262
+ """List feedback entries for a run."""
1263
+ data = await self._c._request("GET", f"/v1/runs/{run_id}/feedback")
1264
+ return data or []
1265
+
1266
+ async def summary_for_agent(self, agent_name: str) -> FeedbackSummary:
1267
+ """Get aggregate feedback summary for an agent."""
1268
+ data = await self._c._request("GET", f"/v1/agents/{agent_name}/feedback")
1269
+ return FeedbackSummary(
1270
+ agent_name=data.get("agentName", agent_name),
1271
+ total_feedback=data.get("totalFeedback", 0),
1272
+ avg_score=data.get("avgScore", 0.0),
1273
+ thumbs_up=data.get("thumbsUp", 0),
1274
+ thumbs_down=data.get("thumbsDown", 0),
1275
+ runs_with_preferred_output=data.get("runsWithPreferredOutput", 0),
1276
+ last_7_days_avg_score=data.get("last7DaysAvgScore", 0.0),
1277
+ )
1278
+
1279
+ # ------------------------------------------------------------------
1280
+ # rehearsals namespace
1281
+ # ------------------------------------------------------------------
1282
+ # runtime namespace (microVMs)
1283
+ # ------------------------------------------------------------------
1284
+
1285
+ class _Runtime:
1286
+ def __init__(self, client: PalClient) -> None:
1287
+ self._c = client
1288
+
1289
+ async def schedule(self, spec: dict[str, Any]) -> dict[str, Any]:
1290
+ """Submit an AgentSpec to schedule a microVM workload.
1291
+
1292
+ Pass ``idle_timeout_secs`` (int) in *spec* to enable idle-suspend
1293
+ auto-pause: the VM will be automatically snapshotted and stopped
1294
+ after that many seconds of inactivity (no running exec/workload
1295
+ child). 0 or absent means never auto-suspend. Exec, ExecTool, and
1296
+ file-API requests to an auto-suspended VM transparently resume it.
1297
+ """
1298
+ return await self._c._request("POST", "/v1/runtime/schedule", body=spec)
1299
+
1300
+ async def list(self, *, state: str | None = None, limit: int | None = None) -> list[dict[str, Any]]:
1301
+ data = await self._c._request("GET", "/v1/runtime/vms", params={"state": state, "limit": limit})
1302
+ return self._c._items(data, "vms")
1303
+
1304
+ async def get(self, vm_id: str) -> dict[str, Any]:
1305
+ """Bare VM row (the detail endpoint wraps it as ``{vm, events}``)."""
1306
+ data = await self._c._request("GET", f"/v1/runtime/vms/{vm_id}")
1307
+ if isinstance(data, dict) and isinstance(data.get("vm"), dict):
1308
+ return data["vm"]
1309
+ return data
1310
+
1311
+ async def terminate(self, vm_id: str, *, grace: str | None = None) -> None:
1312
+ await self._c._request("DELETE", f"/v1/runtime/vms/{vm_id}", params={"grace": grace})
1313
+
1314
+ async def exec(self, vm_id: str, command: str, argv: list[str] | None = None) -> dict[str, Any]:
1315
+ """Buffered exec (execve-style: ``command`` is the executable)."""
1316
+ return await self._c._request(
1317
+ "POST", f"/v1/runtime/vms/{vm_id}/exec", body={"command": command, "argv": argv or []}
1318
+ )
1319
+
1320
+ async def exec_stream(
1321
+ self, vm_id: str, command: str, argv: list[str] | None = None
1322
+ ) -> AsyncIterator[ExecStreamEvent]:
1323
+ """Streaming exec over SSE: stdout/stderr chunks, then one ``exit`` event.
1324
+
1325
+ Raises PalApiError on non-2xx and on an SSE ``error`` event.
1326
+ """
1327
+ client = await self._c._get_client()
1328
+ headers = {**self._c._headers(), "Accept": "text/event-stream"}
1329
+ body = json.dumps({"command": command, "argv": argv or []})
1330
+ async with client.stream("POST", f"/v1/runtime/vms/{vm_id}/exec", headers=headers, content=body) as resp:
1331
+ if not resp.is_success:
1332
+ raw = await resp.aread()
1333
+ raise PalApiError(resp.status_code, raw.decode("utf-8", errors="replace"))
1334
+
1335
+ event, data = "message", ""
1336
+ buffer = ""
1337
+ # aiter_text decodes incrementally, so split multibyte chars are safe.
1338
+ async for chunk in resp.aiter_text():
1339
+ buffer += chunk
1340
+ while "\n" in buffer:
1341
+ line, buffer = buffer.split("\n", 1)
1342
+ line = line.rstrip("\r")
1343
+ if line == "":
1344
+ if data:
1345
+ out = self._parse_exec_event(event, data)
1346
+ if out is not None:
1347
+ yield out
1348
+ if out.type == "exit":
1349
+ return
1350
+ event, data = "message", ""
1351
+ elif line.startswith("event:"):
1352
+ event = line[6:].strip()
1353
+ elif line.startswith("data:"):
1354
+ data = line[5:].strip()
1355
+
1356
+ @staticmethod
1357
+ def _parse_exec_event(event: str, data: str) -> ExecStreamEvent | None:
1358
+ try:
1359
+ payload = json.loads(data)
1360
+ except ValueError:
1361
+ return None
1362
+ if not isinstance(payload, dict):
1363
+ return None
1364
+ if event in ("stdout", "stderr"):
1365
+ return ExecStreamEvent(type=event, data=str(payload.get("data", "")))
1366
+ if event == "exit":
1367
+ return ExecStreamEvent(type="exit", exit_code=int(payload.get("exitCode", 0)))
1368
+ if event == "error":
1369
+ raise PalApiError(500, str(payload.get("error") or payload.get("message") or "exec stream error"))
1370
+ return None
1371
+
1372
+ async def pause(self, vm_id: str) -> VmPauseResult:
1373
+ """Snapshot + pause a running VM. 409 if not running."""
1374
+ data = await self._c._request("POST", f"/v1/runtime/vms/{vm_id}/pause")
1375
+ return VmPauseResult.model_validate(data)
1376
+
1377
+ async def resume(self, vm_id: str) -> VmResumeResult:
1378
+ """Resume a paused VM. 402 quota exceeded, 409 if not paused."""
1379
+ data = await self._c._request("POST", f"/v1/runtime/vms/{vm_id}/resume")
1380
+ return VmResumeResult.model_validate(data)
1381
+
1382
+ async def fork(self, vm_id: str, *, count: int = 1) -> VmForkResult:
1383
+ """Fork ``count`` (1..PAL_MAX_FORK_COUNT, default cap 100) VMs from a snapshot. Per-fork failures are in ``forks[].error``."""
1384
+ data = await self._c._request("POST", f"/v1/runtime/vms/{vm_id}/fork", body={"count": count})
1385
+ return VmForkResult.model_validate(data)
1386
+
1387
+ async def list_files(self, vm_id: str, path: str | None = None) -> dict[str, Any]:
1388
+ """List a directory under the VM's /workspace (default: the root).
1389
+
1390
+ Returns ``{path, entries: [{name, type, size}], truncated}``.
1391
+ """
1392
+ return await self._c._request("GET", f"/v1/runtime/vms/{vm_id}/files", params={"path": path})
1393
+
1394
+ async def read_file(self, vm_id: str, path: str) -> dict[str, Any]:
1395
+ """Read a UTF-8 text file (≤ 1 MiB). Returns ``{content, truncated}``."""
1396
+ client = await self._c._get_client()
1397
+ resp = await client.get(
1398
+ f"/v1/runtime/vms/{vm_id}/files/content", params={"path": path}, headers=self._c._headers()
1399
+ )
1400
+ if not resp.is_success:
1401
+ raise PalApiError(resp.status_code, resp.text)
1402
+ # x-pal-truncated: legacy fallback
1403
+ truncated = resp.headers.get("x-pal-truncated") or resp.headers.get("x-pal-truncated")
1404
+ return {"content": resp.text, "truncated": truncated == "true"}
1405
+
1406
+ async def write_file(self, vm_id: str, path: str, content: str) -> dict[str, Any]:
1407
+ """Create or overwrite a UTF-8 text file (≤ 1 MiB; 413 above). Returns ``{path, bytesWritten}``."""
1408
+ client = await self._c._get_client()
1409
+ headers = {**self._c._headers(), "Content-Type": "text/plain; charset=utf-8"}
1410
+ resp = await client.put(
1411
+ f"/v1/runtime/vms/{vm_id}/files/content",
1412
+ params={"path": path},
1413
+ headers=headers,
1414
+ content=content.encode("utf-8"),
1415
+ )
1416
+ if not resp.is_success:
1417
+ raise PalApiError(resp.status_code, resp.text)
1418
+ return resp.json()
1419
+
1420
+ # ------------------------------------------------------------------
1421
+
1422
+ class _A2A:
1423
+ """A2A v0.3 client (JSON-RPC). Tasks/cards are returned as plain dicts."""
1424
+
1425
+ def __init__(self, client: PalClient) -> None:
1426
+ self._c = client
1427
+
1428
+ async def get_card(self, agent: str) -> dict[str, Any]:
1429
+ return await self._c._request("GET", f"/v1/agents/{quote(agent, safe='')}/a2a/.well-known/agent-card.json")
1430
+
1431
+ async def send_message(self, agent: str, text: str, blocking: bool = False) -> dict[str, Any]:
1432
+ message = {
1433
+ "kind": "message",
1434
+ "messageId": str(uuid.uuid4()),
1435
+ "role": "user",
1436
+ "parts": [{"kind": "text", "text": text}],
1437
+ }
1438
+ return await self._rpc(agent, "message/send", {"message": message, "configuration": {"blocking": blocking}})
1439
+
1440
+ async def get_task(self, agent: str, task_id: str) -> dict[str, Any]:
1441
+ return await self._rpc(agent, "tasks/get", {"id": task_id})
1442
+
1443
+ async def cancel_task(self, agent: str, task_id: str) -> dict[str, Any]:
1444
+ return await self._rpc(agent, "tasks/cancel", {"id": task_id})
1445
+
1446
+ async def _rpc(self, agent: str, method: str, params: dict[str, Any]) -> dict[str, Any]:
1447
+ req = {"jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": method, "params": params}
1448
+ data = await self._c._request("POST", f"/v1/agents/{quote(agent, safe='')}/a2a", body=req) or {}
1449
+ if err := data.get("error"):
1450
+ raise PalApiError(200, str(err.get("message", "")), code=err.get("code"))
1451
+ if "result" not in data:
1452
+ raise PalApiError(200, "a2a: response missing result")
1453
+ return data["result"]
1454
+
1455
+ class _Rehearsals:
1456
+ def __init__(self, client: PalClient) -> None:
1457
+ self._c = client
1458
+
1459
+ async def pull(
1460
+ self,
1461
+ agent_name: str,
1462
+ *,
1463
+ window: str = "",
1464
+ include_failures: bool = True,
1465
+ include_low_score: bool = True,
1466
+ limit: int = 0,
1467
+ ) -> RehearseResponse:
1468
+ """Pull past failed/low-score runs as synthetic test cases.
1469
+
1470
+ Results can be replayed locally and posted back via evals.record_run()
1471
+ to gate merges through the existing baseline machinery.
1472
+ """
1473
+ body: dict[str, Any] = {
1474
+ "agentName": agent_name,
1475
+ "includeFailures": include_failures,
1476
+ "includeLowScore": include_low_score,
1477
+ }
1478
+ if window:
1479
+ body["window"] = window
1480
+ if limit > 0:
1481
+ body["limit"] = limit
1482
+ data = await self._c._request("POST", "/v1/runs/rehearse", body=body)
1483
+ return RehearseResponse(
1484
+ agent_name=(data or {}).get("agentName", agent_name),
1485
+ window=(data or {}).get("window", window),
1486
+ cases=(data or {}).get("cases", []),
1487
+ count=(data or {}).get("count", 0),
1488
+ reason=(data or {}).get("reason"),
1489
+ )
1490
+
1491
+ class _Debug:
1492
+ def __init__(self, client: PalClient) -> None:
1493
+ self._c = client
1494
+
1495
+ async def analyze(
1496
+ self,
1497
+ kind: str,
1498
+ *,
1499
+ run_id: str = "",
1500
+ incident_id: str = "",
1501
+ agent_name: str = "",
1502
+ case: str = "",
1503
+ question: str = "",
1504
+ ) -> DebugReport:
1505
+ """Grounded root-cause report for a run, incident or eval case (``kind``).
1506
+
1507
+ Never applies anything; proposals are data a human applies through the
1508
+ existing endpoints. Errors raise ``PalApiError`` (400 no_provider,
1509
+ 402 budget_exceeded, 404, 502 llm_failed/bad_report).
1510
+ """
1511
+ payload = {
1512
+ "kind": kind,
1513
+ "runId": run_id,
1514
+ "incidentId": incident_id,
1515
+ "agentName": agent_name,
1516
+ "case": case,
1517
+ "question": question,
1518
+ }
1519
+ body = {k: v for k, v in payload.items() if v}
1520
+ data = await self._c._request("POST", "/v1/debug/analyze", body=body)
1521
+ return DebugReport.from_dict(data or {})
1522
+
1523
+ class _Support:
1524
+ def __init__(self, client: PalClient) -> None:
1525
+ self._c = client
1526
+
1527
+ async def ask(
1528
+ self,
1529
+ question: str,
1530
+ *,
1531
+ run_id: str = "",
1532
+ history: list[dict[str, str]] | None = None,
1533
+ ) -> SupportAnswer:
1534
+ """Ask the support agent. ``history`` items are ``{"role": "user"|"agent", "text": ...}``.
1535
+
1536
+ Never applies anything; returned actions are data.
1537
+ """
1538
+ body: dict[str, Any] = {"question": question}
1539
+ if run_id:
1540
+ body["runId"] = run_id
1541
+ if history:
1542
+ body["history"] = history
1543
+ data = await self._c._request("POST", "/v1/support/ask", body=body)
1544
+ return SupportAnswer.from_dict(data or {})
1545
+
1546
+ async def escalate(
1547
+ self,
1548
+ question: str,
1549
+ *,
1550
+ run_id: str = "",
1551
+ incident_id: str = "",
1552
+ transcript: list[dict[str, str]] | None = None,
1553
+ ) -> SupportEscalation:
1554
+ """File a signed escalation bundle. Never applies anything."""
1555
+ body: dict[str, Any] = {"question": question}
1556
+ if run_id:
1557
+ body["runId"] = run_id
1558
+ if incident_id:
1559
+ body["incidentId"] = incident_id
1560
+ if transcript:
1561
+ body["transcript"] = transcript
1562
+ data = await self._c._request("POST", "/v1/support/escalations", body=body)
1563
+ return SupportEscalation.from_dict(data or {})
1564
+
1565
+ async def list_escalations(self) -> list[SupportEscalation]:
1566
+ """List escalations (no signature/bundle in list entries)."""
1567
+ data = await self._c._request("GET", "/v1/support/escalations")
1568
+ return [SupportEscalation.from_dict(e) for e in (data or {}).get("escalations") or []]
1569
+
1570
+ async def get_escalation(self, escalation_id: str) -> SupportEscalation:
1571
+ """Fetch one escalation including signature and bundle."""
1572
+ data = await self._c._request("GET", f"/v1/support/escalations/{quote(escalation_id, safe='')}")
1573
+ return SupportEscalation.from_dict(data or {})
1574
+
1575
+
1576
+ # ---------------------------------------------------------------------------
1577
+ # Response wrappers
1578
+ # ---------------------------------------------------------------------------
1579
+
1580
+
1581
+ class AgentListResponse:
1582
+ __slots__ = ("agents", "next_page_token")
1583
+
1584
+ def __init__(self, agents: list[AgentInfo], next_page_token: str | None = None) -> None:
1585
+ self.agents = agents
1586
+ self.next_page_token = next_page_token
1587
+
1588
+
1589
+ class RunListResponse:
1590
+ __slots__ = ("runs", "next_page_token")
1591
+
1592
+ def __init__(self, runs: list[Run], next_page_token: str | None = None) -> None:
1593
+ self.runs = runs
1594
+ self.next_page_token = next_page_token
1595
+
1596
+
1597
+ class SessionListResponse:
1598
+ __slots__ = ("sessions", "next_page_token")
1599
+
1600
+ def __init__(self, sessions: list[Session], next_page_token: str | None = None) -> None:
1601
+ self.sessions = sessions
1602
+ self.next_page_token = next_page_token
1603
+
1604
+
1605
+ class ConnectorListResponse:
1606
+ __slots__ = ("connectors", "next_page_token")
1607
+
1608
+ def __init__(self, connectors: list[ConnectorInfo], next_page_token: str | None = None) -> None:
1609
+ self.connectors = connectors
1610
+ self.next_page_token = next_page_token
1611
+
1612
+
1613
+ class ForecastResult:
1614
+ """Result of a cost/token forecast for a prospective run."""
1615
+
1616
+ __slots__ = (
1617
+ "agent_name",
1618
+ "model",
1619
+ "provider",
1620
+ "estimated_tokens_in",
1621
+ "estimated_tokens_out",
1622
+ "estimated_cost_usd",
1623
+ "confidence",
1624
+ "would_exceed_budget",
1625
+ "block_reason",
1626
+ "reasoning",
1627
+ )
1628
+
1629
+ def __init__(
1630
+ self,
1631
+ *,
1632
+ agent_name: str,
1633
+ model: str,
1634
+ provider: str,
1635
+ estimated_tokens_in: int,
1636
+ estimated_tokens_out: int,
1637
+ estimated_cost_usd: float,
1638
+ confidence: float,
1639
+ would_exceed_budget: bool,
1640
+ block_reason: str | None,
1641
+ reasoning: dict[str, Any] | None,
1642
+ ) -> None:
1643
+ self.agent_name = agent_name
1644
+ self.model = model
1645
+ self.provider = provider
1646
+ self.estimated_tokens_in = estimated_tokens_in
1647
+ self.estimated_tokens_out = estimated_tokens_out
1648
+ self.estimated_cost_usd = estimated_cost_usd
1649
+ self.confidence = confidence
1650
+ self.would_exceed_budget = would_exceed_budget
1651
+ self.block_reason = block_reason
1652
+ self.reasoning = reasoning
1653
+
1654
+
1655
+ class BudgetResult:
1656
+ """A per-agent budget policy."""
1657
+
1658
+ __slots__ = (
1659
+ "agent_name",
1660
+ "max_cost_usd_per_day",
1661
+ "max_cost_usd_per_run",
1662
+ "max_runs_per_day",
1663
+ "tool_limits",
1664
+ "hard_fail",
1665
+ "notify_at_pct",
1666
+ )
1667
+
1668
+ def __init__(
1669
+ self,
1670
+ *,
1671
+ agent_name: str,
1672
+ max_cost_usd_per_day: float | None = None,
1673
+ max_cost_usd_per_run: float | None = None,
1674
+ max_runs_per_day: int | None = None,
1675
+ tool_limits: dict[str, int] | None = None,
1676
+ hard_fail: bool = False,
1677
+ notify_at_pct: int | None = None,
1678
+ ) -> None:
1679
+ self.agent_name = agent_name
1680
+ self.max_cost_usd_per_day = max_cost_usd_per_day
1681
+ self.max_cost_usd_per_run = max_cost_usd_per_run
1682
+ self.max_runs_per_day = max_runs_per_day
1683
+ self.tool_limits = tool_limits
1684
+ self.hard_fail = hard_fail
1685
+ self.notify_at_pct = notify_at_pct
1686
+
1687
+ @classmethod
1688
+ def from_dict(cls, d: dict[str, Any]) -> BudgetResult:
1689
+ return cls(
1690
+ agent_name=d.get("agentName", ""),
1691
+ max_cost_usd_per_day=d.get("maxCostUsdPerDay"),
1692
+ max_cost_usd_per_run=d.get("maxCostUsdPerRun"),
1693
+ max_runs_per_day=d.get("maxRunsPerDay"),
1694
+ tool_limits=d.get("toolLimits"),
1695
+ hard_fail=d.get("hardFail", False),
1696
+ notify_at_pct=d.get("notifyAtPct"),
1697
+ )
1698
+
1699
+
1700
+ class EvalRunResult:
1701
+ """Server-side score and regression flag for an eval run."""
1702
+
1703
+ __slots__ = ("id", "passed", "score", "cases_total", "cases_passed", "regressed", "baseline_score")
1704
+
1705
+ def __init__(
1706
+ self,
1707
+ *,
1708
+ id: str,
1709
+ passed: bool,
1710
+ score: float,
1711
+ cases_total: int,
1712
+ cases_passed: int,
1713
+ regressed: bool,
1714
+ baseline_score: float | None,
1715
+ ) -> None:
1716
+ self.id = id
1717
+ self.passed = passed
1718
+ self.score = score
1719
+ self.cases_total = cases_total
1720
+ self.cases_passed = cases_passed
1721
+ self.regressed = regressed
1722
+ self.baseline_score = baseline_score
1723
+
1724
+ @classmethod
1725
+ def from_dict(cls, d: dict[str, Any]) -> EvalRunResult:
1726
+ return cls(
1727
+ id=d.get("id", ""),
1728
+ passed=d.get("passed", False),
1729
+ score=d.get("score", 0.0),
1730
+ cases_total=d.get("casesTotal", 0),
1731
+ cases_passed=d.get("casesPassed", 0),
1732
+ regressed=d.get("regressed", False),
1733
+ baseline_score=d.get("baselineScore"),
1734
+ )
1735
+
1736
+
1737
+ class ReceiptVerifyResult:
1738
+ """Result of verifying a signed run receipt."""
1739
+
1740
+ __slots__ = ("valid", "reason", "run_id", "issued_at", "tenant_id")
1741
+
1742
+ def __init__(
1743
+ self,
1744
+ *,
1745
+ valid: bool,
1746
+ reason: str | None,
1747
+ run_id: str | None,
1748
+ issued_at: str | None,
1749
+ tenant_id: str | None,
1750
+ ) -> None:
1751
+ self.valid = valid
1752
+ self.reason = reason
1753
+ self.run_id = run_id
1754
+ self.issued_at = issued_at
1755
+ self.tenant_id = tenant_id
1756
+
1757
+
1758
+ class FeedbackSummary:
1759
+ """Aggregate feedback summary for an agent."""
1760
+
1761
+ __slots__ = (
1762
+ "agent_name",
1763
+ "total_feedback",
1764
+ "avg_score",
1765
+ "thumbs_up",
1766
+ "thumbs_down",
1767
+ "runs_with_preferred_output",
1768
+ "last_7_days_avg_score",
1769
+ )
1770
+
1771
+ def __init__(
1772
+ self,
1773
+ *,
1774
+ agent_name: str,
1775
+ total_feedback: int,
1776
+ avg_score: float,
1777
+ thumbs_up: int,
1778
+ thumbs_down: int,
1779
+ runs_with_preferred_output: int,
1780
+ last_7_days_avg_score: float,
1781
+ ) -> None:
1782
+ self.agent_name = agent_name
1783
+ self.total_feedback = total_feedback
1784
+ self.avg_score = avg_score
1785
+ self.thumbs_up = thumbs_up
1786
+ self.thumbs_down = thumbs_down
1787
+ self.runs_with_preferred_output = runs_with_preferred_output
1788
+ self.last_7_days_avg_score = last_7_days_avg_score
1789
+
1790
+
1791
+ class RehearseResponse:
1792
+ """Synthetic test set returned for rehearsal."""
1793
+
1794
+ __slots__ = ("agent_name", "window", "cases", "count", "reason")
1795
+
1796
+ def __init__(
1797
+ self,
1798
+ *,
1799
+ agent_name: str,
1800
+ window: str,
1801
+ cases: list[dict[str, Any]],
1802
+ count: int,
1803
+ reason: str | None,
1804
+ ) -> None:
1805
+ self.agent_name = agent_name
1806
+ self.window = window
1807
+ self.cases = cases
1808
+ self.count = count
1809
+ self.reason = reason
1810
+
1811
+
1812
+ class AgentPolicyResult:
1813
+ """An agent's policy envelope (``policy`` is the raw Policy dict, incl. ``version``)."""
1814
+
1815
+ __slots__ = ("agent_name", "agent_id", "policy", "updated_at", "updated_by", "warnings")
1816
+
1817
+ def __init__(
1818
+ self,
1819
+ *,
1820
+ agent_name: str,
1821
+ agent_id: str,
1822
+ policy: dict[str, Any],
1823
+ updated_at: str | None,
1824
+ updated_by: str | None,
1825
+ warnings: list[str],
1826
+ ) -> None:
1827
+ self.agent_name = agent_name
1828
+ self.agent_id = agent_id
1829
+ self.policy = policy
1830
+ self.updated_at = updated_at
1831
+ self.updated_by = updated_by
1832
+ self.warnings = warnings
1833
+
1834
+ @classmethod
1835
+ def from_dict(cls, d: dict[str, Any]) -> AgentPolicyResult:
1836
+ return cls(
1837
+ agent_name=d.get("agentName", ""),
1838
+ agent_id=d.get("agentId", ""),
1839
+ policy=d.get("policy") or {},
1840
+ updated_at=d.get("updatedAt"),
1841
+ updated_by=d.get("updatedBy"),
1842
+ warnings=list(d.get("warnings") or []),
1843
+ )
1844
+
1845
+
1846
+ class PolicyProposal:
1847
+ """A least-privilege policy proposal with rationale."""
1848
+
1849
+ __slots__ = ("proposal", "rationale", "sources", "unresolved")
1850
+
1851
+ def __init__(
1852
+ self,
1853
+ *,
1854
+ proposal: dict[str, Any],
1855
+ rationale: list[dict[str, Any]],
1856
+ sources: list[str],
1857
+ unresolved: list[str],
1858
+ ) -> None:
1859
+ self.proposal = proposal
1860
+ self.rationale = rationale
1861
+ self.sources = sources
1862
+ self.unresolved = unresolved
1863
+
1864
+ @classmethod
1865
+ def from_dict(cls, d: dict[str, Any]) -> PolicyProposal:
1866
+ return cls(
1867
+ proposal=d.get("proposal") or {},
1868
+ rationale=list(d.get("rationale") or []),
1869
+ sources=list(d.get("sources") or []),
1870
+ unresolved=list(d.get("unresolved") or []),
1871
+ )
1872
+
1873
+
1874
+ class AgentIdentity:
1875
+ """An agent's cryptographic identity."""
1876
+
1877
+ __slots__ = (
1878
+ "agent_id",
1879
+ "spiffe_id",
1880
+ "key_generation",
1881
+ "status",
1882
+ "public_key_jwk",
1883
+ "jwks_uri",
1884
+ "token_ttl_seconds",
1885
+ "created_at",
1886
+ "rotated_at",
1887
+ "revoked_at",
1888
+ "revoked_reason",
1889
+ )
1890
+
1891
+ def __init__(
1892
+ self,
1893
+ *,
1894
+ agent_id: str,
1895
+ spiffe_id: str,
1896
+ key_generation: int,
1897
+ status: str,
1898
+ public_key_jwk: dict[str, Any],
1899
+ jwks_uri: str,
1900
+ token_ttl_seconds: int,
1901
+ created_at: str | None,
1902
+ rotated_at: str | None,
1903
+ revoked_at: str | None,
1904
+ revoked_reason: str | None,
1905
+ ) -> None:
1906
+ self.agent_id = agent_id
1907
+ self.spiffe_id = spiffe_id
1908
+ self.key_generation = key_generation
1909
+ self.status = status
1910
+ self.public_key_jwk = public_key_jwk
1911
+ self.jwks_uri = jwks_uri
1912
+ self.token_ttl_seconds = token_ttl_seconds
1913
+ self.created_at = created_at
1914
+ self.rotated_at = rotated_at
1915
+ self.revoked_at = revoked_at
1916
+ self.revoked_reason = revoked_reason
1917
+
1918
+ @classmethod
1919
+ def from_dict(cls, d: dict[str, Any]) -> AgentIdentity:
1920
+ return cls(
1921
+ agent_id=d.get("agentId", ""),
1922
+ spiffe_id=d.get("spiffeId", ""),
1923
+ key_generation=d.get("keyGeneration", 0),
1924
+ status=d.get("status", ""),
1925
+ public_key_jwk=d.get("publicKeyJwk") or {},
1926
+ jwks_uri=d.get("jwksUri", ""),
1927
+ token_ttl_seconds=d.get("tokenTtlSeconds", 0),
1928
+ created_at=d.get("createdAt"),
1929
+ rotated_at=d.get("rotatedAt"),
1930
+ revoked_at=d.get("revokedAt"),
1931
+ revoked_reason=d.get("revokedReason"),
1932
+ )
1933
+
1934
+
1935
+ class AgentToken:
1936
+ """A minted agent-identity token."""
1937
+
1938
+ __slots__ = ("token", "expires_at", "jti", "audience")
1939
+
1940
+ def __init__(self, *, token: str, expires_at: str, jti: str, audience: str) -> None:
1941
+ self.token = token
1942
+ self.expires_at = expires_at
1943
+ self.jti = jti
1944
+ self.audience = audience
1945
+
1946
+ @classmethod
1947
+ def from_dict(cls, d: dict[str, Any]) -> AgentToken:
1948
+ return cls(
1949
+ token=d.get("token", ""),
1950
+ expires_at=d.get("expiresAt", ""),
1951
+ jti=d.get("jti", ""),
1952
+ audience=d.get("audience", ""),
1953
+ )
1954
+
1955
+
1956
+ class AgentAuditEvent:
1957
+ """One row of an agent's hash-chained audit log."""
1958
+
1959
+ __slots__ = (
1960
+ "id",
1961
+ "event",
1962
+ "action_kind",
1963
+ "target",
1964
+ "decision",
1965
+ "reason",
1966
+ "run_id",
1967
+ "step_id",
1968
+ "agent_version_id",
1969
+ "jti",
1970
+ "principal",
1971
+ "created_at",
1972
+ )
1973
+
1974
+ def __init__(self, **kw: Any) -> None:
1975
+ for name in self.__slots__:
1976
+ setattr(self, name, kw.get(name))
1977
+
1978
+ @classmethod
1979
+ def from_dict(cls, d: dict[str, Any]) -> AgentAuditEvent:
1980
+ return cls(
1981
+ id=d.get("id"),
1982
+ event=d.get("event"),
1983
+ action_kind=d.get("actionKind"),
1984
+ target=d.get("target"),
1985
+ decision=d.get("decision"),
1986
+ reason=d.get("reason"),
1987
+ run_id=d.get("runId"),
1988
+ step_id=d.get("stepId"),
1989
+ agent_version_id=d.get("agentVersionId"),
1990
+ jti=d.get("jti"),
1991
+ principal=d.get("principal"),
1992
+ created_at=d.get("createdAt"),
1993
+ )
1994
+
1995
+
1996
+ class AgentAuditList:
1997
+ """Audit events plus the chain-integrity verdict."""
1998
+
1999
+ __slots__ = ("events", "chain_valid")
2000
+
2001
+ def __init__(self, *, events: list[AgentAuditEvent], chain_valid: bool) -> None:
2002
+ self.events = events
2003
+ self.chain_valid = chain_valid
2004
+
2005
+ @classmethod
2006
+ def from_dict(cls, d: dict[str, Any]) -> AgentAuditList:
2007
+ return cls(
2008
+ events=[AgentAuditEvent.from_dict(e) for e in (d.get("events") or [])],
2009
+ chain_valid=bool(d.get("chainValid", False)),
2010
+ )
2011
+
2012
+
2013
+ @dataclass
2014
+ class EvalSuiteRunResult:
2015
+ """Result of a hermetic server-side suite run. ``case_results`` and
2016
+ ``case_deltas`` stay raw dicts (v2 per-sample/assertion detail)."""
2017
+
2018
+ id: str = ""
2019
+ suite_id: str = ""
2020
+ agent_name: str = ""
2021
+ passed: bool = False
2022
+ score: float = 0.0
2023
+ cases_total: int = 0
2024
+ cases_passed: int = 0
2025
+ regressed: bool = False
2026
+ baseline_score: float | None = None
2027
+ regressed_cases: list[str] = field(default_factory=list)
2028
+ flaky_cases: list[str] = field(default_factory=list)
2029
+ case_deltas: list[dict[str, Any]] = field(default_factory=list)
2030
+ case_results: list[dict[str, Any]] = field(default_factory=list)
2031
+ total_cost_usd: float = 0.0
2032
+ judge_cost_usd: float = 0.0
2033
+ pinned_baseline: bool = False
2034
+ stopped_early: str = ""
2035
+
2036
+ @classmethod
2037
+ def from_dict(cls, d: dict[str, Any]) -> EvalSuiteRunResult:
2038
+ return cls(
2039
+ id=d.get("id", ""),
2040
+ suite_id=d.get("suiteId", ""),
2041
+ agent_name=d.get("agentName", ""),
2042
+ passed=d.get("passed", False),
2043
+ score=d.get("score", 0.0),
2044
+ cases_total=d.get("casesTotal", 0),
2045
+ cases_passed=d.get("casesPassed", 0),
2046
+ regressed=d.get("regressed", False),
2047
+ baseline_score=d.get("baselineScore"),
2048
+ regressed_cases=d.get("regressedCases") or [],
2049
+ flaky_cases=d.get("flakyCases") or [],
2050
+ case_deltas=d.get("caseDeltas") or [],
2051
+ case_results=d.get("caseResults") or [],
2052
+ total_cost_usd=d.get("totalCostUsd", 0.0),
2053
+ judge_cost_usd=d.get("judgeCostUsd", 0.0),
2054
+ pinned_baseline=d.get("pinnedBaseline", False),
2055
+ stopped_early=d.get("stoppedEarly", ""),
2056
+ )
2057
+
2058
+
2059
+ @dataclass
2060
+ class GeneratedEvalSuite:
2061
+ """An UNSAVED draft suite from ``evals.generate_suite``. ``draft`` has
2062
+ ``agentName``/``name``/``description``/``cases``; save it with ``upsert_suite``."""
2063
+
2064
+ draft: dict[str, Any] = field(default_factory=dict)
2065
+ provenance: list[dict[str, Any]] = field(default_factory=list)
2066
+ dropped: list[dict[str, Any]] = field(default_factory=list)
2067
+ evidence: dict[str, int] = field(default_factory=dict)
2068
+ model: str = ""
2069
+ cost_usd: float = 0.0
2070
+ requires_approval: bool = True
2071
+
2072
+ @classmethod
2073
+ def from_dict(cls, d: dict[str, Any]) -> GeneratedEvalSuite:
2074
+ return cls(
2075
+ draft=d.get("draft") or {},
2076
+ provenance=d.get("provenance") or [],
2077
+ dropped=d.get("dropped") or [],
2078
+ evidence=d.get("evidence") or {},
2079
+ model=d.get("model", ""),
2080
+ cost_usd=d.get("costUsd", 0.0),
2081
+ requires_approval=d.get("requiresApproval", True),
2082
+ )
2083
+
2084
+
2085
+ @dataclass
2086
+ class EvalCalibration:
2087
+ """Judge-vs-human agreement. ``note`` is set (and ``verdict`` empty) when
2088
+ the agent has no human feedback yet."""
2089
+
2090
+ n: int = 0
2091
+ labeled: int = 0
2092
+ agreement: float = 0.0
2093
+ kappa: float = 0.0
2094
+ mae: float = 0.0
2095
+ pairs: list[dict[str, Any]] = field(default_factory=list)
2096
+ verdict: str = ""
2097
+ rubric: str = ""
2098
+ cost_usd: float = 0.0
2099
+ note: str = ""
2100
+
2101
+ @classmethod
2102
+ def from_dict(cls, d: dict[str, Any]) -> EvalCalibration:
2103
+ st = d.get("stats") or {}
2104
+ return cls(
2105
+ n=st.get("n", 0),
2106
+ labeled=st.get("labeled", 0),
2107
+ agreement=st.get("agreement", 0.0),
2108
+ kappa=st.get("kappa", 0.0),
2109
+ mae=st.get("mae", 0.0),
2110
+ pairs=d.get("pairs") or [],
2111
+ verdict=d.get("verdict", ""),
2112
+ rubric=d.get("rubric", ""),
2113
+ cost_usd=d.get("costUsd", 0.0),
2114
+ note=d.get("note", ""),
2115
+ )
2116
+
2117
+
2118
+ @dataclass
2119
+ class DebugProposal:
2120
+ """One suggested remediation. ``kind`` is rollback|prompt_patch|model_change|
2121
+ eval_case|budget|policy|retry. ``action`` is ``{method, path, body?,
2122
+ idempotencyKey?}`` for a human to send; the SDK never does."""
2123
+
2124
+ id: str = ""
2125
+ kind: str = ""
2126
+ title: str = ""
2127
+ rationale: str = ""
2128
+ citations: list[str] = field(default_factory=list)
2129
+ risk: str = ""
2130
+ action: dict[str, Any] | None = None
2131
+ precondition: dict[str, Any] | None = None
2132
+ href: str = ""
2133
+ diff: dict[str, Any] | None = None
2134
+ preview: str = ""
2135
+ follow_up: str = ""
2136
+
2137
+ @classmethod
2138
+ def from_dict(cls, d: dict[str, Any]) -> DebugProposal:
2139
+ return cls(
2140
+ id=d.get("id", ""),
2141
+ kind=d.get("kind", ""),
2142
+ title=d.get("title", ""),
2143
+ rationale=d.get("rationale", ""),
2144
+ citations=d.get("citations") or [],
2145
+ risk=d.get("risk", ""),
2146
+ action=d.get("action"),
2147
+ precondition=d.get("precondition"),
2148
+ href=d.get("href", ""),
2149
+ diff=d.get("diff"),
2150
+ preview=d.get("preview", ""),
2151
+ follow_up=d.get("followUp", ""),
2152
+ )
2153
+
2154
+
2155
+ @dataclass
2156
+ class DebugReport:
2157
+ """Response of ``debug.analyze``. ``confidence`` is high|medium|low."""
2158
+
2159
+ summary: str = ""
2160
+ root_cause: str = ""
2161
+ confidence: str = ""
2162
+ grounded: bool = False
2163
+ citations: list[dict[str, Any]] = field(default_factory=list)
2164
+ proposals: list[DebugProposal] = field(default_factory=list)
2165
+ dropped: list[dict[str, Any]] = field(default_factory=list)
2166
+ subject: dict[str, Any] = field(default_factory=dict)
2167
+ evidence: dict[str, float] = field(default_factory=dict)
2168
+ cost_usd: float = 0.0
2169
+ requires_approval: bool = True
2170
+ generated_at: str = ""
2171
+
2172
+ @classmethod
2173
+ def from_dict(cls, d: dict[str, Any]) -> DebugReport:
2174
+ return cls(
2175
+ summary=d.get("summary", ""),
2176
+ root_cause=d.get("rootCause", ""),
2177
+ confidence=d.get("confidence", ""),
2178
+ grounded=d.get("grounded", False),
2179
+ citations=d.get("citations") or [],
2180
+ proposals=[DebugProposal.from_dict(p) for p in d.get("proposals") or []],
2181
+ dropped=d.get("dropped") or [],
2182
+ subject=d.get("subject") or {},
2183
+ evidence=d.get("evidence") or {},
2184
+ cost_usd=d.get("costUsd", 0.0),
2185
+ requires_approval=d.get("requiresApproval", True),
2186
+ generated_at=d.get("generatedAt", ""),
2187
+ )
2188
+
2189
+
2190
+ @dataclass
2191
+ class SupportAnswer:
2192
+ """Response of ``support.ask``. Each action is ``{kind: debug_run|debug_incident|open,
2193
+ runId?, incidentId?, href?, label?}``."""
2194
+
2195
+ answer: str = ""
2196
+ citations: list[dict[str, Any]] = field(default_factory=list)
2197
+ docs: list[dict[str, Any]] = field(default_factory=list)
2198
+ actions: list[dict[str, Any]] = field(default_factory=list)
2199
+ suggest_escalation: bool = False
2200
+ grounded: bool = False
2201
+ cost_usd: float = 0.0
2202
+ requires_approval: bool = False
2203
+
2204
+ @classmethod
2205
+ def from_dict(cls, d: dict[str, Any]) -> SupportAnswer:
2206
+ return cls(
2207
+ answer=d.get("answer", ""),
2208
+ citations=d.get("citations") or [],
2209
+ docs=d.get("docs") or [],
2210
+ actions=d.get("actions") or [],
2211
+ suggest_escalation=d.get("suggestEscalation", False),
2212
+ grounded=d.get("grounded", False),
2213
+ cost_usd=d.get("costUsd", 0.0),
2214
+ requires_approval=d.get("requiresApproval", False),
2215
+ )
2216
+
2217
+
2218
+ @dataclass
2219
+ class SupportEscalation:
2220
+ """An escalation. ``signature`` and ``bundle`` are empty in list entries."""
2221
+
2222
+ id: str = ""
2223
+ subject_kind: str = ""
2224
+ subject_id: str = ""
2225
+ question: str = ""
2226
+ digest: str = ""
2227
+ algorithm: str = ""
2228
+ created_by: str = ""
2229
+ created_at: str = ""
2230
+ signature: str = ""
2231
+ bundle: dict[str, Any] = field(default_factory=dict)
2232
+
2233
+ @classmethod
2234
+ def from_dict(cls, d: dict[str, Any]) -> SupportEscalation:
2235
+ return cls(
2236
+ id=d.get("id", ""),
2237
+ subject_kind=d.get("subjectKind", ""),
2238
+ subject_id=d.get("subjectId", ""),
2239
+ question=d.get("question", ""),
2240
+ digest=d.get("digest", ""),
2241
+ algorithm=d.get("algorithm", ""),
2242
+ created_by=d.get("createdBy", ""),
2243
+ created_at=d.get("createdAt", ""),
2244
+ signature=d.get("signature", ""),
2245
+ bundle=d.get("bundle") or {},
2246
+ )