@palettelab/cli 0.3.74 → 0.3.76
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 +15 -9
- package/backend-sdk/palette_sdk/__init__.py +1 -1
- package/backend-sdk/palette_sdk/connections_generated.py +26 -0
- package/backend-sdk/palette_sdk/platform_services.py +154 -16
- package/backend-sdk/palette_sdk/plugin_context.py +8 -2
- package/backend-sdk/pyproject.toml +1 -1
- package/docs/python-backend-sdk.md +39 -10
- package/lib/cli.js +1 -0
- package/lib/commands/dev.js +19 -2
- package/lib/connection-catalog.json +132 -0
- package/lib/dev-simulator.js +29 -14
- package/package.json +1 -1
- package/template-fallback/backend/pytest.ini +3 -0
- package/template-fallback/backend/tests/test_import.py +4 -8
- package/template-fallback/package.json +1 -1
- package/template-fallback/pyproject.toml +5 -0
- package/template-fallback/templates/consumer-app/package.json +1 -1
- package/template-fallback/templates/dashboard/package.json +1 -1
- package/template-fallback/templates/database/package.json +1 -1
- package/template-fallback/templates/external-service/backend/api/main.py +7 -6
- package/template-fallback/templates/external-service/package.json +1 -1
- package/template-fallback/templates/external-service/palette-plugin.json +7 -0
- package/template-fallback/templates/frontend-only/package.json +1 -1
- package/template-fallback/templates/next/package.json +1 -1
- package/template-fallback/templates/palette-app/package.json +1 -1
- package/template-fallback/templates/provider-app/package.json +1 -1
package/README.md
CHANGED
|
@@ -317,15 +317,15 @@ 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
|
|
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
|
|
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`.
|
|
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
|
+
- `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`), `run(model, payload, sync=True)` asks fal's synchronous endpoint for models that answer in a second or two (SAM on a click: no queue, no polls), fal's refusals carry `status_code` (`ValueError` for 4xx, `PlatformServiceUnavailable` for 5xx), `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.
|
|
331
331
|
- `pltt platform list` prints every service above with a snippet and its `pltt dev` mode; `pltt platform enable <name>` writes the manifest declaration.
|
|
@@ -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
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
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
|
-
|
|
841
|
-
`
|
|
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
|
|
|
@@ -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
|
}
|
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
|
+
import functools
|
|
6
7
|
import hashlib
|
|
7
8
|
import json
|
|
9
|
+
import logging
|
|
8
10
|
import math
|
|
9
11
|
import mimetypes
|
|
10
12
|
import re
|
|
@@ -589,6 +591,71 @@ def _stop_reason(raw: Any, has_calls: bool) -> str:
|
|
|
589
591
|
return "stop"
|
|
590
592
|
|
|
591
593
|
|
|
594
|
+
# ---- ctx.llm keyword rules shared with palette_sdk ----------------------------------
|
|
595
|
+
# What ctx.llm does with an app's extra keywords, hosted and under pltt dev alike: the block is the same text in
|
|
596
|
+
# backend/app/plugins/platform_services.py and sdk/backend/palette_sdk/platform_services.py (backend
|
|
597
|
+
# test_plugin_llm pins it).
|
|
598
|
+
#
|
|
599
|
+
# A generation keyword goes to a seat whose provider's model class takes it (checked against
|
|
600
|
+
# billing.clients.init_chat_model). Any other seat leaves it out: there it would reach the request raw and the
|
|
601
|
+
# provider would refuse the call (OpenAI refuses top_k and thinking; Anthropic seed, the penalties and logprobs).
|
|
602
|
+
# parallel_tool_calls goes with the bound tools, so a call without tools drops it.
|
|
603
|
+
_LLM_EVERY_PROVIDER = frozenset({"openai", "palette", "anthropic", "google_genai"})
|
|
604
|
+
_LLM_OPENAI_WIRE = frozenset({"openai", "palette"})
|
|
605
|
+
_LLM_KEYWORDS: dict[str, frozenset[str]] = {
|
|
606
|
+
"top_p": _LLM_EVERY_PROVIDER,
|
|
607
|
+
"stop": _LLM_EVERY_PROVIDER,
|
|
608
|
+
"reasoning_effort": _LLM_EVERY_PROVIDER,
|
|
609
|
+
"response_format": _LLM_OPENAI_WIRE | {"anthropic"},
|
|
610
|
+
"seed": _LLM_OPENAI_WIRE | {"google_genai"},
|
|
611
|
+
"frequency_penalty": _LLM_OPENAI_WIRE | {"google_genai"},
|
|
612
|
+
"presence_penalty": _LLM_OPENAI_WIRE | {"google_genai"},
|
|
613
|
+
"logprobs": _LLM_OPENAI_WIRE,
|
|
614
|
+
"top_logprobs": _LLM_OPENAI_WIRE,
|
|
615
|
+
"parallel_tool_calls": _LLM_OPENAI_WIRE | {"anthropic"},
|
|
616
|
+
"top_k": frozenset({"anthropic", "google_genai"}),
|
|
617
|
+
"thinking": frozenset({"anthropic"}),
|
|
618
|
+
}
|
|
619
|
+
# Refused with a ValueError naming it: each would send the platform's key to another endpoint, through another
|
|
620
|
+
# client, or with headers or a request body the app wrote.
|
|
621
|
+
_LLM_REFUSED_KEYWORDS = frozenset({
|
|
622
|
+
"base_url", "api_base", "openai_api_base", "anthropic_api_url", "api_key", "openai_api_key",
|
|
623
|
+
"anthropic_api_key", "google_api_key", "default_headers", "headers", "extra_headers", "http_client",
|
|
624
|
+
"http_async_client", "client", "async_client", "organization", "openai_organization", "openai_proxy",
|
|
625
|
+
"proxies", "model_kwargs", "extra_body", "default_query",
|
|
626
|
+
})
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def _llm_keywords(kwargs: dict[str, Any], max_tokens: Any, app: str) -> tuple[dict[str, Any], Any]:
|
|
630
|
+
"""(the keywords one ctx.llm call passes on, its output cap), from the call's extra keywords.
|
|
631
|
+
|
|
632
|
+
An endpoint, credential or transport keyword is a ValueError naming it. max_completion_tokens is OpenAI's
|
|
633
|
+
newer name for max_tokens and the same cap clips it (passed on raw, it would replace that cap). Anything
|
|
634
|
+
else is left out, with one warning naming the app and the keyword."""
|
|
635
|
+
refused = sorted(name for name in kwargs if name in _LLM_REFUSED_KEYWORDS)
|
|
636
|
+
if refused:
|
|
637
|
+
raise ValueError(
|
|
638
|
+
f"ctx.llm: {', '.join(map(repr, refused))} cannot be set by an app; "
|
|
639
|
+
"the platform chooses the endpoint, credentials and client"
|
|
640
|
+
)
|
|
641
|
+
if kwargs.get("max_completion_tokens") is not None:
|
|
642
|
+
max_tokens = kwargs["max_completion_tokens"]
|
|
643
|
+
dropped = sorted(name for name in kwargs if name not in _LLM_KEYWORDS and name != "max_completion_tokens")
|
|
644
|
+
if dropped:
|
|
645
|
+
logging.getLogger(__name__).warning(
|
|
646
|
+
"ctx.llm: ignored keyword(s) %s from %s", ", ".join(repr(name[:80]) for name in dropped), app
|
|
647
|
+
)
|
|
648
|
+
return {name: value for name, value in kwargs.items() if name in _LLM_KEYWORDS}, max_tokens
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _llm_keywords_for(provider: str, keywords: dict[str, Any]) -> dict[str, Any]:
|
|
652
|
+
"""The keywords a seat of `provider` takes."""
|
|
653
|
+
return {name: value for name, value in keywords.items() if provider in _LLM_KEYWORDS[name]}
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
# ---- end of ctx.llm keyword rules shared with palette_sdk ---------------------------
|
|
657
|
+
|
|
658
|
+
|
|
592
659
|
class LocalLLMService:
|
|
593
660
|
"""`ctx.llm` for pltt dev — the hosted call shapes and receipt keys.
|
|
594
661
|
|
|
@@ -687,11 +754,14 @@ class LocalLLMService:
|
|
|
687
754
|
|
|
688
755
|
def _request(self, messages, system, model, max_tokens, tools, tool_choice, kwargs) -> dict[str, Any]:
|
|
689
756
|
specs = _openai_tools(tools)
|
|
757
|
+
keywords = _llm_keywords_for("openai", kwargs) # pltt dev runs OpenAI models
|
|
758
|
+
if not specs:
|
|
759
|
+
keywords.pop("parallel_tool_calls", None) # it governs the tools; OpenAI refuses it without them
|
|
690
760
|
body: dict[str, Any] = {
|
|
691
761
|
"model": model,
|
|
692
762
|
"messages": _openai_messages(messages, system),
|
|
693
763
|
"max_completion_tokens": max_tokens,
|
|
694
|
-
**
|
|
764
|
+
**keywords,
|
|
695
765
|
}
|
|
696
766
|
if specs:
|
|
697
767
|
body["tools"] = specs
|
|
@@ -725,6 +795,8 @@ class LocalLLMService:
|
|
|
725
795
|
**kwargs: Any,
|
|
726
796
|
) -> dict[str, Any]:
|
|
727
797
|
requested = (model or "").strip() or None
|
|
798
|
+
# The hosted keyword rules, key or no key: what pltt dev accepts is never refused once published.
|
|
799
|
+
kwargs, max_tokens = _llm_keywords(kwargs, max_tokens, "this app")
|
|
728
800
|
# Same checks as hosted, stubbed or not: bad tools / tool_choice are a
|
|
729
801
|
# ValueError and fallback=False refuses what pltt dev cannot run.
|
|
730
802
|
specs = _openai_tools(tools)
|
|
@@ -775,6 +847,7 @@ class LocalLLMService:
|
|
|
775
847
|
**kwargs: Any,
|
|
776
848
|
):
|
|
777
849
|
requested = (model or "").strip() or None
|
|
850
|
+
kwargs, max_tokens = _llm_keywords(kwargs, max_tokens, "this app")
|
|
778
851
|
specs = _openai_tools(tools)
|
|
779
852
|
if specs:
|
|
780
853
|
_openai_tool_choice(tool_choice, specs)
|
|
@@ -1144,6 +1217,45 @@ _STUB_PNG = (
|
|
|
1144
1217
|
)
|
|
1145
1218
|
|
|
1146
1219
|
|
|
1220
|
+
def _hosted_error(exc: Exception) -> Exception | None:
|
|
1221
|
+
"""What hosted ctx.media raises for `exc`, or None to let `exc` go as it is. fal answering an HTTP error status
|
|
1222
|
+
is ValueError (4xx, with up to 300 characters of fal's answer) or PlatformServiceUnavailable (5xx), and both carry
|
|
1223
|
+
`status_code`, which tells "change the request" from "try again later"; an unreachable fal is
|
|
1224
|
+
PlatformServiceUnavailable."""
|
|
1225
|
+
httpx = sys.modules.get("httpx") # only a live call imports it, and only a live call raises its errors
|
|
1226
|
+
if httpx is None:
|
|
1227
|
+
return None
|
|
1228
|
+
if isinstance(exc, httpx.HTTPStatusError):
|
|
1229
|
+
status = exc.response.status_code
|
|
1230
|
+
said = f"ctx.media: fal answered HTTP {status}"
|
|
1231
|
+
if status >= 500:
|
|
1232
|
+
return PlatformServiceUnavailable(said, status_code=status)
|
|
1233
|
+
answer = exc.response.text[:300]
|
|
1234
|
+
refused = ValueError(f"{said}: {answer}" if answer else said)
|
|
1235
|
+
refused.status_code = status
|
|
1236
|
+
return refused
|
|
1237
|
+
if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout)):
|
|
1238
|
+
return PlatformServiceUnavailable("ctx.media: fal could not be reached")
|
|
1239
|
+
return None
|
|
1240
|
+
|
|
1241
|
+
|
|
1242
|
+
def _like_hosted(fn: Any) -> Any:
|
|
1243
|
+
"""A LocalMediaService call that fails the way the hosted one does (_hosted_error), so the app's `except` and
|
|
1244
|
+
its `status_code` checks behave the same under pltt dev."""
|
|
1245
|
+
|
|
1246
|
+
@functools.wraps(fn)
|
|
1247
|
+
async def call(*args: Any, **kwargs: Any) -> Any:
|
|
1248
|
+
try:
|
|
1249
|
+
return await fn(*args, **kwargs)
|
|
1250
|
+
except Exception as exc: # noqa: BLE001 — only fal's HTTP errors are translated
|
|
1251
|
+
hosted = _hosted_error(exc)
|
|
1252
|
+
if hosted is None:
|
|
1253
|
+
raise
|
|
1254
|
+
raise hosted from exc
|
|
1255
|
+
|
|
1256
|
+
return call
|
|
1257
|
+
|
|
1258
|
+
|
|
1147
1259
|
class LocalMediaService:
|
|
1148
1260
|
"""`ctx.media` for pltt dev — the same fal.ai surface as hosted.
|
|
1149
1261
|
|
|
@@ -1154,6 +1266,9 @@ class LocalMediaService:
|
|
|
1154
1266
|
"""
|
|
1155
1267
|
|
|
1156
1268
|
QUEUE_BASE = "https://queue.fal.run"
|
|
1269
|
+
# fal's synchronous endpoint, for run(sync=True): the answer comes back on the request itself.
|
|
1270
|
+
SYNC_BASE = "https://fal.run"
|
|
1271
|
+
SYNC_TIMEOUT_S = 60.0
|
|
1157
1272
|
# fal's own upload flow (fal-client "fal_v3"): trade the key for a CDN
|
|
1158
1273
|
# token, then POST the bytes. storage.fal.ai no longer resolves.
|
|
1159
1274
|
CDN_TOKEN_URL = "https://rest.fal.ai/storage/auth/token?storage_type=fal-cdn-v3"
|
|
@@ -1230,6 +1345,7 @@ class LocalMediaService:
|
|
|
1230
1345
|
"text": f"[pltt dev: no FAL_KEY] {payload.get('prompt') or payload.get('text') or ''}",
|
|
1231
1346
|
}
|
|
1232
1347
|
|
|
1348
|
+
@_like_hosted
|
|
1233
1349
|
async def submit(self, model: str, payload: dict[str, Any] | None = None, **fields: Any) -> dict[str, Any]:
|
|
1234
1350
|
"""Queue a job; returns the durable handle {request_id, model,
|
|
1235
1351
|
status_url, response_url, cancel_url}. A 429 is retried with backoff,
|
|
@@ -1240,12 +1356,30 @@ class LocalMediaService:
|
|
|
1240
1356
|
"request_id": "pltt-dev-stub", "model": model, "status_url": "", "response_url": "",
|
|
1241
1357
|
"cancel_url": "", "request": body,
|
|
1242
1358
|
}
|
|
1359
|
+
task = await self._start(self.QUEUE_BASE, model, body, 60.0)
|
|
1360
|
+
request_id = str(task.get("request_id") or "")
|
|
1361
|
+
rebuilt_status, rebuilt_response, rebuilt_cancel = self._queue_urls(model, request_id)
|
|
1362
|
+
provider_status = str(task.get("status_url") or "")
|
|
1363
|
+
provider_response = str(task.get("response_url") or "")
|
|
1364
|
+
provider_cancel = str(task.get("cancel_url") or "")
|
|
1365
|
+
return {
|
|
1366
|
+
"request_id": request_id,
|
|
1367
|
+
"model": model,
|
|
1368
|
+
"status_url": provider_status if self._fal_host_ok(provider_status) else rebuilt_status,
|
|
1369
|
+
"response_url": provider_response if self._fal_host_ok(provider_response) else rebuilt_response,
|
|
1370
|
+
"cancel_url": provider_cancel if self._fal_host_ok(provider_cancel) else rebuilt_cancel,
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
async def _start(self, base: str, model: str, body: dict[str, Any], timeout: float) -> dict[str, Any]:
|
|
1374
|
+
"""POST work to fal's queue or its synchronous endpoint (`base`), as hosted does: a 429 or a failed connect
|
|
1375
|
+
is retried with backoff, then MediaRateLimited; an answer lost after fal got the request is
|
|
1376
|
+
MediaSubmitInterrupted, never sent again."""
|
|
1243
1377
|
import httpx
|
|
1244
1378
|
|
|
1245
|
-
async with httpx.AsyncClient(timeout=
|
|
1379
|
+
async with httpx.AsyncClient(timeout=timeout, headers=self._headers()) as client:
|
|
1246
1380
|
for attempt in range(1, self.SUBMIT_ATTEMPTS + 1):
|
|
1247
1381
|
try:
|
|
1248
|
-
response = await client.post(f"{
|
|
1382
|
+
response = await client.post(f"{base}/{str(model).strip('/')}", json=body)
|
|
1249
1383
|
except (httpx.ConnectError, httpx.ConnectTimeout):
|
|
1250
1384
|
if attempt == self.SUBMIT_ATTEMPTS:
|
|
1251
1385
|
raise
|
|
@@ -1264,21 +1398,10 @@ class LocalMediaService:
|
|
|
1264
1398
|
)
|
|
1265
1399
|
await asyncio.sleep(self.RETRY_BASE_S * attempt)
|
|
1266
1400
|
response.raise_for_status()
|
|
1267
|
-
|
|
1268
|
-
request_id = str(task.get("request_id") or "")
|
|
1269
|
-
rebuilt_status, rebuilt_response, rebuilt_cancel = self._queue_urls(model, request_id)
|
|
1270
|
-
provider_status = str(task.get("status_url") or "")
|
|
1271
|
-
provider_response = str(task.get("response_url") or "")
|
|
1272
|
-
provider_cancel = str(task.get("cancel_url") or "")
|
|
1273
|
-
return {
|
|
1274
|
-
"request_id": request_id,
|
|
1275
|
-
"model": model,
|
|
1276
|
-
"status_url": provider_status if self._fal_host_ok(provider_status) else rebuilt_status,
|
|
1277
|
-
"response_url": provider_response if self._fal_host_ok(provider_response) else rebuilt_response,
|
|
1278
|
-
"cancel_url": provider_cancel if self._fal_host_ok(provider_cancel) else rebuilt_cancel,
|
|
1279
|
-
}
|
|
1401
|
+
return response.json() or {}
|
|
1280
1402
|
|
|
1281
1403
|
# `request_id=` is the keyword these took before SDK 0.1.16; still accepted.
|
|
1404
|
+
@_like_hosted
|
|
1282
1405
|
async def status(
|
|
1283
1406
|
self, request: Any = None, *, model: str | None = None, request_id: str | None = None, **params: Any
|
|
1284
1407
|
) -> dict[str, Any]:
|
|
@@ -1293,6 +1416,7 @@ class LocalMediaService:
|
|
|
1293
1416
|
response.raise_for_status()
|
|
1294
1417
|
return response.json() or {}
|
|
1295
1418
|
|
|
1419
|
+
@_like_hosted
|
|
1296
1420
|
async def result(self, request: Any = None, *, model: str | None = None, request_id: str | None = None) -> dict[str, Any]:
|
|
1297
1421
|
"""The finished output; an unfinished job raises MediaStillRunning."""
|
|
1298
1422
|
request_id, model = self._ref(request or request_id, model)
|
|
@@ -1309,6 +1433,7 @@ class LocalMediaService:
|
|
|
1309
1433
|
response.raise_for_status()
|
|
1310
1434
|
return response.json() or {}
|
|
1311
1435
|
|
|
1436
|
+
@_like_hosted
|
|
1312
1437
|
async def cancel(self, request: Any = None, *, model: str | None = None, request_id: str | None = None) -> dict[str, Any]:
|
|
1313
1438
|
if not self.live:
|
|
1314
1439
|
return {"cancelled": True, "pltt_dev_stub": True}
|
|
@@ -1320,6 +1445,7 @@ class LocalMediaService:
|
|
|
1320
1445
|
response = await client.put(cancel_url)
|
|
1321
1446
|
return {"cancelled": response.status_code < 400, "status_code": response.status_code}
|
|
1322
1447
|
|
|
1448
|
+
@_like_hosted
|
|
1323
1449
|
async def run(
|
|
1324
1450
|
self,
|
|
1325
1451
|
model: str,
|
|
@@ -1328,11 +1454,19 @@ class LocalMediaService:
|
|
|
1328
1454
|
timeout: float | None = None,
|
|
1329
1455
|
poll_interval: float | None = None,
|
|
1330
1456
|
on_status: Any = None,
|
|
1457
|
+
sync: bool = False,
|
|
1331
1458
|
**fields: Any,
|
|
1332
1459
|
) -> dict[str, Any]:
|
|
1460
|
+
"""Submit, poll to completion, return fal's JSON. `sync=True` is one request to fal's synchronous endpoint
|
|
1461
|
+
instead, for models that answer in a second or two (SAM): `timeout` (default 60 s) bounds it, and there is no
|
|
1462
|
+
handle to resume."""
|
|
1333
1463
|
body = self._merge(payload, fields)
|
|
1334
1464
|
if not self.live:
|
|
1335
1465
|
return self._stub(model, body)
|
|
1466
|
+
if sync:
|
|
1467
|
+
return await self._start(
|
|
1468
|
+
self.SYNC_BASE, model, body, float(timeout if timeout is not None else self.SYNC_TIMEOUT_S)
|
|
1469
|
+
)
|
|
1336
1470
|
import httpx
|
|
1337
1471
|
|
|
1338
1472
|
job = await self.submit(model, body)
|
|
@@ -1364,6 +1498,8 @@ class LocalMediaService:
|
|
|
1364
1498
|
raise MediaStillRunning(job["request_id"], model, **handle)
|
|
1365
1499
|
await asyncio.sleep(interval)
|
|
1366
1500
|
final = await client.get(job["response_url"])
|
|
1501
|
+
if final.status_code >= 500: # done and paid for: collect it later, as hosted
|
|
1502
|
+
raise MediaStillRunning(job["request_id"], model, **handle)
|
|
1367
1503
|
final.raise_for_status()
|
|
1368
1504
|
return final.json() or {}
|
|
1369
1505
|
|
|
@@ -1409,6 +1545,7 @@ class LocalMediaService:
|
|
|
1409
1545
|
fetched.raise_for_status()
|
|
1410
1546
|
return fetched.content, (fetched.headers.get("content-type") or "").split(";")[0].strip() or None
|
|
1411
1547
|
|
|
1548
|
+
@_like_hosted
|
|
1412
1549
|
async def upload(
|
|
1413
1550
|
self,
|
|
1414
1551
|
source: bytes | str,
|
|
@@ -1450,6 +1587,7 @@ class LocalMediaService:
|
|
|
1450
1587
|
raise RuntimeError(f"ctx.media: fal upload returned no URL ({response.text[:200]})")
|
|
1451
1588
|
return url
|
|
1452
1589
|
|
|
1590
|
+
@_like_hosted
|
|
1453
1591
|
async def save(self, url: str, *, filename: str | None = None, key: str | None = None) -> dict[str, Any]:
|
|
1454
1592
|
if self._storage is None or isinstance(self._storage, UnavailablePlatformService):
|
|
1455
1593
|
raise PlatformServiceUnavailable(
|
|
@@ -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
|
|
147
|
+
return default
|
|
142
148
|
|
|
143
149
|
def repo(self, model: type[Any]):
|
|
144
150
|
from palette_sdk.repository import OrgRepository
|
|
@@ -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
|
|
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.
|
|
894
|
-
|
|
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
|
-
#
|
|
935
|
-
#
|
|
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
|
|
@@ -968,6 +975,13 @@ except MediaStillRunning as pending:
|
|
|
968
975
|
job = await ctx.media.submit("fal-ai/kling-video/v3/pro/text-to-video", {"prompt": "…"})
|
|
969
976
|
state = await ctx.media.status(job["request_id"], model=job["model"])
|
|
970
977
|
|
|
978
|
+
# A model that answers in a second or two (SAM on a click): one request to fal's
|
|
979
|
+
# synchronous endpoint, no queue and no polls. timeout defaults to 60 s; no handle.
|
|
980
|
+
mask = await ctx.media.run("fal-ai/sam-3/image", {"image_url": url, "prompt": "shoe"}, sync=True)
|
|
981
|
+
|
|
982
|
+
# fal refusing a call: ValueError (4xx, change the request) or PlatformServiceUnavailable
|
|
983
|
+
# (5xx, try again later), both with .status_code; read it with getattr(exc, "status_code", None).
|
|
984
|
+
|
|
971
985
|
# Web search + reader (HTML tables and PDFs already handled).
|
|
972
986
|
hits = await ctx.web.search("palette os changelog", limit=5)
|
|
973
987
|
text = await ctx.web.fetch("https://example.com/report.pdf")
|
|
@@ -1278,8 +1292,9 @@ await palette.storage.upload(file, {
|
|
|
1278
1292
|
```
|
|
1279
1293
|
|
|
1280
1294
|
Advanced provider features are still available through scoped helpers:
|
|
1281
|
-
`ctx.redis.execute(...)`
|
|
1282
|
-
|
|
1295
|
+
`ctx.redis.execute(...)` runs only the data-plane commands the platform lists,
|
|
1296
|
+
with their key arguments rewritten into the app's namespace; any other command
|
|
1297
|
+
raises `ValueError` (see Provider-style Redis commands below). `ctx.vector.client()` returns the Qdrant
|
|
1283
1298
|
client for custom calls; combine it with `collection_name()`, `scoped_filter()`,
|
|
1284
1299
|
`merge_filter()`, `scoped_payload()`, and `scoped_point()` to preserve isolation.
|
|
1285
1300
|
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 +1345,23 @@ values = await ctx.redis.execute("MGET", "a", "b")
|
|
|
1330
1345
|
await ctx.redis.execute("ZUNIONSTORE", "dest", 2, "scores:1", "scores:2")
|
|
1331
1346
|
```
|
|
1332
1347
|
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
`
|
|
1348
|
+
`execute` is an allowlist: only the data-plane commands the platform lists run,
|
|
1349
|
+
each with the key positions the platform knows for it. Anything else raises
|
|
1350
|
+
`ValueError`:
|
|
1351
|
+
|
|
1352
|
+
- commands whose keys could not all be rewritten: `EVAL`, `EVALSHA`, `FCALL`,
|
|
1353
|
+
`KEYS`, `SCAN` (use `ctx.redis.scan(prefix=...)`), `RANDOMKEY`, `PUBSUB`,
|
|
1354
|
+
`SORT ... BY/GET`;
|
|
1355
|
+
- server and connection commands, which would affect the shared central Redis
|
|
1356
|
+
instance: `FLUSHDB`, `FLUSHALL`, `CONFIG`, `CLUSTER`, `SCRIPT`, `FUNCTION`,
|
|
1357
|
+
`SELECT`, `CLIENT`, and similar control-plane commands;
|
|
1358
|
+
- blocking commands, which would hold a connection every app shares: `BLPOP`,
|
|
1359
|
+
`BRPOP`, `BLMOVE`, `BRPOPLPUSH`, `BLMPOP`, `BZPOPMIN`, `XREAD`/`XREADGROUP`
|
|
1360
|
+
with `BLOCK`, `WAIT`. Hosted, `ctx.redis.xread(..., block=)` waits at most
|
|
1361
|
+
5 seconds instead.
|
|
1362
|
+
|
|
1363
|
+
The `key_positions=` and `all_keys=` keywords are refused as well: key positions
|
|
1364
|
+
come from the command, never from the caller.
|
|
1336
1365
|
|
|
1337
1366
|
Common `ctx.vector` commands:
|
|
1338
1367
|
|
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")
|
package/lib/commands/dev.js
CHANGED
|
@@ -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",
|
package/lib/dev-simulator.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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 =
|
|
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:
|
|
932
|
+
org_role: ${JSON.stringify(role)},
|
|
919
933
|
},
|
|
920
934
|
organizationId: 1,
|
|
921
935
|
pluginId: ${JSON.stringify(manifest.id)},
|
|
922
|
-
orgRole:
|
|
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,11 +1,7 @@
|
|
|
1
|
-
import
|
|
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
|
-
|
|
7
|
-
|
|
8
|
-
assert
|
|
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
|
|
@@ -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"]
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
"""External-service plugin backend.
|
|
2
2
|
|
|
3
|
-
Reads a per-org
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
the
|
|
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
|
-
|
|
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:
|
|
@@ -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",
|