@palettelab/cli 0.3.60 → 0.3.62
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.
- package/README.md +44 -5
- package/backend-sdk/palette_sdk/__init__.py +25 -1
- package/backend-sdk/palette_sdk/capabilities.py +126 -0
- package/backend-sdk/palette_sdk/jobs.py +177 -0
- package/backend-sdk/palette_sdk/manifest.py +63 -1
- package/backend-sdk/palette_sdk/plugin_context.py +3 -0
- package/backend-sdk/palette_sdk/services.py +45 -6
- package/docs/python-backend-sdk.md +144 -0
- package/lib/cli.js +14 -1
- package/lib/commands/capabilities.js +151 -0
- package/lib/commands/init.js +3 -2
- package/lib/commands/services.js +74 -8
- package/lib/commands/test.js +91 -3
- package/lib/dev-simulator.js +208 -1
- package/lib/manifest.js +76 -4
- package/package.json +1 -1
- package/template-fallback/package.json +1 -1
- package/template-fallback/templates/agent-tool/README.md +6 -2
- package/template-fallback/templates/agent-tool/backend/api/main.py +27 -6
- package/template-fallback/templates/agent-tool/palette-plugin.json +35 -4
- package/template-fallback/templates/consumer-app/package.json +1 -1
- package/template-fallback/templates/dashboard/package.json +1 -1
- package/template-fallback/templates/database/package.json +1 -1
- package/template-fallback/templates/external-service/package.json +1 -1
- package/template-fallback/templates/frontend-only/package.json +1 -1
- package/template-fallback/templates/next/package.json +1 -1
- package/template-fallback/templates/palette-app/package.json +1 -1
- package/template-fallback/templates/provider-app/package.json +1 -1
- package/template-fallback/templates/agent-tool/backend/tools/echo.py +0 -15
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ Use the right helper for the runtime you are coding in:
|
|
|
11
11
|
| Runtime | Package/helper | Use it for |
|
|
12
12
|
|---|---|---|
|
|
13
13
|
| Frontend TypeScript/React | `@palettelab/sdk`, `createPaletteClient(...)`, `palette.*` | UI code, current-user OS APIs, frontend broker clients, Data Room browsing/upload from the browser, toasts, and current-user OS notifications |
|
|
14
|
-
| Backend Python/FastAPI | `palette_sdk`, `PluginContext`, `ctx.*`, `services(ctx)` | Backend routes, permission gates, app-owned data, migrations, cross-user notifications, server-side Data Rooms, managed services, app-to-app service handlers, and lifecycle hooks |
|
|
14
|
+
| Backend Python/FastAPI | `palette_sdk`, `PluginContext`, `ctx.*`, `services(ctx)` | Backend routes, permission gates, app-owned data, durable jobs, migrations, cross-user notifications, server-side Data Rooms, managed services, app-to-app service handlers, and lifecycle hooks |
|
|
15
15
|
| CLI tooling | `pltt ...` | Scaffolding, local dev, testing, packaging, publishing, hosted sandbox previews, and generating frontend/backend typed service clients |
|
|
16
16
|
|
|
17
17
|
The CLI bundles `palette_sdk` for local backend simulation, but backend app
|
|
@@ -309,7 +309,7 @@ async def create_invoice(body: InvoiceIn, ctx: PluginContext = Depends(get_plugi
|
|
|
309
309
|
Backend SDK features for app-owned data:
|
|
310
310
|
|
|
311
311
|
- `PluginRouter`, `PluginContext`, and `get_plugin_context` provide the FastAPI route and request-context surface.
|
|
312
|
-
- `PluginContext` exposes `user_id`, `organization_id`, `org_role`, `plugin_id`, `permissions`, `storage`, `ctx.db`, `ctx.data_rooms`, `ctx.connections`, `ctx.members`, `ctx.redis`, `ctx.vector`, `ctx.config`, and `ctx.logger`.
|
|
312
|
+
- `PluginContext` exposes `user_id`, `organization_id`, `org_role`, `plugin_id`, `permissions`, `storage`, `ctx.db`, `ctx.jobs`, `ctx.data_rooms`, `ctx.connections`, `ctx.members`, `ctx.redis`, `ctx.vector`, `ctx.config`, and `ctx.logger`.
|
|
313
313
|
- `ctx.db` is the full scoped SQLAlchemy `AsyncSession` for app-owned database data.
|
|
314
314
|
- `ctx.repo(Model)` gives org-safe CRUD helpers for app tables.
|
|
315
315
|
- `ctx.data_rooms` gives backend access to Palette Data Rooms without importing platform internals.
|
|
@@ -323,16 +323,52 @@ Backend SDK features for app-owned data:
|
|
|
323
323
|
- `ctx.redis` gives a Redis-backed, plugin/org-scoped Redis API when `"redis"` is declared in `platform_services`.
|
|
324
324
|
- `ctx.vector` gives a Qdrant-backed, plugin/org-scoped vector API when `"vector"` is declared in `platform_services`.
|
|
325
325
|
- `ctx.storage` gives app/org-scoped file upload helpers when `"storage"` is declared in `platform_services`.
|
|
326
|
+
- `@job(...)`, `JobExecution`, and `ctx.jobs` provide durable async work with retries, progress, status, and cancellation.
|
|
326
327
|
- `LifecycleHooks` lets apps define install/update/enable/disable/uninstall hooks.
|
|
327
328
|
- `OrgScopedTable` and `PluginBase` keep app data inside the plugin schema model set.
|
|
328
329
|
- `plugin_safe_id(...)`, `plugin_schema(...)`, `plugin_table_prefix(...)`, and `ensure_org_rls(...)` keep database names and row-level security consistent.
|
|
329
330
|
- `Event` and `subscribe_event(...)` register in-process platform event handlers.
|
|
330
331
|
- `sign_webhook(...)` and `verify_webhook_signature(...)` handle HMAC-SHA256 webhook signing checks.
|
|
331
|
-
- `
|
|
332
|
+
- `@capability(...)`, `CapabilityResult`, and `ArtifactRef` define typed,
|
|
333
|
+
broker-governed tools shared by chat agents and visual workflows.
|
|
334
|
+
- `ToolDefinition` is legacy compatibility for existing read-only tools;
|
|
335
|
+
migrate new tools to `@capability(...)`.
|
|
332
336
|
- `PluginManifest` and `load_manifest(...)` parse and validate `palette-plugin.json`.
|
|
333
337
|
- `SuccessResponse`, `ErrorResponse`, and `PaginatedResponse` are reusable response schemas.
|
|
334
338
|
- `route_permission_issues(router, public_routes=None)` is the test helper for detecting ungated backend routes.
|
|
335
339
|
|
|
340
|
+
## Durable Background Jobs
|
|
341
|
+
|
|
342
|
+
Declare `"background_jobs": true`, register an async handler with `@job`, and
|
|
343
|
+
enqueue a JSON payload from the request:
|
|
344
|
+
|
|
345
|
+
```python
|
|
346
|
+
from palette_sdk import JobExecution, PluginContext, job
|
|
347
|
+
|
|
348
|
+
@job("reports.generate", timeout_seconds=1800, max_attempts=3)
|
|
349
|
+
async def generate_report(ctx: PluginContext, execution: JobExecution, payload: dict):
|
|
350
|
+
await execution.progress(10, "Starting")
|
|
351
|
+
# ctx and ctx.db are fresh, job-owned objects created by the worker.
|
|
352
|
+
return {"report_id": payload["report_id"]}
|
|
353
|
+
|
|
354
|
+
handle = await ctx.jobs.enqueue(
|
|
355
|
+
"reports.generate",
|
|
356
|
+
{"report_id": report_id},
|
|
357
|
+
idempotency_key=f"report:{report_id}",
|
|
358
|
+
)
|
|
359
|
+
return handle.accepted_response() # HTTP 202
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
Never pass a request `ctx`, `ctx.db`, connection, ORM object, file handle, or
|
|
363
|
+
other live object into `ThreadPoolExecutor`, `asyncio.create_task`, or a
|
|
364
|
+
detached background callback. Request cleanup releases those resources, and
|
|
365
|
+
async database sessions are not thread-safe. The job payload must be JSON; the
|
|
366
|
+
worker creates fresh scoped context and database resources for every attempt.
|
|
367
|
+
|
|
368
|
+
See [Python Backend SDK Developer Guide](./docs/python-backend-sdk.md#4b-durable-background-jobs)
|
|
369
|
+
for status URLs, SSE progress, cancellation, retries, idempotency, hosted
|
|
370
|
+
execution, and `pltt dev` behavior.
|
|
371
|
+
|
|
336
372
|
Python backend Data Room example:
|
|
337
373
|
|
|
338
374
|
```python
|
|
@@ -833,7 +869,7 @@ pltt test --json
|
|
|
833
869
|
pltt test --publish-type preview
|
|
834
870
|
```
|
|
835
871
|
|
|
836
|
-
Checks include manifest validity, SDK/platform compatibility, release semver bump detection, forbidden platform imports, frontend bundling and size limits, sandbox bridge smoke, backend dependency installation/import, route permission gates, route permission declarations, migration linting, frontend sandbox policy, and dependency policy for `package.json` / `pyproject.toml`. The semver bump check is skipped for `--publish-type preview` because hosted previews may reuse the current app version. The default frontend and backend bundle limits are
|
|
872
|
+
Checks include manifest validity, SDK/platform compatibility, release semver bump detection, forbidden platform imports, frontend bundling and size limits, sandbox bridge smoke, backend dependency installation/import, route permission gates, route permission declarations, migration linting, frontend sandbox policy, and dependency policy for `package.json` / `pyproject.toml`. The semver bump check is skipped for `--publish-type preview` because hosted previews may reuse the current app version. The default frontend and backend bundle limits are 50 MiB; set `PALETTE_MAX_FRONTEND_BUNDLE_BYTES` or `PALETTE_MAX_BACKEND_BUNDLE_BYTES` for reviewed exceptions.
|
|
837
873
|
|
|
838
874
|
### `pltt package`
|
|
839
875
|
|
|
@@ -909,13 +945,16 @@ pltt services mock hr/v1#approvalChain.get
|
|
|
909
945
|
pltt services test --offline
|
|
910
946
|
pltt services pull --env staging
|
|
911
947
|
pltt services scaffold approvalChain.get
|
|
948
|
+
pltt capabilities add creative.poster.generate --method poster.generate --risk write --effects artifact.create --idempotent
|
|
949
|
+
pltt capabilities list
|
|
950
|
+
pltt test --agent
|
|
912
951
|
```
|
|
913
952
|
|
|
914
953
|
Subcommands:
|
|
915
954
|
|
|
916
955
|
- `list`: fetches `/api/v1/os-broker/catalog` from the selected environment and prints services/events available to the current org. Use `--json` for the raw catalog.
|
|
917
956
|
- `add <namespace/version#name>`: appends a consumed service target to `consumes.services`. Use `--event` or `--type event` for `consumes.events`, `--optional` for non-required dependencies, and `--reason <text>` to record why the dependency is needed.
|
|
918
|
-
- `sync`: scans backend `@service(...)` decorators and updates `provides.services` so provider contracts do not drift from code.
|
|
957
|
+
- `sync`: scans backend `@service(...)` and `@capability(...)` decorators and updates `provides.services` so provider contracts do not drift from code.
|
|
919
958
|
- `mock <namespace/version#name>`: adds a local response to `.palette/app-services.local.json` for `pltt dev`.
|
|
920
959
|
- `test`: checks local consumes/provides/mocks and, unless `--offline` is set, verifies consumed targets against `/api/v1/os-broker/schemas`.
|
|
921
960
|
- `pull`: reads `consumes.services` and `consumes.events`, fetches JSON Schemas from `/api/v1/os-broker/schemas`, and generates nested `.palette/types/services.ts` plus Python helpers in `.palette/python/services.py`.
|
|
@@ -16,7 +16,18 @@ from palette_sdk.platform_services import (
|
|
|
16
16
|
)
|
|
17
17
|
from palette_sdk.repository import OrgRepository
|
|
18
18
|
from palette_sdk.lifecycle import LifecycleHooks
|
|
19
|
+
from palette_sdk.jobs import JobCancelledError, JobExecution, JobHandle, JobsClient, job
|
|
19
20
|
from palette_sdk.tool_definition import ToolDefinition
|
|
21
|
+
from palette_sdk.capabilities import (
|
|
22
|
+
ApprovalRequired,
|
|
23
|
+
ArtifactRef,
|
|
24
|
+
CapabilityError,
|
|
25
|
+
CapabilityResult,
|
|
26
|
+
ConnectionRequired,
|
|
27
|
+
RateLimited,
|
|
28
|
+
RetryableError,
|
|
29
|
+
capability,
|
|
30
|
+
)
|
|
20
31
|
from palette_sdk.manifest import PluginManifest, load_manifest
|
|
21
32
|
from palette_sdk.schemas import (
|
|
22
33
|
SuccessResponse,
|
|
@@ -74,7 +85,20 @@ __all__ = [
|
|
|
74
85
|
"UnavailablePlatformService",
|
|
75
86
|
"OrgRepository",
|
|
76
87
|
"LifecycleHooks",
|
|
88
|
+
"JobCancelledError",
|
|
89
|
+
"JobExecution",
|
|
90
|
+
"JobHandle",
|
|
91
|
+
"JobsClient",
|
|
92
|
+
"job",
|
|
77
93
|
"ToolDefinition",
|
|
94
|
+
"capability",
|
|
95
|
+
"ArtifactRef",
|
|
96
|
+
"CapabilityResult",
|
|
97
|
+
"CapabilityError",
|
|
98
|
+
"ConnectionRequired",
|
|
99
|
+
"ApprovalRequired",
|
|
100
|
+
"RateLimited",
|
|
101
|
+
"RetryableError",
|
|
78
102
|
"PluginManifest",
|
|
79
103
|
"load_manifest",
|
|
80
104
|
"SuccessResponse",
|
|
@@ -112,4 +136,4 @@ __all__ = [
|
|
|
112
136
|
"LocalStorageService",
|
|
113
137
|
]
|
|
114
138
|
|
|
115
|
-
__version__ = "0.1.
|
|
139
|
+
__version__ = "0.1.12"
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Typed agent capability contracts for Palette apps."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any, Callable, Literal
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, Field
|
|
9
|
+
|
|
10
|
+
from palette_sdk.services import ServiceHandler, service
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ArtifactRef(BaseModel):
|
|
14
|
+
"""Portable reference to an artifact stored by Palette or an installed app."""
|
|
15
|
+
|
|
16
|
+
id: str
|
|
17
|
+
uri: str
|
|
18
|
+
name: str
|
|
19
|
+
mime_type: str
|
|
20
|
+
kind: str = "file"
|
|
21
|
+
revision: str | None = None
|
|
22
|
+
size_bytes: int | None = None
|
|
23
|
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class CapabilityResult(BaseModel):
|
|
27
|
+
"""Standard result envelope understood by agents and workflow nodes."""
|
|
28
|
+
|
|
29
|
+
data: Any = None
|
|
30
|
+
artifacts: list[ArtifactRef] = Field(default_factory=list)
|
|
31
|
+
citations: list[str] = Field(default_factory=list)
|
|
32
|
+
warnings: list[str] = Field(default_factory=list)
|
|
33
|
+
continuation: dict[str, Any] | None = None
|
|
34
|
+
telemetry: dict[str, Any] = Field(default_factory=dict)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class CapabilityError(RuntimeError):
|
|
38
|
+
code = "capability_error"
|
|
39
|
+
retryable = False
|
|
40
|
+
|
|
41
|
+
def __init__(self, message: str, *, details: dict[str, Any] | None = None):
|
|
42
|
+
super().__init__(message)
|
|
43
|
+
self.details = details or {}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ConnectionRequired(CapabilityError):
|
|
47
|
+
code = "connection_required"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ApprovalRequired(CapabilityError):
|
|
51
|
+
code = "approval_required"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class RateLimited(CapabilityError):
|
|
55
|
+
code = "rate_limited"
|
|
56
|
+
retryable = True
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class RetryableError(CapabilityError):
|
|
60
|
+
code = "retryable"
|
|
61
|
+
retryable = True
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def capability(
|
|
65
|
+
name: str,
|
|
66
|
+
*,
|
|
67
|
+
capability_id: str,
|
|
68
|
+
scope: str | None = None,
|
|
69
|
+
version: str | None = None,
|
|
70
|
+
label: str | None = None,
|
|
71
|
+
description: str | None = None,
|
|
72
|
+
input_schema: dict | str | None = None,
|
|
73
|
+
output_schema: dict | str | None = None,
|
|
74
|
+
effects: list[str] | None = None,
|
|
75
|
+
risk: Literal["read", "write", "destructive", "controlled"] = "read",
|
|
76
|
+
supports_scheduling: bool = True,
|
|
77
|
+
idempotent: bool = False,
|
|
78
|
+
timeout_seconds: int = 60,
|
|
79
|
+
tags: list[str] | None = None,
|
|
80
|
+
artifact_inputs: list[str] | None = None,
|
|
81
|
+
artifact_outputs: list[str] | None = None,
|
|
82
|
+
examples: list[dict[str, Any]] | None = None,
|
|
83
|
+
cost_class: Literal["low", "medium", "high"] | None = None,
|
|
84
|
+
latency_class: Literal["interactive", "background", "long_running"] | None = None,
|
|
85
|
+
deprecated: bool = False,
|
|
86
|
+
replacement: str | None = None,
|
|
87
|
+
) -> Callable[[ServiceHandler], ServiceHandler]:
|
|
88
|
+
"""Declare a broker service that agents and visual workflows may call.
|
|
89
|
+
|
|
90
|
+
The matching provides.services method in the manifest remains the reviewed
|
|
91
|
+
publish contract. pltt test --agent verifies decorator/manifest parity.
|
|
92
|
+
"""
|
|
93
|
+
if not re.match(r"^[a-z][a-z0-9_-]*(?:\.[a-z0-9_-]+)+$", capability_id):
|
|
94
|
+
raise ValueError("capability_id must be a stable dotted lowercase id")
|
|
95
|
+
if not description or input_schema is None:
|
|
96
|
+
raise ValueError("agent capabilities require description and input_schema")
|
|
97
|
+
if not effects:
|
|
98
|
+
raise ValueError("agent capabilities require at least one declared effect")
|
|
99
|
+
if risk in {"write", "destructive"} and supports_scheduling and not idempotent:
|
|
100
|
+
raise ValueError(
|
|
101
|
+
"scheduled write capabilities must be idempotent or disable scheduling"
|
|
102
|
+
)
|
|
103
|
+
return service(
|
|
104
|
+
name,
|
|
105
|
+
scope=scope,
|
|
106
|
+
version=version,
|
|
107
|
+
label=label,
|
|
108
|
+
description=description,
|
|
109
|
+
input_schema=input_schema,
|
|
110
|
+
output_schema=output_schema,
|
|
111
|
+
agent_exposable=True,
|
|
112
|
+
capability_id=capability_id,
|
|
113
|
+
effects=effects or [],
|
|
114
|
+
risk=risk,
|
|
115
|
+
supports_scheduling=supports_scheduling,
|
|
116
|
+
idempotent=idempotent,
|
|
117
|
+
timeout_seconds=timeout_seconds,
|
|
118
|
+
tags=tags or [],
|
|
119
|
+
artifact_inputs=artifact_inputs or [],
|
|
120
|
+
artifact_outputs=artifact_outputs or [],
|
|
121
|
+
examples=examples or [],
|
|
122
|
+
cost_class=cost_class,
|
|
123
|
+
latency_class=latency_class,
|
|
124
|
+
deprecated=deprecated,
|
|
125
|
+
replacement=replacement,
|
|
126
|
+
)
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Durable background jobs for Palette app backends."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
from collections.abc import Awaitable, Callable
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
JobHandler = Callable[[Any, "JobExecution", dict[str, Any]], Awaitable[dict[str, Any] | None]]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class JobDecl:
|
|
16
|
+
name: str
|
|
17
|
+
handler: JobHandler
|
|
18
|
+
timeout_seconds: int = 900
|
|
19
|
+
max_attempts: int = 3
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
_pending: list[JobDecl] = []
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def job(
|
|
26
|
+
name: str,
|
|
27
|
+
*,
|
|
28
|
+
timeout_seconds: int = 900,
|
|
29
|
+
max_attempts: int = 3,
|
|
30
|
+
) -> Callable[[JobHandler], JobHandler]:
|
|
31
|
+
"""Register an async handler that runs in the OS durable job worker."""
|
|
32
|
+
if not name or len(name) > 128:
|
|
33
|
+
raise ValueError("job name must contain 1-128 characters")
|
|
34
|
+
if timeout_seconds < 1 or timeout_seconds > 7200:
|
|
35
|
+
raise ValueError("job timeout_seconds must be between 1 and 7200")
|
|
36
|
+
if max_attempts < 1 or max_attempts > 5:
|
|
37
|
+
raise ValueError("job max_attempts must be between 1 and 5")
|
|
38
|
+
|
|
39
|
+
def decorator(fn: JobHandler) -> JobHandler:
|
|
40
|
+
if not inspect.iscoroutinefunction(fn):
|
|
41
|
+
raise TypeError("@job handlers must be async functions")
|
|
42
|
+
_pending.append(
|
|
43
|
+
JobDecl(
|
|
44
|
+
name=name,
|
|
45
|
+
handler=fn,
|
|
46
|
+
timeout_seconds=timeout_seconds,
|
|
47
|
+
max_attempts=max_attempts,
|
|
48
|
+
)
|
|
49
|
+
)
|
|
50
|
+
return fn
|
|
51
|
+
|
|
52
|
+
return decorator
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def drain_pending_jobs() -> list[JobDecl]:
|
|
56
|
+
"""Platform-only: return and clear handlers registered during app import."""
|
|
57
|
+
out = list(_pending)
|
|
58
|
+
_pending.clear()
|
|
59
|
+
return out
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class JobHandle:
|
|
64
|
+
id: str
|
|
65
|
+
status: str
|
|
66
|
+
status_url: str
|
|
67
|
+
events_url: str
|
|
68
|
+
plugin_id: str = ""
|
|
69
|
+
handler: str = ""
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def from_dict(cls, value: dict[str, Any]) -> "JobHandle":
|
|
73
|
+
job_id = str(value.get("job_id") or value.get("id") or "")
|
|
74
|
+
return cls(
|
|
75
|
+
id=job_id,
|
|
76
|
+
status=str(value.get("status") or "queued"),
|
|
77
|
+
status_url=str(value.get("status_url") or f"/api/v1/app-jobs/{job_id}"),
|
|
78
|
+
events_url=str(value.get("events_url") or f"/api/v1/app-jobs/{job_id}/events"),
|
|
79
|
+
plugin_id=str(value.get("plugin_id") or ""),
|
|
80
|
+
handler=str(value.get("handler") or ""),
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
def to_dict(self) -> dict[str, Any]:
|
|
84
|
+
return {
|
|
85
|
+
"job_id": self.id,
|
|
86
|
+
"status": self.status,
|
|
87
|
+
"status_url": self.status_url,
|
|
88
|
+
"events_url": self.events_url,
|
|
89
|
+
"plugin_id": self.plugin_id,
|
|
90
|
+
"handler": self.handler,
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
def accepted_response(self):
|
|
94
|
+
from fastapi.responses import JSONResponse
|
|
95
|
+
|
|
96
|
+
return JSONResponse(status_code=202, content=self.to_dict())
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class JobsClient:
|
|
100
|
+
"""Request-safe enqueue/status client injected as ``ctx.jobs``."""
|
|
101
|
+
|
|
102
|
+
def __init__(self, adapter: Any = None):
|
|
103
|
+
self._adapter = adapter
|
|
104
|
+
|
|
105
|
+
def _require_adapter(self) -> Any:
|
|
106
|
+
if self._adapter is None:
|
|
107
|
+
raise RuntimeError("Palette durable jobs are not available in this runtime")
|
|
108
|
+
return self._adapter
|
|
109
|
+
|
|
110
|
+
async def enqueue(
|
|
111
|
+
self,
|
|
112
|
+
name: str,
|
|
113
|
+
payload: dict[str, Any] | None = None,
|
|
114
|
+
*,
|
|
115
|
+
idempotency_key: str | None = None,
|
|
116
|
+
) -> JobHandle:
|
|
117
|
+
if payload is not None and not isinstance(payload, dict):
|
|
118
|
+
raise TypeError("job payload must be a dict")
|
|
119
|
+
result = await self._require_adapter().enqueue(
|
|
120
|
+
name,
|
|
121
|
+
payload or {},
|
|
122
|
+
idempotency_key=idempotency_key,
|
|
123
|
+
)
|
|
124
|
+
return JobHandle.from_dict(result)
|
|
125
|
+
|
|
126
|
+
async def get(self, job_id: str) -> dict[str, Any]:
|
|
127
|
+
return await self._require_adapter().get(job_id)
|
|
128
|
+
|
|
129
|
+
async def cancel(self, job_id: str) -> dict[str, Any]:
|
|
130
|
+
return await self._require_adapter().cancel(job_id)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class JobExecution:
|
|
134
|
+
"""Control surface passed to a running durable job handler."""
|
|
135
|
+
|
|
136
|
+
def __init__(
|
|
137
|
+
self,
|
|
138
|
+
adapter: Any,
|
|
139
|
+
*,
|
|
140
|
+
job_id: str,
|
|
141
|
+
attempt: int,
|
|
142
|
+
idempotency_key: str | None = None,
|
|
143
|
+
) -> None:
|
|
144
|
+
self._adapter = adapter
|
|
145
|
+
self.id = job_id
|
|
146
|
+
self.attempt = attempt
|
|
147
|
+
self.idempotency_key = idempotency_key
|
|
148
|
+
|
|
149
|
+
async def progress(self, percent: int, message: str | None = None) -> None:
|
|
150
|
+
if percent < 0 or percent > 100:
|
|
151
|
+
raise ValueError("job progress must be between 0 and 100")
|
|
152
|
+
await self._adapter.progress(percent, message)
|
|
153
|
+
|
|
154
|
+
async def heartbeat(self) -> None:
|
|
155
|
+
await self._adapter.heartbeat()
|
|
156
|
+
|
|
157
|
+
async def cancelled(self) -> bool:
|
|
158
|
+
return bool(await self._adapter.cancelled())
|
|
159
|
+
|
|
160
|
+
async def check_cancelled(self) -> None:
|
|
161
|
+
if await self.cancelled():
|
|
162
|
+
raise JobCancelledError(f"job {self.id} was cancelled")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class JobCancelledError(Exception):
|
|
166
|
+
"""Cooperative cancellation raised by ``JobExecution.check_cancelled``."""
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
__all__ = [
|
|
170
|
+
"JobCancelledError",
|
|
171
|
+
"JobDecl",
|
|
172
|
+
"JobExecution",
|
|
173
|
+
"JobHandle",
|
|
174
|
+
"JobsClient",
|
|
175
|
+
"drain_pending_jobs",
|
|
176
|
+
"job",
|
|
177
|
+
]
|
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import json
|
|
6
|
+
import re
|
|
6
7
|
from pathlib import Path
|
|
7
8
|
from typing import Any, Literal
|
|
8
9
|
|
|
9
|
-
from pydantic import AliasChoices, BaseModel, ConfigDict, Field
|
|
10
|
+
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
class AgentDefinition(BaseModel):
|
|
@@ -113,8 +114,38 @@ class AppServiceMethodSpec(BaseModel):
|
|
|
113
114
|
output: dict[str, Any] | str | None = None
|
|
114
115
|
route_method: Literal["GET", "POST", "PUT", "PATCH", "DELETE"] | None = None
|
|
115
116
|
route_path: str | None = None
|
|
117
|
+
annotations: dict[str, Any] | None = None
|
|
118
|
+
capability_id: str | None = None
|
|
119
|
+
supports_scheduling: bool = True
|
|
120
|
+
agent_exposable: bool = False
|
|
116
121
|
deprecated: bool = False
|
|
117
122
|
replacement: str | None = None
|
|
123
|
+
effects: list[str] = Field(default_factory=list)
|
|
124
|
+
risk: Literal["read", "write", "destructive", "controlled"] = "read"
|
|
125
|
+
idempotent: bool = False
|
|
126
|
+
timeout_seconds: int = Field(default=60, ge=1, le=7200)
|
|
127
|
+
tags: list[str] = Field(default_factory=list)
|
|
128
|
+
artifact_inputs: list[str] = Field(default_factory=list)
|
|
129
|
+
artifact_outputs: list[str] = Field(default_factory=list)
|
|
130
|
+
examples: list[dict[str, Any]] = Field(default_factory=list)
|
|
131
|
+
cost_class: Literal["low", "medium", "high"] | None = None
|
|
132
|
+
latency_class: Literal["interactive", "background", "long_running"] | None = None
|
|
133
|
+
|
|
134
|
+
@model_validator(mode="after")
|
|
135
|
+
def validate_agent_contract(self):
|
|
136
|
+
if not self.agent_exposable:
|
|
137
|
+
return self
|
|
138
|
+
if not self.capability_id or not re.match(
|
|
139
|
+
r"^[a-z][a-z0-9_-]*(?:\.[a-z0-9_-]+)+$", self.capability_id
|
|
140
|
+
):
|
|
141
|
+
raise ValueError("agent-exposable methods require a stable dotted capability_id")
|
|
142
|
+
if not self.description.strip() or self.input_schema is None and self.input is None:
|
|
143
|
+
raise ValueError("agent-exposable methods require description and input_schema")
|
|
144
|
+
if not self.effects:
|
|
145
|
+
raise ValueError("agent-exposable methods require at least one declared effect")
|
|
146
|
+
if self.risk in {"write", "destructive"} and self.supports_scheduling and not self.idempotent:
|
|
147
|
+
raise ValueError("scheduled write capabilities must be idempotent")
|
|
148
|
+
return self
|
|
118
149
|
|
|
119
150
|
|
|
120
151
|
class ProvidedAppServiceSpec(BaseModel):
|
|
@@ -197,6 +228,37 @@ class McpToolSpec(BaseModel):
|
|
|
197
228
|
annotations: dict[str, Any] | None = None # readOnlyHint / destructiveHint ...
|
|
198
229
|
scope: str | None = None
|
|
199
230
|
expose_external: bool = False
|
|
231
|
+
agent_exposable: bool = False
|
|
232
|
+
capability_id: str | None = None
|
|
233
|
+
supports_scheduling: bool = True
|
|
234
|
+
effects: list[str] = Field(default_factory=list)
|
|
235
|
+
risk: Literal["read", "write", "destructive", "controlled"] = "read"
|
|
236
|
+
idempotent: bool = False
|
|
237
|
+
timeout_seconds: int = Field(default=60, ge=1, le=7200)
|
|
238
|
+
tags: list[str] = Field(default_factory=list)
|
|
239
|
+
artifact_inputs: list[str] = Field(default_factory=list)
|
|
240
|
+
artifact_outputs: list[str] = Field(default_factory=list)
|
|
241
|
+
examples: list[dict[str, Any]] = Field(default_factory=list)
|
|
242
|
+
cost_class: Literal["low", "medium", "high"] | None = None
|
|
243
|
+
latency_class: Literal["interactive", "background", "long_running"] | None = None
|
|
244
|
+
deprecated: bool = False
|
|
245
|
+
replacement: str | None = None
|
|
246
|
+
|
|
247
|
+
@model_validator(mode="after")
|
|
248
|
+
def validate_agent_contract(self):
|
|
249
|
+
if not self.agent_exposable:
|
|
250
|
+
return self
|
|
251
|
+
if not self.capability_id or not re.match(
|
|
252
|
+
r"^[a-z][a-z0-9_-]*(?:\.[a-z0-9_-]+)+$", self.capability_id
|
|
253
|
+
):
|
|
254
|
+
raise ValueError("agent-exposable tools require a stable dotted capability_id")
|
|
255
|
+
if not self.description.strip() or self.input_schema is None:
|
|
256
|
+
raise ValueError("agent-exposable tools require description and input_schema")
|
|
257
|
+
if not self.effects:
|
|
258
|
+
raise ValueError("agent-exposable tools require at least one declared effect")
|
|
259
|
+
if self.risk in {"write", "destructive"} and self.supports_scheduling and not self.idempotent:
|
|
260
|
+
raise ValueError("scheduled write capabilities must be idempotent")
|
|
261
|
+
return self
|
|
200
262
|
|
|
201
263
|
|
|
202
264
|
class McpResourceSpec(BaseModel):
|
|
@@ -18,6 +18,7 @@ from palette_sdk.notifications import NotificationsClient
|
|
|
18
18
|
from palette_sdk.organization import OrganizationInfo
|
|
19
19
|
from palette_sdk.platform_services import UnavailablePlatformService
|
|
20
20
|
from palette_sdk.events import EventPublisher
|
|
21
|
+
from palette_sdk.jobs import JobsClient
|
|
21
22
|
|
|
22
23
|
|
|
23
24
|
class MissingSecretError(KeyError):
|
|
@@ -64,6 +65,7 @@ class PluginContext:
|
|
|
64
65
|
redis: Any = field(default_factory=lambda: UnavailablePlatformService("redis"))
|
|
65
66
|
vector: Any = field(default_factory=lambda: UnavailablePlatformService("vector"))
|
|
66
67
|
events: EventPublisher = field(default_factory=EventPublisher)
|
|
68
|
+
jobs: JobsClient = field(default_factory=JobsClient)
|
|
67
69
|
config: dict[str, Any] = field(default_factory=dict)
|
|
68
70
|
logger: logging.Logger = field(default_factory=lambda: logging.getLogger("palette_sdk.plugin"))
|
|
69
71
|
|
|
@@ -142,6 +144,7 @@ async def get_plugin_context(request: Request) -> PluginContext:
|
|
|
142
144
|
redis=getattr(state, "redis", None) or UnavailablePlatformService("redis"),
|
|
143
145
|
vector=getattr(state, "vector", None) or UnavailablePlatformService("vector"),
|
|
144
146
|
events=EventPublisher(getattr(state, "plugin_events", None)),
|
|
147
|
+
jobs=JobsClient(getattr(state, "plugin_jobs", None)),
|
|
145
148
|
config=getattr(state, "plugin_config", {}),
|
|
146
149
|
logger=getattr(state, "plugin_logger", logging.getLogger(f"palette_sdk.plugin.{getattr(state, 'plugin_id', 'unknown')}")),
|
|
147
150
|
)
|
|
@@ -40,10 +40,23 @@ class ServiceDecl:
|
|
|
40
40
|
scope: str | None = None
|
|
41
41
|
label: str | None = None
|
|
42
42
|
description: str | None = None
|
|
43
|
-
input_schema: dict | None = None
|
|
44
|
-
output_schema: dict | None = None
|
|
43
|
+
input_schema: dict | str | None = None
|
|
44
|
+
output_schema: dict | str | None = None
|
|
45
45
|
deprecated: bool = False
|
|
46
46
|
replacement: str | None = None
|
|
47
|
+
agent_exposable: bool = False
|
|
48
|
+
capability_id: str | None = None
|
|
49
|
+
effects: tuple[str, ...] = ()
|
|
50
|
+
risk: str = "read"
|
|
51
|
+
supports_scheduling: bool = True
|
|
52
|
+
idempotent: bool = False
|
|
53
|
+
timeout_seconds: int = 60
|
|
54
|
+
tags: tuple[str, ...] = ()
|
|
55
|
+
artifact_inputs: tuple[str, ...] = ()
|
|
56
|
+
artifact_outputs: tuple[str, ...] = ()
|
|
57
|
+
examples: tuple[dict[str, Any], ...] = ()
|
|
58
|
+
cost_class: str | None = None
|
|
59
|
+
latency_class: str | None = None
|
|
47
60
|
|
|
48
61
|
|
|
49
62
|
# Plugin-declared service handlers captured during module import. The platform
|
|
@@ -60,12 +73,25 @@ def service(
|
|
|
60
73
|
scope: str | None = None,
|
|
61
74
|
label: str | None = None,
|
|
62
75
|
description: str | None = None,
|
|
63
|
-
input_schema: dict | None = None,
|
|
64
|
-
input: dict | None = None,
|
|
65
|
-
output_schema: dict | None = None,
|
|
66
|
-
output: dict | None = None,
|
|
76
|
+
input_schema: dict | str | None = None,
|
|
77
|
+
input: dict | str | None = None,
|
|
78
|
+
output_schema: dict | str | None = None,
|
|
79
|
+
output: dict | str | None = None,
|
|
67
80
|
deprecated: bool = False,
|
|
68
81
|
replacement: str | None = None,
|
|
82
|
+
agent_exposable: bool = False,
|
|
83
|
+
capability_id: str | None = None,
|
|
84
|
+
effects: list[str] | None = None,
|
|
85
|
+
risk: str = "read",
|
|
86
|
+
supports_scheduling: bool = True,
|
|
87
|
+
idempotent: bool = False,
|
|
88
|
+
timeout_seconds: int = 60,
|
|
89
|
+
tags: list[str] | None = None,
|
|
90
|
+
artifact_inputs: list[str] | None = None,
|
|
91
|
+
artifact_outputs: list[str] | None = None,
|
|
92
|
+
examples: list[dict[str, Any]] | None = None,
|
|
93
|
+
cost_class: str | None = None,
|
|
94
|
+
latency_class: str | None = None,
|
|
69
95
|
) -> Callable[[ServiceHandler], ServiceHandler]:
|
|
70
96
|
"""Mark an async function as a broker-callable service method."""
|
|
71
97
|
|
|
@@ -83,6 +109,19 @@ def service(
|
|
|
83
109
|
output_schema=output_schema or output,
|
|
84
110
|
deprecated=deprecated,
|
|
85
111
|
replacement=replacement,
|
|
112
|
+
agent_exposable=agent_exposable,
|
|
113
|
+
capability_id=capability_id,
|
|
114
|
+
effects=tuple(effects or ()),
|
|
115
|
+
risk=risk,
|
|
116
|
+
supports_scheduling=supports_scheduling,
|
|
117
|
+
idempotent=idempotent,
|
|
118
|
+
timeout_seconds=timeout_seconds,
|
|
119
|
+
tags=tuple(tags or ()),
|
|
120
|
+
artifact_inputs=tuple(artifact_inputs or ()),
|
|
121
|
+
artifact_outputs=tuple(artifact_outputs or ()),
|
|
122
|
+
examples=tuple(examples or ()),
|
|
123
|
+
cost_class=cost_class,
|
|
124
|
+
latency_class=latency_class,
|
|
86
125
|
)
|
|
87
126
|
)
|
|
88
127
|
return fn
|