@palettelab/cli 0.3.63 → 0.3.66

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 (43) hide show
  1. package/README.md +144 -9
  2. package/backend-sdk/palette_sdk/__init__.py +17 -1
  3. package/backend-sdk/palette_sdk/data_rooms.py +2 -2
  4. package/backend-sdk/palette_sdk/db/base.py +4 -1
  5. package/backend-sdk/palette_sdk/db/rls.py +7 -1
  6. package/backend-sdk/palette_sdk/manifest.py +9 -1
  7. package/backend-sdk/palette_sdk/platform_services.py +790 -36
  8. package/backend-sdk/palette_sdk/plugin_context.py +30 -2
  9. package/backend-sdk/palette_sdk/plugin_router.py +64 -8
  10. package/backend-sdk/palette_sdk/repository.py +12 -3
  11. package/backend-sdk/palette_sdk/tasks.py +117 -0
  12. package/backend-sdk/pyproject.toml +1 -1
  13. package/docs/python-backend-sdk.md +132 -8
  14. package/lib/cli.js +20 -2
  15. package/lib/commands/capabilities.js +1 -1
  16. package/lib/commands/doctor.js +15 -0
  17. package/lib/commands/models.js +65 -0
  18. package/lib/commands/platform.js +137 -0
  19. package/lib/commands/test.js +47 -4
  20. package/lib/dev-simulator.js +95 -0
  21. package/lib/manifest.js +123 -3
  22. package/package.json +1 -1
  23. package/template-fallback/README.md +9 -0
  24. package/template-fallback/frontend/src/translations.ts +2 -2
  25. package/template-fallback/package.json +1 -1
  26. package/template-fallback/palette-plugin.json +1 -0
  27. package/template-fallback/templates/agent-tool/palette-plugin.json +1 -0
  28. package/template-fallback/templates/consumer-app/package.json +1 -1
  29. package/template-fallback/templates/consumer-app/palette-plugin.json +1 -0
  30. package/template-fallback/templates/dashboard/package.json +1 -1
  31. package/template-fallback/templates/dashboard/palette-plugin.json +1 -0
  32. package/template-fallback/templates/database/package.json +1 -1
  33. package/template-fallback/templates/database/palette-plugin.json +1 -0
  34. package/template-fallback/templates/external-service/package.json +1 -1
  35. package/template-fallback/templates/external-service/palette-plugin.json +1 -0
  36. package/template-fallback/templates/frontend-only/package.json +1 -1
  37. package/template-fallback/templates/frontend-only/palette-plugin.json +1 -0
  38. package/template-fallback/templates/next/package.json +1 -1
  39. package/template-fallback/templates/next/palette-plugin.json +1 -0
  40. package/template-fallback/templates/palette-app/package.json +1 -1
  41. package/template-fallback/templates/palette-app/palette-plugin.json +1 -0
  42. package/template-fallback/templates/provider-app/package.json +1 -1
  43. package/template-fallback/templates/provider-app/palette-plugin.json +1 -0
@@ -2,15 +2,112 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import asyncio
5
6
  import hashlib
7
+ import json
6
8
  import math
9
+ import sys
7
10
  import time
11
+ import types
8
12
  from dataclasses import dataclass, field
9
13
  from typing import Any
10
14
 
11
15
 
16
+ # ---- errors shared with palette_sdk -----------------------------------------
17
+ # Every app bundle vendors its own palette_sdk and the loader re-imports it per
18
+ # app, so a class defined in a module is a different object in every app: an
19
+ # `except MediaStillRunning` in app code never matched the one raised here.
20
+ # The platform and every SDK copy therefore take their error classes from ONE
21
+ # registry module per process — whoever imports first defines them. Keep this
22
+ # block identical to backend/app/plugins/platform_services.py
23
+ # (backend test_platform_errors_shared pins it). Constructors accept **details so a
24
+ # newer caller never breaks an older definition that won the race.
25
+ _ERRORS_MODULE = "palette_platform_errors"
26
+
27
+
28
+ def _shared(cls: type) -> type:
29
+ registry = sys.modules.setdefault(_ERRORS_MODULE, types.ModuleType(_ERRORS_MODULE))
30
+ return registry.__dict__.setdefault(cls.__name__, cls)
31
+
32
+
12
33
  class PlatformServiceUnavailable(RuntimeError):
13
- """Raised when a plugin uses a platform service it did not declare."""
34
+ """A ctx.* platform service cannot serve this call: not declared in the
35
+ manifest, not configured on this platform, or over the monthly budget."""
36
+
37
+ def __init__(self, message: str = "", **details: Any):
38
+ super().__init__(message)
39
+ self.__dict__.update(details)
40
+
41
+
42
+ PlatformServiceUnavailable = _shared(PlatformServiceUnavailable)
43
+
44
+
45
+ class ModelUnavailable(PlatformServiceUnavailable):
46
+ """ctx.llm will not run `model` and the call asked for no substitute
47
+ (`fallback=False`). `reason`: unknown_model, provider_unconfigured,
48
+ not_approved, billing_disabled, org_policy."""
49
+
50
+ def __init__(self, message: str = "", *, model: str | None = None, reason: str | None = None, **details: Any):
51
+ super().__init__(
52
+ message or f"ctx.llm: model {model!r} is unavailable ({reason})",
53
+ model=model,
54
+ reason=reason,
55
+ **details,
56
+ )
57
+
58
+
59
+ ModelUnavailable = _shared(ModelUnavailable)
60
+
61
+
62
+ class MediaRateLimited(PlatformServiceUnavailable):
63
+ """fal kept answering 429 after the platform's own retries. Nothing was
64
+ queued or billed; wait `retry_after` seconds (None = unknown) or move the
65
+ work into ctx.jobs."""
66
+
67
+ def __init__(self, message: str = "", *, model: str | None = None, retry_after: float | None = None, **details: Any):
68
+ super().__init__(
69
+ message or f"ctx.media: fal is rate limiting {model} — retry later",
70
+ model=model,
71
+ retry_after=retry_after,
72
+ **details,
73
+ )
74
+
75
+
76
+ MediaRateLimited = _shared(MediaRateLimited)
77
+
78
+
79
+ class MediaSubmitInterrupted(RuntimeError):
80
+ """The submit reached fal but its answer was lost (timeout, dropped
81
+ connection, gateway error). The job MAY exist and MAY be billed, and there
82
+ is no handle to collect it. The platform never resubmits on its own —
83
+ resubmitting is the app's decision, and it can mean paying twice."""
84
+
85
+ def __init__(self, message: str = "", *, model: str | None = None, **details: Any):
86
+ super().__init__(message or f"ctx.media: submitting {model} was interrupted; the job may or may not exist")
87
+ self.model = model
88
+ self.__dict__.update(details)
89
+
90
+
91
+ MediaSubmitInterrupted = _shared(MediaSubmitInterrupted)
92
+
93
+
94
+ class MediaStillRunning(TimeoutError):
95
+ """The fal job is still going (or could not be polled right now).
96
+
97
+ `handle` is the durable resume handle — persist it (a DB row, ctx.jobs
98
+ payload, the browser) and collect with `ctx.media.result(handle)`.
99
+ """
100
+
101
+ def __init__(self, request_id: str = "", model: str = "", **handle: Any):
102
+ super().__init__(
103
+ f"ctx.media: {model} is still running — collect it with ctx.media.result(exc.handle)"
104
+ )
105
+ self.request_id = request_id
106
+ self.model = model
107
+ self.handle = {"request_id": request_id, "model": model, **handle}
108
+
109
+
110
+ MediaStillRunning = _shared(MediaStillRunning)
14
111
 
15
112
 
16
113
  class UnavailablePlatformService:
@@ -377,13 +474,125 @@ class LocalVectorService:
377
474
  return {"indexes": {name: len(items) for name, items in self._items.items()}}
378
475
 
379
476
 
380
- class LocalLLMService:
381
- """`ctx.llm` for pltt dev.
477
+ _TOOL_NAME_CHARS = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-")
478
+
479
+
480
+ def _text_of(content: Any) -> str:
481
+ if isinstance(content, str):
482
+ return content
483
+ if not isinstance(content, list):
484
+ return str(content or "")
485
+ return "".join(
486
+ str(block.get("text") or "")
487
+ for block in content
488
+ if isinstance(block, dict) and block.get("type", "text") in ("text", "output_text")
489
+ )
490
+
491
+
492
+ def _openai_tools(tools: Any) -> list[dict[str, Any]]:
493
+ """Same tool shapes and checks as hosted ctx.llm, as OpenAI function tools."""
494
+ if not tools:
495
+ return []
496
+ if not isinstance(tools, (list, tuple)) or len(tools) > 128:
497
+ raise ValueError("ctx.llm: tools must be a list of at most 128 function definitions")
498
+ out: list[dict[str, Any]] = []
499
+ for tool in tools:
500
+ if not isinstance(tool, dict) or tool.get("type", "function") != "function":
501
+ raise ValueError("ctx.llm: only function tools are supported ({name, description, parameters})")
502
+ fn = tool["function"] if isinstance(tool.get("function"), dict) else tool
503
+ name = fn.get("name")
504
+ if (
505
+ not isinstance(name, str)
506
+ or not 0 < len(name) <= 64
507
+ or set(name) - _TOOL_NAME_CHARS
508
+ or name in {t["function"]["name"] for t in out}
509
+ ):
510
+ raise ValueError(f"ctx.llm: tool names must be unique and match [A-Za-z0-9_-]{{1,64}} (got {name!r})")
511
+ parameters = fn.get("parameters", fn.get("input_schema")) or {"type": "object", "properties": {}}
512
+ if not isinstance(parameters, dict):
513
+ raise ValueError(f"ctx.llm: tool {name!r} parameters must be a JSON-schema object")
514
+ out.append({
515
+ "type": "function",
516
+ "function": {"name": name, "description": str(fn.get("description") or ""), "parameters": parameters},
517
+ })
518
+ return out
519
+
520
+
521
+ def _openai_tool_choice(choice: Any, tools: list[dict[str, Any]]) -> Any:
522
+ if choice is None or choice == "auto":
523
+ return None
524
+ if isinstance(choice, dict):
525
+ choice = (choice.get("function") or {}).get("name") or choice.get("name")
526
+ if choice in ("required", "any"):
527
+ return "required"
528
+ if choice == "none":
529
+ return "none"
530
+ if not isinstance(choice, str) or choice not in {t["function"]["name"] for t in tools}:
531
+ raise ValueError("ctx.llm: tool_choice must be 'auto', 'none', 'required' or the name of a passed tool")
532
+ return {"type": "function", "function": {"name": choice}}
533
+
534
+
535
+ def _openai_messages(messages: list[dict[str, Any]], system: str | None) -> list[dict[str, Any]]:
536
+ """The hosted ctx.llm history format, spoken as chat-completions."""
537
+ systems = [system] if system else []
538
+ out: list[dict[str, Any]] = []
539
+ for message in messages or []:
540
+ if not isinstance(message, dict):
541
+ raise ValueError("ctx.llm: every message must be a dict with a role")
542
+ role = str(message.get("role") or "user")
543
+ content = message.get("content")
544
+ if role in ("system", "developer"):
545
+ systems.append(_text_of(content))
546
+ elif role == "assistant":
547
+ entry: dict[str, Any] = {"role": "assistant", "content": _text_of(content) or None}
548
+ calls = []
549
+ for call in message.get("tool_calls") or []:
550
+ fn = call["function"] if isinstance(call.get("function"), dict) else call
551
+ args = fn.get("arguments", fn.get("args")) or {}
552
+ calls.append({
553
+ "id": str(call.get("id") or ""),
554
+ "type": "function",
555
+ "function": {"name": str(fn.get("name") or ""), "arguments": args if isinstance(args, str) else json.dumps(args)},
556
+ })
557
+ if calls:
558
+ entry["tool_calls"] = calls
559
+ out.append(entry)
560
+ elif role == "tool":
561
+ if not message.get("tool_call_id"):
562
+ raise ValueError("ctx.llm: a role=tool message needs the tool_call_id it answers")
563
+ out.append({
564
+ "role": "tool",
565
+ "tool_call_id": str(message["tool_call_id"]),
566
+ "content": content if isinstance(content, str) else json.dumps(content, default=str),
567
+ })
568
+ else:
569
+ out.append({"role": "user", "content": content if isinstance(content, list) else str(content or "")})
570
+ if systems:
571
+ out.insert(0, {"role": "system", "content": "\n\n".join(text for text in systems if text)})
572
+ return out
382
573
 
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.
574
+
575
+ def _stop_reason(raw: Any, has_calls: bool) -> str:
576
+ key = str(raw or "").lower()
577
+ if key in ("length", "max_tokens", "max_output_tokens"):
578
+ return "length"
579
+ if key in ("content_filter", "refusal", "safety"):
580
+ return "content_filter"
581
+ if has_calls or key in ("tool_calls", "function_call", "tool_use"):
582
+ return "tool_calls"
583
+ return "stop"
584
+
585
+
586
+ class LocalLLMService:
587
+ """`ctx.llm` for pltt dev — the hosted call shapes and receipt keys.
588
+
589
+ Hosted, this is the platform's catalog on its keys, under an org spend cap.
590
+ Locally there is no platform: OpenAI models run on the developer's own
591
+ `OPENAI_API_KEY` when the dev env supplies one; without a key every call
592
+ returns a deterministic stub, so the app's code path still runs with zero
593
+ setup. Claude and Gemini ids run hosted only (`pltt dev --sandbox`): here
594
+ they are `provider_unconfigured` — a ModelUnavailable with fallback=False,
595
+ the dev model plus an honest receipt otherwise.
387
596
  """
388
597
 
389
598
  def __init__(self, api_key: str | None = None, model: str = "gpt-5.4-mini"):
@@ -394,21 +603,106 @@ class LocalLLMService:
394
603
  def live(self) -> bool:
395
604
  return bool(self.api_key)
396
605
 
606
+ def _pick(self, requested: str | None, fallback: bool) -> tuple[str, str | None]:
607
+ if not requested or (self.live and requested.startswith(("gpt-", "o1", "o3", "o4"))):
608
+ return requested or self.model, None
609
+ if not fallback:
610
+ raise ModelUnavailable(
611
+ f"ctx.llm: {requested!r} is unavailable under pltt dev — only OpenAI ids run, on an "
612
+ "OPENAI_API_KEY in .env.local; use pltt dev --sandbox for the platform catalog",
613
+ model=requested,
614
+ reason="provider_unconfigured",
615
+ )
616
+ return self.model, "provider_unconfigured"
617
+
397
618
  @staticmethod
398
619
  def _last_user(messages: list[dict[str, Any]]) -> str:
399
620
  for message in reversed(messages or []):
400
621
  if str(message.get("role") or "user") == "user":
401
- return str(message.get("content") or "")
622
+ return _text_of(message.get("content"))
402
623
  return ""
403
624
 
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,
625
+ def _receipt(
626
+ self,
627
+ *,
628
+ text: str,
629
+ calls: list[dict[str, Any]],
630
+ broken: list[dict[str, Any]],
631
+ finish: Any,
632
+ model: str,
633
+ provider: str,
634
+ requested: str | None,
635
+ reason: str | None,
636
+ usage: dict[str, int],
637
+ max_tokens: int,
638
+ ) -> dict[str, Any]:
639
+ stop = _stop_reason(finish, bool(calls or broken))
640
+ message: dict[str, Any] = {"role": "assistant", "content": text}
641
+ if calls:
642
+ message["tool_calls"] = calls
643
+ out = {
644
+ "text": text,
645
+ "model": model,
646
+ "provider": provider,
647
+ "provider_model": model,
648
+ "requested_model": requested,
649
+ "fallback_used": reason is not None,
650
+ "fallback_reason": reason,
651
+ "attempts": [],
652
+ "stop_reason": stop,
653
+ "provider_stop_reason": finish,
654
+ "truncated": stop == "length",
655
+ "tool_calls": calls,
656
+ "message": message,
657
+ "max_tokens": max_tokens,
658
+ "input_tokens": usage.get("input_tokens", 0),
659
+ "output_tokens": usage.get("output_tokens", 0),
660
+ "usage": {"cached_input_tokens": 0, "reasoning_tokens": 0, **usage},
661
+ "cost_usd": None,
662
+ }
663
+ if broken:
664
+ out["invalid_tool_calls"] = broken
665
+ return out
666
+
667
+ def _stub(self, messages, requested: str | None, max_tokens: int) -> dict[str, Any]:
668
+ return self._receipt(
669
+ text=f"[pltt dev: no LLM key] {self._last_user(messages)}",
670
+ calls=[],
671
+ broken=[],
672
+ finish="stop",
673
+ model="pltt-dev-stub",
674
+ provider="pltt-dev",
675
+ requested=requested,
676
+ reason="provider_unconfigured" if requested else None,
677
+ usage={"input_tokens": 0, "output_tokens": 0},
678
+ max_tokens=max_tokens,
679
+ )
680
+
681
+ def _request(self, messages, system, model, max_tokens, tools, tool_choice, kwargs) -> dict[str, Any]:
682
+ specs = _openai_tools(tools)
683
+ body: dict[str, Any] = {
684
+ "model": model,
685
+ "messages": _openai_messages(messages, system),
686
+ "max_completion_tokens": max_tokens,
687
+ **kwargs,
411
688
  }
689
+ if specs:
690
+ body["tools"] = specs
691
+ choice = _openai_tool_choice(tool_choice, specs)
692
+ if choice is not None:
693
+ body["tool_choice"] = choice
694
+ return body
695
+
696
+ @staticmethod
697
+ def _calls(raw_calls: list[tuple[str, str, str]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
698
+ calls, broken = [], []
699
+ for call_id, name, arguments in raw_calls:
700
+ try:
701
+ args = json.loads(arguments) if arguments.strip() else {}
702
+ calls.append({"id": call_id, "name": name, "arguments": args if isinstance(args, dict) else {"value": args}})
703
+ except ValueError as exc:
704
+ broken.append({"id": call_id, "name": name, "raw_arguments": arguments, "error": str(exc)})
705
+ return calls, broken
412
706
 
413
707
  async def chat(
414
708
  self,
@@ -418,42 +712,105 @@ class LocalLLMService:
418
712
  system: str | None = None,
419
713
  max_tokens: int = 1024,
420
714
  temperature: float = 0.2,
715
+ tools: list[dict[str, Any]] | None = None,
716
+ tool_choice: Any = None,
717
+ fallback: bool = True,
718
+ **kwargs: Any,
421
719
  ) -> dict[str, Any]:
720
+ requested = (model or "").strip() or None
721
+ # Same checks as hosted, stubbed or not: bad tools / tool_choice are a
722
+ # ValueError and fallback=False refuses what pltt dev cannot run.
723
+ specs = _openai_tools(tools)
724
+ if specs:
725
+ _openai_tool_choice(tool_choice, specs)
726
+ used, reason = self._pick(requested, fallback)
422
727
  if not self.live:
423
- return self._stub(messages)
728
+ return self._stub(messages, requested, max_tokens)
424
729
  from openai import AsyncOpenAI
425
730
 
426
- payload = ([{"role": "system", "content": system}] if system else []) + list(messages)
427
731
  reply = await AsyncOpenAI(api_key=self.api_key).chat.completions.create(
428
- model=model or self.model, messages=payload, max_completion_tokens=max_tokens
732
+ **self._request(messages, system, used, max_tokens, tools, tool_choice, kwargs)
429
733
  )
734
+ choice = reply.choices[0]
735
+ calls, broken = self._calls([
736
+ (call.id, call.function.name, call.function.arguments or "")
737
+ for call in (choice.message.tool_calls or [])
738
+ ])
430
739
  usage = reply.usage
431
- return {
432
- "text": reply.choices[0].message.content or "",
433
- "model": reply.model,
434
- "input_tokens": getattr(usage, "prompt_tokens", 0),
435
- "output_tokens": getattr(usage, "completion_tokens", 0),
436
- "cost_usd": None,
437
- }
740
+ return self._receipt(
741
+ text=choice.message.content or "",
742
+ calls=calls,
743
+ broken=broken,
744
+ finish=choice.finish_reason,
745
+ model=used,
746
+ provider="openai",
747
+ requested=requested,
748
+ reason=reason,
749
+ usage={
750
+ "input_tokens": getattr(usage, "prompt_tokens", 0) or 0,
751
+ "output_tokens": getattr(usage, "completion_tokens", 0) or 0,
752
+ },
753
+ max_tokens=max_tokens,
754
+ )
438
755
 
439
- async def stream(self, messages: list[dict[str, Any]], **kwargs):
756
+ async def stream(
757
+ self,
758
+ messages: list[dict[str, Any]],
759
+ *,
760
+ model: str | None = None,
761
+ system: str | None = None,
762
+ max_tokens: int = 1024,
763
+ temperature: float = 0.2,
764
+ tools: list[dict[str, Any]] | None = None,
765
+ tool_choice: Any = None,
766
+ fallback: bool = True,
767
+ events: bool = False,
768
+ **kwargs: Any,
769
+ ):
770
+ requested = (model or "").strip() or None
771
+ specs = _openai_tools(tools)
772
+ if specs:
773
+ _openai_tool_choice(tool_choice, specs)
774
+ used, reason = self._pick(requested, fallback)
440
775
  if not self.live:
441
- yield self._stub(messages)["text"]
776
+ stub = self._stub(messages, requested, max_tokens)
777
+ yield {"type": "text", "text": stub["text"]} if events else stub["text"]
778
+ if events:
779
+ yield {"type": "done", **stub}
442
780
  return
443
781
  from openai import AsyncOpenAI
444
782
 
445
- system = kwargs.get("system")
446
- payload = ([{"role": "system", "content": system}] if system else []) + list(messages)
783
+ body = self._request(messages, system, used, max_tokens, tools, tool_choice, kwargs)
447
784
  stream = await AsyncOpenAI(api_key=self.api_key).chat.completions.create(
448
- model=kwargs.get("model") or self.model,
449
- messages=payload,
450
- max_completion_tokens=kwargs.get("max_tokens", 1024),
451
- stream=True,
785
+ **body, stream=True, stream_options={"include_usage": True}
452
786
  )
787
+ text: list[str] = []
788
+ pending: dict[int, list[str]] = {}
789
+ finish = None
790
+ usage = {"input_tokens": 0, "output_tokens": 0}
453
791
  async for chunk in stream:
454
- delta = chunk.choices[0].delta if chunk.choices else None
792
+ if chunk.usage:
793
+ usage = {"input_tokens": chunk.usage.prompt_tokens or 0, "output_tokens": chunk.usage.completion_tokens or 0}
794
+ if not chunk.choices:
795
+ continue
796
+ choice = chunk.choices[0]
797
+ finish = choice.finish_reason or finish
798
+ delta = choice.delta
455
799
  if delta and delta.content:
456
- yield delta.content
800
+ text.append(delta.content)
801
+ yield {"type": "text", "text": delta.content} if events else delta.content
802
+ for call in (delta.tool_calls if delta else None) or []:
803
+ slot = pending.setdefault(call.index, ["", "", ""])
804
+ slot[0] = call.id or slot[0]
805
+ if call.function:
806
+ slot[1] = call.function.name or slot[1]
807
+ slot[2] += call.function.arguments or ""
808
+ if events:
809
+ calls, broken = self._calls([tuple(pending[index]) for index in sorted(pending)])
810
+ yield {"type": "done", **self._receipt(
811
+ text="".join(text), calls=calls, broken=broken, finish=finish, model=used, provider="openai",
812
+ requested=requested, reason=reason, usage=usage, max_tokens=max_tokens,
813
+ )}
457
814
 
458
815
  async def embed(self, texts: list[str]) -> list[list[float]]:
459
816
  if not self.live:
@@ -467,9 +824,34 @@ class LocalLLMService:
467
824
  )
468
825
  return [item.embedding for item in reply.data]
469
826
 
470
- async def image(self, prompt: str, *, aspect_ratio: str = "1:1") -> tuple[bytes, str]:
827
+ async def image(self, prompt: str, *, aspect_ratio: str = "1:1", **kwargs: Any) -> tuple[bytes, str]:
471
828
  raise NotImplementedError("ctx.llm.image runs on the platform only — use pltt dev --sandbox")
472
829
 
830
+ async def catalog(self) -> list[dict[str, Any]]:
831
+ """Hosted, every model on the platform with limits and availability
832
+ reasons. Locally only the dev model is known."""
833
+ return [{
834
+ "id": self.model,
835
+ "name": self.model,
836
+ "provider": "openai",
837
+ "kind": "chat",
838
+ "capabilities": ["chat", "streaming", "tools", "vision"],
839
+ "limits": {"max_output_tokens": None, "max_input_tokens": None, "max_images": None},
840
+ "tier": "standard",
841
+ "available": self.live,
842
+ "reason": None if self.live else "provider_unconfigured",
843
+ "default": True,
844
+ }]
845
+
846
+ async def models(self) -> list[str]:
847
+ """Hosted, this is the list the platform will honour in `model=`.
848
+ Locally there is no catalog, so it reports the dev model only."""
849
+ return [self.model] if self.live else []
850
+
851
+ async def spend(self) -> dict[str, Any]:
852
+ """Hosted, the org's monthly wallet. Locally the developer's own key pays."""
853
+ return {"spent_usd": 0.0, "cap_usd": None, "remaining_usd": None}
854
+
473
855
 
474
856
  class LocalWebService:
475
857
  """`ctx.web` for pltt dev — keyless DuckDuckGo search plus a plain fetch."""
@@ -497,3 +879,375 @@ class LocalWebService:
497
879
  response = await client.get(url)
498
880
  response.raise_for_status()
499
881
  return response.text
882
+
883
+
884
+ # 1x1 transparent PNG. Enough for a stubbed render to flow through an <img>
885
+ # and any "did I get a URL back" branch without a network call.
886
+ _STUB_PNG = (
887
+ "data:image/png;base64,"
888
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
889
+ )
890
+
891
+
892
+ class LocalMediaService:
893
+ """`ctx.media` for pltt dev — the same fal.ai surface as hosted.
894
+
895
+ Hosted, the platform's own `FAL_KEY` pays under the org's monthly cap.
896
+ Locally there is no platform: if the dev env supplies a `FAL_KEY` the calls
897
+ are real, otherwise every call returns a stub shaped like a fal response so
898
+ the app's code path still runs with zero setup.
899
+ """
900
+
901
+ QUEUE_BASE = "https://queue.fal.run"
902
+ # fal's own upload flow (fal-client "fal_v3"): trade the key for a CDN
903
+ # token, then POST the bytes. storage.fal.ai no longer resolves.
904
+ CDN_TOKEN_URL = "https://rest.fal.ai/storage/auth/token?storage_type=fal-cdn-v3"
905
+ CDN_UPLOAD_URL = "https://v3.fal.media/files/upload"
906
+ POLL_INTERVAL_S = 3.0
907
+ SUBMIT_ATTEMPTS = 3
908
+ RETRY_BASE_S = 1.0
909
+ DEFAULT_MODELS = {
910
+ "image": "fal-ai/flux/dev",
911
+ "video": "fal-ai/kling-video/v3/standard/text-to-video",
912
+ "speech": "fal-ai/elevenlabs/tts/turbo-v2.5",
913
+ "transcribe": "fal-ai/whisper",
914
+ }
915
+ _DEFAULT_KINDS = {"image": "image", "video": "video", "speech": "audio", "transcribe": "audio"}
916
+
917
+ def __init__(self, api_key: str | None = None, storage: Any = None):
918
+ self.api_key = api_key or ""
919
+ self._storage = storage
920
+ self._cdn_token: dict[str, Any] | None = None
921
+
922
+ @property
923
+ def live(self) -> bool:
924
+ return bool(self.api_key)
925
+
926
+ def _headers(self) -> dict[str, str]:
927
+ return {"Authorization": f"Key {self.api_key}"}
928
+
929
+ @staticmethod
930
+ def _merge(payload: dict[str, Any] | None, fields: dict[str, Any]) -> dict[str, Any]:
931
+ return {**(payload or {}), **fields}
932
+
933
+ def _queue_urls(self, model: str, request_id: str) -> tuple[str, str, str]:
934
+ base = "/".join(str(model).strip("/").split("/")[:2])
935
+ root = f"{self.QUEUE_BASE}/{base}/requests/{request_id}"
936
+ return f"{root}/status", root, f"{root}/cancel"
937
+
938
+ @staticmethod
939
+ def _ref(request: Any, model: str | None) -> tuple[str, str]:
940
+ """(request_id, model) from a submit() handle or a bare request id."""
941
+ if isinstance(request, dict):
942
+ return str(request.get("request_id") or ""), str(model or request.get("model") or "")
943
+ return str(request or ""), str(model or "")
944
+
945
+ @staticmethod
946
+ def _fal_host_ok(url: str) -> bool:
947
+ """A url fetched with the FAL_KEY attached must be on fal's domains.
948
+
949
+ Locally the key is the developer's own, but it is still a key, and
950
+ keeping the check identical to the hosted service means the two cannot
951
+ drift apart. Exact apex or dot-prefixed subdomain only: a bare
952
+ `endswith("fal.run")` would also accept `evilfal.run`.
953
+ """
954
+ from urllib.parse import urlparse
955
+
956
+ parsed = urlparse(url or "")
957
+ host = (parsed.hostname or "").lower().rstrip(".")
958
+ return parsed.scheme == "https" and any(
959
+ host == domain or host.endswith(f".{domain}") for domain in ("fal.run", "fal.ai")
960
+ )
961
+
962
+ @staticmethod
963
+ def _stub(model: str, payload: dict[str, Any]) -> dict[str, Any]:
964
+ """A fal-shaped placeholder covering the output keys the common
965
+ families use, so `out["images"][0]["url"]` and friends resolve."""
966
+ return {
967
+ "pltt_dev_stub": True,
968
+ "model": model,
969
+ "request": payload,
970
+ "images": [{"url": _STUB_PNG, "content_type": "image/png", "width": 1, "height": 1}],
971
+ "image": {"url": _STUB_PNG, "content_type": "image/png"},
972
+ "video": {"url": _STUB_PNG, "content_type": "video/mp4"},
973
+ "audio": {"url": _STUB_PNG, "content_type": "audio/mpeg"},
974
+ "audio_url": {"url": _STUB_PNG},
975
+ "text": f"[pltt dev: no FAL_KEY] {payload.get('prompt') or payload.get('text') or ''}",
976
+ }
977
+
978
+ async def submit(self, model: str, payload: dict[str, Any] | None = None, **fields: Any) -> dict[str, Any]:
979
+ """Queue a job; returns the durable handle {request_id, model,
980
+ status_url, response_url, cancel_url}. A 429 is retried with backoff,
981
+ then MediaRateLimited; a lost answer is MediaSubmitInterrupted."""
982
+ body = self._merge(payload, fields)
983
+ if not self.live:
984
+ return {
985
+ "request_id": "pltt-dev-stub", "model": model, "status_url": "", "response_url": "",
986
+ "cancel_url": "", "request": body,
987
+ }
988
+ import httpx
989
+
990
+ async with httpx.AsyncClient(timeout=60.0, headers=self._headers()) as client:
991
+ for attempt in range(1, self.SUBMIT_ATTEMPTS + 1):
992
+ try:
993
+ response = await client.post(f"{self.QUEUE_BASE}/{str(model).strip('/')}", json=body)
994
+ except (httpx.ConnectError, httpx.ConnectTimeout):
995
+ if attempt == self.SUBMIT_ATTEMPTS:
996
+ raise
997
+ await asyncio.sleep(self.RETRY_BASE_S * attempt)
998
+ continue
999
+ except httpx.TransportError as exc:
1000
+ raise MediaSubmitInterrupted(model=model) from exc
1001
+ if response.status_code in (502, 504):
1002
+ raise MediaSubmitInterrupted(model=model, status_code=response.status_code)
1003
+ if response.status_code != 429:
1004
+ break
1005
+ if attempt == self.SUBMIT_ATTEMPTS:
1006
+ retry = str(response.headers.get("retry-after") or "")
1007
+ raise MediaRateLimited(
1008
+ model=model, retry_after=float(retry) if retry.replace(".", "", 1).isdigit() else None
1009
+ )
1010
+ await asyncio.sleep(self.RETRY_BASE_S * attempt)
1011
+ response.raise_for_status()
1012
+ task = response.json() or {}
1013
+ request_id = str(task.get("request_id") or "")
1014
+ rebuilt_status, rebuilt_response, rebuilt_cancel = self._queue_urls(model, request_id)
1015
+ provider_status = str(task.get("status_url") or "")
1016
+ provider_response = str(task.get("response_url") or "")
1017
+ provider_cancel = str(task.get("cancel_url") or "")
1018
+ return {
1019
+ "request_id": request_id,
1020
+ "model": model,
1021
+ "status_url": provider_status if self._fal_host_ok(provider_status) else rebuilt_status,
1022
+ "response_url": provider_response if self._fal_host_ok(provider_response) else rebuilt_response,
1023
+ "cancel_url": provider_cancel if self._fal_host_ok(provider_cancel) else rebuilt_cancel,
1024
+ }
1025
+
1026
+ async def status(self, request: Any, *, model: str | None = None, **params: Any) -> dict[str, Any]:
1027
+ if not self.live:
1028
+ return {"status": "COMPLETED", "pltt_dev_stub": True}
1029
+ import httpx
1030
+
1031
+ request_id, model = self._ref(request, model)
1032
+ status_url, _response, _cancel = self._queue_urls(model, request_id)
1033
+ async with httpx.AsyncClient(timeout=30.0, headers=self._headers()) as client:
1034
+ response = await client.get(status_url, params=params or None)
1035
+ response.raise_for_status()
1036
+ return response.json() or {}
1037
+
1038
+ async def result(self, request: Any, *, model: str | None = None) -> dict[str, Any]:
1039
+ """The finished output; an unfinished job raises MediaStillRunning."""
1040
+ request_id, model = self._ref(request, model)
1041
+ if not self.live:
1042
+ return self._stub(model, {})
1043
+ import httpx
1044
+
1045
+ state = await self.status(request_id, model=model)
1046
+ if str(state.get("status") or "").upper() in ("IN_QUEUE", "IN_PROGRESS"):
1047
+ raise MediaStillRunning(request_id, model)
1048
+ _status, response_url, _cancel = self._queue_urls(model, request_id)
1049
+ async with httpx.AsyncClient(timeout=60.0, headers=self._headers()) as client:
1050
+ response = await client.get(response_url)
1051
+ response.raise_for_status()
1052
+ return response.json() or {}
1053
+
1054
+ async def cancel(self, request: Any, *, model: str | None = None) -> dict[str, Any]:
1055
+ if not self.live:
1056
+ return {"cancelled": True, "pltt_dev_stub": True}
1057
+ import httpx
1058
+
1059
+ request_id, model = self._ref(request, model)
1060
+ _status, _response, cancel_url = self._queue_urls(model, request_id)
1061
+ async with httpx.AsyncClient(timeout=30.0, headers=self._headers()) as client:
1062
+ response = await client.put(cancel_url)
1063
+ return {"cancelled": response.status_code < 400, "status_code": response.status_code}
1064
+
1065
+ async def run(
1066
+ self,
1067
+ model: str,
1068
+ payload: dict[str, Any] | None = None,
1069
+ *,
1070
+ timeout: float | None = None,
1071
+ poll_interval: float | None = None,
1072
+ on_status: Any = None,
1073
+ **fields: Any,
1074
+ ) -> dict[str, Any]:
1075
+ body = self._merge(payload, fields)
1076
+ if not self.live:
1077
+ return self._stub(model, body)
1078
+ import httpx
1079
+
1080
+ job = await self.submit(model, body)
1081
+ handle = {key: value for key, value in job.items() if key not in ("request_id", "model")}
1082
+ deadline = time.monotonic() + float(timeout if timeout is not None else 600.0)
1083
+ interval = float(poll_interval or self.POLL_INTERVAL_S)
1084
+ last = None
1085
+ async with httpx.AsyncClient(timeout=30.0, headers=self._headers()) as client:
1086
+ while True:
1087
+ try:
1088
+ probe = await client.get(job["status_url"])
1089
+ probe.raise_for_status()
1090
+ body_state = probe.json() or {}
1091
+ except (httpx.HTTPError, ValueError) as exc:
1092
+ # Queued and paid for: hand back the handle, never lose it.
1093
+ raise MediaStillRunning(job["request_id"], model, **handle) from exc
1094
+ state = str(body_state.get("status") or "").upper()
1095
+ if state != last:
1096
+ last = state
1097
+ if on_status is not None:
1098
+ outcome = on_status(state)
1099
+ if asyncio.iscoroutine(outcome):
1100
+ await outcome
1101
+ if state == "COMPLETED":
1102
+ break
1103
+ if state in ("FAILED", "ERROR", "CANCELLED"):
1104
+ raise RuntimeError(f"ctx.media: {model} {state.lower()} ({str(body_state)[:300]})")
1105
+ if time.monotonic() > deadline:
1106
+ raise MediaStillRunning(job["request_id"], model, **handle)
1107
+ await asyncio.sleep(interval)
1108
+ final = await client.get(job["response_url"])
1109
+ final.raise_for_status()
1110
+ return final.json() or {}
1111
+
1112
+ async def image(self, prompt: str, *, model: str | None = None, **payload: Any) -> dict[str, Any]:
1113
+ return await self.run(model or self.DEFAULT_MODELS["image"], {"prompt": prompt, **payload})
1114
+
1115
+ async def video(self, prompt: str, *, model: str | None = None, **payload: Any) -> dict[str, Any]:
1116
+ return await self.run(model or self.DEFAULT_MODELS["video"], {"prompt": prompt, **payload})
1117
+
1118
+ async def speech(self, text: str, *, model: str | None = None, **payload: Any) -> dict[str, Any]:
1119
+ return await self.run(model or self.DEFAULT_MODELS["speech"], {"text": text, **payload})
1120
+
1121
+ async def transcribe(self, audio_url: str, *, model: str | None = None, **payload: Any) -> dict[str, Any]:
1122
+ return await self.run(model or self.DEFAULT_MODELS["transcribe"], {"audio_url": audio_url, **payload})
1123
+
1124
+ async def _source_bytes(self, source: Any) -> tuple[bytes, str | None]:
1125
+ """bytes | data: URL | file:// URL inside local ctx.storage | https URL."""
1126
+ import base64
1127
+ from pathlib import Path
1128
+ from urllib.parse import unquote, unquote_to_bytes, urlparse
1129
+
1130
+ if isinstance(source, (bytes, bytearray, memoryview)):
1131
+ return bytes(source), None
1132
+ if not isinstance(source, str) or not source.strip():
1133
+ raise ValueError("ctx.media.upload: pass bytes, a data: URL, an https URL or a ctx.storage file URL")
1134
+ if source.startswith("data:"):
1135
+ header, _, encoded = source.partition(",")
1136
+ data = base64.b64decode(encoded) if ";base64" in header else unquote_to_bytes(encoded)
1137
+ return data, header[5:].split(";")[0] or None
1138
+ if source.startswith("file:"):
1139
+ # pltt dev's ctx.storage hands out file:// URLs; like hosted, only
1140
+ # this app's own storage is readable through upload().
1141
+ storage = self._storage
1142
+ root = getattr(storage, "root", None)
1143
+ target = Path(unquote(urlparse(source).path)).resolve()
1144
+ if root is None or not target.is_relative_to((Path(root) / storage._prefix()).resolve()):
1145
+ raise ValueError("ctx.media.upload: only this app's own ctx.storage files can be read by URL")
1146
+ return target.read_bytes(), None
1147
+ import httpx
1148
+
1149
+ async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client:
1150
+ fetched = await client.get(source)
1151
+ fetched.raise_for_status()
1152
+ return fetched.content, (fetched.headers.get("content-type") or "").split(";")[0].strip() or None
1153
+
1154
+ async def upload(
1155
+ self,
1156
+ source: bytes | str,
1157
+ *,
1158
+ filename: str | None = None,
1159
+ content_type: str | None = None,
1160
+ ) -> str:
1161
+ if not self.live:
1162
+ return _STUB_PNG
1163
+ import httpx
1164
+ import mimetypes
1165
+ from urllib.parse import urlparse
1166
+
1167
+ content, detected = await self._source_bytes(source)
1168
+ mime = content_type or detected or _sniff_mime(content) or "application/octet-stream"
1169
+ name = filename
1170
+ if not name and isinstance(source, str) and not source.startswith("data:"):
1171
+ name = urlparse(source).path.rsplit("/", 1)[-1]
1172
+ name = name or f"upload{mimetypes.guess_extension(mime) or '.bin'}"
1173
+ async with httpx.AsyncClient(timeout=120.0) as client:
1174
+ for refresh in (False, True):
1175
+ if refresh or not self._cdn_token or self._cdn_token["expires"] < time.time() + 300:
1176
+ minted = await client.post(
1177
+ self.CDN_TOKEN_URL, headers={**self._headers(), "Accept": "application/json"}, json={}
1178
+ )
1179
+ minted.raise_for_status()
1180
+ data = minted.json() or {}
1181
+ self._cdn_token = {"auth": f"{data['token_type']} {data['token']}", "expires": time.time() + 3600}
1182
+ response = await client.post(
1183
+ self.CDN_UPLOAD_URL,
1184
+ content=content,
1185
+ headers={"Authorization": self._cdn_token["auth"], "Content-Type": mime, "X-Fal-File-Name": name},
1186
+ )
1187
+ if response.status_code != 401:
1188
+ break
1189
+ response.raise_for_status()
1190
+ url = str((response.json() or {}).get("access_url") or "")
1191
+ if not url.startswith("https://"):
1192
+ raise RuntimeError(f"ctx.media: fal upload returned no URL ({response.text[:200]})")
1193
+ return url
1194
+
1195
+ async def save(self, url: str, *, filename: str | None = None, key: str | None = None) -> dict[str, Any]:
1196
+ if self._storage is None or isinstance(self._storage, UnavailablePlatformService):
1197
+ raise PlatformServiceUnavailable(
1198
+ 'ctx.media.save needs storage too — declare platform_services: ["media", "storage"]'
1199
+ )
1200
+ name = filename or url.split("?")[0].rsplit("/", 1)[-1] or "media.bin"
1201
+ if url.startswith("data:"):
1202
+ import base64
1203
+
1204
+ header, _, encoded = url.partition(",")
1205
+ content = base64.b64decode(encoded) if ";base64" in header else encoded.encode()
1206
+ content_type = header[5:].split(";")[0] or "application/octet-stream"
1207
+ else:
1208
+ import httpx
1209
+
1210
+ async with httpx.AsyncClient(timeout=120.0, follow_redirects=True) as client:
1211
+ response = await client.get(url)
1212
+ response.raise_for_status()
1213
+ content = response.content
1214
+ content_type = (response.headers.get("content-type") or "application/octet-stream").split(";")[0].strip()
1215
+ return await self._storage.upload_file(name, content, content_type, key=key)
1216
+
1217
+ async def catalog(self, kind: str | None = None) -> list[dict[str, Any]]:
1218
+ """Hosted, the platform's priced fal models with limits and reasons.
1219
+ Locally, the sugar defaults — `run()` still takes any fal id."""
1220
+ rows = []
1221
+ for sugar, model in sorted(self.DEFAULT_MODELS.items()):
1222
+ row_kind = self._DEFAULT_KINDS[sugar]
1223
+ if kind and row_kind != kind:
1224
+ continue
1225
+ rows.append({
1226
+ "id": model,
1227
+ "name": model,
1228
+ "provider": "fal",
1229
+ "kind": row_kind,
1230
+ "operations": [{"image": "text-to-image", "video": "text-to-video", "speech": "text-to-speech", "transcribe": "speech-to-text"}[sugar]],
1231
+ "limits": {"unit": "request", "max_units": None, "max_upload_bytes": 100 * 1024 * 1024},
1232
+ "available": self.live,
1233
+ "reason": None if self.live else "provider_unconfigured",
1234
+ "default_for": [sugar],
1235
+ })
1236
+ return rows
1237
+
1238
+ async def spend(self) -> dict[str, Any]:
1239
+ """Hosted, the org's monthly wallet. Locally the developer's own key pays."""
1240
+ return {"spent_usd": 0.0, "cap_usd": None, "remaining_usd": None}
1241
+
1242
+
1243
+ def _sniff_mime(content: bytes) -> str | None:
1244
+ """fal models read the stored Content-Type; application/octet-stream is not an image."""
1245
+ if content.startswith(b"\x89PNG\r\n\x1a\n"):
1246
+ return "image/png"
1247
+ if content.startswith(b"\xff\xd8\xff"):
1248
+ return "image/jpeg"
1249
+ if content[:4] == b"RIFF" and content[8:12] == b"WEBP":
1250
+ return "image/webp"
1251
+ if content.startswith((b"GIF87a", b"GIF89a")):
1252
+ return "image/gif"
1253
+ return None