@palettelab/cli 0.3.63 → 0.3.66
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 +144 -9
- package/backend-sdk/palette_sdk/__init__.py +17 -1
- package/backend-sdk/palette_sdk/data_rooms.py +2 -2
- package/backend-sdk/palette_sdk/db/base.py +4 -1
- package/backend-sdk/palette_sdk/db/rls.py +7 -1
- package/backend-sdk/palette_sdk/manifest.py +9 -1
- package/backend-sdk/palette_sdk/platform_services.py +790 -36
- package/backend-sdk/palette_sdk/plugin_context.py +30 -2
- package/backend-sdk/palette_sdk/plugin_router.py +64 -8
- package/backend-sdk/palette_sdk/repository.py +12 -3
- package/backend-sdk/palette_sdk/tasks.py +117 -0
- package/backend-sdk/pyproject.toml +1 -1
- package/docs/python-backend-sdk.md +132 -8
- package/lib/cli.js +20 -2
- package/lib/commands/capabilities.js +1 -1
- package/lib/commands/doctor.js +15 -0
- package/lib/commands/models.js +65 -0
- package/lib/commands/platform.js +137 -0
- package/lib/commands/test.js +47 -4
- package/lib/dev-simulator.js +95 -0
- package/lib/manifest.js +123 -3
- package/package.json +1 -1
- package/template-fallback/README.md +9 -0
- package/template-fallback/frontend/src/translations.ts +2 -2
- package/template-fallback/package.json +1 -1
- package/template-fallback/palette-plugin.json +1 -0
- package/template-fallback/templates/agent-tool/palette-plugin.json +1 -0
- package/template-fallback/templates/consumer-app/package.json +1 -1
- package/template-fallback/templates/consumer-app/palette-plugin.json +1 -0
- package/template-fallback/templates/dashboard/package.json +1 -1
- package/template-fallback/templates/dashboard/palette-plugin.json +1 -0
- package/template-fallback/templates/database/package.json +1 -1
- package/template-fallback/templates/database/palette-plugin.json +1 -0
- package/template-fallback/templates/external-service/package.json +1 -1
- package/template-fallback/templates/external-service/palette-plugin.json +1 -0
- package/template-fallback/templates/frontend-only/package.json +1 -1
- package/template-fallback/templates/frontend-only/palette-plugin.json +1 -0
- package/template-fallback/templates/next/package.json +1 -1
- package/template-fallback/templates/next/palette-plugin.json +1 -0
- package/template-fallback/templates/palette-app/package.json +1 -1
- package/template-fallback/templates/palette-app/palette-plugin.json +1 -0
- package/template-fallback/templates/provider-app/package.json +1 -1
- package/template-fallback/templates/provider-app/palette-plugin.json +1 -0
package/lib/commands/doctor.js
CHANGED
|
@@ -34,6 +34,10 @@ const PLATFORM_SERVICE_DEV_NOTES = {
|
|
|
34
34
|
process.env.OPENAI_API_KEY || localEnvHas(cwd, "OPENAI_API_KEY")
|
|
35
35
|
? "pltt dev: live via your OPENAI_API_KEY"
|
|
36
36
|
: "pltt dev: stubbed — set OPENAI_API_KEY for real calls (hosted uses the platform key)",
|
|
37
|
+
media: (cwd) =>
|
|
38
|
+
process.env.FAL_KEY || localEnvHas(cwd, "FAL_KEY")
|
|
39
|
+
? "pltt dev: live via your FAL_KEY"
|
|
40
|
+
: "pltt dev: stubbed — set FAL_KEY for real renders (hosted uses the platform key)",
|
|
37
41
|
web: () => "pltt dev: keyless DuckDuckGo (hosted uses the platform search key)",
|
|
38
42
|
redis: () => "pltt dev: in-memory",
|
|
39
43
|
vector: () => "pltt dev: in-memory hash embeddings",
|
|
@@ -51,8 +55,10 @@ function localEnvHas(cwd, name) {
|
|
|
51
55
|
function reportPlatformServices(manifest, cwd) {
|
|
52
56
|
const declared = manifest.platform_services
|
|
53
57
|
const names = Array.isArray(declared) ? declared : Object.keys(declared || {})
|
|
58
|
+
const { PLATFORM_SERVICES } = require("../manifest")
|
|
54
59
|
if (!names.length) {
|
|
55
60
|
ok("no platform services declared")
|
|
61
|
+
console.log(` available: ${PLATFORM_SERVICES.map((s) => s.name).join(", ")} — pltt platform list`)
|
|
56
62
|
} else {
|
|
57
63
|
ok(`manifest declares ${names.length} platform service(s): ${names.join(", ")}`)
|
|
58
64
|
for (const name of names) {
|
|
@@ -61,6 +67,15 @@ function reportPlatformServices(manifest, cwd) {
|
|
|
61
67
|
}
|
|
62
68
|
}
|
|
63
69
|
|
|
70
|
+
const { INERT_PERMISSIONS } = require("../manifest")
|
|
71
|
+
const inert = (manifest.permissions || []).filter((permission) => INERT_PERMISSIONS.has(permission))
|
|
72
|
+
if (inert.length) {
|
|
73
|
+
warn(
|
|
74
|
+
`permissions grant nothing today: ${inert.join(", ")}`,
|
|
75
|
+
"No ctx.* client is behind them, so an app cannot act on them and a reviewer should not read them as capability. Drop them from the manifest.",
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
|
|
64
79
|
const conns = manifest.connections || []
|
|
65
80
|
if (!conns.length) {
|
|
66
81
|
ok("no service connections declared")
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict"
|
|
2
|
+
|
|
3
|
+
const { loadManifest } = require("../manifest")
|
|
4
|
+
const { parseFlags, resolveEnvironment } = require("../environments")
|
|
5
|
+
|
|
6
|
+
const KINDS = ["chat", "image", "video", "audio"]
|
|
7
|
+
const USAGE = "usage: pltt models [--kind chat|image|video|audio] [--available] [--json] [--env <name>]"
|
|
8
|
+
|
|
9
|
+
// The platform answers with THIS app's view: the manifest goes along so
|
|
10
|
+
// declared premium models and capacity (platform_services.llm) are reflected.
|
|
11
|
+
async function fetchModels(env, manifest) {
|
|
12
|
+
const url = `${env.url}/api/v1/appstore/platform-models`
|
|
13
|
+
const res = await fetch(url, {
|
|
14
|
+
method: "POST",
|
|
15
|
+
headers: { Authorization: `Bearer ${env.token}`, "Content-Type": "application/json" },
|
|
16
|
+
body: JSON.stringify({ manifest }),
|
|
17
|
+
})
|
|
18
|
+
if (!res.ok) throw new Error(`POST ${url} → ${res.status}: ${await res.text()}`)
|
|
19
|
+
return res.json()
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function selectRows(data, { kind, available }) {
|
|
23
|
+
return [...(data.chat || []), ...(data.media || [])].filter(
|
|
24
|
+
(row) => (!kind || row.kind === kind) && (!available || row.available),
|
|
25
|
+
)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function formatRow(row) {
|
|
29
|
+
const limits = row.limits || {}
|
|
30
|
+
const detail =
|
|
31
|
+
row.kind === "chat"
|
|
32
|
+
? `${limits.max_output_tokens ?? "?"} out tok, ${limits.max_images ?? "?"} img`
|
|
33
|
+
: (row.operations || []).join(", ")
|
|
34
|
+
const note = row.available ? (row.default || (row.default_for || []).length ? "default" : "") : row.reason
|
|
35
|
+
return ` ${row.available ? "ok" : "--"} ${String(row.id).padEnd(46)} ${String(row.provider).padEnd(9)} ${String(row.kind).padEnd(6)} ${detail}${note ? ` (${note})` : ""}`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function run(argv, { cwd, log = console.log } = {}) {
|
|
39
|
+
const kindAt = argv.indexOf("--kind")
|
|
40
|
+
const kind = kindAt >= 0 ? argv[kindAt + 1] : undefined
|
|
41
|
+
if (kindAt >= 0 && !KINDS.includes(kind)) throw new Error(USAGE)
|
|
42
|
+
const manifest = loadManifest(cwd)
|
|
43
|
+
const { flags } = parseFlags(argv)
|
|
44
|
+
const env = resolveEnvironment({ cwd, flags })
|
|
45
|
+
if (!env.url) throw new Error(`environment "${env.name}" has no url — run pltt login --env ${env.name} --url <url> --token <token>`)
|
|
46
|
+
if (!env.token) throw new Error(`no publish token for "${env.name}" — run pltt login or set $${env.token_env}`)
|
|
47
|
+
const data = await fetchModels(env, manifest)
|
|
48
|
+
const rows = selectRows(data, { kind, available: argv.includes("--available") })
|
|
49
|
+
if (argv.includes("--json")) {
|
|
50
|
+
log(JSON.stringify({ app_id: data.app_id, organization_id: data.organization_id, models: rows }, null, 2))
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
log(`Models ${data.app_id} can use in workspace ${data.organization_id} (${env.name}):\n`)
|
|
54
|
+
for (const row of rows) log(formatRow(row))
|
|
55
|
+
const blocked = rows.filter((row) => row.reason === "not_approved").map((row) => row.id)
|
|
56
|
+
if (blocked.length) {
|
|
57
|
+
log(`\n Premium models need a declaration, e.g. platform_services.llm.models: ["${blocked[0]}"]`)
|
|
58
|
+
}
|
|
59
|
+
log("\n Pass an id as ctx.llm.chat(..., model=...) or ctx.media.run(<id>, ...); fallback=False refuses substitutes.")
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
module.exports = run
|
|
63
|
+
module.exports.fetchModels = fetchModels
|
|
64
|
+
module.exports.formatRow = formatRow
|
|
65
|
+
module.exports.selectRows = selectRows
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"use strict"
|
|
2
|
+
|
|
3
|
+
const fs = require("fs")
|
|
4
|
+
const path = require("path")
|
|
5
|
+
|
|
6
|
+
const { CTX_PERMISSIONS, PLATFORM_SERVICES, loadManifest } = require("../manifest")
|
|
7
|
+
const { loadLocalEnvDetails } = require("../secrets")
|
|
8
|
+
|
|
9
|
+
// Local key that makes a service call for real under `pltt dev` instead of
|
|
10
|
+
// returning a stub. Absent = the app still runs, it just gets placeholders.
|
|
11
|
+
const DEV_KEYS = { llm: "OPENAI_API_KEY", media: "FAL_KEY" }
|
|
12
|
+
|
|
13
|
+
function declaredNames(manifest) {
|
|
14
|
+
const declared = manifest.platform_services
|
|
15
|
+
return Array.isArray(declared) ? declared.slice() : Object.keys(declared || {})
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function devNote(name, cwd) {
|
|
19
|
+
const key = DEV_KEYS[name]
|
|
20
|
+
if (!key) return "pltt dev: emulated locally"
|
|
21
|
+
let present = Boolean(process.env[key])
|
|
22
|
+
if (!present) {
|
|
23
|
+
try {
|
|
24
|
+
present = Boolean(loadLocalEnvDetails(cwd, { apply: false }).values[key])
|
|
25
|
+
} catch {
|
|
26
|
+
present = false
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return present
|
|
30
|
+
? `pltt dev: live via your ${key}`
|
|
31
|
+
: `pltt dev: stubbed — set ${key} in .env.local for real calls`
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function list(manifest, cwd, json) {
|
|
35
|
+
const on = new Set(declaredNames(manifest))
|
|
36
|
+
const granted = new Set(manifest.permissions || [])
|
|
37
|
+
const rows = PLATFORM_SERVICES.map((service) => ({
|
|
38
|
+
...service,
|
|
39
|
+
declared: on.has(service.name),
|
|
40
|
+
dev: devNote(service.name, cwd),
|
|
41
|
+
}))
|
|
42
|
+
// The other half of what `ctx` can do: clients switched on by a manifest
|
|
43
|
+
// permission rather than by platform_services. Printing them together is the
|
|
44
|
+
// only way "what can ctx do, and what do I declare to get it" is one answer.
|
|
45
|
+
const gated = CTX_PERMISSIONS.map((entry) => ({
|
|
46
|
+
...entry,
|
|
47
|
+
declared: entry.permissions.some((permission) => granted.has(permission)),
|
|
48
|
+
missing: entry.permissions.filter((permission) => !granted.has(permission)),
|
|
49
|
+
}))
|
|
50
|
+
if (json) {
|
|
51
|
+
console.log(JSON.stringify({ app_id: manifest.id, services: rows, permissions: gated }, null, 2))
|
|
52
|
+
return
|
|
53
|
+
}
|
|
54
|
+
console.log(`Platform services for ${manifest.id}@${manifest.version}`)
|
|
55
|
+
console.log("Declare one and the platform's own credential is used — your app ships no key.\n")
|
|
56
|
+
for (const row of rows) {
|
|
57
|
+
console.log(` ${row.declared ? "[on] " : "[ ] "}${row.name.padEnd(8)} ${row.accessor}`)
|
|
58
|
+
console.log(` ${row.summary}`)
|
|
59
|
+
console.log(` instead of: ${row.instead_of}`)
|
|
60
|
+
if (row.python) console.log(` ${row.python}`)
|
|
61
|
+
console.log(` ${row.dev}`)
|
|
62
|
+
}
|
|
63
|
+
console.log("\nPermission-gated clients — add the permission to palette-plugin.json:\n")
|
|
64
|
+
for (const entry of gated) {
|
|
65
|
+
console.log(` ${entry.declared ? "[on] " : "[ ] "}${entry.accessor}`)
|
|
66
|
+
console.log(` ${entry.summary}`)
|
|
67
|
+
console.log(` permissions: ${entry.permissions.join(", ")}`)
|
|
68
|
+
if (entry.python) console.log(` ${entry.python}`)
|
|
69
|
+
}
|
|
70
|
+
const off = rows.filter((row) => !row.declared).map((row) => row.name)
|
|
71
|
+
if (off.length) console.log(`\n pltt platform enable ${off[0]}`)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function writeManifest(cwd, mutate) {
|
|
75
|
+
const file = path.join(cwd, "palette-plugin.json")
|
|
76
|
+
const raw = JSON.parse(fs.readFileSync(file, "utf8"))
|
|
77
|
+
mutate(raw)
|
|
78
|
+
fs.writeFileSync(file, JSON.stringify(raw, null, 2) + "\n")
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function assertKnown(names) {
|
|
82
|
+
const known = new Set(PLATFORM_SERVICES.map((service) => service.name))
|
|
83
|
+
const bad = names.filter((name) => !known.has(name))
|
|
84
|
+
if (!names.length || bad.length) {
|
|
85
|
+
throw new Error(
|
|
86
|
+
`usage: pltt platform <enable|disable> <${Array.from(known).join("|")}>` +
|
|
87
|
+
(bad.length ? ` (unknown: ${bad.join(", ")})` : ""),
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function enable(cwd, names) {
|
|
93
|
+
assertKnown(names)
|
|
94
|
+
writeManifest(cwd, (manifest) => {
|
|
95
|
+
const current = manifest.platform_services
|
|
96
|
+
if (current && !Array.isArray(current)) {
|
|
97
|
+
// Object form carries per-service billing/required settings — keep it.
|
|
98
|
+
for (const name of names) if (!current[name]) current[name] = {}
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
const next = new Set([...(current || []), ...names])
|
|
102
|
+
manifest.platform_services = Array.from(next).sort()
|
|
103
|
+
})
|
|
104
|
+
for (const name of names) {
|
|
105
|
+
const service = PLATFORM_SERVICES.find((entry) => entry.name === name)
|
|
106
|
+
console.log(`[pltt] ${service.accessor} enabled — ${service.summary}`)
|
|
107
|
+
if (service.python) console.log(` ${service.python}`)
|
|
108
|
+
const key = DEV_KEYS[name]
|
|
109
|
+
if (key) console.log(` pltt dev stubs this unless ${key} is in .env.local`)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function disable(cwd, names) {
|
|
114
|
+
assertKnown(names)
|
|
115
|
+
writeManifest(cwd, (manifest) => {
|
|
116
|
+
const current = manifest.platform_services
|
|
117
|
+
if (current && !Array.isArray(current)) {
|
|
118
|
+
for (const name of names) delete current[name]
|
|
119
|
+
return
|
|
120
|
+
}
|
|
121
|
+
manifest.platform_services = (current || []).filter((name) => !names.includes(name))
|
|
122
|
+
})
|
|
123
|
+
console.log(`[pltt] removed: ${names.join(", ")}`)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function run(args, { cwd }) {
|
|
127
|
+
const manifest = loadManifest(cwd)
|
|
128
|
+
const positional = args.filter((arg) => !arg.startsWith("-"))
|
|
129
|
+
const command = positional[0] || "list"
|
|
130
|
+
const names = positional.slice(1)
|
|
131
|
+
if (command === "list") return list(manifest, cwd, args.includes("--json"))
|
|
132
|
+
if (command === "enable" || command === "add") return enable(cwd, names)
|
|
133
|
+
if (command === "disable" || command === "remove") return disable(cwd, names)
|
|
134
|
+
throw new Error("usage: pltt platform [list | enable <service...> | disable <service...>] [--json]")
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
module.exports = run
|
package/lib/commands/test.js
CHANGED
|
@@ -3,11 +3,51 @@
|
|
|
3
3
|
const fs = require("fs")
|
|
4
4
|
const path = require("path")
|
|
5
5
|
const { spawnSync } = require("child_process")
|
|
6
|
-
const { loadManifest, validateManifest, KNOWN_PERMISSIONS } = require("../manifest")
|
|
6
|
+
const { CTX_PERMISSIONS, loadManifest, validateManifest, KNOWN_PERMISSIONS } = require("../manifest")
|
|
7
7
|
const { bundleFrontend, bundleBackend } = require("../bundler")
|
|
8
8
|
const { declaredSecrets, loadLocalEnv, loadLocalEnvDetails } = require("../secrets")
|
|
9
9
|
const buildCommand = require("./build")
|
|
10
10
|
|
|
11
|
+
// Permissions consumed by a `ctx.*` client in a handler body rather than by a
|
|
12
|
+
// route's require_permission() dependency. The route probe cannot see those —
|
|
13
|
+
// reporting them as unused pushed authors to delete permissions their app
|
|
14
|
+
// genuinely needs, which then fails at runtime with a PermissionError.
|
|
15
|
+
function permissionsUsedByCtxClients(entryPath) {
|
|
16
|
+
const root = path.dirname(path.resolve(entryPath))
|
|
17
|
+
const sources = []
|
|
18
|
+
const walk = (dir, depth = 0) => {
|
|
19
|
+
if (depth > 6) return
|
|
20
|
+
let entries = []
|
|
21
|
+
try {
|
|
22
|
+
entries = fs.readdirSync(dir, { withFileTypes: true })
|
|
23
|
+
} catch {
|
|
24
|
+
return
|
|
25
|
+
}
|
|
26
|
+
for (const entry of entries) {
|
|
27
|
+
if (["__pycache__", ".venv", "node_modules", ".palette"].includes(entry.name)) continue
|
|
28
|
+
const abs = path.join(dir, entry.name)
|
|
29
|
+
if (entry.isDirectory()) walk(abs, depth + 1)
|
|
30
|
+
else if (entry.isFile() && entry.name.endsWith(".py")) {
|
|
31
|
+
try {
|
|
32
|
+
sources.push(fs.readFileSync(abs, "utf8"))
|
|
33
|
+
} catch {
|
|
34
|
+
/* unreadable file: fall through, the warning is advisory */
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
walk(root)
|
|
40
|
+
const blob = sources.join("\n")
|
|
41
|
+
const used = new Set()
|
|
42
|
+
for (const entry of CTX_PERMISSIONS) {
|
|
43
|
+
const accessor = entry.accessor.replace(/^ctx\./, "")
|
|
44
|
+
if (new RegExp(`\\bctx\\.${accessor}\\b`).test(blob)) {
|
|
45
|
+
for (const permission of entry.permissions) used.add(permission)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return used
|
|
49
|
+
}
|
|
50
|
+
|
|
11
51
|
const DEFAULT_FRONTEND_BUNDLE_LIMIT = 50 * 1024 * 1024
|
|
12
52
|
const DEFAULT_BACKEND_BUNDLE_LIMIT = 50 * 1024 * 1024
|
|
13
53
|
|
|
@@ -241,11 +281,13 @@ function checkBackendContract(cwd, manifest, out, pythonInfo) {
|
|
|
241
281
|
out.ok("route permissions are declared in manifest")
|
|
242
282
|
}
|
|
243
283
|
|
|
244
|
-
|
|
284
|
+
const ctxUsed = permissionsUsedByCtxClients(abs)
|
|
285
|
+
const trulyUnused = (report.unused_declared_permissions || []).filter((p) => !ctxUsed.has(p))
|
|
286
|
+
if (trulyUnused.length) {
|
|
245
287
|
out.warn(
|
|
246
|
-
`manifest declares unused backend permissions: ${
|
|
288
|
+
`manifest declares unused backend permissions: ${trulyUnused.join(", ")}`,
|
|
247
289
|
"Remove unused permissions unless the frontend uses them directly through the SDK.",
|
|
248
|
-
{ permissions:
|
|
290
|
+
{ permissions: trulyUnused },
|
|
249
291
|
)
|
|
250
292
|
}
|
|
251
293
|
const manifestCapabilities = []
|
|
@@ -936,3 +978,4 @@ async function run(args, { cwd }) {
|
|
|
936
978
|
}
|
|
937
979
|
|
|
938
980
|
module.exports = run
|
|
981
|
+
module.exports.permissionsUsedByCtxClients = permissionsUsedByCtxClients
|
package/lib/dev-simulator.js
CHANGED
|
@@ -162,6 +162,9 @@ function ensurePythonEnv(cwd, devDir, manifest) {
|
|
|
162
162
|
return venvPython
|
|
163
163
|
}
|
|
164
164
|
|
|
165
|
+
// The Python below is a JS template literal: a backtick or a bare ${ inside it
|
|
166
|
+
// terminates the string and the whole CLI stops loading. Keep docstrings
|
|
167
|
+
// backtick-free.
|
|
165
168
|
function writeBackendRunner(cwd, devDir, manifest, backendEntry, backendPort) {
|
|
166
169
|
const runner = path.join(devDir, "backend_runner.py")
|
|
167
170
|
const sdkPath = localBackendSdkPath()
|
|
@@ -218,6 +221,7 @@ DEV_VECTOR = None
|
|
|
218
221
|
DEV_STORAGE = None
|
|
219
222
|
DEV_LLM = None
|
|
220
223
|
DEV_WEB = None
|
|
224
|
+
DEV_MEDIA = None
|
|
221
225
|
if _service_enabled("llm"):
|
|
222
226
|
from palette_sdk.platform_services import LocalLLMService
|
|
223
227
|
DEV_LLM = LocalLLMService(DEV_SECRETS.get("OPENAI_API_KEY") or os.environ.get("OPENAI_API_KEY", ""))
|
|
@@ -242,6 +246,11 @@ if _service_enabled("storage"):
|
|
|
242
246
|
organization_name="Palette Dev",
|
|
243
247
|
)
|
|
244
248
|
|
|
249
|
+
if _service_enabled("media"):
|
|
250
|
+
from palette_sdk.platform_services import LocalMediaService
|
|
251
|
+
DEV_MEDIA = LocalMediaService(DEV_SECRETS.get("FAL_KEY") or os.environ.get("FAL_KEY", ""), DEV_STORAGE)
|
|
252
|
+
print(f"[pltt] ctx.media: {'live (your FAL_KEY)' if DEV_MEDIA.live else 'stubbed (no FAL_KEY)'}")
|
|
253
|
+
|
|
245
254
|
DEV_ORGANIZATION = {
|
|
246
255
|
"id": 1,
|
|
247
256
|
"name": "Palette Dev",
|
|
@@ -399,8 +408,86 @@ class LocalTalkService:
|
|
|
399
408
|
print("[palette-talk]", json.dumps(message, sort_keys=True))
|
|
400
409
|
return message
|
|
401
410
|
|
|
411
|
+
class LocalTasksService:
|
|
412
|
+
"""Local stand-in for the task board: an in-memory list that behaves like
|
|
413
|
+
the hosted one, including the app scoping (an app sees only its own rows).
|
|
414
|
+
|
|
415
|
+
Rows live for the life of the pltt dev process — enough to exercise
|
|
416
|
+
create -> list -> complete without a platform.
|
|
417
|
+
"""
|
|
418
|
+
|
|
419
|
+
def __init__(self):
|
|
420
|
+
self._rows = {}
|
|
421
|
+
self._next_id = 1
|
|
422
|
+
|
|
423
|
+
RESERVED = {"app_id", "source", "source_channel", "source_client", "external_ref", "routine_id"}
|
|
424
|
+
|
|
425
|
+
def _clean(self, fields):
|
|
426
|
+
rejected = sorted(self.RESERVED & set(fields))
|
|
427
|
+
if rejected:
|
|
428
|
+
raise HTTPException(
|
|
429
|
+
status_code=422,
|
|
430
|
+
detail="ctx.tasks sets " + ", ".join(rejected) + " itself — remove it from the call",
|
|
431
|
+
)
|
|
432
|
+
return fields
|
|
433
|
+
|
|
434
|
+
async def create(self, *, title, **fields):
|
|
435
|
+
if not str(title or "").strip():
|
|
436
|
+
raise HTTPException(status_code=422, detail="title is required")
|
|
437
|
+
now = datetime.now(timezone.utc).isoformat()
|
|
438
|
+
row = {
|
|
439
|
+
"id": self._next_id,
|
|
440
|
+
"title": str(title),
|
|
441
|
+
"description": "",
|
|
442
|
+
"output": None,
|
|
443
|
+
"status": "pending",
|
|
444
|
+
"priority": "medium",
|
|
445
|
+
"task_type": "manual",
|
|
446
|
+
"progress": 0,
|
|
447
|
+
"tags": [],
|
|
448
|
+
"due_date": None,
|
|
449
|
+
"agent_id": None,
|
|
450
|
+
"parent_task_id": None,
|
|
451
|
+
"team_id": None,
|
|
452
|
+
"app_id": MANIFEST.get("id", ""),
|
|
453
|
+
"source": "app",
|
|
454
|
+
"created_at": now,
|
|
455
|
+
"updated_at": now,
|
|
456
|
+
"completed_at": None,
|
|
457
|
+
"started_at": None,
|
|
458
|
+
}
|
|
459
|
+
row.update(self._clean(fields))
|
|
460
|
+
self._rows[self._next_id] = row
|
|
461
|
+
self._next_id += 1
|
|
462
|
+
print("[palette-tasks] created", json.dumps(row, sort_keys=True, default=str))
|
|
463
|
+
return dict(row)
|
|
464
|
+
|
|
465
|
+
async def list(self, *, status=None, limit=50):
|
|
466
|
+
rows = [r for r in self._rows.values() if status is None or r["status"] == status]
|
|
467
|
+
rows.sort(key=lambda r: r["id"], reverse=True)
|
|
468
|
+
return [dict(r) for r in rows[: max(1, int(limit))]]
|
|
469
|
+
|
|
470
|
+
async def get(self, task_id):
|
|
471
|
+
row = self._rows.get(int(task_id))
|
|
472
|
+
return dict(row) if row else None
|
|
473
|
+
|
|
474
|
+
async def update(self, task_id, **fields):
|
|
475
|
+
row = self._rows.get(int(task_id))
|
|
476
|
+
if row is None:
|
|
477
|
+
raise HTTPException(status_code=404, detail="Task not found")
|
|
478
|
+
row.update(self._clean(fields))
|
|
479
|
+
row["updated_at"] = datetime.now(timezone.utc).isoformat()
|
|
480
|
+
if row["status"] == "completed":
|
|
481
|
+
row["completed_at"] = row["completed_at"] or row["updated_at"]
|
|
482
|
+
row["progress"] = max(int(row.get("progress") or 0), 100)
|
|
483
|
+
return dict(row)
|
|
484
|
+
|
|
485
|
+
async def delete(self, task_id):
|
|
486
|
+
self._rows.pop(int(task_id), None)
|
|
487
|
+
|
|
402
488
|
NOTIFICATIONS = LocalNotificationsService()
|
|
403
489
|
TALK = LocalTalkService()
|
|
490
|
+
TASKS = LocalTasksService()
|
|
404
491
|
|
|
405
492
|
spec = importlib.util.spec_from_file_location("palette_local_backend", ENTRY)
|
|
406
493
|
module = importlib.util.module_from_spec(spec)
|
|
@@ -531,6 +618,12 @@ def _local_job_context(session):
|
|
|
531
618
|
from palette_sdk.talk import TalkClient
|
|
532
619
|
|
|
533
620
|
extra["talk"] = TalkClient(TALK, MANIFEST.get("permissions", []))
|
|
621
|
+
if "media" in getattr(PluginContext, "__dataclass_fields__", {}):
|
|
622
|
+
extra["media"] = DEV_MEDIA or UnavailablePlatformService("media")
|
|
623
|
+
if "tasks" in getattr(PluginContext, "__dataclass_fields__", {}):
|
|
624
|
+
from palette_sdk.tasks import TasksClient
|
|
625
|
+
|
|
626
|
+
extra["tasks"] = TasksClient(TASKS, MANIFEST.get("permissions", []))
|
|
534
627
|
|
|
535
628
|
return PluginContext(
|
|
536
629
|
db=session,
|
|
@@ -630,12 +723,14 @@ class DevPluginContextMiddleware(BaseHTTPMiddleware):
|
|
|
630
723
|
}
|
|
631
724
|
request.state.llm = DEV_LLM
|
|
632
725
|
request.state.web = DEV_WEB
|
|
726
|
+
request.state.media = DEV_MEDIA
|
|
633
727
|
request.state.plugin_local_connections = DEV_CONNECTIONS
|
|
634
728
|
request.state.plugin_apps = LocalAppInteropService()
|
|
635
729
|
request.state.plugin_events = LocalEventPublisher()
|
|
636
730
|
request.state.plugin_jobs = LOCAL_JOB_SERVICE
|
|
637
731
|
request.state.notifications = NOTIFICATIONS
|
|
638
732
|
request.state.talk = TALK
|
|
733
|
+
request.state.tasks = TASKS
|
|
639
734
|
request.state.storage = DEV_STORAGE
|
|
640
735
|
if DEV_REDIS is not None:
|
|
641
736
|
request.state.redis = DEV_REDIS
|
package/lib/manifest.js
CHANGED
|
@@ -45,6 +45,7 @@ const TOP_LEVEL_KEYS = new Set([
|
|
|
45
45
|
"tools",
|
|
46
46
|
"permissions",
|
|
47
47
|
"ui_extensions",
|
|
48
|
+
"data_scope",
|
|
48
49
|
"shared_tables",
|
|
49
50
|
"public_routes",
|
|
50
51
|
"rate_limit",
|
|
@@ -214,9 +215,99 @@ function validateSecrets(value, errors) {
|
|
|
214
215
|
}
|
|
215
216
|
}
|
|
216
217
|
|
|
218
|
+
// Permission-gated `ctx.*` clients. Declaring the permission in the manifest is
|
|
219
|
+
// what turns the client on; the platform re-checks it on every call.
|
|
220
|
+
const CTX_PERMISSIONS = [
|
|
221
|
+
{
|
|
222
|
+
accessor: "ctx.tasks",
|
|
223
|
+
permissions: ["tasks:read", "tasks:write"],
|
|
224
|
+
summary: "The caller's task board — create, list, update, complete. An app sees only the tasks it created",
|
|
225
|
+
python: 'task = await ctx.tasks.create("Review suppliers", priority="high")',
|
|
226
|
+
},
|
|
227
|
+
{
|
|
228
|
+
accessor: "ctx.data_rooms",
|
|
229
|
+
permissions: ["data_rooms:read", "data_rooms:write"],
|
|
230
|
+
summary: "The organisation's Drive — search and read indexed documents",
|
|
231
|
+
python: 'hits = await ctx.data_rooms.search("supplier contract")',
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
accessor: "ctx.members",
|
|
235
|
+
permissions: ["members:read", "members:write"],
|
|
236
|
+
summary: "Organisation members — list, get, invite, change role",
|
|
237
|
+
python: "people = await ctx.members.list()",
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
accessor: "ctx.talk",
|
|
241
|
+
permissions: ["chat:write"],
|
|
242
|
+
summary: "Post into Talk channels as the app's own agent (no read path)",
|
|
243
|
+
python: 'await ctx.talk.post("Digest ready", channel="general")',
|
|
244
|
+
},
|
|
245
|
+
]
|
|
246
|
+
|
|
247
|
+
// Declarable, validated, and behind nothing today. Left in the vocabulary so
|
|
248
|
+
// published manifests keep validating; `pltt doctor` says so out loud, because
|
|
249
|
+
// a reviewer reading "agents:write" on an app should not believe it can.
|
|
250
|
+
const INERT_PERMISSIONS = new Set([
|
|
251
|
+
"agents:read",
|
|
252
|
+
"agents:write",
|
|
253
|
+
"routines:read",
|
|
254
|
+
"routines:write",
|
|
255
|
+
"resources:read",
|
|
256
|
+
"resources:write",
|
|
257
|
+
])
|
|
258
|
+
|
|
259
|
+
// What the platform lends an app through `ctx.*` when it declares the service.
|
|
260
|
+
// One table: manifest validation, `pltt doctor`, and `pltt platform` all read it.
|
|
261
|
+
const PLATFORM_SERVICES = [
|
|
262
|
+
{
|
|
263
|
+
name: "llm",
|
|
264
|
+
accessor: "ctx.llm",
|
|
265
|
+
summary: "Chat with tool calls, streaming, embeddings and images on the platform's model keys; every reply names the model that ran",
|
|
266
|
+
example: 'const r = await ctx.llm.chat([{role: "user", content: "hi"}], {model: "gpt-4o-mini"})',
|
|
267
|
+
python: 'reply = await ctx.llm.chat(history, tools=TOOLS, model="claude-opus-5", fallback=False)',
|
|
268
|
+
instead_of: "OPENAI_API_KEY / ANTHROPIC_API_KEY",
|
|
269
|
+
},
|
|
270
|
+
{
|
|
271
|
+
name: "media",
|
|
272
|
+
accessor: "ctx.media",
|
|
273
|
+
summary: "fal.ai — image, video, speech, transcription, or any model fal publishes; upload() puts private files on fal's CDN",
|
|
274
|
+
example: 'const out = await ctx.media.run("fal-ai/flux/dev", {prompt: "a red bike"})',
|
|
275
|
+
python: 'out = await ctx.media.image("a red bike", image_size="square_hd")',
|
|
276
|
+
instead_of: "FAL_KEY",
|
|
277
|
+
},
|
|
278
|
+
{
|
|
279
|
+
name: "storage",
|
|
280
|
+
accessor: "ctx.storage",
|
|
281
|
+
summary: "Per-app, per-org object storage with resumable uploads",
|
|
282
|
+
python: 'meta = await ctx.storage.upload_file("report.pdf", data, "application/pdf")',
|
|
283
|
+
instead_of: "an S3/GCS bucket + credentials",
|
|
284
|
+
},
|
|
285
|
+
{
|
|
286
|
+
name: "vector",
|
|
287
|
+
accessor: "ctx.vector",
|
|
288
|
+
summary: "Namespaced vector search, partitioned to this app and org",
|
|
289
|
+
python: 'hits = await ctx.vector.search("notes", query="quarterly plan", top_k=5)',
|
|
290
|
+
instead_of: "a Pinecone/Qdrant account",
|
|
291
|
+
},
|
|
292
|
+
{
|
|
293
|
+
name: "redis",
|
|
294
|
+
accessor: "ctx.redis",
|
|
295
|
+
summary: "Key/value, lists, sets, sorted sets, counters and locks — key-prefixed per app",
|
|
296
|
+
python: 'await ctx.redis.set("last_sync", ts, ttl=3600)',
|
|
297
|
+
instead_of: "REDIS_URL",
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
name: "web",
|
|
301
|
+
accessor: "ctx.web",
|
|
302
|
+
summary: "Web search plus an SSRF-guarded page reader (HTML tables, PDFs)",
|
|
303
|
+
python: 'hits = await ctx.web.search("fx rates", limit=5)',
|
|
304
|
+
instead_of: "TAVILY_API_KEY / SERPAPI_KEY",
|
|
305
|
+
},
|
|
306
|
+
]
|
|
307
|
+
|
|
217
308
|
function validatePlatformServices(value, errors) {
|
|
218
309
|
if (value === undefined) return
|
|
219
|
-
const known = new Set(
|
|
310
|
+
const known = new Set(PLATFORM_SERVICES.map((s) => s.name))
|
|
220
311
|
if (Array.isArray(value)) {
|
|
221
312
|
for (const service of value) {
|
|
222
313
|
if (!known.has(service)) errors.push(`platform_services contains unknown service: ${service}`)
|
|
@@ -233,7 +324,29 @@ function validatePlatformServices(value, errors) {
|
|
|
233
324
|
errors.push(`platform_services.${name} must be an object`)
|
|
234
325
|
continue
|
|
235
326
|
}
|
|
236
|
-
|
|
327
|
+
const allowed = new Set(["required", "billing"])
|
|
328
|
+
if (name === "llm") {
|
|
329
|
+
// Premium models and capacity the app asks ctx.llm for — granted by the
|
|
330
|
+
// publish review, bounded again by the platform at call time.
|
|
331
|
+
for (const key of ["models", "max_output_tokens", "max_images"]) allowed.add(key)
|
|
332
|
+
const models = spec.models
|
|
333
|
+
if (
|
|
334
|
+
models !== undefined &&
|
|
335
|
+
(!Array.isArray(models) ||
|
|
336
|
+
models.length > 50 ||
|
|
337
|
+
new Set(models).size !== models.length ||
|
|
338
|
+
!models.every((m) => typeof m === "string" && m.length > 0 && m.length <= 100))
|
|
339
|
+
) {
|
|
340
|
+
errors.push("platform_services.llm.models must be up to 50 unique model ids")
|
|
341
|
+
}
|
|
342
|
+
for (const [key, ceiling] of [["max_output_tokens", 200000], ["max_images", 100]]) {
|
|
343
|
+
const value = spec[key]
|
|
344
|
+
if (value !== undefined && !(Number.isInteger(value) && value >= 0 && value <= ceiling)) {
|
|
345
|
+
errors.push(`platform_services.llm.${key} must be an integer from 0 to ${ceiling}`)
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
unknownKeys(spec, allowed, `platform_services.${name}`, errors)
|
|
237
350
|
requireBoolean(spec, "required", `platform_services.${name}`, errors)
|
|
238
351
|
requireString(spec, "billing", `platform_services.${name}`, errors)
|
|
239
352
|
if (spec.billing !== undefined && !["org_wallet", "plugin_owner", "platform"].includes(spec.billing)) {
|
|
@@ -704,6 +817,10 @@ function validateManifest(m) {
|
|
|
704
817
|
if (!m.name || typeof m.name !== "string") errors.push("name is required (string)")
|
|
705
818
|
if (!m.version || typeof m.version !== "string") errors.push("version is required (string)")
|
|
706
819
|
else if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(m.version)) errors.push("version must be semver")
|
|
820
|
+
if (!m.data_scope) errors.push("data_scope is required and must be personal or organization")
|
|
821
|
+
else if (!["personal", "organization"].includes(m.data_scope)) {
|
|
822
|
+
errors.push("data_scope must be personal or organization")
|
|
823
|
+
}
|
|
707
824
|
requireString(m, "developer", "manifest", errors)
|
|
708
825
|
requireString(m, "category", "manifest", errors)
|
|
709
826
|
requireString(m, "tagline", "manifest", errors)
|
|
@@ -900,4 +1017,7 @@ function validateManifest(m) {
|
|
|
900
1017
|
return errors
|
|
901
1018
|
}
|
|
902
1019
|
|
|
903
|
-
module.exports = {
|
|
1020
|
+
module.exports = {
|
|
1021
|
+
PLATFORM_SERVICES,
|
|
1022
|
+
CTX_PERMISSIONS,
|
|
1023
|
+
INERT_PERMISSIONS, loadManifest, validateManifest, SUPPORTED_MANIFEST_VERSIONS, KNOWN_PERMISSIONS }
|
package/package.json
CHANGED
|
@@ -8,6 +8,15 @@ pltt test --json
|
|
|
8
8
|
pltt package --json
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
+
See what the platform already gives your app before adding an API key or a
|
|
12
|
+
dependency — models, fal.ai media, web search, storage, vector and redis are all
|
|
13
|
+
available through `ctx.*` on the platform's own credentials:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pltt platform list # every service + a snippet, and its pltt dev mode
|
|
17
|
+
pltt platform enable llm # writes platform_services into palette-plugin.json
|
|
18
|
+
```
|
|
19
|
+
|
|
11
20
|
Expected preview flow:
|
|
12
21
|
|
|
13
22
|
```bash
|
|
@@ -9,7 +9,7 @@ export const translations = {
|
|
|
9
9
|
editApi: "Edit backend/api/main.py to add API endpoints",
|
|
10
10
|
usePlatform: "Use usePlatform() to access the authenticated user and API",
|
|
11
11
|
useTasks: "Use usePluginTasks() to manage tasks",
|
|
12
|
-
useDataRooms: "Use usePluginDataRooms() to browse files",
|
|
12
|
+
useDataRooms: "Use usePluginDataRooms() to browse Drive files",
|
|
13
13
|
tasks: "Tasks",
|
|
14
14
|
noTasks: "No tasks yet.",
|
|
15
15
|
createSampleTask: "Create Sample Task",
|
|
@@ -25,7 +25,7 @@ export const translations = {
|
|
|
25
25
|
editApi: "backend/api/main.py를 수정해 API 엔드포인트를 추가하세요",
|
|
26
26
|
usePlatform: "usePlatform()으로 인증 사용자와 API에 접근하세요",
|
|
27
27
|
useTasks: "usePluginTasks()로 작업을 관리하세요",
|
|
28
|
-
useDataRooms: "usePluginDataRooms()로 파일을 둘러보세요",
|
|
28
|
+
useDataRooms: "usePluginDataRooms()로 드라이브 파일을 둘러보세요",
|
|
29
29
|
tasks: "작업",
|
|
30
30
|
noTasks: "아직 작업이 없습니다.",
|
|
31
31
|
createSampleTask: "샘플 작업 만들기",
|