@palettelab/cli 0.3.62 → 0.3.63
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 +72 -3
- package/backend-sdk/palette_sdk/__init__.py +2 -0
- package/backend-sdk/palette_sdk/connections.py +49 -11
- package/backend-sdk/palette_sdk/connections_generated.py +246 -0
- package/backend-sdk/palette_sdk/manifest.py +15 -2
- package/backend-sdk/palette_sdk/platform_services.py +122 -0
- package/backend-sdk/palette_sdk/plugin_context.py +14 -0
- package/backend-sdk/palette_sdk/talk.py +65 -0
- package/backend-sdk/pyproject.toml +1 -1
- package/docs/python-backend-sdk.md +64 -1
- package/lib/bundler.js +64 -0
- package/lib/cli.js +13 -1
- package/lib/commands/connections.js +234 -0
- package/lib/commands/dev.js +75 -1
- package/lib/commands/doctor.js +70 -0
- package/lib/commands/open.js +43 -0
- package/lib/connection-catalog.json +1185 -0
- package/lib/dev-simulator.js +137 -3
- package/lib/manifest.js +16 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -309,12 +309,12 @@ 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.
|
|
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.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.web`, `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.
|
|
316
316
|
- `ctx.members` gives backend access to current organisation members; it exposes list/get/invite/update-role helpers, but no delete/remove helper.
|
|
317
|
-
- `ctx.connections.
|
|
317
|
+
- `ctx.connections.<namespace>.<tool>(...)` calls the third-party services the viewer connected in Palette Connect — `ctx.connections.gmail.search(query=...)`, `ctx.connections.slack.post_message(...)`, and so on for drive, calendar, sheets, docs, slides, contacts, tasks, forms, notion, telegram and meta. `ctx.connections.list()/status(id)/require(id)` report what is connected and granted. There is no `access_token(...)`: the platform holds the credential so scope checks, write approval and audit cannot be bypassed.
|
|
318
318
|
- `ctx.has_permission("...")`, `ctx.has_any_permission([...])`, and `ctx.has_all_permissions([...])` check declared permissions.
|
|
319
319
|
- `ctx.config_value("key")` and `ctx.require_config("key")` read app install/config values.
|
|
320
320
|
- `ctx.secret("KEY")` reads app secrets from config or environment variables.
|
|
@@ -323,6 +323,9 @@ Backend SDK features for app-owned data:
|
|
|
323
323
|
- `ctx.redis` gives a Redis-backed, plugin/org-scoped Redis API when `"redis"` is declared in `platform_services`.
|
|
324
324
|
- `ctx.vector` gives a Qdrant-backed, plugin/org-scoped vector API when `"vector"` is declared in `platform_services`.
|
|
325
325
|
- `ctx.storage` gives app/org-scoped file upload helpers when `"storage"` is declared in `platform_services`.
|
|
326
|
+
- `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. The platform picks the model (an app cannot select the premium tier or bypass the org's SECURE policy), meters spend per organisation and app, and raises once the monthly budget is spent.
|
|
327
|
+
- `ctx.web` gives web search and an SSRF-guarded page reader (HTML tables and PDFs handled) when `"web"` is declared.
|
|
328
|
+
- `ctx.connections` gives the viewer's OS service connections — see `pltt connections`.
|
|
326
329
|
- `@job(...)`, `JobExecution`, and `ctx.jobs` provide durable async work with retries, progress, status, and cancellation.
|
|
327
330
|
- `LifecycleHooks` lets apps define install/update/enable/disable/uninstall hooks.
|
|
328
331
|
- `OrgScopedTable` and `PluginBase` keep app data inside the plugin schema model set.
|
|
@@ -515,6 +518,30 @@ await notifications.push({
|
|
|
515
518
|
Both helpers create a live toast plus a notification-center entry. Use these
|
|
516
519
|
helpers rather than hand-building platform notification API calls.
|
|
517
520
|
|
|
521
|
+
### Talk messages from Python backends
|
|
522
|
+
|
|
523
|
+
A notification goes to one person's bell. To say something in a room instead,
|
|
524
|
+
post into Talk as your app's own agent identity — the agent members `@`-mention
|
|
525
|
+
and DM:
|
|
526
|
+
|
|
527
|
+
```python
|
|
528
|
+
from palette_sdk import PluginContext, get_plugin_context, require_permission
|
|
529
|
+
|
|
530
|
+
@router.post("/digest", dependencies=[require_permission("chat:write")])
|
|
531
|
+
async def send_digest(ctx: PluginContext = Depends(get_plugin_context)):
|
|
532
|
+
for room in await ctx.talk.channels():
|
|
533
|
+
await ctx.talk.post("Nightly digest is ready.", channel=room["id"])
|
|
534
|
+
```
|
|
535
|
+
|
|
536
|
+
`channel` takes a channel id or its name (`"general"`, `"#general"`), and an
|
|
537
|
+
`@Name` in the text mentions that member or agent exactly as a typed message
|
|
538
|
+
does. Declare `chat:write` in `permissions`, and have a member invite the app's
|
|
539
|
+
agent to the channel first — an app posts into the rooms it was invited to and
|
|
540
|
+
nowhere else, and `ctx.talk.channels()` (ids, names, types) is the only Talk
|
|
541
|
+
read it gets. During `pltt dev` nothing reaches a real channel: the simulator
|
|
542
|
+
reports one fake seat and logs each post as `[palette-talk] {...}`. See
|
|
543
|
+
`docs/python-backend-sdk.md` ("Talk Messages From Python") for details.
|
|
544
|
+
|
|
518
545
|
During `pltt dev`, frontend pushes call the platform backend directly
|
|
519
546
|
(`NEXT_PUBLIC_API_URL`, default `http://localhost:8000`) in the user's session,
|
|
520
547
|
so they land in the real notification pool. Backend pushes run against the
|
|
@@ -706,7 +733,7 @@ install-scoped values or labels/help text:
|
|
|
706
733
|
"STRIPE_SECRET": { "scope": "plugin", "required": true },
|
|
707
734
|
"DEBUG_PROBE_URL": { "scope": "dev", "required": false }
|
|
708
735
|
},
|
|
709
|
-
"platform_services": ["llm", "redis", "storage", "vector"]
|
|
736
|
+
"platform_services": ["llm", "redis", "storage", "vector", "web"]
|
|
710
737
|
}
|
|
711
738
|
```
|
|
712
739
|
|
|
@@ -925,6 +952,48 @@ pltt logs --json
|
|
|
925
952
|
|
|
926
953
|
If no plugin ID is provided, the CLI uses the current `palette-plugin.json` or `.palette/last-publish.json`.
|
|
927
954
|
|
|
955
|
+
### `pltt connections`
|
|
956
|
+
|
|
957
|
+
Use the third-party services the OS already holds — Gmail, Drive, Calendar,
|
|
958
|
+
Sheets, Docs, Slack, Notion, Telegram, Meta.
|
|
959
|
+
|
|
960
|
+
Your app does **no OAuth of its own and never holds a provider token**. The user
|
|
961
|
+
connects a provider once in Palette Connect; your app declares the tools it
|
|
962
|
+
needs; the user grants them with one click; the platform proxies every call,
|
|
963
|
+
keeping the scope check, write approval and audit trail in place.
|
|
964
|
+
|
|
965
|
+
```bash
|
|
966
|
+
pltt connections list --tools # every provider + tool
|
|
967
|
+
pltt connections add google --tools gmail.search,gmail.send
|
|
968
|
+
pltt connections pull # typed helpers for your app
|
|
969
|
+
pltt connections mock google.gmail.search --result '{"messages":[]}'
|
|
970
|
+
```
|
|
971
|
+
|
|
972
|
+
Then, in your app:
|
|
973
|
+
|
|
974
|
+
```python
|
|
975
|
+
# backend
|
|
976
|
+
messages = await ctx.connections.gmail.search(query="invoice newer_than:7d")
|
|
977
|
+
```
|
|
978
|
+
|
|
979
|
+
```ts
|
|
980
|
+
// frontend
|
|
981
|
+
await palette.connections.gmail.search({ query: "invoice newer_than:7d" })
|
|
982
|
+
```
|
|
983
|
+
|
|
984
|
+
Subcommands:
|
|
985
|
+
|
|
986
|
+
- `list`: providers and their tools, marking the ones your manifest declares. `--tools` expands every tool.
|
|
987
|
+
- `add <provider> [--tools a,b]`: writes the `connections` block into `palette-plugin.json`, rejecting unknown tool names. Omit `--tools` to take every read-only tool for that provider.
|
|
988
|
+
- `pull`: generates typed helpers for the tools you declared into `.palette/types/connections.ts`. Python is already typed by `palette-sdk`.
|
|
989
|
+
- `mock <provider>.<tool> [--result JSON]`: seeds `.palette/connections.local.json` so `pltt dev` answers the call offline.
|
|
990
|
+
|
|
991
|
+
Notes:
|
|
992
|
+
|
|
993
|
+
- Writes (`gmail.send`, `slack.post_message`, …) return `{queued_for_approval, approval_id, preview}` instead of running. Render that as a pending state; an org admin can allow a specific app+provider to write directly.
|
|
994
|
+
- `424` means the user has not connected (or granted) the provider — the connection status carries a `connect_url` to send them to.
|
|
995
|
+
- One entry per provider: the platform resolves a grant by provider, so two entries on the same one are rejected at publish.
|
|
996
|
+
|
|
928
997
|
### `pltt services`
|
|
929
998
|
|
|
930
999
|
Inspect and generate OS-broker service integrations declared through
|
|
@@ -8,6 +8,7 @@ from palette_sdk.apps import AppInteropClient, AppServiceClient, MissingAppServi
|
|
|
8
8
|
from palette_sdk.members import OrganizationMembersClient
|
|
9
9
|
from palette_sdk.notifications import NotificationRecipient, NotificationsClient
|
|
10
10
|
from palette_sdk.organization import OrganizationInfo
|
|
11
|
+
from palette_sdk.talk import TalkClient
|
|
11
12
|
from palette_sdk.platform_services import (
|
|
12
13
|
LocalRedisService,
|
|
13
14
|
LocalVectorService,
|
|
@@ -79,6 +80,7 @@ __all__ = [
|
|
|
79
80
|
"OrganizationInfo",
|
|
80
81
|
"NotificationsClient",
|
|
81
82
|
"NotificationRecipient",
|
|
83
|
+
"TalkClient",
|
|
82
84
|
"LocalRedisService",
|
|
83
85
|
"LocalVectorService",
|
|
84
86
|
"PlatformServiceUnavailable",
|
|
@@ -1,11 +1,22 @@
|
|
|
1
|
-
"""Palette
|
|
1
|
+
"""Access to the user's Palette OS service connections.
|
|
2
|
+
|
|
3
|
+
An app never holds a provider credential. The user connects Google/Slack/… once
|
|
4
|
+
in Connect; the app declares the tools it needs in its manifest, the user grants
|
|
5
|
+
them, and every call is proxied by the platform — which owns the token refresh,
|
|
6
|
+
the write-approval gate and the audit trail.
|
|
7
|
+
|
|
8
|
+
await ctx.connections.gmail.search(query="invoice")
|
|
9
|
+
await ctx.connections.slack.post_message(channel="#ops", text="done")
|
|
10
|
+
await ctx.connections.call("google", "sheets.append_row", {...}) # escape hatch
|
|
11
|
+
"""
|
|
2
12
|
|
|
3
13
|
from __future__ import annotations
|
|
4
14
|
|
|
5
15
|
from dataclasses import dataclass, field
|
|
6
|
-
from datetime import datetime, timezone
|
|
7
16
|
from typing import Any
|
|
8
17
|
|
|
18
|
+
from palette_sdk.connections_generated import NAMESPACES
|
|
19
|
+
|
|
9
20
|
|
|
10
21
|
class MissingConnectionError(RuntimeError):
|
|
11
22
|
"""Raised when plugin code requires a connection that is not connected."""
|
|
@@ -49,11 +60,41 @@ def _to_status(raw: dict[str, Any]) -> ConnectionStatus:
|
|
|
49
60
|
|
|
50
61
|
|
|
51
62
|
class PluginConnectionsClient:
|
|
52
|
-
"""Access
|
|
63
|
+
"""Access the user's Palette OS connections on behalf of this app.
|
|
64
|
+
|
|
65
|
+
Exposes one typed namespace per tool family — `.gmail`, `.drive`,
|
|
66
|
+
`.calendar`, `.sheets`, `.docs`, `.slides`, `.contacts`, `.tasks`,
|
|
67
|
+
`.forms`, `.slack`, `.notion`, `.telegram`, `.meta` — generated from the
|
|
68
|
+
platform's tool registry.
|
|
69
|
+
"""
|
|
53
70
|
|
|
54
71
|
def __init__(self, adapter: Any | None = None, local_connections: dict[str, Any] | None = None):
|
|
55
72
|
self._adapter = adapter
|
|
56
73
|
self._local_connections = local_connections or {}
|
|
74
|
+
for name, namespace in NAMESPACES.items():
|
|
75
|
+
setattr(self, name, namespace(self))
|
|
76
|
+
|
|
77
|
+
async def call(self, provider: str, tool: str, args: dict[str, Any] | None = None) -> Any:
|
|
78
|
+
"""Invoke one provider tool. Backs every generated helper."""
|
|
79
|
+
if self._adapter is not None and hasattr(self._adapter, "call"):
|
|
80
|
+
return await self._adapter.call(provider, tool, args or {})
|
|
81
|
+
mock = self._local_tool_mock(provider, tool)
|
|
82
|
+
if mock is not None:
|
|
83
|
+
return mock
|
|
84
|
+
raise MissingConnectionError(
|
|
85
|
+
f"No connection available for {provider}.{tool}. Run inside Palette OS, or add a "
|
|
86
|
+
f'mock: pltt connections mock {provider}.{tool}'
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
def _local_tool_mock(self, provider: str, tool: str) -> Any:
|
|
90
|
+
"""`pltt dev` responses from .palette/connections.local.json."""
|
|
91
|
+
for entry in self._local_connections.values():
|
|
92
|
+
if not isinstance(entry, dict) or entry.get("provider") != provider:
|
|
93
|
+
continue
|
|
94
|
+
tools = entry.get("tools")
|
|
95
|
+
if isinstance(tools, dict) and tool in tools:
|
|
96
|
+
return tools[tool]
|
|
97
|
+
return None
|
|
57
98
|
|
|
58
99
|
async def list(self) -> list[ConnectionStatus]:
|
|
59
100
|
if self._adapter is not None and hasattr(self._adapter, "list"):
|
|
@@ -73,11 +114,8 @@ class PluginConnectionsClient:
|
|
|
73
114
|
return status
|
|
74
115
|
|
|
75
116
|
async def access_token(self, connection_id: str) -> str:
|
|
76
|
-
|
|
77
|
-
token
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
if status.connected:
|
|
82
|
-
return f"palette-local-token:{connection_id}:{int(datetime.now(timezone.utc).timestamp())}"
|
|
83
|
-
raise MissingConnectionError(f"Palette connection is not configured: {connection_id}")
|
|
117
|
+
raise MissingConnectionError(
|
|
118
|
+
"Apps never hold provider credentials — the platform keeps the token so it "
|
|
119
|
+
"can enforce scopes, write approval and audit. Call the tool instead: "
|
|
120
|
+
"ctx.connections.gmail.search(...) or ctx.connections.call(provider, tool, args)."
|
|
121
|
+
)
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""GENERATED by backend/scripts/gen_connection_helpers.py — do not edit by hand.
|
|
2
|
+
|
|
3
|
+
Typed facades over `ctx.connections.call(provider, tool, args)`. Every call is
|
|
4
|
+
proxied by the platform, which owns the OAuth token, the approval gate and the
|
|
5
|
+
audit trail — an app never sees a provider credential.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Protocol
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class _Caller(Protocol):
|
|
14
|
+
async def call(self, provider: str, tool: str, args: dict[str, Any]) -> Any: ...
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class _Namespace:
|
|
18
|
+
def __init__(self, caller: _Caller):
|
|
19
|
+
self._caller = caller
|
|
20
|
+
|
|
21
|
+
async def _call(self, provider: str, tool: str, args: dict[str, Any]) -> Any:
|
|
22
|
+
# Drop unset optionals so provider defaults apply.
|
|
23
|
+
return await self._caller.call(provider, tool, {k: v for k, v in args.items() if v is not None})
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class CalendarTools(_Namespace):
|
|
27
|
+
async def create_event(self, *, end: str, start: str, add_meet: bool | None = None, attendees: str | None = None, calendar_id: str | None = None, description: str | None = None, location: str | None = None, summary: str | None = None, time_zone: str | None = None) -> Any:
|
|
28
|
+
"""Create a Google Calendar event. Set add_meet=true to attach a Google Meet video link. start/end are RFC3339 datetimes. Invites are emailed to attendees."""
|
|
29
|
+
return await self._call("google", "calendar.create_event", {"end": end, "start": start, "add_meet": add_meet, "attendees": attendees, "calendar_id": calendar_id, "description": description, "location": location, "summary": summary, "time_zone": time_zone})
|
|
30
|
+
|
|
31
|
+
async def list_calendars(self, *, max_results: int | None = None) -> Any:
|
|
32
|
+
"""List the calendars the connected Google account can access (id, name, access role)."""
|
|
33
|
+
return await self._call("google", "calendar.list_calendars", {"max_results": max_results})
|
|
34
|
+
|
|
35
|
+
async def list_events(self, *, calendar_id: str | None = None, max_results: int | None = None, query: str | None = None, time_max: str | None = None, time_min: str | None = None) -> Any:
|
|
36
|
+
"""List upcoming events on a Google Calendar. Optional time window (RFC3339) and text query. Returns summary, start/end, attendees and any Meet link."""
|
|
37
|
+
return await self._call("google", "calendar.list_events", {"calendar_id": calendar_id, "max_results": max_results, "query": query, "time_max": time_max, "time_min": time_min})
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ContactsTools(_Namespace):
|
|
41
|
+
async def list(self, *, max_results: int | None = None) -> Any:
|
|
42
|
+
"""List the connected account's Google Contacts (most recently modified first)."""
|
|
43
|
+
return await self._call("google", "contacts.list", {"max_results": max_results})
|
|
44
|
+
|
|
45
|
+
async def search(self, *, query: str, max_results: int | None = None) -> Any:
|
|
46
|
+
"""Search the connected account's Google Contacts by name, email or phone. Returns matching people."""
|
|
47
|
+
return await self._call("google", "contacts.search", {"query": query, "max_results": max_results})
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class DocsTools(_Namespace):
|
|
51
|
+
async def create(self, *, title: str, body: str | None = None) -> Any:
|
|
52
|
+
"""Create a new Google Doc with a title and optional plain-text body. Returns the doc id and edit URL."""
|
|
53
|
+
return await self._call("google", "docs.create", {"title": title, "body": body})
|
|
54
|
+
|
|
55
|
+
async def read(self, *, document_id: str) -> Any:
|
|
56
|
+
"""Read a Google Doc's text content (plain text) by document id."""
|
|
57
|
+
return await self._call("google", "docs.read", {"document_id": document_id})
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class DriveTools(_Namespace):
|
|
61
|
+
async def list(self, *, folder_id: str | None = None, max_results: int | None = None) -> Any:
|
|
62
|
+
"""List recent files in the connected Google Drive (optionally inside one folder)."""
|
|
63
|
+
return await self._call("google", "drive.list", {"folder_id": folder_id, "max_results": max_results})
|
|
64
|
+
|
|
65
|
+
async def read(self, *, file_id: str) -> Any:
|
|
66
|
+
"""Read a Google Drive file's content as text (Docs/Sheets/Slides exported; text files downloaded)."""
|
|
67
|
+
return await self._call("google", "drive.read", {"file_id": file_id})
|
|
68
|
+
|
|
69
|
+
async def search(self, *, query: str, max_results: int | None = None) -> Any:
|
|
70
|
+
"""Search Google Drive by file name or full text."""
|
|
71
|
+
return await self._call("google", "drive.search", {"query": query, "max_results": max_results})
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class FormsTools(_Namespace):
|
|
75
|
+
async def list_responses(self, *, form_id: str, max_results: int | None = None) -> Any:
|
|
76
|
+
"""List submitted responses to a Google Form, with answers keyed by question id."""
|
|
77
|
+
return await self._call("google", "forms.list_responses", {"form_id": form_id, "max_results": max_results})
|
|
78
|
+
|
|
79
|
+
async def read(self, *, form_id: str) -> Any:
|
|
80
|
+
"""Read a Google Form's title, description and questions by form id."""
|
|
81
|
+
return await self._call("google", "forms.read", {"form_id": form_id})
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class GmailTools(_Namespace):
|
|
85
|
+
async def create_draft(self, *, body: str, subject: str, to: str, cc: str | None = None, thread_id: str | None = None) -> Any:
|
|
86
|
+
"""Create a Gmail draft (not sent) — the safe holding pattern for emails the user should review."""
|
|
87
|
+
return await self._call("google", "gmail.create_draft", {"body": body, "subject": subject, "to": to, "cc": cc, "thread_id": thread_id})
|
|
88
|
+
|
|
89
|
+
async def get_draft(self, *, draft_id: str) -> Any:
|
|
90
|
+
"""Read the full content (to, subject, body) of an existing Gmail draft by draft_id."""
|
|
91
|
+
return await self._call("google", "gmail.get_draft", {"draft_id": draft_id})
|
|
92
|
+
|
|
93
|
+
async def read(self, *, message_id: str) -> Any:
|
|
94
|
+
"""Read one Gmail message's full body (plain text) by message id."""
|
|
95
|
+
return await self._call("google", "gmail.read", {"message_id": message_id})
|
|
96
|
+
|
|
97
|
+
async def search(self, *, query: str, max_results: int | None = None) -> Any:
|
|
98
|
+
"""Search the connected Gmail account. Supports Gmail query syntax (from:, subject:, is:unread, newer_than:2d...). Returns message metadata + snippets."""
|
|
99
|
+
return await self._call("google", "gmail.search", {"query": query, "max_results": max_results})
|
|
100
|
+
|
|
101
|
+
async def send(self, *, body: str, subject: str, to: str, cc: str | None = None, thread_id: str | None = None) -> Any:
|
|
102
|
+
"""Send an email from the connected Gmail account. Use gmail.create_draft instead when the user should review before sending."""
|
|
103
|
+
return await self._call("google", "gmail.send", {"body": body, "subject": subject, "to": to, "cc": cc, "thread_id": thread_id})
|
|
104
|
+
|
|
105
|
+
async def send_draft(self, *, draft_id: str) -> Any:
|
|
106
|
+
"""Send an existing Gmail draft by draft_id after the user has approved it."""
|
|
107
|
+
return await self._call("google", "gmail.send_draft", {"draft_id": draft_id})
|
|
108
|
+
|
|
109
|
+
async def update_draft(self, *, body: str, draft_id: str, subject: str, to: str, cc: str | None = None, thread_id: str | None = None) -> Any:
|
|
110
|
+
"""Replace the content of an existing Gmail draft (before it is sent)."""
|
|
111
|
+
return await self._call("google", "gmail.update_draft", {"body": body, "draft_id": draft_id, "subject": subject, "to": to, "cc": cc, "thread_id": thread_id})
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class MetaTools(_Namespace):
|
|
115
|
+
async def create_page_post(self, *, message: str, page_id: str, link: str | None = None) -> Any:
|
|
116
|
+
"""Publish a text post (optionally with a link) to a Facebook Page the account manages."""
|
|
117
|
+
return await self._call("meta", "meta.create_page_post", {"message": message, "page_id": page_id, "link": link})
|
|
118
|
+
|
|
119
|
+
async def list_pages(self, *, limit: int | None = None) -> Any:
|
|
120
|
+
"""List the Facebook Pages this account manages (id, name, category)."""
|
|
121
|
+
return await self._call("meta", "meta.list_pages", {"limit": limit})
|
|
122
|
+
|
|
123
|
+
async def read_page_posts(self, *, page_id: str, limit: int | None = None) -> Any:
|
|
124
|
+
"""Read recent posts from a Facebook Page the account manages."""
|
|
125
|
+
return await self._call("meta", "meta.read_page_posts", {"page_id": page_id, "limit": limit})
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class NotionTools(_Namespace):
|
|
129
|
+
async def append_blocks(self, *, block_id: str, blocks: list[Any] | None = None, content: str | None = None) -> Any:
|
|
130
|
+
"""Append paragraph blocks (from newline-separated text) or raw blocks to a Notion page/block."""
|
|
131
|
+
return await self._call("notion", "notion.append_blocks", {"block_id": block_id, "blocks": blocks, "content": content})
|
|
132
|
+
|
|
133
|
+
async def create_page(self, *, content: str | None = None, parent_database_id: str | None = None, parent_page_id: str | None = None, properties: dict[str, Any] | None = None, title: str | None = None) -> Any:
|
|
134
|
+
"""Create a Notion page under a parent page or database (title + optional plain-text content, or a raw properties object for database parents)."""
|
|
135
|
+
return await self._call("notion", "notion.create_page", {"content": content, "parent_database_id": parent_database_id, "parent_page_id": parent_page_id, "properties": properties, "title": title})
|
|
136
|
+
|
|
137
|
+
async def get_page(self, *, page_id: str) -> Any:
|
|
138
|
+
"""Read a Notion page's title and top-level text content by page id."""
|
|
139
|
+
return await self._call("notion", "notion.get_page", {"page_id": page_id})
|
|
140
|
+
|
|
141
|
+
async def query_database(self, *, database_id: str, filter: dict[str, Any] | None = None, limit: int | None = None, sorts: list[Any] | None = None) -> Any:
|
|
142
|
+
"""Query rows of a Notion database by id (optional Notion filter/sorts objects)."""
|
|
143
|
+
return await self._call("notion", "notion.query_database", {"database_id": database_id, "filter": filter, "limit": limit, "sorts": sorts})
|
|
144
|
+
|
|
145
|
+
async def search(self, *, filter: str | None = None, limit: int | None = None, query: str | None = None) -> Any:
|
|
146
|
+
"""Search pages and databases shared with the Notion integration (by text query)."""
|
|
147
|
+
return await self._call("notion", "notion.search", {"filter": filter, "limit": limit, "query": query})
|
|
148
|
+
|
|
149
|
+
async def update_page(self, *, page_id: str, archived: bool | None = None, properties: dict[str, Any] | None = None) -> Any:
|
|
150
|
+
"""Update a Notion page's properties, or archive/unarchive it."""
|
|
151
|
+
return await self._call("notion", "notion.update_page", {"page_id": page_id, "archived": archived, "properties": properties})
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class SheetsTools(_Namespace):
|
|
155
|
+
async def append_row(self, *, range: str, spreadsheet_id: str, values: list[Any]) -> Any:
|
|
156
|
+
"""Append one row to a Google Sheet range. `values` is an array of cell values for the new row."""
|
|
157
|
+
return await self._call("google", "sheets.append_row", {"range": range, "spreadsheet_id": spreadsheet_id, "values": values})
|
|
158
|
+
|
|
159
|
+
async def read_range(self, *, range: str, spreadsheet_id: str) -> Any:
|
|
160
|
+
"""Read a cell range from a Google Sheet in A1 notation (e.g. 'Sheet1!A1:D20'). Returns a 2D array of values."""
|
|
161
|
+
return await self._call("google", "sheets.read_range", {"range": range, "spreadsheet_id": spreadsheet_id})
|
|
162
|
+
|
|
163
|
+
async def update_range(self, *, range: str, spreadsheet_id: str, values: list[Any]) -> Any:
|
|
164
|
+
"""Overwrite a cell range in a Google Sheet. `values` is a 2D array (array of row arrays) sized to the range."""
|
|
165
|
+
return await self._call("google", "sheets.update_range", {"range": range, "spreadsheet_id": spreadsheet_id, "values": values})
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class SlackTools(_Namespace):
|
|
169
|
+
async def add_reaction(self, *, channel: str, emoji: str, ts: str) -> Any:
|
|
170
|
+
"""Add an emoji reaction to a message (by channel + ts)."""
|
|
171
|
+
return await self._call("slack", "slack.add_reaction", {"channel": channel, "emoji": emoji, "ts": ts})
|
|
172
|
+
|
|
173
|
+
async def get_permalink(self, *, channel: str, ts: str) -> Any:
|
|
174
|
+
"""Get a shareable permalink URL for a message (by channel + ts)."""
|
|
175
|
+
return await self._call("slack", "slack.get_permalink", {"channel": channel, "ts": ts})
|
|
176
|
+
|
|
177
|
+
async def list_channels(self, *, limit: int | None = None) -> Any:
|
|
178
|
+
"""List public Slack channels in the connected workspace."""
|
|
179
|
+
return await self._call("slack", "slack.list_channels", {"limit": limit})
|
|
180
|
+
|
|
181
|
+
async def post_message(self, *, channel: str, text: str) -> Any:
|
|
182
|
+
"""Post a message to a Slack channel (by #name or channel id) as the workspace bot."""
|
|
183
|
+
return await self._call("slack", "slack.post_message", {"channel": channel, "text": text})
|
|
184
|
+
|
|
185
|
+
async def read_channel(self, *, channel: str, limit: int | None = None) -> Any:
|
|
186
|
+
"""Read recent messages from a public Slack channel."""
|
|
187
|
+
return await self._call("slack", "slack.read_channel", {"channel": channel, "limit": limit})
|
|
188
|
+
|
|
189
|
+
async def update_message(self, *, channel: str, text: str, ts: str) -> Any:
|
|
190
|
+
"""Edit the text of a message the bot previously posted (by channel + ts)."""
|
|
191
|
+
return await self._call("slack", "slack.update_message", {"channel": channel, "text": text, "ts": ts})
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class SlidesTools(_Namespace):
|
|
195
|
+
async def read(self, *, presentation_id: str) -> Any:
|
|
196
|
+
"""Read the text of every slide in a Google Slides presentation by presentation id."""
|
|
197
|
+
return await self._call("google", "slides.read", {"presentation_id": presentation_id})
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class TasksTools(_Namespace):
|
|
201
|
+
async def create(self, *, title: str, due: str | None = None, notes: str | None = None, tasklist_id: str | None = None) -> Any:
|
|
202
|
+
"""Create a task in a Google Tasks list. Optional notes and RFC3339 due date."""
|
|
203
|
+
return await self._call("google", "tasks.create", {"title": title, "due": due, "notes": notes, "tasklist_id": tasklist_id})
|
|
204
|
+
|
|
205
|
+
async def list(self, *, max_results: int | None = None, show_completed: bool | None = None, tasklist_id: str | None = None) -> Any:
|
|
206
|
+
"""List tasks from a Google Tasks list (defaults to the primary '@default' list)."""
|
|
207
|
+
return await self._call("google", "tasks.list", {"max_results": max_results, "show_completed": show_completed, "tasklist_id": tasklist_id})
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class TelegramTools(_Namespace):
|
|
211
|
+
async def edit_message(self, *, chat_id: str, message_id: int, text: str) -> Any:
|
|
212
|
+
"""Edit the text of a message the bot previously sent."""
|
|
213
|
+
return await self._call("telegram", "telegram.edit_message", {"chat_id": chat_id, "message_id": message_id, "text": text})
|
|
214
|
+
|
|
215
|
+
async def get_chat(self, *, chat_id: str) -> Any:
|
|
216
|
+
"""Get metadata for a Telegram chat/group/channel the bot is a member of."""
|
|
217
|
+
return await self._call("telegram", "telegram.get_chat", {"chat_id": chat_id})
|
|
218
|
+
|
|
219
|
+
async def read_updates(self, *, limit: int | None = None, offset: int | None = None) -> Any:
|
|
220
|
+
"""Read recent messages sent to the connected Telegram bot (private chats, groups it is in)."""
|
|
221
|
+
return await self._call("telegram", "telegram.read_updates", {"limit": limit, "offset": offset})
|
|
222
|
+
|
|
223
|
+
async def send_message(self, *, chat_id: str, text: str) -> Any:
|
|
224
|
+
"""Send a message to a Telegram chat, group, or channel as the connected bot (chat_id = numeric id or @channelusername; the bot must be a member/admin of the chat)."""
|
|
225
|
+
return await self._call("telegram", "telegram.send_message", {"chat_id": chat_id, "text": text})
|
|
226
|
+
|
|
227
|
+
async def send_photo(self, *, chat_id: str, photo: str, caption: str | None = None) -> Any:
|
|
228
|
+
"""Send a photo (by public URL or Telegram file_id) to a chat as the connected bot, with an optional caption."""
|
|
229
|
+
return await self._call("telegram", "telegram.send_photo", {"chat_id": chat_id, "photo": photo, "caption": caption})
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
NAMESPACES: dict[str, type[_Namespace]] = {
|
|
233
|
+
"calendar": CalendarTools,
|
|
234
|
+
"contacts": ContactsTools,
|
|
235
|
+
"docs": DocsTools,
|
|
236
|
+
"drive": DriveTools,
|
|
237
|
+
"forms": FormsTools,
|
|
238
|
+
"gmail": GmailTools,
|
|
239
|
+
"meta": MetaTools,
|
|
240
|
+
"notion": NotionTools,
|
|
241
|
+
"sheets": SheetsTools,
|
|
242
|
+
"slack": SlackTools,
|
|
243
|
+
"slides": SlidesTools,
|
|
244
|
+
"tasks": TasksTools,
|
|
245
|
+
"telegram": TelegramTools,
|
|
246
|
+
}
|
|
@@ -85,12 +85,25 @@ class SecretSpec(BaseModel):
|
|
|
85
85
|
|
|
86
86
|
|
|
87
87
|
class ConnectionSpec(BaseModel):
|
|
88
|
+
"""A third-party service this app reaches through the user's OS connection.
|
|
89
|
+
|
|
90
|
+
`google`/`slack`/`notion`/`telegram`/`meta` are live: the user connects once
|
|
91
|
+
in Connect and the app calls `ctx.connections.<tool>` with no OAuth of its
|
|
92
|
+
own. The remaining slugs are legacy and validate but dispatch nothing.
|
|
93
|
+
"""
|
|
94
|
+
|
|
88
95
|
id: str
|
|
89
|
-
provider: Literal[
|
|
96
|
+
provider: Literal[
|
|
97
|
+
"google", "slack", "notion", "telegram", "meta",
|
|
98
|
+
"instagram", "linear", "hubspot", "stripe", "zendesk", "custom",
|
|
99
|
+
]
|
|
90
100
|
label: str
|
|
91
101
|
auth: Literal["oauth2", "api_key"] = "oauth2"
|
|
92
102
|
scopes: list[str] = Field(default_factory=list)
|
|
93
103
|
required: bool = False
|
|
104
|
+
# Tool names the app may call, e.g. ["gmail.search", "gmail.send"]. Empty
|
|
105
|
+
# grants every read-only tool the provider offers.
|
|
106
|
+
tools: list[str] = Field(default_factory=list)
|
|
94
107
|
|
|
95
108
|
|
|
96
109
|
class AppServiceRouteSpec(BaseModel):
|
|
@@ -331,7 +344,7 @@ class PluginManifest(BaseModel):
|
|
|
331
344
|
requires: RequiresSpec | None = None
|
|
332
345
|
consumes: ConsumesSpec | None = None
|
|
333
346
|
mcp: McpSpec | None = None
|
|
334
|
-
platform_services: list[Literal["llm", "redis", "storage", "vector"]] | dict[str, PlatformServiceSpec] = Field(default_factory=list)
|
|
347
|
+
platform_services: list[Literal["llm", "redis", "storage", "vector", "web"]] | dict[str, PlatformServiceSpec] = Field(default_factory=list)
|
|
335
348
|
rating: float = 0.0
|
|
336
349
|
reviews: int = 0
|
|
337
350
|
featured: bool = False
|
|
@@ -375,3 +375,125 @@ class LocalVectorService:
|
|
|
375
375
|
if index:
|
|
376
376
|
return {"index": index, "count": len(self._items.get(index, {}))}
|
|
377
377
|
return {"indexes": {name: len(items) for name, items in self._items.items()}}
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
class LocalLLMService:
|
|
381
|
+
"""`ctx.llm` for pltt dev.
|
|
382
|
+
|
|
383
|
+
Hosted, this is the platform's key under an org spend cap. Locally there is
|
|
384
|
+
no platform, so it uses the developer's own `OPENAI_API_KEY` when the dev
|
|
385
|
+
env supplies one and falls back to a deterministic stub otherwise — the app's
|
|
386
|
+
code path stays exercisable with zero setup.
|
|
387
|
+
"""
|
|
388
|
+
|
|
389
|
+
def __init__(self, api_key: str | None = None, model: str = "gpt-5.4-mini"):
|
|
390
|
+
self.api_key = api_key or ""
|
|
391
|
+
self.model = model
|
|
392
|
+
|
|
393
|
+
@property
|
|
394
|
+
def live(self) -> bool:
|
|
395
|
+
return bool(self.api_key)
|
|
396
|
+
|
|
397
|
+
@staticmethod
|
|
398
|
+
def _last_user(messages: list[dict[str, Any]]) -> str:
|
|
399
|
+
for message in reversed(messages or []):
|
|
400
|
+
if str(message.get("role") or "user") == "user":
|
|
401
|
+
return str(message.get("content") or "")
|
|
402
|
+
return ""
|
|
403
|
+
|
|
404
|
+
def _stub(self, messages: list[dict[str, Any]]) -> dict[str, Any]:
|
|
405
|
+
return {
|
|
406
|
+
"text": f"[pltt dev: no LLM key] {self._last_user(messages)}",
|
|
407
|
+
"model": "pltt-dev-stub",
|
|
408
|
+
"input_tokens": 0,
|
|
409
|
+
"output_tokens": 0,
|
|
410
|
+
"cost_usd": 0.0,
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
async def chat(
|
|
414
|
+
self,
|
|
415
|
+
messages: list[dict[str, Any]],
|
|
416
|
+
*,
|
|
417
|
+
model: str | None = None,
|
|
418
|
+
system: str | None = None,
|
|
419
|
+
max_tokens: int = 1024,
|
|
420
|
+
temperature: float = 0.2,
|
|
421
|
+
) -> dict[str, Any]:
|
|
422
|
+
if not self.live:
|
|
423
|
+
return self._stub(messages)
|
|
424
|
+
from openai import AsyncOpenAI
|
|
425
|
+
|
|
426
|
+
payload = ([{"role": "system", "content": system}] if system else []) + list(messages)
|
|
427
|
+
reply = await AsyncOpenAI(api_key=self.api_key).chat.completions.create(
|
|
428
|
+
model=model or self.model, messages=payload, max_completion_tokens=max_tokens
|
|
429
|
+
)
|
|
430
|
+
usage = reply.usage
|
|
431
|
+
return {
|
|
432
|
+
"text": reply.choices[0].message.content or "",
|
|
433
|
+
"model": reply.model,
|
|
434
|
+
"input_tokens": getattr(usage, "prompt_tokens", 0),
|
|
435
|
+
"output_tokens": getattr(usage, "completion_tokens", 0),
|
|
436
|
+
"cost_usd": None,
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
async def stream(self, messages: list[dict[str, Any]], **kwargs):
|
|
440
|
+
if not self.live:
|
|
441
|
+
yield self._stub(messages)["text"]
|
|
442
|
+
return
|
|
443
|
+
from openai import AsyncOpenAI
|
|
444
|
+
|
|
445
|
+
system = kwargs.get("system")
|
|
446
|
+
payload = ([{"role": "system", "content": system}] if system else []) + list(messages)
|
|
447
|
+
stream = await AsyncOpenAI(api_key=self.api_key).chat.completions.create(
|
|
448
|
+
model=kwargs.get("model") or self.model,
|
|
449
|
+
messages=payload,
|
|
450
|
+
max_completion_tokens=kwargs.get("max_tokens", 1024),
|
|
451
|
+
stream=True,
|
|
452
|
+
)
|
|
453
|
+
async for chunk in stream:
|
|
454
|
+
delta = chunk.choices[0].delta if chunk.choices else None
|
|
455
|
+
if delta and delta.content:
|
|
456
|
+
yield delta.content
|
|
457
|
+
|
|
458
|
+
async def embed(self, texts: list[str]) -> list[list[float]]:
|
|
459
|
+
if not self.live:
|
|
460
|
+
# Same deterministic hash embedding LocalVectorService uses, so
|
|
461
|
+
# similarity search behaves consistently offline.
|
|
462
|
+
return [_text_vector(text) for text in texts]
|
|
463
|
+
from openai import AsyncOpenAI
|
|
464
|
+
|
|
465
|
+
reply = await AsyncOpenAI(api_key=self.api_key).embeddings.create(
|
|
466
|
+
model="text-embedding-3-small", input=list(texts)
|
|
467
|
+
)
|
|
468
|
+
return [item.embedding for item in reply.data]
|
|
469
|
+
|
|
470
|
+
async def image(self, prompt: str, *, aspect_ratio: str = "1:1") -> tuple[bytes, str]:
|
|
471
|
+
raise NotImplementedError("ctx.llm.image runs on the platform only — use pltt dev --sandbox")
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
class LocalWebService:
|
|
475
|
+
"""`ctx.web` for pltt dev — keyless DuckDuckGo search plus a plain fetch."""
|
|
476
|
+
|
|
477
|
+
async def search(self, query: str, *, limit: int = 5, topic: str | None = None) -> dict[str, Any]:
|
|
478
|
+
try:
|
|
479
|
+
from ddgs import DDGS
|
|
480
|
+
except ImportError:
|
|
481
|
+
return {"results": [], "error": "pip install ddgs to use ctx.web.search in pltt dev"}
|
|
482
|
+
import asyncio
|
|
483
|
+
|
|
484
|
+
def _run() -> list[dict[str, Any]]:
|
|
485
|
+
with DDGS() as ddgs:
|
|
486
|
+
return [
|
|
487
|
+
{"title": r.get("title", ""), "url": r.get("href", ""), "content": r.get("body", "")}
|
|
488
|
+
for r in ddgs.text(query, max_results=limit)
|
|
489
|
+
]
|
|
490
|
+
|
|
491
|
+
return {"results": await asyncio.to_thread(_run)}
|
|
492
|
+
|
|
493
|
+
async def fetch(self, url: str) -> str:
|
|
494
|
+
import httpx
|
|
495
|
+
|
|
496
|
+
async with httpx.AsyncClient(timeout=20, follow_redirects=True) as client:
|
|
497
|
+
response = await client.get(url)
|
|
498
|
+
response.raise_for_status()
|
|
499
|
+
return response.text
|