@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
|
@@ -117,6 +117,7 @@ Available context values:
|
|
|
117
117
|
| `ctx.notifications` | Push OS notification-center notifications |
|
|
118
118
|
| `ctx.apps` / `services(ctx)` | Governed app-to-app calls through declared `consumes` contracts |
|
|
119
119
|
| `ctx.events` | Publish event topics declared in `provides.events` |
|
|
120
|
+
| `ctx.jobs` | Enqueue, inspect, and cancel durable background jobs |
|
|
120
121
|
| `ctx.redis` | Plugin/org-scoped Redis-style service when `platform_services` includes `redis` |
|
|
121
122
|
| `ctx.vector` | Plugin/org-scoped vector service when `platform_services` includes `vector` |
|
|
122
123
|
| `ctx.config` | App install/config values |
|
|
@@ -155,12 +156,155 @@ These are the public Python helpers exported by `palette_sdk`.
|
|
|
155
156
|
| `PlatformServiceUnavailable`, `UnavailablePlatformService` | Clear errors when an undeclared platform service is used |
|
|
156
157
|
| `LifecycleHooks` | Install/update/enable/disable/uninstall callbacks |
|
|
157
158
|
| `Event`, `EventPublisher`, `subscribe_event(...)` | In-process event subscriptions and declared app event publishing |
|
|
159
|
+
| `job(...)`, `JobExecution` | Register durable async job handlers and report progress, heartbeat, or cancellation |
|
|
160
|
+
| `JobHandle`, `JobsClient`, `ctx.jobs` | Enqueue jobs and inspect or cancel runs without retaining request state |
|
|
158
161
|
| `sign_webhook(...)`, `verify_webhook_signature(...)` | HMAC-SHA256 webhook signing and verification |
|
|
159
162
|
| `ToolDefinition` | Base class for custom agent tools |
|
|
160
163
|
| `PluginManifest`, `load_manifest(...)` | Typed manifest parsing from `palette-plugin.json` |
|
|
161
164
|
| `SuccessResponse`, `ErrorResponse`, `PaginatedResponse` | Common response schemas for plugin APIs |
|
|
162
165
|
| `route_permission_issues(router, public_routes=None)` | Test helper that reports routes missing `require_permission(...)` |
|
|
163
166
|
|
|
167
|
+
## 4b. Durable Background Jobs
|
|
168
|
+
|
|
169
|
+
Use Palette durable jobs for work that should continue after an HTTP response,
|
|
170
|
+
may take longer than normal request limits, or needs retries, progress, and
|
|
171
|
+
cancellation. Do not implement this by submitting an async function or request
|
|
172
|
+
context to `ThreadPoolExecutor`, `asyncio.create_task`, FastAPI
|
|
173
|
+
`BackgroundTasks`, or another process-local fire-and-forget mechanism.
|
|
174
|
+
|
|
175
|
+
Enable the capability in `palette-plugin.json`:
|
|
176
|
+
|
|
177
|
+
```json
|
|
178
|
+
{
|
|
179
|
+
"capabilities": {
|
|
180
|
+
"backend": true,
|
|
181
|
+
"database": true,
|
|
182
|
+
"background_jobs": true
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Register the handler with `@job`, enqueue a JSON payload from the route, and
|
|
188
|
+
return the handle's `202 Accepted` response:
|
|
189
|
+
|
|
190
|
+
```python
|
|
191
|
+
from fastapi import Depends
|
|
192
|
+
from palette_sdk import (
|
|
193
|
+
JobExecution,
|
|
194
|
+
PluginContext,
|
|
195
|
+
PluginRouter,
|
|
196
|
+
get_plugin_context,
|
|
197
|
+
job,
|
|
198
|
+
)
|
|
199
|
+
from models import Report
|
|
200
|
+
|
|
201
|
+
router = PluginRouter(tags=["reports"])
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@job("reports.generate", timeout_seconds=1800, max_attempts=3)
|
|
205
|
+
async def generate_report(
|
|
206
|
+
ctx: PluginContext,
|
|
207
|
+
execution: JobExecution,
|
|
208
|
+
payload: dict,
|
|
209
|
+
):
|
|
210
|
+
await execution.progress(10, "Loading rows")
|
|
211
|
+
report_id = payload["report_id"]
|
|
212
|
+
|
|
213
|
+
# This ctx and ctx.db belong to this job run, not to the HTTP request.
|
|
214
|
+
report = await ctx.repo(Report).get(report_id)
|
|
215
|
+
await execution.check_cancelled()
|
|
216
|
+
|
|
217
|
+
await execution.progress(80, "Writing report")
|
|
218
|
+
# Generate and store the report here.
|
|
219
|
+
return {"report_id": report.id}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@router.post("/reports/{report_id}/generate")
|
|
223
|
+
async def start_report(
|
|
224
|
+
report_id: int,
|
|
225
|
+
ctx: PluginContext = Depends(get_plugin_context),
|
|
226
|
+
):
|
|
227
|
+
handle = await ctx.jobs.enqueue(
|
|
228
|
+
"reports.generate",
|
|
229
|
+
{"report_id": report_id},
|
|
230
|
+
idempotency_key=f"report:{report_id}",
|
|
231
|
+
)
|
|
232
|
+
return handle.accepted_response()
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
`accepted_response()` returns HTTP `202`, because the request accepted the
|
|
236
|
+
work but did not complete it. Its JSON contains `job_id`, `status`,
|
|
237
|
+
`status_url`, and `events_url`. Returning `200` is technically possible, but
|
|
238
|
+
`202 Accepted` communicates the asynchronous contract correctly.
|
|
239
|
+
|
|
240
|
+
### Request Context And Thread Safety
|
|
241
|
+
|
|
242
|
+
The request `PluginContext` is request-scoped. Once the route returns, FastAPI
|
|
243
|
+
dependency cleanup can close or release `ctx.db` and its underlying
|
|
244
|
+
connection. SQLAlchemy `AsyncSession` and async database drivers are also not
|
|
245
|
+
safe to move to a worker thread or another event loop. Therefore, never pass,
|
|
246
|
+
capture, or store any of these for later execution:
|
|
247
|
+
|
|
248
|
+
- `ctx`, `ctx.db`, an ORM model instance, database connection, or transaction
|
|
249
|
+
- `Request`, uploaded file handles, open streams, or response objects
|
|
250
|
+
- an SDK service client whose lifetime is tied to the request context
|
|
251
|
+
|
|
252
|
+
Pass only a JSON object containing durable identifiers and values. The job
|
|
253
|
+
worker loads the handler from the publish that accepted the job and creates a
|
|
254
|
+
fresh `PluginContext`, database session, and scoped services for that run. It
|
|
255
|
+
also closes the job-owned resources after the run finishes.
|
|
256
|
+
|
|
257
|
+
`asyncio.to_thread(sync_function, plain_data)` is appropriate only for a short
|
|
258
|
+
synchronous blocking function that the route still awaits. It is not a durable
|
|
259
|
+
background-job mechanism, and request context or database objects should not
|
|
260
|
+
be passed to it.
|
|
261
|
+
|
|
262
|
+
### Progress, Status, And Cancellation
|
|
263
|
+
|
|
264
|
+
The `JobExecution` object exposes:
|
|
265
|
+
|
|
266
|
+
```python
|
|
267
|
+
await execution.progress(50, "Halfway")
|
|
268
|
+
await execution.heartbeat()
|
|
269
|
+
cancel_requested = await execution.cancelled()
|
|
270
|
+
await execution.check_cancelled()
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
Call `check_cancelled()` between meaningful units of work when the job can stop
|
|
274
|
+
cooperatively. A client can monitor or cancel a job through the returned URLs:
|
|
275
|
+
|
|
276
|
+
```text
|
|
277
|
+
GET /api/v1/app-jobs/<job-id>
|
|
278
|
+
GET /api/v1/app-jobs/<job-id>/events
|
|
279
|
+
POST /api/v1/app-jobs/<job-id>/cancel
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
The events URL is a server-sent event stream. Job states are `queued`,
|
|
283
|
+
`running`, `retrying`, `completed`, `failed`, and `cancelled`. Backend code can
|
|
284
|
+
also use `await ctx.jobs.get(job_id)` and `await ctx.jobs.cancel(job_id)` during
|
|
285
|
+
a normal request. Access remains scoped to the authenticated user,
|
|
286
|
+
organisation, and app.
|
|
287
|
+
|
|
288
|
+
### Retries And Idempotency
|
|
289
|
+
|
|
290
|
+
Handlers must tolerate retries. `max_attempts` defaults to `3` and accepts
|
|
291
|
+
values from `1` to `5`; `timeout_seconds` defaults to `900` and accepts values
|
|
292
|
+
from `1` to `7200`. Use an enqueue `idempotency_key` when repeated HTTP requests
|
|
293
|
+
must resolve to the same job. Keys are scoped by organisation, user, app,
|
|
294
|
+
handler, and key value.
|
|
295
|
+
|
|
296
|
+
Keep external side effects idempotent too. For example, record a stable
|
|
297
|
+
operation key before charging a payment or sending a third-party request. A
|
|
298
|
+
job result must be a JSON object or `None`; store large files through
|
|
299
|
+
`ctx.storage` and return their identifiers.
|
|
300
|
+
|
|
301
|
+
In hosted Palette, PostgreSQL persists job state before the `202` response,
|
|
302
|
+
Redis wakes workers, and each attempt runs in an isolated subprocess with a
|
|
303
|
+
fresh context. `pltt dev` provides the same app-facing API using a local task
|
|
304
|
+
registry and a fresh local database session per run; local jobs do not survive
|
|
305
|
+
the development process exiting. App developers only declare and enqueue jobs;
|
|
306
|
+
they do not create or operate thread pools or worker processes.
|
|
307
|
+
|
|
164
308
|
## 5. Permissions
|
|
165
309
|
|
|
166
310
|
Use route-level permission guards for normal APIs:
|
package/lib/cli.js
CHANGED
|
@@ -14,6 +14,7 @@ const secrets = require("./commands/secrets")
|
|
|
14
14
|
const services = require("./commands/services")
|
|
15
15
|
const version = require("./commands/version")
|
|
16
16
|
const update = require("./commands/update")
|
|
17
|
+
const capabilities = require("./commands/capabilities")
|
|
17
18
|
|
|
18
19
|
const COMMANDS = {
|
|
19
20
|
init: { run: init, help: "Scaffold a new plugin directory from the template" },
|
|
@@ -57,6 +58,14 @@ const COMMANDS = {
|
|
|
57
58
|
run: services,
|
|
58
59
|
help: "Inspect / pull / scaffold OS-broker services (list, pull, scaffold)",
|
|
59
60
|
},
|
|
61
|
+
capability: {
|
|
62
|
+
run: capabilities,
|
|
63
|
+
help: "Add, list, or inspect agent-callable app capabilities",
|
|
64
|
+
},
|
|
65
|
+
capabilities: {
|
|
66
|
+
run: capabilities,
|
|
67
|
+
help: "Add, list, or inspect agent-callable app capabilities",
|
|
68
|
+
},
|
|
60
69
|
version: { run: version, help: "Show the installed pltt CLI version" },
|
|
61
70
|
update: { run: update, help: "Update the globally installed pltt CLI" },
|
|
62
71
|
}
|
|
@@ -83,7 +92,7 @@ function printHelp() {
|
|
|
83
92
|
console.log(" --token <token> Publish token for pltt login")
|
|
84
93
|
console.log(" --no-default Do not make this environment the default")
|
|
85
94
|
console.log("\nInit flags:")
|
|
86
|
-
console.log(" --template <name> One of: dashboard, agent-tool, external-service, database, frontend-only, next")
|
|
95
|
+
console.log(" --template <name> One of: dashboard, agent-ready, agent-tool, external-service, database, frontend-only, next")
|
|
87
96
|
console.log("\nLogs flags:")
|
|
88
97
|
console.log(" --tail <n> Tail last n events (default 50)")
|
|
89
98
|
console.log(" -f, --follow Stream events (poll every 3s)")
|
|
@@ -92,6 +101,10 @@ function printHelp() {
|
|
|
92
101
|
console.log(" pltt services add TARGET # add a consumed service/event target")
|
|
93
102
|
console.log(" pltt services pull # generate typed TS+Python clients from consumes")
|
|
94
103
|
console.log(" pltt services scaffold NAME # add a provider method (schemas + handler stub)")
|
|
104
|
+
console.log("\nAgent capabilities:")
|
|
105
|
+
console.log(" pltt capabilities list")
|
|
106
|
+
console.log(" pltt capabilities inspect CAPABILITY_ID")
|
|
107
|
+
console.log(" pltt capabilities add creative.poster.generate --risk write --idempotent")
|
|
95
108
|
console.log("\nSecrets:")
|
|
96
109
|
console.log(" pltt secrets init")
|
|
97
110
|
console.log(" pltt secrets set NAME --value <secret> --env staging")
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict"
|
|
2
|
+
|
|
3
|
+
const { loadManifest } = require("../manifest")
|
|
4
|
+
const servicesCommand = require("./services")
|
|
5
|
+
|
|
6
|
+
function valueAfter(args, flag) {
|
|
7
|
+
const index = args.indexOf(flag)
|
|
8
|
+
return index === -1 ? null : args[index + 1] || null
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function methodFromCapabilityId(capabilityId) {
|
|
12
|
+
const parts = String(capabilityId || "").split(".").filter(Boolean)
|
|
13
|
+
return parts.slice(-2).join(".") || "agent.action"
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function collect(manifest) {
|
|
17
|
+
const out = []
|
|
18
|
+
for (const service of manifest.provides?.services || []) {
|
|
19
|
+
for (const method of service.methods || []) {
|
|
20
|
+
if (!method.agent_exposable) continue
|
|
21
|
+
out.push({
|
|
22
|
+
capability_id: method.capability_id || "app." + manifest.id + "." + method.name,
|
|
23
|
+
runtime_target: (manifest.provides?.namespace || manifest.id) + "/" + (service.version || "v1") + "#" + method.name,
|
|
24
|
+
name: method.name,
|
|
25
|
+
description: method.description || service.description || "",
|
|
26
|
+
risk: method.risk || (method.annotations?.readOnlyHint ? "read" : "write"),
|
|
27
|
+
effects: method.effects || [],
|
|
28
|
+
supports_scheduling: method.supports_scheduling !== false,
|
|
29
|
+
idempotent: method.idempotent === true,
|
|
30
|
+
timeout_seconds: method.timeout_seconds || 60,
|
|
31
|
+
tags: method.tags || [],
|
|
32
|
+
artifact_inputs: method.artifact_inputs || [],
|
|
33
|
+
artifact_outputs: method.artifact_outputs || [],
|
|
34
|
+
examples: method.examples || [],
|
|
35
|
+
cost_class: method.cost_class || null,
|
|
36
|
+
latency_class: method.latency_class || null,
|
|
37
|
+
deprecated: method.deprecated === true,
|
|
38
|
+
replacement: method.replacement || null,
|
|
39
|
+
input_schema: method.input_schema || method.input || null,
|
|
40
|
+
output_schema: method.output_schema || method.output || null,
|
|
41
|
+
source: "service",
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
for (const tool of manifest.mcp?.provides?.tools || []) {
|
|
46
|
+
if (!tool.agent_exposable) continue
|
|
47
|
+
out.push({
|
|
48
|
+
capability_id: tool.capability_id || "app." + manifest.id + "." + tool.name,
|
|
49
|
+
runtime_target: (manifest.provides?.namespace || manifest.id) + "/v1#" + tool.name,
|
|
50
|
+
name: tool.name,
|
|
51
|
+
description: tool.description || "",
|
|
52
|
+
risk: tool.risk || (tool.annotations?.readOnlyHint ? "read" : "write"),
|
|
53
|
+
effects: tool.effects || [],
|
|
54
|
+
supports_scheduling: tool.supports_scheduling !== false,
|
|
55
|
+
idempotent: tool.idempotent === true,
|
|
56
|
+
timeout_seconds: tool.timeout_seconds || 60,
|
|
57
|
+
tags: tool.tags || [],
|
|
58
|
+
artifact_inputs: tool.artifact_inputs || [],
|
|
59
|
+
artifact_outputs: tool.artifact_outputs || [],
|
|
60
|
+
examples: tool.examples || [],
|
|
61
|
+
cost_class: tool.cost_class || null,
|
|
62
|
+
latency_class: tool.latency_class || null,
|
|
63
|
+
deprecated: tool.deprecated === true,
|
|
64
|
+
replacement: tool.replacement || null,
|
|
65
|
+
input_schema: tool.input_schema || null,
|
|
66
|
+
output_schema: tool.output_schema || null,
|
|
67
|
+
source: "mcp",
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
for (const tool of manifest.tools || []) {
|
|
71
|
+
out.push({
|
|
72
|
+
capability_id: "app." + manifest.id + "." + tool.name,
|
|
73
|
+
name: tool.name,
|
|
74
|
+
description: tool.description || "",
|
|
75
|
+
risk: "unknown",
|
|
76
|
+
effects: [],
|
|
77
|
+
supports_scheduling: false,
|
|
78
|
+
idempotent: false,
|
|
79
|
+
timeout_seconds: null,
|
|
80
|
+
tags: [],
|
|
81
|
+
artifact_inputs: [],
|
|
82
|
+
artifact_outputs: [],
|
|
83
|
+
examples: [],
|
|
84
|
+
cost_class: null,
|
|
85
|
+
latency_class: null,
|
|
86
|
+
deprecated: true,
|
|
87
|
+
replacement: "@capability plus provides.services",
|
|
88
|
+
input_schema: null,
|
|
89
|
+
output_schema: null,
|
|
90
|
+
source: "legacy",
|
|
91
|
+
})
|
|
92
|
+
}
|
|
93
|
+
return out
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function run(args, { cwd }) {
|
|
97
|
+
const manifest = loadManifest(cwd)
|
|
98
|
+
const json = args.includes("--json")
|
|
99
|
+
const positional = args.filter((arg) => !arg.startsWith("-"))
|
|
100
|
+
const command = positional[0] || "list"
|
|
101
|
+
const id = command === "inspect" ? positional[1] : null
|
|
102
|
+
if (command === "add") {
|
|
103
|
+
const capabilityId = positional[1]
|
|
104
|
+
if (!capabilityId || !/^[a-z][a-z0-9_-]*(\.[a-z0-9_-]+){2,}$/.test(capabilityId)) {
|
|
105
|
+
throw new Error("usage: pltt capabilities add <domain.resource.action> [--method name] [--risk read|write|destructive|controlled] [--effects a,b] [--idempotent] [--no-scheduling]")
|
|
106
|
+
}
|
|
107
|
+
const method = valueAfter(args, "--method") || methodFromCapabilityId(capabilityId)
|
|
108
|
+
const risk = valueAfter(args, "--risk") || "read"
|
|
109
|
+
if (["write", "destructive"].includes(risk) && !args.includes("--idempotent") && !args.includes("--no-scheduling")) {
|
|
110
|
+
throw new Error("scheduled write capabilities require --idempotent, or use --no-scheduling for interactive-only actions")
|
|
111
|
+
}
|
|
112
|
+
const forwarded = [method, "--agent", "--capability-id", capabilityId]
|
|
113
|
+
for (const flag of ["--risk", "--effects"]) {
|
|
114
|
+
const value = valueAfter(args, flag)
|
|
115
|
+
if (value) forwarded.push(flag, value)
|
|
116
|
+
}
|
|
117
|
+
for (const flag of ["--idempotent", "--no-scheduling"]) {
|
|
118
|
+
if (args.includes(flag)) forwarded.push(flag)
|
|
119
|
+
}
|
|
120
|
+
await servicesCommand.runScaffold(forwarded, { cwd })
|
|
121
|
+
console.log("[pltt] agent capability ready; implement the generated handler, then run `pltt test --agent`")
|
|
122
|
+
return
|
|
123
|
+
}
|
|
124
|
+
const capabilities = collect(manifest)
|
|
125
|
+
|
|
126
|
+
if (command === "inspect") {
|
|
127
|
+
const item = capabilities.find((entry) => entry.capability_id === id || entry.name === id)
|
|
128
|
+
if (!item) throw new Error("capability not found: " + (id || "(missing id)"))
|
|
129
|
+
console.log(JSON.stringify(item, null, 2))
|
|
130
|
+
return
|
|
131
|
+
}
|
|
132
|
+
if (command !== "list") throw new Error("usage: pltt capabilities [list | inspect <id> | add <id>] [--json]")
|
|
133
|
+
if (json) {
|
|
134
|
+
console.log(JSON.stringify({ app_id: manifest.id, capabilities }, null, 2))
|
|
135
|
+
return
|
|
136
|
+
}
|
|
137
|
+
if (!capabilities.length) {
|
|
138
|
+
console.log("[pltt] no agent-exposable capabilities declared")
|
|
139
|
+
console.log("[pltt] expose a provides.services method with agent_exposable=true and a stable capability_id")
|
|
140
|
+
return
|
|
141
|
+
}
|
|
142
|
+
console.log("Capabilities for " + manifest.id + "@" + manifest.version)
|
|
143
|
+
for (const item of capabilities) {
|
|
144
|
+
const scheduling = item.supports_scheduling ? "scheduled" : "interactive-only"
|
|
145
|
+
console.log(" " + item.capability_id + " " + item.risk + ", " + scheduling)
|
|
146
|
+
console.log(" " + item.name + (item.description ? " - " + item.description : ""))
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
module.exports = run
|
|
151
|
+
module.exports.collect = collect
|
package/lib/commands/init.js
CHANGED
|
@@ -10,7 +10,7 @@ const DEFAULT_TEMPLATE_REPO = "palette-lab/plugin-template"
|
|
|
10
10
|
const TEMPLATE_REPO = process.env.PALETTE_TEMPLATE_REPO || DEFAULT_TEMPLATE_REPO
|
|
11
11
|
const TEMPLATE_REF = process.env.PALETTE_TEMPLATE_REF || "main"
|
|
12
12
|
|
|
13
|
-
const KNOWN_TEMPLATES = ["frontend-only", "palette-app", "next", "dashboard", "agent-tool", "external-service", "database", "provider-app", "consumer-app"]
|
|
13
|
+
const KNOWN_TEMPLATES = ["frontend-only", "palette-app", "next", "dashboard", "agent-tool", "agent-ready", "external-service", "database", "provider-app", "consumer-app"]
|
|
14
14
|
|
|
15
15
|
function toSlug(name) {
|
|
16
16
|
return name
|
|
@@ -39,7 +39,8 @@ function fetchTemplate(destDir) {
|
|
|
39
39
|
|
|
40
40
|
function copyLocalFallback(destDir, template) {
|
|
41
41
|
if (template) {
|
|
42
|
-
const
|
|
42
|
+
const resolvedTemplate = template === "agent-ready" ? "agent-tool" : template
|
|
43
|
+
const tplDir = path.resolve(__dirname, "..", "..", "template-fallback", "templates", resolvedTemplate)
|
|
43
44
|
if (!fs.existsSync(tplDir)) return false
|
|
44
45
|
fs.cpSync(tplDir, destDir, { recursive: true })
|
|
45
46
|
return true
|
package/lib/commands/services.js
CHANGED
|
@@ -380,20 +380,36 @@ function boolArg(source, name) {
|
|
|
380
380
|
return new RegExp(`${name}\\s*=\\s*True`).test(source)
|
|
381
381
|
}
|
|
382
382
|
|
|
383
|
+
function falseArg(source, name) {
|
|
384
|
+
return new RegExp(`${name}\\s*=\\s*False`).test(source)
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function intArg(source, name) {
|
|
388
|
+
const match = source.match(new RegExp(`${name}\\s*=\\s*(\\d+)`))
|
|
389
|
+
return match ? Number(match[1]) : null
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function stringListArg(source, name) {
|
|
393
|
+
const match = source.match(new RegExp(`${name}\\s*=\\s*\\[([\\s\\S]*?)\\]`))
|
|
394
|
+
if (!match) return null
|
|
395
|
+
return Array.from(match[1].matchAll(/["']([^"']+)["']/g), (item) => item[1])
|
|
396
|
+
}
|
|
397
|
+
|
|
383
398
|
function discoverServiceDecorators(cwd) {
|
|
384
399
|
const files = listPythonFiles(path.join(cwd, "backend"))
|
|
385
400
|
const found = []
|
|
386
401
|
for (const file of files) {
|
|
387
402
|
const text = fs.readFileSync(file, "utf8")
|
|
388
|
-
const re = /@service\s*\(([\s\S]*?)\)\s*(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)/g
|
|
403
|
+
const re = /@(service|capability)\s*\(([\s\S]*?)\)\s*(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)/g
|
|
389
404
|
let match
|
|
390
405
|
while ((match = re.exec(text))) {
|
|
391
|
-
const
|
|
406
|
+
const decorator = match[1]
|
|
407
|
+
const args = match[2]
|
|
392
408
|
const name = (args.match(/["']([^"']+)["']/) || [])[1]
|
|
393
409
|
if (!name) continue
|
|
394
410
|
found.push({
|
|
395
411
|
name,
|
|
396
|
-
fn: match[
|
|
412
|
+
fn: match[3],
|
|
397
413
|
scope: argValue(args, "scope"),
|
|
398
414
|
label: argValue(args, "label"),
|
|
399
415
|
description: argValue(args, "description"),
|
|
@@ -403,6 +419,18 @@ function discoverServiceDecorators(cwd) {
|
|
|
403
419
|
output_schema: argValue(args, "output_schema") || argValue(args, "output"),
|
|
404
420
|
deprecated: boolArg(args, "deprecated"),
|
|
405
421
|
replacement: argValue(args, "replacement"),
|
|
422
|
+
agent_exposable: decorator === "capability" || boolArg(args, "agent_exposable"),
|
|
423
|
+
capability_id: argValue(args, "capability_id"),
|
|
424
|
+
effects: stringListArg(args, "effects"),
|
|
425
|
+
risk: argValue(args, "risk"),
|
|
426
|
+
supports_scheduling: falseArg(args, "supports_scheduling") ? false : true,
|
|
427
|
+
idempotent: boolArg(args, "idempotent"),
|
|
428
|
+
timeout_seconds: intArg(args, "timeout_seconds"),
|
|
429
|
+
tags: stringListArg(args, "tags"),
|
|
430
|
+
artifact_inputs: stringListArg(args, "artifact_inputs"),
|
|
431
|
+
artifact_outputs: stringListArg(args, "artifact_outputs"),
|
|
432
|
+
cost_class: argValue(args, "cost_class"),
|
|
433
|
+
latency_class: argValue(args, "latency_class"),
|
|
406
434
|
file: path.relative(cwd, file),
|
|
407
435
|
})
|
|
408
436
|
}
|
|
@@ -414,7 +442,7 @@ async function runSync(argv, { cwd }) {
|
|
|
414
442
|
const manifest = readManifest(cwd)
|
|
415
443
|
const decorators = discoverServiceDecorators(cwd)
|
|
416
444
|
if (!decorators.length) {
|
|
417
|
-
console.log("[pltt] no @service(...) decorators found under backend/.")
|
|
445
|
+
console.log("[pltt] no @service(...) or @capability(...) decorators found under backend/.")
|
|
418
446
|
return
|
|
419
447
|
}
|
|
420
448
|
manifest.provides = manifest.provides || {}
|
|
@@ -443,6 +471,18 @@ async function runSync(argv, { cwd }) {
|
|
|
443
471
|
else method.output_schema = method.output_schema || `schemas/${decl.name}.out.json`
|
|
444
472
|
if (decl.deprecated) method.deprecated = true
|
|
445
473
|
if (decl.replacement) method.replacement = decl.replacement
|
|
474
|
+
if (decl.agent_exposable) method.agent_exposable = true
|
|
475
|
+
if (decl.capability_id) method.capability_id = decl.capability_id
|
|
476
|
+
if (decl.effects) method.effects = decl.effects
|
|
477
|
+
if (decl.risk) method.risk = decl.risk
|
|
478
|
+
if (decl.agent_exposable) method.supports_scheduling = decl.supports_scheduling
|
|
479
|
+
if (decl.agent_exposable) method.idempotent = decl.idempotent
|
|
480
|
+
if (decl.timeout_seconds) method.timeout_seconds = decl.timeout_seconds
|
|
481
|
+
if (decl.tags) method.tags = decl.tags
|
|
482
|
+
if (decl.artifact_inputs) method.artifact_inputs = decl.artifact_inputs
|
|
483
|
+
if (decl.artifact_outputs) method.artifact_outputs = decl.artifact_outputs
|
|
484
|
+
if (decl.cost_class) method.cost_class = decl.cost_class
|
|
485
|
+
if (decl.latency_class) method.latency_class = decl.latency_class
|
|
446
486
|
}
|
|
447
487
|
writeManifest(cwd, manifest)
|
|
448
488
|
console.log(`[pltt] synced ${decorators.length} service method(s) into palette-plugin.json`)
|
|
@@ -544,6 +584,15 @@ async function runScaffold(argv, { cwd }) {
|
|
|
544
584
|
process.exit(1)
|
|
545
585
|
}
|
|
546
586
|
const manifest = readManifest(cwd)
|
|
587
|
+
const agentExposable = argv.includes("--agent") || argv.includes("--capability-id")
|
|
588
|
+
const capabilityId = valueAfter(argv, "--capability-id") || `app.${manifest.id}.${method}`
|
|
589
|
+
const risk = valueAfter(argv, "--risk") || "read"
|
|
590
|
+
const effects = (valueAfter(argv, "--effects") || (risk === "read" ? "external.read" : "external.write"))
|
|
591
|
+
.split(",")
|
|
592
|
+
.map((item) => item.trim())
|
|
593
|
+
.filter(Boolean)
|
|
594
|
+
const supportsScheduling = !argv.includes("--no-scheduling")
|
|
595
|
+
const idempotent = argv.includes("--idempotent")
|
|
547
596
|
const namespace = (manifest.provides && manifest.provides.namespace) || manifest.id
|
|
548
597
|
const provides = manifest.provides || {}
|
|
549
598
|
provides.namespace = namespace
|
|
@@ -556,12 +605,25 @@ async function runScaffold(argv, { cwd }) {
|
|
|
556
605
|
provides.services.push(svc)
|
|
557
606
|
}
|
|
558
607
|
svc.methods = svc.methods || []
|
|
559
|
-
|
|
560
|
-
|
|
608
|
+
let methodSpec = svc.methods.find((m) => m && m.name === method)
|
|
609
|
+
if (!methodSpec) {
|
|
610
|
+
methodSpec = {
|
|
561
611
|
name: method,
|
|
562
612
|
scope: `${namespace}.${method}`,
|
|
563
613
|
input_schema: `schemas/${method}.in.json`,
|
|
564
614
|
output_schema: `schemas/${method}.out.json`,
|
|
615
|
+
}
|
|
616
|
+
svc.methods.push(methodSpec)
|
|
617
|
+
}
|
|
618
|
+
if (agentExposable) {
|
|
619
|
+
Object.assign(methodSpec, {
|
|
620
|
+
agent_exposable: true,
|
|
621
|
+
capability_id: capabilityId,
|
|
622
|
+
description: methodSpec.description || `Agent capability for ${method}.`,
|
|
623
|
+
effects,
|
|
624
|
+
risk,
|
|
625
|
+
supports_scheduling: supportsScheduling,
|
|
626
|
+
idempotent,
|
|
565
627
|
})
|
|
566
628
|
}
|
|
567
629
|
manifest.provides = provides
|
|
@@ -594,8 +656,10 @@ async function runScaffold(argv, { cwd }) {
|
|
|
594
656
|
if (!fs.existsSync(handlerPath)) {
|
|
595
657
|
fs.writeFileSync(
|
|
596
658
|
handlerPath,
|
|
597
|
-
`from palette_sdk import service, PluginContext\n\n` +
|
|
598
|
-
|
|
659
|
+
`from palette_sdk import ${agentExposable ? "capability" : "service"}, PluginContext\n\n` +
|
|
660
|
+
(agentExposable
|
|
661
|
+
? `@capability(${JSON.stringify(method)}, capability_id=${JSON.stringify(capabilityId)}, scope=${JSON.stringify(namespace + "." + method)}, description=${JSON.stringify(`Agent capability for ${method}.`)}, input_schema=${JSON.stringify(`schemas/${method}.in.json`)}, output_schema=${JSON.stringify(`schemas/${method}.out.json`)}, effects=${JSON.stringify(effects)}, risk=${JSON.stringify(risk)}, supports_scheduling=${supportsScheduling ? "True" : "False"}, idempotent=${idempotent ? "True" : "False"})\n`
|
|
662
|
+
: `@service(${JSON.stringify(method)}, scope=${JSON.stringify(namespace + "." + method)})\n`) +
|
|
599
663
|
`async def ${safeIdent(method)}(ctx: PluginContext, payload: dict) -> dict:\n` +
|
|
600
664
|
` """Provider handler for ${namespace}/v1#${method}.\n\n` +
|
|
601
665
|
` The OS broker validates payload against schemas/${method}.in.json and the\n` +
|
|
@@ -662,3 +726,5 @@ async function run(argv, ctx) {
|
|
|
662
726
|
}
|
|
663
727
|
|
|
664
728
|
module.exports = run
|
|
729
|
+
module.exports.runScaffold = runScaffold
|
|
730
|
+
module.exports.discoverServiceDecorators = discoverServiceDecorators
|
package/lib/commands/test.js
CHANGED
|
@@ -8,8 +8,8 @@ const { bundleFrontend, bundleBackend } = require("../bundler")
|
|
|
8
8
|
const { declaredSecrets, loadLocalEnv, loadLocalEnvDetails } = require("../secrets")
|
|
9
9
|
const buildCommand = require("./build")
|
|
10
10
|
|
|
11
|
-
const DEFAULT_FRONTEND_BUNDLE_LIMIT =
|
|
12
|
-
const DEFAULT_BACKEND_BUNDLE_LIMIT =
|
|
11
|
+
const DEFAULT_FRONTEND_BUNDLE_LIMIT = 50 * 1024 * 1024
|
|
12
|
+
const DEFAULT_BACKEND_BUNDLE_LIMIT = 50 * 1024 * 1024
|
|
13
13
|
|
|
14
14
|
function reporter(json, results) {
|
|
15
15
|
function printExtra(meta) {
|
|
@@ -169,6 +169,7 @@ function checkBackendContract(cwd, manifest, out, pythonInfo) {
|
|
|
169
169
|
"router = getattr(mod, 'router', None)",
|
|
170
170
|
"assert router is not None, 'backend entry has no router export'",
|
|
171
171
|
"from palette_sdk.permissions import is_permission_dep",
|
|
172
|
+
"from palette_sdk.services import drain_pending_services",
|
|
172
173
|
"public = set(manifest.get('public_routes') or [])",
|
|
173
174
|
"declared = set(manifest.get('permissions') or [])",
|
|
174
175
|
"routes = []",
|
|
@@ -196,7 +197,10 @@ function checkBackendContract(cwd, manifest, out, pythonInfo) {
|
|
|
196
197
|
" routes.append({'path': path, 'methods': methods, 'permissions': sorted(set(perms)), 'public': path in public})",
|
|
197
198
|
" if path not in public and not perms:",
|
|
198
199
|
" ungated.append({'path': path, 'methods': methods})",
|
|
199
|
-
"
|
|
200
|
+
"capabilities = []",
|
|
201
|
+
"for item in drain_pending_services():",
|
|
202
|
+
" capabilities.append({'name': item.name, 'agent_exposable': item.agent_exposable, 'capability_id': item.capability_id, 'effects': list(item.effects), 'risk': item.risk, 'supports_scheduling': item.supports_scheduling, 'idempotent': item.idempotent, 'timeout_seconds': item.timeout_seconds, 'tags': list(item.tags), 'artifact_inputs': list(item.artifact_inputs), 'artifact_outputs': list(item.artifact_outputs), 'cost_class': item.cost_class, 'latency_class': item.latency_class})",
|
|
203
|
+
"print(json.dumps({'routes': routes, 'used_permissions': sorted(used), 'ungated_routes': ungated, 'undeclared_permissions': sorted(used - declared), 'unused_declared_permissions': sorted(declared - used), 'capabilities': capabilities}))",
|
|
200
204
|
].join("\n")
|
|
201
205
|
const res = spawnSync(python, ["-c", script, abs, JSON.stringify(manifest)], { encoding: "utf8", env })
|
|
202
206
|
if (res.status === 0) {
|
|
@@ -244,6 +248,90 @@ function checkBackendContract(cwd, manifest, out, pythonInfo) {
|
|
|
244
248
|
{ permissions: report.unused_declared_permissions },
|
|
245
249
|
)
|
|
246
250
|
}
|
|
251
|
+
const manifestCapabilities = []
|
|
252
|
+
for (const service of manifest.provides?.services || []) {
|
|
253
|
+
for (const method of service.methods || []) {
|
|
254
|
+
if (method.agent_exposable) manifestCapabilities.push(method)
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const runtimeByName = new Map((report.capabilities || []).map((item) => [item.name, item]))
|
|
258
|
+
for (const method of manifestCapabilities) {
|
|
259
|
+
if (!method.capability_id) {
|
|
260
|
+
failures += out.fail(
|
|
261
|
+
`agent capability has no stable capability_id: ${method.name}`,
|
|
262
|
+
"Add a semantic id such as creative.poster.generate; saved workflows use it to survive provider changes.",
|
|
263
|
+
)
|
|
264
|
+
}
|
|
265
|
+
const writeEffects = (method.effects || []).some((effect) => /(^|\.)(write|create|update|delete|publish|send)$/.test(effect))
|
|
266
|
+
if (method.risk === "read" && writeEffects) {
|
|
267
|
+
failures += out.fail(
|
|
268
|
+
`read-only capability declares write effects: ${method.name}`,
|
|
269
|
+
"Set risk to write/destructive or remove the write effect.",
|
|
270
|
+
)
|
|
271
|
+
}
|
|
272
|
+
if (["write", "destructive"].includes(method.risk) && method.supports_scheduling !== false && method.idempotent !== true) {
|
|
273
|
+
failures += out.fail(
|
|
274
|
+
`scheduled write capability is not idempotent: ${method.name}`,
|
|
275
|
+
"Implement idempotency and set idempotent=true, or set supports_scheduling=false.",
|
|
276
|
+
)
|
|
277
|
+
}
|
|
278
|
+
const runtime = runtimeByName.get(method.name)
|
|
279
|
+
if (!runtime) {
|
|
280
|
+
failures += out.fail(
|
|
281
|
+
`agent capability has no runtime handler: ${method.name}`,
|
|
282
|
+
`Import a @capability("${method.name}", capability_id="${method.capability_id || "..."}") handler from ${entry}.`,
|
|
283
|
+
)
|
|
284
|
+
continue
|
|
285
|
+
}
|
|
286
|
+
if (!runtime.agent_exposable) {
|
|
287
|
+
failures += out.fail(
|
|
288
|
+
`runtime handler is not agent-exposable: ${method.name}`,
|
|
289
|
+
"Use the @capability decorator or service(..., agent_exposable=True).",
|
|
290
|
+
)
|
|
291
|
+
}
|
|
292
|
+
if (method.capability_id && runtime.capability_id !== method.capability_id) {
|
|
293
|
+
failures += out.fail(
|
|
294
|
+
`capability id mismatch for ${method.name}`,
|
|
295
|
+
`Make the decorator capability_id exactly "${method.capability_id}".`,
|
|
296
|
+
{ manifest: method.capability_id, runtime: runtime.capability_id },
|
|
297
|
+
)
|
|
298
|
+
}
|
|
299
|
+
const parityFields = [
|
|
300
|
+
"effects", "risk", "supports_scheduling", "idempotent", "timeout_seconds",
|
|
301
|
+
"tags", "artifact_inputs", "artifact_outputs", "cost_class", "latency_class",
|
|
302
|
+
]
|
|
303
|
+
for (const field of parityFields) {
|
|
304
|
+
if (method[field] === undefined) continue
|
|
305
|
+
if (JSON.stringify(method[field]) !== JSON.stringify(runtime[field])) {
|
|
306
|
+
failures += out.fail(
|
|
307
|
+
`capability metadata mismatch for ${method.name}: ${field}`,
|
|
308
|
+
`Make the @capability ${field} match palette-plugin.json.`,
|
|
309
|
+
{ manifest: method[field], runtime: runtime[field] },
|
|
310
|
+
)
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
const manifestNames = new Set(manifestCapabilities.map((item) => item.name))
|
|
315
|
+
for (const runtime of report.capabilities || []) {
|
|
316
|
+
if (runtime.agent_exposable && !manifestNames.has(runtime.name)) {
|
|
317
|
+
failures += out.fail(
|
|
318
|
+
`runtime capability is missing from manifest: ${runtime.name}`,
|
|
319
|
+
"Add a matching agent_exposable provides.services method so publish review can govern it.",
|
|
320
|
+
)
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
if (manifestCapabilities.length && failures === 0) {
|
|
324
|
+
out.ok("agent capability handlers match the reviewed manifest", {
|
|
325
|
+
capabilities: manifestCapabilities.map((item) => item.capability_id || item.name),
|
|
326
|
+
})
|
|
327
|
+
}
|
|
328
|
+
if ((manifest.tools || []).length) {
|
|
329
|
+
out.warn(
|
|
330
|
+
"manifest.tools is a legacy agent integration surface",
|
|
331
|
+
"Migrate each entry to a typed @capability handler plus an agent_exposable provides.services method.",
|
|
332
|
+
{ tools: manifest.tools.map((item) => item.name) },
|
|
333
|
+
)
|
|
334
|
+
}
|
|
247
335
|
return failures
|
|
248
336
|
}
|
|
249
337
|
return out.fail(
|