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.
talentprism_cli/cli.py ADDED
@@ -0,0 +1,1158 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ import uuid
7
+ from typing import Callable, TextIO
8
+ from urllib.parse import urlencode
9
+
10
+ from . import __version__
11
+ from .auth import login, logout
12
+ from .config import config_status, resolve_config, set_active_profile, set_profile_values
13
+ from .errors import TalentPrismError, missing_api_key_error
14
+ from .format import format_output
15
+ from .sequence_writes import SEQUENCE_WRITE_ACTIONS, load_sequence_file, sequence_write_request
16
+ from .skill import COMMANDS, skill_markdown
17
+ from .transport import APIClient, RequestFn
18
+
19
+
20
+ OUTPUT_FORMATS = ("json", "yaml", "table", "csv")
21
+
22
+ __all__ = ["COMMANDS", "main", "run"]
23
+
24
+
25
+ def main(argv: list[str] | None = None) -> int:
26
+ return run(argv if argv is not None else sys.argv[1:])
27
+
28
+
29
+ def run(
30
+ argv: list[str],
31
+ *,
32
+ stdout: TextIO = sys.stdout,
33
+ stderr: TextIO = sys.stderr,
34
+ is_tty: bool | None = None,
35
+ request: RequestFn | None = None,
36
+ env: dict[str, str] | None = None,
37
+ stdin: TextIO | None = None,
38
+ open_browser: Callable[[str], bool] | None = None,
39
+ ) -> int:
40
+ parser = _build_parser()
41
+ try:
42
+ args = parser.parse_args(argv)
43
+ is_tty = stdout.isatty() if is_tty is None else is_tty
44
+ output = (
45
+ "json" if getattr(args, "json", False) else getattr(args, "output", None) or ("table" if is_tty else "json")
46
+ )
47
+ if args.command == "skill" and args.action == "print":
48
+ stdout.write(skill_markdown())
49
+ return 0
50
+ if args.command in ("login", "logout"):
51
+ payload = _dispatch_auth(args, request, env, stderr, stdin, open_browser)
52
+ stdout.write(format_output(payload, output))
53
+ return 0
54
+ if args.command == "config":
55
+ payload = _dispatch_config(args, env)
56
+ stdout.write(format_output(payload, output))
57
+ return 0
58
+ config = resolve_config(
59
+ api_key=args.api_key,
60
+ base_url=args.base_url,
61
+ profile=args.profile,
62
+ config_path=args.config,
63
+ env=env,
64
+ enforce_safe_permissions=True,
65
+ )
66
+ client = APIClient(config, request=request)
67
+ payload = _dispatch(args, client, stderr)
68
+ if args.command == "whoami" and isinstance(payload, dict):
69
+ payload = {**payload, "profile": config.profile, "base_url": config.base_url}
70
+ stdout.write(format_output(payload, output))
71
+ return 0
72
+ except ValueError as exc:
73
+ if "TALENTPRISM_API_KEY" in str(exc):
74
+ error = missing_api_key_error()
75
+ else:
76
+ error = TalentPrismError(
77
+ code="invalid_input",
78
+ type="invalid_input",
79
+ message=str(exc),
80
+ remediation="Review the command arguments and try again.",
81
+ )
82
+ except TalentPrismError as exc:
83
+ error = exc
84
+
85
+ stderr.write(format_output(error.to_payload(), "json"))
86
+ return error.exit_code
87
+
88
+
89
+ def _build_parser() -> argparse.ArgumentParser:
90
+ # Shared output flags accepted after any subcommand. SUPPRESS keeps a flag
91
+ # parsed at the top level (e.g. `tp --json whoami`) from being reset by the
92
+ # subparser's default.
93
+ common = argparse.ArgumentParser(add_help=False)
94
+ common.add_argument("--output", choices=OUTPUT_FORMATS, default=argparse.SUPPRESS)
95
+ common.add_argument("--json", action="store_true", default=argparse.SUPPRESS)
96
+
97
+ parser = TalentPrismArgumentParser(prog="tp")
98
+ parser.add_argument("--version", action="version", version=f"tp {__version__}")
99
+ parser.add_argument("--api-key")
100
+ parser.add_argument("--base-url")
101
+ parser.add_argument("--profile")
102
+ parser.add_argument("--config")
103
+ parser.add_argument("--output", choices=OUTPUT_FORMATS)
104
+ parser.add_argument("--json", action="store_true")
105
+
106
+ subparsers = parser.add_subparsers(dest="command", required=True, parser_class=TalentPrismArgumentParser)
107
+ subparsers.add_parser("whoami", parents=[common])
108
+
109
+ # SUPPRESS lets `tp --profile x login` and `tp login --profile x` both work.
110
+ login_parser = subparsers.add_parser("login", parents=[common])
111
+ login_parser.add_argument("--profile", default=argparse.SUPPRESS)
112
+ login_parser.add_argument("--base-url", default=argparse.SUPPRESS)
113
+ login_parser.add_argument("--no-browser", action="store_true")
114
+ logout_parser = subparsers.add_parser("logout", parents=[common])
115
+ logout_parser.add_argument("--profile", default=argparse.SUPPRESS)
116
+
117
+ config_parser = subparsers.add_parser("config")
118
+ config_subparsers = config_parser.add_subparsers(
119
+ dest="action", required=True, parser_class=TalentPrismArgumentParser
120
+ )
121
+ config_subparsers.add_parser("get", parents=[common])
122
+ config_set = config_subparsers.add_parser("set", parents=[common])
123
+ config_set.add_argument("profile_name")
124
+ config_set.add_argument("--api-key", dest="set_api_key")
125
+ config_set.add_argument("--base-url", dest="set_base_url")
126
+ config_set_profile = config_subparsers.add_parser("set-profile", parents=[common])
127
+ config_set_profile.add_argument("profile_name")
128
+
129
+ sequence_parser = subparsers.add_parser("sequences")
130
+ sequence_subparsers = sequence_parser.add_subparsers(
131
+ dest="action", required=True, parser_class=TalentPrismArgumentParser
132
+ )
133
+ sequences_list = sequence_subparsers.add_parser("list", parents=[common])
134
+ sequences_list.add_argument("--status")
135
+ sequences_list.add_argument("--all", action="store_true")
136
+ sequences_show = sequence_subparsers.add_parser("show", parents=[common])
137
+ sequences_show.add_argument("sequence_id")
138
+ sequences_summary = sequence_subparsers.add_parser("summary", parents=[common])
139
+ sequences_summary.add_argument("sequence_id")
140
+ sequences_create = sequence_subparsers.add_parser("create", parents=[common])
141
+ sequences_create.add_argument("--file", required=True)
142
+ sequences_create.add_argument("--dry-run", action="store_true")
143
+ _add_write_approval_arguments(sequences_create)
144
+ sequences_update_step2 = sequence_subparsers.add_parser("update-step2", parents=[common])
145
+ sequences_update_step2.add_argument("sequence_id")
146
+ sequences_update_step2.add_argument("--file", required=True)
147
+ _add_write_approval_arguments(sequences_update_step2)
148
+ sequences_update_outreach = sequence_subparsers.add_parser("update-outreach", parents=[common])
149
+ sequences_update_outreach.add_argument("sequence_id")
150
+ sequences_update_outreach.add_argument("--file", required=True)
151
+ _add_write_approval_arguments(sequences_update_outreach)
152
+
153
+ candidate_parser = subparsers.add_parser("candidates")
154
+ candidate_subparsers = candidate_parser.add_subparsers(
155
+ dest="action", required=True, parser_class=TalentPrismArgumentParser
156
+ )
157
+ candidates_list = candidate_subparsers.add_parser("list", parents=[common])
158
+ candidates_list.add_argument("--sequence", required=True)
159
+ candidates_list.add_argument("--all", action="store_true")
160
+ candidates_search = candidate_subparsers.add_parser("search", parents=[common])
161
+ candidates_search.add_argument("--query", required=True)
162
+ candidates_search.add_argument("--all", action="store_true")
163
+ candidates_show = candidate_subparsers.add_parser("show", parents=[common])
164
+ candidates_show.add_argument("candidate_id")
165
+ candidates_show.add_argument("--conversations", action="store_true")
166
+ candidates_show.add_argument("--reminders", action="store_true")
167
+ candidates_add_note = candidate_subparsers.add_parser("add-note", parents=[common])
168
+ candidates_add_note.add_argument("candidate_id", type=int)
169
+ candidates_add_note.add_argument("--text", required=True)
170
+ _add_write_approval_arguments(candidates_add_note)
171
+ candidates_send_email = candidate_subparsers.add_parser("send-email", parents=[common])
172
+ candidates_send_email.add_argument("candidate_id", type=int)
173
+ candidates_send_email.add_argument("--recipient")
174
+ candidates_send_email.add_argument("--subject", required=True)
175
+ candidates_send_email.add_argument("--body", required=True)
176
+ candidates_send_email.add_argument("--idempotency-key")
177
+ _add_write_approval_arguments(candidates_send_email)
178
+ candidates_send_sms = candidate_subparsers.add_parser("send-sms", parents=[common])
179
+ candidates_send_sms.add_argument("candidate_id", type=int)
180
+ candidates_send_sms.add_argument("--recipient")
181
+ candidates_send_sms.add_argument("--message", required=True)
182
+ candidates_send_sms.add_argument("--sequence")
183
+ candidates_send_sms.add_argument("--idempotency-key")
184
+ _add_write_approval_arguments(candidates_send_sms)
185
+ candidates_engaged = candidate_subparsers.add_parser("engaged", parents=[common])
186
+ candidates_engaged.add_argument("--sequence", required=True)
187
+ candidates_engaged.add_argument("--all", action="store_true")
188
+ # Slice 2 evidence reads: the record behind a claim, not just the claim.
189
+ candidates_provenance = candidate_subparsers.add_parser("provenance", parents=[common])
190
+ candidates_provenance.add_argument("candidate_id", type=int)
191
+ candidates_provenance.add_argument("--field")
192
+ candidates_provenance.add_argument("--days", type=int)
193
+ candidates_provenance.add_argument("--limit", type=int)
194
+ candidates_timeline = candidate_subparsers.add_parser("timeline", parents=[common])
195
+ candidates_timeline.add_argument("candidate_id", type=int)
196
+ candidates_timeline.add_argument("--kinds")
197
+ candidates_timeline.add_argument("--days", type=int)
198
+ candidates_timeline.add_argument("--limit", type=int)
199
+ candidates_records = candidate_subparsers.add_parser("records", parents=[common])
200
+ candidates_records.add_argument("candidate_id", type=int)
201
+ candidates_records.add_argument("--record-type")
202
+ candidates_records.add_argument("--days", type=int)
203
+ candidates_records.add_argument("--limit", type=int)
204
+
205
+ leads_parser = subparsers.add_parser("leads")
206
+ leads_subparsers = leads_parser.add_subparsers(dest="action", required=True, parser_class=TalentPrismArgumentParser)
207
+ leads_maturity = leads_subparsers.add_parser("maturity", parents=[common])
208
+ leads_maturity.add_argument("candidate_id", type=int)
209
+ leads_consent = leads_subparsers.add_parser("consent-evidence", parents=[common])
210
+ # Optional: with no candidate this sweeps the team for decisions carrying no quote.
211
+ leads_consent.add_argument("--candidate", type=int)
212
+ leads_consent.add_argument("--limit", type=int)
213
+
214
+ reminders_parser = subparsers.add_parser("reminders")
215
+ reminders_subparsers = reminders_parser.add_subparsers(
216
+ dest="action", required=True, parser_class=TalentPrismArgumentParser
217
+ )
218
+ reminders_list = reminders_subparsers.add_parser("list", parents=[common])
219
+ reminders_list.add_argument("--owner")
220
+ reminders_list.add_argument("--due")
221
+ reminders_list.add_argument("--status")
222
+ reminders_list.add_argument("--all", action="store_true")
223
+ reminders_create = reminders_subparsers.add_parser("create", parents=[common])
224
+ reminders_create.add_argument("--candidate", type=int)
225
+ reminders_create.add_argument("--due", required=True)
226
+ reminders_create.add_argument("--text", required=True)
227
+ _add_write_approval_arguments(reminders_create)
228
+ reminders_complete = reminders_subparsers.add_parser("complete", parents=[common])
229
+ reminders_complete.add_argument("reminder_id", type=int)
230
+ _add_write_approval_arguments(reminders_complete)
231
+
232
+ capabilities_parser = subparsers.add_parser("capabilities")
233
+ capabilities_subparsers = capabilities_parser.add_subparsers(
234
+ dest="action", required=True, parser_class=TalentPrismArgumentParser
235
+ )
236
+ capabilities_subparsers.add_parser("list", parents=[common])
237
+ capabilities_subparsers.add_parser("mcp", parents=[common])
238
+ capabilities_subparsers.add_parser("commands", parents=[common])
239
+ capabilities_invoke = capabilities_subparsers.add_parser("invoke", parents=[common])
240
+ capabilities_invoke.add_argument("capability")
241
+ capabilities_invoke.add_argument("--input-json", default="{}")
242
+ _add_write_approval_arguments(capabilities_invoke)
243
+ capabilities_invoke.add_argument("--idempotency-key")
244
+ capabilities_preview = capabilities_subparsers.add_parser("preview", parents=[common])
245
+ capabilities_preview.add_argument("capability")
246
+ capabilities_preview.add_argument("--input-json", default="{}")
247
+ capabilities_verify = capabilities_subparsers.add_parser("verify", parents=[common])
248
+ capabilities_verify.add_argument("capability")
249
+ capabilities_verify.add_argument("--input-json", default="{}")
250
+
251
+ campaigns_parser = subparsers.add_parser("campaigns")
252
+ campaigns_subparsers = campaigns_parser.add_subparsers(
253
+ dest="action", required=True, parser_class=TalentPrismArgumentParser
254
+ )
255
+ campaigns_summary = campaigns_subparsers.add_parser("summary", parents=[common])
256
+ campaigns_summary.add_argument("campaign_id")
257
+ campaigns_next_actions = campaigns_subparsers.add_parser("next-actions", parents=[common])
258
+ campaigns_next_actions.add_argument("campaign_id")
259
+ campaigns_deliverability = campaigns_subparsers.add_parser("deliverability", parents=[common])
260
+ campaigns_deliverability.add_argument("campaign_id")
261
+
262
+ copilot_parser = subparsers.add_parser("copilot")
263
+ copilot_subparsers = copilot_parser.add_subparsers(
264
+ dest="action", required=True, parser_class=TalentPrismArgumentParser
265
+ )
266
+ copilot_brief = copilot_subparsers.add_parser("brief", parents=[common])
267
+ copilot_brief.add_argument("--recruiter")
268
+ copilot_brief.add_argument("--since", default="yesterday")
269
+ copilot_ask = copilot_subparsers.add_parser("ask", parents=[common])
270
+ copilot_ask.add_argument("prompt")
271
+
272
+ interview_parser = subparsers.add_parser("interviews")
273
+ interview_subparsers = interview_parser.add_subparsers(
274
+ dest="action", required=True, parser_class=TalentPrismArgumentParser
275
+ )
276
+ interviews_list = interview_subparsers.add_parser("list", parents=[common])
277
+ interviews_list.add_argument("--sequence", required=True)
278
+ interviews_list.add_argument("--all", action="store_true")
279
+ interviews_show = interview_subparsers.add_parser("show", parents=[common])
280
+ interviews_show.add_argument("interview_id")
281
+ interviews_create_link = interview_subparsers.add_parser("create-link", parents=[common])
282
+ interviews_create_link.add_argument("--candidate", required=True, type=int)
283
+ interviews_create_link.add_argument("--sequence", required=True)
284
+ interviews_create_link.add_argument("--base-url")
285
+ _add_write_approval_arguments(interviews_create_link)
286
+
287
+ recruiters_parser = subparsers.add_parser("recruiters")
288
+ recruiters_subparsers = recruiters_parser.add_subparsers(
289
+ dest="action", required=True, parser_class=TalentPrismArgumentParser
290
+ )
291
+ recruiters_notify = recruiters_subparsers.add_parser("notify", parents=[common])
292
+ recruiters_notify.add_argument("--candidate", required=True, type=int)
293
+ recruiters_notify.add_argument("--sequence", required=True)
294
+ recruiters_notify.add_argument("--update", required=True, action="append")
295
+ recruiters_notify.add_argument("--action-needed")
296
+ recruiters_notify.add_argument("--action-tag")
297
+ recruiters_notify.add_argument("--subject")
298
+ recruiters_notify.add_argument("--message")
299
+ recruiters_notify.add_argument("--force-channel", action="append")
300
+ _add_write_approval_arguments(recruiters_notify)
301
+
302
+ metrics = subparsers.add_parser("metrics", parents=[common])
303
+ metrics.add_argument("--sequence")
304
+
305
+ activity_parser = subparsers.add_parser("activity")
306
+ activity_subparsers = activity_parser.add_subparsers(
307
+ dest="action", required=True, parser_class=TalentPrismArgumentParser
308
+ )
309
+ activity_summary = activity_subparsers.add_parser("summary", parents=[common])
310
+ activity_summary.add_argument("--days", type=int, default=7)
311
+ activity_summary.add_argument("--sequence")
312
+
313
+ chats_parser = subparsers.add_parser("chats")
314
+ chats_subparsers = chats_parser.add_subparsers(dest="action", required=True, parser_class=TalentPrismArgumentParser)
315
+ chats_summary = chats_subparsers.add_parser("summary", parents=[common])
316
+ chats_summary.add_argument("--days", type=int, default=7)
317
+ chats_summary.add_argument("--sequence")
318
+ chats_summary.add_argument("--candidate", type=int)
319
+ chats_summary.add_argument("--limit", type=int)
320
+ chats_messages = chats_subparsers.add_parser("messages", parents=[common])
321
+ chats_messages.add_argument("--chat-id", type=int)
322
+ chats_messages.add_argument("--days", type=int, default=7)
323
+ chats_messages.add_argument("--sequence")
324
+ chats_messages.add_argument("--candidate", type=int)
325
+ chats_messages.add_argument("--limit", type=int)
326
+ chats_diagnose = chats_subparsers.add_parser("diagnose", parents=[common])
327
+ chats_diagnose.add_argument("--chat-id", type=int, required=True)
328
+
329
+ # `tp ops ...` replaces the hand-built `kamal app exec ... manage.py shell` one-liners that
330
+ # every prod diagnostic used to be (issue #474). Deploys stay on kamal; diagnostics do not.
331
+ ops_parser = subparsers.add_parser("ops")
332
+ ops_subparsers = ops_parser.add_subparsers(dest="action", required=True, parser_class=TalentPrismArgumentParser)
333
+ ops_delivery = ops_subparsers.add_parser("delivery-status", parents=[common])
334
+ ops_delivery.add_argument("--candidate", type=int)
335
+ ops_delivery.add_argument("--sequence")
336
+ ops_delivery.add_argument("--channel", choices=["sms", "email", "phone"])
337
+ ops_delivery.add_argument("--days", type=int, default=3)
338
+ ops_delivery.add_argument("--limit", type=int)
339
+ ops_decisions = ops_subparsers.add_parser("decision-logs", parents=[common])
340
+ ops_decisions.add_argument("--loop", choices=["nudge", "keepwarm"])
341
+ ops_decisions.add_argument("--days", type=int, default=3)
342
+ ops_decisions.add_argument("--candidate", type=int)
343
+ ops_decisions.add_argument("--chat-id", type=int)
344
+ ops_decisions.add_argument("--outcome")
345
+ ops_decisions.add_argument("--skip-reason")
346
+ ops_decisions.add_argument("--limit", type=int)
347
+
348
+ actions_parser = subparsers.add_parser("recruiter-actions")
349
+ actions_subparsers = actions_parser.add_subparsers(
350
+ dest="action", required=True, parser_class=TalentPrismArgumentParser
351
+ )
352
+ actions_list = actions_subparsers.add_parser("list", parents=[common])
353
+ actions_list.add_argument("--days", type=int, default=7)
354
+ actions_list.add_argument("--candidate", type=int)
355
+ actions_list.add_argument("--status")
356
+ actions_list.add_argument("--assignment-status")
357
+ actions_list.add_argument("--action-type")
358
+ actions_list.add_argument("--priority")
359
+ actions_list.add_argument("--unresolved", action="store_true")
360
+ actions_list.add_argument("--limit", type=int)
361
+ actions_show = actions_subparsers.add_parser("show", parents=[common])
362
+ actions_show.add_argument("action_id")
363
+ actions_complete = actions_subparsers.add_parser("complete", parents=[common])
364
+ actions_complete.add_argument("action_id")
365
+ actions_complete.add_argument("--note", default="")
366
+ _add_write_approval_arguments(actions_complete)
367
+ actions_escalate = actions_subparsers.add_parser("escalate", parents=[common])
368
+ actions_escalate.add_argument("action_id")
369
+ actions_escalate.add_argument("--reason", required=True)
370
+ actions_escalate.add_argument("--priority")
371
+ _add_write_approval_arguments(actions_escalate)
372
+
373
+ # `tp team-config ...` answers "why is this disabled" and "which number do we send from"
374
+ # without a shell. The update path deliberately takes the eval evidence as a flag, because
375
+ # the capability refuses an agent-behaviour change that records neither a run nor a waiver.
376
+ team_config_parser = subparsers.add_parser("team-config")
377
+ team_config_subparsers = team_config_parser.add_subparsers(
378
+ dest="action", required=True, parser_class=TalentPrismArgumentParser
379
+ )
380
+ team_config_read = team_config_subparsers.add_parser("read", parents=[common])
381
+ team_config_read.add_argument("--workflow", help="Explain one workflow, e.g. keepwarm or marketplace.")
382
+ team_config_subparsers.add_parser("senders", parents=[common])
383
+ team_config_compare = team_config_subparsers.add_parser("compare", parents=[common])
384
+ team_config_compare.add_argument("--other-team", type=int, required=True)
385
+ team_config_preview = team_config_subparsers.add_parser("preview-change", parents=[common])
386
+ team_config_preview.add_argument("--set", action="append", required=True, metavar="FIELD=VALUE")
387
+ team_config_update = team_config_subparsers.add_parser("update", parents=[common])
388
+ team_config_update.add_argument("--set", action="append", required=True, metavar="FIELD=VALUE")
389
+ team_config_update.add_argument("--eval-run", help="Suite, verdict and date of the eval run covering this change.")
390
+ team_config_update.add_argument("--eval-waiver", help="Why this change ships without an eval run.")
391
+ team_config_update.add_argument("--idempotency-key")
392
+ _add_write_approval_arguments(team_config_update)
393
+
394
+ skill_parser = subparsers.add_parser("skill")
395
+ skill_subparsers = skill_parser.add_subparsers(dest="action", required=True, parser_class=TalentPrismArgumentParser)
396
+ skill_subparsers.add_parser("print")
397
+ return parser
398
+
399
+
400
+ class TalentPrismArgumentParser(argparse.ArgumentParser):
401
+ def error(self, message):
402
+ raise TalentPrismError(
403
+ code="invalid_input",
404
+ type="invalid_input",
405
+ message=message,
406
+ remediation="Run the command with --help and correct the arguments.",
407
+ )
408
+
409
+
410
+ def _add_write_approval_arguments(parser: argparse.ArgumentParser) -> None:
411
+ parser.add_argument("--confirm-write", action="store_true")
412
+ parser.add_argument("--approval-token")
413
+
414
+
415
+ def _validate_write_approval_args(args: argparse.Namespace, command: str) -> None:
416
+ has_token = bool(args.approval_token)
417
+ if args.confirm_write != has_token:
418
+ raise TalentPrismError(
419
+ code="preview_bound_approval_required",
420
+ type="invalid_input",
421
+ message=f"`{command}` requires --confirm-write and --approval-token together.",
422
+ remediation=(
423
+ "Run the command without either flag to receive a non-mutating preview, then repeat the exact "
424
+ "command with both flags and the token returned by that preview."
425
+ ),
426
+ )
427
+
428
+
429
+ def _write_capability_request(
430
+ client: APIClient,
431
+ *,
432
+ capability: str,
433
+ inputs: dict,
434
+ args: argparse.Namespace,
435
+ command: str,
436
+ ):
437
+ _validate_write_approval_args(args, command)
438
+ payload = {
439
+ "capability": capability,
440
+ "inputs": inputs,
441
+ "confirmed_write": args.confirm_write,
442
+ }
443
+ if args.approval_token:
444
+ payload["approval_token"] = args.approval_token
445
+ return client.post("/api/capabilities/invoke/", payload)
446
+
447
+
448
+ def _dispatch(args: argparse.Namespace, client: APIClient, stderr: TextIO):
449
+ if args.command == "whoami":
450
+ return client.get("/api/whoami/")
451
+ if args.command == "sequences":
452
+ return _dispatch_sequences(args, client)
453
+ if args.command == "candidates":
454
+ return _dispatch_candidates(args, client)
455
+ if args.command == "leads":
456
+ return _dispatch_leads(args, client)
457
+ if args.command == "reminders":
458
+ return _dispatch_reminders(args, client)
459
+ if args.command == "capabilities":
460
+ return _dispatch_capabilities(args, client)
461
+ if args.command == "campaigns":
462
+ return _dispatch_campaigns(args, client)
463
+ if args.command == "copilot":
464
+ return _dispatch_copilot(args, client)
465
+ if args.command == "interviews":
466
+ return _dispatch_interviews(args, client)
467
+ if args.command == "recruiters":
468
+ return _dispatch_recruiters(args, client)
469
+ if args.command == "metrics":
470
+ if args.sequence:
471
+ return client.get(f"/api/sequences/{args.sequence}/metrics/")
472
+ return client.get("/api/metrics/")
473
+ if args.command == "activity":
474
+ return _dispatch_activity(args, client)
475
+ if args.command == "chats":
476
+ return _dispatch_chats(args, client)
477
+ if args.command == "ops":
478
+ return _dispatch_ops(args, client)
479
+ if args.command == "recruiter-actions":
480
+ return _dispatch_recruiter_actions(args, client)
481
+ if args.command == "team-config":
482
+ return _dispatch_team_config(args, client)
483
+ raise TalentPrismError(
484
+ code="invalid_command",
485
+ type="invalid_input",
486
+ message="Unknown command.",
487
+ remediation="Run tp --help and choose a supported command.",
488
+ )
489
+
490
+
491
+ def _dispatch_auth(args, request, env, stderr, stdin, open_browser):
492
+ if args.command == "logout":
493
+ return logout(base_url=args.base_url, profile=args.profile, config_path=args.config, env=env, request=request)
494
+ kwargs = {"open_browser": open_browser} if open_browser else {}
495
+ return login(
496
+ base_url=args.base_url,
497
+ profile=args.profile,
498
+ config_path=args.config,
499
+ env=env,
500
+ no_browser=args.no_browser,
501
+ request=request,
502
+ stderr=stderr,
503
+ stdin=stdin,
504
+ **kwargs,
505
+ )
506
+
507
+
508
+ def _dispatch_config(args: argparse.Namespace, env: dict[str, str] | None):
509
+ if args.action == "get":
510
+ return config_status(
511
+ api_key=args.api_key,
512
+ base_url=args.base_url,
513
+ profile=args.profile,
514
+ config_path=args.config,
515
+ env=env,
516
+ )
517
+ if args.action == "set":
518
+ return set_profile_values(
519
+ args.config,
520
+ args.profile_name,
521
+ api_key=args.set_api_key,
522
+ base_url=args.set_base_url,
523
+ )
524
+ if args.action == "set-profile":
525
+ return set_active_profile(args.config, args.profile_name)
526
+ raise TalentPrismError(
527
+ code="invalid_command",
528
+ type="invalid_input",
529
+ message="Unknown config command.",
530
+ remediation="Run tp config --help and choose a supported command.",
531
+ )
532
+
533
+
534
+ def _dispatch_sequences(args: argparse.Namespace, client: APIClient):
535
+ if args.action == "list":
536
+ query = urlencode({"status": args.status}) if args.status else ""
537
+ suffix = f"?{query}" if query else ""
538
+ return client.get_paginated(f"/api/sequences/{suffix}", all_pages=args.all)
539
+ if args.action == "show":
540
+ return client.get(f"/api/sequences/{args.sequence_id}/")
541
+ if args.action == "summary":
542
+ return client.get(f"/api/sequences/{args.sequence_id}/summary/")
543
+ if args.action in SEQUENCE_WRITE_ACTIONS:
544
+ if args.action == "create" and args.dry_run:
545
+ return load_sequence_file(args.file)
546
+ capability, inputs, command = sequence_write_request(args)
547
+ return _write_capability_request(client, capability=capability, inputs=inputs, args=args, command=command)
548
+ raise TalentPrismError(
549
+ code="invalid_command",
550
+ type="invalid_input",
551
+ message="Unknown sequences command.",
552
+ remediation="Run tp sequences --help and choose a supported command.",
553
+ )
554
+
555
+
556
+ def _dispatch_candidates(args: argparse.Namespace, client: APIClient):
557
+ if args.action == "list":
558
+ return client.get_paginated(f"/api/sequences/{args.sequence}/candidates/", all_pages=args.all)
559
+ if args.action == "search":
560
+ query = urlencode({"query": args.query})
561
+ return client.get_paginated(f"/api/candidates/search/?{query}", all_pages=args.all)
562
+ if args.action == "show":
563
+ params = {}
564
+ if args.conversations:
565
+ params["conversations"] = "1"
566
+ if args.reminders:
567
+ params["reminders"] = "1"
568
+ query = urlencode(params)
569
+ suffix = f"?{query}" if query else ""
570
+ return client.get(f"/api/candidates/{args.candidate_id}/{suffix}")
571
+ if args.action == "add-note":
572
+ return _write_capability_request(
573
+ client,
574
+ capability="candidates.add_note",
575
+ inputs={"candidate_id": int(args.candidate_id), "text": args.text},
576
+ args=args,
577
+ command="tp candidates add-note",
578
+ )
579
+ if args.action == "send-email":
580
+ inputs = {
581
+ "candidate_id": args.candidate_id,
582
+ "subject": args.subject,
583
+ "body": args.body,
584
+ "idempotency_key": _resolve_idempotency_key(args),
585
+ }
586
+ if args.recipient:
587
+ inputs["recipient"] = args.recipient
588
+ return _write_capability_request(
589
+ client,
590
+ capability="candidate_outreach.send_email",
591
+ inputs=inputs,
592
+ args=args,
593
+ command="tp candidates send-email",
594
+ )
595
+ if args.action == "send-sms":
596
+ inputs = {
597
+ "candidate_id": args.candidate_id,
598
+ "message": args.message,
599
+ "idempotency_key": _resolve_idempotency_key(args),
600
+ }
601
+ if args.recipient:
602
+ inputs["recipient"] = args.recipient
603
+ if args.sequence:
604
+ inputs["sequence_id"] = args.sequence
605
+ return _write_capability_request(
606
+ client,
607
+ capability="candidate_outreach.send_sms",
608
+ inputs=inputs,
609
+ args=args,
610
+ command="tp candidates send-sms",
611
+ )
612
+ if args.action == "engaged":
613
+ return client.get_paginated(f"/api/sequences/{args.sequence}/candidates/engaged/", all_pages=args.all)
614
+ if args.action == "provenance":
615
+ return _read_capability(
616
+ client,
617
+ "candidates.provenance",
618
+ {
619
+ "candidate_id": args.candidate_id,
620
+ **_optional_inputs(args, field="field", days="days", limit="limit"),
621
+ },
622
+ )
623
+ if args.action == "timeline":
624
+ return _read_capability(
625
+ client,
626
+ "candidates.timeline",
627
+ {
628
+ "candidate_id": args.candidate_id,
629
+ **_optional_inputs(args, kinds="kinds", days="days", limit="limit"),
630
+ },
631
+ )
632
+ if args.action == "records":
633
+ return _read_capability(
634
+ client,
635
+ "candidates.records",
636
+ {
637
+ "candidate_id": args.candidate_id,
638
+ **_optional_inputs(args, record_type="record_type", days="days", limit="limit"),
639
+ },
640
+ )
641
+ raise TalentPrismError(
642
+ code="invalid_command",
643
+ type="invalid_input",
644
+ message="Unknown candidates command.",
645
+ remediation="Run tp candidates --help and choose a supported command.",
646
+ )
647
+
648
+
649
+ def _dispatch_leads(args: argparse.Namespace, client: APIClient):
650
+ if args.action == "maturity":
651
+ return _read_capability(client, "leads.maturity", {"candidate_id": args.candidate_id})
652
+ if args.action == "consent-evidence":
653
+ return _read_capability(
654
+ client,
655
+ "leads.consent_evidence",
656
+ _optional_inputs(args, candidate="candidate_id", limit="limit"),
657
+ )
658
+ raise TalentPrismError(
659
+ code="invalid_command",
660
+ type="invalid_input",
661
+ message="Unknown leads command.",
662
+ remediation="Run tp leads --help and choose a supported command.",
663
+ )
664
+
665
+
666
+ def _dispatch_reminders(args: argparse.Namespace, client: APIClient):
667
+ if args.action == "list":
668
+ params = {}
669
+ if args.owner:
670
+ params["owner"] = args.owner
671
+ if args.due:
672
+ params["due"] = args.due
673
+ if args.status:
674
+ params["status"] = args.status
675
+ query = urlencode(params)
676
+ suffix = f"?{query}" if query else ""
677
+ return client.get_paginated(f"/api/reminders/{suffix}", all_pages=args.all)
678
+ if args.action == "create":
679
+ payload = {"candidate_id": args.candidate, "due": args.due, "text": args.text}
680
+ if args.candidate is None:
681
+ payload.pop("candidate_id")
682
+ return _write_capability_request(
683
+ client,
684
+ capability="reminders.create",
685
+ inputs=payload,
686
+ args=args,
687
+ command="tp reminders create",
688
+ )
689
+ if args.action == "complete":
690
+ return _write_capability_request(
691
+ client,
692
+ capability="reminders.complete",
693
+ inputs={"reminder_id": args.reminder_id},
694
+ args=args,
695
+ command="tp reminders complete",
696
+ )
697
+ raise TalentPrismError(
698
+ code="invalid_command",
699
+ type="invalid_input",
700
+ message="Unknown reminders command.",
701
+ remediation="Run tp reminders --help and choose a supported command.",
702
+ )
703
+
704
+
705
+ def _dispatch_capabilities(args: argparse.Namespace, client: APIClient):
706
+ if args.action == "list":
707
+ return client.get("/api/capabilities/")
708
+ if args.action == "mcp":
709
+ return client.get("/api/capabilities/mcp/")
710
+ if args.action == "commands":
711
+ return _capability_commands(client.get("/api/capabilities/"))
712
+ if args.action == "invoke":
713
+ if args.confirm_write != bool(args.approval_token):
714
+ raise TalentPrismError(
715
+ code="preview_bound_approval_required",
716
+ type="invalid_input",
717
+ message="--confirm-write and --approval-token must be passed together.",
718
+ remediation=(
719
+ "Run `tp capabilities preview` first, then invoke with the exact same inputs, "
720
+ "--confirm-write, and the returned approval token."
721
+ ),
722
+ )
723
+ inputs = _load_json_object(args.input_json)
724
+ if getattr(args, "idempotency_key", None):
725
+ inputs["idempotency_key"] = args.idempotency_key
726
+ request_payload = {
727
+ "capability": args.capability,
728
+ "inputs": inputs,
729
+ "confirmed_write": args.confirm_write,
730
+ }
731
+ if args.approval_token:
732
+ request_payload["approval_token"] = args.approval_token
733
+ return client.post(
734
+ "/api/capabilities/invoke/",
735
+ request_payload,
736
+ )
737
+ if args.action in {"preview", "verify"}:
738
+ # Preview and verify are reads: no --confirm-write, even for a write capability.
739
+ return client.post(
740
+ "/api/capabilities/invoke/",
741
+ {
742
+ "capability": args.capability,
743
+ "inputs": _load_json_object(args.input_json),
744
+ "action": args.action,
745
+ "confirmed_write": False,
746
+ },
747
+ )
748
+ raise TalentPrismError(
749
+ code="invalid_command",
750
+ type="invalid_input",
751
+ message="Unknown capabilities command.",
752
+ remediation="Run tp capabilities --help and choose a supported command.",
753
+ )
754
+
755
+
756
+ def _dispatch_activity(args: argparse.Namespace, client: APIClient):
757
+ if args.action == "summary":
758
+ inputs = {"days": args.days}
759
+ if args.sequence:
760
+ inputs["sequence_id"] = args.sequence
761
+ return client.post(
762
+ "/api/capabilities/invoke/",
763
+ {
764
+ "capability": "activity.summary",
765
+ "inputs": inputs,
766
+ "confirmed_write": False,
767
+ },
768
+ )
769
+ raise TalentPrismError(
770
+ code="invalid_command",
771
+ type="invalid_input",
772
+ message="Unknown activity command.",
773
+ remediation="Run tp activity --help and choose a supported command.",
774
+ )
775
+
776
+
777
+ def _dispatch_chats(args: argparse.Namespace, client: APIClient):
778
+ inputs = {}
779
+ if getattr(args, "days", None) is not None:
780
+ inputs["days"] = args.days
781
+ if getattr(args, "sequence", None):
782
+ inputs["sequence_id"] = args.sequence
783
+ if getattr(args, "candidate", None) is not None:
784
+ inputs["candidate_id"] = args.candidate
785
+ if getattr(args, "limit", None) is not None:
786
+ inputs["limit"] = args.limit
787
+ if args.action == "summary":
788
+ return client.post(
789
+ "/api/capabilities/invoke/",
790
+ {"capability": "chats.summary", "inputs": inputs, "confirmed_write": False},
791
+ )
792
+ if args.action == "messages":
793
+ if args.chat_id is not None:
794
+ inputs["chat_id"] = args.chat_id
795
+ return client.post(
796
+ "/api/capabilities/invoke/",
797
+ {"capability": "chats.messages", "inputs": inputs, "confirmed_write": False},
798
+ )
799
+ if args.action == "diagnose":
800
+ return _read_capability(client, "chats.diagnose", {"chat_id": args.chat_id})
801
+ raise TalentPrismError(
802
+ code="invalid_command",
803
+ type="invalid_input",
804
+ message="Unknown chats command.",
805
+ remediation="Run tp chats --help and choose a supported command.",
806
+ )
807
+
808
+
809
+ def _dispatch_ops(args: argparse.Namespace, client: APIClient):
810
+ if args.action == "delivery-status":
811
+ return _read_capability(
812
+ client,
813
+ "ops.delivery_status",
814
+ _optional_inputs(
815
+ args,
816
+ candidate="candidate_id",
817
+ sequence="sequence_id",
818
+ channel="channel",
819
+ days="days",
820
+ limit="limit",
821
+ ),
822
+ )
823
+ if args.action == "decision-logs":
824
+ return _read_capability(
825
+ client,
826
+ "ops.decision_logs",
827
+ _optional_inputs(
828
+ args,
829
+ loop="loop",
830
+ days="days",
831
+ candidate="candidate_id",
832
+ chat_id="chat_id",
833
+ outcome="outcome",
834
+ skip_reason="skip_reason",
835
+ limit="limit",
836
+ ),
837
+ )
838
+ raise TalentPrismError(
839
+ code="invalid_command",
840
+ type="invalid_input",
841
+ message="Unknown ops command.",
842
+ remediation="Run tp ops --help and choose a supported command.",
843
+ )
844
+
845
+
846
+ def _dispatch_recruiter_actions(args: argparse.Namespace, client: APIClient):
847
+ if args.action == "list":
848
+ return _read_capability(
849
+ client,
850
+ "recruiter_actions.list",
851
+ _optional_inputs(
852
+ args,
853
+ days="days",
854
+ candidate="candidate_id",
855
+ status="status",
856
+ assignment_status="assignment_status",
857
+ action_type="action_type",
858
+ priority="priority",
859
+ unresolved="unresolved",
860
+ limit="limit",
861
+ ),
862
+ )
863
+ if args.action == "show":
864
+ return _read_capability(client, "recruiter_actions.show", {"action_id": args.action_id})
865
+ if args.action == "complete":
866
+ return _write_capability_request(
867
+ client,
868
+ capability="recruiter_actions.complete",
869
+ inputs={"action_id": args.action_id, "note": args.note},
870
+ args=args,
871
+ command="tp recruiter-actions complete",
872
+ )
873
+ if args.action == "escalate":
874
+ inputs = {"action_id": args.action_id, "reason": args.reason}
875
+ if args.priority:
876
+ inputs["priority"] = args.priority
877
+ return _write_capability_request(
878
+ client,
879
+ capability="recruiter_actions.escalate",
880
+ inputs=inputs,
881
+ args=args,
882
+ command="tp recruiter-actions escalate",
883
+ )
884
+ raise TalentPrismError(
885
+ code="invalid_command",
886
+ type="invalid_input",
887
+ message="Unknown recruiter-actions command.",
888
+ remediation="Run tp recruiter-actions --help and choose a supported command.",
889
+ )
890
+
891
+
892
+ def _dispatch_team_config(args: argparse.Namespace, client: APIClient):
893
+ if args.action == "read":
894
+ return _read_capability(client, "team_config.read", _optional_inputs(args, workflow="workflow"))
895
+ if args.action == "senders":
896
+ return _read_capability(client, "team_config.senders", {})
897
+ if args.action == "compare":
898
+ return _read_capability(client, "team_config.compare", {"other_team_id": args.other_team})
899
+ if args.action == "preview-change":
900
+ # The standalone read capability, not `preview` on the write: a recruiter who is only a
901
+ # member can ask what a change would do without being able to make it.
902
+ return _read_capability(client, "team_config.preview_change", {"changes": _parse_settings(args.set)})
903
+ if args.action == "update":
904
+ inputs: dict = {"changes": _parse_settings(args.set)}
905
+ if args.eval_run:
906
+ inputs["eval_run_ref"] = args.eval_run
907
+ if args.eval_waiver:
908
+ inputs["eval_waiver_reason"] = args.eval_waiver
909
+ if args.idempotency_key:
910
+ inputs["idempotency_key"] = args.idempotency_key
911
+ return _write_capability_request(
912
+ client,
913
+ capability="team_config.update",
914
+ inputs=inputs,
915
+ args=args,
916
+ command="tp team-config update",
917
+ )
918
+ raise TalentPrismError(
919
+ code="invalid_command",
920
+ type="invalid_input",
921
+ message="Unknown team-config command.",
922
+ remediation="Run tp team-config --help and choose a supported command.",
923
+ )
924
+
925
+
926
+ def _parse_settings(pairs: list[str]) -> dict:
927
+ """Parse --set FIELD=VALUE flags. Typed values stay typed so the server sees a real boolean.
928
+
929
+ An unrecognised field is not silently dropped here: the capability refuses it by name, which
930
+ is a better error than a write that reports success having applied nothing.
931
+ """
932
+ settings: dict = {}
933
+ for raw in pairs or []:
934
+ if "=" not in raw:
935
+ raise TalentPrismError(
936
+ code="invalid_input",
937
+ type="invalid_input",
938
+ message=f"--set expects FIELD=VALUE, got {raw!r}.",
939
+ remediation="Pass settings as --set nudge_enabled=true.",
940
+ )
941
+ field, _, value = raw.partition("=")
942
+ settings[field.strip()] = _coerce_setting(value.strip())
943
+ return settings
944
+
945
+
946
+ def _coerce_setting(value: str):
947
+ lowered = value.lower()
948
+ if lowered in {"true", "yes", "on"}:
949
+ return True
950
+ if lowered in {"false", "no", "off"}:
951
+ return False
952
+ if lowered in {"", "unset", "null", "none"}:
953
+ return None
954
+ try:
955
+ return float(value) if "." in value else int(value)
956
+ except ValueError:
957
+ return value
958
+
959
+
960
+ def _read_capability(client: APIClient, capability: str, inputs: dict):
961
+ return client.post(
962
+ "/api/capabilities/invoke/",
963
+ {"capability": capability, "inputs": inputs, "confirmed_write": False},
964
+ )
965
+
966
+
967
+ def _optional_inputs(args: argparse.Namespace, **mapping: str) -> dict:
968
+ """Map set CLI flags onto capability inputs, dropping the ones the operator omitted."""
969
+ inputs = {}
970
+ for arg_name, input_name in mapping.items():
971
+ value = getattr(args, arg_name, None)
972
+ if value not in (None, "", False):
973
+ inputs[input_name] = value
974
+ return inputs
975
+
976
+
977
+ def _dispatch_campaigns(args: argparse.Namespace, client: APIClient):
978
+ if args.action == "summary":
979
+ return client.get(f"/api/campaigns/{args.campaign_id}/summary/")
980
+ if args.action == "next-actions":
981
+ return client.get(f"/api/campaigns/{args.campaign_id}/next-actions/")
982
+ if args.action == "deliverability":
983
+ return client.post(
984
+ "/api/capabilities/invoke/",
985
+ {
986
+ "capability": "campaigns.deliverability",
987
+ "inputs": {"sequence_id": args.campaign_id},
988
+ "confirmed_write": False,
989
+ },
990
+ )
991
+ raise TalentPrismError(
992
+ code="invalid_command",
993
+ type="invalid_input",
994
+ message="Unknown campaigns command.",
995
+ remediation="Run tp campaigns --help and choose a supported command.",
996
+ )
997
+
998
+
999
+ def _dispatch_copilot(args: argparse.Namespace, client: APIClient):
1000
+ if args.action == "brief":
1001
+ return client.post("/api/copilot/brief/", {"recruiter_id": args.recruiter, "since": args.since})
1002
+ if args.action == "ask":
1003
+ return client.post("/api/copilot/ask/", {"prompt": args.prompt})
1004
+ raise TalentPrismError(
1005
+ code="invalid_command",
1006
+ type="invalid_input",
1007
+ message="Unknown copilot command.",
1008
+ remediation="Run tp copilot --help and choose a supported command.",
1009
+ )
1010
+
1011
+
1012
+ def _dispatch_interviews(args: argparse.Namespace, client: APIClient):
1013
+ if args.action == "list":
1014
+ return client.get_paginated(f"/api/sequences/{args.sequence}/interviews/", all_pages=args.all)
1015
+ if args.action == "show":
1016
+ return client.get(f"/api/interviews/{args.interview_id}/")
1017
+ if args.action == "create-link":
1018
+ inputs = {"candidate_id": args.candidate, "sequence_id": args.sequence}
1019
+ if args.base_url:
1020
+ inputs["base_url"] = args.base_url
1021
+ return _write_capability_request(
1022
+ client,
1023
+ capability="interviews.create_link",
1024
+ inputs=inputs,
1025
+ args=args,
1026
+ command="tp interviews create-link",
1027
+ )
1028
+ raise TalentPrismError(
1029
+ code="invalid_command",
1030
+ type="invalid_input",
1031
+ message="Unknown interviews command.",
1032
+ remediation="Run tp interviews --help and choose a supported command.",
1033
+ )
1034
+
1035
+
1036
+ def _dispatch_recruiters(args: argparse.Namespace, client: APIClient):
1037
+ if args.action == "notify":
1038
+ inputs = {
1039
+ "candidate_id": args.candidate,
1040
+ "sequence_id": args.sequence,
1041
+ "update_items": args.update,
1042
+ }
1043
+ if args.action_needed:
1044
+ inputs["action_needed"] = args.action_needed
1045
+ if args.action_tag:
1046
+ inputs["action_tag"] = args.action_tag
1047
+ if args.subject:
1048
+ inputs["subject"] = args.subject
1049
+ if args.message:
1050
+ inputs["message"] = args.message
1051
+ if args.force_channel:
1052
+ inputs["force_channels"] = args.force_channel
1053
+ return _write_capability_request(
1054
+ client,
1055
+ capability="recruiter_notifications.send",
1056
+ inputs=inputs,
1057
+ args=args,
1058
+ command="tp recruiters notify",
1059
+ )
1060
+ raise TalentPrismError(
1061
+ code="invalid_command",
1062
+ type="invalid_input",
1063
+ message="Unknown recruiters command.",
1064
+ remediation="Run tp recruiters --help and choose a supported command.",
1065
+ )
1066
+
1067
+
1068
+ def _resolve_idempotency_key(args: argparse.Namespace) -> str:
1069
+ """Candidate-facing sends require an idempotency key; a person typing the command is the
1070
+ idempotency boundary, so generate one when the operator does not supply their own.
1071
+
1072
+ The requirement exists to stop programmatic retries and agent loops from double-sending, not
1073
+ to make a human invent a UUID. Pass --idempotency-key to make a retry of this exact command
1074
+ replay instead of sending again.
1075
+ """
1076
+ idempotency_key = getattr(args, "idempotency_key", None)
1077
+ if getattr(args, "approval_token", None) and not idempotency_key:
1078
+ raise TalentPrismError(
1079
+ code="idempotency_key_required",
1080
+ type="invalid_input",
1081
+ message="The approved send must reuse the idempotency key from its preview.",
1082
+ remediation="Copy inputs.idempotency_key from the preview and pass it with --idempotency-key.",
1083
+ )
1084
+ return idempotency_key or f"tp-cli-{uuid.uuid4()}"
1085
+
1086
+
1087
+ def _load_json_object(value: str) -> dict:
1088
+ try:
1089
+ payload = json.loads(value)
1090
+ except ValueError as exc:
1091
+ raise TalentPrismError(
1092
+ code="invalid_input",
1093
+ type="invalid_input",
1094
+ message="--input-json must be valid JSON.",
1095
+ remediation='Pass a JSON object such as \'{"query": "avery"}\'.',
1096
+ ) from exc
1097
+ if not isinstance(payload, dict):
1098
+ raise TalentPrismError(
1099
+ code="invalid_input",
1100
+ type="invalid_input",
1101
+ message="--input-json must be a JSON object.",
1102
+ remediation='Pass key-value capability inputs such as \'{"query": "avery"}\'.',
1103
+ )
1104
+ return payload
1105
+
1106
+
1107
+ def _capability_commands(manifest: dict) -> dict:
1108
+ return {
1109
+ "commands": [_capability_command(capability) for capability in manifest.get("capabilities", [])],
1110
+ }
1111
+
1112
+
1113
+ def _capability_command(capability: dict) -> dict:
1114
+ inputs = _capability_input_example(capability.get("input_schema") or {})
1115
+ serialized_inputs = json.dumps(inputs, separators=(",", ":"))
1116
+ command = f"tp capabilities invoke {capability['name']} --input-json '{serialized_inputs}'"
1117
+ if capability.get("risk") == "write":
1118
+ command = f"{command} --confirm-write --approval-token <token-from-preview>"
1119
+ preview = capability.get("preview") or {}
1120
+ verify = capability.get("verify") or {}
1121
+ entry = {
1122
+ "capability": capability["name"],
1123
+ "description": capability.get("description", ""),
1124
+ "risk": capability.get("risk", "read"),
1125
+ "command": command,
1126
+ "preview_supported": bool(preview.get("supported")),
1127
+ "verify_supported": bool(verify.get("supported")),
1128
+ }
1129
+ if preview.get("supported"):
1130
+ entry["preview_command"] = f"tp capabilities preview {capability['name']} --input-json '{serialized_inputs}'"
1131
+ entry["preview_completeness"] = preview.get("completeness", "complete")
1132
+ if preview.get("partial_reason"):
1133
+ entry["preview_partial_reason"] = preview["partial_reason"]
1134
+ if verify.get("supported"):
1135
+ entry["verify_command"] = f"tp capabilities verify {capability['name']} --input-json '{serialized_inputs}'"
1136
+ return entry
1137
+
1138
+
1139
+ def _capability_input_example(schema: dict) -> dict:
1140
+ properties = schema.get("properties") if isinstance(schema, dict) else {}
1141
+ if not isinstance(properties, dict):
1142
+ return {}
1143
+ return {name: _schema_value_example(definition) for name, definition in properties.items()}
1144
+
1145
+
1146
+ def _schema_value_example(definition: dict) -> object:
1147
+ value_type = definition.get("type") if isinstance(definition, dict) else None
1148
+ if value_type == "integer":
1149
+ return 0
1150
+ if value_type == "number":
1151
+ return 0
1152
+ if value_type == "boolean":
1153
+ return False
1154
+ if value_type == "array":
1155
+ return []
1156
+ if value_type == "object":
1157
+ return {}
1158
+ return "<string>"