callables 0.3.0__tar.gz → 0.4.0__tar.gz

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 (36) hide show
  1. {callables-0.3.0 → callables-0.4.0}/PKG-INFO +2 -2
  2. {callables-0.3.0 → callables-0.4.0}/README.md +1 -1
  3. {callables-0.3.0 → callables-0.4.0}/callables/GUIDE.md +37 -6
  4. {callables-0.3.0 → callables-0.4.0}/callables/__init__.py +3 -2
  5. {callables-0.3.0 → callables-0.4.0}/callables/checks.py +5 -0
  6. {callables-0.3.0 → callables-0.4.0}/callables/cli.py +26 -0
  7. callables-0.4.0/callables/connections.py +261 -0
  8. {callables-0.3.0 → callables-0.4.0}/callables/decorator.py +24 -2
  9. callables-0.4.0/callables/envfile.py +56 -0
  10. {callables-0.3.0 → callables-0.4.0}/callables/manifest.py +15 -1
  11. {callables-0.3.0 → callables-0.4.0}/callables/project.py +6 -4
  12. {callables-0.3.0 → callables-0.4.0}/callables.egg-info/PKG-INFO +2 -2
  13. {callables-0.3.0 → callables-0.4.0}/callables.egg-info/SOURCES.txt +4 -0
  14. callables-0.4.0/tests/test_connections.py +167 -0
  15. callables-0.4.0/tests/test_envfile.py +113 -0
  16. {callables-0.3.0 → callables-0.4.0}/tests/test_project.py +12 -0
  17. {callables-0.3.0 → callables-0.4.0}/LICENSE +0 -0
  18. {callables-0.3.0 → callables-0.4.0}/callables/__main__.py +0 -0
  19. {callables-0.3.0 → callables-0.4.0}/callables/commands.py +0 -0
  20. {callables-0.3.0 → callables-0.4.0}/callables/files.py +0 -0
  21. {callables-0.3.0 → callables-0.4.0}/callables/init.py +0 -0
  22. {callables-0.3.0 → callables-0.4.0}/callables/py.typed +0 -0
  23. {callables-0.3.0 → callables-0.4.0}/callables/runtime.py +0 -0
  24. {callables-0.3.0 → callables-0.4.0}/callables/schema.py +0 -0
  25. {callables-0.3.0 → callables-0.4.0}/callables.egg-info/dependency_links.txt +0 -0
  26. {callables-0.3.0 → callables-0.4.0}/callables.egg-info/entry_points.txt +0 -0
  27. {callables-0.3.0 → callables-0.4.0}/callables.egg-info/requires.txt +0 -0
  28. {callables-0.3.0 → callables-0.4.0}/callables.egg-info/top_level.txt +0 -0
  29. {callables-0.3.0 → callables-0.4.0}/pyproject.toml +0 -0
  30. {callables-0.3.0 → callables-0.4.0}/setup.cfg +0 -0
  31. {callables-0.3.0 → callables-0.4.0}/tests/test_agent_tools.py +0 -0
  32. {callables-0.3.0 → callables-0.4.0}/tests/test_command.py +0 -0
  33. {callables-0.3.0 → callables-0.4.0}/tests/test_files.py +0 -0
  34. {callables-0.3.0 → callables-0.4.0}/tests/test_groups.py +0 -0
  35. {callables-0.3.0 → callables-0.4.0}/tests/test_next.py +0 -0
  36. {callables-0.3.0 → callables-0.4.0}/tests/test_sdk.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: callables
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Decorate Python functions and push them to Callables: forms, schedules and run history for your team.
5
5
  License-Expression: Apache-2.0
6
6
  Project-URL: Homepage, https://callables.app
@@ -42,7 +42,7 @@ def weekly_report(region: Literal["NA", "EMEA", "APAC"] = "NA", days: int = 7) -
42
42
  - **Results** are shown by return type: `str` as Markdown, `list[dict]` (or a DataFrame) as a table with CSV download, `dict`/Pydantic model as a key-value list, `None` as "done".
43
43
  - **Files in**: a `File` parameter becomes an upload field. Your function gets a `File` with `.path`, `.name`, `.read_text()`, `.read_bytes()` and `.open()`. Limit the picker with `Annotated[File, accept(".csv", ".xlsx")]`.
44
44
  - **Files out**: return a `File` (or a `list[File]`) and people get download buttons. To hand back files alongside another result, call `save_file(path_or_bytes, name=...)`. Files are kept for 24 hours by default.
45
- - **Secrets** you list are injected as environment variables at run time (`os.environ["SALES_API_TOKEN"]`); set their values in the Callables console.
45
+ - **Secrets** you list are injected as environment variables at run time (`os.environ["SALES_API_TOKEN"]`); set their values in the Callables console. Locally, `call local` and `call <group> <action>` load the project's `.env` instead (variables already set in your shell win).
46
46
  - **Schedules** are cron expressions, in UTC.
47
47
 
48
48
  ```python
@@ -24,7 +24,7 @@ def weekly_report(region: Literal["NA", "EMEA", "APAC"] = "NA", days: int = 7) -
24
24
  - **Results** are shown by return type: `str` as Markdown, `list[dict]` (or a DataFrame) as a table with CSV download, `dict`/Pydantic model as a key-value list, `None` as "done".
25
25
  - **Files in**: a `File` parameter becomes an upload field. Your function gets a `File` with `.path`, `.name`, `.read_text()`, `.read_bytes()` and `.open()`. Limit the picker with `Annotated[File, accept(".csv", ".xlsx")]`.
26
26
  - **Files out**: return a `File` (or a `list[File]`) and people get download buttons. To hand back files alongside another result, call `save_file(path_or_bytes, name=...)`. Files are kept for 24 hours by default.
27
- - **Secrets** you list are injected as environment variables at run time (`os.environ["SALES_API_TOKEN"]`); set their values in the Callables console.
27
+ - **Secrets** you list are injected as environment variables at run time (`os.environ["SALES_API_TOKEN"]`); set their values in the Callables console. Locally, `call local` and `call <group> <action>` load the project's `.env` instead (variables already set in your shell win).
28
28
  - **Schedules** are cron expressions, in UTC.
29
29
 
30
30
  ```python
@@ -2,7 +2,7 @@
2
2
 
3
3
  Callables turns Python functions into web forms that non-technical teammates run. A developer decorates a function with `@deploy` and pushes the repo. The platform builds it and shows each function as a form, generated from the type hints, with run history. People can also schedule runs from the web app.
4
4
 
5
- This guide matches the installed SDK version. The full docs, including setup, secrets, schedules, sharing and limits, are at https://callables.app/docs. Every page is also served as Markdown: add `.md` to its URL (for example https://callables.app/docs/inputs.md), or read https://callables.app/llms.txt for an index.
5
+ This guide matches the installed SDK version. The full docs, including setup, secrets, connections, schedules, sharing and limits, are at https://callables.app/docs. Every page is also served as Markdown: add `.md` to its URL (for example https://callables.app/docs/inputs.md), or read https://callables.app/llms.txt for an index.
6
6
 
7
7
  The person running an automation can't see the code, a traceback or a terminal. Everything they see comes from the decorator, the docstring, the parameter names and types, and the return value. Write for them.
8
8
 
@@ -10,7 +10,7 @@ The person running an automation can't see the code, a traceback or a terminal.
10
10
 
11
11
  1. Write or change a function decorated with `@deploy`.
12
12
  2. `call check` (or `call check --json`) lists every problem a deploy would hit, with a fix for each. Exit code 1 means the deploy would fail.
13
- 3. `call local <name> -i key=value --json` runs the function on this machine, with the same input validation as the platform.
13
+ 3. `call local <name> -i key=value --json` runs the function on this machine, with the same input validation as the platform. It loads the project's `.env` first, so it finds the secrets the platform would give it.
14
14
  4. Push. The platform builds and deploys on push.
15
15
 
16
16
  Run `call check` before every push. If any module fails to import, nothing is published.
@@ -44,7 +44,8 @@ def closed_deals(region: Literal["NA", "EMEA", "APAC"] = "NA", since: date | Non
44
44
  - `name`: the function's identity on the platform. It defaults to the function name. **Renaming it creates a new automation**, and the old one's history and schedules stay behind. Pass `name="..."` to keep the identity if you rename the Python function.
45
45
  - `title`: the card and page heading. It defaults to the name, turned into a sentence.
46
46
  - `description`: the first paragraph of the docstring is the default. Write one plain-language sentence about what it does for the person.
47
- - `secrets`: names of environment variables, which builders set in the web app. Read them with `os.environ["CRM_TOKEN"]`. Never hard-code credentials and never take them as inputs. A declared secret that nobody has set doesn't block the run: the variable is simply missing, and builders see a "missing secrets" warning. For an optional secret, declare it and read it with `os.environ.get(...)`. Each secret is a single value, so a key file such as a `.pem` goes in as the file's contents, and the code reads it from the variable.
47
+ - `secrets`: names of environment variables, which builders set in the web app. Read them with `os.environ["CRM_TOKEN"]`. Never hard-code credentials and never take them as inputs. A declared secret that nobody has set doesn't block the run: the variable is simply missing, and builders see a "missing secrets" warning. For an optional secret, declare it and read it with `os.environ.get(...)`. Locally, `call local` and `call <group> <action>` load `.env` from the build folder, then the folder you run from, without overriding variables already set in your shell. The platform never reads `.env`. Each secret is a single value, so a key file such as a `.pem` goes in as the file's contents, and the code reads it from the variable.
48
+ - `connections`: `Connection` objects for accounts each person connects themselves, such as their Gmail. See Connections below.
48
49
  - `timeout`: in seconds. The default is 300 and the maximum is 900.
49
50
  - `schedule`: a cron expression in UTC, for schedules owned by the code. Only use it when the user asks for one. Anyone can add a schedule in the web app, so you usually don't need it.
50
51
 
@@ -98,7 +99,7 @@ def render(slug: str, open_browser: bool = False) -> str:
98
99
  ```
99
100
 
100
101
  - They run as `call audits render --slug x` and with `call local`, with flags from the type hints, like any action. `call check` lists them as "(local only)".
101
- - They're never deployed: the platform doesn't see them and nobody can run them from the web app. `@command` takes `name`, `title`, `description` and `next`, but no `secrets`, `schedule` or `timeout`, because it runs in your own environment (read secrets from `.env`). A deployed action's `next=` can't point at one.
102
+ - They're never deployed: the platform doesn't see them and nobody can run them from the web app. `@command` takes `name`, `title`, `description` and `next`, but no `secrets`, `schedule` or `timeout`, because it runs in your own environment (`call` loads the project's `.env` for it). A deployed action's `next=` can't point at one.
102
103
  - Their module is still imported when the platform builds, so keep imports that only work locally inside the function.
103
104
  - Return the result instead of printing it. The CLI prints what you return (a table as aligned columns in a terminal, JSON when piped), so printing it as well shows it twice. Keep prints for progress.
104
105
  - To deploy one later, change `@command` to `@deploy`. It keeps its name.
@@ -148,6 +149,33 @@ def search(query: str) -> list[dict]:
148
149
  - People only see next actions they're allowed to run.
149
150
  - If a result tells people to run another step ("Next: upload this to step 2"), use `next=` instead of writing it in the text. Text isn't clickable, and `next=` carries the file or row values along.
150
151
 
152
+ ## Connections: act on the person's own account
153
+
154
+ Use a connection when each person should use their own account (their Gmail, calendar, Slack, GitHub). Use secrets when every run should share one account.
155
+
156
+ ```python
157
+ from callables import Connection, deploy
158
+
159
+ google = Connection("google", provider="google", scopes=["gmail.modify", "calendar.readonly"])
160
+
161
+
162
+ @deploy(title="Triage my inbox", connections=[google])
163
+ def triage_inbox() -> str:
164
+ headers = {"Authorization": f"Bearer {google.token}"}
165
+ ...
166
+ ```
167
+
168
+ - The developer brings the OAuth app. Create it in the service's console with the redirect URI `https://callables.app/connections/callback`, then set `<NAME>_CLIENT_ID` and `<NAME>_CLIENT_SECRET` as project secrets (`GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` for a connection named `google`). Other secret names: `client_id_secret=`, `client_secret_secret=`. `call check` lists what each connection reads.
169
+ - Presets: `google`, `microsoft` (`tenant=` for a single-tenant app), `slack`, `github`, `notion`. Presets accept short scope names (`"gmail.modify"`) and handle the service's quirks, such as asking for offline access.
170
+ - Any other OAuth 2.0 service: pass `authorize_url`, `token_url` and `scopes` instead of `provider`. Options for services that differ: `authorize_params`, `token_endpoint_auth_method="client_secret_basic"`, `token_request_format="json"`, `scope_separator=","`, `scope_param`, `pkce=True`, `token_path`, `userinfo_url`, `account_field`, `revoke_url`, and `placeholders` for URLs that depend on the person (such as `{shop}`).
171
+ - During a run: `.token` (valid for the whole run), `.account`, `.scopes_granted`, `.extra`. A module-level object is safe because every run is its own process, for one person. The token is also in `<NAME>_ACCESS_TOKEN`. Read `.token` inside the function, never at module level, and never print it.
172
+ - Each person connects once per project, on the service's own consent screen, the first time they open a function that needs it. A run uses the connection of the person who started it, or of the person who made the schedule, never anyone else's. If they haven't connected, the run doesn't start.
173
+ - The connection's name is its identity. Renaming it makes everyone connect again. Use one connection per service per project with every scope the project needs.
174
+ - `Group(..., connections=[google])` declares a connection for every action in a group.
175
+ - Locally, put a token for your own account in `.env` as `<NAME>_ACCESS_TOKEN`. Builders try the real flow from the project page's Connections card.
176
+ - Ask for the narrowest scopes that work. Never take tokens, passwords or account emails as form inputs.
177
+ - Full reference: https://callables.app/docs/connections
178
+
151
179
  ## Inputs: type hints become the form
152
180
 
153
181
  | Type hint | Form field |
@@ -212,6 +240,7 @@ def clean_contacts(sheet: Annotated[File, accept(".csv")]) -> File:
212
240
  - **Python version:** taken from `.python-version` (e.g. `3.13`), else the newest version your `pyproject.toml` `requires-python` allows, else 3.12. Supported: 3.11 to 3.14.
213
241
  - **Python dependencies** come from `requirements.txt` at the repo root, or from `[project].dependencies` in `pyproject.toml`. **Don't list `callables`.** The platform installs its own matching copy.
214
242
  - **Automations in a subfolder:** by default the whole repo is built. To build only one folder, add `callables.toml` at the repo root containing `root = "automations"` (or `[tool.callables] root = "automations"` in `pyproject.toml`). Then only that folder goes into the image, and its own `requirements.txt`, `apt.txt` and `.python-version` are used. Code in it can't import from the rest of the repo. `call check`, `local` and `manifest` use the same folder when run from the repo root.
243
+ - **Several projects from one repo:** one repo can back several projects, one per folder. Set **Folder** when creating the project in the web app, or change it later on the project page, which redeploys (it takes priority over `root` in `callables.toml`), and each folder builds with its own `requirements.txt`, `apt.txt` and `.python-version`. A push rebuilds only the projects whose folder changed. Each project has its own secrets and counts toward the plan's project limit. Locally, pass `--root automations/email` to `call check`, `local` and `manifest`.
215
244
  - **Writable space:** your home directory (`~`), and `/tmp`, which is limited to 256 MB. Your code in `/app` is read-only. Every run starts fresh, so nothing persists between runs. Keep state in your own database or storage.
216
245
  - **Running downloaded binaries:** `/tmp` doesn't allow running programs, so a binary downloaded there fails with `Permission denied`. Put it under `~` and `chmod +x` it. Better still, install the tool with `apt.txt` (below).
217
246
  - Every module that imports `callables` and mentions `deploy` is imported at build time. Keep import-time code cheap and free of side effects: no network calls, and no reading secrets at module level. Read secrets inside the function.
@@ -238,6 +267,8 @@ You don't size anything. A run can use memory and CPU up to your organisation's
238
267
 
239
268
  If a run goes over the memory limit, it fails with an error that says so. Fix it by using less memory (process files in chunks, stream instead of loading everything, free large objects you're done with), or move to a bigger plan. Child processes count toward the same limit.
240
269
 
270
+ Each plan includes an amount of usage per billing period. On a trial or the Free plan, reaching it cancels queued and running runs, and new runs and schedules wait until the next period or until the workspace picks a plan. Paid plans keep running and are billed for the extra usage.
271
+
241
272
  ## Errors people will see
242
273
 
243
274
  Raise exceptions with messages written for the person running the automation. They see `ValueError: No deals found for EMEA since 2026-01-01`, so make it say what to change. For bad input, raise `ValueError` with a message about that field.
@@ -245,8 +276,8 @@ Raise exceptions with messages written for the person running the automation. Th
245
276
  ## Commands
246
277
 
247
278
  - `call check [--json]`: problems a deploy would hit, with fixes. Exit code 1 on errors.
248
- - `call <group> <action> [--flags]` (or `call <function> [--flags]`): run a function like a CLI command. Each input is a flag (`days` becomes `--days`, a bool becomes `--dry-run/--no-dry-run`, a list takes several values). Add `--help` to see them.
249
- - `call local <name> [-i key=value ...] [--json]`: run a function on this machine. Values are parsed as JSON when possible, and `@path` passes a file. `--json` prints one JSON object on stdout (`ok`, `value`, `files`, `error`, `field_errors`), and the function's own prints go to stderr.
279
+ - `call <group> <action> [--flags]` (or `call <function> [--flags]`): run a function like a CLI command. Each input is a flag (`days` becomes `--days`, a bool becomes `--dry-run/--no-dry-run`, a list takes several values). Add `--help` to see them. Loads the project's `.env` first, like `call local`.
280
+ - `call local <name> [-i key=value ...] [--json]`: run a function on this machine, after loading the project's `.env` (variables already set win). Values are parsed as JSON when possible, and `@path` passes a file. `--json` prints one JSON object on stdout (`ok`, `value`, `files`, `error`, `field_errors`), and the function's own prints go to stderr.
250
281
  - `call manifest`: the full JSON the platform reads, including each input's JSON Schema. Local `@command`s are left out.
251
282
  - `call docs`: prints this guide.
252
283
  - `call init`: an example automation plus agent instructions (`.claude/skills/callables/SKILL.md` and an `AGENTS.md` section). Run it again after upgrading the SDK to refresh the instructions.
@@ -1,6 +1,7 @@
1
1
  """Callables SDK: mark functions with @deploy and push the repo; the platform does the rest."""
2
+ from callables.connections import Connection
2
3
  from callables.decorator import DeployedFunction, Group, Next, command, deploy, registry
3
4
  from callables.files import File, accept, save_file
4
5
 
5
- __version__ = "0.3.0"
6
- __all__ = ["deploy", "command", "Group", "Next", "DeployedFunction", "registry", "File", "accept", "save_file", "__version__"]
6
+ __version__ = "0.4.0"
7
+ __all__ = ["deploy", "command", "Group", "Next", "Connection", "DeployedFunction", "registry", "File", "accept", "save_file", "__version__"]
@@ -112,5 +112,10 @@ def check_project(root: Path) -> dict[str, Any]:
112
112
  "local_only": bool(f.get("local_only"))}
113
113
  for f in manifest["functions"]
114
114
  ],
115
+ "connections": [
116
+ {"name": c["name"], "title": c["title"], "scopes": c["scopes"],
117
+ "secrets": [c["client_id_secret"], c["client_secret_secret"]], "env_var": c["env_var"]}
118
+ for c in manifest.get("connections", [])
119
+ ],
115
120
  "issues": issues,
116
121
  }
@@ -112,6 +112,11 @@ def _check(root: Path, as_json: bool) -> int:
112
112
  print(f" {fn['name']} ({', '.join(fn['inputs']) or 'no inputs'}) -> {fn['output_kind']}{local}")
113
113
  if report["functions"]:
114
114
  print()
115
+ for conn in report.get("connections", []):
116
+ print(f" connection {conn['name']} ({conn['title']}): set project secrets {' and '.join(conn['secrets'])}; "
117
+ f"locally, put a token in .env as {conn['env_var']}")
118
+ if report.get("connections"):
119
+ print()
115
120
  for issue in report["issues"]:
116
121
  where = f"[{issue['function']}] " if issue.get("function") else ""
117
122
  print(f"{issue['level']}: {where}{issue['message']}")
@@ -272,9 +277,30 @@ def _follow(root: Path, fn: dict, functions: list[dict], rows: list[dict], files
272
277
  return _local(root, target["name"], inputs, as_json=False, follow=True)
273
278
 
274
279
 
280
+ _env_loaded = False
281
+
282
+
283
+ def _load_env(root: Path) -> None:
284
+ """The project's .env (the build folder's, then the current folder's), once per process. Never on the platform:
285
+ `call run` doesn't come through here."""
286
+ global _env_loaded
287
+ if _env_loaded:
288
+ return
289
+ _env_loaded = True
290
+ from callables.envfile import load
291
+
292
+ files, added = load(root, Path.cwd())
293
+ if files:
294
+ cwd = Path.cwd().resolve()
295
+ shown = ", ".join(str(p.relative_to(cwd)) if p.is_relative_to(cwd) else str(p) for p in files)
296
+ print(f"Loaded {len(added)} variable{'s' if len(added) != 1 else ''} from {shown}", file=sys.stderr)
297
+
298
+
275
299
  def _local(root: Path, name: str, inputs: dict, as_json: bool, follow: bool = False) -> int:
276
300
  from pydantic import ValidationError
277
301
 
302
+ _load_env(root)
303
+
278
304
  from callables.decorator import registry
279
305
  from callables.files import output_dir, saved_files
280
306
  from callables.manifest import build_manifest
@@ -0,0 +1,261 @@
1
+ """OAuth connections: each person running a function connects their own account (their Gmail, their Slack), and every
2
+ run they start gets a fresh access token for it. The developer brings the OAuth app; the platform signs people in,
3
+ stores and refreshes their tokens, and injects the token into each run.
4
+
5
+ google = Connection("google", provider="google", scopes=["gmail.modify"])
6
+
7
+ @deploy(connections=[google])
8
+ def triage_inbox() -> str:
9
+ token = google.token
10
+ """
11
+ import json
12
+ import os
13
+ import re
14
+ from typing import Any
15
+
16
+ NAME = re.compile(r"^[a-z][a-z0-9_]*$")
17
+ PLACEHOLDER = re.compile(r"\{([a-z][a-z0-9_]*)\}")
18
+ AUTH_METHODS = ("client_secret_post", "client_secret_basic")
19
+ # The run's connection details (account, scopes, extra) as JSON, keyed by connection name; tokens are separate
20
+ CONNECTIONS_ENV = "CALLABLES_CONNECTIONS"
21
+
22
+ GOOGLE_SCOPE_BASE = "https://www.googleapis.com/auth/"
23
+ GOOGLE_PLAIN_SCOPES = {"openid", "email", "profile"}
24
+
25
+ # Each service's sign-in details. Anything here can be overridden on the Connection.
26
+ PRESETS: dict[str, dict[str, Any]] = {
27
+ "google": {
28
+ "title": "Google",
29
+ "authorize_url": "https://accounts.google.com/o/oauth2/v2/auth",
30
+ "token_url": "https://oauth2.googleapis.com/token",
31
+ "revoke_url": "https://oauth2.googleapis.com/revoke",
32
+ "userinfo_url": "https://openidconnect.googleapis.com/v1/userinfo",
33
+ "account_field": "email",
34
+ # offline + consent: Google only hands out a refresh token when asked for both
35
+ "authorize_params": {"access_type": "offline", "prompt": "consent", "include_granted_scopes": "true"},
36
+ "default_scopes": ["openid", "email"],
37
+ "pkce": True,
38
+ },
39
+ "microsoft": {
40
+ "title": "Microsoft",
41
+ "authorize_url": "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize",
42
+ "token_url": "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token",
43
+ "userinfo_url": "https://graph.microsoft.com/v1.0/me",
44
+ "account_field": "userPrincipalName",
45
+ "default_scopes": ["offline_access", "User.Read"],
46
+ "pkce": True,
47
+ },
48
+ "slack": {
49
+ "title": "Slack",
50
+ "authorize_url": "https://slack.com/oauth/v2/authorize",
51
+ "token_url": "https://slack.com/api/oauth.v2.access",
52
+ "revoke_url": "https://slack.com/api/auth.revoke",
53
+ "userinfo_url": "https://slack.com/api/auth.test",
54
+ "account_field": "user",
55
+ # User tokens (acting as the person), not the app's bot token
56
+ "scope_param": "user_scope",
57
+ "scope_separator": ",",
58
+ "token_path": "authed_user.access_token",
59
+ },
60
+ "github": {
61
+ "title": "GitHub",
62
+ "authorize_url": "https://github.com/login/oauth/authorize",
63
+ "token_url": "https://github.com/login/oauth/access_token",
64
+ "userinfo_url": "https://api.github.com/user",
65
+ "account_field": "login",
66
+ },
67
+ "notion": {
68
+ "title": "Notion",
69
+ "authorize_url": "https://api.notion.com/v1/oauth/authorize",
70
+ "token_url": "https://api.notion.com/v1/oauth/token",
71
+ "authorize_params": {"owner": "user"},
72
+ "token_endpoint_auth_method": "client_secret_basic",
73
+ "token_request_format": "json",
74
+ "account_field": "workspace_name", # read from the token response: Notion has no userinfo for users
75
+ },
76
+ }
77
+
78
+
79
+ class ConnectionNotAvailable(RuntimeError):
80
+ pass
81
+
82
+
83
+ class Connection:
84
+ """An account each person connects themselves, through your own OAuth app.
85
+
86
+ Declare it at module level and pass it to `@deploy(connections=[...])`. During a run, `.token` is an access token
87
+ for the person who started it. The app's client ID and secret come from the project secrets
88
+ `<NAME>_CLIENT_ID` and `<NAME>_CLIENT_SECRET` (override with `client_id_secret` / `client_secret_secret`).
89
+ """
90
+
91
+ def __init__(
92
+ self,
93
+ name: str,
94
+ *,
95
+ provider: str | None = None,
96
+ scopes: list[str] | None = None,
97
+ title: str | None = None,
98
+ authorize_url: str | None = None,
99
+ token_url: str | None = None,
100
+ authorize_params: dict[str, str] | None = None,
101
+ token_endpoint_auth_method: str | None = None,
102
+ token_request_format: str | None = None,
103
+ scope_separator: str | None = None,
104
+ scope_param: str | None = None,
105
+ pkce: bool | None = None,
106
+ token_path: str | None = None,
107
+ userinfo_url: str | None = None,
108
+ account_field: str | None = None,
109
+ revoke_url: str | None = None,
110
+ placeholders: dict[str, str] | None = None,
111
+ tenant: str | None = None,
112
+ client_id_secret: str | None = None,
113
+ client_secret_secret: str | None = None,
114
+ ):
115
+ if not NAME.match(name):
116
+ raise ValueError(f"Connection name '{name}' must be lowercase letters, digits or '_', starting with a "
117
+ "letter (it names the GOOGLE_CLIENT_ID-style secrets)")
118
+ preset: dict[str, Any] = {}
119
+ if provider is not None:
120
+ if provider not in PRESETS:
121
+ raise ValueError(f"Connection '{name}': unknown provider '{provider}'. Presets: "
122
+ f"{', '.join(sorted(PRESETS))}. For another service, leave out provider and give "
123
+ "authorize_url and token_url")
124
+ preset = PRESETS[provider]
125
+ if tenant is not None and provider != "microsoft":
126
+ raise ValueError(f"Connection '{name}': tenant only applies to provider='microsoft'")
127
+
128
+ def pick(value: Any, key: str, default: Any = None) -> Any:
129
+ return value if value is not None else preset.get(key, default)
130
+
131
+ self.name = name
132
+ self.provider = provider
133
+ self.title = title or preset.get("title") or name.replace("_", " ").capitalize()
134
+ self.authorize_url = pick(authorize_url, "authorize_url")
135
+ self.token_url = pick(token_url, "token_url")
136
+ if not self.authorize_url or not self.token_url:
137
+ raise ValueError(f"Connection '{name}' needs a provider, or authorize_url and token_url")
138
+ if provider == "microsoft":
139
+ # Multi-tenant apps sign in through "common"; a single-tenant app needs its own tenant
140
+ self.authorize_url = self.authorize_url.replace("{tenant}", tenant or "common")
141
+ self.token_url = self.token_url.replace("{tenant}", tenant or "common")
142
+ self.authorize_params = {**preset.get("authorize_params", {}), **(authorize_params or {})}
143
+ self.token_endpoint_auth_method = pick(token_endpoint_auth_method, "token_endpoint_auth_method",
144
+ "client_secret_post")
145
+ if self.token_endpoint_auth_method not in AUTH_METHODS:
146
+ raise ValueError(f"Connection '{name}': token_endpoint_auth_method must be one of {', '.join(AUTH_METHODS)}")
147
+ self.token_request_format = pick(token_request_format, "token_request_format", "form")
148
+ if self.token_request_format not in ("form", "json"):
149
+ raise ValueError(f"Connection '{name}': token_request_format must be 'form' or 'json'")
150
+ self.scope_separator = pick(scope_separator, "scope_separator", " ")
151
+ self.scope_param = pick(scope_param, "scope_param", "scope")
152
+ self.pkce = bool(pick(pkce, "pkce", False))
153
+ self.token_path = pick(token_path, "token_path", "access_token")
154
+ self.userinfo_url = pick(userinfo_url, "userinfo_url")
155
+ self.account_field = pick(account_field, "account_field", "email")
156
+ self.revoke_url = pick(revoke_url, "revoke_url")
157
+ self.placeholders = dict(placeholders or {})
158
+ self.client_id_secret = client_id_secret or f"{name.upper()}_CLIENT_ID"
159
+ self.client_secret_secret = client_secret_secret or f"{name.upper()}_CLIENT_SECRET"
160
+
161
+ self.scopes = list(dict.fromkeys([*preset.get("default_scopes", []),
162
+ *(self._expand(s) for s in (scopes or []))]))
163
+
164
+ for label, url in (("authorize_url", self.authorize_url), ("token_url", self.token_url),
165
+ ("userinfo_url", self.userinfo_url), ("revoke_url", self.revoke_url)):
166
+ if url is None:
167
+ continue
168
+ if not url.startswith("https://"):
169
+ raise ValueError(f"Connection '{name}': {label} must start with https://")
170
+ unknown = [p for p in PLACEHOLDER.findall(url) if p not in self.placeholders]
171
+ if unknown:
172
+ raise ValueError(f"Connection '{name}': {label} uses {{{unknown[0]}}}, which isn't in placeholders. "
173
+ f"Add placeholders={{'{unknown[0]}': 'What to ask people'}}")
174
+ unused = [p for p in self.placeholders
175
+ if not any(f"{{{p}}}" in (u or "") for u in (self.authorize_url, self.token_url))]
176
+ if unused:
177
+ raise ValueError(f"Connection '{name}': placeholder '{unused[0]}' isn't used in authorize_url or token_url")
178
+ _register(self)
179
+
180
+ def _expand(self, scope: str) -> str:
181
+ """Presets take short scope names: Google's "gmail.modify" is its full https://www.googleapis.com/... URL."""
182
+ if self.provider == "google" and "://" not in scope and scope not in GOOGLE_PLAIN_SCOPES:
183
+ return GOOGLE_SCOPE_BASE + scope
184
+ return scope
185
+
186
+ @property
187
+ def env_var(self) -> str:
188
+ return f"{self.name.upper()}_ACCESS_TOKEN"
189
+
190
+ # During a run --------------------------------------------------------------------------------------------------
191
+
192
+ @property
193
+ def token(self) -> str:
194
+ """An access token for the person running the function, valid for the whole run."""
195
+ value = os.environ.get(self.env_var)
196
+ if not value:
197
+ raise ConnectionNotAvailable(
198
+ f"Connection '{self.name}' has no token here. It's only set while the function runs on Callables, "
199
+ f"for a function that declares connections=[{self.name}]. To run it locally, put a token for your own "
200
+ f"account in .env as {self.env_var}")
201
+ return value
202
+
203
+ def _details(self) -> dict[str, Any]:
204
+ try:
205
+ return json.loads(os.environ.get(CONNECTIONS_ENV) or "{}").get(self.name) or {}
206
+ except json.JSONDecodeError:
207
+ return {}
208
+
209
+ @property
210
+ def account(self) -> str | None:
211
+ """Which account the person connected, such as alice@company.com, when the service says."""
212
+ return self._details().get("account")
213
+
214
+ @property
215
+ def scopes_granted(self) -> list[str]:
216
+ """The scopes the person granted."""
217
+ return list(self._details().get("scopes") or [])
218
+
219
+ @property
220
+ def extra(self) -> dict[str, Any]:
221
+ """Other values the service returned at sign-in, such as Salesforce's instance_url."""
222
+ return dict(self._details().get("extra") or {})
223
+
224
+ def manifest_entry(self) -> dict[str, Any]:
225
+ return {
226
+ "name": self.name,
227
+ "title": self.title,
228
+ "provider": self.provider,
229
+ "scopes": self.scopes,
230
+ "authorize_url": self.authorize_url,
231
+ "token_url": self.token_url,
232
+ "authorize_params": self.authorize_params,
233
+ "token_endpoint_auth_method": self.token_endpoint_auth_method,
234
+ "token_request_format": self.token_request_format,
235
+ "scope_separator": self.scope_separator,
236
+ "scope_param": self.scope_param,
237
+ "pkce": self.pkce,
238
+ "token_path": self.token_path,
239
+ "userinfo_url": self.userinfo_url,
240
+ "account_field": self.account_field,
241
+ "revoke_url": self.revoke_url,
242
+ "placeholders": self.placeholders,
243
+ "client_id_secret": self.client_id_secret,
244
+ "client_secret_secret": self.client_secret_secret,
245
+ "env_var": self.env_var,
246
+ }
247
+
248
+ def __repr__(self) -> str:
249
+ return f"Connection({self.name!r})"
250
+
251
+
252
+ # Every Connection(...) made while importing lands here; one name must mean one set of settings
253
+ connections: dict[str, Connection] = {}
254
+ conflicts: list[str] = []
255
+
256
+
257
+ def _register(conn: Connection) -> None:
258
+ existing = connections.get(conn.name)
259
+ if existing is not None and existing.manifest_entry() != conn.manifest_entry():
260
+ conflicts.append(conn.name)
261
+ connections[conn.name] = conn
@@ -4,6 +4,7 @@ import re
4
4
  from dataclasses import dataclass, field
5
5
  from typing import Any, Callable
6
6
 
7
+ from callables.connections import Connection
7
8
  from callables.schema import file_fields, input_model, input_schema, output_kind, returns_one_file
8
9
 
9
10
 
@@ -14,7 +15,7 @@ RESERVED_GROUP_NAMES = {"check", "local", "manifest", "docs", "init", "run", "he
14
15
 
15
16
  class Group:
16
17
  """A set of related actions, like a Typer sub-app: `call <group> <action>` locally, and one section of the
17
- project in the web app. Secrets listed here are given to every action in the group.
18
+ project in the web app. Secrets and connections listed here are given to every action in the group.
18
19
 
19
20
  backups = Group("backups", title="Database backups", secrets=["SPACES_KEY"])
20
21
 
@@ -23,7 +24,7 @@ class Group:
23
24
  """
24
25
 
25
26
  def __init__(self, name: str, *, title: str | None = None, description: str = "",
26
- secrets: list[str] | None = None):
27
+ secrets: list[str] | None = None, connections: list[Connection] | None = None):
27
28
  if not GROUP_NAME.match(name):
28
29
  raise ValueError(f"Group name '{name}' must be lowercase letters, digits, '-' or '_', starting with a "
29
30
  "letter (it's typed as `call <group> <action>`)")
@@ -33,6 +34,7 @@ class Group:
33
34
  self.title = title or name.replace("_", " ").replace("-", " ").capitalize()
34
35
  self.description = description
35
36
  self.secrets = list(secrets or [])
37
+ self.connections = _connection_list(connections, f"Group '{name}'")
36
38
 
37
39
  def deploy(self, func: Callable[..., Any] | None = None, **options: Any):
38
40
  """`@deploy` for an action in this group; takes the same options. Its full name is `<group>.<name>`."""
@@ -111,6 +113,7 @@ class DeployedFunction:
111
113
  title: str
112
114
  description: str
113
115
  secrets: list[str] = field(default_factory=list)
116
+ connections: list[Connection] = field(default_factory=list)
114
117
  schedule: str | None = None
115
118
  timeout: int = 300
116
119
  group: Group | None = None
@@ -123,6 +126,12 @@ class DeployedFunction:
123
126
  """The group's secrets, then the action's own, without repeats."""
124
127
  return list(dict.fromkeys([*(self.group.secrets if self.group else []), *self.secrets]))
125
128
 
129
+ @property
130
+ def all_connections(self) -> list[Connection]:
131
+ """The group's connections, then the action's own, without repeats."""
132
+ both = [*(self.group.connections if self.group else []), *self.connections]
133
+ return list({c.name: c for c in both}.values())
134
+
126
135
  @property
127
136
  def entrypoint(self) -> str:
128
137
  return f"{self.func.__module__}:{self.func.__qualname__}"
@@ -136,6 +145,7 @@ class DeployedFunction:
136
145
  "input_schema": input_schema(self.func),
137
146
  "output_kind": output_kind(self.func),
138
147
  "secrets": self.all_secrets,
148
+ "connections": [c.name for c in self.all_connections],
139
149
  "schedule": self.schedule,
140
150
  "timeout": self.timeout,
141
151
  "group": self.group.manifest_entry() if self.group else None,
@@ -151,6 +161,14 @@ class DeployedFunction:
151
161
  return self.func(**kwargs)
152
162
 
153
163
 
164
+ def _connection_list(items: list[Connection] | None, where: str) -> list[Connection]:
165
+ for item in items or []:
166
+ if not isinstance(item, Connection):
167
+ raise TypeError(f"{where}: connections takes Connection objects, not {item!r}. "
168
+ "Define it with Connection('name', provider=...) and pass the object")
169
+ return list(items or [])
170
+
171
+
154
172
  # Every @deploy in an imported module lands here; `call manifest` reads it.
155
173
  registry: dict[str, DeployedFunction] = {}
156
174
 
@@ -162,6 +180,7 @@ def deploy(
162
180
  title: str | None = None,
163
181
  description: str | None = None,
164
182
  secrets: list[str] | None = None,
183
+ connections: list[Connection] | None = None,
165
184
  schedule: str | None = None,
166
185
  timeout: int = 300,
167
186
  next: list[Next | Callable[..., Any] | str] | None = None, # noqa: A002 (reads best as @deploy(next=[...]))
@@ -179,6 +198,8 @@ def deploy(
179
198
  description: One line shown on the card (defaults to the docstring's first paragraph).
180
199
  secrets: Environment variable names to inject at run time; values are set in the web app.
181
200
  Read them inside the function with `os.environ["NAME"]`.
201
+ connections: `Connection` objects for accounts each person connects themselves (their Gmail, their
202
+ Slack). Read `conn.token` inside the function: it's for the person running it.
182
203
  schedule: Cron expression in UTC (e.g. "0 9 * * MON"). Every input needs a default.
183
204
  Usually unnecessary: anyone can schedule a function from the web app.
184
205
  timeout: Seconds before the run is stopped (default 300, platform maximum 900).
@@ -208,6 +229,7 @@ def deploy(
208
229
  title=title or action.replace("_", " ").capitalize(),
209
230
  description=description or doc.split("\n\n")[0],
210
231
  secrets=list(secrets or []),
232
+ connections=_connection_list(connections, fn_name),
211
233
  schedule=schedule,
212
234
  timeout=timeout,
213
235
  group=_group,
@@ -0,0 +1,56 @@
1
+ """`.env` for local runs. `call local` and `call <group> <action>` load the project's `.env` so a function finds the
2
+ secrets it would get on the platform. Variables already set win, and the platform (`call run`) never reads it."""
3
+ import os
4
+ from pathlib import Path
5
+
6
+ _ESCAPES = {"n": "\n", "t": "\t", "r": "\r", '"': '"', "\\": "\\"}
7
+
8
+
9
+ def _unescape(value: str) -> str:
10
+ out, chars = [], iter(value)
11
+ for ch in chars:
12
+ if ch == "\\":
13
+ nxt = next(chars, "")
14
+ out.append(_ESCAPES.get(nxt, "\\" + nxt))
15
+ else:
16
+ out.append(ch)
17
+ return "".join(out)
18
+
19
+
20
+ def parse(text: str) -> dict[str, str]:
21
+ """KEY=value lines. Blank lines and `#` comments are skipped, `export ` is allowed, values may be quoted
22
+ ('single' kept as is, "double" with \\n-style escapes), and an unquoted value ends at ` #`. No ${VAR} expansion."""
23
+ values = {}
24
+ for raw in text.splitlines():
25
+ line = raw.strip()
26
+ if not line or line.startswith("#"):
27
+ continue
28
+ if line.startswith("export "):
29
+ line = line[len("export "):].lstrip()
30
+ key, sep, value = line.partition("=")
31
+ key = key.strip()
32
+ if not sep or not key.replace("_", "").isalnum() or key[0].isdigit():
33
+ continue
34
+ value = value.strip()
35
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
36
+ value = _unescape(value[1:-1]) if value[0] == '"' else value[1:-1]
37
+ else:
38
+ value = value.split(" #", 1)[0].rstrip()
39
+ values[key] = value
40
+ return values
41
+
42
+
43
+ def load(*folders: Path) -> tuple[list[Path], list[str]]:
44
+ """Loads `.env` from each folder, earlier folders first, without overriding variables already set.
45
+ Returns the files read and the names it set."""
46
+ files, added = [], []
47
+ for folder in dict.fromkeys(Path(f).resolve() for f in folders):
48
+ path = folder / ".env"
49
+ if not path.is_file():
50
+ continue
51
+ files.append(path)
52
+ for key, value in parse(path.read_text(encoding="utf-8")).items():
53
+ if key not in os.environ:
54
+ os.environ[key] = value
55
+ added.append(key)
56
+ return files, added
@@ -4,6 +4,7 @@ import sys
4
4
  from pathlib import Path
5
5
  from typing import Any
6
6
 
7
+ from callables import connections as connection_registry
7
8
  from callables.decorator import registry
8
9
 
9
10
  SKIP_DIRS = {".git", ".venv", "venv", "env", "node_modules", "__pycache__", "tests", "test", ".callables_sdk", "build", "dist"}
@@ -63,13 +64,26 @@ def build_manifest(root: Path, include_local: bool = False) -> dict[str, Any]:
63
64
  if fn.group is None:
64
65
  continue
65
66
  first = groups.setdefault(fn.group.name, fn.group)
66
- if first is not fn.group and (first.manifest_entry(), first.secrets) != (fn.group.manifest_entry(), fn.group.secrets):
67
+ settings = lambda g: (g.manifest_entry(), g.secrets, [c.name for c in g.connections]) # noqa: E731
68
+ if first is not fn.group and settings(first) != settings(fn.group):
67
69
  errors.append({"function": fn.name, "error": f"Group '{fn.group.name}' is defined twice with different "
68
70
  "settings. Define it once and import it where you need it."})
69
71
 
72
+ for name in dict.fromkeys(connection_registry.conflicts):
73
+ errors.append({"module": f"Connection '{name}'", "error": "defined twice with different settings. Define it "
74
+ "once and import it where you need it."})
75
+ # Only the connections a deployed function uses; the platform keys them by name within the project
76
+ used: dict[str, Any] = {}
77
+ for fn in registry.values():
78
+ if include_local or not fn.local_only:
79
+ for conn in fn.all_connections:
80
+ used[conn.name] = conn
81
+ connections = [used[name].manifest_entry() for name in sorted(used)]
82
+
70
83
  return {
71
84
  "manifest_version": MANIFEST_VERSION,
72
85
  "sdk_version": __version__,
73
86
  "functions": functions,
87
+ "connections": connections,
74
88
  "errors": errors,
75
89
  }
@@ -1,5 +1,6 @@
1
1
  """Which folder of a repo the platform builds. By default the whole repo; a repo can point it at a subfolder,
2
- and then only that folder is built: its requirements.txt / pyproject.toml, apt.txt and .python-version."""
2
+ and then only that folder is built: its requirements.txt / pyproject.toml, apt.txt and .python-version.
3
+ A project's own folder setting wins over the repo's config, so one repo can back several projects."""
3
4
  import tomllib
4
5
  from pathlib import Path, PurePosixPath
5
6
 
@@ -34,10 +35,11 @@ def _configured_root(repo: Path) -> tuple[object, str] | None:
34
35
  return None
35
36
 
36
37
 
37
- def build_root(repo: Path) -> tuple[Path, str | None]:
38
- """The folder to build, and where that setting came from (None when it's the whole repo)."""
38
+ def build_root(repo: Path, project_root: str | None = None) -> tuple[Path, str | None]:
39
+ """The folder to build, and where that setting came from (None when it's the whole repo). `project_root` is the
40
+ project's folder setting, relative to the repo."""
39
41
  repo = repo.resolve()
40
- configured = _configured_root(repo)
42
+ configured = (project_root, "the project's settings") if project_root else _configured_root(repo)
41
43
  if configured is None:
42
44
  return repo, None
43
45
  value, source = configured
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: callables
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Decorate Python functions and push them to Callables: forms, schedules and run history for your team.
5
5
  License-Expression: Apache-2.0
6
6
  Project-URL: Homepage, https://callables.app
@@ -42,7 +42,7 @@ def weekly_report(region: Literal["NA", "EMEA", "APAC"] = "NA", days: int = 7) -
42
42
  - **Results** are shown by return type: `str` as Markdown, `list[dict]` (or a DataFrame) as a table with CSV download, `dict`/Pydantic model as a key-value list, `None` as "done".
43
43
  - **Files in**: a `File` parameter becomes an upload field. Your function gets a `File` with `.path`, `.name`, `.read_text()`, `.read_bytes()` and `.open()`. Limit the picker with `Annotated[File, accept(".csv", ".xlsx")]`.
44
44
  - **Files out**: return a `File` (or a `list[File]`) and people get download buttons. To hand back files alongside another result, call `save_file(path_or_bytes, name=...)`. Files are kept for 24 hours by default.
45
- - **Secrets** you list are injected as environment variables at run time (`os.environ["SALES_API_TOKEN"]`); set their values in the Callables console.
45
+ - **Secrets** you list are injected as environment variables at run time (`os.environ["SALES_API_TOKEN"]`); set their values in the Callables console. Locally, `call local` and `call <group> <action>` load the project's `.env` instead (variables already set in your shell win).
46
46
  - **Schedules** are cron expressions, in UTC.
47
47
 
48
48
  ```python
@@ -7,7 +7,9 @@ callables/__main__.py
7
7
  callables/checks.py
8
8
  callables/cli.py
9
9
  callables/commands.py
10
+ callables/connections.py
10
11
  callables/decorator.py
12
+ callables/envfile.py
11
13
  callables/files.py
12
14
  callables/init.py
13
15
  callables/manifest.py
@@ -23,6 +25,8 @@ callables.egg-info/requires.txt
23
25
  callables.egg-info/top_level.txt
24
26
  tests/test_agent_tools.py
25
27
  tests/test_command.py
28
+ tests/test_connections.py
29
+ tests/test_envfile.py
26
30
  tests/test_files.py
27
31
  tests/test_groups.py
28
32
  tests/test_next.py
@@ -0,0 +1,167 @@
1
+ import json
2
+ import textwrap
3
+
4
+ import pytest
5
+
6
+ from callables import Connection, Group, deploy, registry
7
+ from callables import connections as connection_registry
8
+ from callables.checks import check_project
9
+ from callables.connections import ConnectionNotAvailable
10
+ from callables.manifest import build_manifest
11
+
12
+
13
+ @pytest.fixture(autouse=True)
14
+ def isolated():
15
+ registry.clear()
16
+ connection_registry.connections.clear()
17
+ connection_registry.conflicts.clear()
18
+ yield
19
+ registry.clear()
20
+ connection_registry.connections.clear()
21
+ connection_registry.conflicts.clear()
22
+
23
+
24
+ def test_google_preset_expands_short_scopes_and_adds_sign_in_scopes():
25
+ google = Connection("google", provider="google", scopes=["gmail.modify", "https://www.googleapis.com/auth/drive.file"])
26
+ entry = google.manifest_entry()
27
+ assert entry["scopes"] == ["openid", "email", "https://www.googleapis.com/auth/gmail.modify",
28
+ "https://www.googleapis.com/auth/drive.file"]
29
+ assert entry["authorize_params"]["access_type"] == "offline"
30
+ assert entry["pkce"] is True
31
+ assert entry["client_id_secret"] == "GOOGLE_CLIENT_ID"
32
+ assert entry["client_secret_secret"] == "GOOGLE_CLIENT_SECRET"
33
+ assert entry["env_var"] == "GOOGLE_ACCESS_TOKEN"
34
+
35
+
36
+ def test_microsoft_tenant_and_offline_access():
37
+ ms = Connection("outlook", provider="microsoft", scopes=["Mail.ReadWrite"], tenant="contoso.onmicrosoft.com")
38
+ assert ms.authorize_url == "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/authorize"
39
+ assert ms.scopes == ["offline_access", "User.Read", "Mail.ReadWrite"]
40
+ assert Connection("ms", provider="microsoft").token_url.startswith("https://login.microsoftonline.com/common/")
41
+
42
+
43
+ def test_custom_provider_and_overrides():
44
+ crm = Connection("crm", authorize_url="https://login.crm.example/oauth/authorize",
45
+ token_url="https://login.crm.example/oauth/token", scopes=["contacts.read"],
46
+ token_endpoint_auth_method="client_secret_basic", scope_separator=",",
47
+ client_id_secret="CRM_APP_ID")
48
+ entry = crm.manifest_entry()
49
+ assert entry["provider"] is None and entry["title"] == "Crm"
50
+ assert entry["scopes"] == ["contacts.read"]
51
+ assert entry["client_id_secret"] == "CRM_APP_ID" and entry["client_secret_secret"] == "CRM_CLIENT_SECRET"
52
+
53
+
54
+ @pytest.mark.parametrize("kwargs, message", [
55
+ ({"provider": "gogle"}, "unknown provider"),
56
+ ({}, "needs a provider"),
57
+ ({"authorize_url": "http://x.example/a", "token_url": "https://x.example/t"}, "must start with https://"),
58
+ ({"authorize_url": "https://{shop}.example/a", "token_url": "https://x.example/t"}, "isn't in placeholders"),
59
+ ({"provider": "google", "placeholders": {"shop": "Store"}}, "isn't used"),
60
+ ({"provider": "google", "token_endpoint_auth_method": "basic"}, "token_endpoint_auth_method"),
61
+ ({"provider": "google", "tenant": "x"}, "tenant only applies"),
62
+ ])
63
+ def test_bad_settings_fail_at_definition(kwargs, message):
64
+ with pytest.raises(ValueError, match=message):
65
+ Connection("svc", **kwargs)
66
+
67
+
68
+ def test_bad_name():
69
+ with pytest.raises(ValueError, match="lowercase"):
70
+ Connection("Google", provider="google")
71
+
72
+
73
+ def test_placeholders():
74
+ shop = Connection("shopify", authorize_url="https://{shop}.myshopify.com/admin/oauth/authorize",
75
+ token_url="https://{shop}.myshopify.com/admin/oauth/access_token", scopes=["read_orders"],
76
+ placeholders={"shop": "Your store name"})
77
+ assert shop.manifest_entry()["placeholders"] == {"shop": "Your store name"}
78
+
79
+
80
+ def test_deploy_takes_connection_objects_only():
81
+ with pytest.raises(TypeError, match="Connection objects"):
82
+ deploy(connections=["google"])(lambda: None)
83
+
84
+
85
+ def test_token_and_details_come_from_the_run_environment(monkeypatch):
86
+ google = Connection("google", provider="google")
87
+ with pytest.raises(ConnectionNotAvailable, match="GOOGLE_ACCESS_TOKEN"):
88
+ google.token
89
+ monkeypatch.setenv("GOOGLE_ACCESS_TOKEN", "ya29.abc")
90
+ monkeypatch.setenv("CALLABLES_CONNECTIONS", json.dumps(
91
+ {"google": {"account": "alice@example.com", "scopes": ["openid"], "extra": {"hd": "example.com"}}}))
92
+ assert google.token == "ya29.abc"
93
+ assert google.account == "alice@example.com"
94
+ assert google.scopes_granted == ["openid"]
95
+ assert google.extra == {"hd": "example.com"}
96
+
97
+
98
+ PROJECT = '''
99
+ from callables import Connection, Group, deploy
100
+
101
+ google = Connection("google", provider="google", scopes=["calendar.readonly"])
102
+ slack = Connection("slack", provider="slack", scopes=["chat:write"])
103
+ unused = Connection("unused", provider="github")
104
+
105
+ mail = Group("mail", title="Mail", connections=[google])
106
+
107
+
108
+ @mail.deploy(connections=[slack, google])
109
+ def digest() -> str:
110
+ """Posts your agenda."""
111
+ return google.token
112
+
113
+
114
+ @deploy
115
+ def plain() -> str:
116
+ """No connections."""
117
+ return "ok"
118
+ '''
119
+
120
+
121
+ @pytest.fixture
122
+ def project(tmp_path, monkeypatch, request):
123
+ module = f"conn_{request.node.name.replace('[', '_').replace(']', '').replace('-', '_')}"
124
+ (tmp_path / f"{module}.py").write_text(textwrap.dedent(PROJECT))
125
+ (tmp_path / "requirements.txt").write_text("")
126
+ monkeypatch.chdir(tmp_path)
127
+ return tmp_path
128
+
129
+
130
+ def test_manifest_lists_used_connections_and_each_function_names_them(project):
131
+ manifest = build_manifest(project)
132
+ assert not manifest["errors"]
133
+ by_name = {f["name"]: f for f in manifest["functions"]}
134
+ assert by_name["mail.digest"]["connections"] == ["google", "slack"] # group's first, no repeats
135
+ assert by_name["plain"]["connections"] == []
136
+ assert [c["name"] for c in manifest["connections"]] == ["google", "slack"] # unused one left out
137
+ slack = next(c for c in manifest["connections"] if c["name"] == "slack")
138
+ assert slack["scope_param"] == "user_scope" and slack["token_path"] == "authed_user.access_token"
139
+
140
+
141
+ def test_check_reports_the_secrets_each_connection_needs(project):
142
+ report = check_project(project)
143
+ assert report["ok"], report["issues"]
144
+ google = next(c for c in report["connections"] if c["name"] == "google")
145
+ assert google["secrets"] == ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"]
146
+ assert google["env_var"] == "GOOGLE_ACCESS_TOKEN"
147
+
148
+
149
+ def test_a_connection_defined_twice_differently_fails_the_manifest(tmp_path):
150
+ (tmp_path / "conn_twice.py").write_text(textwrap.dedent('''
151
+ from callables import Connection, deploy
152
+
153
+ a = Connection("google", provider="google", scopes=["gmail.modify"])
154
+ b = Connection("google", provider="google", scopes=["calendar.readonly"])
155
+
156
+ @deploy(connections=[a])
157
+ def f() -> str:
158
+ """x"""
159
+ return ""
160
+ '''))
161
+ errors = build_manifest(tmp_path)["errors"]
162
+ assert any("defined twice" in e["error"] for e in errors)
163
+
164
+
165
+ def test_group_rejects_strings():
166
+ with pytest.raises(TypeError):
167
+ Group("mail", connections=["google"])
@@ -0,0 +1,113 @@
1
+ import json
2
+ import os
3
+ import textwrap
4
+
5
+ import pytest
6
+
7
+ from callables import cli, registry
8
+ from callables.cli import main
9
+ from callables.envfile import load, parse
10
+
11
+
12
+ @pytest.fixture(autouse=True)
13
+ def isolated(monkeypatch):
14
+ registry.clear()
15
+ monkeypatch.setattr(cli, "_env_loaded", False)
16
+ for key in ("CALLABLES_T_TOKEN", "CALLABLES_T_SHELL"):
17
+ monkeypatch.delenv(key, raising=False)
18
+ yield
19
+ registry.clear()
20
+ for key in ("CALLABLES_T_TOKEN", "CALLABLES_T_SHELL"): # load() sets os.environ directly
21
+ os.environ.pop(key, None)
22
+
23
+
24
+ def test_parse_reads_the_usual_dotenv_forms():
25
+ text = textwrap.dedent('''
26
+ # a comment
27
+ PLAIN=abc
28
+ export EXPORTED=1
29
+ SPACED = padded value
30
+ SINGLE='keep $this \\n raw'
31
+ DOUBLE="line\\nbreak \\"quoted\\""
32
+ INLINE=value # trailing comment
33
+ HASH=pass#word
34
+ URL=postgresql://u:p@host:5432/db?sslmode=require
35
+ EMPTY=
36
+ not a line
37
+ 1BAD=x
38
+ ''')
39
+ assert parse(text) == {
40
+ "PLAIN": "abc",
41
+ "EXPORTED": "1",
42
+ "SPACED": "padded value",
43
+ "SINGLE": "keep $this \\n raw",
44
+ "DOUBLE": 'line\nbreak "quoted"',
45
+ "INLINE": "value",
46
+ "HASH": "pass#word",
47
+ "URL": "postgresql://u:p@host:5432/db?sslmode=require",
48
+ "EMPTY": "",
49
+ }
50
+
51
+
52
+ def test_load_never_overrides_what_is_already_set(tmp_path, monkeypatch):
53
+ (tmp_path / ".env").write_text("CALLABLES_T_TOKEN=from-file\nCALLABLES_T_SHELL=from-file\n")
54
+ monkeypatch.setenv("CALLABLES_T_SHELL", "from-shell")
55
+ files, added = load(tmp_path)
56
+ assert files == [(tmp_path / ".env").resolve()]
57
+ assert added == ["CALLABLES_T_TOKEN"]
58
+ assert os.environ["CALLABLES_T_TOKEN"] == "from-file"
59
+ assert os.environ["CALLABLES_T_SHELL"] == "from-shell"
60
+
61
+
62
+ def test_the_build_folder_env_wins_over_the_current_folder(tmp_path):
63
+ sub = tmp_path / "automations"
64
+ sub.mkdir()
65
+ (sub / ".env").write_text("CALLABLES_T_TOKEN=folder\n")
66
+ (tmp_path / ".env").write_text("CALLABLES_T_TOKEN=repo\nCALLABLES_T_SHELL=repo\n")
67
+ load(sub, tmp_path)
68
+ assert os.environ["CALLABLES_T_TOKEN"] == "folder"
69
+ assert os.environ["CALLABLES_T_SHELL"] == "repo"
70
+
71
+
72
+ PROJECT = '''
73
+ import os
74
+ from callables import deploy
75
+
76
+
77
+ @deploy(secrets=["CALLABLES_T_TOKEN"])
78
+ def token() -> str:
79
+ return os.environ.get("CALLABLES_T_TOKEN", "missing")
80
+ '''
81
+
82
+
83
+ @pytest.fixture
84
+ def project(tmp_path, monkeypatch, request):
85
+ (tmp_path / f"env_{request.node.name}.py").write_text(textwrap.dedent(PROJECT))
86
+ (tmp_path / ".env").write_text("CALLABLES_T_TOKEN=secret-from-env-file\n")
87
+ monkeypatch.chdir(tmp_path)
88
+ return tmp_path
89
+
90
+
91
+ def test_local_runs_see_the_env_file(project, capsys):
92
+ assert main(["local", "token", "--json"]) == 0
93
+ out = capsys.readouterr()
94
+ assert json.loads(out.out)["value"] == "secret-from-env-file"
95
+ assert "Loaded 1 variable from .env" in out.err
96
+
97
+
98
+ def test_commands_see_the_env_file(project, capsys):
99
+ assert main(["token"]) == 0
100
+ assert capsys.readouterr().out.strip() == "secret-from-env-file"
101
+
102
+
103
+ def test_the_shell_wins_over_the_env_file(project, capsys, monkeypatch):
104
+ monkeypatch.setenv("CALLABLES_T_TOKEN", "from-shell")
105
+ assert main(["token"]) == 0
106
+ assert capsys.readouterr().out.strip() == "from-shell"
107
+
108
+
109
+ def test_the_platform_runner_ignores_the_env_file(project, monkeypatch, capsys, request):
110
+ monkeypatch.setenv("CALLABLES_INPUTS", "{}")
111
+ main(["run", f"env_{request.node.name}:token", "--root", str(project)])
112
+ assert "missing" in capsys.readouterr().out
113
+ assert "CALLABLES_T_TOKEN" not in os.environ
@@ -14,6 +14,18 @@ def isolated():
14
14
  registry.clear()
15
15
 
16
16
 
17
+ def test_the_projects_folder_wins_over_the_repo_config(tmp_path):
18
+ (tmp_path / "automations" / "email").mkdir(parents=True)
19
+ (tmp_path / "callables.toml").write_text('root = "automations"\n')
20
+ assert build_root(tmp_path, "automations/email") == (
21
+ (tmp_path / "automations" / "email").resolve(), "the project's settings")
22
+ assert build_root(tmp_path, "") == ((tmp_path / "automations").resolve(), "callables.toml")
23
+ with pytest.raises(ConfigError, match="no folder"):
24
+ build_root(tmp_path, "salesforce")
25
+ with pytest.raises(ConfigError, match="inside the repo"):
26
+ build_root(tmp_path, "../other")
27
+
28
+
17
29
  def test_whole_repo_unless_a_root_is_set(tmp_path):
18
30
  assert build_root(tmp_path) == (tmp_path.resolve(), None)
19
31
  (tmp_path / "automations").mkdir()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes