@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
@@ -375,3 +375,403 @@ class LocalVectorService:
375
375
  if index:
376
376
  return {"index": index, "count": len(self._items.get(index, {}))}
377
377
  return {"indexes": {name: len(items) for name, items in self._items.items()}}
378
+
379
+
380
+ class LocalLLMService:
381
+ """`ctx.llm` for pltt dev.
382
+
383
+ Hosted, this is the platform's key under an org spend cap. Locally there is
384
+ no platform, so it uses the developer's own `OPENAI_API_KEY` when the dev
385
+ env supplies one and falls back to a deterministic stub otherwise — the app's
386
+ code path stays exercisable with zero setup.
387
+ """
388
+
389
+ def __init__(self, api_key: str | None = None, model: str = "gpt-5.4-mini"):
390
+ self.api_key = api_key or ""
391
+ self.model = model
392
+
393
+ @property
394
+ def live(self) -> bool:
395
+ return bool(self.api_key)
396
+
397
+ @staticmethod
398
+ def _last_user(messages: list[dict[str, Any]]) -> str:
399
+ for message in reversed(messages or []):
400
+ if str(message.get("role") or "user") == "user":
401
+ return str(message.get("content") or "")
402
+ return ""
403
+
404
+ def _stub(self, messages: list[dict[str, Any]]) -> dict[str, Any]:
405
+ return {
406
+ "text": f"[pltt dev: no LLM key] {self._last_user(messages)}",
407
+ "model": "pltt-dev-stub",
408
+ "input_tokens": 0,
409
+ "output_tokens": 0,
410
+ "cost_usd": 0.0,
411
+ }
412
+
413
+ async def chat(
414
+ self,
415
+ messages: list[dict[str, Any]],
416
+ *,
417
+ model: str | None = None,
418
+ system: str | None = None,
419
+ max_tokens: int = 1024,
420
+ temperature: float = 0.2,
421
+ **kwargs: Any,
422
+ ) -> dict[str, Any]:
423
+ if not self.live:
424
+ return self._stub(messages)
425
+ from openai import AsyncOpenAI
426
+
427
+ payload = ([{"role": "system", "content": system}] if system else []) + list(messages)
428
+ reply = await AsyncOpenAI(api_key=self.api_key).chat.completions.create(
429
+ model=model or self.model, messages=payload, max_completion_tokens=max_tokens, **kwargs
430
+ )
431
+ usage = reply.usage
432
+ return {
433
+ "text": reply.choices[0].message.content or "",
434
+ "model": reply.model,
435
+ "input_tokens": getattr(usage, "prompt_tokens", 0),
436
+ "output_tokens": getattr(usage, "completion_tokens", 0),
437
+ "cost_usd": None,
438
+ }
439
+
440
+ async def stream(self, messages: list[dict[str, Any]], **kwargs):
441
+ if not self.live:
442
+ yield self._stub(messages)["text"]
443
+ return
444
+ from openai import AsyncOpenAI
445
+
446
+ system = kwargs.get("system")
447
+ payload = ([{"role": "system", "content": system}] if system else []) + list(messages)
448
+ passthrough = {
449
+ k: v for k, v in kwargs.items() if k not in ("model", "system", "max_tokens", "temperature")
450
+ }
451
+ stream = await AsyncOpenAI(api_key=self.api_key).chat.completions.create(
452
+ model=kwargs.get("model") or self.model,
453
+ messages=payload,
454
+ max_completion_tokens=kwargs.get("max_tokens", 1024),
455
+ stream=True,
456
+ **passthrough,
457
+ )
458
+ async for chunk in stream:
459
+ delta = chunk.choices[0].delta if chunk.choices else None
460
+ if delta and delta.content:
461
+ yield delta.content
462
+
463
+ async def embed(self, texts: list[str]) -> list[list[float]]:
464
+ if not self.live:
465
+ # Same deterministic hash embedding LocalVectorService uses, so
466
+ # similarity search behaves consistently offline.
467
+ return [_text_vector(text) for text in texts]
468
+ from openai import AsyncOpenAI
469
+
470
+ reply = await AsyncOpenAI(api_key=self.api_key).embeddings.create(
471
+ model="text-embedding-3-small", input=list(texts)
472
+ )
473
+ return [item.embedding for item in reply.data]
474
+
475
+ async def image(self, prompt: str, *, aspect_ratio: str = "1:1", **kwargs: Any) -> tuple[bytes, str]:
476
+ raise NotImplementedError("ctx.llm.image runs on the platform only — use pltt dev --sandbox")
477
+
478
+ async def models(self) -> list[str]:
479
+ """Hosted, this is the list the platform will honour in `model=`.
480
+ Locally there is no catalog, so it reports the dev model only."""
481
+ return [self.model] if self.live else []
482
+
483
+ async def spend(self) -> dict[str, Any]:
484
+ """Hosted, the org's monthly wallet. Locally the developer's own key pays."""
485
+ return {"spent_usd": 0.0, "cap_usd": None, "remaining_usd": None}
486
+
487
+
488
+ class LocalWebService:
489
+ """`ctx.web` for pltt dev — keyless DuckDuckGo search plus a plain fetch."""
490
+
491
+ async def search(self, query: str, *, limit: int = 5, topic: str | None = None) -> dict[str, Any]:
492
+ try:
493
+ from ddgs import DDGS
494
+ except ImportError:
495
+ return {"results": [], "error": "pip install ddgs to use ctx.web.search in pltt dev"}
496
+ import asyncio
497
+
498
+ def _run() -> list[dict[str, Any]]:
499
+ with DDGS() as ddgs:
500
+ return [
501
+ {"title": r.get("title", ""), "url": r.get("href", ""), "content": r.get("body", "")}
502
+ for r in ddgs.text(query, max_results=limit)
503
+ ]
504
+
505
+ return {"results": await asyncio.to_thread(_run)}
506
+
507
+ async def fetch(self, url: str) -> str:
508
+ import httpx
509
+
510
+ async with httpx.AsyncClient(timeout=20, follow_redirects=True) as client:
511
+ response = await client.get(url)
512
+ response.raise_for_status()
513
+ return response.text
514
+
515
+
516
+ # 1x1 transparent PNG. Enough for a stubbed render to flow through an <img>
517
+ # and any "did I get a URL back" branch without a network call.
518
+ _STUB_PNG = (
519
+ "data:image/png;base64,"
520
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
521
+ )
522
+
523
+
524
+ class MediaStillRunning(TimeoutError):
525
+ """`ctx.media.run` gave up waiting; the fal job is still going.
526
+
527
+ Carries what is needed to collect it later, so a request handler can hand
528
+ the id to `ctx.jobs` (or return it to the browser) instead of holding a
529
+ connection open for a four-minute render.
530
+ """
531
+
532
+ def __init__(self, request_id: str, model: str):
533
+ super().__init__(
534
+ f"ctx.media: {model} is still running — collect it with "
535
+ f"ctx.media.result({request_id!r}, model={model!r})"
536
+ )
537
+ self.request_id = request_id
538
+ self.model = model
539
+
540
+
541
+ class LocalMediaService:
542
+ """`ctx.media` for pltt dev — the same fal.ai surface as hosted.
543
+
544
+ Hosted, the platform's own `FAL_KEY` pays under the org's monthly cap.
545
+ Locally there is no platform: if the dev env supplies a `FAL_KEY` the calls
546
+ are real, otherwise every call returns a stub shaped like a fal response so
547
+ the app's code path still runs with zero setup.
548
+ """
549
+
550
+ QUEUE_BASE = "https://queue.fal.run"
551
+ UPLOAD_URL = "https://storage.fal.ai/files/upload"
552
+ POLL_INTERVAL_S = 3.0
553
+ DEFAULT_MODELS = {
554
+ "image": "fal-ai/flux/dev",
555
+ "video": "fal-ai/kling-video/v3/standard/text-to-video",
556
+ "speech": "fal-ai/elevenlabs/tts/turbo-v2.5",
557
+ "transcribe": "fal-ai/whisper",
558
+ }
559
+
560
+ def __init__(self, api_key: str | None = None, storage: Any = None):
561
+ self.api_key = api_key or ""
562
+ self._storage = storage
563
+
564
+ @property
565
+ def live(self) -> bool:
566
+ return bool(self.api_key)
567
+
568
+ def _headers(self) -> dict[str, str]:
569
+ return {"Authorization": f"Key {self.api_key}"}
570
+
571
+ @staticmethod
572
+ def _merge(payload: dict[str, Any] | None, fields: dict[str, Any]) -> dict[str, Any]:
573
+ return {**(payload or {}), **fields}
574
+
575
+ def _queue_urls(self, model: str, request_id: str) -> tuple[str, str, str]:
576
+ base = "/".join(str(model).strip("/").split("/")[:2])
577
+ root = f"{self.QUEUE_BASE}/{base}/requests/{request_id}"
578
+ return f"{root}/status", root, f"{root}/cancel"
579
+
580
+ @staticmethod
581
+ def _fal_host_ok(url: str) -> bool:
582
+ """A url fetched with the FAL_KEY attached must be on fal's domains.
583
+
584
+ Locally the key is the developer's own, but it is still a key, and
585
+ keeping the check identical to the hosted service means the two cannot
586
+ drift apart. Exact apex or dot-prefixed subdomain only: a bare
587
+ `endswith("fal.run")` would also accept `evilfal.run`.
588
+ """
589
+ from urllib.parse import urlparse
590
+
591
+ parsed = urlparse(url or "")
592
+ host = (parsed.hostname or "").lower().rstrip(".")
593
+ return parsed.scheme == "https" and any(
594
+ host == domain or host.endswith(f".{domain}") for domain in ("fal.run", "fal.ai")
595
+ )
596
+
597
+ @staticmethod
598
+ def _stub(model: str, payload: dict[str, Any]) -> dict[str, Any]:
599
+ """A fal-shaped placeholder covering the output keys the common
600
+ families use, so `out["images"][0]["url"]` and friends resolve."""
601
+ return {
602
+ "pltt_dev_stub": True,
603
+ "model": model,
604
+ "request": payload,
605
+ "images": [{"url": _STUB_PNG, "content_type": "image/png", "width": 1, "height": 1}],
606
+ "image": {"url": _STUB_PNG, "content_type": "image/png"},
607
+ "video": {"url": _STUB_PNG, "content_type": "video/mp4"},
608
+ "audio": {"url": _STUB_PNG, "content_type": "audio/mpeg"},
609
+ "audio_url": {"url": _STUB_PNG},
610
+ "text": f"[pltt dev: no FAL_KEY] {payload.get('prompt') or payload.get('text') or ''}",
611
+ }
612
+
613
+ async def submit(self, model: str, payload: dict[str, Any] | None = None, **fields: Any) -> dict[str, Any]:
614
+ body = self._merge(payload, fields)
615
+ if not self.live:
616
+ return {"request_id": "pltt-dev-stub", "model": model, "status_url": "", "response_url": "", "request": body}
617
+ import httpx
618
+
619
+ async with httpx.AsyncClient(timeout=60.0, headers=self._headers()) as client:
620
+ response = await client.post(f"{self.QUEUE_BASE}/{str(model).strip('/')}", json=body)
621
+ response.raise_for_status()
622
+ task = response.json() or {}
623
+ request_id = str(task.get("request_id") or "")
624
+ rebuilt_status, rebuilt_response, _cancel = self._queue_urls(model, request_id)
625
+ provider_status = str(task.get("status_url") or "")
626
+ provider_response = str(task.get("response_url") or "")
627
+ return {
628
+ "request_id": request_id,
629
+ "model": model,
630
+ "status_url": provider_status if self._fal_host_ok(provider_status) else rebuilt_status,
631
+ "response_url": provider_response if self._fal_host_ok(provider_response) else rebuilt_response,
632
+ }
633
+
634
+ async def status(self, request_id: str, *, model: str, **params: Any) -> dict[str, Any]:
635
+ if not self.live:
636
+ return {"status": "COMPLETED", "pltt_dev_stub": True}
637
+ import httpx
638
+
639
+ status_url, _response, _cancel = self._queue_urls(model, request_id)
640
+ async with httpx.AsyncClient(timeout=30.0, headers=self._headers()) as client:
641
+ response = await client.get(status_url, params=params or None)
642
+ response.raise_for_status()
643
+ return response.json() or {}
644
+
645
+ async def result(self, request_id: str, *, model: str) -> dict[str, Any]:
646
+ if not self.live:
647
+ return self._stub(model, {})
648
+ import httpx
649
+
650
+ _status, response_url, _cancel = self._queue_urls(model, request_id)
651
+ async with httpx.AsyncClient(timeout=60.0, headers=self._headers()) as client:
652
+ response = await client.get(response_url)
653
+ response.raise_for_status()
654
+ return response.json() or {}
655
+
656
+ async def cancel(self, request_id: str, *, model: str) -> dict[str, Any]:
657
+ if not self.live:
658
+ return {"cancelled": True, "pltt_dev_stub": True}
659
+ import httpx
660
+
661
+ _status, _response, cancel_url = self._queue_urls(model, request_id)
662
+ async with httpx.AsyncClient(timeout=30.0, headers=self._headers()) as client:
663
+ response = await client.put(cancel_url)
664
+ return {"cancelled": response.status_code < 400, "status_code": response.status_code}
665
+
666
+ async def run(
667
+ self,
668
+ model: str,
669
+ payload: dict[str, Any] | None = None,
670
+ *,
671
+ timeout: float | None = None,
672
+ poll_interval: float | None = None,
673
+ on_status: Any = None,
674
+ **fields: Any,
675
+ ) -> dict[str, Any]:
676
+ body = self._merge(payload, fields)
677
+ if not self.live:
678
+ return self._stub(model, body)
679
+ import asyncio
680
+
681
+ import httpx
682
+
683
+ job = await self.submit(model, body)
684
+ deadline = time.monotonic() + float(timeout if timeout is not None else 600.0)
685
+ interval = float(poll_interval or self.POLL_INTERVAL_S)
686
+ last = None
687
+ async with httpx.AsyncClient(timeout=30.0, headers=self._headers()) as client:
688
+ while True:
689
+ probe = await client.get(job["status_url"])
690
+ probe.raise_for_status()
691
+ state = str((probe.json() or {}).get("status") or "").upper()
692
+ if state != last:
693
+ last = state
694
+ if on_status is not None:
695
+ outcome = on_status(state)
696
+ if asyncio.iscoroutine(outcome):
697
+ await outcome
698
+ if state == "COMPLETED":
699
+ break
700
+ if state in ("FAILED", "ERROR", "CANCELLED"):
701
+ raise RuntimeError(f"ctx.media: {model} {state.lower()} ({str(probe.json())[:300]})")
702
+ if time.monotonic() > deadline:
703
+ raise MediaStillRunning(job["request_id"], model)
704
+ await asyncio.sleep(interval)
705
+ final = await client.get(job["response_url"])
706
+ final.raise_for_status()
707
+ return final.json() or {}
708
+
709
+ async def image(self, prompt: str, *, model: str | None = None, **payload: Any) -> dict[str, Any]:
710
+ return await self.run(model or self.DEFAULT_MODELS["image"], {"prompt": prompt, **payload})
711
+
712
+ async def video(self, prompt: str, *, model: str | None = None, **payload: Any) -> dict[str, Any]:
713
+ return await self.run(model or self.DEFAULT_MODELS["video"], {"prompt": prompt, **payload})
714
+
715
+ async def speech(self, text: str, *, model: str | None = None, **payload: Any) -> dict[str, Any]:
716
+ return await self.run(model or self.DEFAULT_MODELS["speech"], {"text": text, **payload})
717
+
718
+ async def transcribe(self, audio_url: str, *, model: str | None = None, **payload: Any) -> dict[str, Any]:
719
+ return await self.run(model or self.DEFAULT_MODELS["transcribe"], {"audio_url": audio_url, **payload})
720
+
721
+ async def upload(
722
+ self,
723
+ source: bytes | str,
724
+ *,
725
+ filename: str = "upload.bin",
726
+ content_type: str = "application/octet-stream",
727
+ ) -> str:
728
+ if not self.live:
729
+ return _STUB_PNG
730
+ import httpx
731
+
732
+ if isinstance(source, str):
733
+ async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client:
734
+ fetched = await client.get(source)
735
+ fetched.raise_for_status()
736
+ content = fetched.content
737
+ content_type = (fetched.headers.get("content-type") or content_type).split(";")[0].strip()
738
+ else:
739
+ content = bytes(source)
740
+ async with httpx.AsyncClient(timeout=120.0) as client:
741
+ response = await client.post(
742
+ self.UPLOAD_URL,
743
+ content=content,
744
+ headers={**self._headers(), "Content-Type": content_type, "X-Fal-File-Name": filename},
745
+ )
746
+ response.raise_for_status()
747
+ data = response.json() or {}
748
+ url = data.get("access_url") or data.get("url") or data.get("file_url")
749
+ if not url:
750
+ raise RuntimeError(f"ctx.media: no URL in fal upload response ({str(data)[:200]})")
751
+ return str(url)
752
+
753
+ async def save(self, url: str, *, filename: str | None = None, key: str | None = None) -> dict[str, Any]:
754
+ if self._storage is None or isinstance(self._storage, UnavailablePlatformService):
755
+ raise PlatformServiceUnavailable(
756
+ 'ctx.media.save needs storage too — declare platform_services: ["media", "storage"]'
757
+ )
758
+ name = filename or url.split("?")[0].rsplit("/", 1)[-1] or "media.bin"
759
+ if url.startswith("data:"):
760
+ import base64
761
+
762
+ header, _, encoded = url.partition(",")
763
+ content = base64.b64decode(encoded) if ";base64" in header else encoded.encode()
764
+ content_type = header[5:].split(";")[0] or "application/octet-stream"
765
+ else:
766
+ import httpx
767
+
768
+ async with httpx.AsyncClient(timeout=120.0, follow_redirects=True) as client:
769
+ response = await client.get(url)
770
+ response.raise_for_status()
771
+ content = response.content
772
+ content_type = (response.headers.get("content-type") or "application/octet-stream").split(";")[0].strip()
773
+ return await self._storage.upload_file(name, content, content_type, key=key)
774
+
775
+ async def spend(self) -> dict[str, Any]:
776
+ """Hosted, the org's monthly wallet. Locally the developer's own key pays."""
777
+ return {"spent_usd": 0.0, "cap_usd": None, "remaining_usd": None}
@@ -16,6 +16,8 @@ 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
20
+ from palette_sdk.tasks import TasksClient
19
21
  from palette_sdk.platform_services import UnavailablePlatformService
20
22
  from palette_sdk.events import EventPublisher
21
23
  from palette_sdk.jobs import JobsClient
@@ -37,7 +39,9 @@ class PluginContext:
37
39
  caller's organization automatically. Do not add `WHERE
38
40
  organization_id = ?` — RLS already does it.
39
41
  user_id: UUID of the authenticated user
40
- organization_id: Current org ID
42
+ organization_id: Effective app data partition ID. Kept for backwards
43
+ compatibility with existing plugin repositories; use
44
+ `data_partition_id` in new code. The real org is `organization.id`.
41
45
  organization: Read-only snapshot of the current organisation's
42
46
  settings (name, slug, logo_url, company_type, description, ...).
43
47
  Refreshed on every request, so it always reflects the latest
@@ -48,6 +52,15 @@ class PluginContext:
48
52
  storage: Storage service for file upload/download
49
53
  members: Organization member helpers for the current org
50
54
  notifications: OS notification center push helpers
55
+ talk: Post into Talk channels as the app's own agent identity
56
+ tasks: The caller's task board, scoped to the tasks this app created.
57
+ Needs `tasks:read` / `tasks:write` in the manifest.
58
+ llm: Chat / stream / embed / image on the platform's model keys, under
59
+ the organisation's monthly spend cap. Needs platform_services: ["llm"].
60
+ web: Web search + SSRF-guarded page reader. platform_services: ["web"].
61
+ media: fal.ai — image, video, speech, transcription, or any model fal
62
+ publishes, with the payload passed through untouched. Needs
63
+ platform_services: ["media"]; no FAL_KEY of the app's own.
51
64
  """
52
65
  db: AsyncSession
53
66
  user_id: str
@@ -62,8 +75,18 @@ class PluginContext:
62
75
  apps: AppInteropClient = field(default_factory=AppInteropClient)
63
76
  members: OrganizationMembersClient = field(default_factory=OrganizationMembersClient)
64
77
  notifications: NotificationsClient = field(default_factory=NotificationsClient)
78
+ talk: TalkClient = field(default_factory=TalkClient)
79
+ tasks: TasksClient = field(default_factory=TasksClient)
65
80
  redis: Any = field(default_factory=lambda: UnavailablePlatformService("redis"))
66
81
  vector: Any = field(default_factory=lambda: UnavailablePlatformService("vector"))
82
+ # The platform's own model keys, under a per-org spend cap — declare
83
+ # platform_services: ["llm"] instead of shipping an OPENAI_API_KEY secret.
84
+ llm: Any = field(default_factory=lambda: UnavailablePlatformService("llm"))
85
+ # Web search + SSRF-guarded page reader — platform_services: ["web"].
86
+ web: Any = field(default_factory=lambda: UnavailablePlatformService("web"))
87
+ # fal.ai on the platform's key — any model, any payload, no FAL_KEY of your
88
+ # own. platform_services: ["media"].
89
+ media: Any = field(default_factory=lambda: UnavailablePlatformService("media"))
67
90
  events: EventPublisher = field(default_factory=EventPublisher)
68
91
  jobs: JobsClient = field(default_factory=JobsClient)
69
92
  config: dict[str, Any] = field(default_factory=dict)
@@ -72,6 +95,11 @@ class PluginContext:
72
95
  def has_permission(self, permission: str) -> bool:
73
96
  return permission in self.permissions
74
97
 
98
+ @property
99
+ def data_partition_id(self) -> int:
100
+ """Personal tenant ID or real org ID, according to manifest.data_scope."""
101
+ return self.organization_id
102
+
75
103
  def has_any_permission(self, permissions: list[str] | tuple[str, ...] | set[str]) -> bool:
76
104
  return any(permission in self.permissions for permission in permissions)
77
105
 
@@ -124,7 +152,7 @@ async def get_plugin_context(request: Request) -> PluginContext:
124
152
  return PluginContext(
125
153
  db=state.db,
126
154
  user_id=str(state.user.id),
127
- organization_id=state.user.organization_id,
155
+ organization_id=getattr(state, "data_partition_id", state.user.organization_id),
128
156
  organization=OrganizationInfo.from_dict(getattr(state, "organization_info", None)),
129
157
  org_role=getattr(state, "org_role", None),
130
158
  plugin_id=getattr(state, "plugin_id", ""),
@@ -141,8 +169,19 @@ async def get_plugin_context(request: Request) -> PluginContext:
141
169
  getattr(state, "plugin_permissions", []),
142
170
  ),
143
171
  notifications=NotificationsClient(getattr(state, "notifications", None)),
172
+ talk=TalkClient(
173
+ getattr(state, "talk", None),
174
+ getattr(state, "plugin_permissions", []),
175
+ ),
176
+ tasks=TasksClient(
177
+ getattr(state, "tasks", None),
178
+ getattr(state, "plugin_permissions", []),
179
+ ),
144
180
  redis=getattr(state, "redis", None) or UnavailablePlatformService("redis"),
145
181
  vector=getattr(state, "vector", None) or UnavailablePlatformService("vector"),
182
+ llm=getattr(state, "llm", None) or UnavailablePlatformService("llm"),
183
+ web=getattr(state, "web", None) or UnavailablePlatformService("web"),
184
+ media=getattr(state, "media", None) or UnavailablePlatformService("media"),
146
185
  events=EventPublisher(getattr(state, "plugin_events", None)),
147
186
  jobs=JobsClient(getattr(state, "plugin_jobs", None)),
148
187
  config=getattr(state, "plugin_config", {}),
@@ -1,23 +1,74 @@
1
- """Plugin-scoped FastAPI router with automatic prefix and auth."""
1
+ """Plugin-scoped FastAPI router with automatic prefix, auth and context."""
2
2
 
3
- from fastapi import APIRouter
3
+ import inspect
4
+ from typing import Any, Callable
5
+
6
+ from fastapi import APIRouter, Depends
7
+
8
+ # Annotations a plugin might reasonably write for the context parameter. String
9
+ # forms are what `from __future__ import annotations` leaves behind, and plugin
10
+ # modules are loaded by path (never as a package), so nothing here can be
11
+ # resolved by importing the author's module.
12
+ _CONTEXT_ANNOTATIONS = {
13
+ "PluginContext",
14
+ "palette_sdk.PluginContext",
15
+ "palette_sdk.plugin_context.PluginContext",
16
+ }
17
+
18
+
19
+ def _with_context_dependency(endpoint: Callable[..., Any]) -> Callable[..., Any]:
20
+ """Give a bare `ctx: PluginContext` parameter its platform dependency.
21
+
22
+ Without it FastAPI reads the annotation as a request body/response field and
23
+ raises `Invalid args for response field!` — the most common first-run error
24
+ in a plugin backend, and one whose message names nothing the author wrote.
25
+ Parameters that already carry `Depends(...)` are left exactly as they are.
26
+ """
27
+ from palette_sdk.plugin_context import PluginContext, get_plugin_context
28
+
29
+ try:
30
+ signature = inspect.signature(endpoint)
31
+ except (TypeError, ValueError): # builtins / C callables have no signature
32
+ return endpoint
33
+ parameters = []
34
+ injected = False
35
+ for parameter in signature.parameters.values():
36
+ annotation = parameter.annotation
37
+ is_context = annotation is PluginContext or (
38
+ isinstance(annotation, str) and annotation.strip("\"' ") in _CONTEXT_ANNOTATIONS
39
+ )
40
+ if is_context and parameter.default is inspect.Parameter.empty:
41
+ parameter = parameter.replace(
42
+ default=Depends(get_plugin_context), annotation=PluginContext
43
+ )
44
+ injected = True
45
+ parameters.append(parameter)
46
+ if injected:
47
+ # FastAPI reads __signature__ when it builds the dependant, so the
48
+ # function itself keeps working unchanged for direct callers and tests.
49
+ endpoint.__signature__ = signature.replace(parameters=parameters)
50
+ return endpoint
4
51
 
5
52
 
6
53
  class PluginRouter(APIRouter):
7
54
  """A FastAPI router scoped to a plugin.
8
55
 
9
- Routes defined on this router will be automatically mounted
10
- under /api/v1/plugins/{plugin_id}/ by the platform loader.
56
+ Routes defined on this router are mounted under
57
+ `/api/v1/plugins/{plugin_id}/` by the platform loader, and a parameter
58
+ annotated `PluginContext` is wired to the platform context automatically.
11
59
 
12
60
  Usage:
13
- from palette_sdk import PluginRouter
61
+ from palette_sdk import PluginContext, PluginRouter
14
62
 
15
63
  router = PluginRouter(tags=["my-plugin"])
16
64
 
17
65
  @router.get("/stats")
18
- async def get_stats(ctx = Depends(get_plugin_context)):
19
- # This will be available at /api/v1/plugins/my-plugin/stats
20
- ...
66
+ async def get_stats(ctx: PluginContext):
67
+ # available at /api/v1/plugins/my-plugin/stats
68
+ return {"org": ctx.organization.name}
69
+
70
+ # The explicit form still works and is unchanged:
71
+ # async def get_stats(ctx = Depends(get_plugin_context)): ...
21
72
  """
22
73
 
23
74
  def __init__(self, **kwargs):
@@ -25,3 +76,8 @@ class PluginRouter(APIRouter):
25
76
  # previous code set this to None, which broke both the response
26
77
  # pipeline (TypeError at serialization) and OpenAPI generation.
27
78
  super().__init__(**kwargs)
79
+
80
+ def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) -> None:
81
+ # Every decorator (@router.get/post/...) funnels through here, so this
82
+ # is the one place the injection has to happen.
83
+ return super().add_api_route(path, _with_context_dependency(endpoint), **kwargs)
@@ -36,6 +36,15 @@ class OrgRepository(Generic[T]):
36
36
  stmt = stmt.where(org_filter)
37
37
  return stmt
38
38
 
39
+ async def _commit(self) -> None:
40
+ try:
41
+ await self.db.commit()
42
+ except Exception:
43
+ # A failed flush leaves SQLAlchemy unusable until rollback. Restore
44
+ # the injected session before plugin code handles the original error.
45
+ await self.db.rollback()
46
+ raise
47
+
39
48
  def _apply_filters(self, stmt, filters: Mapping[str, Any] | None):
40
49
  for key, value in (filters or {}).items():
41
50
  if not hasattr(self.model, key):
@@ -92,7 +101,7 @@ class OrgRepository(Generic[T]):
92
101
  values["organization_id"] = self.organization_id
93
102
  row = self.model(**values)
94
103
  self.db.add(row)
95
- await self.db.commit()
104
+ await self._commit()
96
105
  await self.db.refresh(row)
97
106
  return row
98
107
 
@@ -106,7 +115,7 @@ class OrgRepository(Generic[T]):
106
115
  if not hasattr(row, key):
107
116
  raise ValueError(f"{self.model.__name__} has no attribute {key!r}")
108
117
  setattr(row, key, value)
109
- await self.db.commit()
118
+ await self._commit()
110
119
  await self.db.refresh(row)
111
120
  return row
112
121
 
@@ -115,5 +124,5 @@ class OrgRepository(Generic[T]):
115
124
  if row is None:
116
125
  return False
117
126
  await self.db.delete(row)
118
- await self.db.commit()
127
+ await self._commit()
119
128
  return True