Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
4495 lines (4243 loc) · 208 KB
/
Copy pathserver.py
File metadata and controls
4495 lines (4243 loc) · 208 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
"""Friday web UI — https://localhost:8500
Browser captures mic (16 kHz mono) over a WebSocket; server runs
Silero VAD -> Parakeet TDT -> Qwen3.8 vLLM stream -> OmniVoice TTS and
streams 24 kHz audio back. Microphone endpointing is gated during playback.
Friday can read/edit files in this project and restart herself.
System prompt lives in system_prompt.md; local development state lives in state/.
Run: venv/bin/python server.py
"""
import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import asyncio
import base64
import hashlib
import json
import math
import re
import secrets
import ssl
import subprocess
import threading
import time
import urllib.request
from datetime import UTC, datetime
from pathlib import Path
from zoneinfo import ZoneInfo
import numpy as np
import uvicorn
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from openai import AsyncOpenAI, DefaultAsyncHttpxClient
from friday_core import (AdmissionBudget, ApprovalService, BatchExecutionOutcome,
CapabilityManager,
ClaimedStep, ContractBuilder, CoreUpgradeHarness,
CorrectedAudioStore, DurableStepWorker,
DeploymentManager, EvolutionEngine, FeedbackService, GraphStore,
IntentInterpreter, MachineOperator, MemoryCurator,
ModelRouter, OperatorGrantService, OutcomeVerifier,
Planner, PolicyEngine, ReflectionService, ReminderService,
ReminderWorker, SkillManager, StepExecutionResult,
PublicWebProxy, ResourceAdmissionController, ResourceSnapshot,
PiperSpeechSynthesizer,
TaskContract, TaskService,
SkillsShRegistry, VoiceManager, WebOperator, fetch_news,
choose_speech_backend,
decide_turn,
FAST_CONVERSATION_TEMPERATURE,
FAST_CONVERSATION_TOP_P,
fast_system_prompt, format_news_list,
format_capability_answer,
format_runtime_answer, page_receipt_has_article_evidence,
observation_tools_only,
load_asr,
migrate_session_json,
requested_browser_install_tool,
requested_capability_topic,
requested_news_list_count, resource_claim_for,
resolve_evidence_followup, runtime_topics,
safe_for_fast_conversation,
TurnDisposition, unverified_action_claim_request)
from friday_core.processes import (
BubblewrapProfile, ProcessBindingError, ProcessBroker,
ProcessBrokerError, ProcessCleanupBlocked, ProcessLimits,
ProcessParameter, ProcessPresentation, ProcessResources,
ProcessSessionAccess, ProcessSpec, ProcessSpecRegistry,
SystemdUserProcessBackend,
)
from friday_core.desktop import (
DesktopApplicationLaunchBinding, DesktopBindingError, DesktopBroker,
DesktopBrokerError, HyprlandDesktopBackend,
)
from friday_core.omarchy import (
OmarchyActionBinding, OmarchyBindingError, OmarchyBrokerError,
OmarchyDesktopBackend, OmarchyDesktopBroker,
)
from friday_host import desktop_io, procs
from friday_host.host import current_host
from friday_host.platform_capabilities import compute_capabilities
from friday_core.platform_gate import (filter_tool_schema, inventory_entries,
platform_status, unsupported_tools)
from friday_core.embeddings import configured_local_embedder
from friday_core.vision_evals import has_qualified_native_vision_score
from friday_core.tasks import (tool_arguments_are_private,
tool_has_private_payload,
tool_result_log_summary)
from friday_core.tls import ensure_tls_material
from friday_core.local_http import (count_prompt_tokens,
normalize_loopback_model_base_url,
open_loopback_request)
from friday_core.frontend import load_frontend
from friday_core.conversation_runtime import (
bounded_response_fallback,
canonical_chat_turn,
completion_integrity_issue,
compile_chat_messages,
compile_fast_chat_messages,
conversation_history_scope,
drop_repeated_echo_messages,
drop_repeated_echo_turns,
echo_turn_signature,
is_action_request,
latest_user_only,
grounded_project_messages,
response_contract_issue,
)
from friday_core.transport import (
valid_host,
valid_origin,
)
from friday_core.voice_transport import VoiceTransportSession
from friday_core.task_orchestration import RecoveredBatchFinalizer
from friday_core.builtin_tools import (
BLOCKING_IO_TOOLS, BUILTIN_TOOL_NAMES, BUILTIN_TOOL_SCHEMAS,
DESKTOP_TOOL_NAMES, EXACT_STEP_APPROVAL_TOOLS, OMARCHY_ACTION_TOOLS,
OMARCHY_STATUS_TOOL, OMARCHY_TOOL_NAMES, PROCESS_TOOL_NAMES,
BuiltinToolAdapters, BuiltinToolRuntime,
)
from friday_core.speech import (accelerator_oom_error, inference_context,
load_omnivoice_runtime,
release_accelerator_memory)
from friday_core.vad import SileroOnnxVad, pinned_vad_model_path
SAMPLE_RATE = 16000
TTS_RATE = 24000
SPEECH_THRESHOLD = 0.5
SILENCE_END_MS = 700
PRE_ROLL_MS = 350
POST_ROLL_MS = 250
BARGE_IN_MS = 220
PLAYBACK_ECHO_TAIL_MS = 1_500
MIN_UTTERANCE_SECONDS = 0.55
MIN_UTTERANCE_DBFS = -38.0
MAX_UTTERANCE_S = 30
HISTORY_TURNS = 24
LOCAL_BASE_URL = normalize_loopback_model_base_url(os.environ.get(
"FRIDAY_LOCAL_BASE_URL", "http://127.0.0.1:18021/v1"))
LOCAL_MODEL = os.environ.get("FRIDAY_LOCAL_MODEL", "qwen3.8-27b").strip()
LLM_ENGINE = os.environ.get("FRIDAY_LLM_ENGINE", "vllm").strip() or "vllm"
TTS_DEVICE = os.environ.get("FRIDAY_TTS_DEVICE", "cuda").strip().lower()
try:
MODEL_CONTEXT_TOKENS = int(
os.environ.get("FRIDAY_MODEL_CONTEXT_TOKENS", "8192"))
except ValueError as exc:
raise RuntimeError("FRIDAY_MODEL_CONTEXT_TOKENS must be an integer") from exc
if MODEL_CONTEXT_TOKENS < 2048:
raise RuntimeError("FRIDAY_MODEL_CONTEXT_TOKENS must be at least 2048")
MAX_OUTPUT_TOKENS = 600
PROMPT_SAFETY_TOKENS = 128
PROMPT_TOKEN_BUDGET = MODEL_CONTEXT_TOKENS - MAX_OUTPUT_TOKENS - PROMPT_SAFETY_TOKENS
MAX_TOOL_ROUNDS = 8
MAX_TOOL_ACTIONS = 8
FAST_HISTORY_TURNS = 6
FAST_CONTEXT_CHARS = 8_000
UNGROUNDED_ACTION_CLAIM = re.compile(
r"\b(?:i(?:'m| am)\s+(?:working|adding|editing|modifying|changing|updating|"
r"checking|inspecting|reading|fetching|creating|implementing|fixing|testing|"
r"activating|switching)|"
r"(?:i(?:'ll| will)|let me)\s+(?:add|edit|modify|change|update|check|inspect|read|fetch|"
r"create|implement|fix|test|activate|switch)|"
r"(?:give me (?:a moment|a minute)|one sec))\b",
re.IGNORECASE)
UNGROUNDED_COMPLETION_CLAIM = re.compile(
r"\bi(?:'ve| have)?\s+(?:added|built|changed|checked|closed|created|deleted|"
r"disabled|edited|enabled|installed|locked|modified|opened|removed|restarted|"
r"set|started|stopped|switched|updated|upgraded|written)\b",
re.IGNORECASE)
ACTION_REQUEST = re.compile(
r"^\s*(?:(?:please\s+)?(?:(?:can|could|would|will)\s+you\s+|"
r"i\s+(?:want|need)\s+you\s+to\s+|let(?:'s| us)\s+)?"
r"(?:add|build|change|check|create|delete|disable|edit|enable|fetch|fix|"
r"close|focus|implement|inspect|install|make|modify|notify|open|read|remind|remove|restart|search|set|switch|"
r"update|upgrade|use|wire|learn)\b|(?:do it|go ahead|proceed|start working)\b)",
re.IGNORECASE)
ACTION_FALLBACK = "I didn't execute that action."
REDACTED_TOOL_ARGUMENTS = '{"_FRIDAY_REDACTED":true}'
REDACTED_TOOL_RECEIPT = "[REDACTED SENSITIVE TOOL RECEIPT]"
PUBLIC_RESPONSE_ERROR = "Friday couldn't complete that response. Try again."
NEWS_INTENT = re.compile(
r"\b(?:news|headline(?:s)?|current events|what(?:'s| is) happening)\b",
re.IGNORECASE,
)
NEWS_SUMMARY_REQUEST = re.compile(
r"\b(?:summar(?:y|ise|ize|ised|ized)|brief|one[- ]?liner?|concise)\b",
re.IGNORECASE,
)
NEWS_STYLE_PREFERENCE = re.compile(
r"(?:\b(?:when|whenever)\b.{0,45}\b(?:news|headlines)\b|"
r"\b(?:news|headlines)\b.{0,45}\b(?:when|whenever)\b|"
r"\b(?:do not|don't)\s+(?:read|list)\b.{0,35}\b(?:everything|all|each|headlines)\b|"
r"\b(?:one[- ]?liner?|one\s+line|concise)\b.{0,35}\b(?:news|headlines|summary)\b|"
r"\b(?:news|headlines|summary)\b.{0,35}\b(?:one[- ]?liner?|one\s+line|concise)\b)",
re.IGNORECASE,
)
NEWS_META_PREFERENCE = re.compile(
r"(?:\b(?:when|whenever)\b.{0,45}\b(?:news|headlines)\b|"
r"\b(?:news|headlines)\b.{0,45}\b(?:when|whenever)\b|"
r"\b(?:do not|don't)\s+(?:read|list)\b.{0,35}\b(?:everything|all|each|headlines)\b)",
re.IGNORECASE,
)
SKILL_SEARCH_INTENT = re.compile(
r"\b(?:find|search|discover|learn|need|add)\b.{0,30}\bskills?\b|\bskills?\.sh\b",
re.IGNORECASE,
)
WEB_SEARCH_INTENT = re.compile(
r"\b(?:search (?:the )?web|look (?:it )?up|find (?:online|on the web)|"
r"research|latest information|weather|forecast|stock price|exchange rate|"
r"sports score)\b", re.IGNORECASE)
REMINDER_INTENT = re.compile(r"\bremind me\b", re.IGNORECASE)
VOICE_ACTIVATION_INTENT = re.compile(
r"\b(?:use|set|activate|load|lord|switch(?:\s+to)?|change(?:\s+to)?)\b"
r".{0,48}\b(?:voice|scarlet|base)\b",
re.IGNORECASE,
)
PROJECT_READ_INTENT = re.compile(
r"\b(?:inspect|read|review|check)\b.{0,96}"
r"\b(?:this\s+)?(?:project|repo(?:sitory)?|codebase|module|source)\b",
re.IGNORECASE,
)
VOICE_RUNTIME_INTENT = re.compile(
r"\b(?:what|which)\b.{0,48}\b(?:tts|voice|speech\s+backend)\b|"
r"\b(?:are|is)\b.{0,48}\b(?:piper|omni\s*voice|omnivoice|pocket\s*t\s*s|scarlet)\b|"
r"\b(?:start|enable|use|switch(?:\s+to)?)\b.{0,40}"
r"\b(?:piper|omni\s*voice|omnivoice)\b",
re.IGNORECASE,
)
FILLER_UTTERANCE = re.compile(r"^\s*(?:um+|uh+|erm+|hmm+|mm+)\s*[.!?]*\s*$",
re.IGNORECASE)
def _voice_audio_is_admissible(
*, audio_seconds: float, signal_dbfs: float,
) -> bool:
return (audio_seconds >= MIN_UTTERANCE_SECONDS
and signal_dbfs >= MIN_UTTERANCE_DBFS)
STALE_CAPABILITY_DENIAL = re.compile(
r"\b(?:i (?:do not|don't) have (?:a )?news feed|i (?:do not|don't) have "
r"(?:a )?web tool|no live feed)\b", re.IGNORECASE)
NEWS_DELIVERY_PREFERENCE = (
"Give news as one concise spoken summary sentence by default; do not read "
"individual headlines unless I explicitly ask for the list or details."
)
REPO = Path(__file__).parent.resolve()
OWNER_NAME = (
os.environ.get("FRIDAY_OWNER_NAME", "").strip()
or Path.home().name
)
_CONFIGURED_STATE_DIR = os.environ.get("FRIDAY_STATE_DIR", "").strip()
STATE_DIR = Path(_CONFIGURED_STATE_DIR or str(REPO / "state")).expanduser().resolve()
SESSION_FILE = STATE_DIR / "session.json"
SERVER_LOG_FILE = STATE_DIR / "logs" / "server.log"
PROMPT_FILE = REPO / "system_prompt.md"
def _harden_private_runtime_file(path: Path) -> None:
if path.exists():
os.chmod(path, 0o600)
_harden_private_runtime_file(SESSION_FILE)
_harden_private_runtime_file(SERVER_LOG_FILE)
def _empty_cuda_cache() -> None:
release_accelerator_memory()
def _tokenize_url() -> str:
root = LOCAL_BASE_URL[:-3] if LOCAL_BASE_URL.endswith("/v1") else LOCAL_BASE_URL
return root.rstrip("/") + "/tokenize"
def _new_local_llm_client() -> AsyncOpenAI:
return AsyncOpenAI(
base_url=LOCAL_BASE_URL, api_key=KEY,
http_client=DefaultAsyncHttpxClient(
trust_env=False, follow_redirects=False))
DEFAULT_PROMPT = (
"You are Friday, a personal AI assistant. Runtime identity is supplied by "
f"the host and must never be guessed from this prompt (user: {OWNER_NAME}). "
"Match the active "
"delivery mode: concise natural speech in voice; complete, polished answers "
"with useful Markdown in text. Start with the answer. No filler, repetition, "
"canned sections, or decorative formatting. Dry wit."
)
TOOL_SCHEMA = BUILTIN_TOOL_SCHEMAS
def _native_vision_qualified() -> bool:
"""Require a current-fingerprint five-scene pass before tool exposure."""
if not bool(globals().get("NATIVE_VISION_ENABLED", False)):
return False
graph = globals().get("GRAPH")
fingerprint = str(globals().get("RUNTIME_FINGERPRINT", ""))
model = str(globals().get("LOCAL_MODEL", ""))
max_side = globals().get("NATIVE_VISION_MAX_SIDE")
if (graph is None or re.fullmatch(r"[0-9a-f]{64}", fingerprint) is None
or not isinstance(max_side, int)):
return False
return has_qualified_native_vision_score(
graph, model=model, runtime_fingerprint=fingerprint,
max_side=max_side)
def _remote_enabled() -> bool:
router = globals().get("MODEL_ROUTER")
return bool(router is not None and router.remote_enabled)
def current_tool_schema() -> list[dict]:
capabilities = globals().get("CAPABILITIES")
builtins = filter_tool_schema(
TOOL_SCHEMA, unsupported=unsupported_tools(globals().get("PLATFORM")),
remote_enabled=_remote_enabled(),
vision_qualified=_native_vision_qualified())
return builtins + (capabilities.tool_schemas() if capabilities else [])
def available_tool_names() -> set[str]:
capabilities = globals().get("CAPABILITIES")
names = {item["function"]["name"] for item in current_tool_schema()
if item["function"]["name"] in BUILTIN_TOOL_NAMES}
return names | (capabilities.active_names() if capabilities else set())
def capability_inventory() -> list[dict]:
builtins = inventory_entries(
TOOL_SCHEMA, unsupported=unsupported_tools(globals().get("PLATFORM")),
remote_enabled=_remote_enabled(),
vision_qualified=_native_vision_qualified())
capabilities = globals().get("CAPABILITIES")
dynamic = ([{**item, "kind": "dynamic"} for item in capabilities.list()]
if capabilities else [])
return builtins + dynamic
BUILTIN_TOOL_RUNTIME = BuiltinToolRuntime()
def _safe_path(path: str):
return BUILTIN_TOOL_RUNTIME.safe_project_path(REPO, path)
def _builtin_tool_adapters() -> BuiltinToolAdapters:
return BuiltinToolAdapters(
repo=REPO,
fetch_news=fetch_news,
web=WEB,
skill_source=SKILL_SOURCE,
reminders=REMINDERS,
run_process=subprocess.run,
start_process=subprocess.Popen,
)
def exec_tool(name: str, args: dict) -> str:
return BUILTIN_TOOL_RUNTIME.execute(
name, args, _builtin_tool_adapters())
class Friday:
def __init__(self):
self.vad = SileroOnnxVad(pinned_vad_model_path(REPO))
self._session_lock = threading.RLock()
self._voice_lock = threading.RLock()
print("loading asr...", flush=True)
self.asr = load_asr(REPO / "models" / "sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8")
print(f"asr backend: {self.asr.name}", flush=True)
print("loading tts...", flush=True)
self.tts_backend = choose_speech_backend(
tts_device=TTS_DEVICE, repo=REPO)
self.tts_device = TTS_DEVICE
self.piper = None
self.tts = None
if self.tts_backend == "piper":
self.piper = PiperSpeechSynthesizer(REPO, output_rate=TTS_RATE)
self.tts_device = "cpu"
self._reserve = None
print("tts backend: piper (kristin, cpu, local)", flush=True)
else:
self.tts, self._reserve = load_omnivoice_runtime(
REPO, self.tts_device)
print("models loaded", flush=True)
self.llm = _new_local_llm_client()
self.clone_enabled = (self.tts_backend == "omnivoice"
and os.environ.get(
"FRIDAY_VOICE_CLONE", "1").lower() not in {
"0", "false", "off", "no"
})
self.instruct = "female, young adult, moderate pitch"
self.ref_audio = None
self.clone_prompt = None
self.voice_name = (self.piper.voice_name
if self.piper is not None else "base")
active_voice = VOICES.active()
if self.tts_backend == "omnivoice":
try:
self._configure_voice(active_voice)
except Exception as exc:
print(f"active voice unavailable, using base: {exc}", flush=True)
self._configure_voice(VOICES.get("base"))
elif str(active_voice.get("name") or "base") != "base":
try:
self._transition_to_omnivoice(active_voice)
print(
f"restored active voice: {self.voice_name} (omnivoice, "
f"{self.tts_device})", flush=True)
except Exception as exc:
print(
f"active voice unavailable, keeping {self.voice_name}: {exc}",
flush=True)
system_prompt = (PROMPT_FILE.read_text() if PROMPT_FILE.is_file()
else DEFAULT_PROMPT)
system_prompt = system_prompt.replace("{{owner_name}}", OWNER_NAME).replace(
"{{project_root}}", str(REPO))
if SESSION_FILE.is_file():
try:
h = json.loads(SESSION_FILE.read_text())
rest = h[1:] if h and h[0]["role"] == "system" else h
self.history = [{"role": "system", "content": system_prompt}] + rest
loaded_messages = len(self.history)
self.history = self._drop_repeated_echo_messages(self.history)
removed_messages = loaded_messages - len(self.history)
repaired = (f"; removed {removed_messages} echo-loop messages"
if removed_messages else "")
print(f"restored session ({len(self.history)} messages{repaired})",
flush=True)
except Exception:
self.history = [{"role": "system", "content": system_prompt}]
else:
self.history = [{"role": "system", "content": system_prompt}]
def save_session(self):
try:
lock = getattr(self, "_session_lock", None)
if lock is None:
lock = self._session_lock = threading.RLock()
with lock:
sensitive_calls: set[str] = set()
for message in self.history:
for call in message.get("tool_calls") or []:
function = call.get("function") or {}
tool_name = str(function.get("name") or "")
if (tool_has_private_payload(tool_name)
or tool_arguments_are_private(tool_name)):
sensitive_calls.add(str(call.get("id") or ""))
self.history = self._drop_repeated_echo_messages(self.history)
snapshot = json.loads(json.dumps(self.history[-80:]))
for message in snapshot:
for call in message.get("tool_calls") or []:
function = call.get("function") or {}
tool_name = str(function.get("name") or "")
if (tool_has_private_payload(tool_name)
or tool_arguments_are_private(tool_name)):
# vLLM's Qwen tool template parses every persisted
# argument string as JSON. Keep the privacy marker
# parseable, then omit its whole turn from prompts.
function["arguments"] = REDACTED_TOOL_ARGUMENTS
if (message.get("role") == "tool"
and str(message.get("tool_call_id") or "")
in sensitive_calls):
message["content"] = REDACTED_TOOL_RECEIPT
temporary = SESSION_FILE.with_suffix(
SESSION_FILE.suffix + f".{os.getpid()}.new")
flags = (os.O_WRONLY | os.O_CREAT | os.O_TRUNC
| getattr(os, "O_NOFOLLOW", 0))
descriptor = os.open(temporary, flags, 0o600)
with os.fdopen(descriptor, "w") as stream:
json.dump(snapshot, stream)
stream.flush()
os.fsync(stream.fileno())
temporary.replace(SESSION_FILE)
os.chmod(SESSION_FILE, 0o600)
except Exception as e:
print("session save failed:", e)
def _latest_web_receipt(self, *, max_age_seconds: int = 900
) -> tuple[str, dict] | None:
"""Return recent structured web evidence retained in conversation history."""
visible_urls: list[str] = []
for message in reversed(self.history[-40:]):
if message.get("role") == "assistant" and not visible_urls:
visible_urls = re.findall(
r"https?://[^\s<>]+", str(message.get("content") or ""))
visible_urls = [url.rstrip(").,]") for url in visible_urls]
if message.get("role") != "tool":
continue
try:
value = json.loads(str(message.get("content") or ""))
except (TypeError, json.JSONDecodeError):
continue
if not isinstance(value, dict):
continue
if value.get("headlines"):
kind = "news"
key = "headlines"
elif value.get("results"):
kind = "search"
key = "results"
else:
continue
fetched = value.get("fetched_at")
if fetched:
try:
observed = datetime.fromisoformat(
str(fetched).replace("Z", "+00:00"))
if observed.tzinfo is None:
observed = observed.replace(tzinfo=ZoneInfo("UTC"))
now = datetime.now(observed.tzinfo)
if (now - observed).total_seconds() > max_age_seconds:
continue
except (TypeError, ValueError):
continue
if visible_urls:
visible = set(visible_urls)
filtered = [
item for item in value.get(key, [])
if isinstance(item, dict)
and str(item.get("url") or "") in visible]
if filtered:
value = dict(value)
value[key] = filtered
return kind, value
return None
@staticmethod
def _is_news_followup(text: str, has_recent_receipt: bool) -> bool:
if not NEWS_INTENT.search(text):
return False
if NEWS_META_PREFERENCE.search(text):
return True
return has_recent_receipt and bool(NEWS_SUMMARY_REQUEST.search(text))
@staticmethod
def _remember_news_style(utterance_id: str | None) -> bool:
"""Promote the explicit one-line-news preference once, with provenance."""
if utterance_id is None:
return False
existing = next((claim for claim in MEMORY.list(
lifecycle="active", limit=100)
if claim.get("subject") == OWNER_NAME
and claim.get("predicate") == "news_delivery_style"
and claim.get("object") == NEWS_DELIVERY_PREFERENCE), None)
if existing:
return True
claim_id = MEMORY.propose(
subject=OWNER_NAME, predicate="news_delivery_style",
object_value=NEWS_DELIVERY_PREFERENCE,
scope="user_preference", evidence_class="user_explicit",
source_node_ids=[utterance_id], confidence=1.0,
retention_reason="explicit news delivery preference")
return MEMORY.evaluate(claim_id).promoted
def _configure_voice(self, profile: dict) -> None:
if getattr(self, "tts_backend", "omnivoice") != "omnivoice":
raise RuntimeError(
"voice cloning requires the OmniVoice speech backend")
config = profile["config"]
kind = profile["kind"]
clone_prompt = None
ref_audio = None
instruct = str(config.get("instruct") or
"female, young adult, moderate pitch")
if kind == "clone":
if not self.clone_enabled:
raise RuntimeError("voice cloning is disabled by FRIDAY_VOICE_CLONE")
reference = (REPO / str(config.get("reference", ""))).resolve()
voices_root = (REPO / "persona" / "voices").resolve()
if voices_root not in reference.parents or not reference.is_file():
raise RuntimeError("voice reference is unavailable")
# Reuse Friday's CPU ASR instead of loading Whisper on the GPU.
ref_text = self.asr.transcribe_file(reference)
if not ref_text:
raise RuntimeError("voice reference transcription was empty")
clone_prompt = self.tts.create_voice_clone_prompt(
str(reference), ref_text=ref_text)
clone_prompt.ref_audio_tokens = clone_prompt.ref_audio_tokens.cpu()
_empty_cuda_cache()
ref_audio = str(reference)
self.instruct = instruct
self.ref_audio = ref_audio
self.clone_prompt = clone_prompt
self.voice_name = profile["name"]
print(f"voice profile: {self.voice_name} ({kind})", flush=True)
def _transition_to_omnivoice(self, profile: dict) -> None:
"""Replace Piper only after OmniVoice and the requested profile load."""
if self.tts_device == "cpu":
raise RuntimeError("voice profiles require a GPU voice-balanced runtime restart")
old = (
getattr(self, "tts_backend", "unknown"),
getattr(self, "piper", None), getattr(self, "tts", None),
getattr(self, "_reserve", None),
getattr(self, "clone_enabled", False),
getattr(self, "instruct", "female, young adult, moderate pitch"),
getattr(self, "ref_audio", None),
getattr(self, "clone_prompt", None),
getattr(self, "voice_name", "unknown"),
)
model = None
try:
model, reserve = load_omnivoice_runtime(REPO, self.tts_device)
self.tts_backend = "omnivoice"
self.tts = model
self._reserve = reserve
self.clone_enabled = os.environ.get(
"FRIDAY_VOICE_CLONE", "1").lower() not in {
"0", "false", "off", "no"
}
self._configure_voice(profile)
self.piper = None
except Exception:
(
self.tts_backend, self.piper, self.tts, self._reserve,
self.clone_enabled, self.instruct, self.ref_audio,
self.clone_prompt, self.voice_name,
) = old
del model
_empty_cuda_cache()
raise
def _verify_current_voice(self) -> dict:
with inference_context():
if self.ref_audio:
out = self.tts.generate(
text="Friday voice verification.", language="English",
voice_clone_prompt=self.clone_prompt)
else:
out = self.tts.generate(
text="Friday voice verification.", language="English",
instruct=self.instruct)
audio = out[0]
samples = int(
audio.numel() if callable(getattr(audio, "numel", None))
else np.asarray(audio).size)
if samples < TTS_RATE // 4:
raise RuntimeError("voice verification produced insufficient audio")
return {"passed": True, "samples": samples, "sample_rate": TTS_RATE}
def activate_voice(self, name: str) -> str:
lock = getattr(self, "_voice_lock", None)
if lock is None:
lock = self._voice_lock = threading.RLock()
with lock:
proposed = VOICES.get(name)
if (getattr(self, "tts_backend", "unknown") == "omnivoice" and
getattr(self, "voice_name", "") == proposed["name"]
and VOICES.active()["name"] == proposed["name"]):
return (f"activated voice {proposed['name']}; it is already active on "
f"OmniVoice {self.tts_device}")
transitioned = getattr(self, "tts_backend", "unknown") != "omnivoice"
old = (self.instruct, self.ref_audio, self.clone_prompt, self.voice_name)
try:
if transitioned:
self._transition_to_omnivoice(proposed)
else:
self._configure_voice(proposed)
verification = self._verify_current_voice()
VOICES.activate(proposed["name"], verification)
transition = " using OmniVoice" if transitioned else ""
return (f"activated voice {proposed['name']}{transition} after a "
f"{verification['samples']}-sample synthesis test")
except Exception:
if not transitioned:
(self.instruct, self.ref_audio,
self.clone_prompt, self.voice_name) = old
raise
finally:
_empty_cuda_cache()
def rollback_voice(self) -> str:
previous = VOICES.previous()
if previous is None:
raise ValueError("no previous voice profile is available")
return self.activate_voice(previous["name"])
def voice_runtime_status(self) -> dict:
backend = str(getattr(self, "tts_backend", "unknown"))
runtime_voice = str(getattr(self, "voice_name", "unknown"))
device = str(getattr(self, "tts_device", "unknown"))
stored = VOICES.active()
stored_name = str(stored.get("name") or "base")
profile_active = backend == "omnivoice" and runtime_voice == stored_name
activation_supported = backend == "omnivoice" or device.startswith("cuda")
return {
"backend": backend,
"device": device,
"runtime_voice": runtime_voice,
"stored_active_profile": stored_name,
"stored_profile_is_runtime_active": profile_active,
"profile_activation_supported": activation_supported,
"runtime_change_required": (None if backend == "omnivoice" else
"voice profiles require a GPU voice-balanced runtime restart"
),
"profiles": VOICES.list(),
}
def runtime_receipt(self) -> dict:
"""Capture runtime identity from live objects and the resolved boot profile."""
manifest = globals().get("_RESOLVED_RUNTIME")
if not isinstance(manifest, dict):
manifest = {}
voice = self.voice_runtime_status()
raw_devices = manifest.get("llm_cuda_devices")
llm_devices = (
[f"cuda:{int(index)}" for index in raw_devices]
if isinstance(raw_devices, list) else [])
if not llm_devices and manifest.get("local_runtime_available") is True:
llm_devices = ["cpu"]
receipt = {
"observed_at": datetime.now(UTC).isoformat(),
"source": "live_runtime",
"runtime": {
"status": "running",
"profile": str(manifest.get("name") or "unknown"),
"fingerprint": str(manifest.get("fingerprint") or ""),
},
"llm": {
"model": str(manifest.get("served_model") or LOCAL_MODEL),
"provider": "local",
"devices": llm_devices,
},
"asr": {
"backend": str(getattr(self.asr, "name", "unknown")),
"device": str(getattr(self.asr, "device", "cpu")),
},
"tts": {
key: voice[key] for key in (
"backend", "device", "runtime_voice",
"stored_active_profile", "stored_profile_is_runtime_active",
"profile_activation_supported", "runtime_change_required")
},
}
encoded = json.dumps(
receipt, ensure_ascii=False, sort_keys=True,
separators=(",", ":")).encode()
receipt["receipt_sha256"] = hashlib.sha256(encoded).hexdigest()
return receipt
def capability_receipt(self) -> dict:
"""Capture supported features from live runtime objects and tool authority."""
tools = available_tool_names()
def has(*names: str) -> bool:
return all(name in tools for name in names)
receipt = {
"observed_at": datetime.now(UTC).isoformat(),
"source": "live_capability_runtime",
"features": {
"project_files": has("list_files", "read_file", "write_file"),
"web_research": has("fetch_news", "web_search", "read_web"),
"memory": has("remember_preference", "recall_memory"),
"reminders": has(
"create_reminder", "list_reminders", "cancel_reminder"),
"machine_files": has(
"machine_grant_path", "machine_list_path",
"machine_read_text", "machine_read_document"),
"ocr": has("machine_ocr_image"),
"managed_processes": bool(
globals().get("PROCESS_BROKER") is not None
and has("machine_list_process_specs", "machine_launch_process",
"machine_inspect_process")),
"desktop": bool(
globals().get("DESKTOP_BROKER") is not None
and has("machine_list_windows", "machine_focus_window")),
"omarchy": bool(
globals().get("OMARCHY_BROKER") is not None
and has(OMARCHY_STATUS_TOOL, *OMARCHY_ACTION_TOOLS)),
"browser": bool(
globals().get("WEB_PROXY_INITIALIZED") is True
and has("browser_open", "browser_snapshot", "browser_click",
"browser_type")),
"voice": bool(has("list_voices") and hasattr(self, "asr")
and hasattr(self, "tts_backend")),
"native_vision": has("machine_understand_image"),
},
}
encoded = json.dumps(
receipt, ensure_ascii=False, sort_keys=True,
separators=(",", ":")).encode()
receipt["receipt_sha256"] = hashlib.sha256(encoded).hexdigest()
return receipt
@staticmethod
def _record_runtime_receipt(receipt: dict, *, session_id: str | None,
turn_id: str | None,
utterance_id: str | None) -> str | None:
graph = globals().get("GRAPH")
if graph is None:
return None
links = ([("derived_from", utterance_id)] if utterance_id else [])
try:
return graph.record_node(
"runtime_receipt", receipt, actor="runtime",
session_id=session_id, turn_id=turn_id,
event_type="runtime.observed", links=links)
except Exception as exc:
print(f"runtime receipt journal unavailable: {exc}", flush=True)
return None
@staticmethod
def _voice_required_tool(text: str) -> str | None:
if VOICE_RUNTIME_INTENT.search(text):
return "list_voices"
if VOICE_ACTIVATION_INTENT.search(text):
return "set_voice"
return None
@staticmethod
def _canonical_chat_turn(turn: list[dict]) -> list[dict] | None:
return canonical_chat_turn(
turn, redacted_tool_receipt=REDACTED_TOOL_RECEIPT)
@staticmethod
def _echo_turn_signature(turn: list[dict]) -> str | None:
return echo_turn_signature(turn)
@classmethod
def _drop_repeated_echo_turns(cls, turns: list[list[dict]]) -> list[list[dict]]:
return drop_repeated_echo_turns(turns)
@classmethod
def _drop_repeated_echo_messages(cls, messages: list[dict]) -> list[dict]:
return drop_repeated_echo_messages(messages)
def _chat_messages(self, context_sections: list[str] | None = None) -> list[dict]:
return compile_chat_messages(
self.history,
base_prompt=str(self.history[0].get("content", DEFAULT_PROMPT)),
local_time=(datetime.now(ZoneInfo("Asia/Kolkata")).isoformat(
timespec="seconds") + " (Asia/Kolkata)."),
context_sections=context_sections or [],
history_turns=HISTORY_TURNS,
redacted_tool_receipt=REDACTED_TOOL_RECEIPT,
synthetic_fallbacks={
"I haven't executed that change.", ACTION_FALLBACK},
stale_capability_denial=STALE_CAPABILITY_DENIAL,
ungrounded_action_claim=UNGROUNDED_ACTION_CLAIM,
)
def _fast_chat_messages(self, *, display_mode: bool) -> list[dict]:
return compile_fast_chat_messages(
self.history,
system_prompt=fast_system_prompt(
owner_name=OWNER_NAME, display_mode=display_mode),
history_turns=FAST_HISTORY_TURNS,
context_chars=FAST_CONTEXT_CHARS,
redacted_tool_receipt=REDACTED_TOOL_RECEIPT,
)
@staticmethod
def _is_action_request(messages: list[dict]) -> bool:
return is_action_request(messages, ACTION_REQUEST)
@staticmethod
def _token_count_sync(messages: list[dict], use_tools: bool) -> int:
body = {
"model": LOCAL_MODEL,
"messages": messages,
"chat_template_kwargs": {"enable_thinking": False},
}
if use_tools:
body["tools"] = current_tool_schema()
headers = {"Content-Type": "application/json",
"Authorization": "Bearer " + KEY}
return count_prompt_tokens(
LLM_ENGINE, _tokenize_url(), body, headers, open_loopback_request)
async def _prompt_token_count(self, messages: list[dict],
use_tools: bool) -> int:
return await asyncio.to_thread(self._token_count_sync, messages, use_tools)
@staticmethod
def _latest_user_only(messages: list[dict]) -> list[dict]:
return latest_user_only(messages)
async def _fit_context(self, messages: list[dict],
use_tools: bool) -> list[dict]:
"""Keep the largest recent, valid user-turn suffix inside the model budget."""
try:
original_count = await self._prompt_token_count(messages, use_tools)
except Exception as exc:
# The generation endpoint remains usable if /tokenize is unavailable.
print(f"prompt token count unavailable: {exc}", flush=True)
return messages
if original_count <= PROMPT_TOKEN_BUDGET:
return messages
conversation = messages[1:]
starts = [index for index, message in enumerate(conversation)
if message.get("role") == "user"]
if not starts:
return [messages[0]]
# Token count is monotonic as older turns are removed. Binary search for
# the earliest user boundary that fits, preserving as much recent context
# as the current prompt and tool schema allow.
low, high = 0, len(starts) - 1
best = [messages[0], conversation[starts[-1]]]
best_count = await self._prompt_token_count(best, use_tools)
while low <= high:
middle = (low + high) // 2
candidate = [messages[0]] + conversation[starts[middle]:]
count = await self._prompt_token_count(candidate, use_tools)
if count <= PROMPT_TOKEN_BUDGET:
best, best_count = candidate, count
high = middle - 1
else:
low = middle + 1
print(f"context trimmed: {original_count} -> {best_count} tokens; "
f"kept {len(best) - 1} conversation messages", flush=True)
return best
# ---------- audio ----------
def speech_prob(self, x16: np.ndarray) -> float:
return float(self.vad(x16, SAMPLE_RATE))
def transcribe(self, x16: np.ndarray) -> str:
return self.asr.transcribe_samples(x16, SAMPLE_RATE)
def synth(self, text: str) -> np.ndarray:
lock = getattr(self, "_voice_lock", None)
if lock is None:
lock = self._voice_lock = threading.RLock()
with lock:
return self._synth_locked(text)
def _synth_locked(self, text: str) -> np.ndarray:
piper = getattr(self, "piper", None)
if piper is not None:
return piper.synthesize(text)
def _gen(**kwargs):
with inference_context():
return self.tts.generate(language="English", **kwargs)
attempts = []
if self.ref_audio:
attempts.append({"text": text, "voice_clone_prompt": self.clone_prompt})
attempts.append({"text": text, "instruct": self.instruct})
last_error: Exception | None = None
for attempt in attempts:
try:
out = _gen(**attempt)
a = out[0]
audio = a.cpu().numpy() if hasattr(a, "cpu") else np.asarray(a)
del a, out
_empty_cuda_cache()
return audio
except accelerator_oom_error() as e:
# The LLM server shares this GPU and can squeeze us mid-decode;
# dropping our cache usually buys the headroom back.
last_error = e
print("tts OOM, clearing cache and retrying:", e, flush=True)
_empty_cuda_cache()
except Exception as e:
last_error = e
print("synth failed:", e, flush=True)
raise RuntimeError(f"speech synthesis failed: {last_error}")
# ---------- llm ----------
async def _stream_once(self, msgs, speak_q, use_tools=True,
required_tool: str | None = None,
display_mode: bool = False,
context_is_bounded: bool = False,
max_tokens: int = MAX_OUTPUT_TOKENS,
temperature: float = 0.7,
top_p: float = 0.8,
response_max_words: int | None = None,
grounded_receipt: bool = False):
"""Stream one completion into speak_q. Returns (text, tool_calls)."""
if not context_is_bounded:
msgs = await self._fit_context(msgs, use_tools)
synthesis_tools = (current_tool_schema() if use_tools or any(
message.get("role") == "tool" for message in msgs) else None)
async def create_stream(messages, *, token_limit=max_tokens,
sampling_temperature=temperature):
tool_choice = "none" if not use_tools else None
if use_tools and required_tool:
tool_choice = {"type": "function",
"function": {"name": required_tool}}
return await self.llm.chat.completions.create(
model=LOCAL_MODEL,
messages=messages,
temperature=sampling_temperature, top_p=top_p,
max_tokens=token_limit,
stream=True,
tools=synthesis_tools,
tool_choice=tool_choice,
extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)
try:
stream = await create_stream(msgs)
except Exception as exc:
latest_only = self._latest_user_only(msgs)
if "maximum context length" in str(exc):
# Race-safe fallback if the serving template's count changes between
# tokenization and generation. Keep the system prompt and latest user.
msgs = latest_only
print("context overflow despite budgeting; retrying latest turn only",
flush=True)
stream = await create_stream(msgs)
elif (getattr(exc, "status_code", None) == 400
and latest_only != msgs):
# A legacy or provider-specific history entry may pass local
# validation but fail the serving chat template. The request was
# rejected before generation, so one context-free retry is safe.
msgs = latest_only
print("model rejected conversation context; retrying latest turn only",
flush=True)
stream = await create_stream(msgs)
else:
raise
async def collect(active_stream):
text = ""
calls: dict[int, dict] = {}
finish_reason = None
async for chunk in active_stream:
choice = chunk.choices[0]
if getattr(choice, "finish_reason", None) is not None:
finish_reason = choice.finish_reason
d = choice.delta
if d.tool_calls:
for tc in d.tool_calls:
slot = calls.setdefault(