aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/assistant.py
blob: f0b3947e0a534090ea8b28449e75836c81f7e27a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# deck-it - assistant module
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

"""desktop-assistant on the tablet: chat, voice, model choice, and the
canvas's Ask presets and Do ops applied to a file picked on the PC.

One client of the daemon's socket (JSON lines both ways; every client sees
every event), folded into one state the tab polls. The protocol is
desktop-assistant's docs/superpowers/specs/2026-10-16-text-daemon-design.md.
"""

import json
import os
import socket
import struct
import subprocess
import threading
from pathlib import Path

from ..module import Module, ModuleError

RUN = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"))
SOCK = RUN / "desktop-assistant.sock"
VOICE = RUN / "deck-it" / "voice.wav"
MAX_VOICE = 2_000_000   # 60 s of 16 kHz mono 16-bit is 1.92 MB


def blank():
    return {"connected": False, "error": None, "state": "idle", "tool": None,
            "model": None, "chatModel": None, "turns": [], "pending": None,
            "notice": "", "models": [], "picking": None, "op": None,
            "catalog": None, "catalogError": "", "epoch": 0}


def _turn(t):
    return {"user": t.get("user", ""), "reply": t.get("reply", ""),
            "think": t.get("think", ""), "tools": list(t.get("tools") or [])}


def _daemon_op(st):
    """Whether a write the daemon is doing for this tab is in flight."""
    op = st["op"] or {}
    return bool(op.get("running") and op.get("daemon"))


def fold(st, e):
    """Apply one daemon event to the state the tab polls."""
    kind = e.get("type")
    if kind == "hello":
        st.update(state=e.get("state", "idle"), tool=e.get("tool"), model=e.get("model"),
                  chatModel=e.get("chat_model"),
                  turns=[_turn(t) for t in e.get("turns") or []],
                  pending=_turn(e["pending"]) if e.get("pending") else None,
                  epoch=st["epoch"] + 1)
    elif kind == "state":
        st.update(state=e.get("state", "idle"), tool=e.get("tool"))
    elif kind == "user":
        st.update(pending=_turn({"user": e.get("text", "")}), notice="")
    elif kind in ("think", "token"):
        p = st["pending"] or _turn({})
        p["think" if kind == "think" else "reply"] += e.get("delta", "")
        st["pending"] = p
    elif kind == "tool":
        if st["pending"] and not e.get("done"):
            st["pending"]["tools"].append(e.get("name", ""))
    elif kind == "done":
        if st["pending"]:
            st["turns"].append({**st["pending"], "stopped": bool(e.get("stopped"))})
        st["pending"] = None
    elif kind == "error":
        msg = e.get("message", "")
        if e.get("turn") and _daemon_op(st):
            st["op"].update(running=False, error=msg)      # a refused or failed write
        elif e.get("turn") and st["pending"]:
            st["turns"].append({**st["pending"], "error": msg})
            st["pending"] = None
        else:
            st["notice"] = msg
    elif kind == "ctx":
        if e.get("model"):
            st["model"] = e["model"]
    elif kind == "models":
        st["models"] = e.get("items") or []
    elif kind == "conversation":
        st.update(turns=[_turn(t) for t in e.get("turns") or []], pending=None,
                  chatModel=e.get("model"), epoch=st["epoch"] + 1)
    elif kind == "written":
        if _daemon_op(st):
            st["op"].update(running=False, ok=True, out=[e.get("path", "")])


def hears(models, wanted):
    """Whether the model that will hear a voice question takes audio: the
    chat's pick if it is local, else the loaded local model (a cloud chat's
    voice is transcribed locally). Unknown counts as yes."""
    local = [m for m in models if not m.get("cloud")]
    m = (next((m for m in local if m.get("id") == wanted), None)
         or next((m for m in local if m.get("status") != "unloaded"), None))
    inputs = m.get("inputs") if m else None
    return inputs is None or "audio" in inputs


def qarma_args(item, kinds):
    """The file dialog for a preset or op: filtered to its kinds' suffixes,
    several files unless the op takes one."""
    args = ["qarma", "--file-selection", f"--title={item['label']}", "--separator=\n"]
    if item.get("max") != 1:
        args.append("--multiple")
    exts = sorted({e for k in item.get("kinds", []) for e in kinds.get(k, [])})
    if exts:
        args.append(f"--file-filter={item['label']} | " + " ".join("*" + e for e in exts))
    return args


def make(cfg: dict) -> Module:
    shell = os.path.expanduser(cfg.get("assistant", {}).get("shell", ""))
    lock = threading.Lock()          # guards st
    send_lock = threading.Lock()     # one writer on the socket at a time
    voice_lock = threading.Lock()
    stop = threading.Event()
    st = blank()
    conn = {"sock": None, "qarma": None}

    def send(cmd):
        s = conn["sock"]
        if s is None:
            raise ModuleError("assistant not running")
        try:
            with send_lock:
                s.sendall((json.dumps(cmd) + "\n").encode())
        except OSError as e:
            raise ModuleError(f"assistant: {e}") from None

    def wanted():
        # Caller holds lock. As the canvas: the chat's pick, else the
        # preferred model, else none (the daemon uses what is loaded).
        return st["chatModel"] or (st["catalog"] or {}).get("preferred") or None

    def with_model(cmd):
        with lock:
            m = wanted()
        return {**cmd, "model": m} if m else cmd

    def loop():
        while not stop.is_set():
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            try:
                s.connect(str(SOCK))
            except OSError as e:
                s.close()
                with lock:
                    st.update(connected=False, error=str(e) or type(e).__name__)
                stop.wait(5)
                continue
            # A stalled daemon must not hang the HTTP handlers that send.
            s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, struct.pack("ll", 2, 0))
            conn["sock"] = s
            with lock:
                st.update(connected=True, error=None)
            # Off-thread: qs may take seconds; retries a catalog that failed at start.
            threading.Thread(target=load_catalog, daemon=True).start()
            try:
                send({"type": "models"})
                for line in s.makefile("r", encoding="utf-8", errors="replace"):
                    try:
                        e = json.loads(line)
                    except ValueError:
                        continue
                    if not isinstance(e, dict):
                        continue
                    with lock:
                        try:
                            fold(st, e)
                        except (AttributeError, TypeError, KeyError, IndexError):
                            continue
            except (OSError, ModuleError):
                pass
            conn["sock"] = None
            s.close()
            with lock:
                st.update(connected=False, error="disconnected")
                if _daemon_op(st):
                    st["op"].update(running=False, error="disconnected")
            stop.wait(5)

    def state():
        with lock:
            out = json.loads(json.dumps(st))   # a copy: the reader keeps writing
            out["wanted"] = wanted()
            out["hears"] = hears(st["models"], out["wanted"])
        return out

    def model(body):
        mid = body.get("id")
        with lock:
            m = next((x for x in st["models"] if x.get("id") == mid), None)
            if m is None:
                raise ModuleError("unknown model")
            was_cloud = any(x.get("cloud") and x.get("id") == wanted() for x in st["models"])
            # Moving a chat with turns to the cloud sends its history there.
            if m.get("cloud") and not was_cloud and st["turns"]:
                st["notice"] = f"History in this chat goes to {m.get('provider')}."
            st["chatModel"] = mid

    def voice(data):
        if data[:4] != b"RIFF" or data[8:12] != b"WAVE":
            raise ModuleError("not a WAV")
        if conn["sock"] is None:
            raise ModuleError("assistant not running")
        with voice_lock:      # one clip at a time: the file is shared
            VOICE.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
            tmp = VOICE.with_suffix(".tmp")
            tmp.write_bytes(data)
            os.replace(tmp, VOICE)
            send(with_model({"type": "ask", "text": "", "audio": str(VOICE)}))

    def load_catalog():
        try:
            out = subprocess.run(["qs", "-p", shell, "ipc", "call", "assistant", "catalog"],
                                 capture_output=True, text=True, timeout=5, check=True).stdout
            cat, err = json.loads(out), ""
            if not isinstance(cat, dict):
                cat, err = None, "keystone's catalog is not an object"
        except (OSError, subprocess.SubprocessError, ValueError) as e:
            cat, err = None, f"no presets from keystone: {e}"
        with lock:
            if cat is not None:
                st["catalog"] = cat
            st["catalogError"] = err
        return cat, err

    def choose(cat, item):
        """Paths picked in qarma on the PC; [] when the dialog is cancelled."""
        p = subprocess.Popen(qarma_args(item, cat.get("kinds", {})),
                             stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
        conn["qarma"] = p
        out, _ = p.communicate()
        conn["qarma"] = None
        if p.returncode not in (0, 1):      # 1 is a cancelled dialog
            raise subprocess.SubprocessError(f"qarma exited {p.returncode}")
        return [x for x in out.split("\n") if x.startswith("/")] if p.returncode == 0 else []

    def set_op(**kw):
        with lock:
            st["op"].update(**kw)

    def run_pick(cat, item, kind):
        try:
            paths = choose(cat, item)
        except (OSError, subprocess.SubprocessError) as e:
            with lock:
                st.update(picking=None, notice=str(e) if isinstance(e, subprocess.SubprocessError) else f"qarma: {e}")
            return
        with lock:
            st["picking"] = None
        if not paths:
            return
        try:
            if kind == "preset":
                send(with_model({"type": "ask", "text": item["prompt"], "files": paths}))
                return
            with lock:
                st["op"] = {"label": item["label"], "running": True, "ok": False, "out": [], "error": "",
                            "daemon": item["op"] == "md"}
            if len(paths) < item.get("min", 1):
                set_op(running=False, error=f"{item['label']} needs at least {item['min']} files")
            elif item["op"] == "md":
                # As the canvas: the daemon writes it; `written` ends the op.
                send({"type": "write", "files": paths[:1], "prompt": cat["mdPrompt"],
                      "dir": cat["outDir"], "name": Path(paths[0]).stem + ".md"})
            else:
                try:
                    out = subprocess.run([cat["fileops"], item["op"], cat["outDir"], *paths],
                                         capture_output=True, text=True, timeout=600).stdout
                    r = json.loads(out.strip().splitlines()[-1])
                    if not isinstance(r, dict):
                        raise ValueError
                except subprocess.TimeoutExpired:
                    r = {"ok": False, "error": "fileops timed out"}
                except (OSError, ValueError, IndexError):
                    r = {"ok": False, "error": "fileops gave no answer"}
                set_op(running=False, ok=bool(r.get("ok")), out=r.get("out") or [], error=r.get("error", ""))
        except Exception as e:      # nothing may leave the op running
            with lock:
                if st["op"] and st["op"]["running"]:
                    st["op"].update(running=False, error=str(e) or type(e).__name__)
                else:
                    st["notice"] = str(e) or type(e).__name__

    def pick(body):
        cat, err = load_catalog()
        if not cat:
            raise ModuleError(err or "no presets from keystone")
        if isinstance(body.get("preset"), str):
            kind, items, label = "preset", cat.get("presets", []), body["preset"]
        elif isinstance(body.get("op"), str):
            kind, items, label = "op", cat.get("ops", []), body["op"]
        else:
            raise ModuleError("preset or op required")
        item = next((i for i in items if i.get("label") == label), None)
        if item is None:
            raise ModuleError(f"unknown {kind}: {label}")
        with lock:
            if st["picking"] or (st["op"] or {}).get("running"):
                raise ModuleError("busy")
            st.update(picking=label, op=None)
        threading.Thread(target=run_pick, args=(cat, item, kind), daemon=True).start()

    def cancel(body):
        p = conn["qarma"]
        if p is not None:
            p.terminate()

    def close():
        # ponytail: a close() between connect and conn["sock"] = s leaves the
        # reader blocked until the daemon speaks; the thread is a daemon one.
        stop.set()
        s = conn["sock"]
        if s is not None:
            try:
                s.shutdown(socket.SHUT_RDWR)
            except OSError:
                pass

    return Module(
        name="assistant", title="Assistant", state=state,
        actions={"stop": lambda b: send({"type": "stop"}),
                 "new": lambda b: send({"type": "new"}),
                 "models": lambda b: send({"type": "models"}),
                 "model": model, "voice": voice, "pick": pick, "cancel": cancel},
        uploads={"voice": ("audio/wav", MAX_VOICE)},
        start=lambda: [threading.Thread(target=f, daemon=True).start() for f in (loop, load_catalog)],
        stop=close,
    )