@palettelab/cli 0.3.71 → 0.3.73
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 +50 -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 +51 -4
- package/lib/agent-client.js +0 -9
- package/lib/bundler.js +32 -1
- package/lib/cli.js +7 -2
- package/lib/commands/agent.js +1 -102
- package/lib/commands/build.js +27 -12
- package/lib/commands/categories.js +25 -0
- package/lib/commands/check.js +1 -1
- package/lib/commands/doctor.js +2 -1
- package/lib/commands/platform.js +3 -2
- package/lib/commands/publish.js +7 -0
- package/lib/css-scope.js +90 -18
- package/lib/dev-simulator.js +8 -0
- package/lib/manifest.js +11 -1
- package/lib/migration_lint.py +128 -0
- 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
|
|
|
@@ -980,11 +984,6 @@ pltt agent archive bas_123 [--undo]
|
|
|
980
984
|
pltt agent move bas_123 --app 43
|
|
981
985
|
pltt agent delete bas_123
|
|
982
986
|
|
|
983
|
-
# A terminal in the session's build sandbox (Ctrl-] closes it; Node 22 or later)
|
|
984
|
-
pltt agent terminal bas_123
|
|
985
|
-
pltt agent terminal bas_123 --attach term_456
|
|
986
|
-
pltt agent terminals bas_123 [--read] [--lines 50]
|
|
987
|
-
|
|
988
987
|
# What the agent made, and what it can use
|
|
989
988
|
pltt agent artifacts bas_123
|
|
990
989
|
pltt agent artifact bas_123 art_1 -o ./mockup
|
|
@@ -1003,8 +1002,6 @@ pltt agent edit --app 42 "add a CSV export"
|
|
|
1003
1002
|
pltt agent init
|
|
1004
1003
|
```
|
|
1005
1004
|
|
|
1006
|
-
`terminal` opens an interactive shell in the session's build sandbox: the project's files and `pltt`, no network. Keys go to it as you type and its output is drawn by your terminal; resizing the window resizes it, and Ctrl-] closes it. A terminal opened while the agent works opens at its next step; on an idle session it starts an edit build that holds it. It closes after 10 minutes without typing. Files the app may not change are put back when it closes, and the agent is told what the terminal showed. `--attach` reconnects to one that is still open; `terminals --read` prints the newest one's last lines.
|
|
1007
|
-
|
|
1008
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`.
|
|
1009
1006
|
|
|
1010
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`.
|
|
@@ -1115,6 +1112,7 @@ pltt platform disable web
|
|
|
1115
1112
|
| `llm` | `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` | chat with tool calls, streaming, embeddings, image generation; receipts name the model that ran |
|
|
1116
1113
|
| `media` | `FAL_KEY` | fal.ai — image, video, speech, transcription, any model fal publishes; `upload()` for private inputs |
|
|
1117
1114
|
| `web` | `TAVILY_API_KEY` / `SERPAPI_KEY` | search + SSRF-guarded page reader |
|
|
1115
|
+
| `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 |
|
|
1118
1116
|
| `storage` | an S3/GCS bucket | per-app, per-org objects with resumable uploads |
|
|
1119
1117
|
| `vector` | a Pinecone/Qdrant account | namespaced vector search |
|
|
1120
1118
|
| `redis` | `REDIS_URL` | KV, lists, sets, sorted sets, counters, locks |
|
|
@@ -1130,10 +1128,15 @@ Notes:
|
|
|
1130
1128
|
settings you already wrote are kept.
|
|
1131
1129
|
- `llm` and `media` spend the workspace's credits under its plan, seat and
|
|
1132
1130
|
member limits. `ctx.llm.spend()["workspace"]` reports what is left.
|
|
1131
|
+
- `email` is not billed. Each app has a daily recipient allowance per
|
|
1132
|
+
workspace (200 per UTC day unless the platform sets another); one message
|
|
1133
|
+
reaches up to 50 recipients and 10 MB. A wrong message raises `ValueError`; a
|
|
1134
|
+
used-up allowance or an unavailable provider raises `PlatformServiceUnavailable`.
|
|
1133
1135
|
- Under `pltt dev` there is no platform: `llm` and `media` use your own
|
|
1134
1136
|
`OPENAI_API_KEY` / `FAL_KEY` when `.env.local` has them and return
|
|
1135
|
-
deterministic stubs when it does not. `
|
|
1136
|
-
|
|
1137
|
+
deterministic stubs when it does not. `email` sends nothing: each message is
|
|
1138
|
+
checked with the hosted rules and saved to `.palette/dev-outbox/` as an `.eml`
|
|
1139
|
+
file (open it in any mail app). `pltt doctor` prints which mode each one is in.
|
|
1137
1140
|
|
|
1138
1141
|
- Bigger calls are declared on `llm`'s object form —
|
|
1139
1142
|
`{"llm": {"max_output_tokens": 12000, "max_images": 16}}` — in the manifest
|
|
@@ -1173,6 +1176,20 @@ pltt models --json --env staging
|
|
|
1173
1176
|
`budget_exhausted` (the workspace is out of credits). The same reason is what a
|
|
1174
1177
|
`fallback=False` call raises as `ModelUnavailable`.
|
|
1175
1178
|
|
|
1179
|
+
|
|
1180
|
+
### `pltt categories`
|
|
1181
|
+
|
|
1182
|
+
The App Store categories `category` in `palette-plugin.json` can name.
|
|
1183
|
+
Superadmins keep the list on the platform, so it is read from there, never
|
|
1184
|
+
shipped with the CLI. Any other value, or no category, is filed under
|
|
1185
|
+
`Other`, and `pltt publish` says where the app went. A superadmin can move
|
|
1186
|
+
the app to another category at any time.
|
|
1187
|
+
|
|
1188
|
+
```bash
|
|
1189
|
+
pltt categories # one name per line, Other last
|
|
1190
|
+
pltt categories --json --env staging
|
|
1191
|
+
```
|
|
1192
|
+
|
|
1176
1193
|
### `pltt connections`
|
|
1177
1194
|
|
|
1178
1195
|
Use the third-party services the OS already holds — Gmail, Drive, Calendar,
|
|
@@ -1308,6 +1325,27 @@ Subcommands:
|
|
|
1308
1325
|
`pltt test` verifies every agent capability has a stable `capability_id` and a
|
|
1309
1326
|
matching `@capability(...)` / `service(..., agent_exposable=True)` handler.
|
|
1310
1327
|
|
|
1328
|
+
## App CSS Isolation
|
|
1329
|
+
|
|
1330
|
+
The bundler scopes every stylesheet your frontend imports to your app's root
|
|
1331
|
+
element, `[data-palette-plugin-root="<id>"]`, so app CSS never restyles Palette
|
|
1332
|
+
or another app.
|
|
1333
|
+
|
|
1334
|
+
- `:root`, `html` and `body` all mean that one root element. Chains such as
|
|
1335
|
+
`html body .x` or `:root[data-theme=dark] body` collapse onto it, so
|
|
1336
|
+
`:root[data-theme=dark] { --bg: #000 }` needs `data-theme` on the root
|
|
1337
|
+
element itself (`el.closest("[data-palette-plugin-root]")`), not on
|
|
1338
|
+
`document.documentElement`. For an in-app theme, font-size, contrast or
|
|
1339
|
+
motion toggle you can also put the attribute on your own top-level wrapper
|
|
1340
|
+
and write `.app[data-theme=dark] …`.
|
|
1341
|
+
- Nested CSS is supported: it is flattened before scoping, with the same
|
|
1342
|
+
matching as in a normal page.
|
|
1343
|
+
- Palette's dark mode is a `dark` class on `<html>`. `.dark .your-root { … }`
|
|
1344
|
+
and `.dark { … }` follow it; a `.dark` class your app sets on its own
|
|
1345
|
+
elements does not.
|
|
1346
|
+
- An unclosed `{`, `(` or `[`, a stray `}`, or a `//` comment fails the build
|
|
1347
|
+
with its file and line. The browser would silently drop the rules after it.
|
|
1348
|
+
|
|
1311
1349
|
## Global Flags
|
|
1312
1350
|
|
|
1313
1351
|
- `--json` emits machine-readable output for `package`, `publish`, `status`, `logs`, `test`, `update`, `version`, `login`, `dev --sandbox`, `platform list`, `services list`, and `capabilities`.
|
|
@@ -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,24 @@ 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.
|
|
976
|
+
page = await ctx.web.fetch("https://shop.example/product/123", render=True)
|
|
977
|
+
|
|
978
|
+
# Email through the platform's provider, from its sender address under the app's name.
|
|
979
|
+
# Recipients: "a@x.com", "Ann <a@x.com>", {"email", "name"} or a list (50 max across to/cc/bcc).
|
|
980
|
+
# Attachments: bytes or str (UTF-8), optional content_type; content_id = inline <img src="cid:...">.
|
|
981
|
+
# ValueError = the message is wrong; PlatformServiceUnavailable = daily allowance used up or provider down.
|
|
982
|
+
await ctx.email.send(
|
|
983
|
+
["Ann <ann@example.com>"], "Invoice 42",
|
|
984
|
+
html='<p>Attached.</p><img src="cid:logo">', text="Attached.",
|
|
985
|
+
cc="finance@example.com", bcc=["audit@acme.io"], reply_to="billing@acme.io", from_name="Acme Billing",
|
|
986
|
+
attachments=[
|
|
987
|
+
{"filename": "invoice-42.pdf", "content": pdf_bytes},
|
|
988
|
+
{"filename": "logo.png", "content": logo_bytes, "content_id": "logo"},
|
|
989
|
+
],
|
|
990
|
+
headers={"X-Invoice-Id": "42"}, tags=["invoice"],
|
|
991
|
+
) # pltt dev: nothing is sent; the message is saved to .palette/dev-outbox/*.eml
|
|
973
992
|
|
|
974
993
|
await ctx.redis.set("cache:summary", {"ready": True}, ttl=600)
|
|
975
994
|
value = await ctx.redis.get("cache:summary")
|
|
@@ -1000,6 +1019,34 @@ Under `pltt dev` there is no platform, so these run against your own
|
|
|
1000
1019
|
deterministic stubs when it does not — the app's code path is exercisable with
|
|
1001
1020
|
zero setup either way. `pltt doctor` prints which mode each service is in.
|
|
1002
1021
|
|
|
1022
|
+
### Email — `ctx.email`
|
|
1023
|
+
|
|
1024
|
+
`await ctx.email.send(to, subject, *, html=None, text=None, cc=None, bcc=None,
|
|
1025
|
+
reply_to=None, from_name=None, attachments=None, headers=None, tags=None)`
|
|
1026
|
+
sends one email through the platform's email provider and returns
|
|
1027
|
+
`{"id": <provider message id>, "recipients": <n>}`.
|
|
1028
|
+
|
|
1029
|
+
| Argument | Accepts |
|
|
1030
|
+
|---|---|
|
|
1031
|
+
| `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 |
|
|
1032
|
+
| `subject` | One line, required |
|
|
1033
|
+
| `html`, `text` | Either or both; `text` is the plain-text alternative |
|
|
1034
|
+
| `reply_to` | One address, in any recipient form |
|
|
1035
|
+
| `from_name` | Display name; defaults to the app's name. The address is always the platform's sender |
|
|
1036
|
+
| `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 |
|
|
1037
|
+
| `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 |
|
|
1038
|
+
| `tags` | Up to 10 ASCII labels kept with the message at the provider |
|
|
1039
|
+
|
|
1040
|
+
Bodies and attachments together stay under 10 MB. `ValueError` means the
|
|
1041
|
+
message itself is wrong — nothing is sent or counted. `PlatformServiceUnavailable`
|
|
1042
|
+
means it cannot go out now: the app's daily recipient allowance in this
|
|
1043
|
+
workspace is used up (200 per UTC day unless the platform sets another), or the
|
|
1044
|
+
platform's provider is not configured or unreachable. Email is not billed to
|
|
1045
|
+
credits, and it is backend only. Under `pltt dev` nothing is sent:
|
|
1046
|
+
`LocalEmailService` checks each message with the same rules, saves it to
|
|
1047
|
+
`.palette/dev-outbox/` as an `.eml` file and returns its `path` as well;
|
|
1048
|
+
`pltt dev --sandbox` sends for real from a hosted preview.
|
|
1049
|
+
|
|
1003
1050
|
## 10. Managed Connections
|
|
1004
1051
|
|
|
1005
1052
|
Declare third-party OAuth or API-key connections in `palette-plugin.json`.
|
package/lib/agent-client.js
CHANGED
|
@@ -107,15 +107,6 @@ class AgentClient {
|
|
|
107
107
|
models(query = "") { return this.request("GET", `/models${query ? `?q=${q(query)}` : ""}`) }
|
|
108
108
|
config() { return this.request("GET", "/config") }
|
|
109
109
|
plugins() { return this.request("GET", "/plugins") }
|
|
110
|
-
terminals(id) { return this.request("GET", `/${q(id)}/terminals`) }
|
|
111
|
-
openTerminal(id, { cols, rows, title } = {}) { return this.request("POST", `/${q(id)}/terminals`, { cols, rows, title }) }
|
|
112
|
-
readTerminal(id, lines = 100) { return this.request("GET", `/${q(id)}/terminals/read?lines=${lines}`) }
|
|
113
|
-
closeTerminal(id, terminal) { return this.request("DELETE", `/${q(id)}/terminals/${q(terminal)}`) }
|
|
114
|
-
terminalTicket(id, terminal) { return this.request("POST", `/${q(id)}/terminals/${q(terminal)}/ticket`) }
|
|
115
|
-
// The terminal's WebSocket, authorised by a one-use ticket (a WebSocket cannot carry the token header).
|
|
116
|
-
terminalUrl(id, terminal, ticket, after = "0") {
|
|
117
|
-
return `${this.base.replace(/^http/, "ws")}/${q(id)}/terminals/${q(terminal)}/connect?ticket=${q(ticket)}&after=${q(after)}`
|
|
118
|
-
}
|
|
119
110
|
// A raw call under /build-sessions, for scripting what has no subcommand.
|
|
120
111
|
raw(method, route, body) { return this.request(method.toUpperCase(), route.startsWith("/") || route.startsWith("?") ? route : `/${route}`, body) }
|
|
121
112
|
answer(id, question, answer) { return this.request("POST", `/${q(id)}/questions/${q(question)}`, { answer }) }
|
package/lib/bundler.js
CHANGED
|
@@ -369,12 +369,43 @@ export function Link({ href, replace, onClick, children, ...props }) {
|
|
|
369
369
|
}
|
|
370
370
|
}
|
|
371
371
|
|
|
372
|
+
// esbuild "repairs" broken CSS: an unclosed "{" or "(" swallows every later rule, and a
|
|
373
|
+
// stray "}" or a "//" comment eats the next selector. The browser then drops those rules
|
|
374
|
+
// with no error, so fail the build on these and print the remaining CSS warnings.
|
|
375
|
+
function isBrokenCss(warning) {
|
|
376
|
+
return (
|
|
377
|
+
warning.id === "js-comment-in-css" ||
|
|
378
|
+
(warning.id === "css-syntax-error" && /^(Expected "[)\]}]" to go with "[([{]"|Unexpected "}")$/.test(warning.text))
|
|
379
|
+
)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const cssGuardPlugin = {
|
|
383
|
+
name: "palette-css-guard",
|
|
384
|
+
setup(build) {
|
|
385
|
+
build.onEnd((result) => {
|
|
386
|
+
const css = result.warnings.filter((w) => /\.css$/i.test(w.location?.file || ""))
|
|
387
|
+
for (const w of css) {
|
|
388
|
+
if (!isBrokenCss(w)) console.warn(`[pltt] CSS warning: ${w.location.file}:${w.location.line}: ${w.text}`)
|
|
389
|
+
}
|
|
390
|
+
const broken = css.filter(isBrokenCss)
|
|
391
|
+
if (!broken.length) return undefined
|
|
392
|
+
return {
|
|
393
|
+
errors: broken.map((w) => ({
|
|
394
|
+
text: `${w.text}${w.notes?.[0]?.location ? ` (opened on line ${w.notes[0].location.line})` : ""}. The browser would silently drop the rules this breaks; fix the CSS.`,
|
|
395
|
+
location: w.location,
|
|
396
|
+
notes: w.notes,
|
|
397
|
+
})),
|
|
398
|
+
}
|
|
399
|
+
})
|
|
400
|
+
},
|
|
401
|
+
}
|
|
402
|
+
|
|
372
403
|
function frontendBuildConfig(pluginDir, frontend = {}) {
|
|
373
404
|
const framework = frontendFramework(frontend)
|
|
374
405
|
const define = {
|
|
375
406
|
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || "production"),
|
|
376
407
|
}
|
|
377
|
-
const plugins = []
|
|
408
|
+
const plugins = [cssGuardPlugin]
|
|
378
409
|
const tsconfigPaths = framework === "next" || framework === "palette-app" ? makeTsconfigPathsPlugin(pluginDir, frontend) : null
|
|
379
410
|
if (tsconfigPaths) plugins.push(tsconfigPaths)
|
|
380
411
|
if (framework === "palette-app") plugins.push(makePaletteAppNextCompatPlugin(pluginDir))
|