@palettelab/cli 0.3.72 → 0.3.74
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 +65 -12
- package/backend-sdk/palette_sdk/__init__.py +3 -1
- package/backend-sdk/palette_sdk/manifest.py +2 -2
- package/backend-sdk/palette_sdk/platform_services.py +254 -1
- package/backend-sdk/palette_sdk/plugin_context.py +8 -0
- package/backend-sdk/pyproject.toml +1 -1
- package/docs/python-backend-sdk.md +53 -4
- package/lib/acp.js +227 -25
- package/lib/agent-client.js +56 -27
- package/lib/cli.js +7 -2
- package/lib/commands/agent.js +145 -50
- package/lib/commands/categories.js +25 -0
- package/lib/commands/doctor.js +2 -1
- package/lib/commands/platform.js +3 -2
- package/lib/commands/publish.js +7 -0
- package/lib/dev-simulator.js +8 -0
- package/lib/manifest.js +11 -1
- package/package.json +1 -1
- package/template-fallback/README.md +2 -2
- package/template-fallback/package.json +1 -1
- package/template-fallback/templates/agent-tool/palette-plugin.json +1 -1
- 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/package.json +1 -1
- package/template-fallback/templates/external-service/palette-plugin.json +1 -1
- 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
|
@@ -309,7 +309,7 @@ async def create_invoice(body: InvoiceIn, ctx: PluginContext = Depends(get_plugi
|
|
|
309
309
|
Backend SDK features for app-owned data:
|
|
310
310
|
|
|
311
311
|
- `PluginRouter`, `PluginContext`, and `get_plugin_context` provide the FastAPI route and request-context surface. A parameter annotated `ctx: PluginContext` is wired automatically — `Depends(get_plugin_context)` is still accepted and behaves identically.
|
|
312
|
-
- `PluginContext` exposes `user_id`, `organization_id`, `org_role`, `plugin_id`, `permissions`, `storage`, `ctx.db`, `ctx.jobs`, `ctx.data_rooms`, `ctx.connections`, `ctx.members`, `ctx.redis`, `ctx.vector`, `ctx.llm`, `ctx.media`, `ctx.web`, `ctx.config`, and `ctx.logger`.
|
|
312
|
+
- `PluginContext` exposes `user_id`, `organization_id`, `org_role`, `plugin_id`, `permissions`, `storage`, `ctx.db`, `ctx.jobs`, `ctx.data_rooms`, `ctx.connections`, `ctx.members`, `ctx.redis`, `ctx.vector`, `ctx.llm`, `ctx.media`, `ctx.web`, `ctx.email`, `ctx.config`, and `ctx.logger`.
|
|
313
313
|
- `ctx.db` is the full scoped SQLAlchemy `AsyncSession` for app-owned database data.
|
|
314
314
|
- `ctx.repo(Model)` gives org-safe CRUD helpers for app tables.
|
|
315
315
|
- `ctx.data_rooms` gives backend access to Palette Data Rooms without importing platform internals.
|
|
@@ -326,7 +326,8 @@ Backend SDK features for app-owned data:
|
|
|
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
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.
|
|
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
|
-
- `ctx.web` gives web search and an SSRF-guarded page reader (HTML tables and PDFs handled) when `"web"` is declared.
|
|
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
|
+
- `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.
|
|
330
331
|
- `pltt platform list` prints every service above with a snippet and its `pltt dev` mode; `pltt platform enable <name>` writes the manifest declaration.
|
|
331
332
|
- `ctx.connections` gives the viewer's OS service connections — see `pltt connections`.
|
|
332
333
|
- `@job(...)`, `JobExecution`, and `ctx.jobs` provide durable async work with retries, progress, status, and cancellation.
|
|
@@ -748,7 +749,7 @@ install-scoped values or labels/help text:
|
|
|
748
749
|
"STRIPE_SECRET": { "scope": "plugin", "required": true },
|
|
749
750
|
"DEBUG_PROBE_URL": { "scope": "dev", "required": false }
|
|
750
751
|
},
|
|
751
|
-
"platform_services": ["llm", "media", "redis", "storage", "vector", "web"]
|
|
752
|
+
"platform_services": ["email", "llm", "media", "redis", "storage", "vector", "web"]
|
|
752
753
|
}
|
|
753
754
|
```
|
|
754
755
|
|
|
@@ -770,6 +771,9 @@ Managed platform services do not require developer Redis/Qdrant keys. Declare
|
|
|
770
771
|
them and use scoped SDK clients:
|
|
771
772
|
|
|
772
773
|
```python
|
|
774
|
+
await ctx.email.send("ann@example.com", "Your order", html="<p>Thanks!</p>",
|
|
775
|
+
attachments=[{"filename": "receipt.pdf", "content": pdf_bytes}])
|
|
776
|
+
|
|
773
777
|
await ctx.redis.set("cart:123", {"items": [1, 2]}, ttl=3600)
|
|
774
778
|
cart = await ctx.redis.get("cart:123")
|
|
775
779
|
|
|
@@ -945,7 +949,8 @@ Drive the Palette Build Agent (the App Builder's coding agent) on the selected e
|
|
|
945
949
|
```bash
|
|
946
950
|
# Change an app and follow the change to its end (CI)
|
|
947
951
|
pltt agent run --app 42 "add a CSV export"
|
|
948
|
-
pltt agent run --app 42
|
|
952
|
+
pltt agent run --app 42 --file change.md --json --timeout 900
|
|
953
|
+
git log -1 --format=%B | pltt agent run --app 42 --auto
|
|
949
954
|
|
|
950
955
|
# Follow, steer and answer a session
|
|
951
956
|
pltt agent sessions --app 42 [--archived] [--limit 50]
|
|
@@ -957,6 +962,7 @@ pltt agent permissions bas_123
|
|
|
957
962
|
pltt agent permit bas_123 per_456 reject "keep dist, it is deployed"
|
|
958
963
|
pltt agent questions bas_123
|
|
959
964
|
pltt agent answer bas_123 que_789 "Bars"
|
|
965
|
+
pltt agent ask bas_123 "which files did the export change?"
|
|
960
966
|
|
|
961
967
|
# Control and inspect it
|
|
962
968
|
pltt agent interrupt bas_123
|
|
@@ -988,8 +994,6 @@ pltt agent schedule bas_123 sch_1 pause|resume|delete
|
|
|
988
994
|
pltt agent skills
|
|
989
995
|
pltt agent models [query]
|
|
990
996
|
pltt agent mcp
|
|
991
|
-
pltt agent config
|
|
992
|
-
pltt agent plugins
|
|
993
997
|
pltt agent api GET /bas_123/context
|
|
994
998
|
|
|
995
999
|
pltt agent agents
|
|
@@ -998,15 +1002,44 @@ pltt agent edit --app 42 "add a CSV export"
|
|
|
998
1002
|
pltt agent init
|
|
999
1003
|
```
|
|
1000
1004
|
|
|
1001
|
-
`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.
|
|
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. 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
|
+
|
|
1007
|
+
With `--json` (or `--format json`), `run` writes one JSON object per line, each with a `type`:
|
|
1008
|
+
|
|
1009
|
+
| `type` | Fields |
|
|
1010
|
+
|---|---|
|
|
1011
|
+
| `edit.sent` | the platform's answer to the change: `status` (`started`, `steered` or `queued`) and, when steered, `session_id` |
|
|
1012
|
+
| `run.following` | `session`, the build session carrying the change out, and `after`, the seq its events follow |
|
|
1013
|
+
| 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 |
|
|
1014
|
+
| `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 |
|
|
1015
|
+
|
|
1016
|
+
The session events a script usually reads (skip any `type` it does not know, since the platform adds kinds):
|
|
1017
|
+
|
|
1018
|
+
- `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`.
|
|
1019
|
+
- `tool.progress` (live): `data.id`, `data.name` and `data.tail`, a running command's newest output (at most 2 KB).
|
|
1020
|
+
- `tool.called`: `data.step`, `data.text`, `data.calls[]` (`id`, `name`); `text.ended`: `data.step`, `data.text` for a step that called no tool.
|
|
1021
|
+
- `tool.success` and `tool.failed`: `data.id`, `data.name`, `data.output`, `data.metadata`.
|
|
1022
|
+
- `step.ended`: `data.step`, `data.files[]` (`file`, `additions`, `deletions`, `status`, `patch`), `data.usage`.
|
|
1023
|
+
- `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`.
|
|
1024
|
+
- `retry.scheduled`: `data.attempt`, `data.seat`, `data.wait_s`, `data.next_at`.
|
|
1025
|
+
- `round.ended`: `data.status`, `data.stop`, `data.steps`, `data.usage` (`input`, `output`, `cache_read`, `cache_write`, `calls`).
|
|
1026
|
+
|
|
1027
|
+
```json
|
|
1028
|
+
{"type":"edit.sent","status":"steered","session_id":"bas_123"}
|
|
1029
|
+
{"type":"run.following","session":"bas_123","after":41}
|
|
1030
|
+
{"type":"text.delta","live":true,"session":"bas_123","data":{"step":1,"text":"Adding the export"}}
|
|
1031
|
+
{"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"}]}}
|
|
1032
|
+
{"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}}}
|
|
1033
|
+
{"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}
|
|
1034
|
+
```
|
|
1002
1035
|
|
|
1003
|
-
`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`.
|
|
1036
|
+
`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`.
|
|
1004
1037
|
|
|
1005
|
-
`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.
|
|
1038
|
+
`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.
|
|
1006
1039
|
|
|
1007
1040
|
#### Use the Build Agent from an ACP editor
|
|
1008
1041
|
|
|
1009
|
-
`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
|
|
1042
|
+
`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`:
|
|
1010
1043
|
|
|
1011
1044
|
```json
|
|
1012
1045
|
{
|
|
@@ -1108,6 +1141,7 @@ pltt platform disable web
|
|
|
1108
1141
|
| `llm` | `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` | chat with tool calls, streaming, embeddings, image generation; receipts name the model that ran |
|
|
1109
1142
|
| `media` | `FAL_KEY` | fal.ai — image, video, speech, transcription, any model fal publishes; `upload()` for private inputs |
|
|
1110
1143
|
| `web` | `TAVILY_API_KEY` / `SERPAPI_KEY` | search + SSRF-guarded page reader |
|
|
1144
|
+
| `email` | `SENDGRID_API_KEY` / SMTP login + a verified domain | `ctx.email.send(...)` — to/cc/bcc, html + text, reply_to, attachments and inline images, headers, tags; from the platform's address under the app's name |
|
|
1111
1145
|
| `storage` | an S3/GCS bucket | per-app, per-org objects with resumable uploads |
|
|
1112
1146
|
| `vector` | a Pinecone/Qdrant account | namespaced vector search |
|
|
1113
1147
|
| `redis` | `REDIS_URL` | KV, lists, sets, sorted sets, counters, locks |
|
|
@@ -1123,10 +1157,15 @@ Notes:
|
|
|
1123
1157
|
settings you already wrote are kept.
|
|
1124
1158
|
- `llm` and `media` spend the workspace's credits under its plan, seat and
|
|
1125
1159
|
member limits. `ctx.llm.spend()["workspace"]` reports what is left.
|
|
1160
|
+
- `email` is not billed. Each app has a daily recipient allowance per
|
|
1161
|
+
workspace (200 per UTC day unless the platform sets another); one message
|
|
1162
|
+
reaches up to 50 recipients and 10 MB. A wrong message raises `ValueError`; a
|
|
1163
|
+
used-up allowance or an unavailable provider raises `PlatformServiceUnavailable`.
|
|
1126
1164
|
- Under `pltt dev` there is no platform: `llm` and `media` use your own
|
|
1127
1165
|
`OPENAI_API_KEY` / `FAL_KEY` when `.env.local` has them and return
|
|
1128
|
-
deterministic stubs when it does not. `
|
|
1129
|
-
|
|
1166
|
+
deterministic stubs when it does not. `email` sends nothing: each message is
|
|
1167
|
+
checked with the hosted rules and saved to `.palette/dev-outbox/` as an `.eml`
|
|
1168
|
+
file (open it in any mail app). `pltt doctor` prints which mode each one is in.
|
|
1130
1169
|
|
|
1131
1170
|
- Bigger calls are declared on `llm`'s object form —
|
|
1132
1171
|
`{"llm": {"max_output_tokens": 12000, "max_images": 16}}` — in the manifest
|
|
@@ -1166,6 +1205,20 @@ pltt models --json --env staging
|
|
|
1166
1205
|
`budget_exhausted` (the workspace is out of credits). The same reason is what a
|
|
1167
1206
|
`fallback=False` call raises as `ModelUnavailable`.
|
|
1168
1207
|
|
|
1208
|
+
|
|
1209
|
+
### `pltt categories`
|
|
1210
|
+
|
|
1211
|
+
The App Store categories `category` in `palette-plugin.json` can name.
|
|
1212
|
+
Superadmins keep the list on the platform, so it is read from there, never
|
|
1213
|
+
shipped with the CLI. Any other value, or no category, is filed under
|
|
1214
|
+
`Other`, and `pltt publish` says where the app went. A superadmin can move
|
|
1215
|
+
the app to another category at any time.
|
|
1216
|
+
|
|
1217
|
+
```bash
|
|
1218
|
+
pltt categories # one name per line, Other last
|
|
1219
|
+
pltt categories --json --env staging
|
|
1220
|
+
```
|
|
1221
|
+
|
|
1169
1222
|
### `pltt connections`
|
|
1170
1223
|
|
|
1171
1224
|
Use the third-party services the OS already holds — Gmail, Drive, Calendar,
|
|
@@ -11,6 +11,7 @@ from palette_sdk.notifications import NotificationRecipient, NotificationsClient
|
|
|
11
11
|
from palette_sdk.organization import OrganizationInfo
|
|
12
12
|
from palette_sdk.talk import TalkClient
|
|
13
13
|
from palette_sdk.platform_services import (
|
|
14
|
+
LocalEmailService,
|
|
14
15
|
LocalLLMService,
|
|
15
16
|
LocalMediaService,
|
|
16
17
|
LocalRedisService,
|
|
@@ -90,6 +91,7 @@ __all__ = [
|
|
|
90
91
|
"NotificationsClient",
|
|
91
92
|
"NotificationRecipient",
|
|
92
93
|
"TalkClient",
|
|
94
|
+
"LocalEmailService",
|
|
93
95
|
"LocalLLMService",
|
|
94
96
|
"LocalMediaService",
|
|
95
97
|
"LocalRedisService",
|
|
@@ -155,4 +157,4 @@ __all__ = [
|
|
|
155
157
|
"LocalStorageService",
|
|
156
158
|
]
|
|
157
159
|
|
|
158
|
-
__version__ = "0.1.
|
|
160
|
+
__version__ = "0.1.21"
|
|
@@ -330,7 +330,7 @@ class PluginManifest(BaseModel):
|
|
|
330
330
|
version: str = "1.0.0"
|
|
331
331
|
data_scope: Literal["personal", "organization"] = "personal"
|
|
332
332
|
developer: str = ""
|
|
333
|
-
category: str = "
|
|
333
|
+
category: str = "Other" # the store files an app with no registered category under Other
|
|
334
334
|
tagline: str = ""
|
|
335
335
|
description: str = ""
|
|
336
336
|
icon: str = "Puzzle"
|
|
@@ -352,7 +352,7 @@ class PluginManifest(BaseModel):
|
|
|
352
352
|
requires: RequiresSpec | None = None
|
|
353
353
|
consumes: ConsumesSpec | None = None
|
|
354
354
|
mcp: McpSpec | None = None
|
|
355
|
-
platform_services: list[Literal["llm", "media", "redis", "storage", "vector", "web"]] | dict[str, PlatformServiceSpec] = Field(default_factory=list)
|
|
355
|
+
platform_services: list[Literal["email", "llm", "media", "redis", "storage", "vector", "web"]] | dict[str, PlatformServiceSpec] = Field(default_factory=list)
|
|
356
356
|
rating: float = 0.0
|
|
357
357
|
reviews: int = 0
|
|
358
358
|
featured: bool = False
|
|
@@ -6,10 +6,16 @@ import asyncio
|
|
|
6
6
|
import hashlib
|
|
7
7
|
import json
|
|
8
8
|
import math
|
|
9
|
+
import mimetypes
|
|
10
|
+
import re
|
|
9
11
|
import sys
|
|
10
12
|
import time
|
|
11
13
|
import types
|
|
14
|
+
import uuid
|
|
12
15
|
from dataclasses import dataclass, field
|
|
16
|
+
from email.message import EmailMessage
|
|
17
|
+
from email.utils import formataddr, parseaddr
|
|
18
|
+
from pathlib import Path
|
|
13
19
|
from typing import Any
|
|
14
20
|
|
|
15
21
|
|
|
@@ -874,7 +880,10 @@ class LocalWebService:
|
|
|
874
880
|
|
|
875
881
|
return {"results": await asyncio.to_thread(_run)}
|
|
876
882
|
|
|
877
|
-
async def fetch(self, url: str) -> str:
|
|
883
|
+
async def fetch(self, url: str, *, render: bool = False) -> str:
|
|
884
|
+
"""Hosted, `render=True` loads the page in a browser first, for content
|
|
885
|
+
its scripts build late. pltt dev has no browser: the flag is accepted
|
|
886
|
+
and the page comes back as fetched."""
|
|
878
887
|
import httpx
|
|
879
888
|
|
|
880
889
|
async with httpx.AsyncClient(timeout=20, follow_redirects=True) as client:
|
|
@@ -883,6 +892,250 @@ class LocalWebService:
|
|
|
883
892
|
return response.text
|
|
884
893
|
|
|
885
894
|
|
|
895
|
+
# ---- email rules shared with palette_sdk --------------------------------------
|
|
896
|
+
# ctx.email checks a message with the same rules hosted and under pltt dev, so a
|
|
897
|
+
# message pltt dev accepts is never refused once the app is published. The block
|
|
898
|
+
# is the same text in backend/app/plugins/platform_services.py and
|
|
899
|
+
# sdk/backend/palette_sdk/platform_services.py (backend test_plugin_email pins it).
|
|
900
|
+
EMAIL_MAX_RECIPIENTS = 50 # to + cc + bcc of one message
|
|
901
|
+
EMAIL_MAX_BYTES = 10 * 1024 * 1024 # bodies + attachments before encoding; fits every major inbox
|
|
902
|
+
_EMAIL_ADDRESS_RE = re.compile(r"^[^\s@<>()\[\]\\,;:\"]{1,64}@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$")
|
|
903
|
+
_EMAIL_HEADER_RE = re.compile(r"^[A-Za-z0-9-]{1,64}$")
|
|
904
|
+
_EMAIL_CONTENT_ID_RE = re.compile(r"^[A-Za-z0-9._@-]{1,100}$")
|
|
905
|
+
_EMAIL_MIME_RE = re.compile(r"^[A-Za-z0-9.+-]+/[A-Za-z0-9.+-]+$")
|
|
906
|
+
# Set by the provider, or they would let one message pass itself off as another.
|
|
907
|
+
_EMAIL_RESERVED_HEADERS = frozenset({
|
|
908
|
+
"bcc", "cc", "content-transfer-encoding", "content-type", "date", "dkim-signature", "from",
|
|
909
|
+
"message-id", "mime-version", "received", "reply-to", "return-path", "sender", "subject", "to",
|
|
910
|
+
"x-sg-eid", "x-sg-id",
|
|
911
|
+
})
|
|
912
|
+
# Files Gmail and Outlook refuse to deliver: refused here instead of as a bounce.
|
|
913
|
+
_EMAIL_BLOCKED_EXTENSIONS = frozenset({
|
|
914
|
+
"ade", "adp", "apk", "appx", "bat", "cab", "chm", "cmd", "com", "cpl", "dll", "dmg", "exe", "hta",
|
|
915
|
+
"ins", "iso", "isp", "jar", "jnlp", "js", "jse", "lib", "lnk", "mde", "msc", "msi", "msix", "msp",
|
|
916
|
+
"mst", "nsh", "pif", "ps1", "scr", "sct", "shb", "sys", "vb", "vbe", "vbs", "vhd", "vxd", "wsc",
|
|
917
|
+
"wsf", "wsh", "xll",
|
|
918
|
+
})
|
|
919
|
+
_EMAIL_ATTACHMENT_KEYS = frozenset({"filename", "content", "content_type", "content_id"})
|
|
920
|
+
|
|
921
|
+
|
|
922
|
+
def _email_line(value: Any, label: str, limit: int) -> str:
|
|
923
|
+
"""One header's worth of text: a line break here would forge headers."""
|
|
924
|
+
if not isinstance(value, str) or "\r" in value or "\n" in value or len(value) > limit:
|
|
925
|
+
raise ValueError(f"ctx.email: {label} must be one line of text, at most {limit} characters")
|
|
926
|
+
return value.strip()
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def _email_name(value: Any, label: str) -> str:
|
|
930
|
+
# SendGrid silently drops a message whose recipient name holds a comma or a
|
|
931
|
+
# semicolon, so names lose both here, hosted and under pltt dev alike.
|
|
932
|
+
return " ".join(_email_line(value or "", label, 100).replace(",", " ").replace(";", " ").split())
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
def _email_addresses(value: Any, label: str) -> list[dict[str, str]]:
|
|
936
|
+
"""'a@x.com', 'Ann <a@x.com>', {"email": ..., "name": ...}, or a list of those."""
|
|
937
|
+
if value is None:
|
|
938
|
+
return []
|
|
939
|
+
out = []
|
|
940
|
+
for item in value if isinstance(value, (list, tuple)) else [value]:
|
|
941
|
+
if isinstance(item, dict):
|
|
942
|
+
name, address = item.get("name"), item.get("email")
|
|
943
|
+
elif isinstance(item, str) and item.count("@") == 1:
|
|
944
|
+
name, address = parseaddr(item)
|
|
945
|
+
else:
|
|
946
|
+
raise ValueError(
|
|
947
|
+
f"ctx.email: each {label} entry is one address ('a@x.com', 'Ann <a@x.com>' or "
|
|
948
|
+
f'{{"email": ..., "name": ...}}) — pass a list for several, got {item!r}'
|
|
949
|
+
)
|
|
950
|
+
address = _email_line(address, f"{label} address", 254)
|
|
951
|
+
if not _EMAIL_ADDRESS_RE.match(address):
|
|
952
|
+
raise ValueError(f"ctx.email: {label} has an invalid address: {address!r}")
|
|
953
|
+
entry = {"email": address}
|
|
954
|
+
if name := _email_name(name, f"{label} name"):
|
|
955
|
+
entry["name"] = name
|
|
956
|
+
out.append(entry)
|
|
957
|
+
return out
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
def _email_message(
|
|
961
|
+
to: Any,
|
|
962
|
+
subject: Any,
|
|
963
|
+
*,
|
|
964
|
+
html: Any = None,
|
|
965
|
+
text: Any = None,
|
|
966
|
+
cc: Any = None,
|
|
967
|
+
bcc: Any = None,
|
|
968
|
+
reply_to: Any = None,
|
|
969
|
+
from_name: Any = None,
|
|
970
|
+
attachments: Any = None,
|
|
971
|
+
headers: Any = None,
|
|
972
|
+
tags: Any = None,
|
|
973
|
+
) -> dict[str, Any]:
|
|
974
|
+
"""The checked, normalized message; ValueError names the first problem.
|
|
975
|
+
|
|
976
|
+
An address repeated across to/cc/bcc is kept once, where it first appears
|
|
977
|
+
(the provider refuses duplicates).
|
|
978
|
+
"""
|
|
979
|
+
seen: set[str] = set()
|
|
980
|
+
lists: dict[str, list[dict[str, str]]] = {}
|
|
981
|
+
for label, value in (("to", to), ("cc", cc), ("bcc", bcc)):
|
|
982
|
+
lists[label] = []
|
|
983
|
+
for entry in _email_addresses(value, label):
|
|
984
|
+
if entry["email"].lower() not in seen:
|
|
985
|
+
seen.add(entry["email"].lower())
|
|
986
|
+
lists[label].append(entry)
|
|
987
|
+
if not lists["to"]:
|
|
988
|
+
raise ValueError("ctx.email: to needs at least one address")
|
|
989
|
+
if len(seen) > EMAIL_MAX_RECIPIENTS:
|
|
990
|
+
raise ValueError(f"ctx.email: {len(seen)} recipients; one message reaches at most {EMAIL_MAX_RECIPIENTS} (to + cc + bcc)")
|
|
991
|
+
replies = _email_addresses(reply_to, "reply_to")
|
|
992
|
+
if len(replies) > 1:
|
|
993
|
+
raise ValueError("ctx.email: reply_to takes one address")
|
|
994
|
+
subject = _email_line(subject, "subject", 998)
|
|
995
|
+
if not subject:
|
|
996
|
+
raise ValueError("ctx.email: subject is required")
|
|
997
|
+
bodies = {}
|
|
998
|
+
for label, value in (("html", html), ("text", text)):
|
|
999
|
+
if value is not None and not isinstance(value, str):
|
|
1000
|
+
raise ValueError(f"ctx.email: {label} must be a string")
|
|
1001
|
+
bodies[label] = value or None
|
|
1002
|
+
if not bodies["html"] and not bodies["text"]:
|
|
1003
|
+
raise ValueError("ctx.email: pass html, text, or both")
|
|
1004
|
+
if headers is not None and not isinstance(headers, dict):
|
|
1005
|
+
raise ValueError("ctx.email: headers must be a dict of header name to value")
|
|
1006
|
+
clean_headers = {}
|
|
1007
|
+
for name, value in (headers or {}).items():
|
|
1008
|
+
if not isinstance(name, str) or not _EMAIL_HEADER_RE.match(name) or name.lower() in _EMAIL_RESERVED_HEADERS:
|
|
1009
|
+
raise ValueError(f"ctx.email: header {name!r} cannot be set by an app")
|
|
1010
|
+
clean_headers[name] = _email_line(value, f"header {name}", 998)
|
|
1011
|
+
tags = [] if tags is None else tags
|
|
1012
|
+
if not isinstance(tags, (list, tuple)) or len(tags) > 10 or not all(
|
|
1013
|
+
isinstance(tag, str) and tag.strip() and tag.isascii() for tag in tags
|
|
1014
|
+
):
|
|
1015
|
+
raise ValueError("ctx.email: tags are a list of up to 10 non-empty ASCII strings")
|
|
1016
|
+
tags = list(dict.fromkeys(_email_line(tag, "tag", 255) for tag in tags))
|
|
1017
|
+
if attachments is not None and not isinstance(attachments, (list, tuple)):
|
|
1018
|
+
raise ValueError("ctx.email: attachments must be a list")
|
|
1019
|
+
files = []
|
|
1020
|
+
size = sum(len(body.encode("utf-8")) for body in bodies.values() if body)
|
|
1021
|
+
for item in attachments or []:
|
|
1022
|
+
if not isinstance(item, dict) or set(item) - _EMAIL_ATTACHMENT_KEYS:
|
|
1023
|
+
raise ValueError(
|
|
1024
|
+
'ctx.email: each attachment is {"filename": ..., "content": bytes or str, '
|
|
1025
|
+
'"content_type": optional, "content_id": optional, for inline <img src="cid:...">}'
|
|
1026
|
+
)
|
|
1027
|
+
filename = _email_line(item.get("filename"), "attachment filename", 255).replace("\\", "/").rsplit("/", 1)[-1]
|
|
1028
|
+
if not filename:
|
|
1029
|
+
raise ValueError("ctx.email: attachment filename is required")
|
|
1030
|
+
extension = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
|
1031
|
+
if extension in _EMAIL_BLOCKED_EXTENSIONS:
|
|
1032
|
+
raise ValueError(f"ctx.email: {filename}: mail servers refuse .{extension} attachments")
|
|
1033
|
+
content = item.get("content")
|
|
1034
|
+
if isinstance(content, str):
|
|
1035
|
+
content = content.encode("utf-8")
|
|
1036
|
+
elif isinstance(content, (bytearray, memoryview)):
|
|
1037
|
+
content = bytes(content)
|
|
1038
|
+
if not isinstance(content, bytes) or not content:
|
|
1039
|
+
raise ValueError(f"ctx.email: attachment {filename} needs non-empty content (bytes, or str sent as UTF-8)")
|
|
1040
|
+
content_type = item.get("content_type") or mimetypes.guess_type(filename)[0] or "application/octet-stream"
|
|
1041
|
+
if not isinstance(content_type, str) or not _EMAIL_MIME_RE.match(content_type):
|
|
1042
|
+
raise ValueError(f"ctx.email: attachment {filename} has an invalid content_type: {content_type!r}")
|
|
1043
|
+
content_id = item.get("content_id")
|
|
1044
|
+
if content_id is not None and not (isinstance(content_id, str) and _EMAIL_CONTENT_ID_RE.match(content_id)):
|
|
1045
|
+
raise ValueError(f"ctx.email: attachment {filename} content_id may use only letters, digits and ._@-")
|
|
1046
|
+
size += len(content)
|
|
1047
|
+
files.append({"filename": filename, "content": content, "content_type": content_type, "content_id": content_id})
|
|
1048
|
+
if size > EMAIL_MAX_BYTES:
|
|
1049
|
+
raise ValueError(f"ctx.email: the message is {size} bytes; bodies and attachments may total {EMAIL_MAX_BYTES}")
|
|
1050
|
+
return {
|
|
1051
|
+
"from_name": _email_name(from_name, "from_name"),
|
|
1052
|
+
"to": lists["to"],
|
|
1053
|
+
"cc": lists["cc"],
|
|
1054
|
+
"bcc": lists["bcc"],
|
|
1055
|
+
"reply_to": replies[0] if replies else None,
|
|
1056
|
+
"subject": subject,
|
|
1057
|
+
"text": bodies["text"],
|
|
1058
|
+
"html": bodies["html"],
|
|
1059
|
+
"attachments": files,
|
|
1060
|
+
"headers": clean_headers,
|
|
1061
|
+
"tags": tags,
|
|
1062
|
+
"recipients": len(seen),
|
|
1063
|
+
}
|
|
1064
|
+
# ---- end of email rules shared with palette_sdk -------------------------------
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
class LocalEmailService:
|
|
1068
|
+
"""`ctx.email` for pltt dev: checked with the hosted rules, never sent.
|
|
1069
|
+
|
|
1070
|
+
Each message is written to `outbox` as an .eml file (open it in any mail
|
|
1071
|
+
app to see the bodies, attachments and inline images) and the file comes
|
|
1072
|
+
back as `path`. Hosted, the platform's email provider sends it from the
|
|
1073
|
+
platform's address under the app's name, within a daily recipient
|
|
1074
|
+
allowance per workspace.
|
|
1075
|
+
"""
|
|
1076
|
+
|
|
1077
|
+
def __init__(self, outbox: str | Path = ".palette/dev-outbox", *, app_name: str = "Palette app"):
|
|
1078
|
+
self.outbox = Path(outbox)
|
|
1079
|
+
self.app_name = app_name
|
|
1080
|
+
|
|
1081
|
+
async def send(
|
|
1082
|
+
self,
|
|
1083
|
+
to: Any,
|
|
1084
|
+
subject: str,
|
|
1085
|
+
*,
|
|
1086
|
+
html: str | None = None,
|
|
1087
|
+
text: str | None = None,
|
|
1088
|
+
cc: Any = None,
|
|
1089
|
+
bcc: Any = None,
|
|
1090
|
+
reply_to: Any = None,
|
|
1091
|
+
from_name: str | None = None,
|
|
1092
|
+
attachments: list[dict[str, Any]] | None = None,
|
|
1093
|
+
headers: dict[str, str] | None = None,
|
|
1094
|
+
tags: list[str] | None = None,
|
|
1095
|
+
) -> dict[str, Any]:
|
|
1096
|
+
"""Same arguments, checks and errors as hosted ctx.email.send; returns
|
|
1097
|
+
{"id", "recipients", "path"} where hosted returns {"id", "recipients"}."""
|
|
1098
|
+
message = _email_message(
|
|
1099
|
+
to, subject, html=html, text=text, cc=cc, bcc=bcc, reply_to=reply_to,
|
|
1100
|
+
from_name=from_name or self.app_name, attachments=attachments, headers=headers, tags=tags,
|
|
1101
|
+
)
|
|
1102
|
+
message_id = f"local-{uuid.uuid4().hex[:16]}"
|
|
1103
|
+
mime = EmailMessage()
|
|
1104
|
+
mime["Message-ID"] = f"<{message_id}@palette.local>"
|
|
1105
|
+
mime["From"] = formataddr((message["from_name"], "no-reply@palette.local"))
|
|
1106
|
+
for header, key in (("To", "to"), ("Cc", "cc"), ("Bcc", "bcc")):
|
|
1107
|
+
if message[key]:
|
|
1108
|
+
mime[header] = ", ".join(formataddr((entry.get("name", ""), entry["email"])) for entry in message[key])
|
|
1109
|
+
if message["reply_to"]:
|
|
1110
|
+
mime["Reply-To"] = formataddr((message["reply_to"].get("name", ""), message["reply_to"]["email"]))
|
|
1111
|
+
mime["Subject"] = message["subject"]
|
|
1112
|
+
if message["tags"]:
|
|
1113
|
+
mime["X-Palette-Tags"] = ", ".join(message["tags"])
|
|
1114
|
+
for name, value in message["headers"].items():
|
|
1115
|
+
mime[name] = value
|
|
1116
|
+
if message["text"]:
|
|
1117
|
+
mime.set_content(message["text"])
|
|
1118
|
+
if message["html"]:
|
|
1119
|
+
mime.add_alternative(message["html"], subtype="html")
|
|
1120
|
+
else:
|
|
1121
|
+
mime.set_content(message["html"], subtype="html")
|
|
1122
|
+
for item in message["attachments"]:
|
|
1123
|
+
maintype, subtype = item["content_type"].split("/", 1)
|
|
1124
|
+
mime.add_attachment(
|
|
1125
|
+
item["content"],
|
|
1126
|
+
maintype=maintype,
|
|
1127
|
+
subtype=subtype,
|
|
1128
|
+
filename=item["filename"],
|
|
1129
|
+
disposition="inline" if item["content_id"] else "attachment",
|
|
1130
|
+
cid=f"<{item['content_id']}>" if item["content_id"] else None,
|
|
1131
|
+
)
|
|
1132
|
+
self.outbox.mkdir(parents=True, exist_ok=True)
|
|
1133
|
+
path = self.outbox / f"{time.strftime('%Y%m%d-%H%M%S')}-{message_id}.eml"
|
|
1134
|
+
path.write_bytes(bytes(mime))
|
|
1135
|
+
print(f"[pltt] ctx.email: {message['subject']!r} to {message['recipients']} recipient(s) saved to {path}, not sent")
|
|
1136
|
+
return {"id": message_id, "recipients": message["recipients"], "path": str(path)}
|
|
1137
|
+
|
|
1138
|
+
|
|
886
1139
|
# 1x1 transparent PNG. Enough for a stubbed render to flow through an <img>
|
|
887
1140
|
# and any "did I get a URL back" branch without a network call.
|
|
888
1141
|
_STUB_PNG = (
|
|
@@ -65,6 +65,11 @@ class PluginContext:
|
|
|
65
65
|
publishes, with the payload passed through untouched; `upload()`
|
|
66
66
|
puts private files on fal's CDN, `submit()` returns a durable
|
|
67
67
|
handle. Needs platform_services: ["media"]; no FAL_KEY of its own.
|
|
68
|
+
email: Send email through the platform's email provider —
|
|
69
|
+
`await ctx.email.send(to, subject, html=..., text=..., cc=...,
|
|
70
|
+
bcc=..., reply_to=..., from_name=..., attachments=[...],
|
|
71
|
+
headers=..., tags=...)`; from the platform's address under the
|
|
72
|
+
app's name, no SendGrid key of its own. platform_services: ["email"].
|
|
68
73
|
"""
|
|
69
74
|
db: AsyncSession
|
|
70
75
|
user_id: str
|
|
@@ -90,6 +95,8 @@ class PluginContext:
|
|
|
90
95
|
# fal.ai on the platform's key — any model, any payload, no FAL_KEY of your
|
|
91
96
|
# own. platform_services: ["media"].
|
|
92
97
|
media: Any = field(default_factory=lambda: UnavailablePlatformService("media"))
|
|
98
|
+
# The platform's email provider — platform_services: ["email"].
|
|
99
|
+
email: Any = field(default_factory=lambda: UnavailablePlatformService("email"))
|
|
93
100
|
events: EventPublisher = field(default_factory=EventPublisher)
|
|
94
101
|
jobs: JobsClient = field(default_factory=JobsClient)
|
|
95
102
|
config: dict[str, Any] = field(default_factory=dict)
|
|
@@ -183,6 +190,7 @@ async def get_plugin_context(request: Request) -> PluginContext:
|
|
|
183
190
|
llm=getattr(state, "llm", None) or UnavailablePlatformService("llm"),
|
|
184
191
|
web=getattr(state, "web", None) or UnavailablePlatformService("web"),
|
|
185
192
|
media=getattr(state, "media", None) or UnavailablePlatformService("media"),
|
|
193
|
+
email=getattr(state, "email", None) or UnavailablePlatformService("email"),
|
|
186
194
|
events=EventPublisher(getattr(state, "plugin_events", None)),
|
|
187
195
|
jobs=JobsClient(getattr(state, "plugin_jobs", None)),
|
|
188
196
|
config=getattr(state, "plugin_config", {}),
|
|
@@ -136,8 +136,9 @@ Available context values:
|
|
|
136
136
|
| `ctx.redis` | Plugin/org-scoped Redis-style service when `platform_services` includes `redis` |
|
|
137
137
|
| `ctx.vector` | Plugin/org-scoped vector service when `platform_services` includes `vector` |
|
|
138
138
|
| `ctx.llm` | The platform's own model keys, billed to the workspace's credits, when `platform_services` includes `llm` |
|
|
139
|
-
| `ctx.web` | Web search + SSRF-guarded page reader when `platform_services` includes `web` |
|
|
139
|
+
| `ctx.web` | Web search + SSRF-guarded page reader (`fetch(url, render=True)` for pages built by their scripts) when `platform_services` includes `web` |
|
|
140
140
|
| `ctx.media` | fal.ai on the platform's key — any model, any payload — when `platform_services` includes `media` |
|
|
141
|
+
| `ctx.email` | Send email through the platform's provider (to/cc/bcc, html + text, reply_to, attachments, inline images, headers, tags) when `platform_services` includes `email` |
|
|
141
142
|
| `ctx.config` | App install/config values |
|
|
142
143
|
| `ctx.logger` | Runtime logger for backend code |
|
|
143
144
|
| `ctx.repo(Model)` | Org-safe CRUD helper for app-owned tables |
|
|
@@ -171,9 +172,9 @@ These are the public Python helpers exported by `palette_sdk`.
|
|
|
171
172
|
| `ensure_org_rls(op, table)` | Alembic helper that enables org row-level security |
|
|
172
173
|
| `plugin_safe_id(...)`, `plugin_schema(...)`, `plugin_table_prefix(...)` | Manifest id to database-safe naming helpers |
|
|
173
174
|
| `get_config(ctx, key)`, `require_config(ctx, key)` | Functional form of config reads when not using `ctx.config_value(...)` |
|
|
174
|
-
| `ctx.llm`, `ctx.media`, `ctx.web` | The platform's model, fal.ai
|
|
175
|
+
| `ctx.llm`, `ctx.media`, `ctx.web`, `ctx.email` | The platform's model, fal.ai, web-search and email-provider keys, declared in `platform_services` |
|
|
175
176
|
| `MediaStillRunning` | `ctx.media.run` gave up waiting; carries `request_id` to collect the render later |
|
|
176
|
-
| `LocalLLMService`, `LocalMediaService`, `LocalWebService`, `LocalRedisService`, `LocalVectorService`, `LocalStorageService` | Local `pltt dev` service emulators and test fakes |
|
|
177
|
+
| `LocalLLMService`, `LocalMediaService`, `LocalWebService`, `LocalEmailService`, `LocalRedisService`, `LocalVectorService`, `LocalStorageService` | Local `pltt dev` service emulators and test fakes |
|
|
177
178
|
| `McpClient`, `mcp_tool(...)`, `mcp_resource(...)`, `mcp_prompt(...)` | Provide and consume MCP tools, resources and prompts |
|
|
178
179
|
| `PlatformServiceUnavailable`, `UnavailablePlatformService` | Clear errors when an undeclared platform service is used |
|
|
179
180
|
| `LifecycleHooks` | Install/update/enable/disable/uninstall callbacks |
|
|
@@ -898,7 +899,7 @@ declaration for you:
|
|
|
898
899
|
|
|
899
900
|
```json
|
|
900
901
|
{
|
|
901
|
-
"platform_services": ["llm", "media", "redis", "storage", "vector", "web"]
|
|
902
|
+
"platform_services": ["email", "llm", "media", "redis", "storage", "vector", "web"]
|
|
902
903
|
}
|
|
903
904
|
```
|
|
904
905
|
|
|
@@ -970,6 +971,26 @@ state = await ctx.media.status(job["request_id"], model=job["model"])
|
|
|
970
971
|
# Web search + reader (HTML tables and PDFs already handled).
|
|
971
972
|
hits = await ctx.web.search("palette os changelog", limit=5)
|
|
972
973
|
text = await ctx.web.fetch("https://example.com/report.pdf")
|
|
974
|
+
# 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. Calls
|
|
976
|
+
# that arrive together wait their turn; PlatformServiceUnavailable (retry_after
|
|
977
|
+
# seconds) means the server's queue for these reads is full: try again.
|
|
978
|
+
page = await ctx.web.fetch("https://shop.example/product/123", render=True)
|
|
979
|
+
|
|
980
|
+
# Email through the platform's provider, from its sender address under the app's name.
|
|
981
|
+
# Recipients: "a@x.com", "Ann <a@x.com>", {"email", "name"} or a list (50 max across to/cc/bcc).
|
|
982
|
+
# Attachments: bytes or str (UTF-8), optional content_type; content_id = inline <img src="cid:...">.
|
|
983
|
+
# ValueError = the message is wrong; PlatformServiceUnavailable = daily allowance used up or provider down.
|
|
984
|
+
await ctx.email.send(
|
|
985
|
+
["Ann <ann@example.com>"], "Invoice 42",
|
|
986
|
+
html='<p>Attached.</p><img src="cid:logo">', text="Attached.",
|
|
987
|
+
cc="finance@example.com", bcc=["audit@acme.io"], reply_to="billing@acme.io", from_name="Acme Billing",
|
|
988
|
+
attachments=[
|
|
989
|
+
{"filename": "invoice-42.pdf", "content": pdf_bytes},
|
|
990
|
+
{"filename": "logo.png", "content": logo_bytes, "content_id": "logo"},
|
|
991
|
+
],
|
|
992
|
+
headers={"X-Invoice-Id": "42"}, tags=["invoice"],
|
|
993
|
+
) # pltt dev: nothing is sent; the message is saved to .palette/dev-outbox/*.eml
|
|
973
994
|
|
|
974
995
|
await ctx.redis.set("cache:summary", {"ready": True}, ttl=600)
|
|
975
996
|
value = await ctx.redis.get("cache:summary")
|
|
@@ -1000,6 +1021,34 @@ Under `pltt dev` there is no platform, so these run against your own
|
|
|
1000
1021
|
deterministic stubs when it does not — the app's code path is exercisable with
|
|
1001
1022
|
zero setup either way. `pltt doctor` prints which mode each service is in.
|
|
1002
1023
|
|
|
1024
|
+
### Email — `ctx.email`
|
|
1025
|
+
|
|
1026
|
+
`await ctx.email.send(to, subject, *, html=None, text=None, cc=None, bcc=None,
|
|
1027
|
+
reply_to=None, from_name=None, attachments=None, headers=None, tags=None)`
|
|
1028
|
+
sends one email through the platform's email provider and returns
|
|
1029
|
+
`{"id": <provider message id>, "recipients": <n>}`.
|
|
1030
|
+
|
|
1031
|
+
| Argument | Accepts |
|
|
1032
|
+
|---|---|
|
|
1033
|
+
| `to`, `cc`, `bcc` | `"a@x.com"`, `"Ann <a@x.com>"`, `{"email": ..., "name": ...}`, or a list of those; at most 50 across all three, an address repeated across them is sent once, commas and semicolons are dropped from names |
|
|
1034
|
+
| `subject` | One line, required |
|
|
1035
|
+
| `html`, `text` | Either or both; `text` is the plain-text alternative |
|
|
1036
|
+
| `reply_to` | One address, in any recipient form |
|
|
1037
|
+
| `from_name` | Display name; defaults to the app's name. The address is always the platform's sender |
|
|
1038
|
+
| `attachments` | `[{"filename", "content", "content_type"?, "content_id"?}]` — `content` is bytes, or a str sent as UTF-8; `content_type` is guessed from the filename; `content_id` makes the file inline for `<img src="cid:...">`. Executables (`.exe`, `.js`, `.bat`, ...) are refused |
|
|
1039
|
+
| `headers` | Custom headers such as `List-Unsubscribe` or `X-...`; `From`, `To`, `Subject`, `Reply-To`, `Content-Type` and the other headers the provider sets are refused |
|
|
1040
|
+
| `tags` | Up to 10 ASCII labels kept with the message at the provider |
|
|
1041
|
+
|
|
1042
|
+
Bodies and attachments together stay under 10 MB. `ValueError` means the
|
|
1043
|
+
message itself is wrong — nothing is sent or counted. `PlatformServiceUnavailable`
|
|
1044
|
+
means it cannot go out now: the app's daily recipient allowance in this
|
|
1045
|
+
workspace is used up (200 per UTC day unless the platform sets another), or the
|
|
1046
|
+
platform's provider is not configured or unreachable. Email is not billed to
|
|
1047
|
+
credits, and it is backend only. Under `pltt dev` nothing is sent:
|
|
1048
|
+
`LocalEmailService` checks each message with the same rules, saves it to
|
|
1049
|
+
`.palette/dev-outbox/` as an `.eml` file and returns its `path` as well;
|
|
1050
|
+
`pltt dev --sandbox` sends for real from a hosted preview.
|
|
1051
|
+
|
|
1003
1052
|
## 10. Managed Connections
|
|
1004
1053
|
|
|
1005
1054
|
Declare third-party OAuth or API-key connections in `palette-plugin.json`.
|