aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/assistant.py
blob: 088cac32b7bb9b40c272c28cce40eece370af05d (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
# 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 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 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 (st["op"] or {}).get("running"):
            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 st["op"]:
            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