@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
|
@@ -16,6 +16,7 @@ from palette_sdk.apps import AppInteropClient
|
|
|
16
16
|
from palette_sdk.members import OrganizationMembersClient
|
|
17
17
|
from palette_sdk.notifications import NotificationsClient
|
|
18
18
|
from palette_sdk.organization import OrganizationInfo
|
|
19
|
+
from palette_sdk.talk import TalkClient
|
|
19
20
|
from palette_sdk.platform_services import UnavailablePlatformService
|
|
20
21
|
from palette_sdk.events import EventPublisher
|
|
21
22
|
from palette_sdk.jobs import JobsClient
|
|
@@ -48,6 +49,7 @@ class PluginContext:
|
|
|
48
49
|
storage: Storage service for file upload/download
|
|
49
50
|
members: Organization member helpers for the current org
|
|
50
51
|
notifications: OS notification center push helpers
|
|
52
|
+
talk: Post into Talk channels as the app's own agent identity
|
|
51
53
|
"""
|
|
52
54
|
db: AsyncSession
|
|
53
55
|
user_id: str
|
|
@@ -62,8 +64,14 @@ class PluginContext:
|
|
|
62
64
|
apps: AppInteropClient = field(default_factory=AppInteropClient)
|
|
63
65
|
members: OrganizationMembersClient = field(default_factory=OrganizationMembersClient)
|
|
64
66
|
notifications: NotificationsClient = field(default_factory=NotificationsClient)
|
|
67
|
+
talk: TalkClient = field(default_factory=TalkClient)
|
|
65
68
|
redis: Any = field(default_factory=lambda: UnavailablePlatformService("redis"))
|
|
66
69
|
vector: Any = field(default_factory=lambda: UnavailablePlatformService("vector"))
|
|
70
|
+
# The platform's own model keys, under a per-org spend cap — declare
|
|
71
|
+
# platform_services: ["llm"] instead of shipping an OPENAI_API_KEY secret.
|
|
72
|
+
llm: Any = field(default_factory=lambda: UnavailablePlatformService("llm"))
|
|
73
|
+
# Web search + SSRF-guarded page reader — platform_services: ["web"].
|
|
74
|
+
web: Any = field(default_factory=lambda: UnavailablePlatformService("web"))
|
|
67
75
|
events: EventPublisher = field(default_factory=EventPublisher)
|
|
68
76
|
jobs: JobsClient = field(default_factory=JobsClient)
|
|
69
77
|
config: dict[str, Any] = field(default_factory=dict)
|
|
@@ -141,8 +149,14 @@ async def get_plugin_context(request: Request) -> PluginContext:
|
|
|
141
149
|
getattr(state, "plugin_permissions", []),
|
|
142
150
|
),
|
|
143
151
|
notifications=NotificationsClient(getattr(state, "notifications", None)),
|
|
152
|
+
talk=TalkClient(
|
|
153
|
+
getattr(state, "talk", None),
|
|
154
|
+
getattr(state, "plugin_permissions", []),
|
|
155
|
+
),
|
|
144
156
|
redis=getattr(state, "redis", None) or UnavailablePlatformService("redis"),
|
|
145
157
|
vector=getattr(state, "vector", None) or UnavailablePlatformService("vector"),
|
|
158
|
+
llm=getattr(state, "llm", None) or UnavailablePlatformService("llm"),
|
|
159
|
+
web=getattr(state, "web", None) or UnavailablePlatformService("web"),
|
|
146
160
|
events=EventPublisher(getattr(state, "plugin_events", None)),
|
|
147
161
|
jobs=JobsClient(getattr(state, "plugin_jobs", None)),
|
|
148
162
|
config=getattr(state, "plugin_config", {}),
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Backend Talk helpers for plugin Python code.
|
|
2
|
+
|
|
3
|
+
Post into a Talk channel as the app's own agent identity — the agent row the
|
|
4
|
+
platform creates for every installation, the same one members `@`-mention:
|
|
5
|
+
|
|
6
|
+
from palette_sdk import PluginContext, get_plugin_context
|
|
7
|
+
|
|
8
|
+
@router.post("/digest", dependencies=[require_permission("chat:write")])
|
|
9
|
+
async def send_digest(ctx: PluginContext = Depends(get_plugin_context)):
|
|
10
|
+
for room in await ctx.talk.channels():
|
|
11
|
+
await ctx.talk.post("Nightly digest is ready.", channel=room["id"])
|
|
12
|
+
|
|
13
|
+
Requires `chat:write` in the manifest's `permissions`, and the app's agent must
|
|
14
|
+
already be a participant of the target channel — a member invites it the same
|
|
15
|
+
way they invite any agent. An app can post into the rooms it was invited to and
|
|
16
|
+
nowhere else, and it cannot read message history at all.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class TalkClient:
|
|
25
|
+
"""Thin wrapper around the platform-injected Talk service.
|
|
26
|
+
|
|
27
|
+
In production/hosted sandbox the platform injects the service into
|
|
28
|
+
`PluginContext`. In local unit tests, pass a fake service with the same
|
|
29
|
+
async `post`/`channels` methods.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, service: Any = None, permissions: list[str] | None = None):
|
|
33
|
+
self._service = service
|
|
34
|
+
self._permissions = permissions or []
|
|
35
|
+
|
|
36
|
+
def _require_service(self) -> Any:
|
|
37
|
+
if self._service is None:
|
|
38
|
+
raise RuntimeError(
|
|
39
|
+
"Talk service is not available in this runtime. "
|
|
40
|
+
"Run inside Palette OS/hosted sandbox or inject a fake service in tests."
|
|
41
|
+
)
|
|
42
|
+
return self._service
|
|
43
|
+
|
|
44
|
+
def _require_permission(self, permission: str) -> None:
|
|
45
|
+
if permission not in self._permissions:
|
|
46
|
+
raise PermissionError(f"App does not declare required permission: {permission}")
|
|
47
|
+
|
|
48
|
+
async def channels(self) -> list[dict[str, Any]]:
|
|
49
|
+
"""Channels this app's agent is seated in: `{id, name, type}` each.
|
|
50
|
+
|
|
51
|
+
The only Talk read an app gets. Everything else in a room stays private
|
|
52
|
+
to its members.
|
|
53
|
+
"""
|
|
54
|
+
self._require_permission("chat:write")
|
|
55
|
+
return await self._require_service().channels()
|
|
56
|
+
|
|
57
|
+
async def post(self, text: str, *, channel: str) -> dict[str, Any]:
|
|
58
|
+
"""Post `text` to `channel`, as the app's agent. Returns the message.
|
|
59
|
+
|
|
60
|
+
`channel` is a channel id or its name (`"general"`, `"#general"`).
|
|
61
|
+
`@Name` in the text mentions that member or agent exactly as a typed
|
|
62
|
+
message does, so a mentioned agent will answer.
|
|
63
|
+
"""
|
|
64
|
+
self._require_permission("chat:write")
|
|
65
|
+
return await self._require_service().post(text=text, channel=channel)
|
|
@@ -112,14 +112,17 @@ Available context values:
|
|
|
112
112
|
| `ctx.permissions` | Permissions granted from `palette-plugin.json` |
|
|
113
113
|
| `ctx.storage` | Runtime storage service, when available |
|
|
114
114
|
| `ctx.data_rooms` | Backend Data Room client |
|
|
115
|
-
| `ctx.connections` | Palette
|
|
115
|
+
| `ctx.connections` | The viewer's Palette OS connections — `ctx.connections.gmail.search(...)`, no OAuth of your own |
|
|
116
116
|
| `ctx.members` | Current organisation member client |
|
|
117
117
|
| `ctx.notifications` | Push OS notification-center notifications |
|
|
118
|
+
| `ctx.talk` | Post into Talk channels as the app's own agent (`chat:write`, seat required) |
|
|
118
119
|
| `ctx.apps` / `services(ctx)` | Governed app-to-app calls through declared `consumes` contracts |
|
|
119
120
|
| `ctx.events` | Publish event topics declared in `provides.events` |
|
|
120
121
|
| `ctx.jobs` | Enqueue, inspect, and cancel durable background jobs |
|
|
121
122
|
| `ctx.redis` | Plugin/org-scoped Redis-style service when `platform_services` includes `redis` |
|
|
122
123
|
| `ctx.vector` | Plugin/org-scoped vector service when `platform_services` includes `vector` |
|
|
124
|
+
| `ctx.llm` | The platform's own model keys under an org spend cap when `platform_services` includes `llm` |
|
|
125
|
+
| `ctx.web` | Web search + SSRF-guarded page reader when `platform_services` includes `web` |
|
|
123
126
|
| `ctx.config` | App install/config values |
|
|
124
127
|
| `ctx.logger` | Runtime logger for backend code |
|
|
125
128
|
| `ctx.repo(Model)` | Org-safe CRUD helper for app-owned tables |
|
|
@@ -144,6 +147,7 @@ These are the public Python helpers exported by `palette_sdk`.
|
|
|
144
147
|
| `DataRoomsClient`, `ctx.data_rooms` | Backend Data Room room/folder/file helpers |
|
|
145
148
|
| `OrganizationMembersClient`, `ctx.members` | Current-organization member lookup, invite, and role helpers |
|
|
146
149
|
| `NotificationsClient`, `ctx.notifications` | Push notifications into the OS notification center |
|
|
150
|
+
| `TalkClient`, `ctx.talk` | Post into Talk channels the app's agent is seated in |
|
|
147
151
|
| `PluginConnectionsClient`, `ConnectionStatus`, `MissingConnectionError`, `ctx.connections` | Third-party connection status and token helpers |
|
|
148
152
|
| `AppInteropClient`, `AppServiceClient`, `MissingAppServiceError`, `ctx.apps` | Call required apps/services without direct database access |
|
|
149
153
|
| `service(...)`, `services(ctx)`, `ServicesClient`, `BrokerCallError` | Provide and consume OS-broker service methods/events |
|
|
@@ -788,6 +792,38 @@ During `pltt dev` notifications are not delivered to a real notification
|
|
|
788
792
|
center — the simulator logs them as `[palette-notification] {...}` and returns
|
|
789
793
|
a stub response, so your code paths still run.
|
|
790
794
|
|
|
795
|
+
## 8b. Talk Messages From Python
|
|
796
|
+
|
|
797
|
+
Every installed app has an agent identity in Talk — the agent members
|
|
798
|
+
`@`-mention and DM. `ctx.talk` lets your backend speak as it, for the moments
|
|
799
|
+
your app has something to say first (a finished export, a nightly digest, an
|
|
800
|
+
alert from a scheduled job):
|
|
801
|
+
|
|
802
|
+
```python
|
|
803
|
+
from palette_sdk import PluginContext, get_plugin_context, require_permission
|
|
804
|
+
|
|
805
|
+
@router.post("/digest", dependencies=[require_permission("chat:write")])
|
|
806
|
+
async def send_digest(ctx: PluginContext = Depends(get_plugin_context)):
|
|
807
|
+
for room in await ctx.talk.channels():
|
|
808
|
+
await ctx.talk.post("Nightly digest is ready.", channel=room["id"])
|
|
809
|
+
```
|
|
810
|
+
|
|
811
|
+
`channel` takes a channel id or its name (`"general"`, `"#general"`). An
|
|
812
|
+
`@Name` in the text mentions that member or agent just as a typed message does,
|
|
813
|
+
so a mentioned agent will answer.
|
|
814
|
+
|
|
815
|
+
Declare `chat:write` in `permissions` or the call raises `PermissionError`. Two
|
|
816
|
+
runtime rules then apply, both fail-closed:
|
|
817
|
+
|
|
818
|
+
- the app's agent must already be a participant of the target channel — a
|
|
819
|
+
member invites it in Talk, so the room's own people decide who may post;
|
|
820
|
+
- `ctx.talk.channels()` is the only read an app gets (ids, names, types of the
|
|
821
|
+
rooms it is seated in). No history, no member list, no search.
|
|
822
|
+
|
|
823
|
+
Available in request handlers, `@capability` methods, and background jobs.
|
|
824
|
+
During `pltt dev` nothing reaches a real channel: the simulator reports one
|
|
825
|
+
fake seat, logs each post as `[palette-talk] {...}`, and returns a stub message.
|
|
826
|
+
|
|
791
827
|
## 9. Config And Secrets
|
|
792
828
|
|
|
793
829
|
Use config for app install settings and secrets for sensitive values.
|
|
@@ -843,6 +879,33 @@ Managed Redis, vector, and storage services are declared in the manifest:
|
|
|
843
879
|
```
|
|
844
880
|
|
|
845
881
|
```python
|
|
882
|
+
# Third-party services — the user connects once in Palette Connect, grants your
|
|
883
|
+
# app the tools your manifest declares, and the platform proxies every call.
|
|
884
|
+
# Your app never holds a provider token, so scope checks, write approval and the
|
|
885
|
+
# audit trail keep working.
|
|
886
|
+
messages = await ctx.connections.gmail.search(query="invoice newer_than:7d")
|
|
887
|
+
await ctx.connections.slack.post_message(channel="#ops", text="digest ready")
|
|
888
|
+
|
|
889
|
+
# Mutating tools (gmail.send, slack.post_message, …) stage for approval by
|
|
890
|
+
# default and return {"queued_for_approval": True, "approval_id", "preview"} —
|
|
891
|
+
# tell the user what you prepared instead of claiming it was sent. An org admin
|
|
892
|
+
# can allow a specific app+provider to write directly.
|
|
893
|
+
sent = await ctx.connections.gmail.send(to="a@b.com", subject="Hi", body="…")
|
|
894
|
+
if sent.get("queued_for_approval"):
|
|
895
|
+
... # render the pending state
|
|
896
|
+
|
|
897
|
+
# The platform's model keys — no OPENAI_API_KEY secret to ship or rotate.
|
|
898
|
+
reply = await ctx.llm.chat([{"role": "user", "content": "Summarise this"}])
|
|
899
|
+
reply["text"], reply["model"], reply["cost_usd"]
|
|
900
|
+
async for chunk in ctx.llm.stream([{"role": "user", "content": "Write a haiku"}]):
|
|
901
|
+
...
|
|
902
|
+
vectors = await ctx.llm.embed(["some text"])
|
|
903
|
+
image_bytes, mime = await ctx.llm.image("a fox in the snow")
|
|
904
|
+
|
|
905
|
+
# Web search + reader (HTML tables and PDFs already handled).
|
|
906
|
+
hits = await ctx.web.search("palette os changelog", limit=5)
|
|
907
|
+
text = await ctx.web.fetch("https://example.com/report.pdf")
|
|
908
|
+
|
|
846
909
|
await ctx.redis.set("cache:summary", {"ready": True}, ttl=600)
|
|
847
910
|
value = await ctx.redis.get("cache:summary")
|
|
848
911
|
|
package/lib/bundler.js
CHANGED
|
@@ -497,6 +497,69 @@ async function bundleFrontend(pluginDir, entry, frontend = {}) {
|
|
|
497
497
|
}
|
|
498
498
|
}
|
|
499
499
|
|
|
500
|
+
/**
|
|
501
|
+
* Watch the frontend entry and hand each successful (minified) bundle to
|
|
502
|
+
* `onBundle(buffer)` — used by `pltt dev --sandbox --watch` to push live
|
|
503
|
+
* frontend updates onto an existing preview publish. Returns the esbuild
|
|
504
|
+
* context (caller disposes).
|
|
505
|
+
*/
|
|
506
|
+
async function watchFrontendBuffer(pluginDir, entry, frontend = {}, onBundle) {
|
|
507
|
+
pluginDir = path.resolve(pluginDir)
|
|
508
|
+
const esbuild = loadEsbuild()
|
|
509
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "palette-frontend-watch-"))
|
|
510
|
+
const bundleEntry = isPaletteApp(frontend)
|
|
511
|
+
? generatePaletteAppEntry(pluginDir, entry || "./frontend/app", path.join(tmp, "entry.tsx"))
|
|
512
|
+
: entry
|
|
513
|
+
const absEntry = path.resolve(pluginDir, bundleEntry)
|
|
514
|
+
if (!fs.existsSync(absEntry)) {
|
|
515
|
+
throw new Error(`frontend entry not found: ${entry}`)
|
|
516
|
+
}
|
|
517
|
+
const buildConfig = frontendBuildConfig(pluginDir, { ...frontend, entry })
|
|
518
|
+
|
|
519
|
+
const ctx = await esbuild.context({
|
|
520
|
+
entryPoints: [absEntry],
|
|
521
|
+
bundle: true,
|
|
522
|
+
outfile: path.join(tmp, "frontend.mjs"),
|
|
523
|
+
format: "esm",
|
|
524
|
+
platform: "browser",
|
|
525
|
+
target: ["es2022"],
|
|
526
|
+
write: false,
|
|
527
|
+
jsx: "automatic",
|
|
528
|
+
loader: { ".ts": "tsx", ".tsx": "tsx", ".js": "jsx", ".jsx": "jsx" },
|
|
529
|
+
define: buildConfig.define,
|
|
530
|
+
external: [
|
|
531
|
+
"react",
|
|
532
|
+
"react-dom",
|
|
533
|
+
"react-dom/client",
|
|
534
|
+
"react/jsx-runtime",
|
|
535
|
+
"react/jsx-dev-runtime",
|
|
536
|
+
"@palettelab/sdk",
|
|
537
|
+
],
|
|
538
|
+
minify: true,
|
|
539
|
+
sourcemap: "inline",
|
|
540
|
+
logLevel: "silent",
|
|
541
|
+
absWorkingDir: pluginDir,
|
|
542
|
+
plugins: [
|
|
543
|
+
...buildConfig.plugins,
|
|
544
|
+
{
|
|
545
|
+
name: "palette-watch-buffer",
|
|
546
|
+
setup(build) {
|
|
547
|
+
build.onEnd((result) => {
|
|
548
|
+
if (result.errors.length) {
|
|
549
|
+
console.error("[pltt] frontend bundle failed:")
|
|
550
|
+
for (const err of result.errors) console.error(` - ${err.text}`)
|
|
551
|
+
return
|
|
552
|
+
}
|
|
553
|
+
onBundle(bundleOutputsToFrontendBuffer(result, pluginCssScopeId(frontend)))
|
|
554
|
+
})
|
|
555
|
+
},
|
|
556
|
+
},
|
|
557
|
+
],
|
|
558
|
+
})
|
|
559
|
+
await ctx.watch()
|
|
560
|
+
return ctx
|
|
561
|
+
}
|
|
562
|
+
|
|
500
563
|
async function watchFrontend(pluginDir, entry, outfile, frontend = {}) {
|
|
501
564
|
pluginDir = path.resolve(pluginDir)
|
|
502
565
|
outfile = path.resolve(outfile)
|
|
@@ -636,6 +699,7 @@ module.exports = {
|
|
|
636
699
|
bundleFrontend,
|
|
637
700
|
bundleBackend,
|
|
638
701
|
watchFrontend,
|
|
702
|
+
watchFrontendBuffer,
|
|
639
703
|
frontendBuildConfig,
|
|
640
704
|
mergePlugins,
|
|
641
705
|
}
|
package/lib/cli.js
CHANGED
|
@@ -12,9 +12,11 @@ const status = require("./commands/status")
|
|
|
12
12
|
const logs = require("./commands/logs")
|
|
13
13
|
const secrets = require("./commands/secrets")
|
|
14
14
|
const services = require("./commands/services")
|
|
15
|
+
const open = require("./commands/open")
|
|
15
16
|
const version = require("./commands/version")
|
|
16
17
|
const update = require("./commands/update")
|
|
17
18
|
const capabilities = require("./commands/capabilities")
|
|
19
|
+
const connections = require("./commands/connections")
|
|
18
20
|
|
|
19
21
|
const COMMANDS = {
|
|
20
22
|
init: { run: init, help: "Scaffold a new plugin directory from the template" },
|
|
@@ -50,10 +52,18 @@ const COMMANDS = {
|
|
|
50
52
|
run: logs,
|
|
51
53
|
help: "Tail telemetry events for a plugin (--follow to stream)",
|
|
52
54
|
},
|
|
55
|
+
open: {
|
|
56
|
+
run: open,
|
|
57
|
+
help: "Open the last publish's preview URL in the browser",
|
|
58
|
+
},
|
|
53
59
|
secrets: {
|
|
54
60
|
run: secrets,
|
|
55
61
|
help: "Initialize local env files and manage plugin-scope secrets",
|
|
56
62
|
},
|
|
63
|
+
connections: {
|
|
64
|
+
run: connections,
|
|
65
|
+
help: "Use the OS service connections (list, add, pull, mock) — no OAuth of your own",
|
|
66
|
+
},
|
|
57
67
|
services: {
|
|
58
68
|
run: services,
|
|
59
69
|
help: "Inspect / pull / scaffold OS-broker services (list, pull, scaffold)",
|
|
@@ -86,6 +96,7 @@ function printHelp() {
|
|
|
86
96
|
console.log("\nDev flags:")
|
|
87
97
|
console.log(" --sandbox Publish a reviewable preview to a configured Palette sandbox (no Docker)")
|
|
88
98
|
console.log(" --cloud Alias for --sandbox")
|
|
99
|
+
console.log(" --watch With --sandbox: live-push frontend changes onto the preview (no republish)")
|
|
89
100
|
console.log(" --platform Internal only: run the Docker platform-dev parity container")
|
|
90
101
|
console.log("\nLogin flags:")
|
|
91
102
|
console.log(" --url <url> Palette platform URL for pltt login")
|
|
@@ -116,7 +127,8 @@ function printHelp() {
|
|
|
116
127
|
console.log(" cd my-app && pltt dev")
|
|
117
128
|
console.log(" pltt sandbox --env staging")
|
|
118
129
|
console.log(" pltt preview --env staging")
|
|
119
|
-
console.log(" pltt dev --sandbox --env staging")
|
|
130
|
+
console.log(" pltt dev --sandbox --watch --env staging")
|
|
131
|
+
console.log(" pltt open")
|
|
120
132
|
console.log(" pltt package")
|
|
121
133
|
console.log(" pltt publish --env staging")
|
|
122
134
|
console.log(" pltt status")
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"use strict"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* pltt connections — use the OS service connections from your app.
|
|
5
|
+
*
|
|
6
|
+
* Your app never does its own OAuth and never holds a provider token. The user
|
|
7
|
+
* connects Google/Slack/… once in Palette Connect; your app declares the tools
|
|
8
|
+
* it needs, the user grants them, and the platform proxies every call (keeping
|
|
9
|
+
* the scope check, write approval and audit trail).
|
|
10
|
+
*
|
|
11
|
+
* pltt connections list — providers + tools, and what you declare
|
|
12
|
+
* pltt connections add <provider> [--tools a,b]
|
|
13
|
+
* — write the connections block
|
|
14
|
+
* pltt connections pull — generate typed stubs for your app
|
|
15
|
+
* pltt connections mock <provider>.<tool> [--result '{...}']
|
|
16
|
+
* — seed a pltt dev response
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const fs = require("fs")
|
|
20
|
+
const path = require("path")
|
|
21
|
+
|
|
22
|
+
const CATALOG = require("../connection-catalog.json")
|
|
23
|
+
|
|
24
|
+
function readManifest(cwd) {
|
|
25
|
+
const p = path.join(cwd, "palette-plugin.json")
|
|
26
|
+
if (!fs.existsSync(p)) throw new Error("no palette-plugin.json found in current directory")
|
|
27
|
+
return JSON.parse(fs.readFileSync(p, "utf8"))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function writeManifest(cwd, manifest) {
|
|
31
|
+
fs.writeFileSync(path.join(cwd, "palette-plugin.json"), JSON.stringify(manifest, null, 2) + "\n")
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function provider(slug) {
|
|
35
|
+
return CATALOG.providers.find((p) => p.slug === slug) || null
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function declaredTools(spec) {
|
|
39
|
+
const known = provider(spec.provider)
|
|
40
|
+
if (!known) return []
|
|
41
|
+
const asked = (spec.tools || []).filter((t) => known.tools.some((k) => k.name === t))
|
|
42
|
+
if (asked.length) return asked
|
|
43
|
+
return known.tools.filter((t) => !t.mutating).map((t) => t.name)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function valueAfter(argv, flag) {
|
|
47
|
+
const i = argv.indexOf(flag)
|
|
48
|
+
return i >= 0 ? argv[i + 1] : undefined
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ---- list --------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
async function runList(argv, { cwd }) {
|
|
54
|
+
let declared = new Map()
|
|
55
|
+
try {
|
|
56
|
+
for (const spec of readManifest(cwd).connections || []) {
|
|
57
|
+
declared.set(spec.provider, new Set(declaredTools(spec)))
|
|
58
|
+
}
|
|
59
|
+
} catch {
|
|
60
|
+
// Outside an app directory — just print the catalog.
|
|
61
|
+
}
|
|
62
|
+
const verbose = argv.includes("--tools") || argv.includes("-v")
|
|
63
|
+
for (const p of CATALOG.providers) {
|
|
64
|
+
const mine = declared.get(p.slug)
|
|
65
|
+
const mark = mine ? `declared (${mine.size} tool${mine.size === 1 ? "" : "s"})` : "not declared"
|
|
66
|
+
console.log(`\n${p.slug.padEnd(10)} ${p.label.padEnd(22)} ${p.auth_type.padEnd(10)} ${mark}`)
|
|
67
|
+
if (!verbose && !mine) {
|
|
68
|
+
console.log(` ${p.tools.length} tools — pltt connections list --tools to see them`)
|
|
69
|
+
continue
|
|
70
|
+
}
|
|
71
|
+
for (const tool of p.tools) {
|
|
72
|
+
const flag = mine?.has(tool.name) ? "✓" : " "
|
|
73
|
+
const write = tool.mutating ? " [write]" : ""
|
|
74
|
+
console.log(` ${flag} ${tool.name}${write}`)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
console.log("\nWrite tools stage for approval unless an org admin allows them for your app.")
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ---- add ---------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
async function runAdd(argv, { cwd }) {
|
|
83
|
+
const slug = argv.find((a) => !a.startsWith("-"))
|
|
84
|
+
const known = provider(slug)
|
|
85
|
+
if (!known) {
|
|
86
|
+
console.error(
|
|
87
|
+
`[pltt] usage: pltt connections add <${CATALOG.providers.map((p) => p.slug).join("|")}> [--tools a,b]`,
|
|
88
|
+
)
|
|
89
|
+
process.exit(1)
|
|
90
|
+
}
|
|
91
|
+
const requested = (valueAfter(argv, "--tools") || "")
|
|
92
|
+
.split(",")
|
|
93
|
+
.map((t) => t.trim())
|
|
94
|
+
.filter(Boolean)
|
|
95
|
+
const unknown = requested.filter((t) => !known.tools.some((k) => k.name === t))
|
|
96
|
+
if (unknown.length) {
|
|
97
|
+
console.error(`[pltt] unknown ${slug} tool(s): ${unknown.join(", ")}`)
|
|
98
|
+
console.error(`[pltt] see: pltt connections list --tools`)
|
|
99
|
+
process.exit(1)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const manifest = readManifest(cwd)
|
|
103
|
+
manifest.connections = manifest.connections || []
|
|
104
|
+
// The platform resolves a grant by provider, so one entry per provider.
|
|
105
|
+
let spec = manifest.connections.find((c) => c && c.provider === slug)
|
|
106
|
+
if (!spec) {
|
|
107
|
+
spec = { id: slug, provider: slug, label: known.label, auth: known.auth_type === "bot_token" ? "api_key" : "oauth2" }
|
|
108
|
+
manifest.connections.push(spec)
|
|
109
|
+
}
|
|
110
|
+
if (requested.length) {
|
|
111
|
+
spec.tools = Array.from(new Set([...(spec.tools || []), ...requested]))
|
|
112
|
+
}
|
|
113
|
+
writeManifest(cwd, manifest)
|
|
114
|
+
const effective = declaredTools(spec)
|
|
115
|
+
console.log(`[pltt] ${slug}: ${effective.length} tool(s) declared`)
|
|
116
|
+
if (!spec.tools) console.log(`[pltt] no --tools given — defaults to every read-only ${slug} tool`)
|
|
117
|
+
console.log(`[pltt] next: pltt connections pull`)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ---- pull --------------------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
function tsType(schemaType) {
|
|
123
|
+
return { integer: "number", number: "number", boolean: "boolean", array: "unknown[]", object: "Record<string, unknown>" }[schemaType] || "string"
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function camel(value) {
|
|
127
|
+
const [head, ...rest] = value.split("_")
|
|
128
|
+
return head + rest.map((p) => p[0].toUpperCase() + p.slice(1)).join("")
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function renderStubs(specs) {
|
|
132
|
+
const lines = [
|
|
133
|
+
"// GENERATED by `pltt connections pull` — do not edit by hand.",
|
|
134
|
+
"//",
|
|
135
|
+
"// Only the tools your palette-plugin.json declares. The platform holds the",
|
|
136
|
+
"// OAuth token and enforces scopes, write approval and audit on every call.",
|
|
137
|
+
"",
|
|
138
|
+
'import { palette } from "@palettelab/sdk"',
|
|
139
|
+
"",
|
|
140
|
+
]
|
|
141
|
+
for (const spec of specs) {
|
|
142
|
+
const known = provider(spec.provider)
|
|
143
|
+
const allowed = new Set(declaredTools(spec))
|
|
144
|
+
for (const tool of known.tools.filter((t) => allowed.has(t.name))) {
|
|
145
|
+
const props = Object.entries(tool.input_schema?.properties || {})
|
|
146
|
+
const required = new Set(tool.input_schema?.required || [])
|
|
147
|
+
const fields = props
|
|
148
|
+
.sort(([a], [b]) => (required.has(b) ? 1 : 0) - (required.has(a) ? 1 : 0) || a.localeCompare(b))
|
|
149
|
+
.map(([name, s]) => `${camel(name)}${required.has(name) ? "" : "?"}: ${tsType(s.type)}`)
|
|
150
|
+
const argMap = props.map(([name]) => `"${name}": args.${camel(name)}`).join(", ")
|
|
151
|
+
const fn = camel(`${tool.namespace}_${tool.method}`)
|
|
152
|
+
lines.push(
|
|
153
|
+
`/** ${tool.description.replace(/\*\//g, "*\\/")}${tool.mutating ? " [write — stages for approval]" : ""} */`,
|
|
154
|
+
`export function ${fn}(${fields.length ? `args: { ${fields.join("; ")} }` : ""}): Promise<unknown> {`,
|
|
155
|
+
` return palette.connections.call("${spec.provider}", "${tool.name}", ${fields.length ? `{ ${argMap} }` : "{}"})`,
|
|
156
|
+
"}",
|
|
157
|
+
"",
|
|
158
|
+
)
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return lines.join("\n")
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function runPull(_argv, { cwd }) {
|
|
165
|
+
const specs = (readManifest(cwd).connections || []).filter((c) => provider(c.provider))
|
|
166
|
+
if (!specs.length) {
|
|
167
|
+
console.log("[pltt] no live connections declared — pltt connections add <provider>")
|
|
168
|
+
return
|
|
169
|
+
}
|
|
170
|
+
const outDir = path.join(cwd, ".palette", "types")
|
|
171
|
+
fs.mkdirSync(outDir, { recursive: true })
|
|
172
|
+
const outFile = path.join(outDir, "connections.ts")
|
|
173
|
+
fs.writeFileSync(outFile, renderStubs(specs))
|
|
174
|
+
const count = specs.reduce((n, s) => n + declaredTools(s).length, 0)
|
|
175
|
+
console.log(`[pltt] wrote ${count} typed helper(s) -> ${path.relative(cwd, outFile)}`)
|
|
176
|
+
console.log("[pltt] python: ctx.connections.<namespace>.<tool>(...) is already typed by palette-sdk")
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ---- mock --------------------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
async function runMock(argv, { cwd }) {
|
|
182
|
+
const target = argv.find((a) => !a.startsWith("-"))
|
|
183
|
+
const [slug, ...rest] = (target || "").split(".")
|
|
184
|
+
const toolName = rest.join(".")
|
|
185
|
+
const known = provider(slug)
|
|
186
|
+
const tool = known?.tools.find((t) => t.name === toolName || t.method === toolName)
|
|
187
|
+
if (!tool) {
|
|
188
|
+
console.error("[pltt] usage: pltt connections mock <provider>.<tool> e.g. google.gmail.search")
|
|
189
|
+
process.exit(1)
|
|
190
|
+
}
|
|
191
|
+
let result = { ok: true, mocked: tool.name }
|
|
192
|
+
const raw = valueAfter(argv, "--result")
|
|
193
|
+
if (raw) {
|
|
194
|
+
try {
|
|
195
|
+
result = JSON.parse(raw)
|
|
196
|
+
} catch (err) {
|
|
197
|
+
console.error(`[pltt] --result must be JSON: ${err.message}`)
|
|
198
|
+
process.exit(1)
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const mockPath = path.join(cwd, ".palette", "connections.local.json")
|
|
203
|
+
fs.mkdirSync(path.dirname(mockPath), { recursive: true })
|
|
204
|
+
const current = fs.existsSync(mockPath) ? JSON.parse(fs.readFileSync(mockPath, "utf8")) : {}
|
|
205
|
+
// Keyed by the manifest connection id so it merges with the status overrides
|
|
206
|
+
// the dev simulator already reads.
|
|
207
|
+
const spec = (readManifest(cwd).connections || []).find((c) => c.provider === slug)
|
|
208
|
+
const key = spec?.id || slug
|
|
209
|
+
current[key] = { ...(current[key] || {}), provider: slug, status: "connected" }
|
|
210
|
+
current[key].tools = { ...(current[key].tools || {}), [tool.name]: result }
|
|
211
|
+
fs.writeFileSync(mockPath, JSON.stringify(current, null, 2) + "\n")
|
|
212
|
+
console.log(`[pltt] mocked ${slug}.${tool.name} -> ${path.relative(cwd, mockPath)}`)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ---- entry -------------------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
module.exports = async function connections(argv, ctx) {
|
|
218
|
+
const [sub, ...rest] = argv
|
|
219
|
+
if (sub === "list") return runList(rest, ctx)
|
|
220
|
+
if (sub === "add") return runAdd(rest, ctx)
|
|
221
|
+
if (sub === "pull") return runPull(rest, ctx)
|
|
222
|
+
if (sub === "mock") return runMock(rest, ctx)
|
|
223
|
+
console.log("pltt connections <command>\n")
|
|
224
|
+
console.log(" list Show OS providers + tools, and which your app declares.")
|
|
225
|
+
console.log(" add Declare a provider (and tools) in palette-plugin.json.")
|
|
226
|
+
console.log(" pull Generate typed helpers for the tools you declared.")
|
|
227
|
+
console.log(" mock Seed a local response for pltt dev.")
|
|
228
|
+
console.log("\nYour app never does its own OAuth: the user connects once in Palette")
|
|
229
|
+
console.log("Connect, grants your app, and the platform proxies every call.")
|
|
230
|
+
if (sub && !["help", "--help", "-h"].includes(sub)) {
|
|
231
|
+
console.error(`\n[pltt] unknown subcommand: ${sub}`)
|
|
232
|
+
process.exit(1)
|
|
233
|
+
}
|
|
234
|
+
}
|