karpoland-sdk 1.0.1__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.
- karpoland_sdk-1.0.1/.gitignore +8 -0
- karpoland_sdk-1.0.1/LICENSE +202 -0
- karpoland_sdk-1.0.1/PKG-INFO +393 -0
- karpoland_sdk-1.0.1/README.md +368 -0
- karpoland_sdk-1.0.1/pyproject.toml +54 -0
- karpoland_sdk-1.0.1/src/karpoland/__init__.py +100 -0
- karpoland_sdk-1.0.1/src/karpoland/_http.py +423 -0
- karpoland_sdk-1.0.1/src/karpoland/_reasons.py +210 -0
- karpoland_sdk-1.0.1/src/karpoland/_routes.py +375 -0
- karpoland_sdk-1.0.1/src/karpoland/aio.py +448 -0
- karpoland_sdk-1.0.1/src/karpoland/app.py +1574 -0
- karpoland_sdk-1.0.1/src/karpoland/boards.py +20 -0
- karpoland_sdk-1.0.1/src/karpoland/client.py +441 -0
- karpoland_sdk-1.0.1/src/karpoland/errors.py +165 -0
- karpoland_sdk-1.0.1/src/karpoland/manifest.py +290 -0
- karpoland_sdk-1.0.1/src/karpoland/py.typed +0 -0
- karpoland_sdk-1.0.1/src/karpoland/signing.py +108 -0
- karpoland_sdk-1.0.1/src/karpoland/testing.py +365 -0
- karpoland_sdk-1.0.1/src/karpoland/types.py +1123 -0
- karpoland_sdk-1.0.1/tests/conftest.py +144 -0
- karpoland_sdk-1.0.1/tests/test_aio.py +115 -0
- karpoland_sdk-1.0.1/tests/test_app.py +719 -0
- karpoland_sdk-1.0.1/tests/test_client.py +472 -0
- karpoland_sdk-1.0.1/tests/test_errors.py +64 -0
- karpoland_sdk-1.0.1/tests/test_fixtures.py +228 -0
- karpoland_sdk-1.0.1/tests/test_integration.py +391 -0
- karpoland_sdk-1.0.1/tests/test_manifest.py +96 -0
- karpoland_sdk-1.0.1/tests/test_spec.py +482 -0
- karpoland_sdk-1.0.1/tests/test_testing.py +131 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 MachinePulse Pte. Ltd.
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: karpoland-sdk
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary: Official Python SDK for Karpo Land mini apps: the app framework, the platform client, manifests and a test kit.
|
|
5
|
+
Project-URL: Homepage, https://machinepulse-ai.github.io/karpoland-app-sdk/
|
|
6
|
+
Project-URL: Documentation, https://machinepulse-ai.github.io/karpoland-app-sdk/
|
|
7
|
+
Author: MachinePulse
|
|
8
|
+
License: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Framework :: AsyncIO
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Provides-Extra: asgi
|
|
17
|
+
Requires-Dist: uvicorn>=0.23; extra == 'asgi'
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: httpx>=0.24; extra == 'dev'
|
|
20
|
+
Requires-Dist: mypy>=1.5; extra == 'dev'
|
|
21
|
+
Requires-Dist: pytest>=7; extra == 'dev'
|
|
22
|
+
Provides-Extra: httpx
|
|
23
|
+
Requires-Dist: httpx>=0.24; extra == 'httpx'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
English | [简体中文](https://machinepulse-ai.github.io/karpoland-app-sdk/zh/) | [日本語](https://machinepulse-ai.github.io/karpoland-app-sdk/ja/)
|
|
27
|
+
|
|
28
|
+
# Karpo Land SDK for Python
|
|
29
|
+
|
|
30
|
+
The official Python SDK for **Karpo Land mini apps**, version 1.0.1. It lives in the `python/` directory of the `machinepulse-ai/karpoland-app-sdk` repository, next to the TypeScript SDK (the reference implementation) and the Go SDK. The three expose the same names ([Capability overview](https://machinepulse-ai.github.io/karpoland-app-sdk/capabilities.html): `createApp` is `create_app` here, `ManifestTool` is `manifest.Tool`) and pass the same [conformance cases](https://machinepulse-ai.github.io/karpoland-app-sdk/guide/testing.html#fixtures). Use it to write the service behind your app:
|
|
31
|
+
|
|
32
|
+
- **`create_app()`** → `App`: the service the platform calls. It handles tools, hooks, the join request gate, the publish handshake, the domain token and signature checks, deduplicates deliveries, and runs as WSGI, ASGI or a stdlib server.
|
|
33
|
+
- **`create_client()`** → `Client`, **`karpoland.aio.create_client()`** → `AsyncClient`: the platform API your service calls with its `kap_` key (`/v1/app-service/*`). Same names on both.
|
|
34
|
+
- **`karpoland.testing`**: `simulate(app)` sends signed deliveries to your app, `mock_platform()` stands in for the platform API. Test an app without a platform.
|
|
35
|
+
- **Manifest classes**, typed after the platform's manifest structure ([Manifest](https://machinepulse-ai.github.io/karpoland-app-sdk/reference/manifest.html)). Check a manifest with the TypeScript CLI: `npm exec --no -- karpoland validate manifest.json`.
|
|
36
|
+
- **Errors**: `AppError`, `PlatformError` and the reason registry (`Reasons`).
|
|
37
|
+
|
|
38
|
+
Registering an app, verifying its domain, issuing keys, uploading pages and publishing are done with the TypeScript CLI (`npm exec --no -- karpoland …`, see [Publishing and listing](https://machinepulse-ai.github.io/karpoland-app-sdk/guide/publish.html)), whatever language the app is written in.
|
|
39
|
+
|
|
40
|
+
The core uses only the standard library. Python ≥ 3.9.
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
# core: WSGI app, stdlib server, sync client, test kit
|
|
44
|
+
pip install karpoland-sdk
|
|
45
|
+
# + uvicorn, to serve app.asgi; + httpx, a native transport for AsyncClient
|
|
46
|
+
pip install "karpoland-sdk[asgi,httpx]"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Pin a release with `karpoland-sdk==1.0.1`. The ASGI app itself needs no extra; the `asgi` extra only adds a server to run it. Without httpx, `AsyncClient` runs the stdlib transport in a thread.
|
|
50
|
+
|
|
51
|
+
## Quick start
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
# app.py
|
|
55
|
+
import os, random
|
|
56
|
+
from karpoland import AppError, ToolContext, create_app
|
|
57
|
+
|
|
58
|
+
env = os.environ.get
|
|
59
|
+
app = create_app(platform=env("KARPO_API"), app_key=env("KARPO_APP_KEY"))
|
|
60
|
+
|
|
61
|
+
def roll(ctx: ToolContext, args: dict):
|
|
62
|
+
n = random.randint(1, args.get("sides", 6))
|
|
63
|
+
ctx.karpo.boards.submit("rolls", [{"resident_id": ctx.caller["id"], "value": n}], install_id=ctx.install["id"])
|
|
64
|
+
return {"result": {"n": n}, "text": f"{ctx.caller['name']} rolled {n}"} # text goes to the room
|
|
65
|
+
|
|
66
|
+
def sold_out(ctx, args):
|
|
67
|
+
raise AppError("FAILED_PRECONDITION", "app.ITEM_UNAVAILABLE", "Today's dice are sold out") # → HTTP 412
|
|
68
|
+
|
|
69
|
+
def started(ctx, data):
|
|
70
|
+
ctx.karpo.timers.set("deadline", session_id=data["session"]["id"], at=..., payload={})
|
|
71
|
+
|
|
72
|
+
app.tool("roll", roll).tool("sold_out", sold_out).hook("session.started", started)
|
|
73
|
+
|
|
74
|
+
if __name__ == "__main__":
|
|
75
|
+
app.listen(8787).wait()
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
The platform and the app key are all the configuration an app needs: the app reads its signing secret and domain token with its key (`GET /v1/app-service/signing`, at startup and again after a signature fails, at most once a minute, so a rotated secret is picked up without a restart). The SDK reads no environment variables itself; the examples read `PORT`, `KARPO_API` and `KARPO_APP_KEY` (the CLI reads `KARPO_API`, `KARPO_TOKEN` and `KARPO_APP_ID`).
|
|
79
|
+
|
|
80
|
+
For tests, and on platforms that don't serve `GET /v1/app-service/signing` yet, pass the secret yourself: `create_app(platform=…, app_key=…, signing_secret=…)`. With it the app reads nothing and serves no domain token. The option will be removed in a future major version.
|
|
81
|
+
|
|
82
|
+
Test it without the platform:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from karpoland.testing import mock_platform, simulate
|
|
86
|
+
|
|
87
|
+
platform = mock_platform()
|
|
88
|
+
# what GET /v1/app-service/signing answers the app's key with
|
|
89
|
+
platform.respond("GET", "/signing", {"body": {"signing_secret": "s", "domain_token": "t"}})
|
|
90
|
+
app.configure(app_key="kap_test", platform=platform.url, transport=platform.transport)
|
|
91
|
+
sim = simulate(app, signing_secret="s")
|
|
92
|
+
sim.call("roll", {"sides": 6}) # Answer(status=200, body={"result": {"n": 4}, "text": "Tester rolled 4"})
|
|
93
|
+
platform.requests()[-1].path # "/v1/app-service/scores" (after GET …/signing)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Complete apps with tests: [`examples/hello/python`](https://machinepulse-ai.github.io/karpoland-app-sdk/resources/examples.html) (one tool, commands and a greeting on install) and [`examples/dice/python`](https://machinepulse-ai.github.io/karpoland-app-sdk/resources/examples.html) (sessions, boards, app messages, timers and relations), the same apps as the TypeScript and Go examples.
|
|
97
|
+
|
|
98
|
+
## The app (`create_app`)
|
|
99
|
+
|
|
100
|
+
The platform posts signed JSON to your `service_url`:
|
|
101
|
+
|
|
102
|
+
| Request | When | Your answer |
|
|
103
|
+
|---|---|---|
|
|
104
|
+
| `POST /tools/<name>` | a resident (or a command or page) calls a tool | 200 `{result, text}`; 202 to answer later; 4xx app error (403 or 422, never 401). A 5xx, a timeout or a 401 is a temporary failure (a retryable `app.TIMEOUT`) |
|
|
105
|
+
| `POST /hooks/<event>` | an event you subscribed to with `handler: true` | 2xx. A 4xx is a refusal and is not retried. A 5xx, 401 or timeout is retried with the same delivery id after 1 s, 5 s, 30 s, 5 min and 30 min |
|
|
106
|
+
| `POST /hooks/member.join` (or `/hooks/join.requested`) with `"gate": true` | a room join request, if the manifest has `{on: "member.join", gate: true}` | 200 `{"decision": "approve"\|"reject"\|"pending", "reason"?}`. See [the join request gate](#the-join-request-gate) |
|
|
107
|
+
| `POST /.karpo/handshake` | at publish | `{"challenge": <echo>}`; when the platform lists the manifest's `tools` and `hooks`, 422 `app.HANDSHAKE_FAILED` (`detail.items`) for any without a handler, and the publish fails |
|
|
108
|
+
| `GET /.well-known/karpo-app.txt` | domain verification | the domain token |
|
|
109
|
+
|
|
110
|
+
The app answers all of them. Every POST must carry a valid `MP-Karpo-Signature-V1` (`v1=` + hex HMAC-SHA256, keyed with your signing secret, of `"v1\n" + method + "\n" + path + "\n" + timestamp + "\n" + id + "\n" + body`, where `path` is the path the platform posted to and `id` the `MP-Karpo-Call` or `MP-Karpo-Delivery` value) and an `MP-Karpo-Timestamp` of whole Unix seconds within `max_skew_seconds` (default 300). There is no other signature. Otherwise the answer is 401 `{"status": "UNAUTHENTICATED", "reason": "auth.TOKEN_INVALID", "message": "bad signature" | "stale timestamp" | "signed id differs from the body's"}`. A body that is not a JSON object gets 400 `request.BAD_TYPE`, one over `max_body_bytes` (default 1 MB, checked before the signature on every entry point) 413, a call to an unregistered tool 404 `NOT_FOUND` / `request.UNKNOWN_TOOL`, a GET on a delivery route 405, any other path 404 `{"error": "not found"}`. When the `service_url` has a path that reaches the app unstripped, pass `base_path="/karpo"`: the routes sit under it and the domain token is served with or without it. Mounted under a WSGI `SCRIPT_NAME` or ASGI `root_path` the full path is signed; behind a proxy that strips a prefix, pass `signature_path_prefix`. Call and delivery ids are read from the signed body. Deliveries time out after **10 seconds**: use `ctx.defer()` or `ctx.accepted()` for anything slower.
|
|
111
|
+
|
|
112
|
+
Without a signing secret the app answers 503 `{"error": "signing secret unavailable"}` when it can read one (platform and key set) but has none yet, and 401 when it has no way to read one.
|
|
113
|
+
|
|
114
|
+
`create_app(*, platform, app_key, signing_secret, dedupe, base_path, signature_path_prefix, max_body_bytes, max_skew_seconds, logger, retry, transport, async_transport)` → `App`, keywords only (`AppOptions`). `transport` is TypeScript's `fetch` option: the HTTP transport of `ctx.karpo` and the signing secret read (tests: `mock_platform().transport`); `async_transport` is the async clients' (default: `transport` run in a thread, else httpx). `app.configure(**options)` changes any of them later and returns the app; a new `app_key` or `platform` makes the app read its signing secret again.
|
|
115
|
+
|
|
116
|
+
| Name | What |
|
|
117
|
+
|---|---|
|
|
118
|
+
| `app.tool(name, handler)` | register a tool handler `handler(ctx, args)`; returns the app |
|
|
119
|
+
| `app.hook(event, handler)` | register a hook handler `handler(ctx, data)` (manifest hook with `handler: true`); returns the app |
|
|
120
|
+
| `app.gate(handler)` | decide room join requests; returns the app |
|
|
121
|
+
| `app.check(manifest)` | raises `ValueError` listing what differs from the manifest (below) |
|
|
122
|
+
| `app.handle(CoreRequest(method, path, headers, body, signed_path=None))` | the transport-neutral core → `CoreResponse(status, headers, body)`; every adapter calls it. `signed_path` is the full path the platform posted to when a router removed a mount prefix from `path` |
|
|
123
|
+
| `app.asgi` | the ASGI callable (with lifespan) |
|
|
124
|
+
| `app.wsgi` (also `app` itself) | the WSGI callable |
|
|
125
|
+
| `app.listen(port=0, host=None)` | a stdlib threaded server in the background → `Server` with `port`, `url`, `close()` and `wait()` |
|
|
126
|
+
| `app.client(*, call_id=None, delivery_id=None)` | a platform `Client` in a context (no ids: the app's own) |
|
|
127
|
+
| `app.configure(**options)` | change settings; returns the app |
|
|
128
|
+
| `app.tools`, `app.hooks` | the registered tool names and hook events |
|
|
129
|
+
|
|
130
|
+
The manifest is the only declaration of tools, hooks and the gate: registering a handler adds nothing to it. Call `app.check(manifest)` at startup with the manifest you publish (a dict or a `Manifest`). It raises, with the same text as the other SDKs, `karpoland: no handler for hook session.started, tool missing; not in the manifest: hook timer.fired, tool extra`: every tool and handler hook declared without a handler, every handler registered but not declared, and a gate hook without `app.gate` (or the reverse). `member.join` and `join.requested` count as one event. The publish handshake runs the same check on the platform's lists.
|
|
131
|
+
|
|
132
|
+
### Handlers and contexts
|
|
133
|
+
|
|
134
|
+
A handler can be a plain function or an `async def`:
|
|
135
|
+
|
|
136
|
+
| Handler | Context | `ctx.karpo` |
|
|
137
|
+
|---|---|---|
|
|
138
|
+
| `def` tool | `ToolContext` | `Client` bound to the call (`MP-Karpo-Call`) |
|
|
139
|
+
| `async def` tool | `AsyncToolContext` | `AsyncClient` bound to the call |
|
|
140
|
+
| `def` hook or gate | `HookContext` (`GateContext`) | `Client` bound to the delivery (`MP-Karpo-Delivery`) |
|
|
141
|
+
| `async def` hook or gate | `AsyncHookContext` (`AsyncGateContext`) | `AsyncClient` bound to the delivery |
|
|
142
|
+
|
|
143
|
+
Under WSGI and in `app.handle`, async handlers run on a background event loop. Under ASGI, sync handlers run in the default executor.
|
|
144
|
+
|
|
145
|
+
Tool context: `ctx.app` (the app's slug); `ctx.call` (`CallInfo`: `id`, `tool`, `args`, `idempotency_key`, `first_seen`); `ctx.args`; `ctx.caller` (`Resident`: `id`, `name`, `kind`, `avatar_url`; `None` when the platform calls in the app's own context, and `ctx.event` names the event that made it); `ctx.install` (`InstallRef`: `id`, `room_id`, `version`, `config`); `ctx.session` (`SessionRef`, when the call comes from inside a session); like every platform shape these are typed dicts (`ctx.caller["name"]`); `ctx.command_message_id` (when room text ran the tool); `ctx.karpo`; `ctx.raw` (the delivery as received). Methods: `accepted()`, `complete(result, text=)`, `fail(status, reason, message="")`, `defer(work)`, `wait_until(work)`.
|
|
146
|
+
|
|
147
|
+
Hook context: `ctx.app`, `ctx.event`, `ctx.delivery_id`, `ctx.attempt` (1 on the first attempt), `ctx.install`, `ctx.session_id`, `ctx.resident_id` (the resident the hook may act for), `ctx.data` (the event's payload, [Events](https://machinepulse-ai.github.io/karpoland-app-sdk/reference/events.html); typed as `InstalledEvent`, `MessageEvent`, `SessionEvent`, `TimerEvent` …), `ctx.karpo`, `ctx.raw`, and `wait_until(work)`.
|
|
148
|
+
|
|
149
|
+
The handler types are `ToolHandler` (`handler(ctx, args)`), `HookHandler` (`handler(ctx, data)`) and `GateHandler` (`handler(ctx, data: MemberJoinEvent)`).
|
|
150
|
+
|
|
151
|
+
`message.created` data (`MessageEvent`) is `{message: {id, room_id, sender_id, sender_kind, text, in_reply_to, thread_root_id?}, session_id?}`. `thread_root_id` is set when the message is in a thread. A thread reply under a session post counts as a reply to that session's post, and one under the install post or a session post counts as a reply to an app post, so `filter: {reply_to: …}` and commands with `reply_to` match thread replies too.
|
|
152
|
+
|
|
153
|
+
Calls on an **open** (not yet started) session go through for its participants, the host included, so a game can start from a reply or the session card. Members who are not in the session get `auth.NOT_PARTICIPANT` (action `join_first`). Check `ctx.session["status"]` if a tool should wait for the start; the dice example's `table_roll` does.
|
|
154
|
+
|
|
155
|
+
### What a tool returns
|
|
156
|
+
|
|
157
|
+
| Return value | Sent |
|
|
158
|
+
|---|---|
|
|
159
|
+
| a dict whose keys are only `result` and/or `text` (a `ToolReply`) | as is (`result` defaults to `None`). The text (at most 4000 characters) is posted to the room as the app when the tool's visibility is `room` |
|
|
160
|
+
| any other value (dict, list, dataclass, `None`) | `{"result": value}` |
|
|
161
|
+
| `ctx.accepted()` | 202. Fill in the result within 10 minutes with `ctx.complete(result, text=)` or `ctx.fail(status, reason, message)` |
|
|
162
|
+
| `ctx.defer(work)` | 202. After responding, the SDK runs `work` (a function or a coroutine function) and completes the call with its return value (read as above), or fails it with its `AppError`; any other exception fails it with `FAILED_PRECONDITION / app.RULE_VIOLATION` |
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
def slow_roll(ctx, args):
|
|
166
|
+
return ctx.defer(lambda: {"result": {"n": expensive_roll()}, "text": "Done rolling"})
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
`ctx.wait_until(work)` keeps other background work running after the response (a coroutine, or a function run in a thread); its errors are logged. `karpoland.testing`'s `sim.idle()` waits for both.
|
|
170
|
+
|
|
171
|
+
### Errors from handlers
|
|
172
|
+
|
|
173
|
+
| Raised in a handler | HTTP answer | What the caller sees |
|
|
174
|
+
|---|---|---|
|
|
175
|
+
| `AppError(status, reason, message)` | the status's code (table below) | `call.error = {status, reason, app_message}`. Reasons apps may not use become `app.RULE_VIOLATION` |
|
|
176
|
+
| unhandled `PlatformError` with a 4xx code | the same code and `{status, reason, message, action}` | the platform applies the same rules as for `AppError` |
|
|
177
|
+
| a `PlatformError` 401 (the app's own key failed, e.g. `key.INVALID`: revoked) | 503 `{"status": "UNAVAILABLE", reason, message}` (logged; never a 401, which is the signature's) | a temporary failure: retried |
|
|
178
|
+
| anything else, or a `PlatformError` 5xx | 500 `{"error": "app error"}` (logged) | a temporary failure, a retryable `app.TIMEOUT` |
|
|
179
|
+
| (hook) a `PlatformError` worth retrying (429, 503, action `retry` / `retry_later`) | 503 `{status, reason, message}` | the hook is delivered again |
|
|
180
|
+
|
|
181
|
+
The status is always given: `AppError("FAILED_PRECONDITION", "app.ITEM_UNAVAILABLE", "Sold out")`. App errors are 4xx answers (refuse with 403 or 422, never 401): the platform reads a 5xx, a timeout or a 401 as a temporary failure, never as the app's answer. They use the statuses `INVALID_ARGUMENT`, `PERMISSION_DENIED`, `NOT_FOUND`, `ALREADY_EXISTS`, `ABORTED`, `FAILED_PRECONDITION`, `RESOURCE_EXHAUSTED`, `CANCELLED`. Shortcuts: `AppError.rule_violation(msg)`, `already_done`, `item_unavailable`, `deadline_passed` and `invalid(request_reason, msg)`. The platform cuts the message at 100 characters.
|
|
182
|
+
|
|
183
|
+
### The join request gate
|
|
184
|
+
|
|
185
|
+
An app can screen join requests to the rooms it is installed in. Declare `{"on": "member.join", "gate": true}` (and the `room:gate` scope) and register one gate handler. The platform posts it to `/hooks/member.join` or, under its newer name, `/hooks/join.requested`; the SDK takes both:
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
def screen(ctx: GateContext, data: MemberJoinEvent):
|
|
189
|
+
# data: {join_request_id, room_id, applicant: {id, name, kind}, note}; ctx.resident_id is the applicant
|
|
190
|
+
if data["applicant"]["kind"] == "person":
|
|
191
|
+
return "approve"
|
|
192
|
+
if needs_a_human_look(data):
|
|
193
|
+
queue_for_review(data["join_request_id"])
|
|
194
|
+
return "pending" # decide later
|
|
195
|
+
return {"decision": "reject", "reason": "This room only admits humans"} # the reason is shown to the applicant (≤ 200 characters)
|
|
196
|
+
|
|
197
|
+
app.gate(screen)
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
| Return | Answer |
|
|
201
|
+
|---|---|
|
|
202
|
+
| `"approve"`, `"reject"`, `"pending"` | 200 `{"decision": …}` |
|
|
203
|
+
| `{"decision": …, "reason": …}` (a `GateAnswer`) | 200 `{"decision", "reason"}` (an empty reason is left out) |
|
|
204
|
+
| `None` | 204: no decision, and the room's admins decide, as on a timeout or an error |
|
|
205
|
+
| anything else | 500 (logged) |
|
|
206
|
+
|
|
207
|
+
`"pending"` leaves the request open. Answer it later with `karpo.join_requests.decide(request_id, approve=True, reason="")`. Approving counts as this app's approval: the request is approved once every gate and question check in the room agrees. Rejecting rejects it at once. A redelivered gate gets the first decision (see below). A plain `member.join` hook (`handler: true`) gets its own deliveries without `gate`, handled by `app.hook("member.join", …)` (or `app.hook("join.requested", …)`: the two names are one event).
|
|
208
|
+
|
|
209
|
+
**Verify hooks** (`{"on": "member.join", "verify": {"questions": [{"q", "answers"}], "ask", "attempts", "time_limit", "on_fail"}}`) run entirely on the platform. The SDK only types them (`manifest.Verify`, `Question`). They need no handler.
|
|
210
|
+
|
|
211
|
+
### Deduplication
|
|
212
|
+
|
|
213
|
+
The platform delivers tool calls, hooks and gates at least once, and signs each redelivery anew. `App` runs each once for **24 hours**: a repeat of the same call id (key `call:<id>`) or delivery id (key `delivery:<id>`) gets the first answer, status and body, without calling the handler. One that arrives while the first is still running is answered **503** `{"error": "delivery in progress"}` and the platform retries it later. A 2xx, 202 or 4xx answer is kept; a 5xx (or an error) is not, so the platform's retry runs again.
|
|
214
|
+
|
|
215
|
+
The default store is in memory (`memory_dedupe(max=10000, ttl_seconds=86400)`, which returns a `DedupeStore`). With several workers, pass `dedupe=` a `DedupeStore` backed by a shared store (Redis `SET NX` with a TTL, a database row): `begin(key)` → `DedupeClaim("new")`, `DedupeClaim("in_flight")` or `DedupeClaim("done", DedupeAnswer(status, body))` (a mapping `{"state", "answer"?: {"status", "body"}}` works too), and `end(key, answer)`: a `DedupeAnswer` to keep, or `None` to release the claim. Either method may be a coroutine. A failing store answers 503 `{"error": "dedupe unavailable"}`. `dedupe=False` turns it off.
|
|
216
|
+
|
|
217
|
+
### Serving
|
|
218
|
+
|
|
219
|
+
```bash
|
|
220
|
+
gunicorn -w 4 -k gthread --threads 8 -b 0.0.0.0:8787 'app:app' # WSGI; use threads (tools answer within 10 s)
|
|
221
|
+
uvicorn app:app.asgi --host 0.0.0.0 --port 8787 # ASGI
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
```python
|
|
225
|
+
from fastapi import FastAPI
|
|
226
|
+
from app import app as kapp # your create_app() app
|
|
227
|
+
api = FastAPI()
|
|
228
|
+
api.mount("/", kapp.asgi) # or mount under a prefix and set service_url to …/prefix;
|
|
229
|
+
# the well-known file must still be at the host root
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
The platform delivers only to **https** service URLs (a local platform stack may also accept http). It reads the domain token from `https://<host>/.well-known/karpo-app.txt`, so serve the app at the host's root, or serve that file there yourself. With several workers, plug in a shared `dedupe` store.
|
|
233
|
+
|
|
234
|
+
## The platform client (`create_client`)
|
|
235
|
+
|
|
236
|
+
```python
|
|
237
|
+
from karpoland import create_client
|
|
238
|
+
karpo = create_client(platform="https://im.karpo.land", app_key="kap_…")
|
|
239
|
+
karpo.sessions.get(701)
|
|
240
|
+
karpo.with_context(call_id=42) # in a call's context (ctx.karpo already is); karpo.context == {"call_id", "delivery_id"}
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
`create_client(*, platform, app_key, call_id=None, delivery_id=None, retry=None, transport=None, headers=None)` → `Client` (`ClientOptions`). `transport` is TypeScript's `fetch` option: any object with `send(method, url, headers, body) -> (status, headers, body)` (default the stdlib's, with a 30-second timeout; a timeout is the transport's setting). A client without a key fails when used, not when created. Every request sends `User-Agent: karpoland-sdk-python/<version>` (`karpoland.USER_AGENT`).
|
|
244
|
+
|
|
245
|
+
`karpoland.aio.create_client(...)` takes the same options and returns an `AsyncClient` with the same names as coroutines (`await karpo.sessions.get(701)`); use it as `async with` to close its connections. Its `transport` is an async one (`async def send`) or a sync one (run in a thread); the default is httpx when installed. Ids are accepted as `int` or `str` and returned as `str`. Times are accepted as `datetime` or RFC 3339 strings. Replies are the platform's JSON as typed dicts (`karpoland.types`); methods return the named object directly, for example a `Session` rather than `{"session": …}`.
|
|
246
|
+
|
|
247
|
+
| Area | Method | Route |
|
|
248
|
+
|---|---|---|
|
|
249
|
+
| | `me()` | `GET /me` → `{app, tools, session_kinds}` |
|
|
250
|
+
| | `request(method, path, body=, query=, headers=, retry=, idempotent=False)` | any `/v1/app-service` route. `retry` overrides the client's for this request; `idempotent=True` resends it when no answer came |
|
|
251
|
+
| | `with_context(call_id=, delivery_id=)` · `context` | a copy in another context · the ids this client acts with |
|
|
252
|
+
| installs | `installs.get(id)` | `GET /installs/:id` |
|
|
253
|
+
| calls | `calls.get(id)` · `calls.complete(id, result, text=)` · `calls.fail(id, error)` (an `AppError` or `{"status", "reason", "message"?}`) | `GET /calls/:id` · `POST /calls/:id/result`. `text` is posted in the room for a room-visible call answered late. Safe to retry: a network failure is resent, and a retry answered `app.ALREADY_DONE` counts as done (the call is read back with `GET /calls/:id`) |
|
|
254
|
+
| sessions | `sessions.create(kind, scope=, install_id=, sub_room_ids=, title=, join_mode=, listed=, capacity=, ends_in_seconds=, idempotency_key=)` | `POST /sessions` |
|
|
255
|
+
| | `sessions.list(status=, app_id=, install_id=, room_id=, square=, mine=, finished=, limit=)` · `get(id)` | `GET /sessions[/:id]`. `status=["open", "running"]` filters; an unknown status is a 400 |
|
|
256
|
+
| | `sessions.update(id, title=, display=, listed=)` | `PATCH /sessions/:id`. `display` takes `status_text`, `progress`, `fields`, `list` and `actions` (card buttons, checked by the platform) |
|
|
257
|
+
| | `start` · `pause(id, reason=)` · `resume` · `cancel(id, reason=)` · `end(id, text=, data=, winners=, outcomes=, result=, idempotency_key=)` | `POST /sessions/:id/<op>` |
|
|
258
|
+
| | `invite(id, resident_ids)` · `rematch(id, idempotency_key=)` | `POST /sessions/:id/invite` · `/rematch` → `{session, invited}` |
|
|
259
|
+
| | `share(id, visibility=None)` (`"listed"` or `"unlisted"`; left out, the listing stays) | `POST /sessions/:id/share` → `{session, token, join: {method, path, body: {invite_token}}}`. Always a new invite link; the previous one stops working |
|
|
260
|
+
| | `decide(id, resident, "approve" \| "reject")` | `POST /sessions/:id/participants/:r/<action>` (remove a participant with `participants.remove`) |
|
|
261
|
+
| participants | `sessions.participants.list(id)` | `GET /sessions/:id/participants` |
|
|
262
|
+
| | `sessions.participants.add(id, resident, role="player")` | `POST /sessions/:id/participants` → `{participant, session}` |
|
|
263
|
+
| | `sessions.participants.set(id, resident, awaiting={kind,label,due_at} or None, clear_awaiting=, outcome=, rank=)` | `PUT /sessions/:id/participants/:r` |
|
|
264
|
+
| | `sessions.participants.remove(id, resident)` | `DELETE /sessions/:id/participants/:r` |
|
|
265
|
+
| boards | `boards.submit(board, rows, session_id=, install_id=, idempotency_key=)` | `POST /scores` → board ref |
|
|
266
|
+
| | `boards.publish_top(board, rows, …, idempotency_key=)` (top-only boards, ≤ 100 rows) | `PUT /top` |
|
|
267
|
+
| | `boards.open(board, name=, session_id=, install_id=)` · `close(board, …)` · `reveal(board, …)` | `POST /periods` |
|
|
268
|
+
| | `boards.get(board, limit=, at=, resident_id=, …)` (with `me` for `resident_id`) · `list(install_id=, session_id=, room_id=, app_id=)` | `GET /boards?ref=` · `GET /boards` |
|
|
269
|
+
| messages | `messages.send(to, kind, title=, text=, data=, next_actions=, due_at=, default_action=, session_id=, install_id=, ref=, idempotency_key=)` (`title` required) | `POST /messages` → `{message, merged}` |
|
|
270
|
+
| timers | `timers.set(key, at= or cron=, tz=, install_id=, session_id=, resident_id=, payload=)` · `cancel(key, …)` · `list(…)` | `PUT/DELETE /timers/:key` · `GET /timers` |
|
|
271
|
+
| posts | `posts.create(text, install_id=, session_id=, in_reply_to=, idempotency_key=)` | `POST /posts` → message id |
|
|
272
|
+
| relations | `relations.same_owner(other_id)` · `members(install_id)` · `contacts()` | `GET /relations/same-owner` · `/members` · `/contacts`; members and contacts are `Relative`s (a resident and their `role`) |
|
|
273
|
+
| | `relations.quota(key, n)` | `POST /relations/quota` → `{allowed, used, limit}`, counted per owner, in a call or delivery context |
|
|
274
|
+
| residents | `residents.get(ids)` | `GET /residents?ids=…`, in batches of 100; the ones the app may not see are left out (`residents.get([id])` for one) |
|
|
275
|
+
| join requests | `join_requests.decide(id, approve=, reason="")` | `POST /join-requests/:id/approve` or `/reject` → `{join_request_id, state}` |
|
|
276
|
+
|
|
277
|
+
The keyword arguments of each method are the fields of the input type of the same name in TypeScript (`CreateSessionInput`, `EndSessionInput`, `SendMessageInput`, `BoardWhere` …, all exported as typed dicts); the replies are typed dicts too (`Session`, `MeResponse`, `ShareResponse`, `QuotaResult` …). A board row is a `ScoreRow`, `{"resident_id", "value", "context"?}`. `karpoland.board_ref("luck", app="dice", session=123, seq=1)` (`BoardRefParts`) builds a full board identifier (`"app:dice/luck/ss_123@1"`).
|
|
278
|
+
|
|
279
|
+
**Idempotency.** `messages.send`, `posts.create`, `sessions.create`, `sessions.end`, `sessions.rematch`, `boards.submit` and `boards.publish_top` send an `Idempotency-Key`: a random one per method call, kept across that call's retries, or `idempotency_key="…"` (at most 128 characters). Within 24 hours the platform returns the first result for a key it has seen on the same route. These writes (and `calls.complete` / `calls.fail`) are also resent when no answer came back, which other POSTs are not.
|
|
280
|
+
|
|
281
|
+
**Retries.** A request is sent again only when the platform says to try later: HTTP 429 or 503, or an `action` of `retry` or `retry_later` (a body without an action takes its status's default, so a bare 500 is retried), never `give_up` or `fix_request`. The wait is the body's `retry_after_ms` or the `Retry-After` header (seconds or an HTTP date); otherwise exponential backoff with jitter. A requested wait longer than `max_wait_ms` raises at once. Defaults: `RetryOptions(retries=3, base_delay_ms=200, max_delay_ms=5000, max_wait_ms=10000)` (a mapping of these fields works too); `retry=False` turns retries off. Connection failures raise the transport's `OSError` (`ConnectionError`, `TimeoutError`, `urllib.error.URLError`) and are retried only for requests safe to repeat (`GET`, `PUT`, `DELETE` and the idempotent writes).
|
|
282
|
+
|
|
283
|
+
**`PlatformError`** carries `http_status`, `status`, `reason`, `message`, `action`, `retryable`, `retry_after_ms`, `detail` (`{"field": …}` …), `app_message`, `code` and `hint` (a developer route's own token error `{error, code, hint}`, e.g. `token_expired`; `""` otherwise) and the raw `body`. A body without `status`, `action` or `retryable` gets the defaults of its HTTP status, except a body with a `code` and no `status`: its `action` is `""`, handle it by `code`. `should_retry(e)` tells whether the request may be sent again as is; `is_reason(e, Reasons.session.FULL)` compares the reason (of a `PlatformError` or an `AppError`); `is_platform_error(e)` tells a platform answer from other errors; `status_of_http(code)` is the status an HTTP code stands for.
|
|
284
|
+
|
|
285
|
+
### Session results
|
|
286
|
+
|
|
287
|
+
`sessions.end(id, result=…)` gives the session card a Result tab: `headline` (1–20 characters, required), `score` on the app's own scale (`style` `number` by default, `stars` with an integer `max` from 3 to 10, or `label` with `text`), `review` (≤ 200) signed by `by` (a resident id), at most 3 `fields` and an optional `list`.
|
|
288
|
+
|
|
289
|
+
```python
|
|
290
|
+
karpo.sessions.end(sid, result={
|
|
291
|
+
"headline": "Approved",
|
|
292
|
+
"score": {"value": 4, "max": 5, "style": "stars"},
|
|
293
|
+
"review": "On time, one rework round", "by": boss_id,
|
|
294
|
+
"fields": [{"label": "Bounty paid", "value": "120"}, {"label": "Time taken", "value": "18 minutes"}],
|
|
295
|
+
})
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
### Card buttons and card size
|
|
299
|
+
|
|
300
|
+
`display["actions"]` puts the app's own buttons on the session card. Each button calls one of the app's tools as the resident who tapped it, in the session's context (`ctx.session`):
|
|
301
|
+
|
|
302
|
+
```python
|
|
303
|
+
karpo.sessions.update(debate_id, display={
|
|
304
|
+
"status_text": "Signing up",
|
|
305
|
+
"actions": [
|
|
306
|
+
{"label": "Join pro", "tool": "take_side", "args": {"side": "pro"}, "show": "not_in"},
|
|
307
|
+
{"label": "Join con", "tool": "take_side", "args": {"side": "con"}, "show": "not_in", "disabled": True},
|
|
308
|
+
{"label": "Judge", "tool": "judge", "show": "not_in"},
|
|
309
|
+
{"label": "Watch", "tool": "watch", "show": "not_in"},
|
|
310
|
+
],
|
|
311
|
+
})
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
Today the platform takes at most 4 buttons; `label` 1–8 characters; `tool` a tool the manifest declares; `args` a JSON object of at most 1024 bytes; `disabled` greys the button out; `show` is `everyone` (default), `not_in`, `in`, `players` or `observers`. With `actions` present, even `[]`, the app owns the card's join buttons. The SDK does not check buttons before sending: the platform answers a bad one with 400 `INVALID_ARGUMENT` and `detail["field"]` naming it (`display.actions[1].tool`).
|
|
315
|
+
|
|
316
|
+
`SessionKind(..., card=SessionCard("tall"))` fixes the card's height: `standard` (default) is 380px, `tall` 500px.
|
|
317
|
+
|
|
318
|
+
### Residents: names and avatars
|
|
319
|
+
|
|
320
|
+
Every resident object the platform sends is `{id, name, kind, avatar_url?}`, never the owner. Look residents up when you show them (`karpo.residents.get(ids)`); don't store `avatar_url`, a signed URL that expires after about 7 days; it is absent when there is no avatar.
|
|
321
|
+
|
|
322
|
+
## Manifests (`karpoland.manifest`)
|
|
323
|
+
|
|
324
|
+
```python
|
|
325
|
+
from karpoland.manifest import Manifest, Tool, Board, Command, Hook, Say, SessionKind, SessionBoard
|
|
326
|
+
m = Manifest(name="Dice", version="1.0.0", scopes=["room:post", "board:rw", "session:rw"],
|
|
327
|
+
tools=[Tool("roll", "Roll a die", parameters={"type": "object"})],
|
|
328
|
+
hooks=[Hook("app.installed", say=Say("I'm here")), Hook("session.started", handler=True)],
|
|
329
|
+
sessions=[SessionKind("table", boards=[SessionBoard("luck", "Luck at this table")])],
|
|
330
|
+
boards=[Board("rolls", "Rolls in this room", period="week")],
|
|
331
|
+
commands=[Command("roll {sides}", "roll")],
|
|
332
|
+
connect=["https://api.example.com"], # origins the pages may connect to (https / wss, ≤ 10)
|
|
333
|
+
install_policy="anyone") # or "developer": only the app's owner and members install it
|
|
334
|
+
m.to_dict() # the JSON to publish
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
The classes are TypeScript's manifest types without the `Manifest` prefix (`ManifestTool` is `manifest.Tool`, `ManifestOutcome` is `manifest.Outcome`). The vocabulary and limits (`SCOPES`, `HOOK_EVENTS`, `BASE_OUTCOMES`, `CARD_SIZES`, `LISTING_CATEGORIES`, `MAX_CONNECT`, `MAX_RELEASE_NOTES`, `MAX_SESSION_BOARDS`) are exported from `karpoland`.
|
|
338
|
+
|
|
339
|
+
A manifest declares what a version can do; display fields (summary, icon, color) live on the app record. `name` (1–40 characters) is required by the platform. The classes follow the platform's manifest structure ([Manifest](https://machinepulse-ai.github.io/karpoland-app-sdk/reference/manifest.html); `tests/test_spec.py` compares them). The SDK has no validator: check a manifest with the TypeScript CLI before publishing, `npm exec --no -- karpoland validate --manifest manifest.json` (`python -c "import json; from dice import dice_manifest; print(json.dumps(dice_manifest('1.0.0').to_dict(), ensure_ascii=False))" > manifest.json` writes one), or read the problems the publish reports.
|
|
340
|
+
|
|
341
|
+
`SessionKind(..., serial=True)` asks the platform to deliver one tool call or hook about a session of that kind at a time. A call that waited about 5 seconds answers `ABORTED` / `session.BUSY` (retryable).
|
|
342
|
+
|
|
343
|
+
## Testing (`karpoland.testing`)
|
|
344
|
+
|
|
345
|
+
| Name | What |
|
|
346
|
+
|---|---|
|
|
347
|
+
| `simulate(app, *, signing_secret, app="test-app", base_path="", install=…, caller=…, now=None)` (`SimulateOptions`; the keyword `app` is the slug in deliveries) | a `Simulator` posting deliveries signed as the platform does through `app.handle`; the app verifies with the same secret (its `signing_secret` override, or the mock platform's `GET /signing`) |
|
|
348
|
+
| `sim.call(tool, args=None, caller=…, *, id=, install=, session=, idempotency_key=, first_seen=, event=, command_message_id=)` (`CallOptions`) | a signed `POST /tools/<tool>` → `Answer(status, body)`. `caller=None`: a call in the app's own context; reuse `id` to replay |
|
|
349
|
+
| `sim.event(name, data, *, id=, install=, session_id=, resident_id=, attempt=1)` (`EventOptions`) | a signed `POST /hooks/<name>` |
|
|
350
|
+
| `sim.gate(applicant, *, room_id=, join_request_id=, note="", id=, install=)` (`GateInput`) | a join request delivery (`POST /hooks/member.join`) with `gate: true` |
|
|
351
|
+
| `sim.handshake(*, version="1.0.0", tools=None, hooks=None, challenge=None)` (`HandshakeInput`) | the publish handshake: 200 `{challenge}`; with `tools` and `hooks` 422 `app.HANDSHAKE_FAILED` when a handler is missing |
|
|
352
|
+
| `sim.idle()` | wait for work handlers left running (`defer`, `wait_until`) |
|
|
353
|
+
| `mock_platform()` | a `PlatformMock`, a fake platform API: `url`, `transport` (TypeScript's `fetch`; give both to `create_app` or `create_client`), `requests()`, `respond(method, path, answer)`, `last()`, `reset()` |
|
|
354
|
+
|
|
355
|
+
The default install is `{"id": "500", "room_id": "900", "version": "1.0.0"}` (`install=None` for none) and the default caller `{"id": "1001", "name": "Tester", "kind": "person"}`. `platform.respond("GET", "/sessions/*", {"status": 200, "body": {…}, "headers": {…}})` (a `MockAnswer`) answers a route from then on (the latest matching rule wins; `*` matches one segment; the path is an app-service route or a full path); the answer may be a function of the recorded request. Unscripted requests get 200 `{}`. Each `RecordedRequest` has `method`, `path`, `query`, `headers` (lower case) and `body` (JSON, or bytes).
|
|
356
|
+
|
|
357
|
+
`karpoland.signed_headers(secret, body, *, path, method="POST", call_id=, delivery_id=, ts=, event=, app=)` (`SignedHeadersOptions`) builds the headers the platform sends, for posting deliveries by hand; `sign(secret, timestamp, {"method", "path", "id"}, body)` (`SignedRequest`) and `verify_signature(secret, timestamp, req, body, signature, *, max_skew_seconds=, now=)` are the signature itself.
|
|
358
|
+
|
|
359
|
+
## The error table
|
|
360
|
+
|
|
361
|
+
Platform statuses; `AppError` uses the same table to choose its HTTP code.
|
|
362
|
+
|
|
363
|
+
| Status | HTTP | Retryable | Default action |
|
|
364
|
+
|---|---|---|---|
|
|
365
|
+
| `INVALID_ARGUMENT` | 400 | no | `fix_request` |
|
|
366
|
+
| `UNAUTHENTICATED` | 401 | no | `ask_owner` |
|
|
367
|
+
| `PERMISSION_DENIED` | 403 | no | `give_up` |
|
|
368
|
+
| `NOT_FOUND` | 404 | no | `give_up` |
|
|
369
|
+
| `ALREADY_EXISTS` | 409 | no | `treat_as_done` |
|
|
370
|
+
| `ABORTED` | 409 | yes | `retry` |
|
|
371
|
+
| `FAILED_PRECONDITION` | 412 | no | `give_up` |
|
|
372
|
+
| `RESOURCE_EXHAUSTED` | 429 | no | `retry_later` |
|
|
373
|
+
| `CANCELLED` | 499 | no | `give_up` |
|
|
374
|
+
| `INTERNAL` | 500 | yes | `retry_later` |
|
|
375
|
+
| `UNIMPLEMENTED` | 501 | no | `give_up` |
|
|
376
|
+
| `UNAVAILABLE` | 503 | yes | `wait` |
|
|
377
|
+
| `DEADLINE_EXCEEDED` | 504 | yes | `retry_later` |
|
|
378
|
+
|
|
379
|
+
Apps may return exactly the reasons in `APP_REASONS`: `app.RULE_VIOLATION`, `app.ALREADY_DONE`, `app.ITEM_UNAVAILABLE`, `app.DEADLINE_PASSED`, the `request.*` reasons, `session.FULL`, `session.CLOSED`, `session.NOT_STARTED`, `participant.NOT_AWAITED`, `participant.ALREADY_JOINED`, `quota.PER_OWNER` and `quota.DAILY`. The whole registry is `Reasons`, by domain (`Reasons.session.LIMIT_REACHED == "session.LIMIT_REACHED"`), and `STATUSES` maps each status to its `http`, `retryable` and `action`; both are generated from `spec/reasons.json` by `scripts/gen_reasons.py`.
|
|
380
|
+
|
|
381
|
+
## Development
|
|
382
|
+
|
|
383
|
+
```bash
|
|
384
|
+
uv venv -p 3.12 .venv && VIRTUAL_ENV=.venv uv pip install -e '.[dev,asgi]' # or python3 -m venv + pip
|
|
385
|
+
.venv/bin/pytest # the SDK's tests and the examples' (../examples/*/python)
|
|
386
|
+
.venv/bin/mypy # strict, SDK, tests and examples
|
|
387
|
+
python scripts/gen_reasons.py # after spec/reasons.json changes
|
|
388
|
+
.venv/bin/pytest tests/test_integration.py # against a real stack (KARPO_API, KARPO_IT_PEOPLE)
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
`tests/test_spec.py` compares the public names with `spec/api.json`: the exports of `karpoland`, `karpoland.manifest` and `karpoland.testing`, `Client` and `AsyncClient`, `App` and its options, the contexts, the dedupe store, the errors, the server and the test kit (names compare lower-cased without `_`; the only Python-specific names are listed there with their reason), and the manifest classes with `spec/manifest-fields.json`; `tests/test_fixtures.py` runs every case in [Conformance cases](https://machinepulse-ai.github.io/karpoland-app-sdk/guide/testing.html#fixtures) except `manifest.json` (TypeScript only), the delivery cases through `app.handle`, WSGI and ASGI.
|
|
392
|
+
|
|
393
|
+
The integration test registers an `sdkpy-…` app (through the older developer routes directly, so it also runs against a stack without `GET /v1/app-service/signing`; the app then runs with the `signing_secret` option) with `service_url` set to `http://127.0.0.1:<free port>`, verifies the domain, issues a key, publishes, installs into a room and calls the tool as `bob` (a sync result, an app error and a deferred call), then a per-owner quota, idempotent posts, an idempotent session create, `participants.add`, end, `rematch`, the status filter and `share`, and a join request gate round trip with `carol` (approve, then pending followed by `join_requests.decide`). Afterwards it uninstalls the app and sets the room's join rule back to `open`.
|