@palettelab/cli 0.3.62 → 0.3.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +185 -9
  2. package/backend-sdk/palette_sdk/__init__.py +13 -1
  3. package/backend-sdk/palette_sdk/connections.py +49 -11
  4. package/backend-sdk/palette_sdk/connections_generated.py +246 -0
  5. package/backend-sdk/palette_sdk/data_rooms.py +2 -2
  6. package/backend-sdk/palette_sdk/db/base.py +4 -1
  7. package/backend-sdk/palette_sdk/db/rls.py +7 -1
  8. package/backend-sdk/palette_sdk/manifest.py +16 -2
  9. package/backend-sdk/palette_sdk/platform_services.py +400 -0
  10. package/backend-sdk/palette_sdk/plugin_context.py +41 -2
  11. package/backend-sdk/palette_sdk/plugin_router.py +64 -8
  12. package/backend-sdk/palette_sdk/repository.py +12 -3
  13. package/backend-sdk/palette_sdk/talk.py +65 -0
  14. package/backend-sdk/palette_sdk/tasks.py +117 -0
  15. package/backend-sdk/pyproject.toml +1 -1
  16. package/docs/python-backend-sdk.md +196 -9
  17. package/lib/bundler.js +64 -0
  18. package/lib/cli.js +25 -3
  19. package/lib/commands/capabilities.js +1 -1
  20. package/lib/commands/connections.js +234 -0
  21. package/lib/commands/dev.js +75 -1
  22. package/lib/commands/doctor.js +85 -0
  23. package/lib/commands/open.js +43 -0
  24. package/lib/commands/platform.js +137 -0
  25. package/lib/commands/test.js +47 -4
  26. package/lib/connection-catalog.json +1185 -0
  27. package/lib/dev-simulator.js +232 -3
  28. package/lib/manifest.js +115 -5
  29. package/package.json +1 -1
  30. package/template-fallback/README.md +9 -0
  31. package/template-fallback/frontend/src/translations.ts +2 -2
  32. package/template-fallback/package.json +1 -1
  33. package/template-fallback/palette-plugin.json +1 -0
  34. package/template-fallback/templates/agent-tool/palette-plugin.json +1 -0
  35. package/template-fallback/templates/consumer-app/package.json +1 -1
  36. package/template-fallback/templates/consumer-app/palette-plugin.json +1 -0
  37. package/template-fallback/templates/dashboard/package.json +1 -1
  38. package/template-fallback/templates/dashboard/palette-plugin.json +1 -0
  39. package/template-fallback/templates/database/package.json +1 -1
  40. package/template-fallback/templates/database/palette-plugin.json +1 -0
  41. package/template-fallback/templates/external-service/package.json +1 -1
  42. package/template-fallback/templates/external-service/palette-plugin.json +1 -0
  43. package/template-fallback/templates/frontend-only/package.json +1 -1
  44. package/template-fallback/templates/frontend-only/palette-plugin.json +1 -0
  45. package/template-fallback/templates/next/package.json +1 -1
  46. package/template-fallback/templates/next/palette-plugin.json +1 -0
  47. package/template-fallback/templates/palette-app/package.json +1 -1
  48. package/template-fallback/templates/palette-app/palette-plugin.json +1 -0
  49. package/template-fallback/templates/provider-app/package.json +1 -1
  50. package/template-fallback/templates/provider-app/palette-plugin.json +1 -0
package/README.md CHANGED
@@ -308,13 +308,14 @@ async def create_invoice(body: InvoiceIn, ctx: PluginContext = Depends(get_plugi
308
308
 
309
309
  Backend SDK features for app-owned data:
310
310
 
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`.
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.tasks`, `ctx.redis`, `ctx.vector`, `ctx.llm`, `ctx.media`, `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.status(id)`, `ctx.connections.require(id)`, and `ctx.connections.access_token(id)` read Palette-managed third-party connections declared in `palette-plugin.json`.
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
+ - `ctx.tasks` puts work on the caller's task board and reads it back — `create(title, **fields)`, `list(status=..., limit=...)`, `get`, `update`, `complete(id, output=...)`, `fail`, `delete`. Needs `tasks:read` / `tasks:write`. An app sees **only the tasks it created**: every row is stamped with the app id, another app's task reads as missing, and provenance fields (`app_id`, `source`, `external_ref`, …) are refused rather than silently overwritten.
318
319
  - `ctx.has_permission("...")`, `ctx.has_any_permission([...])`, and `ctx.has_all_permissions([...])` check declared permissions.
319
320
  - `ctx.config_value("key")` and `ctx.require_config("key")` read app install/config values.
320
321
  - `ctx.secret("KEY")` reads app secrets from config or environment variables.
@@ -323,6 +324,12 @@ Backend SDK features for app-owned data:
323
324
  - `ctx.redis` gives a Redis-backed, plugin/org-scoped Redis API when `"redis"` is declared in `platform_services`.
324
325
  - `ctx.vector` gives a Qdrant-backed, plugin/org-scoped vector API when `"vector"` is declared in `platform_services`.
325
326
  - `ctx.storage` gives app/org-scoped file upload helpers when `"storage"` is declared in `platform_services`.
327
+ - `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.
328
+ - `ctx.llm` also takes provider passthrough (`response_format`, `top_p`, `stop`, `seed`, …) as plain keywords, and reports `ctx.llm.models()` / `ctx.llm.spend()` so an app can offer a real model picker and explain a refusal.
329
+ - `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` handle multi-minute renders, `upload` puts local bytes on fal's CDN, and `save` copies an output into the app's own storage — fal's URLs expire. It shares one monthly wallet with `ctx.llm`.
330
+ - `ctx.web` gives web search and an SSRF-guarded page reader (HTML tables and PDFs handled) when `"web"` is declared.
331
+ - `pltt platform list` prints every service above with a snippet and its `pltt dev` mode; `pltt platform enable <name>` writes the manifest declaration.
332
+ - `ctx.connections` gives the viewer's OS service connections — see `pltt connections`.
326
333
  - `@job(...)`, `JobExecution`, and `ctx.jobs` provide durable async work with retries, progress, status, and cancellation.
327
334
  - `LifecycleHooks` lets apps define install/update/enable/disable/uninstall hooks.
328
335
  - `OrgScopedTable` and `PluginBase` keep app data inside the plugin schema model set.
@@ -515,6 +522,30 @@ await notifications.push({
515
522
  Both helpers create a live toast plus a notification-center entry. Use these
516
523
  helpers rather than hand-building platform notification API calls.
517
524
 
525
+ ### Talk messages from Python backends
526
+
527
+ A notification goes to one person's bell. To say something in a room instead,
528
+ post into Talk as your app's own agent identity — the agent members `@`-mention
529
+ and DM:
530
+
531
+ ```python
532
+ from palette_sdk import PluginContext, get_plugin_context, require_permission
533
+
534
+ @router.post("/digest", dependencies=[require_permission("chat:write")])
535
+ async def send_digest(ctx: PluginContext = Depends(get_plugin_context)):
536
+ for room in await ctx.talk.channels():
537
+ await ctx.talk.post("Nightly digest is ready.", channel=room["id"])
538
+ ```
539
+
540
+ `channel` takes a channel id or its name (`"general"`, `"#general"`), and an
541
+ `@Name` in the text mentions that member or agent exactly as a typed message
542
+ does. Declare `chat:write` in `permissions`, and have a member invite the app's
543
+ agent to the channel first — an app posts into the rooms it was invited to and
544
+ nowhere else, and `ctx.talk.channels()` (ids, names, types) is the only Talk
545
+ read it gets. During `pltt dev` nothing reaches a real channel: the simulator
546
+ reports one fake seat and logs each post as `[palette-talk] {...}`. See
547
+ `docs/python-backend-sdk.md` ("Talk Messages From Python") for details.
548
+
518
549
  During `pltt dev`, frontend pushes call the platform backend directly
519
550
  (`NEXT_PUBLIC_API_URL`, default `http://localhost:8000`) in the user's session,
520
551
  so they land in the real notification pool. Backend pushes run against the
@@ -542,10 +573,15 @@ Templates:
542
573
  - `dashboard`
543
574
  - `palette-app`
544
575
  - `next`
545
- - `agent-tool`
576
+ - `agent-tool` (`agent-ready` is an alias)
546
577
  - `external-service`
547
578
  - `database`
548
579
  - `frontend-only`
580
+ - `provider-app` — publishes OS-broker services for other apps
581
+ - `consumer-app` — consumes another app's services/events
582
+
583
+ `pltt init` clones the official template repository and falls back to the
584
+ bundled copy under `template-fallback/` when git or the network is unavailable.
549
585
 
550
586
  ### Palette App Router
551
587
 
@@ -656,6 +692,13 @@ For developer sandboxes where manual approval should not block OS testing, run t
656
692
  `pltt preview --env staging` is also supported as a developer-friendly alias
657
693
  for the same hosted preview flow.
658
694
 
695
+ `pltt dev --sandbox --watch` keeps the preview alive after publishing: the CLI
696
+ rebuilds the frontend entry on every save and pushes the new bundle onto the
697
+ existing preview record, so the hosted OS shows the change without a second
698
+ publish or review. Only frontend changes are live-pushed; backend changes need
699
+ a re-run. `--ttl-hours <n>` overrides the 24-hour preview TTL and `--json`
700
+ emits the publish record instead of the human log.
701
+
659
702
  `pltt dev --platform` runs the full Docker `platform-dev` image for internal platform parity testing. App developers should not need it. It pulls `ghcr.io/palette-lab/platform-dev:latest` and mounts your plugin at `/plugins/<your-id>`.
660
703
 
661
704
  Environment variables:
@@ -706,7 +749,7 @@ install-scoped values or labels/help text:
706
749
  "STRIPE_SECRET": { "scope": "plugin", "required": true },
707
750
  "DEBUG_PROBE_URL": { "scope": "dev", "required": false }
708
751
  },
709
- "platform_services": ["llm", "redis", "storage", "vector"]
752
+ "platform_services": ["llm", "media", "redis", "storage", "vector", "web"]
710
753
  }
711
754
  ```
712
755
 
@@ -800,9 +843,16 @@ Save a Palette sandbox or production environment URL plus token in `~/.palette/c
800
843
 
801
844
  ```bash
802
845
  pltt login --env staging --url https://sandbox.pltt.ai --token <publish-token>
846
+ pltt login --env production --url https://palette.example.com --token <token> --no-default
803
847
  pltt dev --sandbox --env staging
804
848
  ```
805
849
 
850
+ The saved environment becomes the default for `--env`-less commands unless
851
+ `--no-default` is passed. `--url` and `--token` fall back to
852
+ `PALETTE_PLATFORM_URL` / `PALETTE_<ENV>_URL` and `PALETTE_PUBLISH_TOKEN` /
853
+ `PALETTE_<ENV>_TOKEN` (`PALETTE_PROD_TOKEN` for `production`). `--json` prints
854
+ the saved record.
855
+
806
856
  ### `pltt version`
807
857
 
808
858
  Show the installed `pltt` CLI version.
@@ -839,7 +889,13 @@ Check local tooling and common setup problems.
839
889
  pltt doctor
840
890
  ```
841
891
 
842
- Checks include Node version, port availability, manifest validity, entry files, and frontend bundling.
892
+ Checks include Node version, port availability, manifest validity, entry files,
893
+ and frontend bundling. It also reports every declared platform service with the
894
+ mode `pltt dev` will run it in (live via your own key, or stubbed), names the
895
+ available set when an app declares none, and warns when a manifest declares a
896
+ permission that gates nothing today (`agents:*`, `routines:*`, `resources:*`) —
897
+ those stay valid so published manifests keep working, but a reviewer reading
898
+ "agents:write" on an app should not believe it can write agents.
843
899
 
844
900
  Docker is intentionally skipped by default:
845
901
 
@@ -893,9 +949,11 @@ pltt publish --env production
893
949
  pltt publish --env production -y
894
950
  pltt publish --env staging --json
895
951
  pltt publish --env staging --ttl-hours 24
952
+ pltt publish --env staging --preview
896
953
  ```
897
954
 
898
- Publishing first runs the same contract checks as `pltt test`. Preview publishes skip the release semver bump check, while release publishes still require a version newer than the last release. If preflight passes, it bundles frontend/backend artifacts, uploads them, creates a review record, and prints review/preview URLs when the platform returns them.
955
+ `--preview` (or `--publish-type preview`) publishes a reviewable preview
956
+ instead of a release; `--release` is the default. Publishing first runs the same contract checks as `pltt test`. Preview publishes skip the release semver bump check, while release publishes still require a version newer than the last release. If preflight passes, it bundles frontend/backend artifacts, uploads them, creates a review record, and prints review/preview URLs when the platform returns them.
899
957
 
900
958
  `--ttl-hours` sets an expiration on the preview URL. It is mainly used by `pltt dev --sandbox`, which defaults previews to 24 hours.
901
959
 
@@ -925,6 +983,102 @@ pltt logs --json
925
983
 
926
984
  If no plugin ID is provided, the CLI uses the current `palette-plugin.json` or `.palette/last-publish.json`.
927
985
 
986
+ ### `pltt open`
987
+
988
+ Open the preview URL from the last publish in your default browser.
989
+
990
+ ```bash
991
+ pltt dev --sandbox --env staging
992
+ pltt open
993
+ ```
994
+
995
+ Reads `.palette/last-publish.json`; fails with a hint when no publish has run
996
+ yet or the last publish returned no preview URL.
997
+
998
+ ### `pltt platform`
999
+
1000
+ The services the **platform** lends your app through `ctx.*`. Declaring one is
1001
+ what replaces shipping an API key: the platform's own credential is used,
1002
+ metered per organisation, and the installing org has nothing to paste in.
1003
+
1004
+ ```bash
1005
+ pltt platform list # every ctx.* service, a snippet, and its pltt dev mode
1006
+ pltt platform list --json
1007
+ pltt platform enable llm media # writes platform_services into palette-plugin.json
1008
+ pltt platform disable web
1009
+ ```
1010
+
1011
+ | Service | Replaces | `ctx.*` |
1012
+ |---|---|---|
1013
+ | `llm` | `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` | chat, streaming, embeddings, image generation |
1014
+ | `media` | `FAL_KEY` | fal.ai — image, video, speech, transcription, any model fal publishes |
1015
+ | `web` | `TAVILY_API_KEY` / `SERPAPI_KEY` | search + SSRF-guarded page reader |
1016
+ | `storage` | an S3/GCS bucket | per-app, per-org objects with resumable uploads |
1017
+ | `vector` | a Pinecone/Qdrant account | namespaced vector search |
1018
+ | `redis` | `REDIS_URL` | KV, lists, sets, sorted sets, counters, locks |
1019
+
1020
+ `list` also prints the **permission-gated** clients — `ctx.tasks`,
1021
+ `ctx.data_rooms`, `ctx.members`, `ctx.talk` — and whether your manifest has
1022
+ granted them, so "what can `ctx` do, and what do I declare to get it" is one
1023
+ answer.
1024
+
1025
+ Notes:
1026
+
1027
+ - `enable` preserves the object form, so per-service `billing` / `required`
1028
+ settings you already wrote are kept.
1029
+ - `llm` and `media` share **one** monthly wallet per (app, organisation) and
1030
+ both fail closed. `ctx.llm.spend()` reports what is left.
1031
+ - Under `pltt dev` there is no platform: `llm` and `media` use your own
1032
+ `OPENAI_API_KEY` / `FAL_KEY` when `.env.local` has them and return
1033
+ deterministic stubs when it does not. `pltt doctor` prints which mode each
1034
+ one is in.
1035
+
1036
+ `pltt platform` is about what the *platform* provides. For app-to-app contracts
1037
+ see `pltt services`; for third-party accounts the *user* connected see
1038
+ `pltt connections`.
1039
+
1040
+ ### `pltt connections`
1041
+
1042
+ Use the third-party services the OS already holds — Gmail, Drive, Calendar,
1043
+ Sheets, Docs, Slack, Notion, Telegram, Meta.
1044
+
1045
+ Your app does **no OAuth of its own and never holds a provider token**. The user
1046
+ connects a provider once in Palette Connect; your app declares the tools it
1047
+ needs; the user grants them with one click; the platform proxies every call,
1048
+ keeping the scope check, write approval and audit trail in place.
1049
+
1050
+ ```bash
1051
+ pltt connections list --tools # every provider + tool
1052
+ pltt connections add google --tools gmail.search,gmail.send
1053
+ pltt connections pull # typed helpers for your app
1054
+ pltt connections mock google.gmail.search --result '{"messages":[]}'
1055
+ ```
1056
+
1057
+ Then, in your app:
1058
+
1059
+ ```python
1060
+ # backend
1061
+ messages = await ctx.connections.gmail.search(query="invoice newer_than:7d")
1062
+ ```
1063
+
1064
+ ```ts
1065
+ // frontend
1066
+ await palette.connections.gmail.search({ query: "invoice newer_than:7d" })
1067
+ ```
1068
+
1069
+ Subcommands:
1070
+
1071
+ - `list`: providers and their tools, marking the ones your manifest declares. `--tools` expands every tool.
1072
+ - `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.
1073
+ - `pull`: generates typed helpers for the tools you declared into `.palette/types/connections.ts`. Python is already typed by `palette-sdk`.
1074
+ - `mock <provider>.<tool> [--result JSON]`: seeds `.palette/connections.local.json` so `pltt dev` answers the call offline.
1075
+
1076
+ Notes:
1077
+
1078
+ - 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.
1079
+ - `424` means the user has not connected (or granted) the provider — the connection status carries a `connect_url` to send them to.
1080
+ - One entry per provider: the platform resolves a grant by provider, so two entries on the same one are rejected at publish.
1081
+
928
1082
  ### `pltt services`
929
1083
 
930
1084
  Inspect and generate OS-broker service integrations declared through
@@ -947,7 +1101,7 @@ pltt services pull --env staging
947
1101
  pltt services scaffold approvalChain.get
948
1102
  pltt capabilities add creative.poster.generate --method poster.generate --risk write --effects artifact.create --idempotent
949
1103
  pltt capabilities list
950
- pltt test --agent
1104
+ pltt test
951
1105
  ```
952
1106
 
953
1107
  Subcommands:
@@ -996,9 +1150,31 @@ Provider methods can use inline JSON Schema objects or schema file paths in
996
1150
  `schema` or `payload_schema`. The CLI scaffolds schema files by default because
997
1151
  they are easier to review and reuse for generated clients.
998
1152
 
1153
+ ### `pltt capabilities`
1154
+
1155
+ Manage agent-callable capabilities: provider methods that Palette agents may
1156
+ invoke or schedule on the user's behalf. `pltt capability` is an alias.
1157
+
1158
+ ```bash
1159
+ pltt capabilities list [--json]
1160
+ pltt capabilities inspect creative.poster.generate
1161
+ pltt capabilities add creative.poster.generate --method poster.generate --risk write --effects artifact.create --idempotent
1162
+ pltt capabilities add reports.export --risk read
1163
+ pltt capabilities add mail.send --risk write --no-scheduling
1164
+ ```
1165
+
1166
+ Subcommands:
1167
+
1168
+ - `list`: agent-exposable methods declared in `provides.services`, with their `capability_id`, risk, effects, and scheduling flags.
1169
+ - `inspect <capability_id>`: the full manifest entry for one capability.
1170
+ - `add <domain.resource.action>`: scaffolds a provider method (schemas + Python handler stub, like `pltt services scaffold`) and marks it agent-exposable. `--method <name>` overrides the derived method name, `--risk read|write|destructive|controlled` (default `read`), `--effects a,b` lists side effects. `write`/`destructive` capabilities must pass `--idempotent` to be schedulable, or `--no-scheduling` for interactive-only actions.
1171
+
1172
+ `pltt test` verifies every agent capability has a stable `capability_id` and a
1173
+ matching `@capability(...)` / `service(..., agent_exposable=True)` handler.
1174
+
999
1175
  ## Global Flags
1000
1176
 
1001
- - `--json` emits machine-readable output for `package`, `publish`, `status`, `logs`, `test`, `update`, and `version`.
1177
+ - `--json` emits machine-readable output for `package`, `publish`, `status`, `logs`, `test`, `update`, `version`, `login`, `dev --sandbox`, `platform list`, `services list`, and `capabilities`.
1002
1178
  - `-v, --version` prints the installed `pltt` CLI version.
1003
1179
  - `--env <name>` selects a configured publish/status/logs environment.
1004
1180
  - `-y, --yes` skips production publish confirmation.
@@ -8,9 +8,15 @@ 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
12
+ from palette_sdk.tasks import TasksClient
11
13
  from palette_sdk.platform_services import (
14
+ LocalLLMService,
15
+ LocalMediaService,
12
16
  LocalRedisService,
13
17
  LocalVectorService,
18
+ LocalWebService,
19
+ MediaStillRunning,
14
20
  PlatformServiceUnavailable,
15
21
  UnavailablePlatformService,
16
22
  )
@@ -79,8 +85,14 @@ __all__ = [
79
85
  "OrganizationInfo",
80
86
  "NotificationsClient",
81
87
  "NotificationRecipient",
88
+ "TalkClient",
89
+ "TasksClient",
90
+ "LocalLLMService",
91
+ "LocalMediaService",
82
92
  "LocalRedisService",
83
93
  "LocalVectorService",
94
+ "LocalWebService",
95
+ "MediaStillRunning",
84
96
  "PlatformServiceUnavailable",
85
97
  "UnavailablePlatformService",
86
98
  "OrgRepository",
@@ -136,4 +148,4 @@ __all__ = [
136
148
  "LocalStorageService",
137
149
  ]
138
150
 
139
- __version__ = "0.1.12"
151
+ __version__ = "0.1.15"
@@ -1,11 +1,22 @@
1
- """Palette-managed third-party connection helpers."""
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 install-scoped third-party connections for a plugin."""
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
- if self._adapter is not None and hasattr(self._adapter, "access_token"):
77
- token = await self._adapter.access_token(connection_id)
78
- if token:
79
- return str(token)
80
- status = await self.require(connection_id)
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
+ )