Repository navigation
Expand file tree
/
Copy pathserver_win.py
More file actions
6328 lines (5745 loc) · 302 KB
/
Copy pathserver_win.py
File metadata and controls
6328 lines (5745 loc) · 302 KB
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Orb Server — Windows Edition
Voice AI with local Ollama brain + Edge TTS + Claude Code integration + desktop commands.
"""
import asyncio
import base64
import contextlib
import contextvars
import hashlib
import io
import json
import logging
import os
import re
import shutil
import sys
import subprocess
import tempfile
import time
import uuid
from contextlib import asynccontextmanager
from datetime import datetime, timedelta
from pathlib import Path
# Load .env into the environment BEFORE any os.getenv calls below. Without
# this, ORB_TOKEN (and other settings) were never read from .env, so the
# server auto-generated a fresh random token every restart that never matched
# the bundle/config.json — the real cause of the mobile auth failures.
_dotenv = Path(__file__).resolve().with_name(".env")
if _dotenv.is_file():
for _entry in map(str.strip, _dotenv.read_text(encoding="utf-8").splitlines()):
if not _entry or _entry[0] == "#" or "=" not in _entry:
continue
_name, _sep, _value = _entry.partition("=")
os.environ.setdefault(_name.strip(), _value.strip().strip("\"'"))
import edge_tts
import httpx
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request, Response
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import stt
import tools
import memory_store
import tool_registry
import intent_router
import connectors
import brain
import tasks_store
import screen_bridge
import agent
# Optional legacy modules — NOT shipped in the public snapshot (2026-07-23 trim):
# site_templates seeds build prompts with reference URLs; semantic_router is the
# flag-off Layer-1 embedding matcher. Both degrade to None cleanly when absent.
try:
import site_templates
except ImportError:
site_templates = None
try:
import semantic_router
except ImportError:
semantic_router = None
# AGENT SPINE — the thin agentic loop (agent.py) as the conversational brain:
# the model sees history + tools and decides to talk or call a tool, escalating to
# Haiku only when it needs a bigger brain. Default ON. Set ORB_AGENT_SPINE=0 to
# fall back to the legacy router-first pipeline (kept for A/B + safety).
_AGENT_SPINE = os.getenv("ORB_AGENT_SPINE", "1").lower() not in ("0", "false", "no")
# INSTANT-ACK layer — when the spine runs on a slow claude brain, speak a short
# in-character "heard you" BEFORE the real answer so the turn never feels dead
# during the ~10-13s Haiku latency. Sent as an ADDITIVE {type:"ack"} WS message
# (a client that doesn't handle it simply ignores it — no breakage). DEFAULT OFF
# until the mobile UI wires ack-then-answer playback (see MAC_DELEGATION.md);
# flip on with ORB_ACK=1.
_AGENT_ACK = os.getenv("ORB_ACK", "0").lower() not in ("0", "false", "no")
# Long-term memory (memory.py): inject relevant learned facts into the agent's
# context, and distill new facts after each turn (extraction runs on the LOCAL
# model, off the claude -p budget). DEFAULT OFF — the "knowing when to say what"
# relevance gate needs tuning WITH the user before it shapes live replies. See
# PERSONALIZATION_PLAN.md. Enable with ORB_MEMORY=1.
_AGENT_MEMORY = os.getenv("ORB_MEMORY", "0").lower() not in ("0", "false", "no")
async def _safe_send(ws: WebSocket, payload: dict):
"""Send JSON to a websocket, swallowing errors if it's already closed."""
try:
if ws.client_state.name == "CONNECTED":
await ws.send_text(json.dumps(payload))
except Exception:
pass
async def _safe_send_text(ws: WebSocket, text: str):
"""Send a pre-serialized JSON string, swallowing errors if closed."""
try:
if ws.client_state.name == "CONNECTED":
await ws.send_text(text)
except Exception:
pass
_CHAT_LOG = Path(__file__).parent / "data" / "chat_log.jsonl"
def _log_chat(role: str, text: str, intent: str = ""):
"""Append a conversation turn to a persistent JSONL log (survives restarts) so
real conversations can be reviewed to diagnose behaviour."""
try:
_CHAT_LOG.parent.mkdir(exist_ok=True)
with open(_CHAT_LOG, "a", encoding="utf-8") as f:
f.write(json.dumps({"t": time.strftime("%Y-%m-%d %H:%M:%S"),
"role": role, "text": text,
**({"intent": intent} if intent else {})}) + "\n")
except Exception:
pass
# All connected WS clients (orb overlay, chat HUD, mobile). Orb-state updates are
# BROADCAST to all so the orb animates no matter which client triggered the turn
# (e.g. typing in the chat HUD must animate the orb the same as voice does).
_CLIENTS: set = set()
_MOBILE_CLIENTS: set = set() # subset of _CLIENTS that are phone connections
async def _broadcast_status(state: str):
for c in list(_CLIENTS):
await _safe_send(c, {"type": "status", "state": state})
# The CURRENT working focus — what Orb is on right now. SHARED across all
# connections (a new chat window must not forget what's being worked on); persists
# until explicitly dropped ("forget that" / "never mind"). Single-user assistant,
# so a process-global focus is correct.
_FOCUS = {"subject": None}
# Current BACKGROUND job (deep research) — so the user can keep talking while it
# runs, ask "how's it coming", and get told when it's done. Process-global
# (single user). Cards pop as the work lands; completion is announced.
_BG = {"desc": None, "status": "idle", "started": 0.0}
# Mobile dispatch (Phase 1). A phone can't run the Qt card windows (pythonw +
# PySide6), so when the responding client is MOBILE the _spawn_* helpers send a
# WS message instead of spawning a window — the mobile HUD (mobile_hud.ts) then
# renders the SAME card.html in an in-page panel. The DESKTOP path is unchanged.
# The current client is carried per-connection in a ContextVar set in voice_ws;
# it's visible to the synchronous _spawn_* helpers called from within the
# connection's process_transcript task (contextvars propagate through sync calls).
# NOTE: until the mobile client identifies itself (Phase 2 handshake), every
# connection is "desktop", so _dispatch_to_mobile always returns False and the
# desktop behaviour is byte-for-byte unchanged.
_current_client: contextvars.ContextVar = contextvars.ContextVar("current_client", default=None)
async def _safe_ws_send(ws, obj: dict) -> bool:
"""Returns True only if the message was actually handed to a CONNECTED
socket without raising — callers that need to know delivery actually
happened (not just attempted) should check this, not assume."""
try:
if ws.client_state.name == "CONNECTED":
await ws.send_text(json.dumps(obj))
return True
except Exception as e:
log.warning(f"[mobile dispatch] send failed: {e}")
return False
def _dispatch_to_mobile(obj: dict) -> bool:
"""If the current responding client is mobile, fire it a HUD message and
return True so the caller SKIPS the desktop Qt spawn. Else return False and
the desktop path runs exactly as before."""
client = _current_client.get()
if client and client.get("kind") == "mobile":
ws = client.get("ws")
try:
asyncio.get_running_loop().create_task(_safe_ws_send(ws, obj))
except RuntimeError:
pass
return True
return False
def _set_focus(state: dict, subject):
if subject:
state["last_subject"] = subject
_FOCUS["subject"] = subject
def _get_focus(state: dict):
return state.get("last_subject") or _FOCUS.get("subject")
async def _settle_others_idle(origin_ws, delay: float):
"""After a reply, return OTHER clients' orbs to idle. They animated on the
broadcast 'thinking' but (unlike the originator) don't receive the audio to
self-idle on playback end — so without this the orb stays grown ('stuck big'
after a chat turn). The originator is excluded so voice is unaffected."""
try:
await asyncio.sleep(delay)
for c in list(_CLIENTS):
if c is not origin_ws:
await _safe_send(c, {"type": "status", "state": "idle"})
except Exception:
pass
logging.basicConfig(level=logging.INFO, format="%(asctime)s [orb] %(message)s")
log = logging.getLogger("orb")
import personas
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://localhost:11434")
OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "qwen3.5:9b")
# HTTP/WS bind port. ORB_PORT (or legacy ORB_PORT) in .env moves everything —
# the bind, the resident /mcp URL, the internal relay base, and screen URLs.
PORT = int(os.getenv("ORB_PORT") or "8340")
# Persona controls wake word, system prompt, TTS voice, address form, and orb hue.
# Override with ORB_PERSONA / ORB_PERSONA in env or .env (default: orb — the
# neutral public persona). Individual settings below can still override the
# persona defaults (TTS_VOICE, USER_NAME).
PERSONA = personas.get(os.getenv("ORB_PERSONA") or os.getenv("ORB_PERSONA") or "orb")
TTS_VOICE = os.getenv("TTS_VOICE", PERSONA.tts_voice)
USER_NAME = os.getenv("USER_NAME") or PERSONA.address_user_as or "the user"
# Canned-reply vocative: honorific personas say "sir"/"human"; personas without
# one (Orb) address by real name, or drop the address when no name is set.
_VOC = PERSONA.address_user_as or (os.getenv("USER_NAME") or "").strip()
def _voc() -> str:
return f", {_VOC}" if _VOC else ""
# Auth token for the WebSocket. Required when accessed over the internet
# (e.g. mobile PWA via Cloudflare Tunnel). If empty, no auth is enforced
# (intended for purely-local desktop use). Connections from 127.0.0.1 are
# always allowed.
import secrets as _secrets
ORB_TOKEN = os.getenv("ORB_TOKEN", "")
if not ORB_TOKEN:
# Auto-generate one on first launch and persist it to .env so it's stable
ORB_TOKEN = _secrets.token_urlsafe(24)
try:
env_path = Path(__file__).parent / ".env"
existing = env_path.read_text() if env_path.exists() else ""
if "ORB_TOKEN=" not in existing:
with env_path.open("a", encoding="utf-8") as f:
f.write(f"\nORB_TOKEN={ORB_TOKEN}\n")
except Exception:
pass
# ---------------------------------------------------------------------------
# Desktop commands — fast, deterministic, no LLM needed
# ---------------------------------------------------------------------------
import random as _random
# Desktop commands with varied replies so Orb doesn't sound robotic.
def _desktop_reply(app: str) -> str:
templates = [
f"{app} is open, sir.",
f"Pulled up {app}.",
f"{app} launched, sir.",
f"{app} is ready.",
f"Opening {app} now, sir.",
f"{app}, at your disposal.",
f"Done, sir. {app} is up.",
]
return _random.choice(templates)
DESKTOP_COMMANDS: dict[str, dict] = {
"open chrome": {"url": "https://www.google.com", "app": "your browser"},
"open browser": {"url": "https://www.google.com", "app": "your browser"},
"open vs code": {"cmd": "start code", "app": "VS Code"},
"open vscode": {"cmd": "start code", "app": "VS Code"},
"open visual studio code": {"cmd": "start code", "app": "VS Code"},
"open terminal": {"cmd": "start wt", "app": "Terminal"},
"open command prompt": {"cmd": "start cmd", "app": "Command Prompt"},
"open powershell": {"cmd": "start powershell", "app": "PowerShell"},
"open explorer": {"cmd": "start explorer", "app": "Explorer"},
"open file explorer": {"cmd": "start explorer", "app": "File Explorer"},
"open task manager": {"cmd": "start taskmgr", "app": "Task Manager"},
"open notepad": {"cmd": "start notepad", "app": "Notepad"},
"open settings": {"cmd": "start ms-settings:", "app": "Windows Settings"},
"open calculator": {"cmd": "start calc", "app": "Calculator"},
"open obs": {"cmd": "start obs64.exe", "app": "OBS Studio"},
"open discord": {"cmd": "start discord", "app": "Discord"},
"open spotify": {"cmd": "start spotify", "app": "Spotify"},
"open steam": {"cmd": "start steam", "app": "Steam"},
"open youtube": {"url": "https://youtube.com", "app": "YouTube"},
"open github": {"url": "https://github.com", "app": "GitHub"},
"open davinci resolve": {"cmd": "start resolve", "app": "DaVinci Resolve"},
}
# Note: "look up X" used to open a Google search in Chrome. That collides
# with the intent router's lookup_fact (which the user wants for factual
# questions). So "look up" is now a lookup_fact trigger, not a browser
# search. Only "search for X" / "google X" still open Chrome.
SEARCH_PREFIXES = ["search for", "google", "search the web for"]
# Claude Code trigger phrases — building AND inspecting/awareness tasks
# Explicitly NAMING the build tool is unambiguous intent — match anywhere in
# the sentence ("get claude code to make a chess game").
CLAUDE_EXPLICIT_TRIGGERS = [
"claude code", "open claude", "start claude", "switch to claude",
]
# Imperative build / inspect verbs. These must START the command (the text is
# run through _command_form first, which strips polite/question framing), so a
# mid-sentence "make a"/"build a" in ordinary conversation ("that'll make a big
# difference", "I want to build a habit") no longer fires a build. Matched with
# a word boundary so "make an appointment" / "build another" don't false-fire.
CLAUDE_PREFIX_TRIGGERS = [
"build me", "build this", "build a", "code this", "code me", "make me a",
"make a", "create a", "create me", "write me", "fix this code", "debug this",
# Awareness / delegation — Claude inspects files/folders and reports back.
# Kept narrow on purpose: "tell me about the" was removed because it
# collided with lookup_fact ("tell me about the Eiffel Tower"). For
# filesystem inspection the user can still say "look in the folder",
# "check the directory", "describe what's in", etc.
"describe what", "what's in the", "what is in the", "look in the", "look at the",
"read the file", "summarize the file", "check the folder", "list the files",
"what files", "show me what's",
]
# Mute trigger phrases
MUTE_TRIGGERS = ["mute yourself", "mute", "go to sleep", "shut up", "be quiet", "stop listening", "go silent", "stand down", "go dormant"]
# Wake word — transcript MUST contain this or it's ignored entirely
WAKE_WORD = "orb"
def contains_wake_word(text: str) -> bool:
"""True if the transcript addresses the active persona (Orb or ULTRON).
Accepts the persona's full variant list plus a few common STT mishears for
Orb. The variant list comes from personas.py."""
lower = text.lower()
# Persona-supplied variants
if any(v in lower for v in PERSONA.wake_words):
return True
# Extra STT-mishear variants only for the Orb persona
if PERSONA.name == "orb":
extra = ("jervis", "gervis", "travis", "harvis", "jarfis", "garvis",
"service", "jar vis", "jar-vis")
return any(v in lower for v in extra)
return False
def strip_wake_word(text: str) -> str:
"""Remove the persona's wake word (and lazy variants) from the start."""
import re
# Build pattern from the active persona's variants, longest-first so
# 'orb' matches before 'jarv'.
variants = sorted(PERSONA.wake_words, key=len, reverse=True)
if PERSONA.name == "orb":
variants = variants + ["jervis", "gervis", "travis", "harvis", "jarfis",
"garvis", "service", "jar vis", "jar-vis"]
escaped = [re.escape(v) for v in variants]
pattern = r"^(?:hey\s+)?(?:" + "|".join(escaped) + r")[,\s]*"
stripped = re.sub(pattern, "", text, count=1, flags=re.IGNORECASE).strip()
return stripped if stripped else text
def _strip_to_empty(text: str) -> str:
"""Like strip_wake_word but returns "" when nothing meaningful remains
(used only for the bare-wake detector — process_transcript uses
strip_wake_word which preserves text if stripping empties it).
Tolerates 1-2 trailing junk characters after the wake word so STT
mishears like 'Jervish.' (heard 'Orb' with a phantom 'sh') still
register as a bare wake instead of getting punted to the LLM as 'h.'."""
import re
variants = sorted(PERSONA.wake_words, key=len, reverse=True)
if PERSONA.name == "orb":
variants = variants + [
"orbe", "orbs", "orba", "orab", "or b",
"orib", "orph", "orb it", "orbit", "arb",
]
escaped = [re.escape(v) for v in variants]
# Allow up to 2 trailing alphabetic characters (STT residue) before
# punctuation/whitespace and end-of-string.
pattern = r"^(?:hey\s+)?(?:" + "|".join(escaped) + r")[a-z]{0,2}[,\s.!?]*$"
return re.sub(pattern, "", text.strip(), flags=re.IGNORECASE).strip()
# Round-robin pointer for bare-wake replies. Random picks alone can hit the
# same reply twice in a row, which is exactly what the user complained about.
# Round-robin with a small random jump guarantees no immediate repeats while
# still feeling unscripted.
_bare_wake_idx = 0
def pick_bare_wake_reply() -> str:
"""Return a varied 'hello sir' for when the user just says 'Orb' with
no follow-up. Avoids hitting the LLM (faster, and Qwen converges on the
same phrasing). Falls back to a literal reply if the persona forgot to
declare a pool."""
global _bare_wake_idx
pool = PERSONA.bare_wake_replies
if not pool:
return f"Yes{_voc()}."
import random
# Advance by a small random step so the order shuffles each cycle.
_bare_wake_idx = (_bare_wake_idx + random.randint(1, max(1, len(pool) // 3))) % len(pool)
return pool[_bare_wake_idx]
def is_bare_wake(raw_text: str) -> bool:
"""True if the user said only the wake word (possibly with filler like
'hey' or trailing punctuation) and nothing else of substance."""
return _strip_to_empty(raw_text) == ""
_status_query_idx = 0
_STATUS_QUERY_PATTERNS = (
"how are you", "how're you", "hows it going", "how's it going",
"how are things", "how goes it", "you doing", "you doing okay",
"you good", "you alright", "you ok", "you okay",
"all good", "everything good", "everything alright",
"you there", "you with me", "you awake", "you online",
"how do you feel", "how you doing", "what's up", "whats up",
"status report", "status check", "systems check",
)
def is_status_query(stripped_text: str) -> bool:
"""True if the post-wake-word text is a casual status check.
`stripped_text` is the result of strip_wake_word() (already lowercased
in practice by callers — we lowercase here defensively)."""
t = stripped_text.lower().strip().rstrip(".!?,;:")
return any(t == p or t.startswith(p) for p in _STATUS_QUERY_PATTERNS)
def pick_status_query_reply() -> str:
"""Varied reply for 'how are you' style questions. Avoids the LLM and
its convergent 'functioning within optimal parameters' phrasing."""
global _status_query_idx
pool = PERSONA.status_query_replies
if not pool:
return f"All well{_voc()}."
import random
_status_query_idx = (_status_query_idx + random.randint(1, max(1, len(pool) // 3))) % len(pool)
return pool[_status_query_idx]
_ack_idx = 0
def pick_ack_reply() -> str:
"""A short, content-free, in-character 'heard you, working on it' line —
spoken instantly BEFORE the slower Haiku answer so the user knows their
request landed. Round-robin so it never repeats back-to-back."""
global _ack_idx
pool = PERSONA.ack_replies
if not pool:
return f"One moment{_voc()}."
import random
_ack_idx = (_ack_idx + random.randint(1, max(1, len(pool) // 3))) % len(pool)
return pool[_ack_idx]
def _normalize(text: str) -> str:
"""Lowercase and strip trailing punctuation so 'shut up.' matches 'shut up'."""
return text.lower().strip().rstrip(".!?,;:")
def match_mute_command(text: str) -> bool:
lower = _normalize(text)
for t in MUTE_TRIGGERS:
if t == "mute":
# Bare "mute" silences Orb, but ONLY as an exact command.
# "mute the volume / sound / audio / system" is a system-audio
# connector (see connectors.py) — don't let the "mute " prefix
# swallow it into Orb self-mute.
if lower == "mute":
return True
elif lower == t or lower.startswith(t + " "):
return True
return False
STOP_TRIGGERS = ["stop", "cancel", "stop what you're doing", "stop what you are doing",
"never mind", "nevermind", "abort", "forget it", "stop that"]
def match_stop_command(text: str) -> bool:
lower = _normalize(text)
return any(lower == t or lower.startswith(t + " ") for t in STOP_TRIGGERS)
FORGET_TRIGGERS = ["forget everything", "wipe memory", "clear memory",
"forget our conversation", "start over", "reset memory"]
def match_forget_command(text: str) -> bool:
lower = _normalize(text)
return any(t in lower for t in FORGET_TRIGGERS)
STATUS_PHRASES = ["status", "update", "how's it going", "how is it going",
"are you done", "is it done", "are you finished", "is it finished",
"how's the", "hows the", "what's the progress", "progress",
"where are we", "how far", "you done", "done yet", "finished yet",
"still working", "what are you doing", "what are you working on"]
def match_status_question(text: str) -> bool:
lower = _normalize(text)
return any(p in lower for p in STATUS_PHRASES)
# Polite / question framing that disguises a COMMAND. "Can you open reddit",
# "could you play music", "please open youtube" are requests to ACT — but the
# question word made them bypass the action router and hit the LLM, which then
# waffles ("I cannot directly access Reddit"). Stripping these to the bare
# command lets the deterministic action matchers fire. NOTE: status questions
# ("did you", "has it", "is it done") are deliberately NOT in here, so they
# still can't trigger an action/build.
_POLITE_PREFIX = re.compile(
r"^(?:hey\s+|please\s+|"
r"can you(?: please)?\s+|could you(?: please)?\s+|would you(?: please)?\s+|"
r"will you(?: please)?\s+|can we\s+|let'?s\s+|"
r"i(?:'d| would) like you to\s+|i want you to\s+|i need you to\s+|"
r"go ahead and\s+|please go ahead and\s+)",
re.IGNORECASE)
_AFFIRM = re.compile(
r"^(?:yes|yeah|yep|yup|sure|absolutely|do it|go ahead|please do|do that|"
r"go for it|yes please|yeah do it|yeah do that|let'?s do it|sounds good)\b",
re.IGNORECASE)
def is_affirmation(text: str) -> bool:
"""True for 'yes / do it / go ahead' — used to act on a pending offer."""
return bool(_AFFIRM.match(text.strip()))
def _command_form(text: str) -> str:
"""Strip leading politeness/question framing so 'can you open reddit'
becomes 'open reddit' for the deterministic action matchers. Handles
stacked politeness ('can you please ...'). Returns the original text if
stripping would empty it."""
t = text.strip()
prev = None
while t and t != prev:
prev = t
t = _POLITE_PREFIX.sub("", t, count=1).strip()
return t or text.strip()
def match_desktop_command(text: str) -> dict | None:
lower = _normalize(text)
for trigger, action in DESKTOP_COMMANDS.items():
if lower == trigger or lower.startswith(trigger + " "):
return action
for prefix in SEARCH_PREFIXES:
if lower.startswith(prefix + " "):
query = text[len(prefix):].strip()
if query:
from urllib.parse import quote_plus
return {
"url": f"https://www.google.com/search?q={quote_plus(query)}",
"reply": f"Searching for {query}, sir.",
}
return None
# Yes/no question openers — when the transcript STARTS with one of these,
# it's a question, not a command, no matter what else appears in it. This
# stops "has Claude Code made the organization app?" from triggering a
# new build (a real bug ninjahawk hit in live testing).
_QUESTION_OPENERS = (
"did", "does", "do", "is", "are", "was", "were", "has", "have", "had",
"can", "could", "will", "would", "should", "may", "might", "shall",
"am",
)
def match_claude_trigger(text: str) -> str | None:
lower = text.lower().strip().lstrip(",. ").rstrip(".?!,")
if not lower:
return None
first_word = lower.split(" ", 1)[0]
# If it's framed as a yes/no question, it's NEVER a Claude Code request,
# even if it mentions "claude" or "make" somewhere in the body.
if first_word in _QUESTION_OPENERS:
return None
# Explicitly naming the tool fires from anywhere in the sentence.
for trigger in CLAUDE_EXPLICIT_TRIGGERS:
if trigger in lower:
return text
# Build/inspect verbs only fire when they START the (command-form) request,
# with a trailing word boundary — so "make a website" triggers but "that'll
# make a difference" / "make an appointment" do not.
for trigger in CLAUDE_PREFIX_TRIGGERS:
if lower == trigger or lower.startswith(trigger + " "):
return text
return None
_TASK_ADD = re.compile(
r"^(?:hey\s+)?(?:remind me to|remind me that|note to self[,:]?\s*(?:to\s+)?|"
r"don'?t let me forget to|i need to remember to|add (?:a )?(?:task|reminder|note)[:]?\s*)(.+)$",
re.IGNORECASE)
_TASK_ADD_TOLIST = re.compile(
r"^(?:add|put)\s+(.+?)\s+(?:to|on)\s+(?:my|the)\s+(?:list|to-?do(?:\s*list)?|tasks?)$",
re.IGNORECASE)
_TASK_LIST = re.compile(
r"\b(what(?:'s| is| are)?\s+on my (?:list|to-?do)|what are my (?:tasks|to-?dos?)|"
r"what do i (?:have|need) to do|read (?:me )?my (?:list|tasks)|my to-?do list|"
r"what'?s my to-?do|what are you (?:doing|working on|up to)|what are your tasks)\b",
re.IGNORECASE)
_TASK_DONE = re.compile(
r"^(?:mark|cross off|check off|i (?:just )?finished|i'?ve finished|done with|"
r"completed?|finished|remove)\s+(.+?)"
r"(?:\s+(?:from (?:my|the) list|off (?:my|the) list|as done|done|off))?$",
re.IGNORECASE)
_TASK_CLEAR = re.compile(
r"\b(?:clear|empty|wipe|reset)\s+(?:my|the)\s+(?:list|tasks?|to-?do)\b", re.IGNORECASE)
_TASK_LAST = re.compile(
r"\b(what did i (?:just )?(?:ask|say|tell you|request)|"
r"what was my (?:last|previous) (?:message|request|thing|task)|"
r"what was i saying|what did i ask you to do)\b", re.IGNORECASE)
_HIGH_PRI = re.compile(r"\b(high priority|urgent|asap|important|right away|critical)\b", re.IGNORECASE)
_LOW_PRI = re.compile(r"\b(low priority|whenever|no rush|eventually|someday)\b", re.IGNORECASE)
def match_task_command(text: str) -> dict | None:
"""Deterministic to-do/working-memory commands: add / list / complete /
clear, and 'what was my last request'. Returns an action dict or None."""
t = text.strip().rstrip(".!?")
if _TASK_CLEAR.search(t):
return {"action": "clear"}
if _TASK_LAST.search(t):
return {"action": "last"}
m = _TASK_ADD_TOLIST.match(t)
if m:
body = m.group(1).strip()
if body:
return {"action": "add", "text": body, "priority": _task_priority(t)}
m = _TASK_ADD.match(t)
if m:
body = m.group(1).strip()
if body:
return {"action": "add", "text": body, "priority": _task_priority(t)}
if _TASK_LIST.search(t):
return {"action": "list"}
m = _TASK_DONE.match(t)
if m:
body = m.group(1).strip()
if body and len(body) > 1:
return {"action": "complete", "text": body}
return None
def _task_priority(text: str) -> int:
if _HIGH_PRI.search(text):
return 1
if _LOW_PRI.search(text):
return 3
return 2
async def run_desktop_command(cmd: str):
try:
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
await asyncio.wait_for(proc.wait(), timeout=5)
except Exception as e:
log.error(f"Desktop command failed: {cmd} — {e}")
# ---------------------------------------------------------------------------
# Claude Code integration
# ---------------------------------------------------------------------------
ORB_OUTPUT_DIR = Path.home() / "Desktop" / "Orb_Output"
def is_read_only_task(prompt: str) -> bool:
"""Tasks that only inspect/describe shouldn't create a project folder."""
lower = prompt.lower()
read_verbs = ["describe", "what's in", "what is in", "look in", "look at",
"read", "check", "summarize", "tell me about", "list", "show me what"]
return any(v in lower for v in read_verbs)
CLAUDE_DEFAULT_MODEL = os.getenv("CLAUDE_MODEL", "haiku") # cheap default for testing
def extract_model(prompt: str) -> tuple[str, str]:
"""Pull a model directive out of the spoken prompt.
'build me X using opus' -> ('opus', 'build me X'). Default: CLAUDE_DEFAULT_MODEL.
"""
model = CLAUDE_DEFAULT_MODEL
cleaned = prompt
lower = prompt.lower()
for alias in ("opus", "sonnet", "haiku"):
for phrase in (f"use {alias}", f"using {alias}", f"with {alias}", f"on {alias}"):
if phrase in lower:
model = alias
# remove the directive phrase from the prompt
idx = lower.find(phrase)
cleaned = (prompt[:idx] + prompt[idx + len(phrase):]).strip(" ,.")
return model, cleaned
return model, cleaned
async def run_claude_code(prompt: str, ws: WebSocket):
"""Run `claude -p` with full permissions so it actually creates files."""
claude_path = shutil.which("claude")
if not claude_path:
log.warning("Claude Code CLI not found in PATH")
return ("I'm afraid Claude Code isn't installed on this machine, sir.", "")
model, prompt = extract_model(prompt)
ORB_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
read_only = is_read_only_task(prompt)
if read_only:
# Inspection task — run from Desktop, don't force file creation
wrapped = (
f"You are running autonomously via the {PERSONA.display_name} voice assistant. "
f"The user asked: \"{prompt}\"\n\n"
f"Investigate and answer concisely. The user's Desktop is the current directory. "
f"Report what you find in a few sentences — this will be read aloud."
)
cwd = str(Path.home() / "Desktop")
else:
# Build task — force actual file creation in a dedicated project folder
# AND demand quality output (the bare default is ugly).
tpl = site_templates.match_template(prompt) if site_templates else None
template_block = site_templates.render_template_block(tpl) + "\n" if tpl else ""
if tpl:
log.info(f"[claude] template injected: {tpl.name} ({tpl.reference_url})")
wrapped = (
f"You are running autonomously as the {PERSONA.display_name} voice assistant's hands. "
f"The user asked: \"{prompt}\"\n\n"
+ template_block +
"CRITICAL RULES:\n"
"1. Actually CREATE the files on disk — do NOT just describe them.\n"
"2. Create a new descriptively-named subfolder for this project inside the\n"
" current directory (the output folder on the Desktop). Write all\n"
" files there.\n"
"3. The user said 'looks like crap' about bare HTML. So: this must look\n"
" PROFESSIONAL by default — not a 1995 page.\n"
" - For web pages: use Tailwind CSS via CDN, a tasteful modern color\n"
" palette (consider slate/zinc neutrals + one accent), real hero\n"
" section, proper typography (Inter or system font), responsive\n"
" layout, subtle gradients/shadows where appropriate, semantic HTML.\n"
" - For scripts/apps: complete, runnable, with a clean README.\n"
"4. Implement the FULL feature, not a stub or placeholder. If the user\n"
" asked for a landing page, include hero + features + footer at minimum.\n"
"5. Open the project in the user's default browser if it's a web project\n"
" (use `start <file>` on Windows) so they can see it immediately.\n"
"6. When finished, end with ONE sentence stating what was built and the\n"
" folder name."
)
cwd = str(ORB_OUTPUT_DIR)
log.info(f"[claude] Running (model={model}, read_only={read_only}, cwd={cwd}): \"{prompt[:80]}\"")
await ws.send_text(json.dumps({"type": "status", "state": "working"}))
proc = None
try:
proc = await asyncio.create_subprocess_exec(
claude_path, "-p", wrapped,
"--model", model,
"--permission-mode", "bypassPermissions",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=cwd,
)
# Poll for completion, sending progress updates so the loop isn't a black box.
comm_task = asyncio.ensure_future(proc.communicate())
start = time.time()
last_spoken_update = start
DASH_INTERVAL = 4 # update dashboard every 4s
SPOKEN_INTERVAL = 30 # spoken "still working" every 30s
TIMEOUT = 300
while not comm_task.done():
await asyncio.sleep(DASH_INTERVAL)
elapsed = int(time.time() - start)
if elapsed > TIMEOUT:
proc.kill()
comm_task.cancel()
log.error("[claude] Timed out after 300s")
return ("That task is taking too long, sir — I've stopped it.", "")
# Dashboard progress (cheap, frequent)
try:
await ws.send_text(json.dumps({
"type": "progress", "text": f"working... {elapsed}s", "elapsed": elapsed,
}))
except Exception:
pass
# Spoken reassurance (sparse)
if time.time() - last_spoken_update >= SPOKEN_INTERVAL:
last_spoken_update = time.time()
log.info(f"[claude] heartbeat — {elapsed}s elapsed")
stdout, stderr = await comm_task
output = stdout.decode("utf-8", errors="replace").strip()
if proc.returncode != 0:
err = stderr.decode("utf-8", errors="replace").strip()
log.error(f"[claude] Failed (exit {proc.returncode}): {err[:300]}")
return ("Claude Code ran into a problem, sir. Check the logs.", "")
log.info(f"[claude] Output ({len(output)} chars) in {int(time.time()-start)}s")
# Summarize into ONE spoken sentence via Ollama, grounded in actual output.
try:
summary_prompt = [
{"role": "user", "content": (
f"Claude Code just finished this task: '{prompt}'.\n\n"
f"Here is its output:\n{output[:2000]}\n\n"
f"In ONE short sentence as {PERSONA.display_name}, "
"tell the user what was accomplished. Be specific about what was built or done. "
"No markdown."
)}
]
spoken = await ollama_chat(summary_prompt, f"You are {PERSONA.display_name}. Respond in one concise sentence.")
except Exception:
spoken = "Done, sir. The task is complete."
return (spoken, output[:2000])
except asyncio.CancelledError:
# User said "stop" — kill the subprocess
log.info("[claude] Cancelled — killing subprocess")
if proc and proc.returncode is None:
try:
proc.kill()
except Exception:
pass
raise
except Exception as e:
log.error(f"[claude] Error: {e}")
return ("Something went wrong spawning Claude Code, sir.", "")
def _newest_output_folder(since: float) -> str:
"""Return the name of the most recently-created folder in Orb_Output
(created after `since`), or "" if none. Used to report what REALLY got
built on disk — not what the LLM claims."""
try:
if not ORB_OUTPUT_DIR.exists():
return ""
candidates = [
p for p in ORB_OUTPUT_DIR.iterdir()
if p.is_dir() and p.stat().st_mtime >= since - 2
]
if not candidates:
return ""
newest = max(candidates, key=lambda p: p.stat().st_mtime)
return newest.name
except Exception:
return ""
async def claude_worker(prompt: str, ws: WebSocket, conv, respond, state):
"""Background wrapper around run_claude_code. Tracks REAL state so status
questions report reality, never hallucinated progress."""
try:
spoken, raw_output = await run_claude_code(prompt, ws)
# Verify what actually landed on disk
folder = _newest_output_folder(state["claude_started"])
state["claude_folder"] = folder
# Detect failure honestly from the run_claude_code result
failed = ("ran into a problem" in spoken) or ("went wrong" in spoken) or ("too long" in spoken)
state["claude_status"] = "failed" if failed else "done"
state["claude_result"] = spoken
memory_note = spoken
if raw_output:
memory_note += f"\n\n[Claude Code output for reference: {raw_output[:1000]}]"
if folder:
memory_note += f"\n[Verified on disk: folder '{folder}' in Orb_Output]"
conv.add_assistant(memory_note)
await respond(spoken)
try:
await ws.send_text(json.dumps({"type": "status", "state": "idle"}))
except Exception:
pass
except asyncio.CancelledError:
state["claude_status"] = "failed"
state["claude_result"] = "Task was stopped."
log.info("[claude] worker cancelled")
try:
await ws.send_text(json.dumps({"type": "status", "state": "idle"}))
except Exception:
pass
except Exception as e:
state["claude_status"] = "failed"
state["claude_result"] = f"Error: {e}"
log.error(f"[claude] worker error: {e}")
# ---------------------------------------------------------------------------
# Ollama chat
# ---------------------------------------------------------------------------
# Conversation-only addendum. The deterministic router handles all factual
# / tool-needing queries BEFORE the LLM sees them, so the LLM should only
# get conversational input — and it should NEVER talk about "tools" or
# "looking things up." Just be the character.
_CONV_BLOCK = """
IMPORTANT — STAY IN CHARACTER:
- Never mention tools, lookups, searches, web access, or how you obtain
information. You simply know things.
- NEVER INVENT FACTS. Do not state any specific live or external figure —
weather, temperatures, prices, stock moves, news, scores, dates, statistics —
unless it already appears earlier in THIS conversation. If you are asked for
such information and don't already have it, say plainly you don't have it to
hand (one sentence) rather than making something up. Fabricating a number is
the worst thing you can do.
- For follow-up questions, answer from what was already said in this
conversation — reference it directly, don't start over.
- Don't repeat a reply you've already given; vary your wording every time.
- One sentence, two maximum. No markdown. You are speaking out loud.
WHAT YOU CAN ACTUALLY DO (affirm these plainly if the user asks — NEVER deny
a capability you genuinely have):
- Open apps and websites, and pull up saved sites (email, calendar, GitHub…).
- Start the user's music and control playback (play, pause, skip, previous)
and the system volume.
- Give weather, news and factual answers; report system stats; take and
recall notes; do calculations; read a web page the user names.
- Hand larger coding or build tasks to Claude Code.
- Switch your own thinking model between the local brain and Claude
(Haiku, Sonnet, Opus) when asked.
You do these things directly — when asked "can you X" and X is on this list,
the answer is yes. (You still never narrate "looking things up".)
"""
# ORB_SYSTEM is now derived from the active persona at module load.
# Tests and other callers that imported ORB_SYSTEM keep working unchanged.
ORB_SYSTEM = PERSONA.system_prompt + _CONV_BLOCK
async def ollama_chat(messages: list[dict], system: str) -> str:
payload = {
"model": OLLAMA_MODEL,
"messages": [{"role": "system", "content": system}] + messages,
"stream": False,
"think": False,
"keep_alive": "60m", # keep model resident so it never reloads mid-conversation
"options": {"num_predict": 200, "temperature": 0.7},
}
# 30s ceiling — a warm qwen3.5:9b replies in <1s, so anything past 30s is a real
# problem and we should fail fast rather than leave the user stuck on "thinking".
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.post(f"{OLLAMA_URL}/api/chat", json=payload)
resp.raise_for_status()
data = resp.json()
content = data.get("message", {}).get("content", "").strip()
content = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL).strip()
return content or "I'm afraid words escape me at the moment, sir."
async def ollama_chat_with_tools(messages: list[dict], system: str,
max_rounds: int = 3) -> tuple[str, list[str]]:
"""Call Ollama with the tool registry attached. If the model invokes a tool,
execute it, append the result, and call again until it produces plain text.
Returns (final_reply, [tool_names_used]). max_rounds caps tool-loop depth so
a confused model can't spin forever.
"""
tools_used: list[str] = []
convo: list[dict] = [{"role": "system", "content": system}] + list(messages)
for round_num in range(max_rounds):
payload = {
"model": OLLAMA_MODEL,
"messages": convo,
"stream": False,
"think": False,
"keep_alive": "60m",
"tools": tool_registry.tools_schema(),
"options": {"num_predict": 250, "temperature": 0.5},
}
async with httpx.AsyncClient(timeout=45.0) as client:
resp = await client.post(f"{OLLAMA_URL}/api/chat", json=payload)
resp.raise_for_status()
msg = resp.json().get("message", {}) or {}
tool_calls = msg.get("tool_calls") or []
content = (msg.get("content") or "").strip()
content = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL).strip()
if not tool_calls:
# Model produced a final reply.
return (content or "I'm afraid words escape me at the moment, sir."), tools_used
# Execute each tool call sequentially, append results, loop.
convo.append({"role": "assistant", "content": content, "tool_calls": tool_calls})
for call in tool_calls:
fn = (call.get("function") or {})
name = fn.get("name", "")
args = fn.get("arguments") or {}
if isinstance(args, str):
try:
args = json.loads(args)
except json.JSONDecodeError:
args = {}
result = await tool_registry.dispatch(name, args)
tools_used.append(name)
convo.append({"role": "tool", "name": name, "content": result})
# Hit the round cap — return whatever last text we got or a graceful fallback.
return ("I've gathered the information, sir — let me know if you need more.",