@palettelab/cli 0.3.74 → 0.3.75

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 CHANGED
@@ -317,14 +317,14 @@ Backend SDK features for app-owned data:
317
317
  - `ctx.connections.<namespace>.<tool>(...)` calls the third-party services the viewer connected in Palette Connect — `ctx.connections.gmail.search(query=...)`, `ctx.connections.slack.post_message(...)`, and so on for drive, calendar, sheets, docs, slides, contacts, tasks, forms, notion, telegram and meta. `ctx.connections.list()/status(id)/require(id)` report what is connected and granted. There is no `access_token(...)`: the platform holds the credential so scope checks, write approval and audit cannot be bypassed.
318
318
  - `ctx.has_permission("...")`, `ctx.has_any_permission([...])`, and `ctx.has_all_permissions([...])` check declared permissions.
319
319
  - `ctx.config_value("key")` and `ctx.require_config("key")` read app install/config values.
320
- - `ctx.secret("KEY")` reads app secrets from config or environment variables.
320
+ - `ctx.secret("KEY")` reads a secret the manifest declares (hosted: the install's config or the plugin's encrypted secrets; `pltt dev`: local `.env` files). An undeclared key returns the default; the process environment is never read.
321
321
  - `get_config(ctx, key)` and `require_config(ctx, key)` are functional config helper forms.
322
322
  - `require_permission(permission)`, `KNOWN_PERMISSIONS`, and `is_known_permission(permission)` support route and manifest permission checks.
323
323
  - `ctx.redis` gives a Redis-backed, plugin/org-scoped Redis API when `"redis"` is declared in `platform_services`.
324
324
  - `ctx.vector` gives a Qdrant-backed, plugin/org-scoped vector API when `"vector"` is declared in `platform_services`.
325
325
  - `ctx.storage` gives app/org-scoped file upload helpers when `"storage"` is declared in `platform_services`.
326
326
  - `ctx.llm` gives chat, streaming, embeddings and image generation on the PLATFORM's own provider keys when `"llm"` is declared — no `OPENAI_API_KEY` secret to ship or rotate. An app picks any model the workspace's own chat offers with `model=` — Palette's own models and the latest Claude, GPT and Gemini models, premium ones included, no declaration — and nothing bypasses the workspace's SECURE policy. `fallback=False` runs exactly the requested model or raises `ModelUnavailable`; every reply reports the model that actually ran. Tool calls (`tools=`, `tool_calls`, `reply["message"]` for the history) are supported. Calls spend the workspace's credits under its plan, seat and member limits, and are refused (the billing `CreditError`) when the workspace could not start a chat turn either.
327
- - `ctx.llm` also takes provider passthrough (`response_format`, `top_p`, `stop`, `seed`, …) as plain keywords, and reports `ctx.llm.catalog()` (models with limits and unavailable reasons), `ctx.llm.models()` and `ctx.llm.spend()` so an app can offer a real model picker and explain a refusal.
327
+ - `ctx.llm` also takes generation keywords (`response_format`, `top_p`, `stop`, `seed`, `reasoning_effort`, `top_k`, `thinking`, …) as plain keywords, each sent to the providers that take it (endpoint, credential and transport keywords such as `base_url` or `api_key` raise `ValueError`; any other keyword is ignored with a warning), and reports `ctx.llm.catalog()` (models with limits and unavailable reasons), `ctx.llm.models()` and `ctx.llm.spend()` so an app can offer a real model picker and explain a refusal.
328
328
  - `ctx.media` gives fal.ai on the PLATFORM's key when `"media"` is declared — no `FAL_KEY` secret to ship or rotate. `ctx.media.run(model, payload)` reaches ANY fal model with the payload passed through untouched (so a model fal shipped today needs no SDK release); `image`, `video`, `speech` and `transcribe` are the same call with a default model filled in, `submit`/`status`/`result`/`cancel` handle multi-minute renders through a durable handle (`MediaStillRunning.handle`), `upload` puts bytes, public URLs or the app's own `ctx.storage` files on fal's CDN, `catalog()` lists the fal models it can run, and `save` copies an output into the app's own storage — fal's URLs expire. It spends the workspace's credits like `ctx.llm`.
329
329
  - `ctx.web` gives web search and an SSRF-guarded page reader (HTML tables and PDFs handled) when `"web"` is declared. `ctx.web.fetch(url, render=True)` loads the page in a browser first, for content its scripts build after it loads (a shop page's size table); it takes tens of seconds and `pltt dev` ignores the flag.
330
330
  - `ctx.email.send(to, subject, html=..., text=..., cc=..., bcc=..., reply_to=..., from_name=..., attachments=[...], headers=..., tags=...)` sends email through the PLATFORM's email provider when `"email"` is declared — from the platform's sender address under the app's name, so no SendGrid key, SMTP login or verified domain to ship. Attachments are bytes or text with an optional `content_type`, and a `content_id` makes one inline for `<img src="cid:...">`. Up to 50 recipients and 10 MB per message, within a daily recipient allowance per workspace. `pltt dev` sends nothing: each message is checked with the hosted rules and saved to `.palette/dev-outbox/` as an `.eml` file.
@@ -788,10 +788,14 @@ The platform rewrites Redis keys and vector filters with `plugin_id` and
788
788
  `organization_id`, so create/update/delete/list operations cannot reach another
789
789
  app or org's data.
790
790
 
791
- For provider-level Redis features, use `ctx.redis.execute(...)`. It forwards to
792
- Redis after rewriting key arguments into the plugin/org namespace, and blocks
793
- server/admin commands such as `FLUSHDB`, `CONFIG`, `KEYS`, and cluster
794
- management. For advanced Qdrant features, use `ctx.vector.client()` with
791
+ For provider-level Redis features, use `ctx.redis.execute(...)`. It runs only
792
+ the data-plane commands the platform lists, with their key arguments rewritten
793
+ into the plugin/org namespace. Anything else raises `ValueError`: commands
794
+ whose keys cannot all be rewritten (`EVAL` and other scripts, `KEYS`, `SCAN`,
795
+ `RANDOMKEY`, `PUBSUB`), server and connection commands (`FLUSHDB`, `CONFIG`,
796
+ `CLIENT`, cluster management) and blocking commands (`BLPOP`, `BRPOP`,
797
+ `BLMOVE`, `XREAD ... BLOCK`, `WAIT`). Key positions come from the command, so
798
+ `key_positions=` and `all_keys=` are refused too. For advanced Qdrant features, use `ctx.vector.client()` with
795
799
  `collection_name()`, `scoped_filter()`, `merge_filter()`, `scoped_payload()`,
796
800
  and `scoped_point()` so custom calls remain scoped. The client is confined to your app's partition: it offers `query_points`, `scroll`, `count`, `retrieve`, `upsert` (of `scoped_point(...)` points only) and `delete`, always filtered to this app and organization; other operations are refused.
797
801
 
@@ -837,8 +841,10 @@ await ctx.vector.delete_index("knowledge")
837
841
  stats = await ctx.vector.stats("knowledge")
838
842
  ```
839
843
 
840
- Blocked Redis control-plane commands include `FLUSHDB`, `FLUSHALL`, `CONFIG`,
841
- `KEYS`, `CLUSTER`, `SCRIPT`, `EVAL`, `FUNCTION`, and `SELECT`.
844
+ `ctx.redis.execute` runs only the commands the platform lists. Control-plane
845
+ commands such as `FLUSHDB`, `FLUSHALL`, `CONFIG`, `KEYS`, `CLUSTER`, `SCRIPT`,
846
+ `EVAL`, `FUNCTION` and `SELECT`, and blocking ones such as `BLPOP` and
847
+ `XREAD ... BLOCK`, raise `ValueError`.
842
848
 
843
849
  ### `pltt login`
844
850
 
@@ -157,4 +157,4 @@ __all__ = [
157
157
  "LocalStorageService",
158
158
  ]
159
159
 
160
- __version__ = "0.1.21"
160
+ __version__ = "0.1.22"
@@ -151,6 +151,16 @@ class GmailTools(_Namespace):
151
151
  return await self._call("google", "gmail.update_draft", {"body": body, "draft_id": draft_id, "subject": subject, "to": to, "cc": cc, "thread_id": thread_id})
152
152
 
153
153
 
154
+ class InstagramTools(_Namespace):
155
+ async def list_accounts(self, *, limit: int | None = None) -> Any:
156
+ """List the Instagram professional accounts linked to the account's Facebook Pages."""
157
+ return await self._call("meta", "instagram.list_accounts", {"limit": limit})
158
+
159
+ async def publish_reel(self, *, video_url: str, account_id: str | None = None, caption: str | None = None) -> Any:
160
+ """Post a video Palette made as a Reel on the linked Instagram professional account (its only one unless account_id names one). Takes a minute or two while Instagram processes it."""
161
+ return await self._call("meta", "instagram.publish_reel", {"video_url": video_url, "account_id": account_id, "caption": caption})
162
+
163
+
154
164
  class JiraTools(_Namespace):
155
165
  async def add_comment(self, *, body: str, issue_key: str, site: str | None = None) -> Any:
156
166
  """Add a plain-text comment to a Jira issue."""
@@ -210,6 +220,10 @@ class MetaTools(_Namespace):
210
220
  """List the Facebook Pages this account manages (id, name, category)."""
211
221
  return await self._call("meta", "meta.list_pages", {"limit": limit})
212
222
 
223
+ async def publish_video(self, *, video_url: str, description: str | None = None, page_id: str | None = None, title: str | None = None) -> Any:
224
+ """Post a video Palette made to a Facebook Page the account manages (its only Page unless page_id names one). Returns its link."""
225
+ return await self._call("meta", "meta.publish_video", {"video_url": video_url, "description": description, "page_id": page_id, "title": title})
226
+
213
227
  async def read_page_posts(self, *, page_id: str, limit: int | None = None) -> Any:
214
228
  """Read recent posts from a Facebook Page the account manages."""
215
229
  return await self._call("meta", "meta.read_page_posts", {"page_id": page_id, "limit": limit})
@@ -475,6 +489,16 @@ class TiroTools(_Namespace):
475
489
  return await self._call("tiro", "tiro.search_wiki", {"keyword": keyword, "limit": limit, "workspace": workspace})
476
490
 
477
491
 
492
+ class YoutubeTools(_Namespace):
493
+ async def list_channels(self, *, limit: int | None = None) -> Any:
494
+ """List the YouTube channels of the connected account (id, title, handle)."""
495
+ return await self._call("google", "youtube.list_channels", {"limit": limit})
496
+
497
+ async def upload_video(self, *, title: str, video_url: str, description: str | None = None, privacy_status: str | None = None) -> Any:
498
+ """Post a video Palette made to the connected YouTube channel. A vertical video up to 3 minutes shows as a Short. Returns its link."""
499
+ return await self._call("google", "youtube.upload_video", {"title": title, "video_url": video_url, "description": description, "privacy_status": privacy_status})
500
+
501
+
478
502
  NAMESPACES: dict[str, type[_Namespace]] = {
479
503
  "calendar": CalendarTools,
480
504
  "confluence": ConfluenceTools,
@@ -484,6 +508,7 @@ NAMESPACES: dict[str, type[_Namespace]] = {
484
508
  "figma": FigmaTools,
485
509
  "forms": FormsTools,
486
510
  "gmail": GmailTools,
511
+ "instagram": InstagramTools,
487
512
  "jira": JiraTools,
488
513
  "meta": MetaTools,
489
514
  "notion": NotionTools,
@@ -494,4 +519,5 @@ NAMESPACES: dict[str, type[_Namespace]] = {
494
519
  "telegram": TelegramTools,
495
520
  "tiktok": TiktokTools,
496
521
  "tiro": TiroTools,
522
+ "youtube": YoutubeTools,
497
523
  }
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import asyncio
6
6
  import hashlib
7
7
  import json
8
+ import logging
8
9
  import math
9
10
  import mimetypes
10
11
  import re
@@ -589,6 +590,71 @@ def _stop_reason(raw: Any, has_calls: bool) -> str:
589
590
  return "stop"
590
591
 
591
592
 
593
+ # ---- ctx.llm keyword rules shared with palette_sdk ----------------------------------
594
+ # What ctx.llm does with an app's extra keywords, hosted and under pltt dev alike: the block is the same text in
595
+ # backend/app/plugins/platform_services.py and sdk/backend/palette_sdk/platform_services.py (backend
596
+ # test_plugin_llm pins it).
597
+ #
598
+ # A generation keyword goes to a seat whose provider's model class takes it (checked against
599
+ # billing.clients.init_chat_model). Any other seat leaves it out: there it would reach the request raw and the
600
+ # provider would refuse the call (OpenAI refuses top_k and thinking; Anthropic seed, the penalties and logprobs).
601
+ # parallel_tool_calls goes with the bound tools, so a call without tools drops it.
602
+ _LLM_EVERY_PROVIDER = frozenset({"openai", "palette", "anthropic", "google_genai"})
603
+ _LLM_OPENAI_WIRE = frozenset({"openai", "palette"})
604
+ _LLM_KEYWORDS: dict[str, frozenset[str]] = {
605
+ "top_p": _LLM_EVERY_PROVIDER,
606
+ "stop": _LLM_EVERY_PROVIDER,
607
+ "reasoning_effort": _LLM_EVERY_PROVIDER,
608
+ "response_format": _LLM_OPENAI_WIRE | {"anthropic"},
609
+ "seed": _LLM_OPENAI_WIRE | {"google_genai"},
610
+ "frequency_penalty": _LLM_OPENAI_WIRE | {"google_genai"},
611
+ "presence_penalty": _LLM_OPENAI_WIRE | {"google_genai"},
612
+ "logprobs": _LLM_OPENAI_WIRE,
613
+ "top_logprobs": _LLM_OPENAI_WIRE,
614
+ "parallel_tool_calls": _LLM_OPENAI_WIRE | {"anthropic"},
615
+ "top_k": frozenset({"anthropic", "google_genai"}),
616
+ "thinking": frozenset({"anthropic"}),
617
+ }
618
+ # Refused with a ValueError naming it: each would send the platform's key to another endpoint, through another
619
+ # client, or with headers or a request body the app wrote.
620
+ _LLM_REFUSED_KEYWORDS = frozenset({
621
+ "base_url", "api_base", "openai_api_base", "anthropic_api_url", "api_key", "openai_api_key",
622
+ "anthropic_api_key", "google_api_key", "default_headers", "headers", "extra_headers", "http_client",
623
+ "http_async_client", "client", "async_client", "organization", "openai_organization", "openai_proxy",
624
+ "proxies", "model_kwargs", "extra_body", "default_query",
625
+ })
626
+
627
+
628
+ def _llm_keywords(kwargs: dict[str, Any], max_tokens: Any, app: str) -> tuple[dict[str, Any], Any]:
629
+ """(the keywords one ctx.llm call passes on, its output cap), from the call's extra keywords.
630
+
631
+ An endpoint, credential or transport keyword is a ValueError naming it. max_completion_tokens is OpenAI's
632
+ newer name for max_tokens and the same cap clips it (passed on raw, it would replace that cap). Anything
633
+ else is left out, with one warning naming the app and the keyword."""
634
+ refused = sorted(name for name in kwargs if name in _LLM_REFUSED_KEYWORDS)
635
+ if refused:
636
+ raise ValueError(
637
+ f"ctx.llm: {', '.join(map(repr, refused))} cannot be set by an app; "
638
+ "the platform chooses the endpoint, credentials and client"
639
+ )
640
+ if kwargs.get("max_completion_tokens") is not None:
641
+ max_tokens = kwargs["max_completion_tokens"]
642
+ dropped = sorted(name for name in kwargs if name not in _LLM_KEYWORDS and name != "max_completion_tokens")
643
+ if dropped:
644
+ logging.getLogger(__name__).warning(
645
+ "ctx.llm: ignored keyword(s) %s from %s", ", ".join(repr(name[:80]) for name in dropped), app
646
+ )
647
+ return {name: value for name, value in kwargs.items() if name in _LLM_KEYWORDS}, max_tokens
648
+
649
+
650
+ def _llm_keywords_for(provider: str, keywords: dict[str, Any]) -> dict[str, Any]:
651
+ """The keywords a seat of `provider` takes."""
652
+ return {name: value for name, value in keywords.items() if provider in _LLM_KEYWORDS[name]}
653
+
654
+
655
+ # ---- end of ctx.llm keyword rules shared with palette_sdk ---------------------------
656
+
657
+
592
658
  class LocalLLMService:
593
659
  """`ctx.llm` for pltt dev — the hosted call shapes and receipt keys.
594
660
 
@@ -687,11 +753,14 @@ class LocalLLMService:
687
753
 
688
754
  def _request(self, messages, system, model, max_tokens, tools, tool_choice, kwargs) -> dict[str, Any]:
689
755
  specs = _openai_tools(tools)
756
+ keywords = _llm_keywords_for("openai", kwargs) # pltt dev runs OpenAI models
757
+ if not specs:
758
+ keywords.pop("parallel_tool_calls", None) # it governs the tools; OpenAI refuses it without them
690
759
  body: dict[str, Any] = {
691
760
  "model": model,
692
761
  "messages": _openai_messages(messages, system),
693
762
  "max_completion_tokens": max_tokens,
694
- **kwargs,
763
+ **keywords,
695
764
  }
696
765
  if specs:
697
766
  body["tools"] = specs
@@ -725,6 +794,8 @@ class LocalLLMService:
725
794
  **kwargs: Any,
726
795
  ) -> dict[str, Any]:
727
796
  requested = (model or "").strip() or None
797
+ # The hosted keyword rules, key or no key: what pltt dev accepts is never refused once published.
798
+ kwargs, max_tokens = _llm_keywords(kwargs, max_tokens, "this app")
728
799
  # Same checks as hosted, stubbed or not: bad tools / tool_choice are a
729
800
  # ValueError and fallback=False refuses what pltt dev cannot run.
730
801
  specs = _openai_tools(tools)
@@ -775,6 +846,7 @@ class LocalLLMService:
775
846
  **kwargs: Any,
776
847
  ):
777
848
  requested = (model or "").strip() or None
849
+ kwargs, max_tokens = _llm_keywords(kwargs, max_tokens, "this app")
778
850
  specs = _openai_tools(tools)
779
851
  if specs:
780
852
  _openai_tool_choice(tool_choice, specs)
@@ -4,7 +4,6 @@ from __future__ import annotations
4
4
 
5
5
  from dataclasses import dataclass, field
6
6
  import logging
7
- import os
8
7
  from typing import Any
9
8
 
10
9
  from fastapi import Depends, Request
@@ -126,6 +125,13 @@ class PluginContext:
126
125
  return self.config[key]
127
126
 
128
127
  def secret(self, key: str, default: str | None = None) -> str | None:
128
+ """A secret the manifest declares, from the app's config.
129
+
130
+ An undeclared key returns ``default``: it is never read from the process
131
+ environment, which in a hosted runtime belongs to the platform. Declared
132
+ secrets reach ``config["secrets"]`` from the platform when hosted, and from
133
+ local .env files under ``pltt dev``.
134
+ """
129
135
  secrets = self.config.get("secrets")
130
136
  if isinstance(secrets, dict) and key in secrets:
131
137
  return secrets[key]
@@ -138,7 +144,7 @@ class PluginContext:
138
144
  help_text = spec.get("help") or spec.get("label") or "Configure this secret before using the plugin."
139
145
  raise MissingSecretError(f"missing plugin secret {key}: {help_text}")
140
146
  return default
141
- return os.environ.get(key, default)
147
+ return default
142
148
 
143
149
  def repo(self, model: type[Any]):
144
150
  from palette_sdk.repository import OrgRepository
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "palette-sdk"
3
- version = "0.1.21"
3
+ version = "0.1.22"
4
4
  description = "Palette Platform SDK for building backend plugins"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -147,7 +147,7 @@ Available context values:
147
147
  | `ctx.has_all_permissions([...])` | Check every listed permission |
148
148
  | `ctx.config_value(key, default)` | Read optional config |
149
149
  | `ctx.require_config(key)` | Read required config or raise |
150
- | `ctx.secret(key, default)` | Read a secret from app config or environment |
150
+ | `ctx.secret(key, default)` | Read a secret the manifest declares; an undeclared key returns `default` |
151
151
 
152
152
  ## 4a. Backend Helper API Index
153
153
 
@@ -890,8 +890,13 @@ Declare secret ownership in `palette-plugin.json`:
890
890
  `ctx.secret("KEY")` resolves declared secrets from the configured scope:
891
891
  install config, plugin-scope encrypted secrets, or local root `.env` files
892
892
  during `pltt dev`. During hosted preview/publish, server-only `.env` keys are
893
- uploaded automatically as encrypted plugin secrets. Undeclared keys still fall
894
- back to the process environment for local compatibility.
893
+ declared and uploaded automatically as encrypted plugin secrets. A key the
894
+ manifest does not declare returns `default` (or `None`): `ctx.secret` never
895
+ reads the process environment, which in a hosted runtime is the platform's, not
896
+ the app's. Declare every secret the app reads under `secrets` in the manifest.
897
+ Under `pltt dev` every key in the local `.env` files answers, declared or not,
898
+ so a key that works locally can still return `default` when hosted until the
899
+ manifest declares it.
895
900
 
896
901
  Managed services are declared in the manifest — `pltt platform list` prints the
897
902
  whole set with a snippet for each, and `pltt platform enable <name>` writes the
@@ -931,8 +936,10 @@ async for chunk in ctx.llm.stream([{"role": "user", "content": "Write a haiku"}]
931
936
  vectors = await ctx.llm.embed(["some text"])
932
937
  image_bytes, mime = await ctx.llm.image("a fox in the snow")
933
938
 
934
- # Anything else is passed straight to the provider — the platform only pins the
935
- # model, the budget and the token cap.
939
+ # Generation keywords go on to the providers that take them (response_format, top_p,
940
+ # stop, seed, the penalties, reasoning_effort, top_k, thinking, logprobs; max_completion_tokens
941
+ # is max_tokens). base_url, api_key, headers and clients raise ValueError; anything else is
942
+ # ignored with a warning. The platform pins the model, the budget and the token cap.
936
943
  strict = await ctx.llm.chat(messages, response_format={"type": "json_object"}, top_p=0.1)
937
944
  available = await ctx.llm.models() # what `model=` will honour ([] under SECURE)
938
945
  wallet = await ctx.llm.spend() # wallet["workspace"]: the member's credits in the workspace
@@ -1278,8 +1285,9 @@ await palette.storage.upload(file, {
1278
1285
  ```
1279
1286
 
1280
1287
  Advanced provider features are still available through scoped helpers:
1281
- `ctx.redis.execute(...)` forwards Redis data-plane commands after key rewriting,
1282
- while blocking server/admin commands. `ctx.vector.client()` returns the Qdrant
1288
+ `ctx.redis.execute(...)` runs only the data-plane commands the platform lists,
1289
+ with their key arguments rewritten into the app's namespace; any other command
1290
+ raises `ValueError` (see Provider-style Redis commands below). `ctx.vector.client()` returns the Qdrant
1283
1291
  client for custom calls; combine it with `collection_name()`, `scoped_filter()`,
1284
1292
  `merge_filter()`, `scoped_payload()`, and `scoped_point()` to preserve isolation.
1285
1293
  The client is confined to your app's partition: it offers `query_points`, `scroll`, `count`, `retrieve`, `upsert` (of `scoped_point(...)` points only) and `delete`, always filtered to this app and organization; other operations are refused.
@@ -1330,9 +1338,23 @@ values = await ctx.redis.execute("MGET", "a", "b")
1330
1338
  await ctx.redis.execute("ZUNIONSTORE", "dest", 2, "scores:1", "scores:2")
1331
1339
  ```
1332
1340
 
1333
- Server/admin Redis commands are blocked because they would affect the shared
1334
- central Redis instance: `FLUSHDB`, `FLUSHALL`, `CONFIG`, `KEYS`, `CLUSTER`,
1335
- `SCRIPT`, `EVAL`, `FUNCTION`, `SELECT`, and similar control-plane commands.
1341
+ `execute` is an allowlist: only the data-plane commands the platform lists run,
1342
+ each with the key positions the platform knows for it. Anything else raises
1343
+ `ValueError`:
1344
+
1345
+ - commands whose keys could not all be rewritten: `EVAL`, `EVALSHA`, `FCALL`,
1346
+ `KEYS`, `SCAN` (use `ctx.redis.scan(prefix=...)`), `RANDOMKEY`, `PUBSUB`,
1347
+ `SORT ... BY/GET`;
1348
+ - server and connection commands, which would affect the shared central Redis
1349
+ instance: `FLUSHDB`, `FLUSHALL`, `CONFIG`, `CLUSTER`, `SCRIPT`, `FUNCTION`,
1350
+ `SELECT`, `CLIENT`, and similar control-plane commands;
1351
+ - blocking commands, which would hold a connection every app shares: `BLPOP`,
1352
+ `BRPOP`, `BLMOVE`, `BRPOPLPUSH`, `BLMPOP`, `BZPOPMIN`, `XREAD`/`XREADGROUP`
1353
+ with `BLOCK`, `WAIT`. Hosted, `ctx.redis.xread(..., block=)` waits at most
1354
+ 5 seconds instead.
1355
+
1356
+ The `key_positions=` and `all_keys=` keywords are refused as well: key positions
1357
+ come from the command, never from the caller.
1336
1358
 
1337
1359
  Common `ctx.vector` commands:
1338
1360
 
package/lib/cli.js CHANGED
@@ -119,6 +119,7 @@ function printHelp() {
119
119
  console.log(" --sandbox Publish a reviewable preview to a configured Palette sandbox (no Docker)")
120
120
  console.log(" --cloud Alias for --sandbox")
121
121
  console.log(" --watch With --sandbox: live-push frontend changes onto the preview (no republish)")
122
+ console.log(" --role <role> Local simulator only: ctx.org_role as owner, admin or member (default owner; or set PALETTE_DEV_ROLE)")
122
123
  console.log(" --platform Internal only: run the Docker platform-dev parity container")
123
124
  console.log("\nLogin flags:")
124
125
  console.log(" --url <url> Palette platform URL for pltt login")
@@ -8,7 +8,7 @@ const { loadManifest } = require("../manifest")
8
8
  const { watchFrontend, watchFrontendBuffer } = require("../bundler")
9
9
  const { parseFlags, resolveEnvironment } = require("../environments")
10
10
  const { resolveDevPorts } = require("../ports")
11
- const { startSimulator } = require("../dev-simulator")
11
+ const { resolveDevRole, startSimulator } = require("../dev-simulator")
12
12
  const { loadLocalEnvDetails } = require("../secrets")
13
13
  const buildCommand = require("./build")
14
14
  const publish = require("./publish")
@@ -192,6 +192,15 @@ async function startPreviewWatch({ cwd, flags, record, json }) {
192
192
  )
193
193
  }
194
194
 
195
+ // `--role member` / `--role=member`; validated by resolveDevRole.
196
+ function parseRoleFlag(args) {
197
+ for (let i = 0; i < args.length; i++) {
198
+ if (args[i] === "--role") return args[i + 1] ?? ""
199
+ if (args[i].startsWith("--role=")) return args[i].slice("--role=".length)
200
+ }
201
+ return undefined
202
+ }
203
+
195
204
  async function run(args, { cwd }) {
196
205
  notifyIfUpdateAvailable(args).catch(() => {})
197
206
  const { flags, rest } = parseFlags(args)
@@ -252,6 +261,13 @@ async function run(args, { cwd }) {
252
261
  const manifest = loadManifest(cwd)
253
262
  lintMigrationsForDev(cwd, manifest)
254
263
  const pluginId = manifest.id
264
+ let role
265
+ try {
266
+ role = resolveDevRole(parseRoleFlag(args))
267
+ } catch (err) {
268
+ console.error(`[pltt] ${err.message}`)
269
+ process.exit(1)
270
+ }
255
271
  const ports = await resolveDevPorts({ host: platform ? "0.0.0.0" : "127.0.0.1" })
256
272
 
257
273
  if (!platform) {
@@ -261,7 +277,7 @@ async function run(args, { cwd }) {
261
277
  if (ports.backend !== ports.preferredBackend) {
262
278
  console.log(`[pltt] backend port ${ports.preferredBackend} is busy; using ${ports.backend}`)
263
279
  }
264
- await startSimulator({ cwd, frontendPort: ports.frontend, backendPort: ports.backend })
280
+ await startSimulator({ cwd, frontendPort: ports.frontend, backendPort: ports.backend, role })
265
281
  return
266
282
  }
267
283
 
@@ -347,3 +363,4 @@ async function run(args, { cwd }) {
347
363
  }
348
364
 
349
365
  module.exports = run
366
+ module.exports.parseRoleFlag = parseRoleFlag
@@ -1310,6 +1310,61 @@
1310
1310
  }
1311
1311
  }
1312
1312
  }
1313
+ },
1314
+ {
1315
+ "name": "youtube.list_channels",
1316
+ "namespace": "youtube",
1317
+ "method": "list_channels",
1318
+ "description": "List the YouTube channels of the connected account (id, title, handle).",
1319
+ "mutating": false,
1320
+ "risk": "read",
1321
+ "input_schema": {
1322
+ "type": "object",
1323
+ "properties": {
1324
+ "limit": {
1325
+ "type": "integer",
1326
+ "description": "Max to return (optional)"
1327
+ }
1328
+ }
1329
+ }
1330
+ },
1331
+ {
1332
+ "name": "youtube.upload_video",
1333
+ "namespace": "youtube",
1334
+ "method": "upload_video",
1335
+ "description": "Post a video Palette made to the connected YouTube channel. A vertical video up to 3 minutes shows as a Short. Returns its link.",
1336
+ "mutating": true,
1337
+ "risk": "external_write",
1338
+ "input_schema": {
1339
+ "type": "object",
1340
+ "properties": {
1341
+ "video_url": {
1342
+ "type": "string",
1343
+ "description": "The video's link exactly as Palette gave it (generate_video's url)"
1344
+ },
1345
+ "title": {
1346
+ "type": "string",
1347
+ "description": "Title, at most 100 characters"
1348
+ },
1349
+ "description": {
1350
+ "type": "string",
1351
+ "description": "Description; hashtags go here"
1352
+ },
1353
+ "privacy_status": {
1354
+ "type": "string",
1355
+ "enum": [
1356
+ "public",
1357
+ "unlisted",
1358
+ "private"
1359
+ ],
1360
+ "description": "Who can watch it (default public)"
1361
+ }
1362
+ },
1363
+ "required": [
1364
+ "video_url",
1365
+ "title"
1366
+ ]
1367
+ }
1313
1368
  }
1314
1369
  ]
1315
1370
  },
@@ -1318,6 +1373,51 @@
1318
1373
  "label": "Facebook / Instagram",
1319
1374
  "auth_type": "oauth2",
1320
1375
  "tools": [
1376
+ {
1377
+ "name": "instagram.list_accounts",
1378
+ "namespace": "instagram",
1379
+ "method": "list_accounts",
1380
+ "description": "List the Instagram professional accounts linked to the account's Facebook Pages.",
1381
+ "mutating": false,
1382
+ "risk": "read",
1383
+ "input_schema": {
1384
+ "type": "object",
1385
+ "properties": {
1386
+ "limit": {
1387
+ "type": "integer",
1388
+ "description": "Max to return (optional)"
1389
+ }
1390
+ }
1391
+ }
1392
+ },
1393
+ {
1394
+ "name": "instagram.publish_reel",
1395
+ "namespace": "instagram",
1396
+ "method": "publish_reel",
1397
+ "description": "Post a video Palette made as a Reel on the linked Instagram professional account (its only one unless account_id names one). Takes a minute or two while Instagram processes it.",
1398
+ "mutating": true,
1399
+ "risk": "external_write",
1400
+ "input_schema": {
1401
+ "type": "object",
1402
+ "properties": {
1403
+ "video_url": {
1404
+ "type": "string",
1405
+ "description": "The video's link exactly as Palette gave it (generate_video's url)"
1406
+ },
1407
+ "caption": {
1408
+ "type": "string",
1409
+ "description": "The Reel's caption; hashtags go here"
1410
+ },
1411
+ "account_id": {
1412
+ "type": "string",
1413
+ "description": "Account id from instagram.list_accounts, when there are several"
1414
+ }
1415
+ },
1416
+ "required": [
1417
+ "video_url"
1418
+ ]
1419
+ }
1420
+ },
1321
1421
  {
1322
1422
  "name": "meta.create_page_post",
1323
1423
  "namespace": "meta",
@@ -1364,6 +1464,38 @@
1364
1464
  }
1365
1465
  }
1366
1466
  },
1467
+ {
1468
+ "name": "meta.publish_video",
1469
+ "namespace": "meta",
1470
+ "method": "publish_video",
1471
+ "description": "Post a video Palette made to a Facebook Page the account manages (its only Page unless page_id names one). Returns its link.",
1472
+ "mutating": true,
1473
+ "risk": "external_write",
1474
+ "input_schema": {
1475
+ "type": "object",
1476
+ "properties": {
1477
+ "video_url": {
1478
+ "type": "string",
1479
+ "description": "The video's link exactly as Palette gave it (generate_video's url)"
1480
+ },
1481
+ "description": {
1482
+ "type": "string",
1483
+ "description": "The post's text"
1484
+ },
1485
+ "title": {
1486
+ "type": "string",
1487
+ "description": "Video title (optional)"
1488
+ },
1489
+ "page_id": {
1490
+ "type": "string",
1491
+ "description": "Page id from meta.list_pages, when it has several"
1492
+ }
1493
+ },
1494
+ "required": [
1495
+ "video_url"
1496
+ ]
1497
+ }
1498
+ },
1367
1499
  {
1368
1500
  "name": "meta.read_page_posts",
1369
1501
  "namespace": "meta",
@@ -165,7 +165,21 @@ function ensurePythonEnv(cwd, devDir, manifest) {
165
165
  // The Python below is a JS template literal: a backtick or a bare ${ inside it
166
166
  // terminates the string and the whole CLI stops loading. Keep docstrings
167
167
  // backtick-free.
168
- function writeBackendRunner(cwd, devDir, manifest, backendEntry, backendPort) {
168
+ const DEV_ROLES = ["owner", "admin", "member"]
169
+
170
+ // The role the simulator plays: the flag wins over PALETTE_DEV_ROLE; the default is owner.
171
+ function resolveDevRole(flagValue, env = process.env) {
172
+ const fromFlag = flagValue !== undefined
173
+ const role = fromFlag ? flagValue : env.PALETTE_DEV_ROLE || "owner"
174
+ if (!DEV_ROLES.includes(role)) {
175
+ throw new Error(
176
+ `${fromFlag ? "--role" : "PALETTE_DEV_ROLE"} must be one of ${DEV_ROLES.join(", ")} (got "${role}")`,
177
+ )
178
+ }
179
+ return role
180
+ }
181
+
182
+ function writeBackendRunner(cwd, devDir, manifest, backendEntry, backendPort, role = "owner") {
169
183
  const runner = path.join(devDir, "backend_runner.py")
170
184
  const sdkPath = localBackendSdkPath()
171
185
  const databasePath = path.join(devDir, `${manifest.id}.sqlite3`)
@@ -557,7 +571,7 @@ def _local_job_context(session):
557
571
  user_id="dev-user",
558
572
  organization_id=1,
559
573
  organization=OrganizationInfo.from_dict(DEV_ORGANIZATION),
560
- org_role="owner",
574
+ org_role=${JSON.stringify(role)},
561
575
  plugin_id=MANIFEST.get("id", ""),
562
576
  permissions=MANIFEST.get("permissions", []),
563
577
  storage=DEV_STORAGE or UnavailablePlatformService("storage"),
@@ -639,7 +653,7 @@ class DevPluginContextMiddleware(BaseHTTPMiddleware):
639
653
  name="Palette Developer",
640
654
  organization_id=1,
641
655
  )
642
- request.state.org_role = "owner"
656
+ request.state.org_role = ${JSON.stringify(role)}
643
657
  request.state.organization_info = DEV_ORGANIZATION
644
658
  request.state.plugin_id = MANIFEST.get("id", "")
645
659
  request.state.plugin_permissions = MANIFEST.get("permissions", [])
@@ -801,14 +815,14 @@ async def create_local_database_tables():
801
815
  return runner
802
816
  }
803
817
 
804
- function startBackend(cwd, devDir, manifest, backendPort) {
818
+ function startBackend(cwd, devDir, manifest, backendPort, role) {
805
819
  const backendEntry = manifest.backend?.entry
806
820
  if (!backendEntry) return null
807
821
  const absEntry = path.resolve(cwd, backendEntry)
808
822
  if (!fs.existsSync(absEntry)) throw new Error(`backend entry not found: ${backendEntry}`)
809
823
 
810
824
  const python = ensurePythonEnv(cwd, devDir, manifest)
811
- const runner = writeBackendRunner(cwd, devDir, manifest, backendEntry, backendPort)
825
+ const runner = writeBackendRunner(cwd, devDir, manifest, backendEntry, backendPort, role)
812
826
  const sdkPath = localBackendSdkPath()
813
827
  const env = { ...process.env }
814
828
  if (sdkPath) {
@@ -823,7 +837,7 @@ function startBackend(cwd, devDir, manifest, backendPort) {
823
837
  return child
824
838
  }
825
839
 
826
- function simulatorEntrySource(cwd, pluginEntry, manifest, backendPort) {
840
+ function simulatorEntrySource(cwd, pluginEntry, manifest, backendPort, role = "owner") {
827
841
  const localConnections = loadLocalConnections(cwd, manifest)
828
842
  return `
829
843
  import React from "react"
@@ -915,11 +929,11 @@ const basePlatform = {
915
929
  org_app_store_enabled: true,
916
930
  org_enabled_agent_ids: null,
917
931
  organization_id: 1,
918
- org_role: "owner",
932
+ org_role: ${JSON.stringify(role)},
919
933
  },
920
934
  organizationId: 1,
921
935
  pluginId: ${JSON.stringify(manifest.id)},
922
- orgRole: "owner",
936
+ orgRole: ${JSON.stringify(role)},
923
937
  orgs: [{ id: 1, name: "Palette Dev", slug: "palette-dev", theme_id: "default", logo_url: null }],
924
938
  agents: [],
925
939
  permissions: ${JSON.stringify(manifest.permissions || [])},
@@ -1094,7 +1108,7 @@ function escapeHtml(value) {
1094
1108
  }[ch]))
1095
1109
  }
1096
1110
 
1097
- async function startFrontend(cwd, devDir, manifest, frontendPort, backendPort) {
1111
+ async function startFrontend(cwd, devDir, manifest, frontendPort, backendPort, role) {
1098
1112
  const entry = manifest.frontend?.entry || "./frontend/src/index.tsx"
1099
1113
  const pluginEntry = manifest.frontend?.framework === "palette-app"
1100
1114
  ? generatePaletteAppEntry(cwd, entry || "./frontend/app", path.join(devDir, "palette-app-entry.tsx"))
@@ -1104,7 +1118,7 @@ async function startFrontend(cwd, devDir, manifest, frontendPort, backendPort) {
1104
1118
  const generatedEntry = path.join(devDir, "simulator-entry.jsx")
1105
1119
  const bundlePath = path.join(devDir, "simulator.js")
1106
1120
  const cssPath = path.join(devDir, "simulator.css")
1107
- fs.writeFileSync(generatedEntry, simulatorEntrySource(cwd, absEntry, manifest, backendPort))
1121
+ fs.writeFileSync(generatedEntry, simulatorEntrySource(cwd, absEntry, manifest, backendPort, role))
1108
1122
  const buildConfig = frontendBuildConfig(cwd, { ...(manifest.frontend || {}), entry })
1109
1123
 
1110
1124
  const sseClients = new Set()
@@ -1210,15 +1224,16 @@ async function startFrontend(cwd, devDir, manifest, frontendPort, backendPort) {
1210
1224
  return { server, ctx, sseClients }
1211
1225
  }
1212
1226
 
1213
- async function startSimulator({ cwd, frontendPort, backendPort }) {
1227
+ async function startSimulator({ cwd, frontendPort, backendPort, role = "owner" }) {
1214
1228
  const manifest = loadManifest(cwd)
1215
1229
  const devDir = path.join(cwd, ".palette", "dev")
1216
1230
  fs.mkdirSync(devDir, { recursive: true })
1217
1231
 
1218
- const backend = startBackend(cwd, devDir, manifest, backendPort)
1219
- const frontend = await startFrontend(cwd, devDir, manifest, frontendPort, backendPort)
1232
+ const backend = startBackend(cwd, devDir, manifest, backendPort, role)
1233
+ const frontend = await startFrontend(cwd, devDir, manifest, frontendPort, backendPort, role)
1220
1234
 
1221
1235
  console.log("[pltt] running local SDK simulator (no Docker)")
1236
+ console.log(`[pltt] role: ${role} (ctx.org_role; change with --role owner|admin|member)`)
1222
1237
  console.log(`[pltt] app: http://localhost:${frontendPort}/`)
1223
1238
  if (backend) console.log(`[pltt] backend: http://localhost:${backendPort}/api/v1/plugins/${manifest.id}`)
1224
1239
  console.log("[pltt] logs: streaming frontend requests, frontend bundle rebuilds, and backend output")
@@ -1250,4 +1265,4 @@ async function startSimulator({ cwd, frontendPort, backendPort }) {
1250
1265
  await stop()
1251
1266
  }
1252
1267
 
1253
- module.exports = { databaseDriverDependencies, resolveDevSecrets, startSimulator, writeBackendRunner }
1268
+ module.exports = { databaseDriverDependencies, resolveDevRole, resolveDevSecrets, startSimulator, writeBackendRunner }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@palettelab/cli",
3
- "version": "0.3.74",
3
+ "version": "0.3.75",
4
4
  "description": "Developer CLI for building Palette platform plugins — no platform source access required.",
5
5
  "bin": {
6
6
  "pltt": "bin/pltt.js"
@@ -0,0 +1,3 @@
1
+ [pytest]
2
+ # The backend entry's folder is on the import path, as the platform loader puts it: tests import `main`.
3
+ pythonpath = api
@@ -1,11 +1,7 @@
1
- import importlib.util
2
- from pathlib import Path
1
+ # pytest.ini puts backend/api on the import path, as the platform loader does.
3
2
 
4
3
 
5
4
  def test_backend_entry_exports_router():
6
- entry = Path(__file__).resolve().parents[1] / "api" / "main.py"
7
- spec = importlib.util.spec_from_file_location("plugin_backend_entry", entry)
8
- assert spec and spec.loader
9
- module = importlib.util.module_from_spec(spec)
10
- spec.loader.exec_module(module)
11
- assert getattr(module, "router", None) is not None
5
+ from main import router
6
+
7
+ assert router is not None
@@ -4,7 +4,7 @@
4
4
  "private": true,
5
5
  "description": "A Palette platform plugin",
6
6
  "dependencies": {
7
- "@palettelab/sdk": "^0.1.38"
7
+ "@palettelab/sdk": "^0.1.39"
8
8
  },
9
9
  "devDependencies": {
10
10
  "typescript": "^5.0.0",
@@ -17,3 +17,8 @@ dependencies = [
17
17
  # `pltt test` ships the backend SDK on PYTHONPATH. Pin a released
18
18
  # palette-sdk package here only if you run backend tests outside the CLI.
19
19
  ]
20
+
21
+ [tool.pytest.ini_options]
22
+ # The backend entry's folder is on the import path, as the platform loader puts it (backend/pytest.ini does the same
23
+ # for runs from backend/): backend/tests import `main` directly.
24
+ pythonpath = ["backend/api"]
@@ -2,7 +2,7 @@
2
2
  "private": true,
3
3
  "type": "module",
4
4
  "dependencies": {
5
- "@palettelab/sdk": "^0.1.38",
5
+ "@palettelab/sdk": "^0.1.39",
6
6
  "react": "^19.0.0",
7
7
  "react-dom": "^19.0.0"
8
8
  }
@@ -3,7 +3,7 @@
3
3
  "version": "1.0.0",
4
4
  "private": true,
5
5
  "dependencies": {
6
- "@palettelab/sdk": "^0.1.38",
6
+ "@palettelab/sdk": "^0.1.39",
7
7
  "react": "^19.0.0"
8
8
  }
9
9
  }
@@ -2,5 +2,5 @@
2
2
  "name": "my-db-plugin",
3
3
  "version": "1.0.0",
4
4
  "private": true,
5
- "dependencies": { "@palettelab/sdk": "^0.1.38", "react": "^19.0.0" }
5
+ "dependencies": { "@palettelab/sdk": "^0.1.39", "react": "^19.0.0" }
6
6
  }
@@ -1,12 +1,12 @@
1
1
  """External-service plugin backend.
2
2
 
3
- Reads a per-org config token (set when the org installs the plugin) and
4
- forwards a request to a declared external host. The host MUST be listed
5
- in capabilities.external_network in the manifest — the platform enforces
6
- the allowlist at runtime.
3
+ Reads a per-org API token (the install-scoped EXAMPLE_API_TOKEN secret the
4
+ manifest declares, set when the org installs the plugin) and forwards a
5
+ request to a declared external host. The host MUST be listed in
6
+ capabilities.external_network in the manifest — the platform enforces the
7
+ allowlist at runtime.
7
8
  """
8
9
 
9
- import os
10
10
  from fastapi import Depends, HTTPException
11
11
 
12
12
  from palette_sdk import PluginRouter, PluginContext, get_plugin_context, require_permission
@@ -21,7 +21,8 @@ async def proxy(ctx: PluginContext = Depends(get_plugin_context)) -> dict:
21
21
  import httpx
22
22
 
23
23
  connection = await ctx.connections.status("example_oauth")
24
- token = os.environ.get("EXAMPLE_API_TOKEN")
24
+ # Declared secrets come from the install's config, never the server's environment.
25
+ token = ctx.secret("EXAMPLE_API_TOKEN")
25
26
  if not token:
26
27
  raise HTTPException(status_code=500, detail="EXAMPLE_API_TOKEN not configured")
27
28
  async with httpx.AsyncClient() as client:
@@ -2,5 +2,5 @@
2
2
  "name": "my-external-svc",
3
3
  "version": "1.0.0",
4
4
  "private": true,
5
- "dependencies": { "@palettelab/sdk": "^0.1.38", "react": "^19.0.0" }
5
+ "dependencies": { "@palettelab/sdk": "^0.1.39", "react": "^19.0.0" }
6
6
  }
@@ -24,6 +24,13 @@
24
24
  "frontend": { "entry": "./frontend/src/index.tsx", "sandbox": true },
25
25
  "backend": { "entry": "./backend/api/main.py" },
26
26
  "permissions": ["resources:read"],
27
+ "secrets": {
28
+ "EXAMPLE_API_TOKEN": {
29
+ "scope": "install",
30
+ "required": false,
31
+ "help": "API token for api.example.com, entered by the installing organization."
32
+ }
33
+ },
27
34
  "connections": [
28
35
  {
29
36
  "id": "example_oauth",
@@ -3,7 +3,7 @@
3
3
  "version": "1.0.0",
4
4
  "private": true,
5
5
  "dependencies": {
6
- "@palettelab/sdk": "^0.1.38",
6
+ "@palettelab/sdk": "^0.1.39",
7
7
  "react": "^19.0.0"
8
8
  }
9
9
  }
@@ -3,7 +3,7 @@
3
3
  "version": "1.0.0",
4
4
  "private": true,
5
5
  "dependencies": {
6
- "@palettelab/sdk": "^0.1.38",
6
+ "@palettelab/sdk": "^0.1.39",
7
7
  "react": "^19.0.0"
8
8
  },
9
9
  "devDependencies": {
@@ -3,7 +3,7 @@
3
3
  "version": "1.0.0",
4
4
  "private": true,
5
5
  "dependencies": {
6
- "@palettelab/sdk": "^0.1.38",
6
+ "@palettelab/sdk": "^0.1.39",
7
7
  "react": "^19.0.0"
8
8
  },
9
9
  "devDependencies": {
@@ -2,7 +2,7 @@
2
2
  "private": true,
3
3
  "type": "module",
4
4
  "dependencies": {
5
- "@palettelab/sdk": "^0.1.38",
5
+ "@palettelab/sdk": "^0.1.39",
6
6
  "react": "^19.0.0"
7
7
  }
8
8
  }