urun-sense 0.1.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.
@@ -0,0 +1,4 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .pytest_cache/
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that are granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Urun Platform, Inc
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.5
2
+ Name: urun-sense
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Sense realtime decision protocol
5
+ Project-URL: Homepage, https://github.com/urun-sh/sense-sdk
6
+ Project-URL: Repository, https://github.com/urun-sh/sense-sdk
7
+ Author: Urun Platform Inc
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.10
11
+ Requires-Dist: aiohttp>=3.9
12
+ Provides-Extra: demo
13
+ Requires-Dist: rich>=13; extra == 'demo'
14
+ Requires-Dist: sounddevice>=0.5; (sys_platform != 'linux') and extra == 'demo'
15
+ Provides-Extra: quic
16
+ Requires-Dist: aioquic>=1.2; extra == 'quic'
17
+ Requires-Dist: msgpack>=1.0; extra == 'quic'
18
+ Provides-Extra: webrtc
19
+ Requires-Dist: aiortc>=1.9; extra == 'webrtc'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # urun-sense (Python SDK)
23
+
24
+ Python SDK for the Sense realtime decision protocol (`docs/protocol.md`). Dependency:
25
+ `aiohttp` only.
26
+
27
+ ```bash
28
+ uv add urun-sense # or: pip install urun-sense
29
+ ```
30
+
31
+ ## Quick start
32
+
33
+ ```python
34
+ import asyncio
35
+ from sense import Sense
36
+
37
+ app = Sense(api_key="...") # or SENSE_API_KEY env
38
+ finished = app.noul("Did the speaker just finish their turn?", id="finished")
39
+ intent = app.choice("What does the user want?", ["support", "sales", "other"], id="intent")
40
+ urgency = app.score("How urgent is this?", ["low", "medium", "high"], id="urgency")
41
+
42
+ s = app.session()
43
+
44
+
45
+ async def main():
46
+ async for wave in s.run(audio=mic_stream): # async iterator / callable / iterable
47
+ print(
48
+ wave.wave_id,
49
+ wave.t_ms,
50
+ wave.result("finished").value, # bool
51
+ wave.result("intent").top, # argmax option
52
+ wave.result("urgency").p_at_least("medium"),
53
+ )
54
+ ```
55
+
56
+ ## Flagship demo
57
+
58
+ The wheel ships the cheese classifier example (`sense/examples/cheese_demo.py`): it streams your
59
+ microphone, classifies what you say, and renders a live ANSI display. Requires Python 3.11+.
60
+
61
+ ```bash
62
+ pip install "urun-sense[demo]" # adds rich + sounddevice (non-Linux)
63
+ SENSE_API_KEY=<key> python -m sense.examples.cheese_demo
64
+ ```
65
+
66
+ PowerShell: `$env:SENSE_API_KEY = "<key>"` first, then run the `python` line bare.
67
+
68
+ Linux drives PipeWire directly (`pw-record`/`pw-dump`/`wpctl`); macOS and Windows need microphone
69
+ permission for your terminal. `--mic-only` runs without a key.
70
+
71
+ ## Surface
72
+
73
+ - **Questions** — TEXT-FIRST: `app.noul(question, *, id=None, options=None)`,
74
+ `app.choice(question, options, *, id=None)`, `app.score(question, levels, *, id=None)`.
75
+ The natural-language question is the first argument; the id is optional and
76
+ auto-slugged (lowercase, non-alnum → `_`, unique) when omitted. Low-level
77
+ alternative: `Session.add_question(qid, kind, ...)`.
78
+ - **Predicates** — questions and accessors compose into `Predicate` trees:
79
+ `finished & (intent == "support")`, `finished.p >= 0.8`,
80
+ `intent.p("support") >= 0.7`, `urgency.value >= 1.5`,
81
+ `urgency.p_at_least("medium") >= 0.6`, `~q`, `Predicate.all_of/any_of`,
82
+ `Predicate.between(subject, enter, exit)` (stateful hysteresis latch).
83
+ Score comparison rule: on the bare question subject, `q == x` / `q != x`
84
+ compare the TOP LEVEL NAME (argmax) while `q > x` / `>=` / `<` / `<=`
85
+ compare the EXPECTED ORDINAL.
86
+ `q == x` and `q.top == x` are the same argmax comparison on a choice question.
87
+ - **Context** — passed to `when`/`onWave` handlers (and usable standalone for
88
+ offline replay): `ctx.latest(source=None)`, `ctx.waves(coalesce=False)`
89
+ (bounded to the last 512 waves), `ctx.when(pred, handler, source=None) -> handle`
90
+ (edge-triggered), `ctx.onWave(handler, source=None)`, `ctx.get(q, source=None)`,
91
+ `ctx.run(key, fn(ctx), on_cancel=..., replace=False)`, `ctx.cancel(key, barge_in=True)`,
92
+ `ctx.signal` (the current run's cancellation event, TS AbortSignal parity),
93
+ `ctx.session`.
94
+ - **Inputs** — `s.audio.push(pcm_bytes, source="default")` (PCM16 24 kHz mono),
95
+ `s.video.push(jpeg_bytes)` (≤ 256 KB/frame), `s.text.push(text, mode="append"|"replace"|"event")`.
96
+ A text push alone opens and drives a turn — a text-only session works with
97
+ zero audio.
98
+ - **Session** — `s.latest(q, source=None)`, `s.when(..., source=None)`,
99
+ `s.onWave(handler, coalesce=False, source=None)`, `s.waves(coalesce=False)`
100
+ (live bounded subscription — see below), `s.stats`
101
+ (waves/decisions/errors/protocol_errors), `s.close()` (cancels every tracked
102
+ ctx task, firing `on_cancel` hooks, before tearing down the wire).
103
+
104
+ ## Wire behavior (protocol.md §1–§7)
105
+
106
+ - `wss://.../v1/realtime?model=...` + Bearer auth; `session.update` carries the
107
+ question envelope (`{questions, hz}`) as a JSON string.
108
+ - One commit + `response.create(max_output_tokens=250_000)` opens a cadence turn;
109
+ the empty commit before audio arrives is benign and ignored (`empty_buffer`).
110
+ - Decision lines are assembled into waves client-side (§6.3: repeat-qid flush,
111
+ turn-end flush, `sense.wave` boundary preferred when PR-3 lands).
112
+ - An incomplete wave (missing/unknown/null answer) is a `ProtocolError`: logged
113
+ loudly and counted in `stats.protocol_errors` — never silently treated as
114
+ false/hold.
115
+ - `503`/`429` back off (5 s→30 s cap, `Retry-After` honored), `401`/`404` fatal,
116
+ `session_gone` (close 1011) reconnects fresh, `buffer_full` commits.
117
+ - `ctx.cancel(key)` / barge-in sends `response.cancel`; `ctx.cancel(key, barge_in=False)`
118
+ cancels background work without preempting the turn (used by
119
+ `run(..., replace=True)` supersede).
120
+
121
+ ## Documented degradations (awaiting serving PRs)
122
+
123
+ - **Audio sources (PR-2)**: non-default sources are queued client-side and pushed
124
+ round-robin over the single unlabeled audio lane; every wave is labeled with
125
+ the input source it was drained for, and `when`/`onWave`/`latest` accept
126
+ `source=` to evaluate against that source's stream. Sources are a client-side
127
+ concept until the server PR lands — no `source` field is sent on the wire.
128
+ - **Session.waves() vs run()**: `run()` is the primary consumption path;
129
+ `s.waves()` is a live bounded subscription (queue of 64, drop-oldest) that
130
+ never replays history and never competes with `run()` delivery. `ctx.waves()`
131
+ keeps the last 512 waves for offline replay.
132
+ - **Text replace/event**: the conversation transcript is append-only on today's
133
+ wire; `replace`/`event` are client-side bookkeeping with documented degradation.
134
+
135
+ ## Tests
136
+
137
+ ```bash
138
+ uv run --project . pytest tests ../conformance/python_runner.py
139
+ ```
@@ -0,0 +1,118 @@
1
+ # urun-sense (Python SDK)
2
+
3
+ Python SDK for the Sense realtime decision protocol (`docs/protocol.md`). Dependency:
4
+ `aiohttp` only.
5
+
6
+ ```bash
7
+ uv add urun-sense # or: pip install urun-sense
8
+ ```
9
+
10
+ ## Quick start
11
+
12
+ ```python
13
+ import asyncio
14
+ from sense import Sense
15
+
16
+ app = Sense(api_key="...") # or SENSE_API_KEY env
17
+ finished = app.noul("Did the speaker just finish their turn?", id="finished")
18
+ intent = app.choice("What does the user want?", ["support", "sales", "other"], id="intent")
19
+ urgency = app.score("How urgent is this?", ["low", "medium", "high"], id="urgency")
20
+
21
+ s = app.session()
22
+
23
+
24
+ async def main():
25
+ async for wave in s.run(audio=mic_stream): # async iterator / callable / iterable
26
+ print(
27
+ wave.wave_id,
28
+ wave.t_ms,
29
+ wave.result("finished").value, # bool
30
+ wave.result("intent").top, # argmax option
31
+ wave.result("urgency").p_at_least("medium"),
32
+ )
33
+ ```
34
+
35
+ ## Flagship demo
36
+
37
+ The wheel ships the cheese classifier example (`sense/examples/cheese_demo.py`): it streams your
38
+ microphone, classifies what you say, and renders a live ANSI display. Requires Python 3.11+.
39
+
40
+ ```bash
41
+ pip install "urun-sense[demo]" # adds rich + sounddevice (non-Linux)
42
+ SENSE_API_KEY=<key> python -m sense.examples.cheese_demo
43
+ ```
44
+
45
+ PowerShell: `$env:SENSE_API_KEY = "<key>"` first, then run the `python` line bare.
46
+
47
+ Linux drives PipeWire directly (`pw-record`/`pw-dump`/`wpctl`); macOS and Windows need microphone
48
+ permission for your terminal. `--mic-only` runs without a key.
49
+
50
+ ## Surface
51
+
52
+ - **Questions** — TEXT-FIRST: `app.noul(question, *, id=None, options=None)`,
53
+ `app.choice(question, options, *, id=None)`, `app.score(question, levels, *, id=None)`.
54
+ The natural-language question is the first argument; the id is optional and
55
+ auto-slugged (lowercase, non-alnum → `_`, unique) when omitted. Low-level
56
+ alternative: `Session.add_question(qid, kind, ...)`.
57
+ - **Predicates** — questions and accessors compose into `Predicate` trees:
58
+ `finished & (intent == "support")`, `finished.p >= 0.8`,
59
+ `intent.p("support") >= 0.7`, `urgency.value >= 1.5`,
60
+ `urgency.p_at_least("medium") >= 0.6`, `~q`, `Predicate.all_of/any_of`,
61
+ `Predicate.between(subject, enter, exit)` (stateful hysteresis latch).
62
+ Score comparison rule: on the bare question subject, `q == x` / `q != x`
63
+ compare the TOP LEVEL NAME (argmax) while `q > x` / `>=` / `<` / `<=`
64
+ compare the EXPECTED ORDINAL.
65
+ `q == x` and `q.top == x` are the same argmax comparison on a choice question.
66
+ - **Context** — passed to `when`/`onWave` handlers (and usable standalone for
67
+ offline replay): `ctx.latest(source=None)`, `ctx.waves(coalesce=False)`
68
+ (bounded to the last 512 waves), `ctx.when(pred, handler, source=None) -> handle`
69
+ (edge-triggered), `ctx.onWave(handler, source=None)`, `ctx.get(q, source=None)`,
70
+ `ctx.run(key, fn(ctx), on_cancel=..., replace=False)`, `ctx.cancel(key, barge_in=True)`,
71
+ `ctx.signal` (the current run's cancellation event, TS AbortSignal parity),
72
+ `ctx.session`.
73
+ - **Inputs** — `s.audio.push(pcm_bytes, source="default")` (PCM16 24 kHz mono),
74
+ `s.video.push(jpeg_bytes)` (≤ 256 KB/frame), `s.text.push(text, mode="append"|"replace"|"event")`.
75
+ A text push alone opens and drives a turn — a text-only session works with
76
+ zero audio.
77
+ - **Session** — `s.latest(q, source=None)`, `s.when(..., source=None)`,
78
+ `s.onWave(handler, coalesce=False, source=None)`, `s.waves(coalesce=False)`
79
+ (live bounded subscription — see below), `s.stats`
80
+ (waves/decisions/errors/protocol_errors), `s.close()` (cancels every tracked
81
+ ctx task, firing `on_cancel` hooks, before tearing down the wire).
82
+
83
+ ## Wire behavior (protocol.md §1–§7)
84
+
85
+ - `wss://.../v1/realtime?model=...` + Bearer auth; `session.update` carries the
86
+ question envelope (`{questions, hz}`) as a JSON string.
87
+ - One commit + `response.create(max_output_tokens=250_000)` opens a cadence turn;
88
+ the empty commit before audio arrives is benign and ignored (`empty_buffer`).
89
+ - Decision lines are assembled into waves client-side (§6.3: repeat-qid flush,
90
+ turn-end flush, `sense.wave` boundary preferred when PR-3 lands).
91
+ - An incomplete wave (missing/unknown/null answer) is a `ProtocolError`: logged
92
+ loudly and counted in `stats.protocol_errors` — never silently treated as
93
+ false/hold.
94
+ - `503`/`429` back off (5 s→30 s cap, `Retry-After` honored), `401`/`404` fatal,
95
+ `session_gone` (close 1011) reconnects fresh, `buffer_full` commits.
96
+ - `ctx.cancel(key)` / barge-in sends `response.cancel`; `ctx.cancel(key, barge_in=False)`
97
+ cancels background work without preempting the turn (used by
98
+ `run(..., replace=True)` supersede).
99
+
100
+ ## Documented degradations (awaiting serving PRs)
101
+
102
+ - **Audio sources (PR-2)**: non-default sources are queued client-side and pushed
103
+ round-robin over the single unlabeled audio lane; every wave is labeled with
104
+ the input source it was drained for, and `when`/`onWave`/`latest` accept
105
+ `source=` to evaluate against that source's stream. Sources are a client-side
106
+ concept until the server PR lands — no `source` field is sent on the wire.
107
+ - **Session.waves() vs run()**: `run()` is the primary consumption path;
108
+ `s.waves()` is a live bounded subscription (queue of 64, drop-oldest) that
109
+ never replays history and never competes with `run()` delivery. `ctx.waves()`
110
+ keeps the last 512 waves for offline replay.
111
+ - **Text replace/event**: the conversation transcript is append-only on today's
112
+ wire; `replace`/`event` are client-side bookkeeping with documented degradation.
113
+
114
+ ## Tests
115
+
116
+ ```bash
117
+ uv run --project . pytest tests ../conformance/python_runner.py
118
+ ```
@@ -0,0 +1,32 @@
1
+ [project]
2
+ name = "urun-sense"
3
+ version = "0.1.0"
4
+ description = "Python SDK for the Sense realtime decision protocol"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Urun Platform Inc" }]
9
+ requires-python = ">=3.10"
10
+ dependencies = ["aiohttp>=3.9"]
11
+
12
+ [project.optional-dependencies]
13
+ # Transport extras: the core wire is WebSocket; QUIC (WebTransport) and
14
+ # WebRTC are opt-in and feature-detected at dial time.
15
+ quic = ["aioquic>=1.2", "msgpack>=1.0"]
16
+ webrtc = ["aiortc>=1.9"]
17
+ # Everything the shipped cheese demo needs beyond the SDK itself.
18
+ demo = ["rich>=13", 'sounddevice>=0.5; sys_platform != "linux"']
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/urun-sh/sense-sdk"
22
+ Repository = "https://github.com/urun-sh/sense-sdk"
23
+
24
+ [build-system]
25
+ requires = ["hatchling>=1.26"]
26
+ build-backend = "hatchling.build"
27
+
28
+ [tool.hatch.build.targets.wheel]
29
+ packages = ["src/sense"]
30
+
31
+ [dependency-groups]
32
+ dev = ["pytest>=8", "rich>=13"]
@@ -0,0 +1,170 @@
1
+ """sense — Python SDK for the Sense realtime decision protocol.
2
+
3
+ Public surface: :class:`Sense` (facade), :class:`Session`, :class:`Question`,
4
+ :class:`QuestionKind`, :class:`Predicate`, :class:`Wave`, :class:`Score`,
5
+ :class:`Result`, :class:`Context`, :class:`ProtocolError`,
6
+ :class:`SenseUnavailable`, :func:`session_event`, and the input handles
7
+ :class:`AudioInput`, :class:`VideoInput`, :class:`TextInput`. For clients that
8
+ drive their own event loop over a transport wire (qvs) the QUIC wire
9
+ :class:`QuicWire` and :class:`TransportFailed` are public too.
10
+ """
11
+
12
+ from collections.abc import Callable
13
+ from typing import Any
14
+
15
+ from ._core import (
16
+ Context,
17
+ Predicate,
18
+ ProtocolError,
19
+ Question,
20
+ QuestionKind,
21
+ Result,
22
+ Score,
23
+ SessionEvent,
24
+ Wave,
25
+ session_event,
26
+ )
27
+ from ._session import (
28
+ AudioInput,
29
+ SenseUnavailable,
30
+ Session,
31
+ TextInput,
32
+ VideoInput,
33
+ )
34
+ from ._transport import QuicWire, TransportFailed
35
+
36
+ __all__ = [
37
+ "AudioInput",
38
+ "Context",
39
+ "Predicate",
40
+ "ProtocolError",
41
+ "Question",
42
+ "QuestionKind",
43
+ "QuicWire",
44
+ "Result",
45
+ "Score",
46
+ "Sense",
47
+ "SenseUnavailable",
48
+ "Session",
49
+ "SessionEvent",
50
+ "TextInput",
51
+ "TransportFailed",
52
+ "VideoInput",
53
+ "Wave",
54
+ "session_event",
55
+ ]
56
+
57
+
58
+ def _slug(text: str, taken: set[str]) -> str:
59
+ """Auto-id from the question text: lowercase, non-alnum -> ``_``, never
60
+ empty, unique within the app."""
61
+ base = "".join(c if c.isalnum() else "_" for c in text.strip().lower()).strip("_")
62
+ base = base or "question"
63
+ qid, n = base, 1
64
+ while qid in taken:
65
+ n += 1
66
+ qid = f"{base}_{n}"
67
+ return qid
68
+
69
+
70
+ class Sense:
71
+ """Facade over a :class:`Session`: register questions, attach handlers,
72
+ then :meth:`session` for the wire loop.
73
+
74
+ Questions are TEXT-FIRST — the natural-language question is the first
75
+ positional argument; the id is optional and auto-slugged when omitted::
76
+
77
+ app = Sense(api_key=...)
78
+ finished = app.noul("Did the speaker just finish?")
79
+ intent = app.choice("What does the user want?", ["support", "sales", "other"])
80
+ urgency = app.score("How urgent is this?", ["low", "medium", "high"])
81
+ s = app.session()
82
+ s.when(finished & (intent == "support"), handle)
83
+ async for wave in s.run(audio=mic):
84
+ ...
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ api_key: str | None = None,
90
+ base_url: str | None = None,
91
+ model: str = "sense-latest:bf16",
92
+ hz: float = 25.0,
93
+ transport: str = "auto",
94
+ ) -> None:
95
+ self._kw = {"api_key": api_key, "base_url": base_url, "model": model, "hz": hz, "transport": transport}
96
+ self._session: Session | None = None
97
+
98
+ def _s(self) -> Session:
99
+ if self._session is None:
100
+ self._session = Session(**self._kw)
101
+ return self._session
102
+
103
+ def _qid(self, question: str, id: str | None) -> str:
104
+ if not isinstance(question, str) or not question.strip():
105
+ raise ValueError("question text must be a non-empty string (text-first API)")
106
+ if id is None:
107
+ return _slug(question, {q.id for q in self._s().questions})
108
+ if not id or not id.strip():
109
+ raise ValueError("explicit id must be non-empty")
110
+ return id
111
+
112
+ def noul(self, question: str, *, id: str | None = None, options: Any = None) -> Question:
113
+ return self._s().add_question(
114
+ self._qid(question, id), QuestionKind.NOUL, prompt=question, options=options
115
+ )
116
+
117
+ def choice(self, question: str, options: Any, *, id: str | None = None) -> Question:
118
+ return self._s().add_question(
119
+ self._qid(question, id), QuestionKind.CHOICE, prompt=question, options=options
120
+ )
121
+
122
+ def score(self, question: str, levels: Any, *, id: str | None = None) -> Question:
123
+ return self._s().add_question(
124
+ self._qid(question, id), QuestionKind.SCORE, prompt=question, levels=levels
125
+ )
126
+
127
+ def predicate(self, fn: Callable) -> Predicate:
128
+ """Callable leaf: ``Predicate(fn)`` where ``fn(wave) -> bool``."""
129
+ return Predicate(fn)
130
+
131
+ def when(
132
+ self, pred: Predicate, handler: Callable | None = None, *, source: str | None = None
133
+ ) -> Any:
134
+ """Register an edge-triggered ``when``. Both forms work, and the
135
+ decorator form returns the function::
136
+
137
+ app.when(pred, handler)
138
+ @app.when(pred)
139
+ async def respond(event): ...
140
+ """
141
+ if handler is None:
142
+
143
+ def deco(fn: Callable) -> Any:
144
+ self._s().when(pred, fn, source=source)
145
+ return fn
146
+
147
+ return deco
148
+ return self._s().when(pred, handler, source=source)
149
+
150
+ def onWave(
151
+ self, handler: Callable | None = None, coalesce: bool = False, *, source: str | None = None
152
+ ) -> Any:
153
+ """Observe every completed wave. Both forms work::
154
+
155
+ app.onWave(handler, coalesce=True)
156
+ @app.onWave(coalesce=True)
157
+ def observe(event): ...
158
+ """
159
+ if handler is None:
160
+
161
+ def deco(fn: Callable) -> Any:
162
+ self._s().onWave(fn, coalesce, source=source)
163
+ return fn
164
+
165
+ return deco
166
+ self._s().onWave(handler, coalesce, source=source)
167
+ return handler
168
+
169
+ def session(self) -> Session:
170
+ return self._s()