@palettelab/cli 0.3.61 → 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.
Files changed (39) hide show
  1. package/README.md +80 -5
  2. package/backend-sdk/palette_sdk/__init__.py +21 -1
  3. package/backend-sdk/palette_sdk/capabilities.py +126 -0
  4. package/backend-sdk/palette_sdk/connections.py +49 -11
  5. package/backend-sdk/palette_sdk/connections_generated.py +246 -0
  6. package/backend-sdk/palette_sdk/manifest.py +78 -3
  7. package/backend-sdk/palette_sdk/platform_services.py +122 -0
  8. package/backend-sdk/palette_sdk/plugin_context.py +14 -0
  9. package/backend-sdk/palette_sdk/services.py +45 -6
  10. package/backend-sdk/palette_sdk/talk.py +65 -0
  11. package/backend-sdk/pyproject.toml +1 -1
  12. package/docs/python-backend-sdk.md +64 -1
  13. package/lib/bundler.js +64 -0
  14. package/lib/cli.js +27 -2
  15. package/lib/commands/capabilities.js +151 -0
  16. package/lib/commands/connections.js +234 -0
  17. package/lib/commands/dev.js +75 -1
  18. package/lib/commands/doctor.js +70 -0
  19. package/lib/commands/init.js +3 -2
  20. package/lib/commands/open.js +43 -0
  21. package/lib/commands/services.js +74 -8
  22. package/lib/commands/test.js +89 -1
  23. package/lib/connection-catalog.json +1185 -0
  24. package/lib/dev-simulator.js +137 -3
  25. package/lib/manifest.js +90 -6
  26. package/package.json +1 -1
  27. package/template-fallback/package.json +1 -1
  28. package/template-fallback/templates/agent-tool/README.md +6 -2
  29. package/template-fallback/templates/agent-tool/backend/api/main.py +27 -6
  30. package/template-fallback/templates/agent-tool/palette-plugin.json +35 -4
  31. package/template-fallback/templates/consumer-app/package.json +1 -1
  32. package/template-fallback/templates/dashboard/package.json +1 -1
  33. package/template-fallback/templates/database/package.json +1 -1
  34. package/template-fallback/templates/external-service/package.json +1 -1
  35. package/template-fallback/templates/frontend-only/package.json +1 -1
  36. package/template-fallback/templates/next/package.json +1 -1
  37. package/template-fallback/templates/palette-app/package.json +1 -1
  38. package/template-fallback/templates/provider-app/package.json +1 -1
  39. package/template-fallback/templates/agent-tool/backend/tools/echo.py +0 -15
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.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
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,13 +323,19 @@ 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.
329
332
  - `plugin_safe_id(...)`, `plugin_schema(...)`, `plugin_table_prefix(...)`, and `ensure_org_rls(...)` keep database names and row-level security consistent.
330
333
  - `Event` and `subscribe_event(...)` register in-process platform event handlers.
331
334
  - `sign_webhook(...)` and `verify_webhook_signature(...)` handle HMAC-SHA256 webhook signing checks.
332
- - `ToolDefinition` is the base class for custom agent tools.
335
+ - `@capability(...)`, `CapabilityResult`, and `ArtifactRef` define typed,
336
+ broker-governed tools shared by chat agents and visual workflows.
337
+ - `ToolDefinition` is legacy compatibility for existing read-only tools;
338
+ migrate new tools to `@capability(...)`.
333
339
  - `PluginManifest` and `load_manifest(...)` parse and validate `palette-plugin.json`.
334
340
  - `SuccessResponse`, `ErrorResponse`, and `PaginatedResponse` are reusable response schemas.
335
341
  - `route_permission_issues(router, public_routes=None)` is the test helper for detecting ungated backend routes.
@@ -512,6 +518,30 @@ await notifications.push({
512
518
  Both helpers create a live toast plus a notification-center entry. Use these
513
519
  helpers rather than hand-building platform notification API calls.
514
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
+
515
545
  During `pltt dev`, frontend pushes call the platform backend directly
516
546
  (`NEXT_PUBLIC_API_URL`, default `http://localhost:8000`) in the user's session,
517
547
  so they land in the real notification pool. Backend pushes run against the
@@ -703,7 +733,7 @@ install-scoped values or labels/help text:
703
733
  "STRIPE_SECRET": { "scope": "plugin", "required": true },
704
734
  "DEBUG_PROBE_URL": { "scope": "dev", "required": false }
705
735
  },
706
- "platform_services": ["llm", "redis", "storage", "vector"]
736
+ "platform_services": ["llm", "redis", "storage", "vector", "web"]
707
737
  }
708
738
  ```
709
739
 
@@ -922,6 +952,48 @@ pltt logs --json
922
952
 
923
953
  If no plugin ID is provided, the CLI uses the current `palette-plugin.json` or `.palette/last-publish.json`.
924
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
+
925
997
  ### `pltt services`
926
998
 
927
999
  Inspect and generate OS-broker service integrations declared through
@@ -942,13 +1014,16 @@ pltt services mock hr/v1#approvalChain.get
942
1014
  pltt services test --offline
943
1015
  pltt services pull --env staging
944
1016
  pltt services scaffold approvalChain.get
1017
+ pltt capabilities add creative.poster.generate --method poster.generate --risk write --effects artifact.create --idempotent
1018
+ pltt capabilities list
1019
+ pltt test --agent
945
1020
  ```
946
1021
 
947
1022
  Subcommands:
948
1023
 
949
1024
  - `list`: fetches `/api/v1/os-broker/catalog` from the selected environment and prints services/events available to the current org. Use `--json` for the raw catalog.
950
1025
  - `add <namespace/version#name>`: appends a consumed service target to `consumes.services`. Use `--event` or `--type event` for `consumes.events`, `--optional` for non-required dependencies, and `--reason <text>` to record why the dependency is needed.
951
- - `sync`: scans backend `@service(...)` decorators and updates `provides.services` so provider contracts do not drift from code.
1026
+ - `sync`: scans backend `@service(...)` and `@capability(...)` decorators and updates `provides.services` so provider contracts do not drift from code.
952
1027
  - `mock <namespace/version#name>`: adds a local response to `.palette/app-services.local.json` for `pltt dev`.
953
1028
  - `test`: checks local consumes/provides/mocks and, unless `--offline` is set, verifies consumed targets against `/api/v1/os-broker/schemas`.
954
1029
  - `pull`: reads `consumes.services` and `consumes.events`, fetches JSON Schemas from `/api/v1/os-broker/schemas`, and generates nested `.palette/types/services.ts` plus Python helpers in `.palette/python/services.py`.
@@ -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,
@@ -18,6 +19,16 @@ from palette_sdk.repository import OrgRepository
18
19
  from palette_sdk.lifecycle import LifecycleHooks
19
20
  from palette_sdk.jobs import JobCancelledError, JobExecution, JobHandle, JobsClient, job
20
21
  from palette_sdk.tool_definition import ToolDefinition
22
+ from palette_sdk.capabilities import (
23
+ ApprovalRequired,
24
+ ArtifactRef,
25
+ CapabilityError,
26
+ CapabilityResult,
27
+ ConnectionRequired,
28
+ RateLimited,
29
+ RetryableError,
30
+ capability,
31
+ )
21
32
  from palette_sdk.manifest import PluginManifest, load_manifest
22
33
  from palette_sdk.schemas import (
23
34
  SuccessResponse,
@@ -69,6 +80,7 @@ __all__ = [
69
80
  "OrganizationInfo",
70
81
  "NotificationsClient",
71
82
  "NotificationRecipient",
83
+ "TalkClient",
72
84
  "LocalRedisService",
73
85
  "LocalVectorService",
74
86
  "PlatformServiceUnavailable",
@@ -81,6 +93,14 @@ __all__ = [
81
93
  "JobsClient",
82
94
  "job",
83
95
  "ToolDefinition",
96
+ "capability",
97
+ "ArtifactRef",
98
+ "CapabilityResult",
99
+ "CapabilityError",
100
+ "ConnectionRequired",
101
+ "ApprovalRequired",
102
+ "RateLimited",
103
+ "RetryableError",
84
104
  "PluginManifest",
85
105
  "load_manifest",
86
106
  "SuccessResponse",
@@ -118,4 +138,4 @@ __all__ = [
118
138
  "LocalStorageService",
119
139
  ]
120
140
 
121
- __version__ = "0.1.11"
141
+ __version__ = "0.1.12"
@@ -0,0 +1,126 @@
1
+ """Typed agent capability contracts for Palette apps."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Callable, Literal
7
+
8
+ from pydantic import BaseModel, Field
9
+
10
+ from palette_sdk.services import ServiceHandler, service
11
+
12
+
13
+ class ArtifactRef(BaseModel):
14
+ """Portable reference to an artifact stored by Palette or an installed app."""
15
+
16
+ id: str
17
+ uri: str
18
+ name: str
19
+ mime_type: str
20
+ kind: str = "file"
21
+ revision: str | None = None
22
+ size_bytes: int | None = None
23
+ metadata: dict[str, Any] = Field(default_factory=dict)
24
+
25
+
26
+ class CapabilityResult(BaseModel):
27
+ """Standard result envelope understood by agents and workflow nodes."""
28
+
29
+ data: Any = None
30
+ artifacts: list[ArtifactRef] = Field(default_factory=list)
31
+ citations: list[str] = Field(default_factory=list)
32
+ warnings: list[str] = Field(default_factory=list)
33
+ continuation: dict[str, Any] | None = None
34
+ telemetry: dict[str, Any] = Field(default_factory=dict)
35
+
36
+
37
+ class CapabilityError(RuntimeError):
38
+ code = "capability_error"
39
+ retryable = False
40
+
41
+ def __init__(self, message: str, *, details: dict[str, Any] | None = None):
42
+ super().__init__(message)
43
+ self.details = details or {}
44
+
45
+
46
+ class ConnectionRequired(CapabilityError):
47
+ code = "connection_required"
48
+
49
+
50
+ class ApprovalRequired(CapabilityError):
51
+ code = "approval_required"
52
+
53
+
54
+ class RateLimited(CapabilityError):
55
+ code = "rate_limited"
56
+ retryable = True
57
+
58
+
59
+ class RetryableError(CapabilityError):
60
+ code = "retryable"
61
+ retryable = True
62
+
63
+
64
+ def capability(
65
+ name: str,
66
+ *,
67
+ capability_id: str,
68
+ scope: str | None = None,
69
+ version: str | None = None,
70
+ label: str | None = None,
71
+ description: str | None = None,
72
+ input_schema: dict | str | None = None,
73
+ output_schema: dict | str | None = None,
74
+ effects: list[str] | None = None,
75
+ risk: Literal["read", "write", "destructive", "controlled"] = "read",
76
+ supports_scheduling: bool = True,
77
+ idempotent: bool = False,
78
+ timeout_seconds: int = 60,
79
+ tags: list[str] | None = None,
80
+ artifact_inputs: list[str] | None = None,
81
+ artifact_outputs: list[str] | None = None,
82
+ examples: list[dict[str, Any]] | None = None,
83
+ cost_class: Literal["low", "medium", "high"] | None = None,
84
+ latency_class: Literal["interactive", "background", "long_running"] | None = None,
85
+ deprecated: bool = False,
86
+ replacement: str | None = None,
87
+ ) -> Callable[[ServiceHandler], ServiceHandler]:
88
+ """Declare a broker service that agents and visual workflows may call.
89
+
90
+ The matching provides.services method in the manifest remains the reviewed
91
+ publish contract. pltt test --agent verifies decorator/manifest parity.
92
+ """
93
+ if not re.match(r"^[a-z][a-z0-9_-]*(?:\.[a-z0-9_-]+)+$", capability_id):
94
+ raise ValueError("capability_id must be a stable dotted lowercase id")
95
+ if not description or input_schema is None:
96
+ raise ValueError("agent capabilities require description and input_schema")
97
+ if not effects:
98
+ raise ValueError("agent capabilities require at least one declared effect")
99
+ if risk in {"write", "destructive"} and supports_scheduling and not idempotent:
100
+ raise ValueError(
101
+ "scheduled write capabilities must be idempotent or disable scheduling"
102
+ )
103
+ return service(
104
+ name,
105
+ scope=scope,
106
+ version=version,
107
+ label=label,
108
+ description=description,
109
+ input_schema=input_schema,
110
+ output_schema=output_schema,
111
+ agent_exposable=True,
112
+ capability_id=capability_id,
113
+ effects=effects or [],
114
+ risk=risk,
115
+ supports_scheduling=supports_scheduling,
116
+ idempotent=idempotent,
117
+ timeout_seconds=timeout_seconds,
118
+ tags=tags or [],
119
+ artifact_inputs=artifact_inputs or [],
120
+ artifact_outputs=artifact_outputs or [],
121
+ examples=examples or [],
122
+ cost_class=cost_class,
123
+ latency_class=latency_class,
124
+ deprecated=deprecated,
125
+ replacement=replacement,
126
+ )
@@ -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
+ )
@@ -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
+ }