@palettelab/cli 0.3.63 → 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 (42) hide show
  1. package/README.md +115 -8
  2. package/backend-sdk/palette_sdk/__init__.py +11 -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 +2 -1
  7. package/backend-sdk/palette_sdk/platform_services.py +280 -2
  8. package/backend-sdk/palette_sdk/plugin_context.py +27 -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 +12 -2
  15. package/lib/commands/capabilities.js +1 -1
  16. package/lib/commands/doctor.js +15 -0
  17. package/lib/commands/platform.js +137 -0
  18. package/lib/commands/test.js +47 -4
  19. package/lib/dev-simulator.js +95 -0
  20. package/lib/manifest.js +100 -2
  21. package/package.json +1 -1
  22. package/template-fallback/README.md +9 -0
  23. package/template-fallback/frontend/src/translations.ts +2 -2
  24. package/template-fallback/package.json +1 -1
  25. package/template-fallback/palette-plugin.json +1 -0
  26. package/template-fallback/templates/agent-tool/palette-plugin.json +1 -0
  27. package/template-fallback/templates/consumer-app/package.json +1 -1
  28. package/template-fallback/templates/consumer-app/palette-plugin.json +1 -0
  29. package/template-fallback/templates/dashboard/package.json +1 -1
  30. package/template-fallback/templates/dashboard/palette-plugin.json +1 -0
  31. package/template-fallback/templates/database/package.json +1 -1
  32. package/template-fallback/templates/database/palette-plugin.json +1 -0
  33. package/template-fallback/templates/external-service/package.json +1 -1
  34. package/template-fallback/templates/external-service/palette-plugin.json +1 -0
  35. package/template-fallback/templates/frontend-only/package.json +1 -1
  36. package/template-fallback/templates/frontend-only/palette-plugin.json +1 -0
  37. package/template-fallback/templates/next/package.json +1 -1
  38. package/template-fallback/templates/next/palette-plugin.json +1 -0
  39. package/template-fallback/templates/palette-app/package.json +1 -1
  40. package/template-fallback/templates/palette-app/palette-plugin.json +1 -0
  41. package/template-fallback/templates/provider-app/package.json +1 -1
  42. package/template-fallback/templates/provider-app/palette-plugin.json +1 -0
package/README.md CHANGED
@@ -308,13 +308,14 @@ async def create_invoice(body: InvoiceIn, ctx: PluginContext = Depends(get_plugi
308
308
 
309
309
  Backend SDK features for app-owned data:
310
310
 
311
- - `PluginRouter`, `PluginContext`, and `get_plugin_context` provide the FastAPI route and request-context surface.
312
- - `PluginContext` exposes `user_id`, `organization_id`, `org_role`, `plugin_id`, `permissions`, `storage`, `ctx.db`, `ctx.jobs`, `ctx.data_rooms`, `ctx.connections`, `ctx.members`, `ctx.redis`, `ctx.vector`, `ctx.llm`, `ctx.web`, `ctx.config`, and `ctx.logger`.
311
+ - `PluginRouter`, `PluginContext`, and `get_plugin_context` provide the FastAPI route and request-context surface. A parameter annotated `ctx: PluginContext` is wired automatically — `Depends(get_plugin_context)` is still accepted and behaves identically.
312
+ - `PluginContext` exposes `user_id`, `organization_id`, `org_role`, `plugin_id`, `permissions`, `storage`, `ctx.db`, `ctx.jobs`, `ctx.data_rooms`, `ctx.connections`, `ctx.members`, `ctx.tasks`, `ctx.redis`, `ctx.vector`, `ctx.llm`, `ctx.media`, `ctx.web`, `ctx.config`, and `ctx.logger`.
313
313
  - `ctx.db` is the full scoped SQLAlchemy `AsyncSession` for app-owned database data.
314
314
  - `ctx.repo(Model)` gives org-safe CRUD helpers for app tables.
315
315
  - `ctx.data_rooms` gives backend access to Palette Data Rooms without importing platform internals.
316
316
  - `ctx.members` gives backend access to current organisation members; it exposes list/get/invite/update-role helpers, but no delete/remove helper.
317
317
  - `ctx.connections.<namespace>.<tool>(...)` calls the third-party services the viewer connected in Palette Connect — `ctx.connections.gmail.search(query=...)`, `ctx.connections.slack.post_message(...)`, and so on for drive, calendar, sheets, docs, slides, contacts, tasks, forms, notion, telegram and meta. `ctx.connections.list()/status(id)/require(id)` report what is connected and granted. There is no `access_token(...)`: the platform holds the credential so scope checks, write approval and audit cannot be bypassed.
318
+ - `ctx.tasks` puts work on the caller's task board and reads it back — `create(title, **fields)`, `list(status=..., limit=...)`, `get`, `update`, `complete(id, output=...)`, `fail`, `delete`. Needs `tasks:read` / `tasks:write`. An app sees **only the tasks it created**: every row is stamped with the app id, another app's task reads as missing, and provenance fields (`app_id`, `source`, `external_ref`, …) are refused rather than silently overwritten.
318
319
  - `ctx.has_permission("...")`, `ctx.has_any_permission([...])`, and `ctx.has_all_permissions([...])` check declared permissions.
319
320
  - `ctx.config_value("key")` and `ctx.require_config("key")` read app install/config values.
320
321
  - `ctx.secret("KEY")` reads app secrets from config or environment variables.
@@ -324,7 +325,10 @@ Backend SDK features for app-owned data:
324
325
  - `ctx.vector` gives a Qdrant-backed, plugin/org-scoped vector API when `"vector"` is declared in `platform_services`.
325
326
  - `ctx.storage` gives app/org-scoped file upload helpers when `"storage"` is declared in `platform_services`.
326
327
  - `ctx.llm` gives chat, streaming, embeddings and image generation on the PLATFORM's own provider keys when `"llm"` is declared — no `OPENAI_API_KEY` secret to ship or rotate. The platform picks the model (an app cannot select the premium tier or bypass the org's SECURE policy), meters spend per organisation and app, and raises once the monthly budget is spent.
328
+ - `ctx.llm` also takes provider passthrough (`response_format`, `top_p`, `stop`, `seed`, …) as plain keywords, and reports `ctx.llm.models()` / `ctx.llm.spend()` so an app can offer a real model picker and explain a refusal.
329
+ - `ctx.media` gives fal.ai on the PLATFORM's key when `"media"` is declared — no `FAL_KEY` secret to ship or rotate. `ctx.media.run(model, payload)` reaches ANY fal model with the payload passed through untouched (so a model fal shipped today needs no SDK release); `image`, `video`, `speech` and `transcribe` are the same call with a default model filled in, `submit`/`status`/`result` handle multi-minute renders, `upload` puts local bytes on fal's CDN, and `save` copies an output into the app's own storage — fal's URLs expire. It shares one monthly wallet with `ctx.llm`.
327
330
  - `ctx.web` gives web search and an SSRF-guarded page reader (HTML tables and PDFs handled) when `"web"` is declared.
331
+ - `pltt platform list` prints every service above with a snippet and its `pltt dev` mode; `pltt platform enable <name>` writes the manifest declaration.
328
332
  - `ctx.connections` gives the viewer's OS service connections — see `pltt connections`.
329
333
  - `@job(...)`, `JobExecution`, and `ctx.jobs` provide durable async work with retries, progress, status, and cancellation.
330
334
  - `LifecycleHooks` lets apps define install/update/enable/disable/uninstall hooks.
@@ -569,10 +573,15 @@ Templates:
569
573
  - `dashboard`
570
574
  - `palette-app`
571
575
  - `next`
572
- - `agent-tool`
576
+ - `agent-tool` (`agent-ready` is an alias)
573
577
  - `external-service`
574
578
  - `database`
575
579
  - `frontend-only`
580
+ - `provider-app` — publishes OS-broker services for other apps
581
+ - `consumer-app` — consumes another app's services/events
582
+
583
+ `pltt init` clones the official template repository and falls back to the
584
+ bundled copy under `template-fallback/` when git or the network is unavailable.
576
585
 
577
586
  ### Palette App Router
578
587
 
@@ -683,6 +692,13 @@ For developer sandboxes where manual approval should not block OS testing, run t
683
692
  `pltt preview --env staging` is also supported as a developer-friendly alias
684
693
  for the same hosted preview flow.
685
694
 
695
+ `pltt dev --sandbox --watch` keeps the preview alive after publishing: the CLI
696
+ rebuilds the frontend entry on every save and pushes the new bundle onto the
697
+ existing preview record, so the hosted OS shows the change without a second
698
+ publish or review. Only frontend changes are live-pushed; backend changes need
699
+ a re-run. `--ttl-hours <n>` overrides the 24-hour preview TTL and `--json`
700
+ emits the publish record instead of the human log.
701
+
686
702
  `pltt dev --platform` runs the full Docker `platform-dev` image for internal platform parity testing. App developers should not need it. It pulls `ghcr.io/palette-lab/platform-dev:latest` and mounts your plugin at `/plugins/<your-id>`.
687
703
 
688
704
  Environment variables:
@@ -733,7 +749,7 @@ install-scoped values or labels/help text:
733
749
  "STRIPE_SECRET": { "scope": "plugin", "required": true },
734
750
  "DEBUG_PROBE_URL": { "scope": "dev", "required": false }
735
751
  },
736
- "platform_services": ["llm", "redis", "storage", "vector", "web"]
752
+ "platform_services": ["llm", "media", "redis", "storage", "vector", "web"]
737
753
  }
738
754
  ```
739
755
 
@@ -827,9 +843,16 @@ Save a Palette sandbox or production environment URL plus token in `~/.palette/c
827
843
 
828
844
  ```bash
829
845
  pltt login --env staging --url https://sandbox.pltt.ai --token <publish-token>
846
+ pltt login --env production --url https://palette.example.com --token <token> --no-default
830
847
  pltt dev --sandbox --env staging
831
848
  ```
832
849
 
850
+ The saved environment becomes the default for `--env`-less commands unless
851
+ `--no-default` is passed. `--url` and `--token` fall back to
852
+ `PALETTE_PLATFORM_URL` / `PALETTE_<ENV>_URL` and `PALETTE_PUBLISH_TOKEN` /
853
+ `PALETTE_<ENV>_TOKEN` (`PALETTE_PROD_TOKEN` for `production`). `--json` prints
854
+ the saved record.
855
+
833
856
  ### `pltt version`
834
857
 
835
858
  Show the installed `pltt` CLI version.
@@ -866,7 +889,13 @@ Check local tooling and common setup problems.
866
889
  pltt doctor
867
890
  ```
868
891
 
869
- Checks include Node version, port availability, manifest validity, entry files, and frontend bundling.
892
+ Checks include Node version, port availability, manifest validity, entry files,
893
+ and frontend bundling. It also reports every declared platform service with the
894
+ mode `pltt dev` will run it in (live via your own key, or stubbed), names the
895
+ available set when an app declares none, and warns when a manifest declares a
896
+ permission that gates nothing today (`agents:*`, `routines:*`, `resources:*`) —
897
+ those stay valid so published manifests keep working, but a reviewer reading
898
+ "agents:write" on an app should not believe it can write agents.
870
899
 
871
900
  Docker is intentionally skipped by default:
872
901
 
@@ -920,9 +949,11 @@ pltt publish --env production
920
949
  pltt publish --env production -y
921
950
  pltt publish --env staging --json
922
951
  pltt publish --env staging --ttl-hours 24
952
+ pltt publish --env staging --preview
923
953
  ```
924
954
 
925
- Publishing first runs the same contract checks as `pltt test`. Preview publishes skip the release semver bump check, while release publishes still require a version newer than the last release. If preflight passes, it bundles frontend/backend artifacts, uploads them, creates a review record, and prints review/preview URLs when the platform returns them.
955
+ `--preview` (or `--publish-type preview`) publishes a reviewable preview
956
+ instead of a release; `--release` is the default. Publishing first runs the same contract checks as `pltt test`. Preview publishes skip the release semver bump check, while release publishes still require a version newer than the last release. If preflight passes, it bundles frontend/backend artifacts, uploads them, creates a review record, and prints review/preview URLs when the platform returns them.
926
957
 
927
958
  `--ttl-hours` sets an expiration on the preview URL. It is mainly used by `pltt dev --sandbox`, which defaults previews to 24 hours.
928
959
 
@@ -952,6 +983,60 @@ pltt logs --json
952
983
 
953
984
  If no plugin ID is provided, the CLI uses the current `palette-plugin.json` or `.palette/last-publish.json`.
954
985
 
986
+ ### `pltt open`
987
+
988
+ Open the preview URL from the last publish in your default browser.
989
+
990
+ ```bash
991
+ pltt dev --sandbox --env staging
992
+ pltt open
993
+ ```
994
+
995
+ Reads `.palette/last-publish.json`; fails with a hint when no publish has run
996
+ yet or the last publish returned no preview URL.
997
+
998
+ ### `pltt platform`
999
+
1000
+ The services the **platform** lends your app through `ctx.*`. Declaring one is
1001
+ what replaces shipping an API key: the platform's own credential is used,
1002
+ metered per organisation, and the installing org has nothing to paste in.
1003
+
1004
+ ```bash
1005
+ pltt platform list # every ctx.* service, a snippet, and its pltt dev mode
1006
+ pltt platform list --json
1007
+ pltt platform enable llm media # writes platform_services into palette-plugin.json
1008
+ pltt platform disable web
1009
+ ```
1010
+
1011
+ | Service | Replaces | `ctx.*` |
1012
+ |---|---|---|
1013
+ | `llm` | `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` | chat, streaming, embeddings, image generation |
1014
+ | `media` | `FAL_KEY` | fal.ai — image, video, speech, transcription, any model fal publishes |
1015
+ | `web` | `TAVILY_API_KEY` / `SERPAPI_KEY` | search + SSRF-guarded page reader |
1016
+ | `storage` | an S3/GCS bucket | per-app, per-org objects with resumable uploads |
1017
+ | `vector` | a Pinecone/Qdrant account | namespaced vector search |
1018
+ | `redis` | `REDIS_URL` | KV, lists, sets, sorted sets, counters, locks |
1019
+
1020
+ `list` also prints the **permission-gated** clients — `ctx.tasks`,
1021
+ `ctx.data_rooms`, `ctx.members`, `ctx.talk` — and whether your manifest has
1022
+ granted them, so "what can `ctx` do, and what do I declare to get it" is one
1023
+ answer.
1024
+
1025
+ Notes:
1026
+
1027
+ - `enable` preserves the object form, so per-service `billing` / `required`
1028
+ settings you already wrote are kept.
1029
+ - `llm` and `media` share **one** monthly wallet per (app, organisation) and
1030
+ both fail closed. `ctx.llm.spend()` reports what is left.
1031
+ - Under `pltt dev` there is no platform: `llm` and `media` use your own
1032
+ `OPENAI_API_KEY` / `FAL_KEY` when `.env.local` has them and return
1033
+ deterministic stubs when it does not. `pltt doctor` prints which mode each
1034
+ one is in.
1035
+
1036
+ `pltt platform` is about what the *platform* provides. For app-to-app contracts
1037
+ see `pltt services`; for third-party accounts the *user* connected see
1038
+ `pltt connections`.
1039
+
955
1040
  ### `pltt connections`
956
1041
 
957
1042
  Use the third-party services the OS already holds — Gmail, Drive, Calendar,
@@ -1016,7 +1101,7 @@ pltt services pull --env staging
1016
1101
  pltt services scaffold approvalChain.get
1017
1102
  pltt capabilities add creative.poster.generate --method poster.generate --risk write --effects artifact.create --idempotent
1018
1103
  pltt capabilities list
1019
- pltt test --agent
1104
+ pltt test
1020
1105
  ```
1021
1106
 
1022
1107
  Subcommands:
@@ -1065,9 +1150,31 @@ Provider methods can use inline JSON Schema objects or schema file paths in
1065
1150
  `schema` or `payload_schema`. The CLI scaffolds schema files by default because
1066
1151
  they are easier to review and reuse for generated clients.
1067
1152
 
1153
+ ### `pltt capabilities`
1154
+
1155
+ Manage agent-callable capabilities: provider methods that Palette agents may
1156
+ invoke or schedule on the user's behalf. `pltt capability` is an alias.
1157
+
1158
+ ```bash
1159
+ pltt capabilities list [--json]
1160
+ pltt capabilities inspect creative.poster.generate
1161
+ pltt capabilities add creative.poster.generate --method poster.generate --risk write --effects artifact.create --idempotent
1162
+ pltt capabilities add reports.export --risk read
1163
+ pltt capabilities add mail.send --risk write --no-scheduling
1164
+ ```
1165
+
1166
+ Subcommands:
1167
+
1168
+ - `list`: agent-exposable methods declared in `provides.services`, with their `capability_id`, risk, effects, and scheduling flags.
1169
+ - `inspect <capability_id>`: the full manifest entry for one capability.
1170
+ - `add <domain.resource.action>`: scaffolds a provider method (schemas + Python handler stub, like `pltt services scaffold`) and marks it agent-exposable. `--method <name>` overrides the derived method name, `--risk read|write|destructive|controlled` (default `read`), `--effects a,b` lists side effects. `write`/`destructive` capabilities must pass `--idempotent` to be schedulable, or `--no-scheduling` for interactive-only actions.
1171
+
1172
+ `pltt test` verifies every agent capability has a stable `capability_id` and a
1173
+ matching `@capability(...)` / `service(..., agent_exposable=True)` handler.
1174
+
1068
1175
  ## Global Flags
1069
1176
 
1070
- - `--json` emits machine-readable output for `package`, `publish`, `status`, `logs`, `test`, `update`, and `version`.
1177
+ - `--json` emits machine-readable output for `package`, `publish`, `status`, `logs`, `test`, `update`, `version`, `login`, `dev --sandbox`, `platform list`, `services list`, and `capabilities`.
1071
1178
  - `-v, --version` prints the installed `pltt` CLI version.
1072
1179
  - `--env <name>` selects a configured publish/status/logs environment.
1073
1180
  - `-y, --yes` skips production publish confirmation.
@@ -9,9 +9,14 @@ from palette_sdk.members import OrganizationMembersClient
9
9
  from palette_sdk.notifications import NotificationRecipient, NotificationsClient
10
10
  from palette_sdk.organization import OrganizationInfo
11
11
  from palette_sdk.talk import TalkClient
12
+ from palette_sdk.tasks import TasksClient
12
13
  from palette_sdk.platform_services import (
14
+ LocalLLMService,
15
+ LocalMediaService,
13
16
  LocalRedisService,
14
17
  LocalVectorService,
18
+ LocalWebService,
19
+ MediaStillRunning,
15
20
  PlatformServiceUnavailable,
16
21
  UnavailablePlatformService,
17
22
  )
@@ -81,8 +86,13 @@ __all__ = [
81
86
  "NotificationsClient",
82
87
  "NotificationRecipient",
83
88
  "TalkClient",
89
+ "TasksClient",
90
+ "LocalLLMService",
91
+ "LocalMediaService",
84
92
  "LocalRedisService",
85
93
  "LocalVectorService",
94
+ "LocalWebService",
95
+ "MediaStillRunning",
86
96
  "PlatformServiceUnavailable",
87
97
  "UnavailablePlatformService",
88
98
  "OrgRepository",
@@ -138,4 +148,4 @@ __all__ = [
138
148
  "LocalStorageService",
139
149
  ]
140
150
 
141
- __version__ = "0.1.12"
151
+ __version__ = "0.1.15"
@@ -19,7 +19,7 @@ class DataRoomsClient:
19
19
  def _require_service(self) -> Any:
20
20
  if self._service is None:
21
21
  raise RuntimeError(
22
- "Data Room service is not available in this runtime. "
22
+ "Drive service is not available in this runtime. "
23
23
  "Run inside Palette OS/hosted sandbox or inject a fake service in tests."
24
24
  )
25
25
  return self._service
@@ -36,7 +36,7 @@ class DataRoomsClient:
36
36
  async def require_room_by_name(self, name: str, *, case_sensitive: bool = False) -> dict[str, Any]:
37
37
  room = await self.find_room_by_name(name, case_sensitive=case_sensitive)
38
38
  if room is None:
39
- raise LookupError(f"Data Room not found: {name}")
39
+ raise LookupError(f"Drive not found: {name}")
40
40
  return room
41
41
 
42
42
  async def ensure_room(self, name: str, description: str | None = None) -> dict[str, Any]:
@@ -39,7 +39,7 @@ class PluginBase(DeclarativeBase):
39
39
 
40
40
 
41
41
  class OrgScopedTable(PluginBase):
42
- """Base for all per-organization plugin tables.
42
+ """Base for all per-install plugin tables.
43
43
 
44
44
  Inheriting from this gives you:
45
45
  - An `organization_id BIGINT NOT NULL` column with an index.
@@ -49,6 +49,9 @@ class OrgScopedTable(PluginBase):
49
49
  Never write `WHERE organization_id = ?` in your queries — the database
50
50
  will filter rows for you based on the session variable set by the
51
51
  platform at request time.
52
+
53
+ The value is the app's effective data partition: a member tenant for
54
+ personal scope, or the real org id for organization scope.
52
55
  """
53
56
 
54
57
  __abstract__ = True
@@ -1,10 +1,16 @@
1
1
  """Row-level security helpers for plugin migrations.
2
2
 
3
- Every plugin table that holds org data must call `ensure_org_rls(op, table)`
3
+ Every plugin table that holds app data must call `ensure_org_rls(op, table)`
4
4
  in the migration that creates it. This enables RLS and installs the standard
5
5
  policy, which filters rows by the `app.current_org_id` session variable set
6
6
  by the platform at request time.
7
7
 
8
+ Every member installs an app individually. `manifest.data_scope` selects the
9
+ partition stored in `app.current_org_id`: `personal` uses that member's tenant
10
+ id; `organization` uses the real org id so installed members share one dataset.
11
+ `manifest.shared_tables` is only for global static lookup data shared across
12
+ all organisations, never for organisation business data.
13
+
8
14
  The `palette build` CLI lints migrations and will reject any that:
9
15
  - create an org table without a matching `ensure_org_rls` call,
10
16
  - contain `DROP POLICY` or `DISABLE ROW LEVEL SECURITY`,
@@ -321,6 +321,7 @@ class PluginManifest(BaseModel):
321
321
  id: str
322
322
  name: str
323
323
  version: str = "1.0.0"
324
+ data_scope: Literal["personal", "organization"] = "personal"
324
325
  developer: str = ""
325
326
  category: str = "Productivity"
326
327
  tagline: str = ""
@@ -344,7 +345,7 @@ class PluginManifest(BaseModel):
344
345
  requires: RequiresSpec | None = None
345
346
  consumes: ConsumesSpec | None = None
346
347
  mcp: McpSpec | None = None
347
- platform_services: list[Literal["llm", "redis", "storage", "vector", "web"]] | dict[str, PlatformServiceSpec] = Field(default_factory=list)
348
+ platform_services: list[Literal["llm", "media", "redis", "storage", "vector", "web"]] | dict[str, PlatformServiceSpec] = Field(default_factory=list)
348
349
  rating: float = 0.0
349
350
  reviews: int = 0
350
351
  featured: bool = False
@@ -418,6 +418,7 @@ class LocalLLMService:
418
418
  system: str | None = None,
419
419
  max_tokens: int = 1024,
420
420
  temperature: float = 0.2,
421
+ **kwargs: Any,
421
422
  ) -> dict[str, Any]:
422
423
  if not self.live:
423
424
  return self._stub(messages)
@@ -425,7 +426,7 @@ class LocalLLMService:
425
426
 
426
427
  payload = ([{"role": "system", "content": system}] if system else []) + list(messages)
427
428
  reply = await AsyncOpenAI(api_key=self.api_key).chat.completions.create(
428
- model=model or self.model, messages=payload, max_completion_tokens=max_tokens
429
+ model=model or self.model, messages=payload, max_completion_tokens=max_tokens, **kwargs
429
430
  )
430
431
  usage = reply.usage
431
432
  return {
@@ -444,11 +445,15 @@ class LocalLLMService:
444
445
 
445
446
  system = kwargs.get("system")
446
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
+ }
447
451
  stream = await AsyncOpenAI(api_key=self.api_key).chat.completions.create(
448
452
  model=kwargs.get("model") or self.model,
449
453
  messages=payload,
450
454
  max_completion_tokens=kwargs.get("max_tokens", 1024),
451
455
  stream=True,
456
+ **passthrough,
452
457
  )
453
458
  async for chunk in stream:
454
459
  delta = chunk.choices[0].delta if chunk.choices else None
@@ -467,9 +472,18 @@ class LocalLLMService:
467
472
  )
468
473
  return [item.embedding for item in reply.data]
469
474
 
470
- async def image(self, prompt: str, *, aspect_ratio: str = "1:1") -> tuple[bytes, str]:
475
+ async def image(self, prompt: str, *, aspect_ratio: str = "1:1", **kwargs: Any) -> tuple[bytes, str]:
471
476
  raise NotImplementedError("ctx.llm.image runs on the platform only — use pltt dev --sandbox")
472
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
+
473
487
 
474
488
  class LocalWebService:
475
489
  """`ctx.web` for pltt dev — keyless DuckDuckGo search plus a plain fetch."""
@@ -497,3 +511,267 @@ class LocalWebService:
497
511
  response = await client.get(url)
498
512
  response.raise_for_status()
499
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}