@palettelab/cli 0.3.63 → 0.3.65

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.
Files changed (42) hide show
  1. package/README.md +115 -8
  2. package/backend-sdk/palette_sdk/__init__.py +11 -1
  3. package/backend-sdk/palette_sdk/data_rooms.py +2 -2
  4. package/backend-sdk/palette_sdk/db/base.py +4 -1
  5. package/backend-sdk/palette_sdk/db/rls.py +7 -1
  6. package/backend-sdk/palette_sdk/manifest.py +2 -1
  7. package/backend-sdk/palette_sdk/platform_services.py +280 -2
  8. package/backend-sdk/palette_sdk/plugin_context.py +27 -2
  9. package/backend-sdk/palette_sdk/plugin_router.py +64 -8
  10. package/backend-sdk/palette_sdk/repository.py +12 -3
  11. package/backend-sdk/palette_sdk/tasks.py +117 -0
  12. package/backend-sdk/pyproject.toml +1 -1
  13. package/docs/python-backend-sdk.md +132 -8
  14. package/lib/cli.js +12 -2
  15. package/lib/commands/capabilities.js +1 -1
  16. package/lib/commands/doctor.js +15 -0
  17. package/lib/commands/platform.js +137 -0
  18. package/lib/commands/test.js +47 -4
  19. package/lib/dev-simulator.js +95 -0
  20. package/lib/manifest.js +100 -2
  21. package/package.json +1 -1
  22. package/template-fallback/README.md +9 -0
  23. package/template-fallback/frontend/src/translations.ts +2 -2
  24. package/template-fallback/package.json +1 -1
  25. package/template-fallback/palette-plugin.json +1 -0
  26. package/template-fallback/templates/agent-tool/palette-plugin.json +1 -0
  27. package/template-fallback/templates/consumer-app/package.json +1 -1
  28. package/template-fallback/templates/consumer-app/palette-plugin.json +1 -0
  29. package/template-fallback/templates/dashboard/package.json +1 -1
  30. package/template-fallback/templates/dashboard/palette-plugin.json +1 -0
  31. package/template-fallback/templates/database/package.json +1 -1
  32. package/template-fallback/templates/database/palette-plugin.json +1 -0
  33. package/template-fallback/templates/external-service/package.json +1 -1
  34. package/template-fallback/templates/external-service/palette-plugin.json +1 -0
  35. package/template-fallback/templates/frontend-only/package.json +1 -1
  36. package/template-fallback/templates/frontend-only/palette-plugin.json +1 -0
  37. package/template-fallback/templates/next/package.json +1 -1
  38. package/template-fallback/templates/next/palette-plugin.json +1 -0
  39. package/template-fallback/templates/palette-app/package.json +1 -1
  40. package/template-fallback/templates/palette-app/palette-plugin.json +1 -0
  41. package/template-fallback/templates/provider-app/package.json +1 -1
  42. package/template-fallback/templates/provider-app/palette-plugin.json +1 -0
@@ -17,6 +17,7 @@ from palette_sdk.members import OrganizationMembersClient
17
17
  from palette_sdk.notifications import NotificationsClient
18
18
  from palette_sdk.organization import OrganizationInfo
19
19
  from palette_sdk.talk import TalkClient
20
+ from palette_sdk.tasks import TasksClient
20
21
  from palette_sdk.platform_services import UnavailablePlatformService
21
22
  from palette_sdk.events import EventPublisher
22
23
  from palette_sdk.jobs import JobsClient
@@ -38,7 +39,9 @@ class PluginContext:
38
39
  caller's organization automatically. Do not add `WHERE
39
40
  organization_id = ?` — RLS already does it.
40
41
  user_id: UUID of the authenticated user
41
- organization_id: Current org ID
42
+ organization_id: Effective app data partition ID. Kept for backwards
43
+ compatibility with existing plugin repositories; use
44
+ `data_partition_id` in new code. The real org is `organization.id`.
42
45
  organization: Read-only snapshot of the current organisation's
43
46
  settings (name, slug, logo_url, company_type, description, ...).
44
47
  Refreshed on every request, so it always reflects the latest
@@ -50,6 +53,14 @@ class PluginContext:
50
53
  members: Organization member helpers for the current org
51
54
  notifications: OS notification center push helpers
52
55
  talk: Post into Talk channels as the app's own agent identity
56
+ tasks: The caller's task board, scoped to the tasks this app created.
57
+ Needs `tasks:read` / `tasks:write` in the manifest.
58
+ llm: Chat / stream / embed / image on the platform's model keys, under
59
+ the organisation's monthly spend cap. Needs platform_services: ["llm"].
60
+ web: Web search + SSRF-guarded page reader. platform_services: ["web"].
61
+ media: fal.ai — image, video, speech, transcription, or any model fal
62
+ publishes, with the payload passed through untouched. Needs
63
+ platform_services: ["media"]; no FAL_KEY of the app's own.
53
64
  """
54
65
  db: AsyncSession
55
66
  user_id: str
@@ -65,6 +76,7 @@ class PluginContext:
65
76
  members: OrganizationMembersClient = field(default_factory=OrganizationMembersClient)
66
77
  notifications: NotificationsClient = field(default_factory=NotificationsClient)
67
78
  talk: TalkClient = field(default_factory=TalkClient)
79
+ tasks: TasksClient = field(default_factory=TasksClient)
68
80
  redis: Any = field(default_factory=lambda: UnavailablePlatformService("redis"))
69
81
  vector: Any = field(default_factory=lambda: UnavailablePlatformService("vector"))
70
82
  # The platform's own model keys, under a per-org spend cap — declare
@@ -72,6 +84,9 @@ class PluginContext:
72
84
  llm: Any = field(default_factory=lambda: UnavailablePlatformService("llm"))
73
85
  # Web search + SSRF-guarded page reader — platform_services: ["web"].
74
86
  web: Any = field(default_factory=lambda: UnavailablePlatformService("web"))
87
+ # fal.ai on the platform's key — any model, any payload, no FAL_KEY of your
88
+ # own. platform_services: ["media"].
89
+ media: Any = field(default_factory=lambda: UnavailablePlatformService("media"))
75
90
  events: EventPublisher = field(default_factory=EventPublisher)
76
91
  jobs: JobsClient = field(default_factory=JobsClient)
77
92
  config: dict[str, Any] = field(default_factory=dict)
@@ -80,6 +95,11 @@ class PluginContext:
80
95
  def has_permission(self, permission: str) -> bool:
81
96
  return permission in self.permissions
82
97
 
98
+ @property
99
+ def data_partition_id(self) -> int:
100
+ """Personal tenant ID or real org ID, according to manifest.data_scope."""
101
+ return self.organization_id
102
+
83
103
  def has_any_permission(self, permissions: list[str] | tuple[str, ...] | set[str]) -> bool:
84
104
  return any(permission in self.permissions for permission in permissions)
85
105
 
@@ -132,7 +152,7 @@ async def get_plugin_context(request: Request) -> PluginContext:
132
152
  return PluginContext(
133
153
  db=state.db,
134
154
  user_id=str(state.user.id),
135
- organization_id=state.user.organization_id,
155
+ organization_id=getattr(state, "data_partition_id", state.user.organization_id),
136
156
  organization=OrganizationInfo.from_dict(getattr(state, "organization_info", None)),
137
157
  org_role=getattr(state, "org_role", None),
138
158
  plugin_id=getattr(state, "plugin_id", ""),
@@ -153,10 +173,15 @@ async def get_plugin_context(request: Request) -> PluginContext:
153
173
  getattr(state, "talk", None),
154
174
  getattr(state, "plugin_permissions", []),
155
175
  ),
176
+ tasks=TasksClient(
177
+ getattr(state, "tasks", None),
178
+ getattr(state, "plugin_permissions", []),
179
+ ),
156
180
  redis=getattr(state, "redis", None) or UnavailablePlatformService("redis"),
157
181
  vector=getattr(state, "vector", None) or UnavailablePlatformService("vector"),
158
182
  llm=getattr(state, "llm", None) or UnavailablePlatformService("llm"),
159
183
  web=getattr(state, "web", None) or UnavailablePlatformService("web"),
184
+ media=getattr(state, "media", None) or UnavailablePlatformService("media"),
160
185
  events=EventPublisher(getattr(state, "plugin_events", None)),
161
186
  jobs=JobsClient(getattr(state, "plugin_jobs", None)),
162
187
  config=getattr(state, "plugin_config", {}),
@@ -1,23 +1,74 @@
1
- """Plugin-scoped FastAPI router with automatic prefix and auth."""
1
+ """Plugin-scoped FastAPI router with automatic prefix, auth and context."""
2
2
 
3
- from fastapi import APIRouter
3
+ import inspect
4
+ from typing import Any, Callable
5
+
6
+ from fastapi import APIRouter, Depends
7
+
8
+ # Annotations a plugin might reasonably write for the context parameter. String
9
+ # forms are what `from __future__ import annotations` leaves behind, and plugin
10
+ # modules are loaded by path (never as a package), so nothing here can be
11
+ # resolved by importing the author's module.
12
+ _CONTEXT_ANNOTATIONS = {
13
+ "PluginContext",
14
+ "palette_sdk.PluginContext",
15
+ "palette_sdk.plugin_context.PluginContext",
16
+ }
17
+
18
+
19
+ def _with_context_dependency(endpoint: Callable[..., Any]) -> Callable[..., Any]:
20
+ """Give a bare `ctx: PluginContext` parameter its platform dependency.
21
+
22
+ Without it FastAPI reads the annotation as a request body/response field and
23
+ raises `Invalid args for response field!` — the most common first-run error
24
+ in a plugin backend, and one whose message names nothing the author wrote.
25
+ Parameters that already carry `Depends(...)` are left exactly as they are.
26
+ """
27
+ from palette_sdk.plugin_context import PluginContext, get_plugin_context
28
+
29
+ try:
30
+ signature = inspect.signature(endpoint)
31
+ except (TypeError, ValueError): # builtins / C callables have no signature
32
+ return endpoint
33
+ parameters = []
34
+ injected = False
35
+ for parameter in signature.parameters.values():
36
+ annotation = parameter.annotation
37
+ is_context = annotation is PluginContext or (
38
+ isinstance(annotation, str) and annotation.strip("\"' ") in _CONTEXT_ANNOTATIONS
39
+ )
40
+ if is_context and parameter.default is inspect.Parameter.empty:
41
+ parameter = parameter.replace(
42
+ default=Depends(get_plugin_context), annotation=PluginContext
43
+ )
44
+ injected = True
45
+ parameters.append(parameter)
46
+ if injected:
47
+ # FastAPI reads __signature__ when it builds the dependant, so the
48
+ # function itself keeps working unchanged for direct callers and tests.
49
+ endpoint.__signature__ = signature.replace(parameters=parameters)
50
+ return endpoint
4
51
 
5
52
 
6
53
  class PluginRouter(APIRouter):
7
54
  """A FastAPI router scoped to a plugin.
8
55
 
9
- Routes defined on this router will be automatically mounted
10
- under /api/v1/plugins/{plugin_id}/ by the platform loader.
56
+ Routes defined on this router are mounted under
57
+ `/api/v1/plugins/{plugin_id}/` by the platform loader, and a parameter
58
+ annotated `PluginContext` is wired to the platform context automatically.
11
59
 
12
60
  Usage:
13
- from palette_sdk import PluginRouter
61
+ from palette_sdk import PluginContext, PluginRouter
14
62
 
15
63
  router = PluginRouter(tags=["my-plugin"])
16
64
 
17
65
  @router.get("/stats")
18
- async def get_stats(ctx = Depends(get_plugin_context)):
19
- # This will be available at /api/v1/plugins/my-plugin/stats
20
- ...
66
+ async def get_stats(ctx: PluginContext):
67
+ # available at /api/v1/plugins/my-plugin/stats
68
+ return {"org": ctx.organization.name}
69
+
70
+ # The explicit form still works and is unchanged:
71
+ # async def get_stats(ctx = Depends(get_plugin_context)): ...
21
72
  """
22
73
 
23
74
  def __init__(self, **kwargs):
@@ -25,3 +76,8 @@ class PluginRouter(APIRouter):
25
76
  # previous code set this to None, which broke both the response
26
77
  # pipeline (TypeError at serialization) and OpenAPI generation.
27
78
  super().__init__(**kwargs)
79
+
80
+ def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) -> None:
81
+ # Every decorator (@router.get/post/...) funnels through here, so this
82
+ # is the one place the injection has to happen.
83
+ return super().add_api_route(path, _with_context_dependency(endpoint), **kwargs)
@@ -36,6 +36,15 @@ class OrgRepository(Generic[T]):
36
36
  stmt = stmt.where(org_filter)
37
37
  return stmt
38
38
 
39
+ async def _commit(self) -> None:
40
+ try:
41
+ await self.db.commit()
42
+ except Exception:
43
+ # A failed flush leaves SQLAlchemy unusable until rollback. Restore
44
+ # the injected session before plugin code handles the original error.
45
+ await self.db.rollback()
46
+ raise
47
+
39
48
  def _apply_filters(self, stmt, filters: Mapping[str, Any] | None):
40
49
  for key, value in (filters or {}).items():
41
50
  if not hasattr(self.model, key):
@@ -92,7 +101,7 @@ class OrgRepository(Generic[T]):
92
101
  values["organization_id"] = self.organization_id
93
102
  row = self.model(**values)
94
103
  self.db.add(row)
95
- await self.db.commit()
104
+ await self._commit()
96
105
  await self.db.refresh(row)
97
106
  return row
98
107
 
@@ -106,7 +115,7 @@ class OrgRepository(Generic[T]):
106
115
  if not hasattr(row, key):
107
116
  raise ValueError(f"{self.model.__name__} has no attribute {key!r}")
108
117
  setattr(row, key, value)
109
- await self.db.commit()
118
+ await self._commit()
110
119
  await self.db.refresh(row)
111
120
  return row
112
121
 
@@ -115,5 +124,5 @@ class OrgRepository(Generic[T]):
115
124
  if row is None:
116
125
  return False
117
126
  await self.db.delete(row)
118
- await self.db.commit()
127
+ await self._commit()
119
128
  return True
@@ -0,0 +1,117 @@
1
+ """Backend task-board helpers for plugin Python code.
2
+
3
+ Put work on the user's task board from an app, and read back what happened:
4
+
5
+ from palette_sdk import PluginContext, PluginRouter
6
+
7
+ router = PluginRouter()
8
+
9
+ @router.post("/queue-review")
10
+ async def queue_review(ctx: PluginContext):
11
+ task = await ctx.tasks.create(
12
+ "Review the Q3 supplier list",
13
+ description="Flag anything over £50k.",
14
+ priority="high",
15
+ tags=["procurement"],
16
+ )
17
+ return {"task_id": task["id"]}
18
+
19
+ Requires `tasks:read` / `tasks:write` in the manifest's `permissions`.
20
+
21
+ **An app sees only its own tasks.** Every task created here is stamped with the
22
+ app's id, and `list`/`get`/`update`/`delete` refuse anything another app or a
23
+ person created — declaring `tasks:read` buys an app its own rows back, not the
24
+ user's whole board. The platform's own visibility rules still apply on top of
25
+ that, so a member never sees a colleague's task through an app either.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from typing import Any
31
+
32
+
33
+ class TasksClient:
34
+ """Thin wrapper around the platform-injected task service.
35
+
36
+ In production/hosted sandbox the platform injects the service into
37
+ `PluginContext`. In local unit tests, pass a fake service exposing the same
38
+ async `create`/`list`/`get`/`update`/`delete` methods.
39
+ """
40
+
41
+ def __init__(self, service: Any = None, permissions: list[str] | None = None):
42
+ self._service = service
43
+ self._permissions = permissions or []
44
+
45
+ def _require_service(self) -> Any:
46
+ if self._service is None:
47
+ raise RuntimeError(
48
+ "Task service is not available in this runtime. "
49
+ "Run inside Palette OS/hosted sandbox or inject a fake service in tests."
50
+ )
51
+ return self._service
52
+
53
+ def _require_permission(self, permission: str) -> None:
54
+ if permission not in self._permissions:
55
+ raise PermissionError(f"App does not declare required permission: {permission}")
56
+
57
+ async def create(self, title: str, **fields: Any) -> dict[str, Any]:
58
+ """Create a task on the caller's board, owned by this app.
59
+
60
+ `title` is the only required field. Everything the board understands is
61
+ accepted as a keyword — `description`, `status`, `priority`
62
+ (`low`/`medium`/`high`/`urgent`), `progress`, `tags`, `due_date`,
63
+ `agent_id`, `parent_task_id`, `team_id` — and is validated by the
64
+ platform, so an unknown or malformed field is a 422 rather than a silent
65
+ drop. `app_id` and `source` are set by the platform and cannot be
66
+ spoofed from here.
67
+ """
68
+ self._require_permission("tasks:write")
69
+ return await self._require_service().create(title=title, **fields)
70
+
71
+ async def list(self, *, status: str | None = None, limit: int = 50) -> list[dict[str, Any]]:
72
+ """This app's tasks, newest first. `status` filters to one state
73
+ (`pending`, `in_progress`, `completed`, `failed`, `cancelled`)."""
74
+ self._require_permission("tasks:read")
75
+ return await self._require_service().list(status=status, limit=limit)
76
+
77
+ async def get(self, task_id: int) -> dict[str, Any] | None:
78
+ """One of this app's tasks, or None — a task belonging to anything else
79
+ reads as missing rather than as a permission error, so an app cannot
80
+ probe the board for ids."""
81
+ self._require_permission("tasks:read")
82
+ return await self._require_service().get(task_id)
83
+
84
+ async def update(self, task_id: int, **fields: Any) -> dict[str, Any]:
85
+ """Patch one of this app's tasks. Same field names as `create`, plus
86
+ `output` for the result text the board shows when it finishes."""
87
+ self._require_permission("tasks:write")
88
+ return await self._require_service().update(task_id, **fields)
89
+
90
+ async def complete(self, task_id: int, *, output: str | None = None) -> dict[str, Any]:
91
+ """Mark a task done at 100%, with optional result text.
92
+
93
+ Sugar for the three-field update every caller was writing by hand, and
94
+ it keeps `progress` honest — a "completed" task still sitting at 40% is
95
+ what makes a board stop being trusted.
96
+ """
97
+ self._require_permission("tasks:write")
98
+ fields: dict[str, Any] = {"status": "completed", "progress": 100}
99
+ if output is not None:
100
+ fields["output"] = output
101
+ return await self._require_service().update(task_id, **fields)
102
+
103
+ async def fail(self, task_id: int, *, output: str | None = None) -> dict[str, Any]:
104
+ """Mark a task failed, with optional reason text."""
105
+ self._require_permission("tasks:write")
106
+ fields: dict[str, Any] = {"status": "failed"}
107
+ if output is not None:
108
+ fields["output"] = output
109
+ return await self._require_service().update(task_id, **fields)
110
+
111
+ async def delete(self, task_id: int) -> None:
112
+ """Remove one of this app's tasks."""
113
+ self._require_permission("tasks:write")
114
+ await self._require_service().delete(task_id)
115
+
116
+
117
+ __all__ = ["TasksClient"]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "palette-sdk"
3
- version = "0.1.13"
3
+ version = "0.1.15"
4
4
  description = "Palette Platform SDK for building backend plugins"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -69,14 +69,13 @@ Every backend file exports a `PluginRouter`. Routes are mounted by the platform
69
69
  under `/api/v1/plugins/<plugin-id>`.
70
70
 
71
71
  ```python
72
- from fastapi import Depends
73
- from palette_sdk import PluginRouter, PluginContext, get_plugin_context
72
+ from palette_sdk import PluginRouter, PluginContext
74
73
 
75
74
  router = PluginRouter(tags=["finance-tools"])
76
75
 
77
76
 
78
77
  @router.get("/me")
79
- async def me(ctx: PluginContext = Depends(get_plugin_context)):
78
+ async def me(ctx: PluginContext):
80
79
  return {
81
80
  "user_id": ctx.user_id,
82
81
  "organization_id": ctx.organization_id,
@@ -85,6 +84,19 @@ async def me(ctx: PluginContext = Depends(get_plugin_context)):
85
84
  }
86
85
  ```
87
86
 
87
+ A parameter annotated `PluginContext` is wired to the platform context
88
+ automatically. The explicit form is identical and still supported — the rest of
89
+ this document uses it:
90
+
91
+ ```python
92
+ from fastapi import Depends
93
+ from palette_sdk import get_plugin_context
94
+
95
+ @router.get("/me")
96
+ async def me(ctx: PluginContext = Depends(get_plugin_context)):
97
+ ...
98
+ ```
99
+
88
100
  If the app id is `finance-tools`, this route is available at:
89
101
 
90
102
  ```text
@@ -106,7 +118,9 @@ Available context values:
106
118
  |---|---|
107
119
  | `ctx.db` | Async SQLAlchemy session for the app backend |
108
120
  | `ctx.user_id` | Authenticated Palette user id |
109
- | `ctx.organization_id` | Current organization id |
121
+ | `ctx.organization_id` | The app's data partition id — member tenant for `data_scope: personal`, the real org id for `organization` |
122
+ | `ctx.data_partition_id` | The same value, under the name that says what it is; prefer it in new code |
123
+ | `ctx.organization` | Read-only snapshot of the real organisation (`id`, `name`, `slug`, `logo_url`, `company_type`, `description`), refreshed every request |
110
124
  | `ctx.org_role` | User role in the current organization |
111
125
  | `ctx.plugin_id` | Current app/plugin id |
112
126
  | `ctx.permissions` | Permissions granted from `palette-plugin.json` |
@@ -116,6 +130,7 @@ Available context values:
116
130
  | `ctx.members` | Current organisation member client |
117
131
  | `ctx.notifications` | Push OS notification-center notifications |
118
132
  | `ctx.talk` | Post into Talk channels as the app's own agent (`chat:write`, seat required) |
133
+ | `ctx.tasks` | The caller's task board, scoped to this app's own tasks (`tasks:read` / `tasks:write`) |
119
134
  | `ctx.apps` / `services(ctx)` | Governed app-to-app calls through declared `consumes` contracts |
120
135
  | `ctx.events` | Publish event topics declared in `provides.events` |
121
136
  | `ctx.jobs` | Enqueue, inspect, and cancel durable background jobs |
@@ -123,6 +138,7 @@ Available context values:
123
138
  | `ctx.vector` | Plugin/org-scoped vector service when `platform_services` includes `vector` |
124
139
  | `ctx.llm` | The platform's own model keys under an org spend cap when `platform_services` includes `llm` |
125
140
  | `ctx.web` | Web search + SSRF-guarded page reader when `platform_services` includes `web` |
141
+ | `ctx.media` | fal.ai on the platform's key — any model, any payload — when `platform_services` includes `media` |
126
142
  | `ctx.config` | App install/config values |
127
143
  | `ctx.logger` | Runtime logger for backend code |
128
144
  | `ctx.repo(Model)` | Org-safe CRUD helper for app-owned tables |
@@ -148,7 +164,8 @@ These are the public Python helpers exported by `palette_sdk`.
148
164
  | `OrganizationMembersClient`, `ctx.members` | Current-organization member lookup, invite, and role helpers |
149
165
  | `NotificationsClient`, `ctx.notifications` | Push notifications into the OS notification center |
150
166
  | `TalkClient`, `ctx.talk` | Post into Talk channels the app's agent is seated in |
151
- | `PluginConnectionsClient`, `ConnectionStatus`, `MissingConnectionError`, `ctx.connections` | Third-party connection status and token helpers |
167
+ | `TasksClient`, `ctx.tasks` | The caller's task board, scoped to the tasks this app created |
168
+ | `PluginConnectionsClient`, `ConnectionStatus`, `MissingConnectionError`, `ctx.connections` | Third-party connection status and tool calls (there is no token accessor — the platform holds the credential) |
152
169
  | `AppInteropClient`, `AppServiceClient`, `MissingAppServiceError`, `ctx.apps` | Call required apps/services without direct database access |
153
170
  | `service(...)`, `services(ctx)`, `ServicesClient`, `BrokerCallError` | Provide and consume OS-broker service methods/events |
154
171
  | `OrgRepository`, `ctx.repo(Model)` | Org-safe convenience CRUD for app-owned models |
@@ -156,7 +173,10 @@ These are the public Python helpers exported by `palette_sdk`.
156
173
  | `ensure_org_rls(op, table)` | Alembic helper that enables org row-level security |
157
174
  | `plugin_safe_id(...)`, `plugin_schema(...)`, `plugin_table_prefix(...)` | Manifest id to database-safe naming helpers |
158
175
  | `get_config(ctx, key)`, `require_config(ctx, key)` | Functional form of config reads when not using `ctx.config_value(...)` |
159
- | `LocalRedisService`, `LocalVectorService`, `LocalStorageService` | Local `pltt dev` service emulators and test fakes |
176
+ | `ctx.llm`, `ctx.media`, `ctx.web` | The platform's model, fal.ai and web-search keys, declared in `platform_services` |
177
+ | `MediaStillRunning` | `ctx.media.run` gave up waiting; carries `request_id` to collect the render later |
178
+ | `LocalLLMService`, `LocalMediaService`, `LocalWebService`, `LocalRedisService`, `LocalVectorService`, `LocalStorageService` | Local `pltt dev` service emulators and test fakes |
179
+ | `McpClient`, `mcp_tool(...)`, `mcp_resource(...)`, `mcp_prompt(...)` | Provide and consume MCP tools, resources and prompts |
160
180
  | `PlatformServiceUnavailable`, `UnavailablePlatformService` | Clear errors when an undeclared platform service is used |
161
181
  | `LifecycleHooks` | Install/update/enable/disable/uninstall callbacks |
162
182
  | `Event`, `EventPublisher`, `subscribe_event(...)` | In-process event subscriptions and declared app event publishing |
@@ -824,6 +844,55 @@ Available in request handlers, `@capability` methods, and background jobs.
824
844
  During `pltt dev` nothing reaches a real channel: the simulator reports one
825
845
  fake seat, logs each post as `[palette-talk] {...}`, and returns a stub message.
826
846
 
847
+ ## 8c. The Task Board From Python
848
+
849
+ `ctx.tasks` puts work on the caller's board and reads it back. Declare
850
+ `tasks:read` / `tasks:write` in `permissions`:
851
+
852
+ ```python
853
+ @router.post("/queue-review", dependencies=[require_permission("tasks:write")])
854
+ async def queue_review(ctx: PluginContext = Depends(get_plugin_context)):
855
+ task = await ctx.tasks.create(
856
+ "Review the Q3 supplier list",
857
+ description="Flag anything over 50k.",
858
+ priority="high",
859
+ tags=["procurement"],
860
+ due_date="2026-10-01T09:00:00Z",
861
+ )
862
+ return {"task_id": task["id"]}
863
+
864
+
865
+ @router.post("/finish/{task_id}", dependencies=[require_permission("tasks:write")])
866
+ async def finish(task_id: int, ctx: PluginContext = Depends(get_plugin_context)):
867
+ # complete() also sets progress to 100 — a "completed" task still at 40% is
868
+ # what makes a board stop being trusted.
869
+ return await ctx.tasks.complete(task_id, output="12 suppliers checked, 2 flagged.")
870
+ ```
871
+
872
+ | Helper | Notes |
873
+ |---|---|
874
+ | `ctx.tasks.create(title, **fields)` | `description`, `status`, `priority`, `progress`, `tags`, `due_date`, `agent_id`, `parent_task_id`, `team_id` |
875
+ | `ctx.tasks.list(status=None, limit=50)` | Newest first, capped at 200 |
876
+ | `ctx.tasks.get(task_id)` | `None` when it is not this app's task |
877
+ | `ctx.tasks.update(task_id, **fields)` | Same fields as `create`, plus `output` |
878
+ | `ctx.tasks.complete(task_id, output=None)` | Sets `status="completed"` and `progress=100` |
879
+ | `ctx.tasks.fail(task_id, output=None)` | Sets `status="failed"` |
880
+ | `ctx.tasks.delete(task_id)` | Removes one of this app's tasks |
881
+
882
+ **An app sees only its own tasks.** Every row is stamped with the app's id on
883
+ create, and every other path re-checks that stamp. A task belonging to another
884
+ app or to a person reads as *missing*, not as a permission error, so an app
885
+ cannot probe the board for ids. Declaring `tasks:read` buys an app its own rows
886
+ back, not the user's whole board, and the platform's own visibility rules still
887
+ run underneath (a member sees their own tasks, an org admin the organisation's).
888
+
889
+ Provenance fields — `app_id`, `source`, `source_channel`, `source_client`,
890
+ `external_ref`, `routine_id` — are refused with a 422 rather than silently
891
+ overwritten, so a caller cannot forge where a task came from.
892
+
893
+ During `pltt dev` the board is an in-memory list for the life of the process,
894
+ and each create is logged as `[palette-tasks] created {...}`.
895
+
827
896
  ## 9. Config And Secrets
828
897
 
829
898
  Use config for app install settings and secrets for sensitive values.
@@ -870,14 +939,20 @@ during `pltt dev`. During hosted preview/publish, server-only `.env` keys are
870
939
  uploaded automatically as encrypted plugin secrets. Undeclared keys still fall
871
940
  back to the process environment for local compatibility.
872
941
 
873
- Managed Redis, vector, and storage services are declared in the manifest:
942
+ Managed services are declared in the manifest — `pltt platform list` prints the
943
+ whole set with a snippet for each, and `pltt platform enable <name>` writes the
944
+ declaration for you:
874
945
 
875
946
  ```json
876
947
  {
877
- "platform_services": ["redis", "vector", "storage"]
948
+ "platform_services": ["llm", "media", "redis", "storage", "vector", "web"]
878
949
  }
879
950
  ```
880
951
 
952
+ Declaring a service is what replaces shipping a key: the platform's own
953
+ credential is used, metered per organisation, and the app ships no `.env` of its
954
+ own for it.
955
+
881
956
  ```python
882
957
  # Third-party services — the user connects once in Palette Connect, grants your
883
958
  # app the tools your manifest declares, and the platform proxies every call.
@@ -902,6 +977,43 @@ async for chunk in ctx.llm.stream([{"role": "user", "content": "Write a haiku"}]
902
977
  vectors = await ctx.llm.embed(["some text"])
903
978
  image_bytes, mime = await ctx.llm.image("a fox in the snow")
904
979
 
980
+ # Anything else is passed straight to the provider — the platform only pins the
981
+ # model, the budget and the token cap.
982
+ strict = await ctx.llm.chat(messages, response_format={"type": "json_object"}, top_p=0.1)
983
+ available = await ctx.llm.models() # what `model=` will honour ([] under SECURE)
984
+ wallet = await ctx.llm.spend() # {"spent_usd", "cap_usd", "remaining_usd"}
985
+
986
+ # fal.ai on the platform's key — no FAL_KEY secret to ship or rotate.
987
+ # `run` reaches ANY fal model and the payload is passed through untouched, so a
988
+ # model fal published this morning works with no SDK release.
989
+ out = await ctx.media.run("fal-ai/flux/dev", {"prompt": "a red bike", "num_images": 2})
990
+ out["images"][0]["url"]
991
+
992
+ # The same call with a default model filled in. Every keyword is forwarded to
993
+ # the model, so use whatever fields its own docs list.
994
+ poster = await ctx.media.image("a red bike", image_size="square_hd", seed=7)
995
+ clip = await ctx.media.video("a drone shot over dunes", duration="8", aspect_ratio="16:9")
996
+ speech = await ctx.media.speech("Good morning", voice="rachel")
997
+ words = await ctx.media.transcribe(audio_url, language="en")
998
+
999
+ # fal output URLs EXPIRE — save anything the app shows later (needs "storage" too).
1000
+ saved = await ctx.media.save(poster["images"][0]["url"], filename="poster.png")
1001
+ saved["file_url"]
1002
+
1003
+ # Local bytes a model needs as an input URL (image_url, audio_url, ...).
1004
+ url = await ctx.media.upload(png_bytes, filename="input.png", content_type="image/png")
1005
+
1006
+ # Renders take minutes. Don't hold an HTTP request open — hand the job to ctx.jobs.
1007
+ from palette_sdk import MediaStillRunning
1008
+ try:
1009
+ result = await ctx.media.run(model, payload, timeout=20)
1010
+ except MediaStillRunning as pending:
1011
+ result = await ctx.media.result(pending.request_id, model=pending.model)
1012
+
1013
+ # Or submit and collect explicitly.
1014
+ job = await ctx.media.submit("fal-ai/kling-video/v3/pro/text-to-video", {"prompt": "…"})
1015
+ state = await ctx.media.status(job["request_id"], model=job["model"])
1016
+
905
1017
  # Web search + reader (HTML tables and PDFs already handled).
906
1018
  hits = await ctx.web.search("palette os changelog", limit=5)
907
1019
  text = await ctx.web.fetch("https://example.com/report.pdf")
@@ -920,6 +1032,18 @@ Palette scopes every Redis key and vector operation by `plugin_id` and
920
1032
  `organization_id`; hosted previews also include the publish id. Plugin code
921
1033
  cannot read, list, update, or delete records owned by another app or org.
922
1034
 
1035
+ `ctx.llm` and `ctx.media` draw on **one** monthly wallet per (app, organisation)
1036
+ — separate ledgers would just let an app route around the cap it had already
1037
+ exhausted. Both fail closed: past the cap the call raises
1038
+ `PlatformServiceUnavailable` rather than spending. Call `ctx.llm.spend()` (or
1039
+ `ctx.media.spend()` — the same wallet) to show the user why, instead of
1040
+ surfacing a bare 503.
1041
+
1042
+ Under `pltt dev` there is no platform, so these run against your own
1043
+ `OPENAI_API_KEY` / `FAL_KEY` when your `.env.local` has them and return
1044
+ deterministic stubs when it does not — the app's code path is exercisable with
1045
+ zero setup either way. `pltt doctor` prints which mode each service is in.
1046
+
923
1047
  ## 10. Managed Connections
924
1048
 
925
1049
  Declare third-party OAuth or API-key connections in `palette-plugin.json`.
package/lib/cli.js CHANGED
@@ -17,6 +17,7 @@ const version = require("./commands/version")
17
17
  const update = require("./commands/update")
18
18
  const capabilities = require("./commands/capabilities")
19
19
  const connections = require("./commands/connections")
20
+ const platform = require("./commands/platform")
20
21
 
21
22
  const COMMANDS = {
22
23
  init: { run: init, help: "Scaffold a new plugin directory from the template" },
@@ -64,6 +65,10 @@ const COMMANDS = {
64
65
  run: connections,
65
66
  help: "Use the OS service connections (list, add, pull, mock) — no OAuth of your own",
66
67
  },
68
+ platform: {
69
+ run: platform,
70
+ help: "List / enable the platform services an app borrows through ctx.* (no keys of your own)",
71
+ },
67
72
  services: {
68
73
  run: services,
69
74
  help: "Inspect / pull / scaffold OS-broker services (list, pull, scaffold)",
@@ -85,10 +90,10 @@ function printHelp() {
85
90
  console.log("Usage: pltt <command> [options]\n")
86
91
  console.log("Commands:")
87
92
  for (const [name, { help }] of Object.entries(COMMANDS)) {
88
- console.log(` ${name.padEnd(8)} ${help}`)
93
+ console.log(` ${name.padEnd(12)} ${help}`)
89
94
  }
90
95
  console.log("\nGlobal flags:")
91
- console.log(" --json Emit machine-readable JSON output (status, logs, package, publish, test, update, version)")
96
+ console.log(" --json Emit machine-readable JSON output (status, logs, package, publish, test, update, version, login, dev --sandbox, platform, services, capabilities)")
92
97
  console.log(" -v, --version Show the installed pltt CLI version")
93
98
  console.log("\nPublish flags:")
94
99
  console.log(" --env <name> Target environment from ~/.palette/config.json (default: local)")
@@ -107,6 +112,10 @@ function printHelp() {
107
112
  console.log("\nLogs flags:")
108
113
  console.log(" --tail <n> Tail last n events (default 50)")
109
114
  console.log(" -f, --follow Stream events (poll every 3s)")
115
+ console.log("\nPlatform services (ctx.* — the platform's own credentials):")
116
+ console.log(" pltt platform list # llm, media, storage, vector, redis, web")
117
+ console.log(" pltt platform enable llm media # declare them in palette-plugin.json")
118
+ console.log(" pltt platform disable web")
110
119
  console.log("\nServices (OS broker):")
111
120
  console.log(" pltt services list # show provided services/events in the org")
112
121
  console.log(" pltt services add TARGET # add a consumed service/event target")
@@ -133,6 +142,7 @@ function printHelp() {
133
142
  console.log(" pltt publish --env staging")
134
143
  console.log(" pltt status")
135
144
  console.log(" pltt update")
145
+ console.log(" pltt platform enable media")
136
146
  console.log(" pltt logs --follow")
137
147
  console.log(" pltt secrets init")
138
148
  }
@@ -118,7 +118,7 @@ async function run(args, { cwd }) {
118
118
  if (args.includes(flag)) forwarded.push(flag)
119
119
  }
120
120
  await servicesCommand.runScaffold(forwarded, { cwd })
121
- console.log("[pltt] agent capability ready; implement the generated handler, then run `pltt test --agent`")
121
+ console.log("[pltt] agent capability ready; implement the generated handler, then run `pltt test`")
122
122
  return
123
123
  }
124
124
  const capabilities = collect(manifest)