stackshift 1.3.1__tar.gz → 1.7.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 (71) hide show
  1. {stackshift-1.3.1/stackshift.egg-info → stackshift-1.7.0}/PKG-INFO +162 -2
  2. stackshift-1.3.1/PKG-INFO → stackshift-1.7.0/README.md +157 -9
  3. {stackshift-1.3.1 → stackshift-1.7.0}/pyproject.toml +7 -1
  4. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/__init__.py +48 -0
  5. stackshift-1.7.0/stackshift/agents.py +98 -0
  6. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/client.py +30 -2
  7. stackshift-1.7.0/stackshift/databases.py +226 -0
  8. stackshift-1.7.0/stackshift/hosted_agents.py +78 -0
  9. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail.py +6 -0
  10. stackshift-1.7.0/stackshift/mail_agent_inboxes.py +199 -0
  11. stackshift-1.7.0/stackshift/mail_agreements.py +158 -0
  12. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail_events_webhooks.py +5 -1
  13. stackshift-1.7.0/stackshift/mail_inbox_webhooks.py +89 -0
  14. stackshift-1.7.0/stackshift/mail_team_inboxes.py +148 -0
  15. stackshift-1.7.0/stackshift/partner.py +251 -0
  16. stackshift-1.3.1/README.md → stackshift-1.7.0/stackshift.egg-info/PKG-INFO +169 -1
  17. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift.egg-info/SOURCES.txt +14 -0
  18. stackshift-1.7.0/tests/test_agents.py +129 -0
  19. stackshift-1.7.0/tests/test_databases.py +441 -0
  20. stackshift-1.7.0/tests/test_hosted_agents.py +116 -0
  21. stackshift-1.7.0/tests/test_mail_agent_inboxes.py +203 -0
  22. stackshift-1.7.0/tests/test_mail_agreements.py +153 -0
  23. stackshift-1.7.0/tests/test_mail_inbox_webhooks.py +81 -0
  24. stackshift-1.7.0/tests/test_mail_team_inboxes.py +114 -0
  25. stackshift-1.7.0/tests/test_partner.py +159 -0
  26. stackshift-1.3.1/stackshift/partner.py +0 -93
  27. stackshift-1.3.1/tests/test_partner.py +0 -82
  28. {stackshift-1.3.1 → stackshift-1.7.0}/setup.cfg +0 -0
  29. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/ai_credits.py +0 -0
  30. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/assets.py +0 -0
  31. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/assets_dam.py +0 -0
  32. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/assets_media.py +0 -0
  33. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/assets_platform.py +0 -0
  34. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/assets_video.py +0 -0
  35. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/assets_workflows.py +0 -0
  36. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail_advanced.py +0 -0
  37. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail_billing.py +0 -0
  38. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail_brands.py +0 -0
  39. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail_campaigns.py +0 -0
  40. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail_exports.py +0 -0
  41. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail_mailboxes.py +0 -0
  42. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail_marketing.py +0 -0
  43. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail_migration.py +0 -0
  44. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail_reputation.py +0 -0
  45. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail_streams.py +0 -0
  46. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/mail_tracking.py +0 -0
  47. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/projects.py +0 -0
  48. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/support_action_manifest.py +0 -0
  49. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/support_action_receiver.py +0 -0
  50. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/support_action_sqlite.py +0 -0
  51. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/support_action_types.py +0 -0
  52. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/support_actions.py +0 -0
  53. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift/workload_security.py +0 -0
  54. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift.egg-info/dependency_links.txt +0 -0
  55. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift.egg-info/requires.txt +0 -0
  56. {stackshift-1.3.1 → stackshift-1.7.0}/stackshift.egg-info/top_level.txt +0 -0
  57. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_ai_credits.py +0 -0
  58. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_assets_media.py +0 -0
  59. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_assets_platform.py +0 -0
  60. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_assets_workflows.py +0 -0
  61. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_mail.py +0 -0
  62. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_mail_advanced.py +0 -0
  63. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_mail_diagnostics.py +0 -0
  64. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_mail_events_webhooks.py +0 -0
  65. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_mail_exports.py +0 -0
  66. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_mail_mailboxes.py +0 -0
  67. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_mail_platform.py +0 -0
  68. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_mail_simulation.py +0 -0
  69. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_mail_subscribers.py +0 -0
  70. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_mail_tracking.py +0 -0
  71. {stackshift-1.3.1 → stackshift-1.7.0}/tests/test_support_actions.py +0 -0
@@ -1,7 +1,11 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stackshift
3
- Version: 1.3.1
3
+ Version: 1.7.0
4
4
  Summary: Official Python SDK for StackShift.
5
+ Author-email: StackShift <support@stackshift.cloud>
6
+ Project-URL: Homepage, https://stackshift.cloud
7
+ Project-URL: Documentation, https://docs.stackshift.cloud
8
+ Classifier: Programming Language :: Python :: 3
5
9
  Requires-Python: >=3.9
6
10
  Description-Content-Type: text/markdown
7
11
  Requires-Dist: requests>=2.31
@@ -33,7 +37,54 @@ domain = stackshift.partner.purchase_domain(
33
37
  status = stackshift.partner.get_domain(domain["id"])
34
38
  ```
35
39
 
36
- `partner` also exposes `overview`, `update_settings`, `list_domains` (with `q` and `attention` to find the merchants that need you), `retry_domain`, `get_diagnosis`, `restore_dns`, `transfer_out`, `resume_brand`, `get_complaints`, `list_complaint_sources`, `suppress_never_opened`, `undo_suppression`, `usage`, `list_requests` and `create_request`. `transfer_out` needs the `partner:transfer` scope (or `*`); `partner:manage` alone is refused. Purchases are capped at 30 per minute and, per partner, at 25 domains in a rolling 24 hours (429 `daily_purchase_limit`; staff can raise it). Validation errors are 400, state conflicts are 409. The `brand` and `replies` dictionaries use API camelCase keys.
40
+ `partner` also exposes `overview`, `update_settings`, `list_domains` (with `q`, `attention` and `website` to find the merchants that need you), `connect_domain` and `transfer_in_domain` / `transfer_in_connected_domain` / `switch_transfer_nameservers` for domains the merchant already owns, `set_website`, `remove_website`, `check_website` and `list_website_projects` for the storefront, `list_mailboxes`, `create_mailbox`, `update_mailbox`, `create_mailbox_password_link`, `pause_mailbox`, `resume_mailbox`, `remove_mailbox`, `create_alias`, `update_alias` and `remove_alias` for merchant mailboxes, `start_mail_migration`, `get_mail_migration`, `switch_mail_migration`, `cancel_mail_migration`, `retry_mail_migration`, `retry_mail_migration_account` and `skip_mail_migration_account` for moving old email in, `retry_domain`, `get_diagnosis`, `restore_dns`, `transfer_out`, `resume_brand`, `get_complaints`, `list_complaint_sources`, `suppress_never_opened`, `undo_suppression`, `usage`, `list_requests` and `create_request`. `transfer_out` needs the `partner:transfer` scope (or `*`); `partner:manage` alone is refused. Purchases are capped at 30 per minute and, per partner, at 25 domains in a rolling 24 hours (429 `daily_purchase_limit`; staff can raise it). Validation errors are 400, state conflicts are 409. The `brand` and `replies` dictionaries use API camelCase keys.
41
+
42
+ ## Connected agents
43
+
44
+ An agent that holds a connection credential (issued by the owner, not an account API key) can use the same API the MCP tools and the CLI use:
45
+
46
+ ```python
47
+ stackshift = StackShift(api_key=os.environ["STACKSHIFT_CONNECTION_CREDENTIAL"])
48
+ before = stackshift.agents.connections.identity().get("before_each_change")
49
+ operation = stackshift.agents.connections.operations.propose(
50
+ action="deployment.restart", resource_id=project_id, configuration={},
51
+ reason="Restart after the config fix", idempotency_key="restart-shop-1",
52
+ )
53
+ waited = stackshift.agents.connections.operations.wait(operation["id"])
54
+ while not waited["settled"]:
55
+ waited = stackshift.agents.connections.operations.wait(operation["id"])
56
+ ```
57
+
58
+ `agents.connections` has `identity`, `resources`, `capabilities`, `plan`, `task_facts(objective_id)`, `history` and `lower_level(level=..., expected_version=...)`; `agents.connections.operations` has `list`, `propose`, `get`, `wait` and `approval`. `propose` needs an `idempotency_key`: keep it and send the same one to retry. `wait` returns `settled: False` when the owner has not decided yet; call it again instead of proposing again. `approval(id)` says whether the owner has decided, with `review_url` for the owner. `lower_level` only makes the connection stricter; raising a level raises `StackShiftAPIError` with `code` `session_required`.
59
+
60
+ ## Manage the agents you run on StackShift
61
+
62
+ `hosted_agents` manages agents that run on StackShift from your own code or a script. It is separate from `agents`, which is for agents that hold a connection credential.
63
+
64
+ ```python
65
+ stackshift = StackShift(api_key=os.environ["STACKSHIFT_API_KEY"])
66
+ agent = stackshift.hosted_agents.create(
67
+ {"name": "Supplies agent", "source": {"template": "inbox-helper", "language": "python"}, "level": "ask_every_time"},
68
+ idempotency_key="supplies-agent-1",
69
+ )
70
+ stackshift.hosted_agents.secrets.set(agent["id"], "SHOP_API_KEY", os.environ["SHOP_API_KEY"])
71
+ stackshift.hosted_agents.budget.set(agent["id"], {"ai_credits_per_month": 200000, "compute_per_day": {"NGN": "5000000"}})
72
+ stackshift.hosted_agents.deploy(agent["id"], branch="main")
73
+ runs = stackshift.hosted_agents.runs(agent["id"], limit=10)
74
+ ```
75
+
76
+ `hosted_agents` has `list`, `get`, `create`, `deploy`, `rollback(id, version)`, `stop(id, reason=None)`, `start`, `delete`, `runs`, `run`, `spend(id, days=None)` and `logs(id, offset=None)`, plus `secrets.set`, `secrets.unset` and `budget.set`. `create` needs an `idempotency_key`: keep it and send the same one to retry. Money amounts are in minor units (kobo or cents). To write the agent itself, use `stackshift-agent`.
77
+
78
+ ## Databases: Branches and Sleep when idle
79
+
80
+ Branches give you a copy of a database for a test run, a preview or a pull request. `with_branch` makes one, waits until it is ready and always deletes it when the block ends:
81
+
82
+ ```python
83
+ with stackshift.databases.branches.with_branch(database_id) as branch:
84
+ run_migrations_and_tests(branch["url"])
85
+ ```
86
+
87
+ If the block raises, that error is the one you get back (a failed cleanup is attached as `cleanup_error`); a slow create is waited out before the Branch is deleted (`cleanup_timeout`, default 10 minutes). `branch["url"]` is the shared (pooled) connection string; pass `direct=True` for the direct one. `databases.branches` also has `list`, `create`, `get`, `update`, `delete`, `reset`, `retry` (a failed Branch), `promote`, `operation`, `wait_for_operation`, `url`, `options` (what a new Branch can start from), `changes` and `resume_scheduled_jobs`. `list` also returns your plan `allowance`. `create`, `reset`, `retry`, `promote` and `delete` return an operation; `wait_for_operation` polls it until it succeeds or fails. `reset`, `retry`, `promote` and `delete` send an `Idempotency-Key` (a new one for each call if you do not pass `idempotency_key`). Deleting with `cascade=True` also needs `confirm_name` (the Branch's name), or a `ValueError` is raised before the call is sent. `promote` accepts the parent's name or, when the parent is a Branch, its short name. `databases.sleep`, `databases.wake`, `databases.billing`, `databases.branch_usage`, `databases.pay_branch_usage`, `databases.scheduled_jobs`, `databases.wake_events`, `databases.move_to_instant_branches` and `databases.instant_branches_move` cover Sleep when idle and the move to instant Branches. Refusals raise `StackShiftAPIError` with `code` set to values such as `plan_limit`, `no_capacity`, `outside_window`, `too_large` and `payment_required`. On a Dedicated database, `create` and `retry` first raise `price_confirmation_required` with the price in `error.details["quote"]`; send the same call again with `confirm_charge_minor=error.details["quote"]["charge_minor"]`. `create` also takes `instance_class` to pick the size of a Dedicated Branch, and a Dedicated Branch carries its `cost`. A `plan_limit` error carries `limit`, `current` and `upgrade_url` in `details`.
37
88
 
38
89
  ## AI credits
39
90
 
@@ -149,6 +200,115 @@ stackshift.mail.mailboxes.suspend(mailbox["id"])
149
200
 
150
201
  `stackshift.mail.groups` manages team addresses, and `stackshift.mail.mailbox_imports` copies mail from Google, Microsoft or any IMAP server.
151
202
 
203
+ ## Give your agent an email address in one call
204
+
205
+ Agent inboxes are real addresses on StackShift's shared domain. Create one, let your agent sign up somewhere, wait for the verification code and delete the inbox when the job is done.
206
+
207
+ ```python
208
+ inbox = stackshift.mail.agent_inboxes.create(
209
+ prefix="signup",
210
+ labels={"job": "onboarding-42"},
211
+ job_id="onboarding-42",
212
+ expires_in=3600,
213
+ idempotency_key="onboarding-42-inbox",
214
+ )
215
+
216
+ sign_up_somewhere(inbox["address"])
217
+
218
+ message = stackshift.mail.agent_inboxes.wait_for_message(
219
+ inbox["id"],
220
+ sender="paystack.com",
221
+ timeout=120,
222
+ since=inbox["createdAt"],
223
+ )
224
+ if message:
225
+ print(message["codes"][0], message["links"])
226
+
227
+ stackshift.mail.agent_inboxes.finish_job("onboarding-42")
228
+ ```
229
+
230
+ `wait_for_message` calls the server wait endpoint in turns of up to 50 seconds until a message arrives or `timeout` (seconds, default 30) is used up, and returns `None` on timeout. Pass `since` (usually `inbox["createdAt"]`) so a message that arrived before you started waiting is found. `delete_many` takes `ids`, `job_id` or `labels`; `finish_job(job_id)` is the same as `delete_many(job_id=...)`. `create_batch` makes up to 100 inboxes at once.
231
+
232
+ Read mail with `agent_inboxes.messages.list`, `messages.latest(sender=..., subject=...)` and `messages.get`. Find inboxes with `agent_inboxes.list(labels=..., job_id=..., q=..., domain=..., limit=..., cursor=...)`, change them with `update`, remove one with `delete`, and check what your account may do with `limits()` and `pricing()`.
233
+
234
+ Sending never hides an approval. `send` returns `status` as `sent`, `waiting_approval` or `draft`, plus `pendingReplyId` and `reasons` when a person has to approve first:
235
+
236
+ ```python
237
+ result = stackshift.mail.agent_inboxes.send(
238
+ inbox["id"],
239
+ to=["ada@example.com"],
240
+ subject="Re: your question",
241
+ text="Thanks, here is the answer.",
242
+ reply_to_message_id=message["id"],
243
+ )
244
+ if result["status"] == "waiting_approval":
245
+ print("Waiting for a person to approve", result["pendingReplyId"], result["reasons"])
246
+ ```
247
+
248
+ ### Team inboxes
249
+
250
+ Team inboxes are shared mailboxes your people and agents work together. Use the mailbox id:
251
+
252
+ ```python
253
+ page = stackshift.mail.team_inboxes.conversations.list(mailbox_id, status="open", assignee="nobody")
254
+ thread = page["conversations"][0]
255
+ stackshift.mail.team_inboxes.conversations.assign(mailbox_id, thread["threadId"], worker_id=worker_id, expected_revision=thread["revision"])
256
+ stackshift.mail.team_inboxes.conversations.add_note(mailbox_id, thread["threadId"], body="Checked the logs, restarting the app.")
257
+
258
+ waiting = stackshift.mail.team_inboxes.pending_replies.list(mailbox_id)["pendingReplies"]
259
+ stackshift.mail.team_inboxes.pending_replies.send(mailbox_id, waiting[0]["id"])
260
+
261
+ activity = stackshift.mail.team_inboxes.activity.wait(mailbox_id, after=cursor, timeout=30)
262
+ cursor = activity["next"]
263
+ ```
264
+
265
+ `conversations.reply(mailbox_id, thread_id, draft_email_id=...)` sends a draft you prepared as the inbox, `conversations.set_status` takes `status` and `expected_revision`, `settings.get(mailbox_id)` reads the inbox settings, and `people(mailbox_id)` returns `{"people": [...], "workers": [...]}`: the people (`userId`, `name`, `email`) and workers you can assign conversations to. `activity.wait` checks for new activity after your cursor every 2 seconds (`interval`) until something happens or `timeout` seconds pass. Refusals raise `StackShiftAPIError` with `code` set to values such as `reply_locked`, `revision_conflict`, `reply_already_decided`, `send_in_progress` (409, a send for the same conversation is already running; wait for it to finish) and `mail_allowance_reached`.
266
+
267
+ To get inbox events at your own endpoint, create a webhook with `mailbox_id` and the `mailbox.conversation.*` events you want, and check it with `stackshift.mail.webhooks.test(webhook_id)`, which returns `{"deliveryId": ..., "eventId": ...}` once the test event is queued (202).
268
+
269
+ ### Inbox webhooks
270
+
271
+ Inbox events (`mailbox.conversation.*`, `mailbox.agent_inbox.*`, `mailbox.sending.*`) use the same `StackShift-Signature` header as Mail webhooks:
272
+
273
+ ```python
274
+ from stackshift import verify_inbox_webhook
275
+
276
+ raw_body = request.get_data()
277
+ if not verify_inbox_webhook(raw_body, request.headers.get("StackShift-Signature"), os.environ["STACKSHIFT_WEBHOOK_SECRET"]):
278
+ return "Invalid signature", 400
279
+ event = json.loads(raw_body)
280
+ if event["type"] == "mailbox.conversation.received":
281
+ print(event["data"]["conversation"]["subject"])
282
+ ```
283
+
284
+ Signatures older than five minutes are refused. Handlers should be idempotent. `InboxWebhookEvent` and the `INBOX_*_EVENT_TYPES` lists describe the payloads.
285
+
286
+ ## Agent agreements
287
+
288
+ Agent inboxes can ask for quotes, quote, offer times, and accept or decline offers. Every agreement ends in a record you can check from anywhere.
289
+
290
+ ```python
291
+ threads = stackshift.mail.agreements.list(inbox_id=inbox["id"], state="waiting_for_you")
292
+
293
+ sent = stackshift.mail.agreements.propose(
294
+ inbox["id"],
295
+ type="ask_quote",
296
+ to="orders@mills.example",
297
+ items=[{"description": "Flour", "quantity": "200", "unit": "kg"}],
298
+ wanted_by="2026-11-10",
299
+ idempotency_key="flour-nov-1",
300
+ )
301
+
302
+ change = stackshift.mail.agreements.wait_for_change(sent["threadId"])
303
+ stackshift.mail.agreements.accept(sent["threadId"], "OFFER_ID", idempotency_key="flour-accept-1")
304
+
305
+ record = stackshift.mail.agreements.record(sent["threadId"])
306
+ print(stackshift.mail.agreements.check(record)["summary"])
307
+ print(stackshift.mail.agreements.limits.get(inbox["id"])["usedToday"])
308
+ ```
309
+
310
+ Whether an agent may send on its own depends on the limits the owner sets for the inbox. Anything outside them waits for the owner's approval. Limits are changed in the dashboard.
311
+
152
312
  ## Send a template
153
313
 
154
314
  Templates are rendered by StackShift servers. The Python SDK only calls the REST API.
@@ -1,11 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: stackshift
3
- Version: 1.3.1
4
- Summary: Official Python SDK for StackShift.
5
- Requires-Python: >=3.9
6
- Description-Content-Type: text/markdown
7
- Requires-Dist: requests>=2.31
8
-
9
1
  # StackShift Python SDK
10
2
 
11
3
  Official Python SDK for StackShift.
@@ -33,7 +25,54 @@ domain = stackshift.partner.purchase_domain(
33
25
  status = stackshift.partner.get_domain(domain["id"])
34
26
  ```
35
27
 
36
- `partner` also exposes `overview`, `update_settings`, `list_domains` (with `q` and `attention` to find the merchants that need you), `retry_domain`, `get_diagnosis`, `restore_dns`, `transfer_out`, `resume_brand`, `get_complaints`, `list_complaint_sources`, `suppress_never_opened`, `undo_suppression`, `usage`, `list_requests` and `create_request`. `transfer_out` needs the `partner:transfer` scope (or `*`); `partner:manage` alone is refused. Purchases are capped at 30 per minute and, per partner, at 25 domains in a rolling 24 hours (429 `daily_purchase_limit`; staff can raise it). Validation errors are 400, state conflicts are 409. The `brand` and `replies` dictionaries use API camelCase keys.
28
+ `partner` also exposes `overview`, `update_settings`, `list_domains` (with `q`, `attention` and `website` to find the merchants that need you), `connect_domain` and `transfer_in_domain` / `transfer_in_connected_domain` / `switch_transfer_nameservers` for domains the merchant already owns, `set_website`, `remove_website`, `check_website` and `list_website_projects` for the storefront, `list_mailboxes`, `create_mailbox`, `update_mailbox`, `create_mailbox_password_link`, `pause_mailbox`, `resume_mailbox`, `remove_mailbox`, `create_alias`, `update_alias` and `remove_alias` for merchant mailboxes, `start_mail_migration`, `get_mail_migration`, `switch_mail_migration`, `cancel_mail_migration`, `retry_mail_migration`, `retry_mail_migration_account` and `skip_mail_migration_account` for moving old email in, `retry_domain`, `get_diagnosis`, `restore_dns`, `transfer_out`, `resume_brand`, `get_complaints`, `list_complaint_sources`, `suppress_never_opened`, `undo_suppression`, `usage`, `list_requests` and `create_request`. `transfer_out` needs the `partner:transfer` scope (or `*`); `partner:manage` alone is refused. Purchases are capped at 30 per minute and, per partner, at 25 domains in a rolling 24 hours (429 `daily_purchase_limit`; staff can raise it). Validation errors are 400, state conflicts are 409. The `brand` and `replies` dictionaries use API camelCase keys.
29
+
30
+ ## Connected agents
31
+
32
+ An agent that holds a connection credential (issued by the owner, not an account API key) can use the same API the MCP tools and the CLI use:
33
+
34
+ ```python
35
+ stackshift = StackShift(api_key=os.environ["STACKSHIFT_CONNECTION_CREDENTIAL"])
36
+ before = stackshift.agents.connections.identity().get("before_each_change")
37
+ operation = stackshift.agents.connections.operations.propose(
38
+ action="deployment.restart", resource_id=project_id, configuration={},
39
+ reason="Restart after the config fix", idempotency_key="restart-shop-1",
40
+ )
41
+ waited = stackshift.agents.connections.operations.wait(operation["id"])
42
+ while not waited["settled"]:
43
+ waited = stackshift.agents.connections.operations.wait(operation["id"])
44
+ ```
45
+
46
+ `agents.connections` has `identity`, `resources`, `capabilities`, `plan`, `task_facts(objective_id)`, `history` and `lower_level(level=..., expected_version=...)`; `agents.connections.operations` has `list`, `propose`, `get`, `wait` and `approval`. `propose` needs an `idempotency_key`: keep it and send the same one to retry. `wait` returns `settled: False` when the owner has not decided yet; call it again instead of proposing again. `approval(id)` says whether the owner has decided, with `review_url` for the owner. `lower_level` only makes the connection stricter; raising a level raises `StackShiftAPIError` with `code` `session_required`.
47
+
48
+ ## Manage the agents you run on StackShift
49
+
50
+ `hosted_agents` manages agents that run on StackShift from your own code or a script. It is separate from `agents`, which is for agents that hold a connection credential.
51
+
52
+ ```python
53
+ stackshift = StackShift(api_key=os.environ["STACKSHIFT_API_KEY"])
54
+ agent = stackshift.hosted_agents.create(
55
+ {"name": "Supplies agent", "source": {"template": "inbox-helper", "language": "python"}, "level": "ask_every_time"},
56
+ idempotency_key="supplies-agent-1",
57
+ )
58
+ stackshift.hosted_agents.secrets.set(agent["id"], "SHOP_API_KEY", os.environ["SHOP_API_KEY"])
59
+ stackshift.hosted_agents.budget.set(agent["id"], {"ai_credits_per_month": 200000, "compute_per_day": {"NGN": "5000000"}})
60
+ stackshift.hosted_agents.deploy(agent["id"], branch="main")
61
+ runs = stackshift.hosted_agents.runs(agent["id"], limit=10)
62
+ ```
63
+
64
+ `hosted_agents` has `list`, `get`, `create`, `deploy`, `rollback(id, version)`, `stop(id, reason=None)`, `start`, `delete`, `runs`, `run`, `spend(id, days=None)` and `logs(id, offset=None)`, plus `secrets.set`, `secrets.unset` and `budget.set`. `create` needs an `idempotency_key`: keep it and send the same one to retry. Money amounts are in minor units (kobo or cents). To write the agent itself, use `stackshift-agent`.
65
+
66
+ ## Databases: Branches and Sleep when idle
67
+
68
+ Branches give you a copy of a database for a test run, a preview or a pull request. `with_branch` makes one, waits until it is ready and always deletes it when the block ends:
69
+
70
+ ```python
71
+ with stackshift.databases.branches.with_branch(database_id) as branch:
72
+ run_migrations_and_tests(branch["url"])
73
+ ```
74
+
75
+ If the block raises, that error is the one you get back (a failed cleanup is attached as `cleanup_error`); a slow create is waited out before the Branch is deleted (`cleanup_timeout`, default 10 minutes). `branch["url"]` is the shared (pooled) connection string; pass `direct=True` for the direct one. `databases.branches` also has `list`, `create`, `get`, `update`, `delete`, `reset`, `retry` (a failed Branch), `promote`, `operation`, `wait_for_operation`, `url`, `options` (what a new Branch can start from), `changes` and `resume_scheduled_jobs`. `list` also returns your plan `allowance`. `create`, `reset`, `retry`, `promote` and `delete` return an operation; `wait_for_operation` polls it until it succeeds or fails. `reset`, `retry`, `promote` and `delete` send an `Idempotency-Key` (a new one for each call if you do not pass `idempotency_key`). Deleting with `cascade=True` also needs `confirm_name` (the Branch's name), or a `ValueError` is raised before the call is sent. `promote` accepts the parent's name or, when the parent is a Branch, its short name. `databases.sleep`, `databases.wake`, `databases.billing`, `databases.branch_usage`, `databases.pay_branch_usage`, `databases.scheduled_jobs`, `databases.wake_events`, `databases.move_to_instant_branches` and `databases.instant_branches_move` cover Sleep when idle and the move to instant Branches. Refusals raise `StackShiftAPIError` with `code` set to values such as `plan_limit`, `no_capacity`, `outside_window`, `too_large` and `payment_required`. On a Dedicated database, `create` and `retry` first raise `price_confirmation_required` with the price in `error.details["quote"]`; send the same call again with `confirm_charge_minor=error.details["quote"]["charge_minor"]`. `create` also takes `instance_class` to pick the size of a Dedicated Branch, and a Dedicated Branch carries its `cost`. A `plan_limit` error carries `limit`, `current` and `upgrade_url` in `details`.
37
76
 
38
77
  ## AI credits
39
78
 
@@ -149,6 +188,115 @@ stackshift.mail.mailboxes.suspend(mailbox["id"])
149
188
 
150
189
  `stackshift.mail.groups` manages team addresses, and `stackshift.mail.mailbox_imports` copies mail from Google, Microsoft or any IMAP server.
151
190
 
191
+ ## Give your agent an email address in one call
192
+
193
+ Agent inboxes are real addresses on StackShift's shared domain. Create one, let your agent sign up somewhere, wait for the verification code and delete the inbox when the job is done.
194
+
195
+ ```python
196
+ inbox = stackshift.mail.agent_inboxes.create(
197
+ prefix="signup",
198
+ labels={"job": "onboarding-42"},
199
+ job_id="onboarding-42",
200
+ expires_in=3600,
201
+ idempotency_key="onboarding-42-inbox",
202
+ )
203
+
204
+ sign_up_somewhere(inbox["address"])
205
+
206
+ message = stackshift.mail.agent_inboxes.wait_for_message(
207
+ inbox["id"],
208
+ sender="paystack.com",
209
+ timeout=120,
210
+ since=inbox["createdAt"],
211
+ )
212
+ if message:
213
+ print(message["codes"][0], message["links"])
214
+
215
+ stackshift.mail.agent_inboxes.finish_job("onboarding-42")
216
+ ```
217
+
218
+ `wait_for_message` calls the server wait endpoint in turns of up to 50 seconds until a message arrives or `timeout` (seconds, default 30) is used up, and returns `None` on timeout. Pass `since` (usually `inbox["createdAt"]`) so a message that arrived before you started waiting is found. `delete_many` takes `ids`, `job_id` or `labels`; `finish_job(job_id)` is the same as `delete_many(job_id=...)`. `create_batch` makes up to 100 inboxes at once.
219
+
220
+ Read mail with `agent_inboxes.messages.list`, `messages.latest(sender=..., subject=...)` and `messages.get`. Find inboxes with `agent_inboxes.list(labels=..., job_id=..., q=..., domain=..., limit=..., cursor=...)`, change them with `update`, remove one with `delete`, and check what your account may do with `limits()` and `pricing()`.
221
+
222
+ Sending never hides an approval. `send` returns `status` as `sent`, `waiting_approval` or `draft`, plus `pendingReplyId` and `reasons` when a person has to approve first:
223
+
224
+ ```python
225
+ result = stackshift.mail.agent_inboxes.send(
226
+ inbox["id"],
227
+ to=["ada@example.com"],
228
+ subject="Re: your question",
229
+ text="Thanks, here is the answer.",
230
+ reply_to_message_id=message["id"],
231
+ )
232
+ if result["status"] == "waiting_approval":
233
+ print("Waiting for a person to approve", result["pendingReplyId"], result["reasons"])
234
+ ```
235
+
236
+ ### Team inboxes
237
+
238
+ Team inboxes are shared mailboxes your people and agents work together. Use the mailbox id:
239
+
240
+ ```python
241
+ page = stackshift.mail.team_inboxes.conversations.list(mailbox_id, status="open", assignee="nobody")
242
+ thread = page["conversations"][0]
243
+ stackshift.mail.team_inboxes.conversations.assign(mailbox_id, thread["threadId"], worker_id=worker_id, expected_revision=thread["revision"])
244
+ stackshift.mail.team_inboxes.conversations.add_note(mailbox_id, thread["threadId"], body="Checked the logs, restarting the app.")
245
+
246
+ waiting = stackshift.mail.team_inboxes.pending_replies.list(mailbox_id)["pendingReplies"]
247
+ stackshift.mail.team_inboxes.pending_replies.send(mailbox_id, waiting[0]["id"])
248
+
249
+ activity = stackshift.mail.team_inboxes.activity.wait(mailbox_id, after=cursor, timeout=30)
250
+ cursor = activity["next"]
251
+ ```
252
+
253
+ `conversations.reply(mailbox_id, thread_id, draft_email_id=...)` sends a draft you prepared as the inbox, `conversations.set_status` takes `status` and `expected_revision`, `settings.get(mailbox_id)` reads the inbox settings, and `people(mailbox_id)` returns `{"people": [...], "workers": [...]}`: the people (`userId`, `name`, `email`) and workers you can assign conversations to. `activity.wait` checks for new activity after your cursor every 2 seconds (`interval`) until something happens or `timeout` seconds pass. Refusals raise `StackShiftAPIError` with `code` set to values such as `reply_locked`, `revision_conflict`, `reply_already_decided`, `send_in_progress` (409, a send for the same conversation is already running; wait for it to finish) and `mail_allowance_reached`.
254
+
255
+ To get inbox events at your own endpoint, create a webhook with `mailbox_id` and the `mailbox.conversation.*` events you want, and check it with `stackshift.mail.webhooks.test(webhook_id)`, which returns `{"deliveryId": ..., "eventId": ...}` once the test event is queued (202).
256
+
257
+ ### Inbox webhooks
258
+
259
+ Inbox events (`mailbox.conversation.*`, `mailbox.agent_inbox.*`, `mailbox.sending.*`) use the same `StackShift-Signature` header as Mail webhooks:
260
+
261
+ ```python
262
+ from stackshift import verify_inbox_webhook
263
+
264
+ raw_body = request.get_data()
265
+ if not verify_inbox_webhook(raw_body, request.headers.get("StackShift-Signature"), os.environ["STACKSHIFT_WEBHOOK_SECRET"]):
266
+ return "Invalid signature", 400
267
+ event = json.loads(raw_body)
268
+ if event["type"] == "mailbox.conversation.received":
269
+ print(event["data"]["conversation"]["subject"])
270
+ ```
271
+
272
+ Signatures older than five minutes are refused. Handlers should be idempotent. `InboxWebhookEvent` and the `INBOX_*_EVENT_TYPES` lists describe the payloads.
273
+
274
+ ## Agent agreements
275
+
276
+ Agent inboxes can ask for quotes, quote, offer times, and accept or decline offers. Every agreement ends in a record you can check from anywhere.
277
+
278
+ ```python
279
+ threads = stackshift.mail.agreements.list(inbox_id=inbox["id"], state="waiting_for_you")
280
+
281
+ sent = stackshift.mail.agreements.propose(
282
+ inbox["id"],
283
+ type="ask_quote",
284
+ to="orders@mills.example",
285
+ items=[{"description": "Flour", "quantity": "200", "unit": "kg"}],
286
+ wanted_by="2026-11-10",
287
+ idempotency_key="flour-nov-1",
288
+ )
289
+
290
+ change = stackshift.mail.agreements.wait_for_change(sent["threadId"])
291
+ stackshift.mail.agreements.accept(sent["threadId"], "OFFER_ID", idempotency_key="flour-accept-1")
292
+
293
+ record = stackshift.mail.agreements.record(sent["threadId"])
294
+ print(stackshift.mail.agreements.check(record)["summary"])
295
+ print(stackshift.mail.agreements.limits.get(inbox["id"])["usedToday"])
296
+ ```
297
+
298
+ Whether an agent may send on its own depends on the limits the owner sets for the inbox. Anything outside them waits for the owner's approval. Limits are changed in the dashboard.
299
+
152
300
  ## Send a template
153
301
 
154
302
  Templates are rendered by StackShift servers. The Python SDK only calls the REST API.
@@ -4,11 +4,17 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "stackshift"
7
- version = "1.3.1"
7
+ version = "1.7.0"
8
8
  description = "Official Python SDK for StackShift."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
11
+ authors = [{name = "StackShift", email = "support@stackshift.cloud"}]
12
+ classifiers = ["Programming Language :: Python :: 3"]
11
13
  dependencies = ["requests>=2.31"]
12
14
 
15
+ [project.urls]
16
+ Homepage = "https://stackshift.cloud"
17
+ Documentation = "https://docs.stackshift.cloud"
18
+
13
19
  [tool.setuptools]
14
20
  packages = ["stackshift"]
@@ -1,6 +1,9 @@
1
1
  from .client import StackShift
2
+ from .agents import AgentConnectionOperationsClient, AgentConnectionsClient, AgentsClient
2
3
  from .ai_credits import AICreditsClient
3
4
  from .assets import ASSET_TRANSFORM_PRESETS, AssetsClient, asset_transform_options, asset_transform_spec, get_asset_transform_preset
5
+ from .databases import DatabaseBranchesClient, DatabaseOperationFailed, DatabasesClient
6
+ from .hosted_agents import HostedAgentBudgetClient, HostedAgentSecretsClient, HostedAgentsClient
4
7
  from .mail import (
5
8
  MailClient,
6
9
  MailDomainsClient,
@@ -13,6 +16,7 @@ from .mail_events_webhooks import MailEventsClient, MailWebhooksClient, verify_w
13
16
  from .mail_streams import MailStreamsClient
14
17
  from .mail_campaigns import MailAudiencesClient, MailCampaignsClient
15
18
  from .mail_exports import MailExportsClient
19
+ from .mail_agreements import AgreementLimitsClient, AgreementsClient
16
20
  from .mail_mailboxes import (
17
21
  MailboxAliasesClient,
18
22
  MailboxDomainsClient,
@@ -21,6 +25,24 @@ from .mail_mailboxes import (
21
25
  MailboxesClient,
22
26
  MailboxRoutesClient,
23
27
  )
28
+ from .mail_agent_inboxes import AgentInboxesClient, AgentInboxMessagesClient
29
+ from .mail_team_inboxes import (
30
+ TeamInboxActivityClient,
31
+ TeamInboxConversationsClient,
32
+ TeamInboxesClient,
33
+ TeamInboxPendingRepliesClient,
34
+ TeamInboxSettingsClient,
35
+ )
36
+ from .mail_inbox_webhooks import (
37
+ INBOX_AGENT_INBOX_EVENT_TYPES,
38
+ INBOX_CONVERSATION_EVENT_TYPES,
39
+ INBOX_SENDING_EVENT_TYPES,
40
+ InboxAgentInboxEvent,
41
+ InboxConversationEvent,
42
+ InboxSendingEvent,
43
+ InboxWebhookEvent,
44
+ verify_inbox_webhook,
45
+ )
24
46
  from .partner import PartnerClient
25
47
  from .projects import ProjectsClient
26
48
  from .workload_security import WorkloadSecurityClient
@@ -28,8 +50,17 @@ from .workload_security import WorkloadSecurityClient
28
50
  __all__ = [
29
51
  "StackShift",
30
52
  "AICreditsClient",
53
+ "AgentConnectionOperationsClient",
54
+ "AgentConnectionsClient",
55
+ "AgentsClient",
31
56
  "ASSET_TRANSFORM_PRESETS",
32
57
  "AssetsClient",
58
+ "DatabaseBranchesClient",
59
+ "DatabaseOperationFailed",
60
+ "DatabasesClient",
61
+ "HostedAgentBudgetClient",
62
+ "HostedAgentSecretsClient",
63
+ "HostedAgentsClient",
33
64
  "MailClient",
34
65
  "MailDomainsClient",
35
66
  "MailEventsClient",
@@ -44,12 +75,29 @@ __all__ = [
44
75
  "MailAudiencesClient",
45
76
  "MailCampaignsClient",
46
77
  "MailExportsClient",
78
+ "AgreementLimitsClient",
79
+ "AgreementsClient",
47
80
  "MailboxAliasesClient",
48
81
  "MailboxDomainsClient",
49
82
  "MailboxGroupsClient",
50
83
  "MailboxImportsClient",
51
84
  "MailboxesClient",
52
85
  "MailboxRoutesClient",
86
+ "AgentInboxesClient",
87
+ "AgentInboxMessagesClient",
88
+ "TeamInboxActivityClient",
89
+ "TeamInboxConversationsClient",
90
+ "TeamInboxesClient",
91
+ "TeamInboxPendingRepliesClient",
92
+ "TeamInboxSettingsClient",
93
+ "INBOX_AGENT_INBOX_EVENT_TYPES",
94
+ "INBOX_CONVERSATION_EVENT_TYPES",
95
+ "INBOX_SENDING_EVENT_TYPES",
96
+ "InboxAgentInboxEvent",
97
+ "InboxConversationEvent",
98
+ "InboxSendingEvent",
99
+ "InboxWebhookEvent",
100
+ "verify_inbox_webhook",
53
101
  "PartnerClient",
54
102
  "ProjectsClient",
55
103
  "WorkloadSecurityClient",
@@ -0,0 +1,98 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+ from urllib.parse import quote
5
+
6
+
7
+ def _connection_data(payload: Any) -> Any:
8
+ if isinstance(payload, dict) and "data" in payload:
9
+ return payload["data"]
10
+ return payload
11
+
12
+
13
+ def _query(**values: Any) -> dict[str, Any] | None:
14
+ present = {key: value for key, value in values.items() if value is not None}
15
+ return present or None
16
+
17
+
18
+ class AgentConnectionOperationsClient:
19
+ def __init__(self, client: Any) -> None:
20
+ self._client = client
21
+
22
+ def list(self, *, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:
23
+ return _connection_data(self._client.request("GET", "/agents/connections/operations", params=_query(limit=limit, cursor=cursor)))
24
+
25
+ def propose(
26
+ self,
27
+ *,
28
+ action: str,
29
+ configuration: dict[str, Any],
30
+ idempotency_key: str,
31
+ resource_id: str | None = None,
32
+ expected_resource_version: str | None = None,
33
+ reason: str | None = None,
34
+ ) -> dict[str, Any]:
35
+ if not idempotency_key:
36
+ raise ValueError("Proposing an operation needs an idempotency_key. Keep it and send the same one when you retry.")
37
+ fields = {
38
+ "action": action, "resource_id": resource_id, "configuration": configuration,
39
+ "expected_resource_version": expected_resource_version, "reason": reason,
40
+ }
41
+ return _connection_data(self._client.request(
42
+ "POST", "/agents/connections/operations",
43
+ headers={"Idempotency-Key": idempotency_key},
44
+ json={key: value for key, value in fields.items() if value is not None},
45
+ ))
46
+
47
+ def get(self, operation_id: str) -> dict[str, Any]:
48
+ return _connection_data(self._client.request("GET", f"/agents/connections/operations/{quote(operation_id, safe='')}"))
49
+
50
+ def wait(self, operation_id: str, *, timeout_seconds: int | None = None) -> dict[str, Any]:
51
+ return _connection_data(self._client.request(
52
+ "GET", f"/agents/connections/operations/{quote(operation_id, safe='')}/wait",
53
+ params=_query(timeout_seconds=timeout_seconds),
54
+ ))
55
+
56
+ def approval(self, operation_id: str) -> dict[str, Any]:
57
+ return _connection_data(self._client.request("GET", f"/agents/connections/operations/{quote(operation_id, safe='')}/approval"))
58
+
59
+
60
+ class AgentConnectionsClient:
61
+ def __init__(self, client: Any) -> None:
62
+ self._client = client
63
+ self.operations = AgentConnectionOperationsClient(client)
64
+
65
+ def identity(self) -> dict[str, Any]:
66
+ return _connection_data(self._client.request("GET", "/agents/connections/identity"))
67
+
68
+ def resources(
69
+ self, *, kind: str | None = None, query: str | None = None, limit: int | None = None, cursor: str | None = None,
70
+ ) -> dict[str, Any]:
71
+ return _connection_data(self._client.request(
72
+ "GET", "/agents/connections/resources",
73
+ params=_query(kind=kind, query=query, limit=limit, cursor=cursor),
74
+ ))
75
+
76
+ def capabilities(self, *, family: str | None = None) -> list[dict[str, Any]]:
77
+ return _connection_data(self._client.request("GET", "/agents/connections/capabilities", params=_query(family=family)))
78
+
79
+ def plan(self) -> dict[str, Any]:
80
+ return _connection_data(self._client.request("GET", "/agents/connections/plan"))
81
+
82
+ def task_facts(self, objective_id: str) -> dict[str, Any]:
83
+ return _connection_data(self._client.request("GET", "/agents/connections/task-facts", params={"objective_id": objective_id}))
84
+
85
+ def history(self, *, limit: int | None = None, cursor: str | None = None) -> dict[str, Any]:
86
+ return _connection_data(self._client.request("GET", "/agents/connections/history", params=_query(limit=limit, cursor=cursor)))
87
+
88
+ def lower_level(self, *, level: str, expected_version: int | None = None) -> dict[str, Any]:
89
+ fields = {"level": level, "expected_version": expected_version}
90
+ return _connection_data(self._client.request(
91
+ "PUT", "/agents/connections/level",
92
+ json={key: value for key, value in fields.items() if value is not None},
93
+ ))
94
+
95
+
96
+ class AgentsClient:
97
+ def __init__(self, client: Any) -> None:
98
+ self.connections = AgentConnectionsClient(client)
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import os
4
+ import re
4
5
  from typing import Any
5
6
 
6
7
  import requests
@@ -26,16 +27,22 @@ class StackShift:
26
27
  self.cdn_base_url = cdn_base_url.rstrip("/")
27
28
  self.session = session or requests.Session()
28
29
 
30
+ from .agents import AgentsClient
29
31
  from .ai_credits import AICreditsClient
30
32
  from .assets import AssetsClient
33
+ from .databases import DatabasesClient
34
+ from .hosted_agents import HostedAgentsClient
31
35
  from .mail import MailClient
32
36
  from .partner import PartnerClient
33
37
  from .projects import ProjectsClient
34
38
  from .workload_security import WorkloadSecurityClient
35
39
 
40
+ self.agents = AgentsClient(self)
36
41
  self.ai_credits = AICreditsClient(self)
37
42
  self.projects = ProjectsClient(self)
38
43
  self.assets = AssetsClient(self)
44
+ self.databases = DatabasesClient(self)
45
+ self.hosted_agents = HostedAgentsClient(self)
39
46
  self.mail = MailClient(self)
40
47
  self.partner = PartnerClient(self)
41
48
  self.workload_security = WorkloadSecurityClient(self)
@@ -57,19 +64,40 @@ class StackShift:
57
64
  error = payload.get("error") if isinstance(payload, dict) else None
58
65
  if isinstance(error, dict):
59
66
  raise StackShiftAPIError(
60
- error.get("message") or f"StackShift API request failed with {response.status_code}",
67
+ error.get("message") or payload.get("message") or f"StackShift API request failed with {response.status_code}",
61
68
  status_code=response.status_code,
62
69
  code=error.get("code"),
63
70
  details=error.get("details"),
64
71
  )
65
72
  message = payload.get("message") if isinstance(payload, dict) else None
66
- raise StackShiftAPIError(message or f"StackShift API request failed with {response.status_code}", status_code=response.status_code)
73
+ raise StackShiftAPIError(
74
+ message or f"StackShift API request failed with {response.status_code}",
75
+ status_code=response.status_code,
76
+ code=_top_level_error_code(payload),
77
+ details=_top_level_error_details(payload),
78
+ )
67
79
 
68
80
  if isinstance(payload, dict) and "success" in payload and "data" in payload:
69
81
  return payload["data"]
70
82
  return payload
71
83
 
72
84
 
85
+ def _top_level_error_code(payload: Any) -> str | None:
86
+ if not isinstance(payload, dict):
87
+ return None
88
+ if isinstance(payload.get("code"), str):
89
+ return payload["code"]
90
+ error = payload.get("error")
91
+ return error if isinstance(error, str) and re.fullmatch(r"[a-z][a-z0-9_]*", error) else None
92
+
93
+
94
+ def _top_level_error_details(payload: Any) -> dict[str, Any] | None:
95
+ if not isinstance(payload, dict):
96
+ return None
97
+ details = {key: value for key, value in payload.items() if key not in ("success", "status", "status_code", "message", "error", "code")}
98
+ return details or None
99
+
100
+
73
101
  class StackShiftAPIError(RuntimeError):
74
102
  def __init__(
75
103
  self,