cooloo 0.1.0__py3-none-win_amd64.whl

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,5 @@
1
+ """cooloo: Python API and launcher for the bundled GUI+CLI client."""
2
+ from .client import Client, CoolooError, Message, MessageStream, SendOutcomeUnknown, SentResult
3
+
4
+ __version__ = "0.1.0"
5
+ __all__ = ["Client", "CoolooError", "Message", "MessageStream", "SendOutcomeUnknown", "SentResult"]
@@ -0,0 +1,7 @@
1
+ {
2
+ "filename": "cooloo.exe",
3
+ "version": "0.2.3",
4
+ "source_commit": "2ac3f027aca3b5f6a746e490bf5dd3384fc0b746",
5
+ "sha256": "19079ec6c559eb58c5ddac6807669ba51b34fa830103246cdae003b7613fc28a",
6
+ "platform_tag": "win_amd64"
7
+ }
@@ -0,0 +1,93 @@
1
+ Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ https://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,25 @@
1
+ /******************************************************************************
2
+ * Copyright (C) 1994-2026 Lua.org, PUC-Rio.
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining
5
+ * a copy of this software and associated documentation files (the
6
+ * "Software"), to deal in the Software without restriction, including
7
+ * without limitation the rights to use, copy, modify, merge, publish,
8
+ * distribute, sublicense, and/or sell copies of the Software, and to
9
+ * permit persons to whom the Software is furnished to do so, subject to
10
+ * the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be
13
+ * included in all copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ ******************************************************************************/
23
+
24
+
25
+ #endif
@@ -0,0 +1,53 @@
1
+ // Monocypher version 4.0.2
2
+ //
3
+ // This file is dual-licensed. Choose whichever licence you want from
4
+ // the two licences listed below.
5
+ //
6
+ // The first licence is a regular 2-clause BSD licence. The second licence
7
+ // is the CC-0 from Creative Commons. It is intended to release Monocypher
8
+ // to the public domain. The BSD licence serves as a fallback option.
9
+ //
10
+ // SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0
11
+ //
12
+ // ------------------------------------------------------------------------
13
+ //
14
+ // Copyright (c) 2017-2020, Loup Vaillant
15
+ // All rights reserved.
16
+ //
17
+ //
18
+ // Redistribution and use in source and binary forms, with or without
19
+ // modification, are permitted provided that the following conditions are
20
+ // met:
21
+ //
22
+ // 1. Redistributions of source code must retain the above copyright
23
+ // notice, this list of conditions and the following disclaimer.
24
+ //
25
+ // 2. Redistributions in binary form must reproduce the above copyright
26
+ // notice, this list of conditions and the following disclaimer in the
27
+ // documentation and/or other materials provided with the
28
+ // distribution.
29
+ //
30
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
31
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
32
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
33
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
34
+ // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
36
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
40
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41
+ //
42
+ // ------------------------------------------------------------------------
43
+ //
44
+ // Written in 2017-2020 by Loup Vaillant
45
+ //
46
+ // To the extent possible under law, the author(s) have dedicated all copyright
47
+ // and related neighboring rights to this software to the public domain
48
+ // worldwide. This software is distributed without any warranty.
49
+ //
50
+ // You should have received a copy of the CC0 Public Domain Dedication along
51
+ // with this software. If not, see
52
+ // <https://creativecommons.org/publicdomain/zero/1.0/>
53
+
@@ -0,0 +1,18 @@
1
+ Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
2
+
3
+ This software is provided 'as-is', without any express or implied
4
+ warranty. In no event will the authors be held liable for any damages
5
+ arising from the use of this software.
6
+
7
+ Permission is granted to anyone to use this software for any purpose,
8
+ including commercial applications, and to alter it and redistribute it
9
+ freely, subject to the following restrictions:
10
+
11
+ 1. The origin of this software must not be misrepresented; you must not
12
+ claim that you wrote the original software. If you use this software
13
+ in a product, an acknowledgment in the product documentation would be
14
+ appreciated but is not required.
15
+ 2. Altered source versions must be plainly marked as such, and must not be
16
+ misrepresented as being the original software.
17
+ 3. This notice may not be removed or altered from any source distribution.
18
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 cooloo contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,37 @@
1
+ ALTERNATIVE A - MIT License
2
+ Copyright (c) 2017 Sean Barrett
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the "Software"), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7
+ of the Software, and to permit persons to whom the Software is furnished to do
8
+ so, subject to the following conditions:
9
+ The above copyright notice and this permission notice shall be included in all
10
+ copies or substantial portions of the Software.
11
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17
+ SOFTWARE.
18
+ ------------------------------------------------------------------------------
19
+ ALTERNATIVE B - Public Domain (www.unlicense.org)
20
+ This is free and unencumbered software released into the public domain.
21
+ Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
22
+ software, either in source code form or as a compiled binary, for any purpose,
23
+ commercial or non-commercial, and by any means.
24
+ In jurisdictions that recognize copyright laws, the author or authors of this
25
+ software dedicate any and all copyright interest in the software to the public
26
+ domain. We make this dedication for the benefit of the public at large and to
27
+ the detriment of our heirs and successors. We intend this dedication to be an
28
+ overt act of relinquishment in perpetuity of all present and future rights to
29
+ this software under copyright law.
30
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
31
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
32
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
33
+ AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
34
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
35
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36
+ ------------------------------------------------------------------------------
37
+ */
@@ -0,0 +1,340 @@
1
+ """Thin subprocess adapter for cooloo's JSONL CLI schema 1. No wire protocol."""
2
+ from __future__ import annotations
3
+
4
+ from collections import deque
5
+ from dataclasses import dataclass
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import queue
10
+ import subprocess
11
+ import threading
12
+ import time
13
+ from typing import Iterator
14
+
15
+
16
+ class CoolooError(RuntimeError):
17
+ def __init__(self, code: str, message: str):
18
+ super().__init__(f"{code}: {message}")
19
+ self.code = code
20
+ self.message = message
21
+
22
+
23
+ class SendOutcomeUnknown(CoolooError):
24
+ pass
25
+
26
+
27
+ def _error(code: str, message: str) -> CoolooError:
28
+ return (SendOutcomeUnknown if code == "send-outcome-unknown" else CoolooError)(code, message)
29
+
30
+
31
+ def binary_path(explicit: str | Path | None = None) -> Path:
32
+ path = Path(explicit).expanduser().resolve() if explicit else Path(__file__).parent / "_bin" / ("cooloo.exe" if os.name == "nt" else "cooloo")
33
+ if not path.is_file():
34
+ raise CoolooError("binary-missing", "install the matching platform wheel or specify binary= explicitly")
35
+ return path
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Message:
40
+ ts: int
41
+ sender: str
42
+ destination: str
43
+ content: str
44
+ end_offset: int
45
+
46
+ @classmethod
47
+ def from_event(cls, event: dict) -> Message:
48
+ try:
49
+ m = event["message"]
50
+ if not isinstance(m["ts"], int) or not all(isinstance(m[k], str) for k in ("from", "to", "content")):
51
+ raise ValueError()
52
+ offset = event["end_offset"]
53
+ if type(offset) is not int or offset < 0:
54
+ raise ValueError()
55
+ return cls(m["ts"], m["from"], m["to"], m["content"], offset)
56
+ except (KeyError, TypeError, ValueError) as exc:
57
+ raise CoolooError("protocol-error", "invalid message event") from exc
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class SentResult:
62
+ messages: list[Message]
63
+ scan_offset: int
64
+
65
+
66
+ def _stop(proc: subprocess.Popen) -> None:
67
+ if proc.poll() is None:
68
+ proc.terminate()
69
+ try:
70
+ proc.wait(timeout=2)
71
+ except subprocess.TimeoutExpired:
72
+ proc.kill()
73
+ proc.wait()
74
+
75
+
76
+ class EventStream:
77
+ """Context-managed stream. Always close early-abandoned streams."""
78
+ def __init__(self, args: list[str], env: dict, payload: bytes | None, timeout: float | None, idle_timeout: float | None, sending: bool):
79
+ self._deadline = None if timeout is None else time.monotonic() + timeout
80
+ self._idle_timeout = idle_timeout
81
+ self._sending = sending
82
+ self._closed = False
83
+ self._terminal = False
84
+ self._events: queue.Queue = queue.Queue(maxsize=64)
85
+ self._stop_event = threading.Event()
86
+ self._diagnostics: deque[bytes] = deque(maxlen=16)
87
+ try:
88
+ self._proc = subprocess.Popen(args, stdin=subprocess.PIPE if payload is not None else subprocess.DEVNULL,
89
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
90
+ creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0)
91
+ except OSError as exc:
92
+ raise CoolooError("process-start-failed", str(exc)) from exc
93
+ self._threads = [threading.Thread(target=self._read_stdout, daemon=True), threading.Thread(target=self._read_stderr, daemon=True)]
94
+ for thread in self._threads:
95
+ thread.start()
96
+ if payload is not None:
97
+ try:
98
+ self._proc.stdin.write(payload) # bounded by SEND's 4096-byte limit
99
+ self._proc.stdin.close()
100
+ except (BrokenPipeError, OSError):
101
+ pass # consume the structured error or process status
102
+
103
+ def _put(self, event) -> None:
104
+ while not self._stop_event.is_set():
105
+ try:
106
+ self._events.put(event, timeout=.1)
107
+ return
108
+ except queue.Full:
109
+ pass
110
+
111
+ def _read_stdout(self) -> None:
112
+ try:
113
+ while True:
114
+ line = self._proc.stdout.readline(131073)
115
+ if not line:
116
+ break
117
+ if len(line) > 131072 or not line.endswith(b"\n"):
118
+ raise CoolooError("protocol-error", "oversized or incomplete JSONL event")
119
+ try:
120
+ event = json.loads(line.decode("utf-8"))
121
+ except (UnicodeError, ValueError) as exc:
122
+ raise CoolooError("protocol-error", "invalid JSONL") from exc
123
+ if not isinstance(event, dict) or event.get("schema") != 1 or event.get("type") not in {"message", "room", "result", "end", "error"}:
124
+ raise CoolooError("protocol-error", "unsupported event schema/type")
125
+ self._put(event)
126
+ except Exception as exc:
127
+ self._put(exc)
128
+ finally:
129
+ self._put(None)
130
+
131
+ def _read_stderr(self) -> None:
132
+ while True:
133
+ data = self._proc.stderr.read(4096)
134
+ if not data:
135
+ return
136
+ self._diagnostics.append(data)
137
+
138
+ def __iter__(self):
139
+ return self
140
+
141
+ def __next__(self) -> dict:
142
+ if self._closed:
143
+ raise StopIteration
144
+ wait = self._idle_timeout
145
+ if self._deadline is not None:
146
+ remaining = max(0, self._deadline - time.monotonic())
147
+ wait = remaining if wait is None else min(wait, remaining)
148
+ try:
149
+ event = self._events.get(timeout=wait)
150
+ if isinstance(event, Exception):
151
+ raise event
152
+ if event is None:
153
+ self._proc.wait(timeout=max(.001, self._deadline-time.monotonic()) if self._deadline else 2)
154
+ if self._proc.returncode != 0 or not self._terminal:
155
+ raise _error("send-outcome-unknown" if self._sending and not self._terminal else "process-failed", "CLI exited without successful completion")
156
+ self.close()
157
+ raise StopIteration
158
+ if self._terminal:
159
+ raise CoolooError("protocol-error", "event after terminal result")
160
+ if event["type"] == "error":
161
+ raise _error(event.get("code", "protocol-error"), event.get("message", "CLI failed"))
162
+ if event["type"] in {"result", "end"}:
163
+ self._terminal = True
164
+ return event
165
+ except (queue.Empty, subprocess.TimeoutExpired) as exc:
166
+ self.close()
167
+ raise _error("send-outcome-unknown" if self._sending and not self._terminal else "timeout", "CLI deadline exceeded") from exc
168
+ except Exception:
169
+ self.close()
170
+ raise
171
+
172
+ def close(self) -> None:
173
+ if self._closed:
174
+ return
175
+ self._closed = True
176
+ self._stop_event.set()
177
+ _stop(self._proc)
178
+ for thread in self._threads:
179
+ thread.join(timeout=3)
180
+ for pipe in (self._proc.stdin, self._proc.stdout, self._proc.stderr):
181
+ if pipe is not None:
182
+ pipe.close()
183
+
184
+ def __enter__(self):
185
+ return self
186
+
187
+ def __exit__(self, *_):
188
+ self.close()
189
+
190
+
191
+ class MessageStream:
192
+ def __init__(self, events: EventStream, offset: int, follow: bool):
193
+ self._events = events
194
+ self._offset = offset
195
+ self._follow = follow
196
+ self.next_offset: int | None = None
197
+
198
+ def __iter__(self) -> Iterator[Message]:
199
+ return self
200
+
201
+ def __next__(self) -> Message:
202
+ try:
203
+ event = next(self._events)
204
+ if event["type"] == "end" and not self._follow:
205
+ cursor = event.get("next_offset")
206
+ if type(cursor) is not int or cursor != self._offset:
207
+ raise CoolooError("protocol-error", "invalid read cursor")
208
+ self.next_offset = cursor
209
+ try:
210
+ next(self._events)
211
+ except StopIteration:
212
+ raise
213
+ raise CoolooError("protocol-error", "event after end")
214
+ if event["type"] != "message":
215
+ raise CoolooError("protocol-error", "expected message")
216
+ message = Message.from_event(event)
217
+ if message.end_offset <= self._offset:
218
+ raise CoolooError("protocol-error", "non-increasing cursor")
219
+ self._offset = message.end_offset
220
+ return message
221
+ except Exception:
222
+ self.close()
223
+ raise
224
+
225
+ def close(self):
226
+ self._events.close()
227
+
228
+ def __enter__(self):
229
+ return self
230
+
231
+ def __exit__(self, *_):
232
+ self.close()
233
+
234
+
235
+ class Client:
236
+ """One CLI process per call. No retries, implicit registration or shared cache."""
237
+ def __init__(self, *, binary: str | Path | None = None, host: str | None = None,
238
+ config_dir: str | Path | None = None, tofu: bool = False,
239
+ effective_identity: str | None = None, timeout: float = 30):
240
+ self.binary = binary_path(binary)
241
+ self._env = dict(os.environ)
242
+ if host is not None:
243
+ self._env["COOLOO_HOST"] = host
244
+ if config_dir is not None:
245
+ self._env["COOLOO_CONFIG"] = str(Path(config_dir).expanduser().resolve())
246
+ self._prefix = [str(self.binary), "--json"]
247
+ if tofu:
248
+ self._prefix.append("--tofu")
249
+ if effective_identity:
250
+ self._prefix += ["--as", effective_identity]
251
+ if timeout <= 0:
252
+ raise ValueError("timeout must be positive")
253
+ self.timeout = timeout
254
+ with EventStream([str(self.binary), "--json", "version"], self._env, None, timeout, None, False) as stream:
255
+ events = list(stream)
256
+ if len(events) != 1 or events[0].get("type") != "result" or 1 not in events[0].get("schema_versions", []) or not {"json-output", "follow-offset", "no-cache"} <= set(events[0].get("capabilities", [])):
257
+ raise CoolooError("incompatible-binary", "CLI schema 1 with explicit offsets is required")
258
+ self.binary_version = events[0]["binary_version"]
259
+
260
+ @staticmethod
261
+ def _offset(offset: int) -> str:
262
+ if type(offset) is not int or not 0 <= offset <= 2**63-1:
263
+ raise ValueError("offset must be a nonnegative signed 64-bit integer")
264
+ return str(offset)
265
+
266
+ def _stream(self, *args: str, payload: bytes | None = None, follow: bool = False, idle_timeout: float | None = None):
267
+ return EventStream(self._prefix + list(args), self._env, payload,
268
+ None if follow else self.timeout, idle_timeout, args[0] in {"send", "join"})
269
+
270
+ def _result(self, *args: str, payload: bytes | None = None) -> dict:
271
+ with self._stream(*args, payload=payload) as stream:
272
+ events = list(stream)
273
+ if len(events) != 1 or events[0]["type"] != "result":
274
+ raise CoolooError("protocol-error", "expected one result")
275
+ return {k: v for k, v in events[0].items() if k not in {"schema", "type"}}
276
+
277
+ def keygen(self) -> str:
278
+ return self._result("keygen")["id"]
279
+
280
+ def register(self, nickname: str) -> dict:
281
+ return self._result("whoami", "--register", nickname)
282
+
283
+ def whoami(self) -> dict:
284
+ return self._result("whoami")
285
+
286
+ def send(self, destination: str, content: str) -> int:
287
+ payload = content.encode("utf-8")
288
+ if not 1 <= len(payload) <= 4096 or b"\0" in payload:
289
+ raise ValueError("content must be 1–4096 UTF-8 bytes without NUL")
290
+ return self._result("send", destination, payload=payload)["end_offset"]
291
+
292
+ def read(self, destination: str, *, offset: int) -> MessageStream:
293
+ return MessageStream(self._stream("read", destination, self._offset(offset)), offset, False)
294
+
295
+ def follow(self, destination: str, *, offset: int, idle_timeout: float | None = None) -> MessageStream:
296
+ if idle_timeout is not None and idle_timeout <= 0:
297
+ raise ValueError("idle_timeout must be positive")
298
+ return MessageStream(self._stream("follow", destination, self._offset(offset), follow=True, idle_timeout=idle_timeout), offset, True)
299
+
300
+ def sent(self, peer: str, *, offset: int) -> SentResult:
301
+ with self._stream("sent", peer, self._offset(offset)) as stream:
302
+ events = list(stream)
303
+ if not events or events[-1]["type"] != "end" or any(e["type"] != "message" for e in events[:-1]):
304
+ raise CoolooError("protocol-error", "invalid sent result")
305
+ messages = [Message.from_event(e) for e in events[:-1]]
306
+ cursor = events[-1].get("scan_offset")
307
+ if type(cursor) is not int or cursor < offset or (messages and cursor < messages[-1].end_offset):
308
+ raise CoolooError("protocol-error", "invalid scan cursor")
309
+ return SentResult(messages, cursor)
310
+
311
+ def rooms(self) -> list[dict]:
312
+ with self._stream("rooms") as stream:
313
+ events = list(stream)
314
+ if not events or events[-1]["type"] != "end" or any(e["type"] != "room" for e in events[:-1]):
315
+ raise CoolooError("protocol-error", "invalid rooms result")
316
+ return [{"id": e["id"], "nickname": e["nickname"]} for e in events[:-1]]
317
+
318
+ def create_room(self, nickname: str) -> dict:
319
+ return self._result("create", nickname)
320
+
321
+ def meta(self, identity: str) -> dict:
322
+ return self._result("meta", identity)
323
+
324
+ def rename(self, identity: str, nickname: str) -> None:
325
+ self._result("rename", identity, nickname)
326
+
327
+ def avatar(self, slot: int, child_id: str, nickname: str) -> dict:
328
+ return self._result("avatar", f"{slot:03d}", child_id, nickname)
329
+
330
+ def join(self, room: str) -> int:
331
+ return self._result("join", room)["end_offset"]
332
+
333
+ def approve_join(self, room: str, applicant: str) -> int:
334
+ return self.send(room, f"@{room} join-approve {applicant}")
335
+
336
+ def set_room_mode(self, room: str, mode: str) -> None:
337
+ self._result("room-mode", room, mode)
338
+
339
+ def delegate(self, child_id: str, permissions: str) -> None:
340
+ self._result("delegate", child_id, permissions)
@@ -0,0 +1,27 @@
1
+ """Transparent command forwarding; never resolves the bundled executable via PATH."""
2
+ import os
3
+ import subprocess
4
+ import sys
5
+ from .client import binary_path, CoolooError, _stop
6
+
7
+
8
+ def main() -> int:
9
+ try:
10
+ args = [str(binary_path()), *sys.argv[1:]]
11
+ if os.name != "nt":
12
+ os.execv(args[0], args)
13
+ # Explicit handles preserve redirected streams through the Python launcher.
14
+ proc = subprocess.Popen(args, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
15
+ try:
16
+ return proc.wait()
17
+ except KeyboardInterrupt:
18
+ _stop(proc)
19
+ return 130
20
+ except (CoolooError, OSError) as exc:
21
+ print(f"cooloo: {exc}", file=sys.stderr)
22
+ return 1
23
+ return 0
24
+
25
+
26
+ if __name__ == "__main__":
27
+ raise SystemExit(main())
File without changes
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: cooloo
3
+ Version: 0.1.0
4
+ Summary: Python API and launcher for the cooloo GUI and CLI client
5
+ Author: cooloo contributors
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # cooloo Python API and GUI launcher — 0.1.0
13
+
14
+ Thin wrapper around the bundled C GUI+CLI client (0.2.3, JSONL schema 1).
15
+ No Python Native/Noise implementation, SSH backend, daemon, or CLI-only distribution.
16
+ Initial wheels target Windows x86_64 and macOS arm64. Python >=3.10.
17
+ Licensed under MIT; bundled third-party components retain their own licenses.
18
+
19
+ ## Installation / launch (after publication)
20
+
21
+ ```sh
22
+ pip install cooloo
23
+ pipx install cooloo
24
+ cooloo --gui
25
+ # Or without a persistent pipx installation:
26
+ pipx run --spec cooloo cooloo --gui
27
+ ```
28
+
29
+ `cooloo` with no arguments also opens the GUI. Other commands are forwarded unchanged.
30
+ Unsigned/not notarized native artifacts retain their platform trust limitations.
31
+ No runtime downloads, PATH lookup, implicit identity creation or registration.
32
+ Unsupported platforms have no matching wheel; source users may explicitly supply a
33
+ compatible local C executable. No source distribution is published in this first release.
34
+
35
+ ## Python usage
36
+
37
+ ```python
38
+ from cooloo import Client
39
+
40
+ client = Client(host="your-server:4222", config_dir="./bot-identity")
41
+ # client.keygen() # once, explicitly
42
+ # Client(..., tofu=True).register("bot") # explicitly trust first server connection
43
+ end = client.send("<destination-id>", "hello\n世界")
44
+ with client.read("<destination-id>", offset=0) as messages:
45
+ for message in messages:
46
+ print(message.sender, message.content, message.end_offset)
47
+
48
+ with client.follow("<destination-id>", offset=saved_offset) as messages:
49
+ for message in messages:
50
+ process(message)
51
+ save_checkpoint(message.end_offset) # only AFTER business processing
52
+ ```
53
+
54
+ Replace example IDs, server, and application functions. Obtain/trust the server pin through
55
+ an appropriate trusted channel; `tofu=True` is an explicit first-use trust decision, not
56
+ protection from a first-connection MITM. Changed stored pins always fail. Config defaults
57
+ match native CLI (`~/.cooloo`); use a separate directory per service/credential. Parent
58
+ of a new config directory must exist. Private identity files must not be shared/logged.
59
+
60
+ Methods: keygen, register, whoami, rooms, create_room, meta, rename, avatar, send,
61
+ read, follow, sent, join, approve_join, set_room_mode, delegate. Pass
62
+ `effective_identity=owner_id` to select an explicitly delegated identity; failed AS
63
+ never falls back to login identity. Administrative operations require actual owner
64
+ credentials. `sent(peer, offset=...)` returns SentResult(messages, scan_offset), including
65
+ an advanced cursor on empty filtered results. SENT never populates normal message caches.
66
+ Private rooms currently permit any registered user to make them public: **not a
67
+ confidentiality guarantee**. No aggregate history or complete multi-device recovery.
68
+
69
+ Each call starts a process and authenticates a connection. `timeout=30` bounds finite
70
+ commands. FOLLOW has no overall timeout; optional idle_timeout bounds silence. It may
71
+ end when the server closes an idle connection; no automatic reconnect, keepalive or retry.
72
+ Context managers close streams and reap subprocesses; **always close streams on early
73
+ exit**, including breaks. GUI caches are untouched by machine READ/FOLLOW. No exactly-once
74
+ claim: replay can occur; deduplicate by destination/end_offset and persist business cursors.
75
+
76
+ CoolooError exposes code/message. SendOutcomeUnknown means delivery may have happened;
77
+ never blindly retry. A valid server acknowledgement returns end_offset. No guarantees of
78
+ thread-safe shared Client usage. No shell execution; SEND uses UTF-8 stdin, max 4096 bytes.
79
+
80
+ ## Development and packaging
81
+
82
+ ```sh
83
+ PYTHONPATH=src python -m unittest discover -s tests -v
84
+ ```
85
+
86
+ Integration tests need sibling `client/cooloo-cli` and `server/coolood`, or explicit test
87
+ binary overrides; all connections use temporary identities and loopback servers.
88
+ This CLI-only build is a local test fixture, not the distributed product.
89
+
90
+ Build each platform from a separate package source copy: stage its verified GUI+CLI
91
+ artifact with tools/stage_binary.py, then `python -m build --wheel`. The builder refuses
92
+ missing artifacts, changed hashes, and source distributions. macOS wheel tag must match
93
+ the actual deployment target; do not infer it from the build host version. Keep the
94
+ manifest's source commit/version/hash with the binary. The bundle must include third-party
95
+ license notices and the C client's MIT license before public distribution.
96
+ See [LICENSE](LICENSE) for the Python SDK's MIT license.
97
+
98
+ Source repository: https://github.com/cooloo-app/python-sdk . The planner includes it as
99
+ `python-sdk/` submodule; package name and Python import remain `cooloo`.
@@ -0,0 +1,18 @@
1
+ cooloo-0.1.0.data/purelib/cooloo/__init__.py,sha256=kqhMsLudG3jtGDxhKp77ZbggOsk7Em7vOUlLbtECPGw,289
2
+ cooloo-0.1.0.data/purelib/cooloo/client.py,sha256=szY1ZNxNC10R0pqUm8jhxLGdyewsn1_CO0qQ2IK2nLA,13993
3
+ cooloo-0.1.0.data/purelib/cooloo/launcher.py,sha256=nj1AL_PNgJldMiJMKzRKr5C0Dn_UHzokXzrwQWOtgkQ,803
4
+ cooloo-0.1.0.data/purelib/cooloo/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ cooloo-0.1.0.data/purelib/cooloo/_bin/cooloo.exe,sha256=GQeexsVZ61jF3axoB2abpRs0-oMBAyRs2uADt2E_woo,4161497
6
+ cooloo-0.1.0.data/purelib/cooloo/_bin/manifest.json,sha256=iflB9gHFDFD57zPr97y4mWRZFt8uwpGUv37S6-iLXhQ,227
7
+ cooloo-0.1.0.data/purelib/cooloo/_licenses/JetBrainsMono.txt,sha256=PV-7LQ6DkZyNnGqnow6VVO80SLAnD1KnUg1JzJ_6WI8,4492
8
+ cooloo-0.1.0.data/purelib/cooloo/_licenses/Lua.txt,sha256=1lt9iPvOQOsSEbrI5b1OVkLyLmqqqGzn4KBrPKL5DFg,1272
9
+ cooloo-0.1.0.data/purelib/cooloo/_licenses/Monocypher.txt,sha256=qj1GVxNp3cAGTRiTpLTrl5EwZtxB68aXsCwdfBmTPGM,2401
10
+ cooloo-0.1.0.data/purelib/cooloo/_licenses/SDL.txt,sha256=a42od_UYuuPiYbJhN1TMl-kW8gABxUmbTOpmgKxtHhs,902
11
+ cooloo-0.1.0.data/purelib/cooloo/_licenses/cooloo-client-MIT.txt,sha256=JY1ueC0hOGNyMPJ_-QpIeJNCW-1f4VZKJG9FWUDnACo,1076
12
+ cooloo-0.1.0.data/purelib/cooloo/_licenses/stb_truetype.txt,sha256=Mj6sZoxCIgPzxUok4Hf9LpmaxteawYcuYZgwyzvLNP4,2437
13
+ cooloo-0.1.0.dist-info/licenses/LICENSE,sha256=JY1ueC0hOGNyMPJ_-QpIeJNCW-1f4VZKJG9FWUDnACo,1076
14
+ cooloo-0.1.0.dist-info/METADATA,sha256=XSvw4frQm22CSDMASknnWRpbLBQJ0s72SIlVLpmggKM,4925
15
+ cooloo-0.1.0.dist-info/WHEEL,sha256=GjDPPQwEcripVP6P2r3RxLa-h5Lb9ifGB7FYYtbLDT0,98
16
+ cooloo-0.1.0.dist-info/entry_points.txt,sha256=NEIIivBmhBaxCNIna5IQWzD1uEbvpOCrgEA_nt7HzoM,48
17
+ cooloo-0.1.0.dist-info/top_level.txt,sha256=aY-6iDoTkzKFAu2BPS1IxrqZLBvq1SOtW2ZNYv9scwI,7
18
+ cooloo-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-win_amd64
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ cooloo = cooloo.launcher:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 cooloo contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ cooloo