talentprism-cli 0.3.0__py3-none-any.whl

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.
@@ -0,0 +1,277 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from email.utils import parsedate_to_datetime
5
+ from typing import Any, Callable
6
+ from urllib.parse import urlparse
7
+
8
+ from . import __version__
9
+ from .config import TalentPrismConfig
10
+ from .credentials import TokenManager
11
+ from .errors import TalentPrismError
12
+
13
+
14
+ RequestFn = Callable[..., Any]
15
+
16
+ RETRY_BACKOFF_SECONDS = 0.2
17
+ MAX_PAGES = 1000
18
+ ERROR_BODY_PREVIEW_CHARS = 2000
19
+ MAX_RETRY_AFTER_SECONDS = 10.0
20
+
21
+
22
+ class APIClient:
23
+ def __init__(self, config: TalentPrismConfig, *, request: RequestFn | None = None):
24
+ self.config = config
25
+ if request is None:
26
+ import requests
27
+
28
+ request = requests.request
29
+ self._request = request
30
+ self._tokens = TokenManager(config, request, config.timeout_seconds) if config.auth_kind == "login" else None
31
+
32
+ def get(self, path: str) -> Any:
33
+ return self._send("GET", path)
34
+
35
+ def get_paginated(self, path: str, *, all_pages: bool = False, cap: int = 100) -> Any:
36
+ first_page = self.get(path)
37
+ if not _is_paginated(first_page):
38
+ return first_page
39
+ total_count = first_page.get("count", 0)
40
+ if total_count > cap and not all_pages:
41
+ raise TalentPrismError(
42
+ code="too_many_results",
43
+ type="validation",
44
+ message="List result exceeds the safe automatic cap.",
45
+ details={"count": total_count, "cap": cap},
46
+ remediation="Refine the query or pass --all to walk every page.",
47
+ )
48
+
49
+ results = list(first_page.get("results", []))
50
+ next_url = first_page.get("next")
51
+ seen_urls: set[str] = set()
52
+ while next_url:
53
+ if next_url in seen_urls or len(seen_urls) >= MAX_PAGES:
54
+ raise TalentPrismError(
55
+ code="pagination_not_terminating",
56
+ type="schema_mismatch",
57
+ message="Pagination did not terminate within the page safety limit.",
58
+ details={"next": next_url, "pages_fetched": len(seen_urls) + 1, "max_pages": MAX_PAGES},
59
+ remediation="Confirm the base URL points at a compatible TalentPrism API.",
60
+ )
61
+ seen_urls.add(next_url)
62
+ page = self.get(next_url)
63
+ results.extend(page.get("results", []))
64
+ next_url = page.get("next")
65
+ return {**first_page, "next": None, "results": results, "truncated": False}
66
+
67
+ def post(self, path: str, payload: dict[str, Any]) -> Any:
68
+ return self._send("POST", path, json=payload)
69
+
70
+ def _send(self, method: str, path: str, **kwargs) -> Any:
71
+ url = self._url(path)
72
+ # Only GETs are retried: POSTs are not idempotent.
73
+ retries = self.config.get_retries if method == "GET" else 0
74
+ attempt = 0
75
+ refreshed = False
76
+ while True:
77
+ headers = self._headers()
78
+ try:
79
+ response = self._request(method, url, headers=headers, timeout=self.config.timeout_seconds, **kwargs)
80
+ except OSError as exc:
81
+ if attempt < retries:
82
+ attempt += 1
83
+ time.sleep(RETRY_BACKOFF_SECONDS * attempt)
84
+ continue
85
+ raise TalentPrismError(
86
+ code="connection_failed",
87
+ type="transient",
88
+ message=f"Could not reach TalentPrism at {self.config.base_url}.",
89
+ details={"error": str(exc)},
90
+ remediation="Check the network connection and base URL, then retry.",
91
+ ) from exc
92
+ if response.status_code >= 500 and attempt < retries:
93
+ attempt += 1
94
+ time.sleep(RETRY_BACKOFF_SECONDS * attempt)
95
+ continue
96
+ if response.status_code == 401 and self._tokens and not refreshed:
97
+ # The access token may have been revoked or rotated under us: refresh once and retry once.
98
+ refreshed = True
99
+ self._tokens.refresh(rejected=headers["Authorization"].removeprefix("Bearer "))
100
+ continue
101
+ if response.status_code == 429:
102
+ retry_after = _retry_after_seconds(response)
103
+ if retry_after is not None and retry_after <= MAX_RETRY_AFTER_SECONDS and attempt < retries:
104
+ attempt += 1
105
+ time.sleep(retry_after)
106
+ continue
107
+ raise TalentPrismError(
108
+ code="rate_limited",
109
+ type="transient",
110
+ message="TalentPrism is rate limiting requests.",
111
+ details={"retry_after": retry_after},
112
+ remediation=(
113
+ f"Wait {retry_after:g} seconds and retry." if retry_after is not None else "Wait and retry."
114
+ ),
115
+ )
116
+ break
117
+ if response.status_code == 401:
118
+ if self._tokens:
119
+ raise TalentPrismError(
120
+ code="auth_failed",
121
+ type="auth",
122
+ message="TalentPrism rejected the login session.",
123
+ remediation="Run `tp login` to sign in again.",
124
+ )
125
+ raise TalentPrismError(
126
+ code="auth_failed",
127
+ type="auth",
128
+ message="TalentPrism rejected the API key.",
129
+ remediation=(
130
+ "Verify TALENTPRISM_API_KEY is active and scoped to the expected team. API keys "
131
+ "expire on the date chosen when they were created: create a new one from your TalentPrism account page, "
132
+ "or run `tp login` to sign in as yourself."
133
+ ),
134
+ )
135
+ if response.status_code == 403:
136
+ # Deliberately NOT the same message as a 401. The credential authenticated fine; the user
137
+ # behind it is not allowed to do this. Reporting that as "rejected the API key" sent
138
+ # people to rotate a perfectly good key, and let an automated caller conclude its
139
+ # credentials were broken and quietly fall back to something else.
140
+ if self.config.auth_kind == "login":
141
+ raise TalentPrismError(
142
+ code="not_authorized",
143
+ type="auth",
144
+ message=("You are signed in, but your user is not allowed to use this capability for this team."),
145
+ remediation=(
146
+ "This is a role problem, not a login problem - signing in again will not help. "
147
+ "`ops.*` capabilities (`tp ops delivery-status`, `tp ops decision-logs`) require "
148
+ "your user to be an ADMIN of the team, not a member. Check your membership role "
149
+ "with `tp whoami`, then ask a team admin to grant you admin, or run `tp login` "
150
+ "and choose a team where you are an admin."
151
+ ),
152
+ )
153
+ raise TalentPrismError(
154
+ code="not_authorized",
155
+ type="auth",
156
+ message=(
157
+ "The API key authenticated, but its user is not allowed to use this capability for this team."
158
+ ),
159
+ remediation=(
160
+ "This is a role problem, not a key problem - do not rotate the key. `ops.*` "
161
+ "capabilities (`tp ops delivery-status`, `tp ops decision-logs`) require the "
162
+ "key's user to be an ADMIN of the team, not a member. Check the membership "
163
+ "role with `tp whoami`, then either grant that user admin on the team or "
164
+ "issue the key from an admin account."
165
+ ),
166
+ )
167
+ if response.status_code == 404:
168
+ raise TalentPrismError(
169
+ code="not_found",
170
+ type="not_found",
171
+ message="TalentPrism could not find the requested resource.",
172
+ remediation="Check the identifier and confirm it belongs to the API key's team.",
173
+ )
174
+ if response.status_code == 409:
175
+ payload = _safe_json(response)
176
+ approval = payload.get("approval") if isinstance(payload, dict) else None
177
+ if (
178
+ isinstance(payload, dict)
179
+ and payload.get("status") == "approval_required"
180
+ and isinstance(payload.get("preview"), dict)
181
+ and isinstance(approval, dict)
182
+ and approval.get("token")
183
+ ):
184
+ # A write proposal is an expected, actionable command result: the server has
185
+ # performed no mutation and returned the exact preview plus its one-shot token.
186
+ return payload
187
+ if isinstance(payload, dict) and payload.get("status") == "approval_rejected":
188
+ raise TalentPrismError(
189
+ code=str(payload.get("code") or "approval_rejected"),
190
+ type="validation",
191
+ message=str(payload.get("message") or "TalentPrism rejected the approval token."),
192
+ details=payload,
193
+ remediation="Preview the write again and confirm the newly returned one-shot approval token.",
194
+ )
195
+ if 400 <= response.status_code < 500:
196
+ raise TalentPrismError(
197
+ code="validation_failed",
198
+ type="validation",
199
+ message="TalentPrism rejected the request.",
200
+ details=_safe_json(response),
201
+ remediation="Review the request payload and field errors.",
202
+ )
203
+ if response.status_code >= 500:
204
+ raise TalentPrismError(
205
+ code="transient_failure",
206
+ type="transient",
207
+ message="TalentPrism returned a server error.",
208
+ remediation="Retry later, or check the TalentPrism service logs if the error persists.",
209
+ )
210
+ return _safe_json(response)
211
+
212
+ def _url(self, path: str) -> str:
213
+ if path.startswith("http://") or path.startswith("https://"):
214
+ self._assert_same_origin(path)
215
+ return path
216
+ return f"{self.config.base_url}/{path.lstrip('/')}"
217
+
218
+ def _assert_same_origin(self, url: str) -> None:
219
+ # Credentials are attached to every request, so absolute URLs (e.g. pagination
220
+ # `next` links from the server) must stay on the configured origin.
221
+ if _origin(url) != _origin(self.config.base_url):
222
+ raise TalentPrismError(
223
+ code="cross_origin_url",
224
+ type="validation",
225
+ message="Refusing to send credentials to a URL outside the configured base URL.",
226
+ details={"url": url, "base_url": self.config.base_url},
227
+ remediation="Confirm the API returns URLs on the configured host, or update TALENTPRISM_BASE_URL.",
228
+ )
229
+
230
+ def _headers(self) -> dict[str, str]:
231
+ authorization = f"Bearer {self._tokens.bearer()}" if self._tokens else f"Api-Key {self.config.api_key}"
232
+ headers = {
233
+ "Authorization": authorization,
234
+ "Accept": "application/json",
235
+ "Content-Type": "application/json",
236
+ "User-Agent": f"TalentPrism CLI/{__version__}",
237
+ }
238
+ if self.config.agent_source:
239
+ headers["X-TalentPrism-Agent-Source"] = self.config.agent_source
240
+ return headers
241
+
242
+
243
+ def _origin(url: str) -> tuple[str, str, int]:
244
+ parsed = urlparse(url)
245
+ port = parsed.port or (80 if parsed.scheme == "http" else 443)
246
+ return (parsed.scheme, (parsed.hostname or "").lower(), port)
247
+
248
+
249
+ def _retry_after_seconds(response) -> float | None:
250
+ raw = str((getattr(response, "headers", None) or {}).get("Retry-After", "")).strip()
251
+ if not raw:
252
+ return None
253
+ try:
254
+ return max(0.0, float(raw))
255
+ except ValueError:
256
+ pass
257
+ try:
258
+ return max(0.0, parsedate_to_datetime(raw).timestamp() - time.time())
259
+ except (TypeError, ValueError):
260
+ return None
261
+
262
+
263
+ def _safe_json(response) -> Any:
264
+ try:
265
+ return response.json()
266
+ except ValueError as exc:
267
+ raise TalentPrismError(
268
+ code="schema_mismatch",
269
+ type="schema_mismatch",
270
+ message="TalentPrism returned a non-JSON response.",
271
+ details={"body": getattr(response, "text", "")[:ERROR_BODY_PREVIEW_CHARS]},
272
+ remediation="Confirm the base URL points at a compatible TalentPrism API.",
273
+ ) from exc
274
+
275
+
276
+ def _is_paginated(payload: Any) -> bool:
277
+ return isinstance(payload, dict) and "results" in payload and "count" in payload
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: talentprism-cli
3
+ Version: 0.3.0
4
+ Summary: Command line for TalentPrism: team-scoped recruiting data and actions for people and AI agents
5
+ License-Expression: LicenseRef-Proprietary
6
+ Project-URL: Homepage, https://talentprism.ai
7
+ Project-URL: Documentation, https://talentprism.ai/help/talentprism-cli/
8
+ Keywords: talentprism,recruiting,cli,agents
9
+ Classifier: Environment :: Console
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Office/Business
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: talentprism_cli/LICENSE.txt
20
+ Requires-Dist: PyYAML>=6.0.0
21
+ Requires-Dist: requests>=2.32.0
22
+ Dynamic: license-file
23
+
24
+ # TalentPrism CLI
25
+
26
+ `tp` is the command line for TalentPrism. It reads team-scoped recruiting data (sequences, candidates, interviews, reminders, campaign and activity summaries, evidence records) and makes changes through the same permissions and validation as the web app. It prints JSON that scripts and AI agents can parse, and reports errors as structured JSON with a stable `code`.
27
+
28
+ Full documentation: https://talentprism.ai/help/talentprism-cli/
29
+
30
+ ## Install
31
+
32
+ ```shell
33
+ pipx install talentprism-cli
34
+ # or
35
+ uv tool install talentprism-cli
36
+
37
+ tp --version
38
+ ```
39
+
40
+ Requires Python 3.11 or newer.
41
+
42
+ ## Sign in
43
+
44
+ People sign in with the browser:
45
+
46
+ ```shell
47
+ tp login
48
+ ```
49
+
50
+ Pick a team and approve. The CLI keeps short-lived tokens in `~/.talentprism/config.toml` and refreshes them on its own. Use `tp login --no-browser` over SSH, and `tp logout` to sign out.
51
+
52
+ Scripts, CI jobs and AI agents use a team-scoped API key instead:
53
+
54
+ ```shell
55
+ export TALENTPRISM_API_KEY="<your api key>"
56
+ ```
57
+
58
+ New API keys expire one year after they are created. Your account page shows each key's expiry date and when it was last used; create a replacement key before the old one expires.
59
+
60
+ When several credentials are present, `tp` uses the first of: the `--api-key` flag, `TALENTPRISM_API_KEY`, login tokens in the profile, `api_key` in the profile. The server is `https://talentprism.ai` unless you set `TALENTPRISM_BASE_URL` (local development only).
61
+
62
+ ## Examples
63
+
64
+ ```shell
65
+ tp whoami
66
+ tp sequences list --status Active --json
67
+ tp candidates search --query "aircraft assembler North Charleston" --json
68
+ tp activity summary --days 14 --json
69
+ tp candidates timeline <candidate_id> --days 30 --json
70
+ ```
71
+
72
+ ## Changing data
73
+
74
+ Every write is two steps. Run the command once to get a preview and a one-time approval token. Nothing changes. Then run the same command again with `--confirm-write --approval-token <token>`:
75
+
76
+ ```shell
77
+ tp candidates add-note 123 --text "Prefers second shift"
78
+ tp candidates add-note 123 --text "Prefers second shift" --confirm-write --approval-token <token>
79
+ ```
80
+
81
+ ## Rate limits
82
+
83
+ Per credential (each API key, or each login), per minute: 300 reads, 60 changes, and 30 copilot questions (`tp copilot ask` and `tp copilot brief`). Previews count as reads. When a limit is hit the CLI reports `rate_limited` with a `retry_after` value.
84
+
85
+ ## Help
86
+
87
+ - `tp --help` and `tp <command> --help` list every command and flag.
88
+ - `tp skill print` prints the agent skill text bundled with the CLI.
89
+ - Errors come with a `remediation` line. The help page has a troubleshooting table keyed by error code.
90
+
91
+ ## License
92
+
93
+ Proprietary. The CLI is provided for use with a TalentPrism account; see `LICENSE.txt` in the package.
@@ -0,0 +1,24 @@
1
+ talentprism_cli/LICENSE.txt,sha256=Iikp35TKg_fUatDA7RLKbTeLX3p9CmnGb4Q5IzEOaVw,853
2
+ talentprism_cli/README.md,sha256=3rU5LzBLdEAWTcZiCgPQGjbn6KfVqf11k1-wnhItzIE,2684
3
+ talentprism_cli/__init__.py,sha256=VrXpHDu3erkzwl_WXrqINBm9xWkcyUy53IQOj042dOs,22
4
+ talentprism_cli/__main__.py,sha256=PSQ4rpL0dG6f-qH4N7H-gD9igQkdHzH4yVZDcW8lfZo,80
5
+ talentprism_cli/auth.py,sha256=oTjVT7DCUKhnTjBWXR4zahyESNfwl4iCmU8Y88p16mo,7985
6
+ talentprism_cli/cli.py,sha256=ZXbSRxkCoqi9Lkp5MfMe54K661sU4gAguItNusY8Uqc,49910
7
+ talentprism_cli/config.py,sha256=SSQD3KlHoNoEta3E01w-cKNmojaXTM2MKj7xI1JYUBM,11891
8
+ talentprism_cli/config_store.py,sha256=PbqZwfsUZ8ex2haWzr4pq2zZuMc6zRaB67WbGzcyU8c,5037
9
+ talentprism_cli/credentials.py,sha256=-xpP3Tn8NsLdWh-H3gHqpbgOkXOvX7FYSxskeIOlxAQ,7019
10
+ talentprism_cli/errors.py,sha256=1rY0YGOsxccrvapvilOEu3kv0ImAZzULsqx-_Lzkl0w,1169
11
+ talentprism_cli/format.py,sha256=_arRhSc-ceZI23Gm_TVSUSZMAqGbbTw4WuYf-CjWiQk,3235
12
+ talentprism_cli/loopback.py,sha256=BYAXrVVgrzFP3WrX0Y63XfupEz8khkiVOTn1Zwfdi8E,5947
13
+ talentprism_cli/network_bootstrap.py,sha256=uQI8x-8KiOVldiGoWFmHT-2wWsA2hUh_fCpn3r2UPEw,3607
14
+ talentprism_cli/oauth.py,sha256=vv7VdQfzjFSNJWoROLjxNADWBJbwo3tEJtBdQzAuL44,6397
15
+ talentprism_cli/readonly_api.py,sha256=TaYJ6-9l4Bmwbr6Nha0EVpanopePRtbjESaQBdOEgMw,15047
16
+ talentprism_cli/sequence_writes.py,sha256=ry9BYfFie4hjkOUKBDV6BLTalAbo2KnQA6WG4fIaaaE,2942
17
+ talentprism_cli/skill.py,sha256=b3iriRLUy0AFxC-rrUvDKNL93hhRxIbfo1hEuR30_Uw,19253
18
+ talentprism_cli/transport.py,sha256=L35iX3Ye3ZbGu__VVOE_WhQUB2oSFb0YLg7DW3E3LjY,12713
19
+ talentprism_cli-0.3.0.dist-info/licenses/talentprism_cli/LICENSE.txt,sha256=Iikp35TKg_fUatDA7RLKbTeLX3p9CmnGb4Q5IzEOaVw,853
20
+ talentprism_cli-0.3.0.dist-info/METADATA,sha256=HOKwxOdG8znXPe1NGXSjOCoWcTw88C56HPlXJsQbCSE,3607
21
+ talentprism_cli-0.3.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
22
+ talentprism_cli-0.3.0.dist-info/entry_points.txt,sha256=tPkosEbiDWaFBuR_Sqdl9aTXgGxBbj3dlv5nzZN-8Pw,53
23
+ talentprism_cli-0.3.0.dist-info/top_level.txt,sha256=J7GB4F7RwsyiYPvRxG0V4kd8_UapXSDA_szGfTR0zKk,16
24
+ talentprism_cli-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tp = talentprism_cli.__main__:main
@@ -0,0 +1,17 @@
1
+ TalentPrism CLI License
2
+
3
+ Copyright (c) 2026 TalentPrism. All rights reserved.
4
+
5
+ This software is provided for use with a TalentPrism account, under the
6
+ TalentPrism terms of service. You may install and run it on systems you
7
+ control to access TalentPrism services that you are authorized to use.
8
+
9
+ You may not modify, copy, redistribute, sublicense or sell this software,
10
+ or use it to access TalentPrism other than through your own authorized
11
+ account, without prior written permission from TalentPrism.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16
+ TALENTPRISM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING
17
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR ITS USE.
@@ -0,0 +1 @@
1
+ talentprism_cli