@palettelab/cli 0.3.61 → 0.3.63

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 (39) hide show
  1. package/README.md +80 -5
  2. package/backend-sdk/palette_sdk/__init__.py +21 -1
  3. package/backend-sdk/palette_sdk/capabilities.py +126 -0
  4. package/backend-sdk/palette_sdk/connections.py +49 -11
  5. package/backend-sdk/palette_sdk/connections_generated.py +246 -0
  6. package/backend-sdk/palette_sdk/manifest.py +78 -3
  7. package/backend-sdk/palette_sdk/platform_services.py +122 -0
  8. package/backend-sdk/palette_sdk/plugin_context.py +14 -0
  9. package/backend-sdk/palette_sdk/services.py +45 -6
  10. package/backend-sdk/palette_sdk/talk.py +65 -0
  11. package/backend-sdk/pyproject.toml +1 -1
  12. package/docs/python-backend-sdk.md +64 -1
  13. package/lib/bundler.js +64 -0
  14. package/lib/cli.js +27 -2
  15. package/lib/commands/capabilities.js +151 -0
  16. package/lib/commands/connections.js +234 -0
  17. package/lib/commands/dev.js +75 -1
  18. package/lib/commands/doctor.js +70 -0
  19. package/lib/commands/init.js +3 -2
  20. package/lib/commands/open.js +43 -0
  21. package/lib/commands/services.js +74 -8
  22. package/lib/commands/test.js +89 -1
  23. package/lib/connection-catalog.json +1185 -0
  24. package/lib/dev-simulator.js +137 -3
  25. package/lib/manifest.js +90 -6
  26. package/package.json +1 -1
  27. package/template-fallback/package.json +1 -1
  28. package/template-fallback/templates/agent-tool/README.md +6 -2
  29. package/template-fallback/templates/agent-tool/backend/api/main.py +27 -6
  30. package/template-fallback/templates/agent-tool/palette-plugin.json +35 -4
  31. package/template-fallback/templates/consumer-app/package.json +1 -1
  32. package/template-fallback/templates/dashboard/package.json +1 -1
  33. package/template-fallback/templates/database/package.json +1 -1
  34. package/template-fallback/templates/external-service/package.json +1 -1
  35. package/template-fallback/templates/frontend-only/package.json +1 -1
  36. package/template-fallback/templates/next/package.json +1 -1
  37. package/template-fallback/templates/palette-app/package.json +1 -1
  38. package/template-fallback/templates/provider-app/package.json +1 -1
  39. package/template-fallback/templates/agent-tool/backend/tools/echo.py +0 -15
@@ -3,10 +3,11 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
+ import re
6
7
  from pathlib import Path
7
8
  from typing import Any, Literal
8
9
 
9
- from pydantic import AliasChoices, BaseModel, ConfigDict, Field
10
+ from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator
10
11
 
11
12
 
12
13
  class AgentDefinition(BaseModel):
@@ -84,12 +85,25 @@ class SecretSpec(BaseModel):
84
85
 
85
86
 
86
87
  class ConnectionSpec(BaseModel):
88
+ """A third-party service this app reaches through the user's OS connection.
89
+
90
+ `google`/`slack`/`notion`/`telegram`/`meta` are live: the user connects once
91
+ in Connect and the app calls `ctx.connections.<tool>` with no OAuth of its
92
+ own. The remaining slugs are legacy and validate but dispatch nothing.
93
+ """
94
+
87
95
  id: str
88
- provider: Literal["google", "instagram", "slack", "linear", "hubspot", "stripe", "zendesk", "custom"]
96
+ provider: Literal[
97
+ "google", "slack", "notion", "telegram", "meta",
98
+ "instagram", "linear", "hubspot", "stripe", "zendesk", "custom",
99
+ ]
89
100
  label: str
90
101
  auth: Literal["oauth2", "api_key"] = "oauth2"
91
102
  scopes: list[str] = Field(default_factory=list)
92
103
  required: bool = False
104
+ # Tool names the app may call, e.g. ["gmail.search", "gmail.send"]. Empty
105
+ # grants every read-only tool the provider offers.
106
+ tools: list[str] = Field(default_factory=list)
93
107
 
94
108
 
95
109
  class AppServiceRouteSpec(BaseModel):
@@ -113,8 +127,38 @@ class AppServiceMethodSpec(BaseModel):
113
127
  output: dict[str, Any] | str | None = None
114
128
  route_method: Literal["GET", "POST", "PUT", "PATCH", "DELETE"] | None = None
115
129
  route_path: str | None = None
130
+ annotations: dict[str, Any] | None = None
131
+ capability_id: str | None = None
132
+ supports_scheduling: bool = True
133
+ agent_exposable: bool = False
116
134
  deprecated: bool = False
117
135
  replacement: str | None = None
136
+ effects: list[str] = Field(default_factory=list)
137
+ risk: Literal["read", "write", "destructive", "controlled"] = "read"
138
+ idempotent: bool = False
139
+ timeout_seconds: int = Field(default=60, ge=1, le=7200)
140
+ tags: list[str] = Field(default_factory=list)
141
+ artifact_inputs: list[str] = Field(default_factory=list)
142
+ artifact_outputs: list[str] = Field(default_factory=list)
143
+ examples: list[dict[str, Any]] = Field(default_factory=list)
144
+ cost_class: Literal["low", "medium", "high"] | None = None
145
+ latency_class: Literal["interactive", "background", "long_running"] | None = None
146
+
147
+ @model_validator(mode="after")
148
+ def validate_agent_contract(self):
149
+ if not self.agent_exposable:
150
+ return self
151
+ if not self.capability_id or not re.match(
152
+ r"^[a-z][a-z0-9_-]*(?:\.[a-z0-9_-]+)+$", self.capability_id
153
+ ):
154
+ raise ValueError("agent-exposable methods require a stable dotted capability_id")
155
+ if not self.description.strip() or self.input_schema is None and self.input is None:
156
+ raise ValueError("agent-exposable methods require description and input_schema")
157
+ if not self.effects:
158
+ raise ValueError("agent-exposable methods require at least one declared effect")
159
+ if self.risk in {"write", "destructive"} and self.supports_scheduling and not self.idempotent:
160
+ raise ValueError("scheduled write capabilities must be idempotent")
161
+ return self
118
162
 
119
163
 
120
164
  class ProvidedAppServiceSpec(BaseModel):
@@ -197,6 +241,37 @@ class McpToolSpec(BaseModel):
197
241
  annotations: dict[str, Any] | None = None # readOnlyHint / destructiveHint ...
198
242
  scope: str | None = None
199
243
  expose_external: bool = False
244
+ agent_exposable: bool = False
245
+ capability_id: str | None = None
246
+ supports_scheduling: bool = True
247
+ effects: list[str] = Field(default_factory=list)
248
+ risk: Literal["read", "write", "destructive", "controlled"] = "read"
249
+ idempotent: bool = False
250
+ timeout_seconds: int = Field(default=60, ge=1, le=7200)
251
+ tags: list[str] = Field(default_factory=list)
252
+ artifact_inputs: list[str] = Field(default_factory=list)
253
+ artifact_outputs: list[str] = Field(default_factory=list)
254
+ examples: list[dict[str, Any]] = Field(default_factory=list)
255
+ cost_class: Literal["low", "medium", "high"] | None = None
256
+ latency_class: Literal["interactive", "background", "long_running"] | None = None
257
+ deprecated: bool = False
258
+ replacement: str | None = None
259
+
260
+ @model_validator(mode="after")
261
+ def validate_agent_contract(self):
262
+ if not self.agent_exposable:
263
+ return self
264
+ if not self.capability_id or not re.match(
265
+ r"^[a-z][a-z0-9_-]*(?:\.[a-z0-9_-]+)+$", self.capability_id
266
+ ):
267
+ raise ValueError("agent-exposable tools require a stable dotted capability_id")
268
+ if not self.description.strip() or self.input_schema is None:
269
+ raise ValueError("agent-exposable tools require description and input_schema")
270
+ if not self.effects:
271
+ raise ValueError("agent-exposable tools require at least one declared effect")
272
+ if self.risk in {"write", "destructive"} and self.supports_scheduling and not self.idempotent:
273
+ raise ValueError("scheduled write capabilities must be idempotent")
274
+ return self
200
275
 
201
276
 
202
277
  class McpResourceSpec(BaseModel):
@@ -269,7 +344,7 @@ class PluginManifest(BaseModel):
269
344
  requires: RequiresSpec | None = None
270
345
  consumes: ConsumesSpec | None = None
271
346
  mcp: McpSpec | None = None
272
- platform_services: list[Literal["llm", "redis", "storage", "vector"]] | dict[str, PlatformServiceSpec] = Field(default_factory=list)
347
+ platform_services: list[Literal["llm", "redis", "storage", "vector", "web"]] | dict[str, PlatformServiceSpec] = Field(default_factory=list)
273
348
  rating: float = 0.0
274
349
  reviews: int = 0
275
350
  featured: bool = False
@@ -375,3 +375,125 @@ class LocalVectorService:
375
375
  if index:
376
376
  return {"index": index, "count": len(self._items.get(index, {}))}
377
377
  return {"indexes": {name: len(items) for name, items in self._items.items()}}
378
+
379
+
380
+ class LocalLLMService:
381
+ """`ctx.llm` for pltt dev.
382
+
383
+ Hosted, this is the platform's key under an org spend cap. Locally there is
384
+ no platform, so it uses the developer's own `OPENAI_API_KEY` when the dev
385
+ env supplies one and falls back to a deterministic stub otherwise — the app's
386
+ code path stays exercisable with zero setup.
387
+ """
388
+
389
+ def __init__(self, api_key: str | None = None, model: str = "gpt-5.4-mini"):
390
+ self.api_key = api_key or ""
391
+ self.model = model
392
+
393
+ @property
394
+ def live(self) -> bool:
395
+ return bool(self.api_key)
396
+
397
+ @staticmethod
398
+ def _last_user(messages: list[dict[str, Any]]) -> str:
399
+ for message in reversed(messages or []):
400
+ if str(message.get("role") or "user") == "user":
401
+ return str(message.get("content") or "")
402
+ return ""
403
+
404
+ def _stub(self, messages: list[dict[str, Any]]) -> dict[str, Any]:
405
+ return {
406
+ "text": f"[pltt dev: no LLM key] {self._last_user(messages)}",
407
+ "model": "pltt-dev-stub",
408
+ "input_tokens": 0,
409
+ "output_tokens": 0,
410
+ "cost_usd": 0.0,
411
+ }
412
+
413
+ async def chat(
414
+ self,
415
+ messages: list[dict[str, Any]],
416
+ *,
417
+ model: str | None = None,
418
+ system: str | None = None,
419
+ max_tokens: int = 1024,
420
+ temperature: float = 0.2,
421
+ ) -> dict[str, Any]:
422
+ if not self.live:
423
+ return self._stub(messages)
424
+ from openai import AsyncOpenAI
425
+
426
+ payload = ([{"role": "system", "content": system}] if system else []) + list(messages)
427
+ reply = await AsyncOpenAI(api_key=self.api_key).chat.completions.create(
428
+ model=model or self.model, messages=payload, max_completion_tokens=max_tokens
429
+ )
430
+ usage = reply.usage
431
+ return {
432
+ "text": reply.choices[0].message.content or "",
433
+ "model": reply.model,
434
+ "input_tokens": getattr(usage, "prompt_tokens", 0),
435
+ "output_tokens": getattr(usage, "completion_tokens", 0),
436
+ "cost_usd": None,
437
+ }
438
+
439
+ async def stream(self, messages: list[dict[str, Any]], **kwargs):
440
+ if not self.live:
441
+ yield self._stub(messages)["text"]
442
+ return
443
+ from openai import AsyncOpenAI
444
+
445
+ system = kwargs.get("system")
446
+ payload = ([{"role": "system", "content": system}] if system else []) + list(messages)
447
+ stream = await AsyncOpenAI(api_key=self.api_key).chat.completions.create(
448
+ model=kwargs.get("model") or self.model,
449
+ messages=payload,
450
+ max_completion_tokens=kwargs.get("max_tokens", 1024),
451
+ stream=True,
452
+ )
453
+ async for chunk in stream:
454
+ delta = chunk.choices[0].delta if chunk.choices else None
455
+ if delta and delta.content:
456
+ yield delta.content
457
+
458
+ async def embed(self, texts: list[str]) -> list[list[float]]:
459
+ if not self.live:
460
+ # Same deterministic hash embedding LocalVectorService uses, so
461
+ # similarity search behaves consistently offline.
462
+ return [_text_vector(text) for text in texts]
463
+ from openai import AsyncOpenAI
464
+
465
+ reply = await AsyncOpenAI(api_key=self.api_key).embeddings.create(
466
+ model="text-embedding-3-small", input=list(texts)
467
+ )
468
+ return [item.embedding for item in reply.data]
469
+
470
+ async def image(self, prompt: str, *, aspect_ratio: str = "1:1") -> tuple[bytes, str]:
471
+ raise NotImplementedError("ctx.llm.image runs on the platform only — use pltt dev --sandbox")
472
+
473
+
474
+ class LocalWebService:
475
+ """`ctx.web` for pltt dev — keyless DuckDuckGo search plus a plain fetch."""
476
+
477
+ async def search(self, query: str, *, limit: int = 5, topic: str | None = None) -> dict[str, Any]:
478
+ try:
479
+ from ddgs import DDGS
480
+ except ImportError:
481
+ return {"results": [], "error": "pip install ddgs to use ctx.web.search in pltt dev"}
482
+ import asyncio
483
+
484
+ def _run() -> list[dict[str, Any]]:
485
+ with DDGS() as ddgs:
486
+ return [
487
+ {"title": r.get("title", ""), "url": r.get("href", ""), "content": r.get("body", "")}
488
+ for r in ddgs.text(query, max_results=limit)
489
+ ]
490
+
491
+ return {"results": await asyncio.to_thread(_run)}
492
+
493
+ async def fetch(self, url: str) -> str:
494
+ import httpx
495
+
496
+ async with httpx.AsyncClient(timeout=20, follow_redirects=True) as client:
497
+ response = await client.get(url)
498
+ response.raise_for_status()
499
+ return response.text
@@ -16,6 +16,7 @@ from palette_sdk.apps import AppInteropClient
16
16
  from palette_sdk.members import OrganizationMembersClient
17
17
  from palette_sdk.notifications import NotificationsClient
18
18
  from palette_sdk.organization import OrganizationInfo
19
+ from palette_sdk.talk import TalkClient
19
20
  from palette_sdk.platform_services import UnavailablePlatformService
20
21
  from palette_sdk.events import EventPublisher
21
22
  from palette_sdk.jobs import JobsClient
@@ -48,6 +49,7 @@ class PluginContext:
48
49
  storage: Storage service for file upload/download
49
50
  members: Organization member helpers for the current org
50
51
  notifications: OS notification center push helpers
52
+ talk: Post into Talk channels as the app's own agent identity
51
53
  """
52
54
  db: AsyncSession
53
55
  user_id: str
@@ -62,8 +64,14 @@ class PluginContext:
62
64
  apps: AppInteropClient = field(default_factory=AppInteropClient)
63
65
  members: OrganizationMembersClient = field(default_factory=OrganizationMembersClient)
64
66
  notifications: NotificationsClient = field(default_factory=NotificationsClient)
67
+ talk: TalkClient = field(default_factory=TalkClient)
65
68
  redis: Any = field(default_factory=lambda: UnavailablePlatformService("redis"))
66
69
  vector: Any = field(default_factory=lambda: UnavailablePlatformService("vector"))
70
+ # The platform's own model keys, under a per-org spend cap — declare
71
+ # platform_services: ["llm"] instead of shipping an OPENAI_API_KEY secret.
72
+ llm: Any = field(default_factory=lambda: UnavailablePlatformService("llm"))
73
+ # Web search + SSRF-guarded page reader — platform_services: ["web"].
74
+ web: Any = field(default_factory=lambda: UnavailablePlatformService("web"))
67
75
  events: EventPublisher = field(default_factory=EventPublisher)
68
76
  jobs: JobsClient = field(default_factory=JobsClient)
69
77
  config: dict[str, Any] = field(default_factory=dict)
@@ -141,8 +149,14 @@ async def get_plugin_context(request: Request) -> PluginContext:
141
149
  getattr(state, "plugin_permissions", []),
142
150
  ),
143
151
  notifications=NotificationsClient(getattr(state, "notifications", None)),
152
+ talk=TalkClient(
153
+ getattr(state, "talk", None),
154
+ getattr(state, "plugin_permissions", []),
155
+ ),
144
156
  redis=getattr(state, "redis", None) or UnavailablePlatformService("redis"),
145
157
  vector=getattr(state, "vector", None) or UnavailablePlatformService("vector"),
158
+ llm=getattr(state, "llm", None) or UnavailablePlatformService("llm"),
159
+ web=getattr(state, "web", None) or UnavailablePlatformService("web"),
146
160
  events=EventPublisher(getattr(state, "plugin_events", None)),
147
161
  jobs=JobsClient(getattr(state, "plugin_jobs", None)),
148
162
  config=getattr(state, "plugin_config", {}),
@@ -40,10 +40,23 @@ class ServiceDecl:
40
40
  scope: str | None = None
41
41
  label: str | None = None
42
42
  description: str | None = None
43
- input_schema: dict | None = None
44
- output_schema: dict | None = None
43
+ input_schema: dict | str | None = None
44
+ output_schema: dict | str | None = None
45
45
  deprecated: bool = False
46
46
  replacement: str | None = None
47
+ agent_exposable: bool = False
48
+ capability_id: str | None = None
49
+ effects: tuple[str, ...] = ()
50
+ risk: str = "read"
51
+ supports_scheduling: bool = True
52
+ idempotent: bool = False
53
+ timeout_seconds: int = 60
54
+ tags: tuple[str, ...] = ()
55
+ artifact_inputs: tuple[str, ...] = ()
56
+ artifact_outputs: tuple[str, ...] = ()
57
+ examples: tuple[dict[str, Any], ...] = ()
58
+ cost_class: str | None = None
59
+ latency_class: str | None = None
47
60
 
48
61
 
49
62
  # Plugin-declared service handlers captured during module import. The platform
@@ -60,12 +73,25 @@ def service(
60
73
  scope: str | None = None,
61
74
  label: str | None = None,
62
75
  description: str | None = None,
63
- input_schema: dict | None = None,
64
- input: dict | None = None,
65
- output_schema: dict | None = None,
66
- output: dict | None = None,
76
+ input_schema: dict | str | None = None,
77
+ input: dict | str | None = None,
78
+ output_schema: dict | str | None = None,
79
+ output: dict | str | None = None,
67
80
  deprecated: bool = False,
68
81
  replacement: str | None = None,
82
+ agent_exposable: bool = False,
83
+ capability_id: str | None = None,
84
+ effects: list[str] | None = None,
85
+ risk: str = "read",
86
+ supports_scheduling: bool = True,
87
+ idempotent: bool = False,
88
+ timeout_seconds: int = 60,
89
+ tags: list[str] | None = None,
90
+ artifact_inputs: list[str] | None = None,
91
+ artifact_outputs: list[str] | None = None,
92
+ examples: list[dict[str, Any]] | None = None,
93
+ cost_class: str | None = None,
94
+ latency_class: str | None = None,
69
95
  ) -> Callable[[ServiceHandler], ServiceHandler]:
70
96
  """Mark an async function as a broker-callable service method."""
71
97
 
@@ -83,6 +109,19 @@ def service(
83
109
  output_schema=output_schema or output,
84
110
  deprecated=deprecated,
85
111
  replacement=replacement,
112
+ agent_exposable=agent_exposable,
113
+ capability_id=capability_id,
114
+ effects=tuple(effects or ()),
115
+ risk=risk,
116
+ supports_scheduling=supports_scheduling,
117
+ idempotent=idempotent,
118
+ timeout_seconds=timeout_seconds,
119
+ tags=tuple(tags or ()),
120
+ artifact_inputs=tuple(artifact_inputs or ()),
121
+ artifact_outputs=tuple(artifact_outputs or ()),
122
+ examples=tuple(examples or ()),
123
+ cost_class=cost_class,
124
+ latency_class=latency_class,
86
125
  )
87
126
  )
88
127
  return fn
@@ -0,0 +1,65 @@
1
+ """Backend Talk helpers for plugin Python code.
2
+
3
+ Post into a Talk channel as the app's own agent identity — the agent row the
4
+ platform creates for every installation, the same one members `@`-mention:
5
+
6
+ from palette_sdk import PluginContext, get_plugin_context
7
+
8
+ @router.post("/digest", dependencies=[require_permission("chat:write")])
9
+ async def send_digest(ctx: PluginContext = Depends(get_plugin_context)):
10
+ for room in await ctx.talk.channels():
11
+ await ctx.talk.post("Nightly digest is ready.", channel=room["id"])
12
+
13
+ Requires `chat:write` in the manifest's `permissions`, and the app's agent must
14
+ already be a participant of the target channel — a member invites it the same
15
+ way they invite any agent. An app can post into the rooms it was invited to and
16
+ nowhere else, and it cannot read message history at all.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Any
22
+
23
+
24
+ class TalkClient:
25
+ """Thin wrapper around the platform-injected Talk service.
26
+
27
+ In production/hosted sandbox the platform injects the service into
28
+ `PluginContext`. In local unit tests, pass a fake service with the same
29
+ async `post`/`channels` methods.
30
+ """
31
+
32
+ def __init__(self, service: Any = None, permissions: list[str] | None = None):
33
+ self._service = service
34
+ self._permissions = permissions or []
35
+
36
+ def _require_service(self) -> Any:
37
+ if self._service is None:
38
+ raise RuntimeError(
39
+ "Talk service is not available in this runtime. "
40
+ "Run inside Palette OS/hosted sandbox or inject a fake service in tests."
41
+ )
42
+ return self._service
43
+
44
+ def _require_permission(self, permission: str) -> None:
45
+ if permission not in self._permissions:
46
+ raise PermissionError(f"App does not declare required permission: {permission}")
47
+
48
+ async def channels(self) -> list[dict[str, Any]]:
49
+ """Channels this app's agent is seated in: `{id, name, type}` each.
50
+
51
+ The only Talk read an app gets. Everything else in a room stays private
52
+ to its members.
53
+ """
54
+ self._require_permission("chat:write")
55
+ return await self._require_service().channels()
56
+
57
+ async def post(self, text: str, *, channel: str) -> dict[str, Any]:
58
+ """Post `text` to `channel`, as the app's agent. Returns the message.
59
+
60
+ `channel` is a channel id or its name (`"general"`, `"#general"`).
61
+ `@Name` in the text mentions that member or agent exactly as a typed
62
+ message does, so a mentioned agent will answer.
63
+ """
64
+ self._require_permission("chat:write")
65
+ return await self._require_service().post(text=text, channel=channel)
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "palette-sdk"
3
- version = "0.1.9"
3
+ version = "0.1.13"
4
4
  description = "Palette Platform SDK for building backend plugins"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -112,14 +112,17 @@ Available context values:
112
112
  | `ctx.permissions` | Permissions granted from `palette-plugin.json` |
113
113
  | `ctx.storage` | Runtime storage service, when available |
114
114
  | `ctx.data_rooms` | Backend Data Room client |
115
- | `ctx.connections` | Palette-managed third-party connection client |
115
+ | `ctx.connections` | The viewer's Palette OS connections — `ctx.connections.gmail.search(...)`, no OAuth of your own |
116
116
  | `ctx.members` | Current organisation member client |
117
117
  | `ctx.notifications` | Push OS notification-center notifications |
118
+ | `ctx.talk` | Post into Talk channels as the app's own agent (`chat:write`, seat required) |
118
119
  | `ctx.apps` / `services(ctx)` | Governed app-to-app calls through declared `consumes` contracts |
119
120
  | `ctx.events` | Publish event topics declared in `provides.events` |
120
121
  | `ctx.jobs` | Enqueue, inspect, and cancel durable background jobs |
121
122
  | `ctx.redis` | Plugin/org-scoped Redis-style service when `platform_services` includes `redis` |
122
123
  | `ctx.vector` | Plugin/org-scoped vector service when `platform_services` includes `vector` |
124
+ | `ctx.llm` | The platform's own model keys under an org spend cap when `platform_services` includes `llm` |
125
+ | `ctx.web` | Web search + SSRF-guarded page reader when `platform_services` includes `web` |
123
126
  | `ctx.config` | App install/config values |
124
127
  | `ctx.logger` | Runtime logger for backend code |
125
128
  | `ctx.repo(Model)` | Org-safe CRUD helper for app-owned tables |
@@ -144,6 +147,7 @@ These are the public Python helpers exported by `palette_sdk`.
144
147
  | `DataRoomsClient`, `ctx.data_rooms` | Backend Data Room room/folder/file helpers |
145
148
  | `OrganizationMembersClient`, `ctx.members` | Current-organization member lookup, invite, and role helpers |
146
149
  | `NotificationsClient`, `ctx.notifications` | Push notifications into the OS notification center |
150
+ | `TalkClient`, `ctx.talk` | Post into Talk channels the app's agent is seated in |
147
151
  | `PluginConnectionsClient`, `ConnectionStatus`, `MissingConnectionError`, `ctx.connections` | Third-party connection status and token helpers |
148
152
  | `AppInteropClient`, `AppServiceClient`, `MissingAppServiceError`, `ctx.apps` | Call required apps/services without direct database access |
149
153
  | `service(...)`, `services(ctx)`, `ServicesClient`, `BrokerCallError` | Provide and consume OS-broker service methods/events |
@@ -788,6 +792,38 @@ During `pltt dev` notifications are not delivered to a real notification
788
792
  center — the simulator logs them as `[palette-notification] {...}` and returns
789
793
  a stub response, so your code paths still run.
790
794
 
795
+ ## 8b. Talk Messages From Python
796
+
797
+ Every installed app has an agent identity in Talk — the agent members
798
+ `@`-mention and DM. `ctx.talk` lets your backend speak as it, for the moments
799
+ your app has something to say first (a finished export, a nightly digest, an
800
+ alert from a scheduled job):
801
+
802
+ ```python
803
+ from palette_sdk import PluginContext, get_plugin_context, require_permission
804
+
805
+ @router.post("/digest", dependencies=[require_permission("chat:write")])
806
+ async def send_digest(ctx: PluginContext = Depends(get_plugin_context)):
807
+ for room in await ctx.talk.channels():
808
+ await ctx.talk.post("Nightly digest is ready.", channel=room["id"])
809
+ ```
810
+
811
+ `channel` takes a channel id or its name (`"general"`, `"#general"`). An
812
+ `@Name` in the text mentions that member or agent just as a typed message does,
813
+ so a mentioned agent will answer.
814
+
815
+ Declare `chat:write` in `permissions` or the call raises `PermissionError`. Two
816
+ runtime rules then apply, both fail-closed:
817
+
818
+ - the app's agent must already be a participant of the target channel — a
819
+ member invites it in Talk, so the room's own people decide who may post;
820
+ - `ctx.talk.channels()` is the only read an app gets (ids, names, types of the
821
+ rooms it is seated in). No history, no member list, no search.
822
+
823
+ Available in request handlers, `@capability` methods, and background jobs.
824
+ During `pltt dev` nothing reaches a real channel: the simulator reports one
825
+ fake seat, logs each post as `[palette-talk] {...}`, and returns a stub message.
826
+
791
827
  ## 9. Config And Secrets
792
828
 
793
829
  Use config for app install settings and secrets for sensitive values.
@@ -843,6 +879,33 @@ Managed Redis, vector, and storage services are declared in the manifest:
843
879
  ```
844
880
 
845
881
  ```python
882
+ # Third-party services — the user connects once in Palette Connect, grants your
883
+ # app the tools your manifest declares, and the platform proxies every call.
884
+ # Your app never holds a provider token, so scope checks, write approval and the
885
+ # audit trail keep working.
886
+ messages = await ctx.connections.gmail.search(query="invoice newer_than:7d")
887
+ await ctx.connections.slack.post_message(channel="#ops", text="digest ready")
888
+
889
+ # Mutating tools (gmail.send, slack.post_message, …) stage for approval by
890
+ # default and return {"queued_for_approval": True, "approval_id", "preview"} —
891
+ # tell the user what you prepared instead of claiming it was sent. An org admin
892
+ # can allow a specific app+provider to write directly.
893
+ sent = await ctx.connections.gmail.send(to="a@b.com", subject="Hi", body="…")
894
+ if sent.get("queued_for_approval"):
895
+ ... # render the pending state
896
+
897
+ # The platform's model keys — no OPENAI_API_KEY secret to ship or rotate.
898
+ reply = await ctx.llm.chat([{"role": "user", "content": "Summarise this"}])
899
+ reply["text"], reply["model"], reply["cost_usd"]
900
+ async for chunk in ctx.llm.stream([{"role": "user", "content": "Write a haiku"}]):
901
+ ...
902
+ vectors = await ctx.llm.embed(["some text"])
903
+ image_bytes, mime = await ctx.llm.image("a fox in the snow")
904
+
905
+ # Web search + reader (HTML tables and PDFs already handled).
906
+ hits = await ctx.web.search("palette os changelog", limit=5)
907
+ text = await ctx.web.fetch("https://example.com/report.pdf")
908
+
846
909
  await ctx.redis.set("cache:summary", {"ready": True}, ttl=600)
847
910
  value = await ctx.redis.get("cache:summary")
848
911
 
package/lib/bundler.js CHANGED
@@ -497,6 +497,69 @@ async function bundleFrontend(pluginDir, entry, frontend = {}) {
497
497
  }
498
498
  }
499
499
 
500
+ /**
501
+ * Watch the frontend entry and hand each successful (minified) bundle to
502
+ * `onBundle(buffer)` — used by `pltt dev --sandbox --watch` to push live
503
+ * frontend updates onto an existing preview publish. Returns the esbuild
504
+ * context (caller disposes).
505
+ */
506
+ async function watchFrontendBuffer(pluginDir, entry, frontend = {}, onBundle) {
507
+ pluginDir = path.resolve(pluginDir)
508
+ const esbuild = loadEsbuild()
509
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "palette-frontend-watch-"))
510
+ const bundleEntry = isPaletteApp(frontend)
511
+ ? generatePaletteAppEntry(pluginDir, entry || "./frontend/app", path.join(tmp, "entry.tsx"))
512
+ : entry
513
+ const absEntry = path.resolve(pluginDir, bundleEntry)
514
+ if (!fs.existsSync(absEntry)) {
515
+ throw new Error(`frontend entry not found: ${entry}`)
516
+ }
517
+ const buildConfig = frontendBuildConfig(pluginDir, { ...frontend, entry })
518
+
519
+ const ctx = await esbuild.context({
520
+ entryPoints: [absEntry],
521
+ bundle: true,
522
+ outfile: path.join(tmp, "frontend.mjs"),
523
+ format: "esm",
524
+ platform: "browser",
525
+ target: ["es2022"],
526
+ write: false,
527
+ jsx: "automatic",
528
+ loader: { ".ts": "tsx", ".tsx": "tsx", ".js": "jsx", ".jsx": "jsx" },
529
+ define: buildConfig.define,
530
+ external: [
531
+ "react",
532
+ "react-dom",
533
+ "react-dom/client",
534
+ "react/jsx-runtime",
535
+ "react/jsx-dev-runtime",
536
+ "@palettelab/sdk",
537
+ ],
538
+ minify: true,
539
+ sourcemap: "inline",
540
+ logLevel: "silent",
541
+ absWorkingDir: pluginDir,
542
+ plugins: [
543
+ ...buildConfig.plugins,
544
+ {
545
+ name: "palette-watch-buffer",
546
+ setup(build) {
547
+ build.onEnd((result) => {
548
+ if (result.errors.length) {
549
+ console.error("[pltt] frontend bundle failed:")
550
+ for (const err of result.errors) console.error(` - ${err.text}`)
551
+ return
552
+ }
553
+ onBundle(bundleOutputsToFrontendBuffer(result, pluginCssScopeId(frontend)))
554
+ })
555
+ },
556
+ },
557
+ ],
558
+ })
559
+ await ctx.watch()
560
+ return ctx
561
+ }
562
+
500
563
  async function watchFrontend(pluginDir, entry, outfile, frontend = {}) {
501
564
  pluginDir = path.resolve(pluginDir)
502
565
  outfile = path.resolve(outfile)
@@ -636,6 +699,7 @@ module.exports = {
636
699
  bundleFrontend,
637
700
  bundleBackend,
638
701
  watchFrontend,
702
+ watchFrontendBuffer,
639
703
  frontendBuildConfig,
640
704
  mergePlugins,
641
705
  }