@palettelab/cli 0.3.73 → 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.
Files changed (29) hide show
  1. package/README.md +50 -15
  2. package/backend-sdk/palette_sdk/__init__.py +1 -1
  3. package/backend-sdk/palette_sdk/connections_generated.py +26 -0
  4. package/backend-sdk/palette_sdk/platform_services.py +73 -1
  5. package/backend-sdk/palette_sdk/plugin_context.py +8 -2
  6. package/backend-sdk/pyproject.toml +1 -1
  7. package/docs/python-backend-sdk.md +35 -11
  8. package/lib/acp.js +227 -25
  9. package/lib/agent-client.js +56 -27
  10. package/lib/cli.js +1 -0
  11. package/lib/commands/agent.js +145 -50
  12. package/lib/commands/dev.js +19 -2
  13. package/lib/connection-catalog.json +132 -0
  14. package/lib/dev-simulator.js +29 -14
  15. package/package.json +1 -1
  16. package/template-fallback/backend/pytest.ini +3 -0
  17. package/template-fallback/backend/tests/test_import.py +4 -8
  18. package/template-fallback/package.json +1 -1
  19. package/template-fallback/pyproject.toml +5 -0
  20. package/template-fallback/templates/consumer-app/package.json +1 -1
  21. package/template-fallback/templates/dashboard/package.json +1 -1
  22. package/template-fallback/templates/database/package.json +1 -1
  23. package/template-fallback/templates/external-service/backend/api/main.py +7 -6
  24. package/template-fallback/templates/external-service/package.json +1 -1
  25. package/template-fallback/templates/external-service/palette-plugin.json +7 -0
  26. package/template-fallback/templates/frontend-only/package.json +1 -1
  27. package/template-fallback/templates/next/package.json +1 -1
  28. package/template-fallback/templates/palette-app/package.json +1 -1
  29. package/template-fallback/templates/provider-app/package.json +1 -1
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
 
@@ -949,7 +955,8 @@ Drive the Palette Build Agent (the App Builder's coding agent) on the selected e
949
955
  ```bash
950
956
  # Change an app and follow the change to its end (CI)
951
957
  pltt agent run --app 42 "add a CSV export"
952
- pltt agent run --app 42 "add a CSV export" --format json --timeout 900
958
+ pltt agent run --app 42 --file change.md --json --timeout 900
959
+ git log -1 --format=%B | pltt agent run --app 42 --auto
953
960
 
954
961
  # Follow, steer and answer a session
955
962
  pltt agent sessions --app 42 [--archived] [--limit 50]
@@ -961,6 +968,7 @@ pltt agent permissions bas_123
961
968
  pltt agent permit bas_123 per_456 reject "keep dist, it is deployed"
962
969
  pltt agent questions bas_123
963
970
  pltt agent answer bas_123 que_789 "Bars"
971
+ pltt agent ask bas_123 "which files did the export change?"
964
972
 
965
973
  # Control and inspect it
966
974
  pltt agent interrupt bas_123
@@ -992,8 +1000,6 @@ pltt agent schedule bas_123 sch_1 pause|resume|delete
992
1000
  pltt agent skills
993
1001
  pltt agent models [query]
994
1002
  pltt agent mcp
995
- pltt agent config
996
- pltt agent plugins
997
1003
  pltt agent api GET /bas_123/context
998
1004
 
999
1005
  pltt agent agents
@@ -1002,15 +1008,44 @@ pltt agent edit --app 42 "add a CSV export"
1002
1008
  pltt agent init
1003
1009
  ```
1004
1010
 
1005
- `run` sends the change (it steers the agent when it is already working on the app), follows the session that carries it out until the session is idle again, and exits 0 when the agent finished (`done`), 2 when it stopped short (`blocked`, `declined`, `stalled`, `gate_rounds`, `steps`, `timeout`, `tokens`, `output_limit`, or still running at `--timeout`, default 1800 s), and 1 on errors. With `--format json` (or `--json`) it writes the edit response, then one event per line, then the final state. `run` is unattended: the agent's permission asks are denied by the platform. `edit --follow` does the same as `run`.
1011
+ `run` sends the change (it steers the agent when it is already working on the app), follows the session that carries it out until the session is idle again, and exits 0 when the agent finished (`done`), 2 when it stopped short (`blocked`, `declined`, `stalled`, `gate_rounds`, `steps`, `timeout`, `tokens`, `output_limit`, or still running at `--timeout`, default 1800 s), and 1 on errors. The change comes as words, from a file (`--file change.md`), or on standard input (`-`, `--file -`, or piped in with no words). Ctrl+C (SIGINT) and SIGTERM, which CI runners send when a job is cancelled, interrupt the session (even one still being found; a change queued behind another build stays queued) and exit 130 and 143; a second Ctrl+C ends the process at once. While it runs, the agent's text prints as it is written, a line at a time, and a running command shows its newest output line; a dropped connection picks up after the last event it saw. Without `--auto`, `run` is unattended: the platform denies the agent's permission asks and lets its questions go on with the agent's own assumption. With `--auto`, for unattended runs that should not stop at an ask, `run` counts as present and answers for you: each permission ask is allowed once (never always), and each question is answered with the agent's assumption at once instead of waiting. `edit --follow` does the same as `run`.
1006
1012
 
1007
- `attach` is the interactive follower: it streams the log, keeps the owner present (the agent's permission asks and questions wait for you instead of being decided unattended), prompts `Allow <action> on <resource>? [o]nce/[a]lways/[r]eject:` for each ask (a reject may carry a message after the letter), lists each question's options to answer by number or in your own words, sends any other line you type as a steering message, and leaves on `/exit`.
1013
+ With `--json` (or `--format json`), `run` writes one JSON object per line, each with a `type`:
1008
1014
 
1009
- `prompt` reaches a running session at its next step (`--queue` waits until the round ends) and wakes an idle one, as an edit of its app that continues the same transcript; each prompt carries a client-minted id, so a retried request is admitted once. `log` replays the durable event log and, with `--follow`, streams it until the running round ends (exit 1 when that round did not finish, 130 on Ctrl-C). `wait` returns when the session stops, with the same exit codes as `run`. `diff` prints every file's patches, step by step (`--stat`: a table of additions and deletions). `export --sanitize` drops file contents and tool outputs. Every command takes `--json` to print the raw response as one JSON line. `init` writes the platform's AGENTS.md, the Palette app contract the hosted agent follows, into a project for any coding agent.
1015
+ | `type` | Fields |
1016
+ |---|---|
1017
+ | `edit.sent` | the platform's answer to the change: `status` (`started`, `steered` or `queued`) and, when steered, `session_id` |
1018
+ | `run.following` | `session`, the build session carrying the change out, and `after`, the seq its events follow |
1019
+ | a session event | as the session's log has it. Durable events `{"type", "seq", "at", "data"}` come in seq order, without gaps or repeats. Live events `{"type", "live": true, "session", "data"}` are not stored, carry no `seq` and can be missed |
1020
+ | `run.ended` | the last line (an error instead ends the run with exit 1 and a message on stderr): `session`, `status`, `done`, `last_stop`, `summary`, `usage`, `exit_code`, and `signal` (`SIGINT` or `SIGTERM`) when a signal stopped the run |
1021
+
1022
+ The session events a script usually reads (skip any `type` it does not know, since the platform adds kinds):
1023
+
1024
+ - `text.delta` (live): `data.step`, `data.text`, the text written since the previous delta; `reasoning.delta` (live) is the same for the model's thinking. The step's whole text still comes in its `tool.called` or `text.ended`.
1025
+ - `tool.progress` (live): `data.id`, `data.name` and `data.tail`, a running command's newest output (at most 2 KB).
1026
+ - `tool.called`: `data.step`, `data.text`, `data.calls[]` (`id`, `name`); `text.ended`: `data.step`, `data.text` for a step that called no tool.
1027
+ - `tool.success` and `tool.failed`: `data.id`, `data.name`, `data.output`, `data.metadata`.
1028
+ - `step.ended`: `data.step`, `data.files[]` (`file`, `additions`, `deletions`, `status`, `patch`), `data.usage`.
1029
+ - `permission.asked` (`data.id`, `data.action`, `data.resource`), `question.asked` (`data.id`, `data.question`, `data.options`, `data.assumption`, `data.questions[]`) and their `permission.replied` and `question.replied`.
1030
+ - `retry.scheduled`: `data.attempt`, `data.seat`, `data.wait_s`, `data.next_at`.
1031
+ - `round.ended`: `data.status`, `data.stop`, `data.steps`, `data.usage` (`input`, `output`, `cache_read`, `cache_write`, `calls`).
1032
+
1033
+ ```json
1034
+ {"type":"edit.sent","status":"steered","session_id":"bas_123"}
1035
+ {"type":"run.following","session":"bas_123","after":41}
1036
+ {"type":"text.delta","live":true,"session":"bas_123","data":{"step":1,"text":"Adding the export"}}
1037
+ {"seq":42,"type":"tool.called","at":"2026-11-13T09:00:01+00:00","data":{"step":1,"text":"Adding the export.","calls":[{"id":"call_1","name":"edit"}]}}
1038
+ {"seq":47,"type":"round.ended","at":"2026-11-13T09:02:10+00:00","data":{"status":"idle","stop":"done","steps":6,"usage":{"input":81200,"output":2400,"cache_read":64000,"cache_write":9000,"calls":6}}}
1039
+ {"type":"run.ended","session":"bas_123","status":"idle","done":true,"last_stop":"done","summary":"Added a CSV export.","usage":{"input":81200,"output":2400,"cache_read":64000,"cache_write":9000,"calls":6},"exit_code":0}
1040
+ ```
1041
+
1042
+ `attach` is the interactive follower: it streams the log (the agent's text as it is written), keeps the owner present (the agent's permission asks and questions wait for you instead of being decided unattended), prompts `Allow <action> on <resource>? [o]nce/[a]lways/[r]eject:` for each ask (a reject may carry a message after the letter), lists each question's options to answer by number or in your own words, sends any other line you type as a steering message, and leaves on `/exit`.
1043
+
1044
+ `prompt` reaches a running session at its next step (`--queue` waits until the round ends) and wakes an idle one, as an edit of its app that continues the same transcript; each prompt carries a client-minted id, so a retried request is admitted once. `ask` puts a side question to a session ("which files did you change?") and prints the answer: the platform answers from the transcript, leaves the session's history as it is, and bills the session. `log` replays the durable event log and, with `--follow`, streams it until the running round ends, across dropped connections (exit 1 when that round did not finish, 130 on Ctrl-C). `wait` returns when the session stops, with the same exit codes as `run`. `diff` prints every file's patches, step by step (`--stat`: a table of additions and deletions). `export --sanitize` drops file contents and tool outputs. Every command takes `--json` to print the raw response as one JSON line. `init` writes the platform's AGENTS.md, the Palette app contract the hosted agent follows, into a project for any coding agent.
1010
1045
 
1011
1046
  #### Use the Build Agent from an ACP editor
1012
1047
 
1013
- `pltt agent acp --app <id>` is an [Agent Client Protocol](https://agentclientprotocol.com) server on stdin/stdout, so Zed and other ACP editors can drive the hosted Build Agent. A session's first prompt starts an edit of that app; later prompts go to the same build session. The editor sees the agent's messages, tool calls with their results, and its plan; the agent's permission asks come up as the editor's permission prompts (the owner counts as present while a prompt runs), and a question with choices comes up the same way, with "Let the agent decide" beside the choices; cancelling interrupts the round. `session/load` with a build session id (`bas_...`) replays that session. In Zed's `settings.json`:
1048
+ `pltt agent acp --app <id>` is an [Agent Client Protocol](https://agentclientprotocol.com) server on stdin/stdout, so Zed and other ACP editors can drive the hosted Build Agent. A session's first prompt starts an edit of that app; later prompts go to the same build session. A prompt can carry embedded files, links and up to 6 pictures (PNG, JPEG, GIF, WebP, HEIC, HEIF or AVIF, at most about 5 MB each) beside its text; a picture past those limits becomes a note to the agent that it was left out. The session has two modes: build (the default) and plan, in which each prompt goes to the read-only plan agent as a plan request (the same as starting it with `/plan `), gets a plan back and leaves the app unchanged. Modes switch between prompts, not while one runs, and a plan prompt is refused while the agent is already working on the app, since it stays read-only only in a round of its own. The editor sees the agent's messages and thinking as they are written, tool calls with their live output and results, each step's changed files as diffs, and its plan; after each prompt it gets the turn's token usage and how full the session's context is. The agent's permission asks come up as the editor's permission prompts (the owner counts as present while a prompt runs), and a question with choices comes up the same way, with "Let the agent decide" beside the choices; cancelling interrupts the round. While a prompt runs, a second prompt is refused: a message for the running turn goes through the `_session/steering` extension and reaches the agent at its next step, as an ordinary message in either mode; a steer that arrives after the round ended starts nothing, and the editor sends it as a prompt instead. `session/list` lists the app's build sessions, and `session/load` (with a replay) or `session/resume` (without) takes one up by its id (`bas_...`). In Zed's `settings.json`:
1014
1049
 
1015
1050
  ```json
1016
1051
  {
@@ -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
@@ -972,7 +979,9 @@ state = await ctx.media.status(job["request_id"], model=job["model"])
972
979
  hits = await ctx.web.search("palette os changelog", limit=5)
973
980
  text = await ctx.web.fetch("https://example.com/report.pdf")
974
981
  # render=True loads the page in a browser first, for content its scripts build
975
- # late (a shop page's size table). Tens of seconds; ignored in pltt dev.
982
+ # late (a shop page's size table). Tens of seconds; ignored in pltt dev. Calls
983
+ # that arrive together wait their turn; PlatformServiceUnavailable (retry_after
984
+ # seconds) means the server's queue for these reads is full: try again.
976
985
  page = await ctx.web.fetch("https://shop.example/product/123", render=True)
977
986
 
978
987
  # Email through the platform's provider, from its sender address under the app's name.
@@ -1276,8 +1285,9 @@ await palette.storage.upload(file, {
1276
1285
  ```
1277
1286
 
1278
1287
  Advanced provider features are still available through scoped helpers:
1279
- `ctx.redis.execute(...)` forwards Redis data-plane commands after key rewriting,
1280
- 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
1281
1291
  client for custom calls; combine it with `collection_name()`, `scoped_filter()`,
1282
1292
  `merge_filter()`, `scoped_payload()`, and `scoped_point()` to preserve isolation.
1283
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.
@@ -1328,9 +1338,23 @@ values = await ctx.redis.execute("MGET", "a", "b")
1328
1338
  await ctx.redis.execute("ZUNIONSTORE", "dest", 2, "scores:1", "scores:2")
1329
1339
  ```
1330
1340
 
1331
- Server/admin Redis commands are blocked because they would affect the shared
1332
- central Redis instance: `FLUSHDB`, `FLUSHALL`, `CONFIG`, `KEYS`, `CLUSTER`,
1333
- `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.
1334
1358
 
1335
1359
  Common `ctx.vector` commands:
1336
1360