stacklink-sdk 0.2.2__tar.gz → 0.3.10__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 (46) hide show
  1. stacklink_sdk-0.3.10/PKG-INFO +139 -0
  2. stacklink_sdk-0.3.10/README.md +118 -0
  3. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/pyproject.toml +2 -1
  4. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/__init__.py +8 -0
  5. stacklink_sdk-0.3.10/stacklink/approvals.py +118 -0
  6. stacklink_sdk-0.3.10/stacklink/bots.py +266 -0
  7. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/client.py +17 -8
  8. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/errors.py +2 -1
  9. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/executions.py +4 -0
  10. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/webhooks.py +20 -0
  11. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/workbench.py +75 -32
  12. stacklink_sdk-0.3.10/stacklink/x_chat.py +138 -0
  13. stacklink_sdk-0.3.10/stacklink_sdk.egg-info/PKG-INFO +139 -0
  14. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink_sdk.egg-info/SOURCES.txt +3 -0
  15. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink_sdk.egg-info/requires.txt +3 -0
  16. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/tests/test_client.py +191 -3
  17. stacklink_sdk-0.2.2/PKG-INFO +0 -84
  18. stacklink_sdk-0.2.2/README.md +0 -65
  19. stacklink_sdk-0.2.2/stacklink_sdk.egg-info/PKG-INFO +0 -84
  20. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/LICENSE +0 -0
  21. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/setup.cfg +0 -0
  22. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/api_keys.py +0 -0
  23. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/artifacts.py +0 -0
  24. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/auth_configs.py +0 -0
  25. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/billing.py +0 -0
  26. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/claude_agent.py +0 -0
  27. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/connected_accounts.py +0 -0
  28. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/knowledge.py +0 -0
  29. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/logs.py +0 -0
  30. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/mcp.py +0 -0
  31. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/memory.py +0 -0
  32. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/openai_agents.py +0 -0
  33. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/openai_memory.py +0 -0
  34. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/projects.py +0 -0
  35. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/providers.py +0 -0
  36. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/sessions.py +0 -0
  37. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/tools.py +0 -0
  38. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/triggers.py +0 -0
  39. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink/types.py +0 -0
  40. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink_sdk.egg-info/dependency_links.txt +0 -0
  41. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/stacklink_sdk.egg-info/top_level.txt +0 -0
  42. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/tests/test_google_docs_provider.py +0 -0
  43. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/tests/test_google_drive_provider.py +0 -0
  44. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/tests/test_google_sheets_provider.py +0 -0
  45. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/tests/test_openai_memory.py +0 -0
  46. {stacklink_sdk-0.2.2 → stacklink_sdk-0.3.10}/tests/test_zoho_books_provider.py +0 -0
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.4
2
+ Name: stacklink-sdk
3
+ Version: 0.3.10
4
+ Summary: Python SDK for Stacklink sessions, tools, MCP, auth, workbench, logs, knowledge, and billing.
5
+ Author: Stacklink
6
+ License-Expression: LicenseRef-Proprietary
7
+ Project-URL: Documentation, https://docs.stacklink.in/docs/quickstart
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: httpx[http2]<1,>=0.27
12
+ Provides-Extra: x-chat
13
+ Requires-Dist: chatxdk==0.5.0; extra == "x-chat"
14
+ Provides-Extra: openai
15
+ Requires-Dist: openai<3,>=2.0; extra == "openai"
16
+ Provides-Extra: openai-agents
17
+ Requires-Dist: openai-agents<0.19,>=0.18; extra == "openai-agents"
18
+ Provides-Extra: claude-agent
19
+ Requires-Dist: claude-agent-sdk<0.3,>=0.2; extra == "claude-agent"
20
+ Dynamic: license-file
21
+
22
+ # Stacklink Python SDK
23
+
24
+ ## X Chat bot keys
25
+
26
+ Install `stacklink-sdk[x-chat]` for the official native Chat XDK. Import
27
+ `create_x_bot_chat`, `restore_x_bot_chat` and `XBotChatKeyState` from
28
+ `stacklink.x_chat`. This optional module runs on your bot infrastructure and makes
29
+ no network requests. Personal X Chat remains in the browser SDK; do not pass a
30
+ person's PIN or private keys to this module or to Stacklink's backend.
31
+
32
+ Call `create_x_bot_chat(account_id, bot_user_id, persist)` once. The `persist`
33
+ callback must store the opaque key state in your secret manager, replacing the
34
+ value for that exact account and bot before returning. Submit the returned
35
+ `registration` public-key payload through X's bot bearer-token API. Fetch the
36
+ registered public-key record, add its exact `user_id`, and call
37
+ `bind_registered_identity(record)`. The helper checks both public keys and their
38
+ binding before exposing `crypto`, the official native XDK for messages, groups,
39
+ reactions, history and encrypted media. Close the session after use.
40
+
41
+ On restart, call `restore_x_bot_chat(account_id, bot_user_id, stored_state,
42
+ current_public_record, persist)`. Account, bot, key version and both keys must
43
+ match. An uncertain registration must be reconciled using X's current public
44
+ record; do not generate replacement keys automatically. Keep the bot bearer
45
+ token retrieved by `x.getStoredBotToken` in the same customer-owned secret
46
+ manager, separately from its private key blob. Bot bearer tokens are separate
47
+ from a person's OAuth2 grant. This helper supplies local cryptography; it does
48
+ not turn a person's Stacklink connection into a bot connection.
49
+
50
+ Stacklink supplies executable, governed tools to an agent harness. The selected harness owns the model call, tool loop, and final answer.
51
+
52
+ Install the public package with the harness extra you use:
53
+
54
+ ```bash
55
+ uv add 'stacklink-sdk[openai-agents]'
56
+ ```
57
+
58
+ or:
59
+
60
+ ```bash
61
+ uv add 'stacklink-sdk[claude-agent]'
62
+ ```
63
+
64
+ The complete guides and certified recipes live at [docs.stacklink.in](https://docs.stacklink.in/docs/quickstart). PyPI is the package delivery system, not the primary documentation surface. Stacklink does not display registry download badges in its product or documentation.
65
+
66
+ ## Certified agent harnesses
67
+
68
+ | Harness | Stacklink adapter |
69
+ |---|---|
70
+ | OpenAI Agents SDK | `create_stacklink_openai_agents_tools(session)` |
71
+ | Claude Agent SDK | `create_stacklink_claude_agent_tool_config(session)` |
72
+
73
+ Both start with one explicit Stacklink session:
74
+
75
+ ```python
76
+ import os
77
+ from stacklink import Stacklink
78
+
79
+ stacklink = Stacklink(
80
+ api_key=os.environ['STACKLINK_API_KEY'],
81
+ base_url=os.getenv('STACKLINK_BASE_URL', 'https://api.stacklink.in'),
82
+ )
83
+ session = stacklink.sessions.create_bound({
84
+ 'externalTenantId': 'acme',
85
+ 'externalUserId': 'user_123',
86
+ 'modelSurface': {'mode': 'router'},
87
+ })
88
+
89
+ try:
90
+ # Pass the selected Stacklink adapter output to your agent harness.
91
+ pass
92
+ finally:
93
+ session.close()
94
+ ```
95
+
96
+ The complete OpenAI Agents and Claude Agent examples shown by the Stacklink Overview are generated from the executable files under `examples/sdk/`. The dashboard, documentation, and certification tests all read those same files.
97
+
98
+ The raw OpenAI `with_stacklink_memory` helper remains a separate Memory integration. It is not the agent-tool integration and is not part of basic Overview onboarding.
99
+
100
+ Environment variables are `STACKLINK_API_KEY`, optional `STACKLINK_BASE_URL`, and the model-provider credentials required by the selected harness. The SDK is proprietary and is provided under the applicable Stacklink agreement.
101
+
102
+ ## Accepted operations, approvals and retries
103
+
104
+ An execution response can be pending. Keep its `executionKind`, `executionId`, session ID and retry key in your application. Read or wait for that operation using the existing execution APIs. A lost connection does not submit a second action, and closing the application session can remove the authority required to execute pending work.
105
+
106
+ Retry keys are case-sensitive and accept up to 240 characters. Tool and batch requests have separate key namespaces. Reuse a key only for the exact same request in the same SDK session. Changed inputs return `409 idempotency_key_reused`; an expired stored result returns `410 execution_result_expired`. Neither response authorizes submitting the write again.
107
+
108
+ For `waiting_for_approval`, read the shared request using `client.approvals` and `platform_approvals:read`. A decision also needs `platform_approvals:manage` and the authority required by that request. A server key alone cannot approve on behalf of a company person; eligible customer confirmation uses the verified session and its scoped grant. Keep the API key on your backend. A pending action must not be labelled completed. `provider_execution_result_unknown` means an external write may have happened; inspect the provider before considering another action.
109
+
110
+ Use execution cancellation for an explicit Stop request. Losing a stream only stops observation. Vercel and LangChain adapters forward their supported abort signal; other adapters keep the structured operation identity available for explicit cancellation. MCP progress reports actual stages, not invented percentages.
111
+
112
+ Streaming has a total observation deadline and a separate inactivity timeout. A timeout raises `sdk_stream_timeout` without repeating the action; use its original operation ID to resume observation. Stream responses are limited to 8 MiB, including JSON responses to streaming requests. The synchronous client keeps blocking reads in a bounded reader and releases the response when that read finishes or reaches its inactivity timeout. Custom transports must honor the timeout passed to them. MCP calls return once all matching responses arrive, even if the server keeps the stream open.
113
+
114
+ ## Hosted Bots (0.3.2)
115
+
116
+ Bots are saved, published agents with project-scoped configuration and durable runs. Use a server-held project API key with `bots:manage` to create/update/publish, and `bots:run` to invoke. Supply a session established from your authenticated customer; input variables do not grant identity or access. Both SDKs expose run status, replayable events, cancellation and callback delivery recovery. A callback failure does not rerun the model.
117
+
118
+ ```python
119
+ bot = stacklink.bots.get(bot_id)
120
+ run = stacklink.bots.run(bot_id, session_id=session.id, message="Where is my order?", variables={"orderNumber": "4821"})
121
+ for event in stacklink.bots.stream(bot_id, run["id"]):
122
+ print(event)
123
+ result = stacklink.bots.get_run(bot_id, run["id"])
124
+ print(result["output"] or result["finalText"])
125
+ ```
126
+
127
+ The async client provides the same operations with `await` and `async for`.
128
+
129
+ Reuse the returned `conversationId` for the next message. Preserve the last event sequence to resume observation. Published invocations are available through the existing session MCP endpoint using `STACKLINK_BOTS`; no separate server per bot is needed.
130
+
131
+ ## Shared approvals (0.3.3)
132
+
133
+ `client.approvals` lists and retrieves approvals for an authorized session, submits a permitted decision or customer correction, and observes reconnectable approval events. A project key represents an application; it cannot substitute for a required human company approver. `as_customer=True` derives the customer from the authenticated session and still requires a scoped customer grant. Continue observing the original execution after deciding; do not resubmit the action.
134
+
135
+ All enabled notification channels use the same stored request. Decision, notification delivery and execution have separate states. See the [approval guide](https://docs.stacklink.in/docs/reference/sdk-python#shared-approvals) for request and lifecycle details.
136
+
137
+ When project settings require Workbench code approval, a foreground code/bash call returns `waiting_for_approval`, `approvalRequestId`, and its original execution ID immediately. No runtime sandbox is allocated for that wait. After the authorized person decides, observe the original execution; do not submit the code again.
138
+
139
+ Server-side customer grant management (0.3.5): `get_customer_grant`, `save_customer_grant`, and `remove_customer_grant` operate on an authenticated customer session. Save exact tool keys and resource restrictions with the returned settings revision. The server supplies identity from the session; callers cannot choose another customer in the request body. These methods never grant company approval or bypass connected-account access.
@@ -0,0 +1,118 @@
1
+ # Stacklink Python SDK
2
+
3
+ ## X Chat bot keys
4
+
5
+ Install `stacklink-sdk[x-chat]` for the official native Chat XDK. Import
6
+ `create_x_bot_chat`, `restore_x_bot_chat` and `XBotChatKeyState` from
7
+ `stacklink.x_chat`. This optional module runs on your bot infrastructure and makes
8
+ no network requests. Personal X Chat remains in the browser SDK; do not pass a
9
+ person's PIN or private keys to this module or to Stacklink's backend.
10
+
11
+ Call `create_x_bot_chat(account_id, bot_user_id, persist)` once. The `persist`
12
+ callback must store the opaque key state in your secret manager, replacing the
13
+ value for that exact account and bot before returning. Submit the returned
14
+ `registration` public-key payload through X's bot bearer-token API. Fetch the
15
+ registered public-key record, add its exact `user_id`, and call
16
+ `bind_registered_identity(record)`. The helper checks both public keys and their
17
+ binding before exposing `crypto`, the official native XDK for messages, groups,
18
+ reactions, history and encrypted media. Close the session after use.
19
+
20
+ On restart, call `restore_x_bot_chat(account_id, bot_user_id, stored_state,
21
+ current_public_record, persist)`. Account, bot, key version and both keys must
22
+ match. An uncertain registration must be reconciled using X's current public
23
+ record; do not generate replacement keys automatically. Keep the bot bearer
24
+ token retrieved by `x.getStoredBotToken` in the same customer-owned secret
25
+ manager, separately from its private key blob. Bot bearer tokens are separate
26
+ from a person's OAuth2 grant. This helper supplies local cryptography; it does
27
+ not turn a person's Stacklink connection into a bot connection.
28
+
29
+ Stacklink supplies executable, governed tools to an agent harness. The selected harness owns the model call, tool loop, and final answer.
30
+
31
+ Install the public package with the harness extra you use:
32
+
33
+ ```bash
34
+ uv add 'stacklink-sdk[openai-agents]'
35
+ ```
36
+
37
+ or:
38
+
39
+ ```bash
40
+ uv add 'stacklink-sdk[claude-agent]'
41
+ ```
42
+
43
+ The complete guides and certified recipes live at [docs.stacklink.in](https://docs.stacklink.in/docs/quickstart). PyPI is the package delivery system, not the primary documentation surface. Stacklink does not display registry download badges in its product or documentation.
44
+
45
+ ## Certified agent harnesses
46
+
47
+ | Harness | Stacklink adapter |
48
+ |---|---|
49
+ | OpenAI Agents SDK | `create_stacklink_openai_agents_tools(session)` |
50
+ | Claude Agent SDK | `create_stacklink_claude_agent_tool_config(session)` |
51
+
52
+ Both start with one explicit Stacklink session:
53
+
54
+ ```python
55
+ import os
56
+ from stacklink import Stacklink
57
+
58
+ stacklink = Stacklink(
59
+ api_key=os.environ['STACKLINK_API_KEY'],
60
+ base_url=os.getenv('STACKLINK_BASE_URL', 'https://api.stacklink.in'),
61
+ )
62
+ session = stacklink.sessions.create_bound({
63
+ 'externalTenantId': 'acme',
64
+ 'externalUserId': 'user_123',
65
+ 'modelSurface': {'mode': 'router'},
66
+ })
67
+
68
+ try:
69
+ # Pass the selected Stacklink adapter output to your agent harness.
70
+ pass
71
+ finally:
72
+ session.close()
73
+ ```
74
+
75
+ The complete OpenAI Agents and Claude Agent examples shown by the Stacklink Overview are generated from the executable files under `examples/sdk/`. The dashboard, documentation, and certification tests all read those same files.
76
+
77
+ The raw OpenAI `with_stacklink_memory` helper remains a separate Memory integration. It is not the agent-tool integration and is not part of basic Overview onboarding.
78
+
79
+ Environment variables are `STACKLINK_API_KEY`, optional `STACKLINK_BASE_URL`, and the model-provider credentials required by the selected harness. The SDK is proprietary and is provided under the applicable Stacklink agreement.
80
+
81
+ ## Accepted operations, approvals and retries
82
+
83
+ An execution response can be pending. Keep its `executionKind`, `executionId`, session ID and retry key in your application. Read or wait for that operation using the existing execution APIs. A lost connection does not submit a second action, and closing the application session can remove the authority required to execute pending work.
84
+
85
+ Retry keys are case-sensitive and accept up to 240 characters. Tool and batch requests have separate key namespaces. Reuse a key only for the exact same request in the same SDK session. Changed inputs return `409 idempotency_key_reused`; an expired stored result returns `410 execution_result_expired`. Neither response authorizes submitting the write again.
86
+
87
+ For `waiting_for_approval`, read the shared request using `client.approvals` and `platform_approvals:read`. A decision also needs `platform_approvals:manage` and the authority required by that request. A server key alone cannot approve on behalf of a company person; eligible customer confirmation uses the verified session and its scoped grant. Keep the API key on your backend. A pending action must not be labelled completed. `provider_execution_result_unknown` means an external write may have happened; inspect the provider before considering another action.
88
+
89
+ Use execution cancellation for an explicit Stop request. Losing a stream only stops observation. Vercel and LangChain adapters forward their supported abort signal; other adapters keep the structured operation identity available for explicit cancellation. MCP progress reports actual stages, not invented percentages.
90
+
91
+ Streaming has a total observation deadline and a separate inactivity timeout. A timeout raises `sdk_stream_timeout` without repeating the action; use its original operation ID to resume observation. Stream responses are limited to 8 MiB, including JSON responses to streaming requests. The synchronous client keeps blocking reads in a bounded reader and releases the response when that read finishes or reaches its inactivity timeout. Custom transports must honor the timeout passed to them. MCP calls return once all matching responses arrive, even if the server keeps the stream open.
92
+
93
+ ## Hosted Bots (0.3.2)
94
+
95
+ Bots are saved, published agents with project-scoped configuration and durable runs. Use a server-held project API key with `bots:manage` to create/update/publish, and `bots:run` to invoke. Supply a session established from your authenticated customer; input variables do not grant identity or access. Both SDKs expose run status, replayable events, cancellation and callback delivery recovery. A callback failure does not rerun the model.
96
+
97
+ ```python
98
+ bot = stacklink.bots.get(bot_id)
99
+ run = stacklink.bots.run(bot_id, session_id=session.id, message="Where is my order?", variables={"orderNumber": "4821"})
100
+ for event in stacklink.bots.stream(bot_id, run["id"]):
101
+ print(event)
102
+ result = stacklink.bots.get_run(bot_id, run["id"])
103
+ print(result["output"] or result["finalText"])
104
+ ```
105
+
106
+ The async client provides the same operations with `await` and `async for`.
107
+
108
+ Reuse the returned `conversationId` for the next message. Preserve the last event sequence to resume observation. Published invocations are available through the existing session MCP endpoint using `STACKLINK_BOTS`; no separate server per bot is needed.
109
+
110
+ ## Shared approvals (0.3.3)
111
+
112
+ `client.approvals` lists and retrieves approvals for an authorized session, submits a permitted decision or customer correction, and observes reconnectable approval events. A project key represents an application; it cannot substitute for a required human company approver. `as_customer=True` derives the customer from the authenticated session and still requires a scoped customer grant. Continue observing the original execution after deciding; do not resubmit the action.
113
+
114
+ All enabled notification channels use the same stored request. Decision, notification delivery and execution have separate states. See the [approval guide](https://docs.stacklink.in/docs/reference/sdk-python#shared-approvals) for request and lifecycle details.
115
+
116
+ When project settings require Workbench code approval, a foreground code/bash call returns `waiting_for_approval`, `approvalRequestId`, and its original execution ID immediately. No runtime sandbox is allocated for that wait. After the authorized person decides, observe the original execution; do not submit the code again.
117
+
118
+ Server-side customer grant management (0.3.5): `get_customer_grant`, `save_customer_grant`, and `remove_customer_grant` operate on an authenticated customer session. Save exact tool keys and resource restrictions with the returned settings revision. The server supplies identity from the session; callers cannot choose another customer in the request body. These methods never grant company approval or bypass connected-account access.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "stacklink-sdk"
7
- version = "0.2.2"
7
+ version = "0.3.10"
8
8
  description = "Python SDK for Stacklink sessions, tools, MCP, auth, workbench, logs, knowledge, and billing."
9
9
  readme = "README.md"
10
10
  license = "LicenseRef-Proprietary"
@@ -17,6 +17,7 @@ dependencies = ["httpx[http2]>=0.27,<1"]
17
17
  Documentation = "https://docs.stacklink.in/docs/quickstart"
18
18
 
19
19
  [project.optional-dependencies]
20
+ x-chat = ["chatxdk==0.5.0"]
20
21
  openai = ["openai>=2.0,<3"]
21
22
  openai-agents = ["openai-agents>=0.18,<0.19"]
22
23
  claude-agent = ["claude-agent-sdk>=0.2,<0.3"]
@@ -1,5 +1,8 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from .bots import verify_bot_api_request, sign_bot_trigger_request
4
+ from .approvals import ApprovalDecision, ApprovalRecord, ApprovalEvent, ApprovalPermissions, CustomerApprovalGrantInput
5
+ from .webhooks import verify_webhook_signature
3
6
  from .client import AsyncStacklink, STACKLINK_PYTHON_SDK_VERSION, Stacklink
4
7
  from .claude_agent import create_stacklink_claude_agent_tool_config
5
8
  from .errors import RateLimitError, StacklinkError
@@ -24,7 +27,12 @@ from .types import (
24
27
  )
25
28
 
26
29
  __all__ = [
30
+ "ApprovalDecision", "ApprovalRecord", "ApprovalEvent", "ApprovalPermissions",
31
+ "CustomerApprovalGrantInput",
27
32
  "Stacklink",
33
+ "verify_bot_api_request",
34
+ "sign_bot_trigger_request",
35
+ "verify_webhook_signature",
28
36
  "AsyncStacklink",
29
37
  "STACKLINK_PYTHON_SDK_VERSION",
30
38
  "StacklinkError",
@@ -0,0 +1,118 @@
1
+ """Shared approvals. Decisions apply to the stored action; never submit that action again."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import time
6
+ from typing import Any, Literal, TypedDict, Iterator, AsyncIterator
7
+ from urllib.parse import quote
8
+
9
+
10
+ class ApprovalDecision(TypedDict):
11
+ requirement: Literal['customer', 'company']
12
+ decision: Literal['approve', 'decline']
13
+ expectedRevision: int
14
+
15
+
16
+ class CustomerApprovalGrantInput(TypedDict):
17
+ revision: int
18
+ name: str
19
+ toolKeys: list[str]
20
+ accountIds: list[str]
21
+ resources: list[dict[str, str | int | float | bool]]
22
+
23
+
24
+ class ApprovalPermissions(TypedDict):
25
+ canDecide: bool
26
+ canManage: bool
27
+ requirement: Literal['customer', 'company'] | None
28
+ reason: str | None
29
+
30
+
31
+ class ApprovalRecord(TypedDict):
32
+ id: str
33
+ projectId: str
34
+ sessionId: str | None
35
+ revision: int
36
+ status: Literal['pending', 'approved', 'applying', 'applied', 'apply_failed', 'denied', 'cancelled', 'expired']
37
+ audience: Literal['approvers', 'customer', 'customer-approvers']
38
+ requirements: list[dict[str, Any]]
39
+ permissions: ApprovalPermissions
40
+ execution: dict[str, Any]
41
+ deliveries: list[dict[str, Any]]
42
+
43
+
44
+ class ApprovalEvent(TypedDict):
45
+ sequence: str
46
+ approvalId: str
47
+ type: Literal['approval.request.updated']
48
+ data: dict[str, Any]
49
+ occurredAt: str
50
+
51
+
52
+ class ApprovalsResource:
53
+ def __init__(self, client, *, async_mode: bool = False):
54
+ self.client = client
55
+ self.async_mode = async_mode
56
+
57
+ def get_customer_grant(self, *, session_id: str):
58
+ """Server-only: identity is resolved from this authenticated customer session."""
59
+ return self.client.request('GET', '/v1/approvals/customer-grant', query={'sessionId': session_id})
60
+
61
+ def save_customer_grant(self, grant: CustomerApprovalGrantInput, *, session_id: str):
62
+ return self.client.request('PUT', '/v1/approvals/customer-grant', query={'sessionId': session_id}, json_body=grant)
63
+
64
+ def remove_customer_grant(self, *, session_id: str, revision: int):
65
+ return self.client.request('DELETE', '/v1/approvals/customer-grant', query={'sessionId': session_id}, json_body={'revision': revision})
66
+
67
+ @staticmethod
68
+ def _query(session_id: str, as_customer: bool) -> dict[str, Any]:
69
+ return {'sessionId': session_id, 'asCustomer': 'true' if as_customer else 'false'}
70
+
71
+ def list(self, *, session_id: str, as_customer: bool = False, **filters):
72
+ return self.client.request('GET', '/v1/approvals', query={**filters, **self._query(session_id, as_customer)})
73
+
74
+ def get(self, approval_id: str, *, session_id: str, as_customer: bool = False):
75
+ return self.client.request('GET', '/v1/approvals/' + quote(approval_id, safe=''), query=self._query(session_id, as_customer))
76
+
77
+ def decide(self, approval_id: str, decision: ApprovalDecision, *, session_id: str, as_customer: bool = False, reason: str | None = None):
78
+ """Call only after a current authorized person confirms the displayed exact proposal."""
79
+ body = dict(decision)
80
+ if reason is not None:
81
+ body['reason'] = reason
82
+ return self.client.request('POST', '/v1/approvals/' + quote(approval_id, safe='') + '/decide', query=self._query(session_id, as_customer), json_body=body)
83
+
84
+ def change(self, approval_id: str, *, session_id: str, expected_revision: int, message: str, as_customer: bool = False):
85
+ return self.client.request('POST', '/v1/approvals/' + quote(approval_id, safe='') + '/change', query=self._query(session_id, as_customer), json_body={'expectedRevision': expected_revision, 'message': message})
86
+
87
+ def events(self, *, session_id: str, after: str = '0', as_customer: bool = False, timeout_ms: int = 15_000):
88
+ return self.client.request('GET', '/v1/approvals/events', query={**self._query(session_id, as_customer), 'after': after}, timeout_ms=timeout_ms)
89
+
90
+ def observe(self, *, session_id: str, after: str = '0', as_customer: bool = False, timeout_ms: int = 300_000) -> Iterator[ApprovalEvent] | AsyncIterator[ApprovalEvent]:
91
+ """Save each sequence and pass it back as after when reconnecting. Close the iterator to stop."""
92
+ if self.async_mode:
93
+ return self._observe_async(session_id, after, as_customer, timeout_ms)
94
+ return self._observe_sync(session_id, after, as_customer, timeout_ms)
95
+
96
+ def _observe_sync(self, session_id: str, cursor: str, as_customer: bool, timeout_ms: int) -> Iterator[ApprovalEvent]:
97
+ deadline = time.monotonic() + timeout_ms / 1000
98
+ while time.monotonic() < deadline:
99
+ page = self.events(session_id=session_id, after=cursor, as_customer=as_customer, timeout_ms=max(1, min(15_000, int((deadline - time.monotonic()) * 1000))))
100
+ for event in page['events']:
101
+ if int(event['sequence']) <= int(cursor):
102
+ continue
103
+ cursor = event['sequence']
104
+ yield event
105
+ if len(page['events']) < 100:
106
+ time.sleep(max(0, min(1, deadline - time.monotonic())))
107
+
108
+ async def _observe_async(self, session_id: str, cursor: str, as_customer: bool, timeout_ms: int) -> AsyncIterator[ApprovalEvent]:
109
+ deadline = time.monotonic() + timeout_ms / 1000
110
+ while time.monotonic() < deadline:
111
+ page = await self.events(session_id=session_id, after=cursor, as_customer=as_customer, timeout_ms=max(1, min(15_000, int((deadline - time.monotonic()) * 1000))))
112
+ for event in page['events']:
113
+ if int(event['sequence']) <= int(cursor):
114
+ continue
115
+ cursor = event['sequence']
116
+ yield event
117
+ if len(page['events']) < 100:
118
+ await asyncio.sleep(max(0, min(1, deadline - time.monotonic())))