clickdust 0.4.0__py3-none-any.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.
clickdust/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """clickdust: turn a day of clicking into generative art."""
2
+
3
+ __version__ = "0.4.0"
clickdust/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,29 @@
1
+ """Input backends turn operating-system events into calls on a sink.
2
+
3
+ A sink has three methods:
4
+
5
+ on_key(device) one key went down (which key is never passed)
6
+ on_click(x, y, button, pressed, device)
7
+ on_move(x, y, device)
8
+
9
+ `device` is "int" (built into the computer), "ext" (plugged in or wireless) or "unknown".
10
+ """
11
+
12
+ import sys
13
+
14
+ UNKNOWN = "unknown"
15
+
16
+
17
+ class BackendError(RuntimeError):
18
+ """The operating system would not let us listen."""
19
+
20
+
21
+ def open_backend(sink, keys: bool = True):
22
+ """Return a started backend with pump(seconds), alive(), close() and a list of `notes`."""
23
+ if sys.platform == "darwin":
24
+ from .macos import MacBackend
25
+
26
+ return MacBackend(sink, keys)
27
+ from .generic import PynputBackend
28
+
29
+ return PynputBackend(sink, keys)
@@ -0,0 +1,45 @@
1
+ """Windows and Linux (X11) through pynput. Devices are not told apart here."""
2
+
3
+ import time
4
+
5
+ from . import UNKNOWN, BackendError
6
+
7
+
8
+ class PynputBackend:
9
+ def __init__(self, sink, keys: bool = True):
10
+ try:
11
+ from pynput import keyboard, mouse
12
+ except Exception as error:
13
+ raise BackendError(f"Cannot load the input library: {error}")
14
+ self.notes = ["Built-in and external devices are not told apart on this system."]
15
+ # Held keys stay in memory only, to ignore auto-repeat. Nothing about them is passed on.
16
+ held = set()
17
+
18
+ def press(key):
19
+ if key not in held:
20
+ held.add(key)
21
+ sink.on_key(UNKNOWN)
22
+
23
+ self._listeners = [
24
+ mouse.Listener(
25
+ on_move=lambda x, y: sink.on_move(x, y),
26
+ on_click=lambda x, y, button, pressed: sink.on_click(
27
+ x, y, getattr(button, "name", str(button)), pressed, UNKNOWN
28
+ ),
29
+ )
30
+ ]
31
+ if keys:
32
+ self._listeners.append(keyboard.Listener(on_press=press, on_release=held.discard))
33
+ for listener in self._listeners:
34
+ listener.start()
35
+ listener.wait()
36
+
37
+ def pump(self, seconds: float) -> None:
38
+ time.sleep(seconds)
39
+
40
+ def alive(self) -> bool:
41
+ return all(listener.is_alive() for listener in self._listeners)
42
+
43
+ def close(self) -> None:
44
+ for listener in self._listeners:
45
+ listener.stop()
@@ -0,0 +1,153 @@
1
+ """Which physical device was used last? (macOS, via IOKit's HID manager.)
2
+
3
+ The event tap says *what* happened but not on which keyboard or mouse. IOKit does know the
4
+ device behind each raw input value, so we remember the most recent one for each kind.
5
+
6
+ Privacy: for a raw value we read only its usage *page* (is it a key, a button, a pointer?),
7
+ never its usage (which key) and never its value (what was typed).
8
+ """
9
+
10
+ import ctypes
11
+ from ctypes import c_char_p, c_int32, c_long, c_uint32, c_void_p
12
+
13
+ from . import UNKNOWN
14
+
15
+ GENERIC_DESKTOP, KEYBOARD_PAGE, BUTTON_PAGE, DIGITIZER_PAGE = 0x01, 0x07, 0x09, 0x0D
16
+ # (usage page, usage): keyboard, mouse, pointer, touchpad, multitouch surface
17
+ WANTED = [(GENERIC_DESKTOP, 6), (GENERIC_DESKTOP, 2), (GENERIC_DESKTOP, 1), (DIGITIZER_PAGE, 5), (DIGITIZER_PAGE, 12)]
18
+ BUILT_IN_TRANSPORTS = {"FIFO", "SPI", "SPU"}
19
+ _UTF8 = 0x08000100
20
+ _SINT32 = 3
21
+
22
+ _Callback = ctypes.CFUNCTYPE(None, c_void_p, c_int32, c_void_p, c_void_p)
23
+
24
+
25
+ def classify(built_in, transport) -> str:
26
+ if built_in or transport in BUILT_IN_TRANSPORTS:
27
+ return "int"
28
+ if built_in is None and not transport:
29
+ return UNKNOWN
30
+ return "ext"
31
+
32
+
33
+ def kind_of(usage_page: int):
34
+ if usage_page == KEYBOARD_PAGE:
35
+ return "keyboard"
36
+ if usage_page in (GENERIC_DESKTOP, BUTTON_PAGE, DIGITIZER_PAGE):
37
+ return "pointer"
38
+ return None
39
+
40
+
41
+ def _libraries():
42
+ cf = ctypes.CDLL("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
43
+ io = ctypes.CDLL("/System/Library/Frameworks/IOKit.framework/IOKit")
44
+
45
+ def declare(lib, name, result, *arguments):
46
+ function = getattr(lib, name)
47
+ function.restype, function.argtypes = result, list(arguments)
48
+
49
+ declare(cf, "CFStringCreateWithCString", c_void_p, c_void_p, c_char_p, c_uint32)
50
+ declare(cf, "CFStringGetCString", ctypes.c_bool, c_void_p, c_char_p, c_long, c_uint32)
51
+ declare(cf, "CFGetTypeID", c_long, c_void_p)
52
+ declare(cf, "CFStringGetTypeID", c_long)
53
+ declare(cf, "CFNumberGetTypeID", c_long)
54
+ declare(cf, "CFBooleanGetTypeID", c_long)
55
+ declare(cf, "CFNumberGetValue", ctypes.c_bool, c_void_p, c_long, c_void_p)
56
+ declare(cf, "CFBooleanGetValue", ctypes.c_bool, c_void_p)
57
+ declare(cf, "CFSetGetCount", c_long, c_void_p)
58
+ declare(cf, "CFSetGetValues", None, c_void_p, ctypes.POINTER(c_void_p))
59
+ declare(cf, "CFRunLoopGetCurrent", c_void_p)
60
+ declare(cf, "CFRelease", None, c_void_p)
61
+ declare(io, "IOHIDManagerCreate", c_void_p, c_void_p, c_uint32)
62
+ declare(io, "IOHIDManagerSetDeviceMatchingMultiple", None, c_void_p, c_void_p)
63
+ declare(io, "IOHIDManagerRegisterInputValueCallback", None, c_void_p, _Callback, c_void_p)
64
+ declare(io, "IOHIDManagerScheduleWithRunLoop", None, c_void_p, c_void_p, c_void_p)
65
+ declare(io, "IOHIDManagerUnscheduleFromRunLoop", None, c_void_p, c_void_p, c_void_p)
66
+ declare(io, "IOHIDManagerOpen", c_int32, c_void_p, c_uint32)
67
+ declare(io, "IOHIDManagerClose", c_int32, c_void_p, c_uint32)
68
+ declare(io, "IOHIDManagerCopyDevices", c_void_p, c_void_p)
69
+ declare(io, "IOHIDDeviceGetProperty", c_void_p, c_void_p, c_void_p)
70
+ declare(io, "IOHIDValueGetElement", c_void_p, c_void_p)
71
+ declare(io, "IOHIDElementGetDevice", c_void_p, c_void_p)
72
+ declare(io, "IOHIDElementGetUsagePage", c_uint32, c_void_p)
73
+ return cf, io
74
+
75
+
76
+ class DeviceTracker:
77
+ def __init__(self):
78
+ import objc
79
+ from Foundation import NSArray
80
+
81
+ self.cf, self.io = _libraries()
82
+ self.last = {"keyboard": UNKNOWN, "pointer": UNKNOWN}
83
+ self._cache = {}
84
+ self._keys = {name: self._string(name) for name in ("Built-In", "Transport", "Product")}
85
+ # NSArray is toll-free bridged to CFArray; keep a reference for as long as the manager lives
86
+ self._matching = NSArray.arrayWithArray_(
87
+ [{"DeviceUsagePage": page, "DeviceUsage": usage} for page, usage in WANTED]
88
+ )
89
+ self.manager = self.io.IOHIDManagerCreate(None, 0)
90
+ self.io.IOHIDManagerSetDeviceMatchingMultiple(self.manager, objc.pyobjc_id(self._matching))
91
+ self._callback = None
92
+ self._mode = c_void_p.in_dll(self.cf, "kCFRunLoopDefaultMode")
93
+
94
+ def _string(self, text):
95
+ return self.cf.CFStringCreateWithCString(None, text.encode(), _UTF8)
96
+
97
+ def _property(self, device, name):
98
+ ref = self.io.IOHIDDeviceGetProperty(device, self._keys[name])
99
+ if not ref:
100
+ return None
101
+ kind = self.cf.CFGetTypeID(ref)
102
+ if kind == self.cf.CFBooleanGetTypeID():
103
+ return bool(self.cf.CFBooleanGetValue(ref))
104
+ if kind == self.cf.CFNumberGetTypeID():
105
+ number = c_int32()
106
+ self.cf.CFNumberGetValue(ref, _SINT32, ctypes.byref(number))
107
+ return number.value
108
+ if kind == self.cf.CFStringGetTypeID():
109
+ buffer = ctypes.create_string_buffer(256)
110
+ if self.cf.CFStringGetCString(ref, buffer, len(buffer), _UTF8):
111
+ return buffer.value.decode("utf-8", "replace")
112
+ return None
113
+
114
+ def _class_of(self, device) -> str:
115
+ if device not in self._cache:
116
+ self._cache[device] = classify(self._property(device, "Built-In"), self._property(device, "Transport"))
117
+ return self._cache[device]
118
+
119
+ def devices(self):
120
+ """Connected keyboards and pointers as (product, class). Reads no input."""
121
+ found = self.io.IOHIDManagerCopyDevices(self.manager)
122
+ if not found:
123
+ return []
124
+ count = self.cf.CFSetGetCount(found)
125
+ values = (c_void_p * count)()
126
+ self.cf.CFSetGetValues(found, values)
127
+ result = sorted({(self._property(d, "Product") or "unnamed", self._class_of(d)) for d in values})
128
+ self._cache.clear()
129
+ self.cf.CFRelease(found)
130
+ return result
131
+
132
+ def start(self) -> bool:
133
+ """Listen on the current run loop. False if macOS refuses."""
134
+
135
+ def seen(_context, _result, _sender, value):
136
+ element = self.io.IOHIDValueGetElement(value)
137
+ kind = kind_of(self.io.IOHIDElementGetUsagePage(element))
138
+ if kind:
139
+ self.last[kind] = self._class_of(self.io.IOHIDElementGetDevice(element))
140
+
141
+ self._callback = _Callback(seen)
142
+ self.io.IOHIDManagerRegisterInputValueCallback(self.manager, self._callback, None)
143
+ self.io.IOHIDManagerScheduleWithRunLoop(self.manager, self.cf.CFRunLoopGetCurrent(), self._mode)
144
+ if self.io.IOHIDManagerOpen(self.manager, 0) != 0:
145
+ self.close()
146
+ return False
147
+ return True
148
+
149
+ def close(self):
150
+ if self._callback:
151
+ self.io.IOHIDManagerUnscheduleFromRunLoop(self.manager, self.cf.CFRunLoopGetCurrent(), self._mode)
152
+ self.io.IOHIDManagerClose(self.manager, 0)
153
+ self._callback = None
@@ -0,0 +1,115 @@
1
+ """macOS: a listen-only event tap on the main run loop, plus HID device attribution.
2
+
3
+ For a key press the only field read from the event is the auto-repeat flag. The key code
4
+ and the characters are never requested.
5
+ """
6
+
7
+ import ctypes
8
+
9
+ import Quartz
10
+
11
+ from . import UNKNOWN, BackendError
12
+
13
+ BUTTONS = {
14
+ Quartz.kCGEventLeftMouseDown: ("left", True),
15
+ Quartz.kCGEventLeftMouseUp: ("left", False),
16
+ Quartz.kCGEventRightMouseDown: ("right", True),
17
+ Quartz.kCGEventRightMouseUp: ("right", False),
18
+ Quartz.kCGEventOtherMouseDown: ("middle", True),
19
+ Quartz.kCGEventOtherMouseUp: ("middle", False),
20
+ }
21
+ MOVES = (Quartz.kCGEventMouseMoved, Quartz.kCGEventLeftMouseDragged, Quartz.kCGEventRightMouseDragged)
22
+ DISABLED = (Quartz.kCGEventTapDisabledByTimeout, Quartz.kCGEventTapDisabledByUserInput)
23
+
24
+
25
+ def secure_input_check():
26
+ """A function that is True while a password field has switched on Secure Input."""
27
+ try:
28
+ carbon = ctypes.CDLL("/System/Library/Frameworks/Carbon.framework/Carbon")
29
+ carbon.IsSecureEventInputEnabled.restype = ctypes.c_bool
30
+ return lambda: bool(carbon.IsSecureEventInputEnabled())
31
+ except (OSError, AttributeError):
32
+ return lambda: False
33
+
34
+
35
+ class Dispatcher:
36
+ """Turns one CGEvent into one sink call. Separate from the tap so it can be tested."""
37
+
38
+ def __init__(self, sink, devices, secure):
39
+ self.sink, self.devices, self.secure = sink, devices, secure
40
+
41
+ def _device(self, kind):
42
+ return self.devices.last[kind] if self.devices else UNKNOWN
43
+
44
+ def handle(self, event_type, event):
45
+ if event_type == Quartz.kCGEventKeyDown:
46
+ held = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventAutorepeat)
47
+ if not held and not self.secure():
48
+ self.sink.on_key(self._device("keyboard"))
49
+ elif event_type in BUTTONS:
50
+ button, pressed = BUTTONS[event_type]
51
+ at = Quartz.CGEventGetLocation(event)
52
+ self.sink.on_click(at.x, at.y, button, pressed, self._device("pointer"))
53
+ elif event_type in MOVES:
54
+ at = Quartz.CGEventGetLocation(event)
55
+ self.sink.on_move(at.x, at.y, self._device("pointer"))
56
+
57
+
58
+ class MacBackend:
59
+ def __init__(self, sink, keys: bool = True):
60
+ self.notes = []
61
+ self.devices = None
62
+ try:
63
+ from .hid import DeviceTracker
64
+
65
+ tracker = DeviceTracker()
66
+ if tracker.start():
67
+ self.devices = tracker
68
+ except Exception as error: # attribution is optional; counting still works without it
69
+ self.notes.append(f"Device detection failed: {error}")
70
+ if not self.devices:
71
+ self.notes.append("Cannot tell built-in from external devices; they are recorded as unknown.")
72
+
73
+ dispatcher = Dispatcher(sink, self.devices, secure_input_check())
74
+ wanted = list(BUTTONS) + list(MOVES) + ([Quartz.kCGEventKeyDown] if keys else [])
75
+ mask = 0
76
+ for event_type in wanted:
77
+ mask |= Quartz.CGEventMaskBit(event_type)
78
+
79
+ def callback(_proxy, event_type, event, _info):
80
+ if event_type in DISABLED:
81
+ Quartz.CGEventTapEnable(self.tap, True)
82
+ else:
83
+ dispatcher.handle(event_type, event)
84
+ return event
85
+
86
+ self._callback = callback
87
+ self.tap = Quartz.CGEventTapCreate(
88
+ Quartz.kCGSessionEventTap,
89
+ Quartz.kCGHeadInsertEventTap,
90
+ Quartz.kCGEventTapOptionListenOnly, # we can watch but never alter or block input
91
+ mask,
92
+ callback,
93
+ None,
94
+ )
95
+ if self.tap is None:
96
+ self.close()
97
+ raise BackendError("macOS refused to let this app watch input. Run `clickdust doctor`.")
98
+ self._source = Quartz.CFMachPortCreateRunLoopSource(None, self.tap, 0)
99
+ Quartz.CFRunLoopAddSource(Quartz.CFRunLoopGetCurrent(), self._source, Quartz.kCFRunLoopDefaultMode)
100
+ Quartz.CGEventTapEnable(self.tap, True)
101
+
102
+ def pump(self, seconds: float) -> None:
103
+ Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, seconds, False)
104
+
105
+ def alive(self) -> bool:
106
+ return self.tap is not None and bool(Quartz.CFMachPortIsValid(self.tap))
107
+
108
+ def close(self) -> None:
109
+ tap = getattr(self, "tap", None)
110
+ if tap is not None:
111
+ Quartz.CGEventTapEnable(tap, False)
112
+ Quartz.CFMachPortInvalidate(tap)
113
+ self.tap = None
114
+ if self.devices:
115
+ self.devices.close()
clickdust/claude.py ADDED
@@ -0,0 +1,132 @@
1
+ """Copy numbers out of Claude Code's session logs before Claude Code deletes them.
2
+
3
+ Claude Code keeps one JSON-lines file per session and removes old ones (30 days by
4
+ default). From each file only this is kept:
5
+
6
+ your messages when, and how many characters you typed
7
+ Claude replies when, and how many output tokens
8
+ events memory compactions and helper agents
9
+
10
+ Never stored: message text, session titles, file paths or project names.
11
+ """
12
+
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import re
17
+ from datetime import datetime
18
+ from pathlib import Path
19
+ from typing import List, NamedTuple, Optional
20
+
21
+ from .store import Store
22
+
23
+ PASTE_CAP = 2000 # characters; a longer message is mostly pasted material
24
+ HUMAN_SOURCES = ("typed", "queued", "suggestion_accepted")
25
+ # blocks the app puts into a message that the person did not type
26
+ INJECTED = re.compile(
27
+ r"<(pasted_content|system-reminder|command-[a-z]+|local-command-[a-z]+)\b.*?</\1[^>]*>", re.S
28
+ )
29
+
30
+
31
+ class Found(NamedTuple):
32
+ messages: List[tuple] # id, session, ts, chars
33
+ replies: List[tuple] # id, session, ts, tokens
34
+ events: List[tuple] # id, session, ts, kind
35
+
36
+
37
+ def logs_root() -> Path:
38
+ base = os.environ.get("CLAUDE_CONFIG_DIR")
39
+ return (Path(base).expanduser() if base else Path.home() / ".claude") / "projects"
40
+
41
+
42
+ def _short_hash(text: str) -> str:
43
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()[:24]
44
+
45
+
46
+ def _when(record) -> Optional[float]:
47
+ try:
48
+ return datetime.fromisoformat(record["timestamp"].replace("Z", "+00:00")).timestamp()
49
+ except (KeyError, TypeError, ValueError, AttributeError):
50
+ return None
51
+
52
+
53
+ def _typed_by_a_person(record) -> bool:
54
+ if record.get("isSidechain") or record.get("isMeta"):
55
+ return False
56
+ origin = record.get("origin")
57
+ kind = origin.get("kind") if isinstance(origin, dict) else None
58
+ return kind == "human" or (kind is None and record.get("promptSource") in HUMAN_SOURCES)
59
+
60
+
61
+ def _length(record) -> int:
62
+ if record.get("promptSource") == "suggestion_accepted":
63
+ return 0
64
+ content = (record.get("message") or {}).get("content")
65
+ if isinstance(content, list):
66
+ content = " ".join(b.get("text", "") for b in content if isinstance(b, dict) and b.get("type") == "text")
67
+ if not isinstance(content, str):
68
+ return 0
69
+ return min(len(INJECTED.sub("", content)), PASTE_CAP)
70
+
71
+
72
+ def parse(lines, session: str, helper: Optional[str] = None) -> Found:
73
+ """Read one log file. `helper` identifies a helper agent's own log."""
74
+ found = Found([], [], [])
75
+ first = None
76
+ for line in lines:
77
+ try:
78
+ record = json.loads(line)
79
+ kind = record.get("type")
80
+ except (ValueError, AttributeError):
81
+ continue # a line still being written, or not a record
82
+ if kind not in ("user", "assistant", "system"):
83
+ continue
84
+ ts = _when(record)
85
+ if ts is None:
86
+ continue
87
+ first = ts if first is None else min(first, ts)
88
+ if kind == "user" and helper is None and record.get("uuid") and _typed_by_a_person(record):
89
+ found.messages.append((record["uuid"], session, ts, _length(record)))
90
+ elif kind == "assistant":
91
+ message = record.get("message") or {}
92
+ tokens = (message.get("usage") or {}).get("output_tokens")
93
+ if message.get("id") and isinstance(tokens, int):
94
+ found.replies.append((message["id"], session, ts, tokens))
95
+ elif kind == "system" and record.get("subtype") == "compact_boundary" and record.get("uuid"):
96
+ found.events.append((record["uuid"], session, ts, "compact"))
97
+ if helper and first is not None:
98
+ found.events.append((helper, session, first, "helper"))
99
+ return found
100
+
101
+
102
+ def harvest(store: Store, root: Optional[Path] = None) -> int:
103
+ """Read every log that changed since last time. Returns the number of new messages."""
104
+ root = root or logs_root()
105
+ if not root.is_dir():
106
+ return 0
107
+ files = []
108
+ for path in root.rglob("*.jsonl"):
109
+ try:
110
+ info = path.stat()
111
+ except OSError:
112
+ continue
113
+ files.append((info.st_mtime, info.st_size, path))
114
+
115
+ before = store.claude_totals()[1]
116
+ known = store.claude_files()
117
+ for mtime, size, path in sorted(files): # oldest first, so a resumed copy does not claim old messages
118
+ parts = path.relative_to(root).parts
119
+ key = _short_hash("/".join(parts))
120
+ if known.get(key) == (size, mtime):
121
+ continue
122
+ if "subagents" in parts and len(parts) > 2:
123
+ session, helper = parts[1], key
124
+ else:
125
+ session, helper = path.stem, None
126
+ try:
127
+ with open(path, encoding="utf-8", errors="replace") as lines:
128
+ found = parse(lines, _short_hash(session), helper)
129
+ except OSError:
130
+ continue
131
+ store.add_claude(found.messages, found.replies, found.events, (key, size, mtime))
132
+ return store.claude_totals()[1] - before