appsocom 0.6.0__tar.gz → 0.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.
- {appsocom-0.6.0 → appsocom-0.7.0}/PKG-INFO +33 -2
- appsocom-0.7.0/README.md +74 -0
- {appsocom-0.6.0 → appsocom-0.7.0}/appsocom/__init__.py +268 -5
- {appsocom-0.6.0 → appsocom-0.7.0}/appsocom.egg-info/PKG-INFO +33 -2
- {appsocom-0.6.0 → appsocom-0.7.0}/pyproject.toml +1 -1
- appsocom-0.7.0/tests/test_sfukit.py +300 -0
- appsocom-0.6.0/README.md +0 -43
- appsocom-0.6.0/tests/test_sfukit.py +0 -142
- {appsocom-0.6.0 → appsocom-0.7.0}/LICENSE +0 -0
- {appsocom-0.6.0 → appsocom-0.7.0}/appsocom.egg-info/SOURCES.txt +0 -0
- {appsocom-0.6.0 → appsocom-0.7.0}/appsocom.egg-info/dependency_links.txt +0 -0
- {appsocom-0.6.0 → appsocom-0.7.0}/appsocom.egg-info/top_level.txt +0 -0
- {appsocom-0.6.0 → appsocom-0.7.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: appsocom
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.0
|
|
4
4
|
Summary: Python server SDK for Appsocom Live video calls: join tokens, rooms, moderation and webhook verification
|
|
5
5
|
Author: Appsotech Limited
|
|
6
6
|
License-Expression: MIT
|
|
@@ -55,7 +55,38 @@ def hook():
|
|
|
55
55
|
return "", 204
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
## AI assistant
|
|
59
|
+
|
|
60
|
+
Tell the assistant about your app once, mint a token for each signed-in person, and answer its tool calls at your `toolsUrl`:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from appsocom import AssistantToolError, assistant_tools
|
|
64
|
+
|
|
65
|
+
kit.set_assistant_config({
|
|
66
|
+
"name": "Ada",
|
|
67
|
+
"toolsUrl": "https://app.example/assistant-tools",
|
|
68
|
+
"tools": [{"name": "list_students", "description": "Students in a class", "parameters": {"type": "object", "properties": {"cls": {"type": "string"}}}}],
|
|
69
|
+
"appMap": [{"label": "Fees", "path": "/fees", "aliases": ["bursary"]}],
|
|
70
|
+
})
|
|
71
|
+
tok = kit.create_assistant_token(user.id, name=user.name, role=user.role, metadata={"school": user.school_id})
|
|
72
|
+
# give tok["token"] to the browser (@appsocom/react <AssistantPanel>)
|
|
73
|
+
|
|
74
|
+
def list_students(args, call): # runs as the person who asked
|
|
75
|
+
if call["role"] != "teacher":
|
|
76
|
+
raise AssistantToolError("Only teachers can list students.") # the model sees this message
|
|
77
|
+
return db.students(call["metadata"]["school"], args["cls"])
|
|
78
|
+
|
|
79
|
+
tools = assistant_tools(os.environ["APPSOCOM_WEBHOOK_SECRET"], {"list_students": list_students})
|
|
80
|
+
|
|
81
|
+
@app.post("/assistant-tools")
|
|
82
|
+
def assistant_tools_route():
|
|
83
|
+
status, body = tools.handle(request.get_data(), request.headers.get("X-SfuKit-Signature"))
|
|
84
|
+
return body, status, {"Content-Type": "application/json"}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`handle()` refuses bad or stale signatures with 401, answers `{"result": ...}` (`"done"` when a tool returns `None`) or `{"error": ...}`, and hides any exception other than `AssistantToolError` as "The tool failed." (pass `on_error=` to see it). Also: `get_assistant_config`, `delete_assistant_conversation(user_id, conversation_id)`, `verify_assistant_tool_call`.
|
|
88
|
+
|
|
89
|
+
All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
|
|
59
90
|
|
|
60
91
|
Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
|
|
61
92
|
|
appsocom-0.7.0/README.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# appsocom (Python)
|
|
2
|
+
|
|
3
|
+
Python server SDK for [Appsocom Live](https://live.appsocom.com): mint join tokens, manage rooms and participants, moderate and verify webhooks. Python 3.9+, standard library only.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install appsocom
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
import os
|
|
11
|
+
from appsocom import SfuKit, SfuKitError, verify_webhook
|
|
12
|
+
|
|
13
|
+
kit = SfuKit("https://api.appsocom.dev", os.environ["APPSOCOM_API_KEY"]) # project API key from the console
|
|
14
|
+
|
|
15
|
+
tok = kit.create_token("class-1", "u_7", name="Ada", role="student", metadata={"seat": 3})
|
|
16
|
+
tok["token"], tok["expiresAt"]
|
|
17
|
+
|
|
18
|
+
kit.set_role("class-1", "u_9", "student") # promote an observer
|
|
19
|
+
kit.mute("class-1", "*", ["mic"], lock=True) # mute everyone, keep them muted
|
|
20
|
+
kit.set_room_metadata("class-1", {"topic": "Fractions"})
|
|
21
|
+
kit.set_track_permissions("class-1", "u_7", {"allowAll": False, "allow": [{"userId": "u_1"}]})
|
|
22
|
+
kit.remove_participant("class-1", "u_8", ban=True)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Errors raise `SfuKitError` with `.status` and `.body`.
|
|
26
|
+
|
|
27
|
+
Webhooks (Flask):
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
@app.post("/appsocom-webhooks")
|
|
31
|
+
def hook():
|
|
32
|
+
event = verify_webhook(os.environ["APPSOCOM_WEBHOOK_SECRET"], request.get_data(), request.headers.get("X-SfuKit-Signature"))
|
|
33
|
+
if event is None:
|
|
34
|
+
return "", 401
|
|
35
|
+
print(event["event"], event["roomId"])
|
|
36
|
+
return "", 204
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## AI assistant
|
|
40
|
+
|
|
41
|
+
Tell the assistant about your app once, mint a token for each signed-in person, and answer its tool calls at your `toolsUrl`:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from appsocom import AssistantToolError, assistant_tools
|
|
45
|
+
|
|
46
|
+
kit.set_assistant_config({
|
|
47
|
+
"name": "Ada",
|
|
48
|
+
"toolsUrl": "https://app.example/assistant-tools",
|
|
49
|
+
"tools": [{"name": "list_students", "description": "Students in a class", "parameters": {"type": "object", "properties": {"cls": {"type": "string"}}}}],
|
|
50
|
+
"appMap": [{"label": "Fees", "path": "/fees", "aliases": ["bursary"]}],
|
|
51
|
+
})
|
|
52
|
+
tok = kit.create_assistant_token(user.id, name=user.name, role=user.role, metadata={"school": user.school_id})
|
|
53
|
+
# give tok["token"] to the browser (@appsocom/react <AssistantPanel>)
|
|
54
|
+
|
|
55
|
+
def list_students(args, call): # runs as the person who asked
|
|
56
|
+
if call["role"] != "teacher":
|
|
57
|
+
raise AssistantToolError("Only teachers can list students.") # the model sees this message
|
|
58
|
+
return db.students(call["metadata"]["school"], args["cls"])
|
|
59
|
+
|
|
60
|
+
tools = assistant_tools(os.environ["APPSOCOM_WEBHOOK_SECRET"], {"list_students": list_students})
|
|
61
|
+
|
|
62
|
+
@app.post("/assistant-tools")
|
|
63
|
+
def assistant_tools_route():
|
|
64
|
+
status, body = tools.handle(request.get_data(), request.headers.get("X-SfuKit-Signature"))
|
|
65
|
+
return body, status, {"Content-Type": "application/json"}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`handle()` refuses bad or stale signatures with 401, answers `{"result": ...}` (`"done"` when a tool returns `None`) or `{"error": ...}`, and hides any exception other than `AssistantToolError` as "The tool failed." (pass `on_error=` to see it). Also: `get_assistant_config`, `delete_assistant_conversation(user_id, conversation_id)`, `verify_assistant_tool_call`.
|
|
69
|
+
|
|
70
|
+
All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
|
|
71
|
+
|
|
72
|
+
Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
|
|
73
|
+
|
|
74
|
+
Docs: [docs.appsocom.dev](https://docs.appsocom.dev) · License: MIT
|
|
@@ -16,13 +16,27 @@ import time
|
|
|
16
16
|
import urllib.error
|
|
17
17
|
import urllib.parse
|
|
18
18
|
import urllib.request
|
|
19
|
-
from typing import Any, Dict, List, Optional, Sequence, Union
|
|
20
|
-
|
|
21
|
-
__all__ = [
|
|
22
|
-
|
|
19
|
+
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"SfuKit",
|
|
23
|
+
"SfuKitError",
|
|
24
|
+
"sign_token",
|
|
25
|
+
"verify_webhook",
|
|
26
|
+
"sign_webhook",
|
|
27
|
+
"SIGNATURE_HEADER",
|
|
28
|
+
"AssistantToolError",
|
|
29
|
+
"AssistantTools",
|
|
30
|
+
"assistant_tools",
|
|
31
|
+
"verify_assistant_tool_call",
|
|
32
|
+
]
|
|
33
|
+
__version__ = "0.7.0"
|
|
23
34
|
|
|
24
35
|
SIGNATURE_HEADER = "X-SfuKit-Signature"
|
|
25
36
|
_ID = re.compile(r"^[A-Za-z0-9._:@-]{1,128}$")
|
|
37
|
+
# The kit's own patterns for the parts of a recording download path.
|
|
38
|
+
_RECORDING_ID = re.compile(r"^[A-Za-z0-9-]{1,64}$")
|
|
39
|
+
_RECORDING_FILE = re.compile(r"^[A-Za-z0-9._@-]{1,128}$")
|
|
26
40
|
_ROLE = re.compile(r"^[A-Za-z0-9._-]{1,32}$")
|
|
27
41
|
_ROLE_DEFAULTS = {
|
|
28
42
|
"teacher": {"mic": True, "camera": True, "screen": True, "moderate": True},
|
|
@@ -42,7 +56,8 @@ class SfuKitError(Exception):
|
|
|
42
56
|
|
|
43
57
|
|
|
44
58
|
def _id(value: str) -> str:
|
|
45
|
-
|
|
59
|
+
# "." and ".." would be resolved as dot segments, sending the request to a different route.
|
|
60
|
+
if not isinstance(value, str) or not _ID.match(value) or value in (".", ".."):
|
|
46
61
|
raise SfuKitError(400, f'invalid id "{value}" (letters, numbers, . _ : @ -, max 128)')
|
|
47
62
|
return urllib.parse.quote(value, safe="")
|
|
48
63
|
|
|
@@ -227,6 +242,10 @@ class SfuKit:
|
|
|
227
242
|
return self.request("GET", f"/rooms/{_id(room_id)}/recordings")["recordings"]
|
|
228
243
|
|
|
229
244
|
def download_recording(self, room_id: str, recording_id: str, file: str) -> bytes:
|
|
245
|
+
if not isinstance(recording_id, str) or not _RECORDING_ID.fullmatch(recording_id):
|
|
246
|
+
raise SfuKitError(400, f'invalid recording id "{recording_id}" (letters, numbers, -, max 64)')
|
|
247
|
+
if not isinstance(file, str) or not _RECORDING_FILE.fullmatch(file) or file in (".", ".."):
|
|
248
|
+
raise SfuKitError(400, f'invalid recording file "{file}" (letters, numbers, . _ @ -, max 128, not . or ..)')
|
|
230
249
|
q = urllib.parse.quote
|
|
231
250
|
return self.request("GET", f"/rooms/{_id(room_id)}/recordings/{q(recording_id, safe='')}/{q(file, safe='')}", raw=bytes)
|
|
232
251
|
|
|
@@ -253,6 +272,93 @@ class SfuKit:
|
|
|
253
272
|
"""A finished lesson's report: summary, per-learner results and feedback, alerts, transcript."""
|
|
254
273
|
return self.request("GET", f"/lessons/{_id(lesson_id)}/report")
|
|
255
274
|
|
|
275
|
+
# ---------- AI Presenter (product demos and walkthroughs) ----------
|
|
276
|
+
|
|
277
|
+
def start_presenter(self, room_id: str, **options: Any) -> Dict[str, Any]:
|
|
278
|
+
"""Start an AI Presenter from an approved presentation kit. options: planId (or lesson), lead ("ai"|"human"),
|
|
279
|
+
name, voice, avatar, reportEmails, webhookUrl, maxMinutes. Returns {"presentationId", "lessonId", "agentId", ...}.
|
|
280
|
+
Stop it with stop_lesson."""
|
|
281
|
+
return self.request("POST", f"/rooms/{_id(room_id)}/presenter", options)
|
|
282
|
+
|
|
283
|
+
def set_presenter_lead(self, room_id: str, presentation_id: str, lead: str) -> None:
|
|
284
|
+
"""lead: "ai" or "human"."""
|
|
285
|
+
self.control_lesson(room_id, presentation_id, "lead", lead=lead)
|
|
286
|
+
|
|
287
|
+
def presenter_browser(self, room_id: str, presentation_id: str, action: Union[str, Dict[str, Any]]) -> None:
|
|
288
|
+
"""The live demo's cloud browser: "take", "give", "close", or an op such as
|
|
289
|
+
{"op": "click-at", "x": 0.4, "y": 0.2} or {"op": "scroll", "direction": "down"}."""
|
|
290
|
+
if isinstance(action, dict):
|
|
291
|
+
self.control_lesson(room_id, presentation_id, "browser", browser="op", op=action)
|
|
292
|
+
else:
|
|
293
|
+
self.control_lesson(room_id, presentation_id, "browser", browser=action)
|
|
294
|
+
|
|
295
|
+
def upload_presentation_assets(self, files: Sequence[tuple]) -> Dict[str, Any]:
|
|
296
|
+
"""files: [(filename, bytes), ...] screenshots (PNG, JPEG, WebP, GIF; up to 5 MB each, 20 at once).
|
|
297
|
+
Returns {"assets": [{"name", "url"}]}: use the links as screen imageUrl in the kit."""
|
|
298
|
+
types = {"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "webp": "image/webp", "gif": "image/gif"}
|
|
299
|
+
boundary = "sfukit" + hashlib.sha256(str(time.time()).encode()).hexdigest()[:24]
|
|
300
|
+
parts: List[bytes] = []
|
|
301
|
+
for name, data in files:
|
|
302
|
+
safe = str(name).replace('"', "").replace("\r", "").replace("\n", "")
|
|
303
|
+
ctype = types.get(safe.rsplit(".", 1)[-1].lower(), "application/octet-stream")
|
|
304
|
+
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{safe}"\r\nContent-Type: {ctype}\r\n\r\n'.encode("utf-8") + bytes(data) + b"\r\n")
|
|
305
|
+
parts.append(f"--{boundary}--\r\n".encode("utf-8"))
|
|
306
|
+
return self.request("POST", "/presentation-assets", _encoded=(b"".join(parts), f"multipart/form-data; boundary={boundary}"))
|
|
307
|
+
|
|
308
|
+
def list_presentation_reports(self, plan_id: Optional[str] = None) -> Dict[str, Any]:
|
|
309
|
+
"""Presentations that ended, newest first (optionally of one kit): {"presentations": [...]}."""
|
|
310
|
+
q = f"?planId={urllib.parse.quote(plan_id, safe='')}" if plan_id is not None else ""
|
|
311
|
+
return self.request("GET", f"/presentation-reports{q}")
|
|
312
|
+
|
|
313
|
+
def get_presentation_report(self, report_id: str) -> Dict[str, Any]:
|
|
314
|
+
"""One presentation: summary, recommendations, questions and suggestions."""
|
|
315
|
+
return self.request("GET", f"/presentation-reports/{_id(report_id)}")
|
|
316
|
+
|
|
317
|
+
def review_suggestion(self, report_id: str, index: int, status: str) -> Dict[str, Any]:
|
|
318
|
+
"""status: "new", "reviewed", "accepted" or "dismissed"."""
|
|
319
|
+
return self.request("PUT", f"/presentation-reports/{_id(report_id)}/suggestions/{int(index)}", {"status": status})
|
|
320
|
+
|
|
321
|
+
# ---- self-running presentations: a link the AI Presenter presents on its own, privately to each visitor
|
|
322
|
+
|
|
323
|
+
def create_presentation_link(self, plan_id: str, **options: Any) -> Dict[str, Any]:
|
|
324
|
+
"""A link from an approved kit. options: title, name, voice, avatar, reportEmails, askDetails,
|
|
325
|
+
maxMinutes (30), perDay (50), maxConcurrent (5), active."""
|
|
326
|
+
return self.request("POST", "/presentation-links", {"planId": plan_id, **options})
|
|
327
|
+
|
|
328
|
+
def list_presentation_links(self) -> Dict[str, Any]:
|
|
329
|
+
return self.request("GET", "/presentation-links")
|
|
330
|
+
|
|
331
|
+
def get_presentation_link(self, link_id: str) -> Dict[str, Any]:
|
|
332
|
+
return self.request("GET", f"/presentation-links/{_id(link_id)}")
|
|
333
|
+
|
|
334
|
+
def update_presentation_link(self, link_id: str, **patch: Any) -> Dict[str, Any]:
|
|
335
|
+
"""Fields you leave out stay; active=False closes the link."""
|
|
336
|
+
return self.request("PATCH", f"/presentation-links/{_id(link_id)}", patch)
|
|
337
|
+
|
|
338
|
+
def delete_presentation_link(self, link_id: str) -> None:
|
|
339
|
+
self.request("DELETE", f"/presentation-links/{_id(link_id)}")
|
|
340
|
+
|
|
341
|
+
def start_presentation_session(self, link_id: str, name: Optional[str] = None, email: Optional[str] = None, company: Optional[str] = None, phone: Optional[str] = None) -> Dict[str, Any]:
|
|
342
|
+
"""A visitor opened the link. Returns {"sessionId", "roomId", "token", "expiresAt"}; the presenter
|
|
343
|
+
starts when they join. Past the link's limits the API answers 429."""
|
|
344
|
+
visitor = {k: v for k, v in {"name": name, "email": email, "company": company, "phone": phone}.items() if v}
|
|
345
|
+
return self.request("POST", f"/presentation-links/{_id(link_id)}/sessions", {"visitor": visitor})
|
|
346
|
+
|
|
347
|
+
def list_presentation_sessions(self, link_id: Optional[str] = None) -> Dict[str, Any]:
|
|
348
|
+
"""Visitors and their leads, newest first: {"sessions": [...]}."""
|
|
349
|
+
q = f"?linkId={urllib.parse.quote(link_id, safe='')}" if link_id else ""
|
|
350
|
+
return self.request("GET", f"/presentation-sessions{q}")
|
|
351
|
+
|
|
352
|
+
def get_presentation_session(self, session_id: str) -> Dict[str, Any]:
|
|
353
|
+
return self.request("GET", f"/presentation-sessions/{_id(session_id)}")
|
|
354
|
+
|
|
355
|
+
def join_presentation_session(self, session_id: str, name: str, user_id: Optional[str] = None) -> Dict[str, Any]:
|
|
356
|
+
"""A host token for a colleague to step into a visitor's presentation."""
|
|
357
|
+
body: Dict[str, Any] = {"name": name}
|
|
358
|
+
if user_id:
|
|
359
|
+
body["userId"] = user_id
|
|
360
|
+
return self.request("POST", f"/presentation-sessions/{_id(session_id)}/join", body)
|
|
361
|
+
|
|
256
362
|
def learner_progress(self, learner_id: str) -> Dict[str, Any]:
|
|
257
363
|
return self.request("GET", f"/learners/{urllib.parse.quote(learner_id, safe='')}/progress")
|
|
258
364
|
|
|
@@ -362,6 +468,39 @@ class SfuKit:
|
|
|
362
468
|
def skip_timetable_run(self, key: str) -> Dict[str, Any]:
|
|
363
469
|
return self.request("POST", f"/timetable-runs/{urllib.parse.quote(key, safe='')}/skip")
|
|
364
470
|
|
|
471
|
+
# ---------- AI assistant ----------
|
|
472
|
+
|
|
473
|
+
def set_assistant_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
|
|
474
|
+
"""Tell the assistant about your app; replaces the whole config.
|
|
475
|
+
|
|
476
|
+
config uses the API's own keys: name, instructions, tools ([{name, description,
|
|
477
|
+
parameters, risk, pinned, assistantAllowed}]), toolsUrl, appMap ([{label, path,
|
|
478
|
+
description, aliases}]), defaultTier, roleTiers, knowledge, retentionDays.
|
|
479
|
+
"""
|
|
480
|
+
return self.request("PUT", "/assistant/config", config)["config"]
|
|
481
|
+
|
|
482
|
+
def get_assistant_config(self) -> Dict[str, Any]:
|
|
483
|
+
return self.request("GET", "/assistant/config")["config"]
|
|
484
|
+
|
|
485
|
+
def create_assistant_token(self, user_id: str, **options: Any) -> Dict[str, Any]:
|
|
486
|
+
"""A token for one signed-in person to chat with the assistant: {"token", "conversationId", "expiresAt"}.
|
|
487
|
+
|
|
488
|
+
options: name, role, conversation_id, tools (names), paths, tier, retention_days,
|
|
489
|
+
monthly_messages (this person's messages per month), metadata (dict of strings, passed back with every tool call),
|
|
490
|
+
context (what your app knows about this person that the assistant should always have, at most 3,000 characters),
|
|
491
|
+
report_usage (add tier, units, cost and tokens to the done event; for a backend that relays answers), ttl_seconds (default 3600, max 43200).
|
|
492
|
+
"""
|
|
493
|
+
body: Dict[str, Any] = {"userId": user_id}
|
|
494
|
+
names = {"conversation_id": "conversationId", "retention_days": "retentionDays", "monthly_messages": "monthlyMessages", "report_usage": "reportUsage", "ttl_seconds": "ttlSeconds"}
|
|
495
|
+
for k, v in options.items():
|
|
496
|
+
if v is not None:
|
|
497
|
+
body[names.get(k, k)] = v
|
|
498
|
+
return self.request("POST", "/assistant/tokens", body)
|
|
499
|
+
|
|
500
|
+
def delete_assistant_conversation(self, user_id: str, conversation_id: str) -> None:
|
|
501
|
+
"""Forget one person's conversation (its memory and transcript)."""
|
|
502
|
+
self.request("DELETE", f"/assistant/conversations/{_id(user_id)}/{_id(conversation_id)}")
|
|
503
|
+
|
|
365
504
|
def health(self) -> Dict[str, Any]:
|
|
366
505
|
return self.request("GET", "/health")
|
|
367
506
|
|
|
@@ -498,3 +637,127 @@ def sign_webhook(secret: str, raw_body: Union[str, bytes], t: Optional[int] = No
|
|
|
498
637
|
t = int(time.time()) if t is None else t
|
|
499
638
|
body = raw_body if isinstance(raw_body, bytes) else raw_body.encode("utf-8")
|
|
500
639
|
return f"t={t},v1=" + hmac.new(secret.encode(), str(t).encode() + b"." + body, hashlib.sha256).hexdigest()
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
# ---------- AI assistant tools (your toolsUrl) ----------
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
class AssistantToolError(Exception):
|
|
646
|
+
"""Raise this from a tool to tell the model what went wrong (its message is shown to the model)."""
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _parse_signature(signature_header: str) -> Optional[tuple]:
|
|
650
|
+
parts = {}
|
|
651
|
+
for p in signature_header.split(","):
|
|
652
|
+
k, _, v = p.partition("=")
|
|
653
|
+
parts[k.strip()] = v.strip()
|
|
654
|
+
try:
|
|
655
|
+
t = int(parts.get("t", ""))
|
|
656
|
+
except ValueError:
|
|
657
|
+
return None
|
|
658
|
+
v1 = parts.get("v1", "")
|
|
659
|
+
if not re.fullmatch(r"[0-9a-f]{64}", v1):
|
|
660
|
+
return None
|
|
661
|
+
return t, v1
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def verify_assistant_tool_call(
|
|
665
|
+
secret: str, raw_body: Union[str, bytes], signature_header: Optional[str], tolerance_seconds: int = 300
|
|
666
|
+
) -> Optional[Dict[str, Any]]:
|
|
667
|
+
"""Check a tool call's signature; the call dict, or None when it is wrong, stale or not an assistant call."""
|
|
668
|
+
if not secret or not signature_header:
|
|
669
|
+
return None
|
|
670
|
+
parsed = _parse_signature(signature_header)
|
|
671
|
+
if parsed is None:
|
|
672
|
+
return None
|
|
673
|
+
t, v1 = parsed
|
|
674
|
+
if abs(time.time() - t) > tolerance_seconds:
|
|
675
|
+
return None
|
|
676
|
+
body = raw_body if isinstance(raw_body, bytes) else raw_body.encode("utf-8")
|
|
677
|
+
expected = hmac.new(secret.encode(), str(t).encode() + b"." + body, hashlib.sha256).hexdigest()
|
|
678
|
+
if not hmac.compare_digest(expected, v1):
|
|
679
|
+
return None
|
|
680
|
+
try:
|
|
681
|
+
call = json.loads(body)
|
|
682
|
+
except ValueError:
|
|
683
|
+
return None
|
|
684
|
+
if not isinstance(call, dict) or call.get("type") != "tool_call" or call.get("kind") != "assistant" or not isinstance(call.get("name"), str):
|
|
685
|
+
return None
|
|
686
|
+
call["arguments"] = call.get("arguments") or {}
|
|
687
|
+
call["metadata"] = call.get("metadata") or {}
|
|
688
|
+
return call
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
class AssistantTools:
|
|
692
|
+
"""Your toolsUrl: checks each request's signature and runs the matching handler.
|
|
693
|
+
|
|
694
|
+
A handler is called as handler(arguments, call); `call` has conversationId, userId,
|
|
695
|
+
role, callId, name and metadata. What it returns goes back to the model (keep it
|
|
696
|
+
small: at most 16 KB is read). Returning None sends "done".
|
|
697
|
+
"""
|
|
698
|
+
|
|
699
|
+
def __init__(
|
|
700
|
+
self,
|
|
701
|
+
secret: str,
|
|
702
|
+
handlers: Dict[str, Callable[[Dict[str, Any], Dict[str, Any]], Any]],
|
|
703
|
+
tolerance_seconds: int = 300,
|
|
704
|
+
on_error: Optional[Callable[[BaseException, Dict[str, Any]], None]] = None,
|
|
705
|
+
):
|
|
706
|
+
if not secret:
|
|
707
|
+
raise ValueError("secret is required (your webhook secret)")
|
|
708
|
+
self._secret = secret
|
|
709
|
+
self._handlers = dict(handlers)
|
|
710
|
+
self.tolerance_seconds = tolerance_seconds
|
|
711
|
+
self.on_error = on_error
|
|
712
|
+
|
|
713
|
+
def verify(self, raw_body: Union[str, bytes], signature_header: Optional[str]) -> Optional[Dict[str, Any]]:
|
|
714
|
+
return verify_assistant_tool_call(self._secret, raw_body, signature_header, self.tolerance_seconds)
|
|
715
|
+
|
|
716
|
+
def handle(self, raw_body: Union[str, bytes], signature_header: Optional[str]) -> Tuple[int, str]:
|
|
717
|
+
"""Check, run and answer one call. Pass the RAW body. Returns (status, JSON body) to send."""
|
|
718
|
+
call = self.verify(raw_body, signature_header)
|
|
719
|
+
if call is None:
|
|
720
|
+
return 401, _json({"error": "bad signature"})
|
|
721
|
+
handler = self._handlers.get(call["name"])
|
|
722
|
+
if handler is None:
|
|
723
|
+
return 200, _json({"error": f"There is no tool called {call['name']}."})
|
|
724
|
+
try:
|
|
725
|
+
result = handler(call["arguments"], call)
|
|
726
|
+
except AssistantToolError as e:
|
|
727
|
+
return 200, _json({"error": str(e)})
|
|
728
|
+
except Exception as e: # noqa: BLE001 (any other failure is hidden from the model)
|
|
729
|
+
if self.on_error is not None:
|
|
730
|
+
try:
|
|
731
|
+
self.on_error(e, call)
|
|
732
|
+
except Exception: # noqa: BLE001
|
|
733
|
+
pass
|
|
734
|
+
return 200, _json({"error": "The tool failed."})
|
|
735
|
+
try:
|
|
736
|
+
return 200, _json({"result": "done" if result is None else result})
|
|
737
|
+
except (TypeError, ValueError) as e:
|
|
738
|
+
if self.on_error is not None:
|
|
739
|
+
try:
|
|
740
|
+
self.on_error(e, call)
|
|
741
|
+
except Exception: # noqa: BLE001
|
|
742
|
+
pass
|
|
743
|
+
return 200, _json({"error": "The tool failed."})
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def assistant_tools(
|
|
747
|
+
secret: str,
|
|
748
|
+
handlers: Dict[str, Callable[[Dict[str, Any], Dict[str, Any]], Any]],
|
|
749
|
+
tolerance_seconds: int = 300,
|
|
750
|
+
on_error: Optional[Callable[[BaseException, Dict[str, Any]], None]] = None,
|
|
751
|
+
) -> AssistantTools:
|
|
752
|
+
"""Your toolsUrl in one call. `secret` is your webhook secret.
|
|
753
|
+
|
|
754
|
+
tools = assistant_tools(os.environ["APPSOCOM_WEBHOOK_SECRET"], {
|
|
755
|
+
"list_students": lambda args, call: db.students(call["metadata"]["school"], args["cls"]),
|
|
756
|
+
})
|
|
757
|
+
|
|
758
|
+
@app.post("/assistant-tools")
|
|
759
|
+
def assistant_tools_route():
|
|
760
|
+
status, body = tools.handle(request.get_data(), request.headers.get("X-SfuKit-Signature"))
|
|
761
|
+
return body, status, {"Content-Type": "application/json"}
|
|
762
|
+
"""
|
|
763
|
+
return AssistantTools(secret, handlers, tolerance_seconds=tolerance_seconds, on_error=on_error)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: appsocom
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.0
|
|
4
4
|
Summary: Python server SDK for Appsocom Live video calls: join tokens, rooms, moderation and webhook verification
|
|
5
5
|
Author: Appsotech Limited
|
|
6
6
|
License-Expression: MIT
|
|
@@ -55,7 +55,38 @@ def hook():
|
|
|
55
55
|
return "", 204
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
## AI assistant
|
|
59
|
+
|
|
60
|
+
Tell the assistant about your app once, mint a token for each signed-in person, and answer its tool calls at your `toolsUrl`:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from appsocom import AssistantToolError, assistant_tools
|
|
64
|
+
|
|
65
|
+
kit.set_assistant_config({
|
|
66
|
+
"name": "Ada",
|
|
67
|
+
"toolsUrl": "https://app.example/assistant-tools",
|
|
68
|
+
"tools": [{"name": "list_students", "description": "Students in a class", "parameters": {"type": "object", "properties": {"cls": {"type": "string"}}}}],
|
|
69
|
+
"appMap": [{"label": "Fees", "path": "/fees", "aliases": ["bursary"]}],
|
|
70
|
+
})
|
|
71
|
+
tok = kit.create_assistant_token(user.id, name=user.name, role=user.role, metadata={"school": user.school_id})
|
|
72
|
+
# give tok["token"] to the browser (@appsocom/react <AssistantPanel>)
|
|
73
|
+
|
|
74
|
+
def list_students(args, call): # runs as the person who asked
|
|
75
|
+
if call["role"] != "teacher":
|
|
76
|
+
raise AssistantToolError("Only teachers can list students.") # the model sees this message
|
|
77
|
+
return db.students(call["metadata"]["school"], args["cls"])
|
|
78
|
+
|
|
79
|
+
tools = assistant_tools(os.environ["APPSOCOM_WEBHOOK_SECRET"], {"list_students": list_students})
|
|
80
|
+
|
|
81
|
+
@app.post("/assistant-tools")
|
|
82
|
+
def assistant_tools_route():
|
|
83
|
+
status, body = tools.handle(request.get_data(), request.headers.get("X-SfuKit-Signature"))
|
|
84
|
+
return body, status, {"Content-Type": "application/json"}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`handle()` refuses bad or stale signatures with 401, answers `{"result": ...}` (`"done"` when a tool returns `None`) or `{"error": ...}`, and hides any exception other than `AssistantToolError` as "The tool failed." (pass `on_error=` to see it). Also: `get_assistant_config`, `delete_assistant_conversation(user_id, conversation_id)`, `verify_assistant_tool_call`.
|
|
88
|
+
|
|
89
|
+
All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
|
|
59
90
|
|
|
60
91
|
Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
|
|
61
92
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "appsocom"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.7.0"
|
|
8
8
|
description = "Python server SDK for Appsocom Live video calls: join tokens, rooms, moderation and webhook verification"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
import json
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
import unittest
|
|
8
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
9
|
+
|
|
10
|
+
from appsocom import (
|
|
11
|
+
AssistantToolError,
|
|
12
|
+
SfuKit,
|
|
13
|
+
SfuKitError,
|
|
14
|
+
assistant_tools,
|
|
15
|
+
sign_token,
|
|
16
|
+
sign_webhook,
|
|
17
|
+
verify_assistant_tool_call,
|
|
18
|
+
verify_webhook,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
SECRET = "x" * 40
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def decode(part):
|
|
25
|
+
return json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TokenTests(unittest.TestCase):
|
|
29
|
+
def test_signs_hs256_with_role_defaults_and_metadata(self):
|
|
30
|
+
t = sign_token(SECRET, "r1", "u1", role="student", metadata={"seat": 3}, permissions={"screen": True})
|
|
31
|
+
head, body, sig = t["token"].split(".")
|
|
32
|
+
self.assertEqual(decode(head), {"alg": "HS256", "typ": "JWT"})
|
|
33
|
+
claims = decode(body)
|
|
34
|
+
self.assertEqual(claims["sub"], "u1")
|
|
35
|
+
self.assertEqual(claims["room"], "r1")
|
|
36
|
+
self.assertEqual(claims["aud"], "sfukit")
|
|
37
|
+
self.assertEqual(claims["role"], "student")
|
|
38
|
+
self.assertEqual(claims["md"], {"seat": 3})
|
|
39
|
+
self.assertEqual(claims["perm"], {"mic": True, "camera": True, "screen": True, "moderate": False})
|
|
40
|
+
self.assertEqual(claims["exp"] - claims["iat"], 7200)
|
|
41
|
+
want = hmac.new(SECRET.encode(), f"{head}.{body}".encode(), hashlib.sha256).digest()
|
|
42
|
+
self.assertEqual(base64.urlsafe_b64encode(want).rstrip(b"=").decode(), sig)
|
|
43
|
+
|
|
44
|
+
def test_rejects_bad_input(self):
|
|
45
|
+
with self.assertRaises(ValueError):
|
|
46
|
+
sign_token("short", "r1", "u1")
|
|
47
|
+
with self.assertRaises(ValueError):
|
|
48
|
+
sign_token(SECRET, "bad room", "u1")
|
|
49
|
+
with self.assertRaises(ValueError):
|
|
50
|
+
sign_token(SECRET, "r1", "u1", max_participants=1)
|
|
51
|
+
with self.assertRaises(ValueError):
|
|
52
|
+
sign_token(SECRET, "r1", "u1", metadata={"x": "y" * 5000})
|
|
53
|
+
|
|
54
|
+
def test_client_signs_locally_with_secret(self):
|
|
55
|
+
kit = SfuKit("http://127.0.0.1:1", "k", jwt_secret=SECRET)
|
|
56
|
+
self.assertEqual(decode(kit.create_token("r1", "u1")["token"].split(".")[1])["sub"], "u1")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class WebhookTests(unittest.TestCase):
|
|
60
|
+
def test_round_trip(self):
|
|
61
|
+
body = '{"id":"evt_1","event":"room_started"}'
|
|
62
|
+
sig = sign_webhook("s", body)
|
|
63
|
+
self.assertEqual(verify_webhook("s", body, sig)["id"], "evt_1")
|
|
64
|
+
self.assertEqual(verify_webhook("s", body.encode(), sig)["id"], "evt_1")
|
|
65
|
+
self.assertIsNone(verify_webhook("s", body + " ", sig))
|
|
66
|
+
self.assertIsNone(verify_webhook("other", body, sig))
|
|
67
|
+
self.assertIsNone(verify_webhook("s", body, None))
|
|
68
|
+
old = sign_webhook("s", body, int(time.time()) - 600)
|
|
69
|
+
self.assertIsNone(verify_webhook("s", body, old))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Handler(BaseHTTPRequestHandler):
|
|
73
|
+
seen = []
|
|
74
|
+
|
|
75
|
+
def log_message(self, *a):
|
|
76
|
+
pass
|
|
77
|
+
|
|
78
|
+
def _go(self):
|
|
79
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
80
|
+
body = json.loads(self.rfile.read(n)) if n else None
|
|
81
|
+
Handler.seen.append((self.command, self.path, self.headers.get("Authorization"), body))
|
|
82
|
+
if self.path == "/assistant/config":
|
|
83
|
+
out, code = {"config": body if self.command == "PUT" else {"name": "Ada"}}, 200
|
|
84
|
+
elif self.path == "/assistant/tokens":
|
|
85
|
+
out, code = {"token": "t", "conversationId": body.get("conversationId", "new"), "expiresAt": 1}, 200
|
|
86
|
+
elif self.path.startswith("/assistant/conversations/"):
|
|
87
|
+
self.send_response(204)
|
|
88
|
+
self.end_headers()
|
|
89
|
+
return
|
|
90
|
+
elif self.path.startswith("/rooms/missing"):
|
|
91
|
+
out, code = {"error": "nope"}, 404
|
|
92
|
+
elif self.command == "PATCH" and "/participants/" in self.path:
|
|
93
|
+
out, code = {"updated": 1}, 200
|
|
94
|
+
elif self.command == "PATCH":
|
|
95
|
+
out, code = {"room": {"locked": True}}, 200
|
|
96
|
+
else:
|
|
97
|
+
out, code = {"disconnected": 1, "muted": 2}, 200
|
|
98
|
+
data = json.dumps(out).encode()
|
|
99
|
+
self.send_response(code)
|
|
100
|
+
self.send_header("Content-Type", "application/json")
|
|
101
|
+
self.send_header("Content-Length", str(len(data)))
|
|
102
|
+
self.end_headers()
|
|
103
|
+
self.wfile.write(data)
|
|
104
|
+
|
|
105
|
+
do_GET = do_POST = do_PATCH = do_DELETE = do_PUT = _go
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class AdminTests(unittest.TestCase):
|
|
109
|
+
@classmethod
|
|
110
|
+
def setUpClass(cls):
|
|
111
|
+
cls.server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
112
|
+
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
113
|
+
cls.kit = SfuKit(f"http://127.0.0.1:{cls.server.server_port}/", "k")
|
|
114
|
+
|
|
115
|
+
@classmethod
|
|
116
|
+
def tearDownClass(cls):
|
|
117
|
+
cls.server.shutdown()
|
|
118
|
+
|
|
119
|
+
def test_calls(self):
|
|
120
|
+
kit = self.kit
|
|
121
|
+
self.assertEqual(kit.set_role("r1", "u1", "student"), 1)
|
|
122
|
+
self.assertEqual(Handler.seen[-1], ("PATCH", "/rooms/r1/participants/u1", "Bearer k", {"role": "student"}))
|
|
123
|
+
kit.set_participant_metadata("r1", "u1", None)
|
|
124
|
+
self.assertEqual(Handler.seen[-1][3], {"metadata": None})
|
|
125
|
+
self.assertEqual(kit.mute("r1", "*", ["mic"], lock=True), 2)
|
|
126
|
+
self.assertEqual(Handler.seen[-1][3], {"userId": "*", "devices": ["mic"], "lock": True})
|
|
127
|
+
self.assertEqual(kit.remove_participant("r1", "u1", ban=True), 1)
|
|
128
|
+
self.assertEqual(Handler.seen[-1][1], "/rooms/r1/participants/u1?ban=true")
|
|
129
|
+
self.assertTrue(kit.lock_room("r1")["locked"])
|
|
130
|
+
kit.update_room("r1", waiting_room=True)
|
|
131
|
+
self.assertEqual(Handler.seen[-1][3], {"waitingRoom": True})
|
|
132
|
+
|
|
133
|
+
def test_presenter(self):
|
|
134
|
+
kit = self.kit
|
|
135
|
+
kit.start_presenter("demo", planId="p1", lead="human")
|
|
136
|
+
self.assertEqual(Handler.seen[-1], ("POST", "/rooms/demo/presenter", "Bearer k", {"planId": "p1", "lead": "human"}))
|
|
137
|
+
kit.presenter_browser("demo", "agent-1", "take")
|
|
138
|
+
self.assertEqual(Handler.seen[-1][1:], ("/rooms/demo/lessons/agent-1/control", "Bearer k", {"action": "browser", "browser": "take"}))
|
|
139
|
+
kit.presenter_browser("demo", "agent-1", {"op": "click-at", "x": 0.5, "y": 0.25})
|
|
140
|
+
self.assertEqual(Handler.seen[-1][3], {"action": "browser", "browser": "op", "op": {"op": "click-at", "x": 0.5, "y": 0.25}})
|
|
141
|
+
kit.set_presenter_lead("demo", "agent-1", "ai")
|
|
142
|
+
self.assertEqual(Handler.seen[-1][3], {"action": "lead", "lead": "ai"})
|
|
143
|
+
kit.list_presentation_reports("p 1")
|
|
144
|
+
self.assertEqual(Handler.seen[-1][1], "/presentation-reports?planId=p%201")
|
|
145
|
+
kit.review_suggestion("agent-1", 2, "accepted")
|
|
146
|
+
self.assertEqual(Handler.seen[-1], ("PUT", "/presentation-reports/agent-1/suggestions/2", "Bearer k", {"status": "accepted"}))
|
|
147
|
+
|
|
148
|
+
def test_self_running_presentations(self):
|
|
149
|
+
kit = self.kit
|
|
150
|
+
kit.create_presentation_link("p1", title="Proposal", maxConcurrent=2)
|
|
151
|
+
self.assertEqual(Handler.seen[-1], ("POST", "/presentation-links", "Bearer k", {"planId": "p1", "title": "Proposal", "maxConcurrent": 2}))
|
|
152
|
+
kit.update_presentation_link("pl_1", active=False)
|
|
153
|
+
self.assertEqual(Handler.seen[-1], ("PATCH", "/presentation-links/pl_1", "Bearer k", {"active": False}))
|
|
154
|
+
kit.start_presentation_session("pl_1", name="Ngozi", email="n@x.ng")
|
|
155
|
+
self.assertEqual(Handler.seen[-1], ("POST", "/presentation-links/pl_1/sessions", "Bearer k", {"visitor": {"name": "Ngozi", "email": "n@x.ng"}}))
|
|
156
|
+
kit.list_presentation_sessions("pl 1")
|
|
157
|
+
self.assertEqual(Handler.seen[-1][1], "/presentation-sessions?linkId=pl%201")
|
|
158
|
+
kit.join_presentation_session("ps_1", "Tunde")
|
|
159
|
+
self.assertEqual(Handler.seen[-1][1:], ("/presentation-sessions/ps_1/join", "Bearer k", {"name": "Tunde"}))
|
|
160
|
+
kit.delete_presentation_link("pl_1")
|
|
161
|
+
self.assertEqual(Handler.seen[-1][:2], ("DELETE", "/presentation-links/pl_1"))
|
|
162
|
+
|
|
163
|
+
def test_errors(self):
|
|
164
|
+
with self.assertRaises(SfuKitError) as e:
|
|
165
|
+
self.kit.get_room("missing")
|
|
166
|
+
self.assertEqual(e.exception.status, 404)
|
|
167
|
+
self.assertIn("nope", str(e.exception))
|
|
168
|
+
with self.assertRaises(SfuKitError) as e:
|
|
169
|
+
self.kit.get_room("bad room!")
|
|
170
|
+
self.assertEqual(e.exception.status, 400)
|
|
171
|
+
sent = len(Handler.seen)
|
|
172
|
+
for args in (("..", "20261118T073712-1a2b3c4d", "transcript"), ("r1", "..", "transcript"), ("r1", "20261118T073712-1a2b3c4d", "..")):
|
|
173
|
+
with self.assertRaises(SfuKitError) as e:
|
|
174
|
+
self.kit.download_recording(*args)
|
|
175
|
+
self.assertEqual(e.exception.status, 400)
|
|
176
|
+
self.assertEqual(len(Handler.seen), sent)
|
|
177
|
+
self.kit.download_recording("r1", "20261118T073712-1a2b3c4d", "001-u1-audio.wav")
|
|
178
|
+
self.assertEqual(Handler.seen[-1][1], "/rooms/r1/recordings/20261118T073712-1a2b3c4d/001-u1-audio.wav")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# A tool call signed by the Worker's own signWebhook (packages/server/src/webhooks.ts), shared by every SDK's tests.
|
|
182
|
+
VECTOR_SECRET = "whsec_assistant_test"
|
|
183
|
+
VECTOR_BODY = '{"type":"tool_call","kind":"assistant","conversationId":"c1","userId":"u_7","role":"teacher","callId":"call_1","name":"list_students","arguments":{"cls":"JSS1"},"metadata":{"school":"s1"}}'
|
|
184
|
+
VECTOR_SIGNATURE = "t=1763500000,v1=6497035b3915fa61b8deb6bfa54b0f22d52ff62c71f077a2d43873d747ed24a9"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def tool_call(name, arguments=None, **extra):
|
|
188
|
+
call = {"type": "tool_call", "kind": "assistant", "conversationId": "c1", "userId": "u_7", "role": "teacher", "callId": "call_1", "name": name, "arguments": arguments or {}, "metadata": {"school": "s1"}}
|
|
189
|
+
call.update(extra)
|
|
190
|
+
return json.dumps(call, separators=(",", ":"))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class AssistantToolsTests(unittest.TestCase):
|
|
194
|
+
def setUp(self):
|
|
195
|
+
self.errors = []
|
|
196
|
+
|
|
197
|
+
def boom(args, call):
|
|
198
|
+
raise RuntimeError("database password is hunter2")
|
|
199
|
+
|
|
200
|
+
def denied(args, call):
|
|
201
|
+
raise AssistantToolError("You can only see your own classes.")
|
|
202
|
+
|
|
203
|
+
self.tools = assistant_tools(
|
|
204
|
+
"s",
|
|
205
|
+
{
|
|
206
|
+
"list_students": lambda args, call: [{"name": "Ada", "cls": args["cls"], "school": call["metadata"]["school"], "asker": call["userId"]}],
|
|
207
|
+
"nothing": lambda args, call: None,
|
|
208
|
+
"boom": boom,
|
|
209
|
+
"denied": denied,
|
|
210
|
+
},
|
|
211
|
+
on_error=lambda e, call: self.errors.append((str(e), call["name"])),
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
def run_call(self, body, secret="s", t=None):
|
|
215
|
+
status, out = self.tools.handle(body, sign_webhook(secret, body, t))
|
|
216
|
+
return status, json.loads(out)
|
|
217
|
+
|
|
218
|
+
def test_verifies_the_workers_signature(self):
|
|
219
|
+
self.assertIsNone(verify_assistant_tool_call(VECTOR_SECRET, VECTOR_BODY, VECTOR_SIGNATURE)) # stale now
|
|
220
|
+
call = verify_assistant_tool_call(VECTOR_SECRET, VECTOR_BODY, VECTOR_SIGNATURE, tolerance_seconds=10**10)
|
|
221
|
+
self.assertEqual((call["name"], call["arguments"], call["metadata"]), ("list_students", {"cls": "JSS1"}, {"school": "s1"}))
|
|
222
|
+
self.assertIsNone(verify_assistant_tool_call("other", VECTOR_BODY, VECTOR_SIGNATURE, tolerance_seconds=10**10))
|
|
223
|
+
self.assertIsNone(verify_assistant_tool_call(VECTOR_SECRET, VECTOR_BODY + " ", VECTOR_SIGNATURE, tolerance_seconds=10**10))
|
|
224
|
+
|
|
225
|
+
def test_runs_the_tool_as_the_person(self):
|
|
226
|
+
status, out = self.run_call(tool_call("list_students", {"cls": "JSS1"}))
|
|
227
|
+
self.assertEqual(status, 200)
|
|
228
|
+
self.assertEqual(out, {"result": [{"name": "Ada", "cls": "JSS1", "school": "s1", "asker": "u_7"}]})
|
|
229
|
+
self.assertEqual(self.run_call(tool_call("nothing")), (200, {"result": "done"}))
|
|
230
|
+
status, out = self.tools.handle(tool_call("nothing").encode(), sign_webhook("s", tool_call("nothing")))
|
|
231
|
+
self.assertEqual(json.loads(out), {"result": "done"})
|
|
232
|
+
|
|
233
|
+
def test_refuses_bad_signatures_and_other_bodies(self):
|
|
234
|
+
body = tool_call("list_students", {"cls": "JSS1"})
|
|
235
|
+
self.assertEqual(self.run_call(body, secret="other")[0], 401)
|
|
236
|
+
self.assertEqual(self.run_call(body, t=int(time.time()) - 301)[0], 401)
|
|
237
|
+
self.assertEqual(self.tools.handle(body, None)[0], 401)
|
|
238
|
+
self.assertEqual(self.tools.handle(body, "t=1,v1=zz")[0], 401)
|
|
239
|
+
self.assertEqual(self.run_call(tool_call("list_students", kind="agent"))[0], 401)
|
|
240
|
+
self.assertEqual(self.run_call(tool_call("list_students", type="call.ended"))[0], 401)
|
|
241
|
+
self.assertEqual(self.run_call("not json")[0], 401)
|
|
242
|
+
|
|
243
|
+
def test_unknown_and_inherited_names(self):
|
|
244
|
+
for name in ("missing", "__class__", "__init__", "get", "keys"):
|
|
245
|
+
self.assertEqual(self.run_call(tool_call(name)), (200, {"error": f"There is no tool called {name}."}))
|
|
246
|
+
|
|
247
|
+
def test_errors(self):
|
|
248
|
+
self.assertEqual(self.run_call(tool_call("denied")), (200, {"error": "You can only see your own classes."}))
|
|
249
|
+
self.assertEqual(self.run_call(tool_call("boom")), (200, {"error": "The tool failed."}))
|
|
250
|
+
self.assertEqual(self.errors, [("database password is hunter2", "boom")])
|
|
251
|
+
|
|
252
|
+
def test_needs_a_secret(self):
|
|
253
|
+
with self.assertRaises(ValueError):
|
|
254
|
+
assistant_tools("", {})
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class AssistantAdminTests(unittest.TestCase):
|
|
258
|
+
@classmethod
|
|
259
|
+
def setUpClass(cls):
|
|
260
|
+
cls.server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
261
|
+
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
262
|
+
cls.kit = SfuKit(f"http://127.0.0.1:{cls.server.server_port}", "k")
|
|
263
|
+
|
|
264
|
+
@classmethod
|
|
265
|
+
def tearDownClass(cls):
|
|
266
|
+
cls.server.shutdown()
|
|
267
|
+
|
|
268
|
+
def test_admin_calls(self):
|
|
269
|
+
kit = self.kit
|
|
270
|
+
cfg = {"name": "Ada", "toolsUrl": "https://app.example/assistant-tools", "tools": [{"name": "list_students", "description": "Students in a class"}]}
|
|
271
|
+
self.assertEqual(kit.set_assistant_config(cfg), cfg)
|
|
272
|
+
self.assertEqual(Handler.seen[-1], ("PUT", "/assistant/config", "Bearer k", cfg))
|
|
273
|
+
self.assertEqual(kit.get_assistant_config(), {"name": "Ada"})
|
|
274
|
+
self.assertEqual(Handler.seen[-1][:2], ("GET", "/assistant/config"))
|
|
275
|
+
tok = kit.create_assistant_token("u_7", name="Ada", role="teacher", conversation_id="c1", ttl_seconds=600, metadata={"school": "s1"}, tier=None)
|
|
276
|
+
self.assertEqual(tok["conversationId"], "c1")
|
|
277
|
+
self.assertEqual(Handler.seen[-1], ("POST", "/assistant/tokens", "Bearer k", {"userId": "u_7", "name": "Ada", "role": "teacher", "conversationId": "c1", "ttlSeconds": 600, "metadata": {"school": "s1"}}))
|
|
278
|
+
self.assertIsNone(kit.delete_assistant_conversation("u_7", "c1"))
|
|
279
|
+
self.assertEqual(Handler.seen[-1][:2], ("DELETE", "/assistant/conversations/u_7/c1"))
|
|
280
|
+
with self.assertRaises(SfuKitError):
|
|
281
|
+
kit.delete_assistant_conversation("u_7", "..")
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
if __name__ == "__main__":
|
|
285
|
+
unittest.main()
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class DataSaverTokenTest(unittest.TestCase):
|
|
289
|
+
def test_data_saver_claim(self):
|
|
290
|
+
import base64
|
|
291
|
+
import json as _j
|
|
292
|
+
|
|
293
|
+
def claims(tok):
|
|
294
|
+
p = tok.split(".")[1]
|
|
295
|
+
return _j.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)))
|
|
296
|
+
|
|
297
|
+
self.assertEqual(claims(sign_token(SECRET, "r1", "u1", data_saver="audio")["token"])["ds"], "audio")
|
|
298
|
+
self.assertNotIn("ds", claims(sign_token(SECRET, "r1", "u1", data_saver="off")["token"]))
|
|
299
|
+
with self.assertRaises(ValueError):
|
|
300
|
+
sign_token(SECRET, "r1", "u1", data_saver="ultra")
|
appsocom-0.6.0/README.md
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
# appsocom (Python)
|
|
2
|
-
|
|
3
|
-
Python server SDK for [Appsocom Live](https://live.appsocom.com): mint join tokens, manage rooms and participants, moderate and verify webhooks. Python 3.9+, standard library only.
|
|
4
|
-
|
|
5
|
-
```bash
|
|
6
|
-
pip install appsocom
|
|
7
|
-
```
|
|
8
|
-
|
|
9
|
-
```python
|
|
10
|
-
import os
|
|
11
|
-
from appsocom import SfuKit, SfuKitError, verify_webhook
|
|
12
|
-
|
|
13
|
-
kit = SfuKit("https://api.appsocom.dev", os.environ["APPSOCOM_API_KEY"]) # project API key from the console
|
|
14
|
-
|
|
15
|
-
tok = kit.create_token("class-1", "u_7", name="Ada", role="student", metadata={"seat": 3})
|
|
16
|
-
tok["token"], tok["expiresAt"]
|
|
17
|
-
|
|
18
|
-
kit.set_role("class-1", "u_9", "student") # promote an observer
|
|
19
|
-
kit.mute("class-1", "*", ["mic"], lock=True) # mute everyone, keep them muted
|
|
20
|
-
kit.set_room_metadata("class-1", {"topic": "Fractions"})
|
|
21
|
-
kit.set_track_permissions("class-1", "u_7", {"allowAll": False, "allow": [{"userId": "u_1"}]})
|
|
22
|
-
kit.remove_participant("class-1", "u_8", ban=True)
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
Errors raise `SfuKitError` with `.status` and `.body`.
|
|
26
|
-
|
|
27
|
-
Webhooks (Flask):
|
|
28
|
-
|
|
29
|
-
```python
|
|
30
|
-
@app.post("/appsocom-webhooks")
|
|
31
|
-
def hook():
|
|
32
|
-
event = verify_webhook(os.environ["APPSOCOM_WEBHOOK_SECRET"], request.get_data(), request.headers.get("X-SfuKit-Signature"))
|
|
33
|
-
if event is None:
|
|
34
|
-
return "", 401
|
|
35
|
-
print(event["event"], event["roomId"])
|
|
36
|
-
return "", 204
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`.
|
|
40
|
-
|
|
41
|
-
Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
|
|
42
|
-
|
|
43
|
-
Docs: [docs.appsocom.dev](https://docs.appsocom.dev) · License: MIT
|
|
@@ -1,142 +0,0 @@
|
|
|
1
|
-
import base64
|
|
2
|
-
import hashlib
|
|
3
|
-
import hmac
|
|
4
|
-
import json
|
|
5
|
-
import threading
|
|
6
|
-
import time
|
|
7
|
-
import unittest
|
|
8
|
-
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
9
|
-
|
|
10
|
-
from appsocom import SfuKit, SfuKitError, sign_token, sign_webhook, verify_webhook
|
|
11
|
-
|
|
12
|
-
SECRET = "x" * 40
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
def decode(part):
|
|
16
|
-
return json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)))
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
class TokenTests(unittest.TestCase):
|
|
20
|
-
def test_signs_hs256_with_role_defaults_and_metadata(self):
|
|
21
|
-
t = sign_token(SECRET, "r1", "u1", role="student", metadata={"seat": 3}, permissions={"screen": True})
|
|
22
|
-
head, body, sig = t["token"].split(".")
|
|
23
|
-
self.assertEqual(decode(head), {"alg": "HS256", "typ": "JWT"})
|
|
24
|
-
claims = decode(body)
|
|
25
|
-
self.assertEqual(claims["sub"], "u1")
|
|
26
|
-
self.assertEqual(claims["room"], "r1")
|
|
27
|
-
self.assertEqual(claims["aud"], "sfukit")
|
|
28
|
-
self.assertEqual(claims["role"], "student")
|
|
29
|
-
self.assertEqual(claims["md"], {"seat": 3})
|
|
30
|
-
self.assertEqual(claims["perm"], {"mic": True, "camera": True, "screen": True, "moderate": False})
|
|
31
|
-
self.assertEqual(claims["exp"] - claims["iat"], 7200)
|
|
32
|
-
want = hmac.new(SECRET.encode(), f"{head}.{body}".encode(), hashlib.sha256).digest()
|
|
33
|
-
self.assertEqual(base64.urlsafe_b64encode(want).rstrip(b"=").decode(), sig)
|
|
34
|
-
|
|
35
|
-
def test_rejects_bad_input(self):
|
|
36
|
-
with self.assertRaises(ValueError):
|
|
37
|
-
sign_token("short", "r1", "u1")
|
|
38
|
-
with self.assertRaises(ValueError):
|
|
39
|
-
sign_token(SECRET, "bad room", "u1")
|
|
40
|
-
with self.assertRaises(ValueError):
|
|
41
|
-
sign_token(SECRET, "r1", "u1", max_participants=1)
|
|
42
|
-
with self.assertRaises(ValueError):
|
|
43
|
-
sign_token(SECRET, "r1", "u1", metadata={"x": "y" * 5000})
|
|
44
|
-
|
|
45
|
-
def test_client_signs_locally_with_secret(self):
|
|
46
|
-
kit = SfuKit("http://127.0.0.1:1", "k", jwt_secret=SECRET)
|
|
47
|
-
self.assertEqual(decode(kit.create_token("r1", "u1")["token"].split(".")[1])["sub"], "u1")
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
class WebhookTests(unittest.TestCase):
|
|
51
|
-
def test_round_trip(self):
|
|
52
|
-
body = '{"id":"evt_1","event":"room_started"}'
|
|
53
|
-
sig = sign_webhook("s", body)
|
|
54
|
-
self.assertEqual(verify_webhook("s", body, sig)["id"], "evt_1")
|
|
55
|
-
self.assertEqual(verify_webhook("s", body.encode(), sig)["id"], "evt_1")
|
|
56
|
-
self.assertIsNone(verify_webhook("s", body + " ", sig))
|
|
57
|
-
self.assertIsNone(verify_webhook("other", body, sig))
|
|
58
|
-
self.assertIsNone(verify_webhook("s", body, None))
|
|
59
|
-
old = sign_webhook("s", body, int(time.time()) - 600)
|
|
60
|
-
self.assertIsNone(verify_webhook("s", body, old))
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
class Handler(BaseHTTPRequestHandler):
|
|
64
|
-
seen = []
|
|
65
|
-
|
|
66
|
-
def log_message(self, *a):
|
|
67
|
-
pass
|
|
68
|
-
|
|
69
|
-
def _go(self):
|
|
70
|
-
n = int(self.headers.get("Content-Length") or 0)
|
|
71
|
-
body = json.loads(self.rfile.read(n)) if n else None
|
|
72
|
-
Handler.seen.append((self.command, self.path, self.headers.get("Authorization"), body))
|
|
73
|
-
if self.path.startswith("/rooms/missing"):
|
|
74
|
-
out, code = {"error": "nope"}, 404
|
|
75
|
-
elif self.command == "PATCH" and "/participants/" in self.path:
|
|
76
|
-
out, code = {"updated": 1}, 200
|
|
77
|
-
elif self.command == "PATCH":
|
|
78
|
-
out, code = {"room": {"locked": True}}, 200
|
|
79
|
-
else:
|
|
80
|
-
out, code = {"disconnected": 1, "muted": 2}, 200
|
|
81
|
-
data = json.dumps(out).encode()
|
|
82
|
-
self.send_response(code)
|
|
83
|
-
self.send_header("Content-Type", "application/json")
|
|
84
|
-
self.send_header("Content-Length", str(len(data)))
|
|
85
|
-
self.end_headers()
|
|
86
|
-
self.wfile.write(data)
|
|
87
|
-
|
|
88
|
-
do_GET = do_POST = do_PATCH = do_DELETE = do_PUT = _go
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
class AdminTests(unittest.TestCase):
|
|
92
|
-
@classmethod
|
|
93
|
-
def setUpClass(cls):
|
|
94
|
-
cls.server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
95
|
-
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
96
|
-
cls.kit = SfuKit(f"http://127.0.0.1:{cls.server.server_port}/", "k")
|
|
97
|
-
|
|
98
|
-
@classmethod
|
|
99
|
-
def tearDownClass(cls):
|
|
100
|
-
cls.server.shutdown()
|
|
101
|
-
|
|
102
|
-
def test_calls(self):
|
|
103
|
-
kit = self.kit
|
|
104
|
-
self.assertEqual(kit.set_role("r1", "u1", "student"), 1)
|
|
105
|
-
self.assertEqual(Handler.seen[-1], ("PATCH", "/rooms/r1/participants/u1", "Bearer k", {"role": "student"}))
|
|
106
|
-
kit.set_participant_metadata("r1", "u1", None)
|
|
107
|
-
self.assertEqual(Handler.seen[-1][3], {"metadata": None})
|
|
108
|
-
self.assertEqual(kit.mute("r1", "*", ["mic"], lock=True), 2)
|
|
109
|
-
self.assertEqual(Handler.seen[-1][3], {"userId": "*", "devices": ["mic"], "lock": True})
|
|
110
|
-
self.assertEqual(kit.remove_participant("r1", "u1", ban=True), 1)
|
|
111
|
-
self.assertEqual(Handler.seen[-1][1], "/rooms/r1/participants/u1?ban=true")
|
|
112
|
-
self.assertTrue(kit.lock_room("r1")["locked"])
|
|
113
|
-
kit.update_room("r1", waiting_room=True)
|
|
114
|
-
self.assertEqual(Handler.seen[-1][3], {"waitingRoom": True})
|
|
115
|
-
|
|
116
|
-
def test_errors(self):
|
|
117
|
-
with self.assertRaises(SfuKitError) as e:
|
|
118
|
-
self.kit.get_room("missing")
|
|
119
|
-
self.assertEqual(e.exception.status, 404)
|
|
120
|
-
self.assertIn("nope", str(e.exception))
|
|
121
|
-
with self.assertRaises(SfuKitError) as e:
|
|
122
|
-
self.kit.get_room("bad room!")
|
|
123
|
-
self.assertEqual(e.exception.status, 400)
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
if __name__ == "__main__":
|
|
127
|
-
unittest.main()
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
class DataSaverTokenTest(unittest.TestCase):
|
|
131
|
-
def test_data_saver_claim(self):
|
|
132
|
-
import base64
|
|
133
|
-
import json as _j
|
|
134
|
-
|
|
135
|
-
def claims(tok):
|
|
136
|
-
p = tok.split(".")[1]
|
|
137
|
-
return _j.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)))
|
|
138
|
-
|
|
139
|
-
self.assertEqual(claims(sign_token(SECRET, "r1", "u1", data_saver="audio")["token"])["ds"], "audio")
|
|
140
|
-
self.assertNotIn("ds", claims(sign_token(SECRET, "r1", "u1", data_saver="off")["token"]))
|
|
141
|
-
with self.assertRaises(ValueError):
|
|
142
|
-
sign_token(SECRET, "r1", "u1", data_saver="ultra")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|