-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgreenclaw.py
More file actions
1790 lines (1571 loc) · 67.5 KB
/
Copy pathgreenclaw.py
File metadata and controls
1790 lines (1571 loc) · 67.5 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
#!/usr/bin/env python3
"""Minimal Claude router.
Two front ends, one core:
python greenclaw.py terminal stdin loop
python greenclaw.py --tasks run always-on tasks from tasks/ (Telegram etc.)
Per-message channels:
<prompt> -> cloud model (default; escalates to CC when needed)
cc <prompt> -> Claude Code CLI (explicit)
/<trigger> ... -> a skill recipe from skills/
/watch -> show scheduled jobs and when they last ran
usage / calls -> CC invocation count today
/version -> show greenclaw version
/cheat -> built-in cheat sheet (prefixes, commands, skills)
Skills vs tasks vs schedules:
skills/*.md triggered recipes — what to do with a request
schedules/*.md timed jobs — when to run a skill automatically
tasks/*.py always-on connectors — how messages get in and out.
A task implements start(on_message) and calls
on_message(text, reply, chat_id) per incoming message, where
reply(text) sends the answer back on the same channel.
LAN / sole-user box. Secrets in .env (TELEGRAM_*).
Deps: pip install -r requirements.txt
"""
__version__ = "0.5.1"
import importlib.util
import json
import os
import shutil
import signal
import subprocess
import sys
import threading
import time
from datetime import datetime
import httpx
from shared import (
CC_LOG_FILE,
MEMORY_DIR,
MEMORY_SIZE_THRESHOLD,
NOTES_FILE,
SCHEDULE_STATE_FILE,
SCHEDULES_DIR,
TASKS_DIR,
parse_front_matter,
send_smtp,
)
# Cap run_shell output so a chatty command can't blow the local context or Telegram.
SHELL_MAX_OUTPUT = 6000 # chars
# Skills: markdown recipes loaded at boot (front matter only), bodies loaded on demand.
_HERE = os.path.dirname(os.path.abspath(__file__))
SKILLS_DIR = os.path.join(_HERE, "skills")
SKILLS_ALLOW = os.path.join(_HERE, "skills.allow")
INBOX_ACTIVE_FLAG = os.path.expanduser("~/.local/share/greenclaw/inbox_active")
MEMORY_COMPACTION_COOLDOWN = 86_400 # seconds (24h) between auto-compactions
MEMORY_COMPACTION_STATE = os.path.expanduser("~/.local/share/greenclaw/memory_compaction.json")
HEARTBEAT_FILE = os.path.expanduser("~/.local/share/greenclaw/heartbeat.jsonl")
SKILLS = {} # name -> {description, exposes, trigger, locked, source, path}; filled at boot
_trigger_map = {} # trigger (lowercase) -> skill name; filled by load_skills()
_memory_context = "" # loaded at boot, refreshed after every save
# Per-chat rolling history for converse_local. Persisted to disk across restarts.
# Keys are chat_id strings; values are lists of {role, content} dicts.
_history: dict = {}
_history_updated: dict = {} # key -> float; per-chat last-active timestamp
_history_lock = threading.Lock()
HISTORY_MAX_TURNS = 10 # pairs (user + assistant); older turns are dropped
HISTORY_FILE = os.path.expanduser("~/.local/share/greenclaw/history.json")
HISTORY_TTL_DAYS = 7 # discard entries older than this on load
OLLAMA_URL = "http://localhost:11434"
OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "qwen3:8b")
OLLAMA_IDLE_TIMEOUT = 600 # seconds before auto-shutdown after last use
CLOUD_SEMAPHORE = threading.Semaphore(3) # Ollama Cloud: 3 concurrent models
GC_CLOUD_MODEL = os.environ.get("GC_CLOUD_MODEL", "glm-5.2:cloud")
GC_CLOUD_FALLBACK = os.environ.get("GC_CLOUD_FALLBACK", "kimi-k2.7-code:cloud")
GC_CLOUD_FALLBACK_2 = os.environ.get("GC_CLOUD_FALLBACK_2", "kimi-k3:cloud")
CLOUD_CHAIN = [GC_CLOUD_MODEL, GC_CLOUD_FALLBACK, GC_CLOUD_FALLBACK_2]
CLOUD_MAX_STEPS = 8
GC_CC_MODEL = os.environ.get("GC_CC_MODEL", "claude-haiku-4-5-20251001")
# EMAIL_CC_KEYWORD read at call time in route() — .env loads after module-level constants
def _tz_stamp():
"""Local date/time with the real UTC offset — no hardcoded GMT+1."""
now = datetime.now()
off = time.localtime().tm_gmtoff
sign = "+" if off >= 0 else "-"
hh = abs(off) // 3600
return now.strftime("%Y-%m-%d %H:%M ") + f"UTC{sign}{hh:.0f}"
def load_history():
global _history, _history_updated
if not os.path.exists(HISTORY_FILE):
return
try:
with open(HISTORY_FILE) as f:
data = json.load(f)
cutoff = time.time() - HISTORY_TTL_DAYS * 86400
with _history_lock:
_history = {
k: v["messages"]
for k, v in data.items()
if v.get("updated", 0) >= cutoff
}
_history_updated = {
k: v.get("updated", 0)
for k, v in data.items()
if v.get("updated", 0) >= cutoff
}
print(f"[history] loaded {len(_history)} chat(s) from disk")
except Exception as e:
print(f"[history] failed to load: {e}")
def save_history(key):
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
# Hold the lock across the whole read+write so two concurrent saves can't
# interleave and have the older snapshot clobber the newer one on rename.
with _history_lock:
data = {
k: {"messages": v, "updated": _history_updated.get(k, 0)}
for k, v in _history.items()
}
tmp = HISTORY_FILE + ".tmp"
try:
with open(tmp, "w") as f:
json.dump(data, f)
os.replace(tmp, HISTORY_FILE)
except Exception as e:
print(f"[history] failed to save: {e}")
def _load_memory_from_disk():
"""Read all memory files from CC's memory dir and return a single context block."""
if not os.path.isdir(MEMORY_DIR):
return ""
parts = []
for fn in sorted(os.listdir(MEMORY_DIR)):
if fn == "MEMORY.md" or not fn.endswith(".md"):
continue
try:
with open(os.path.join(MEMORY_DIR, fn)) as f:
content = f.read().strip()
if content:
parts.append(content)
except Exception:
continue
return "\n\n".join(parts)
def reload_memory():
global _memory_context
_memory_context = _load_memory_from_disk()
print(f"[memory] loaded {len(_memory_context)} chars from {MEMORY_DIR}")
def _memory_total_size():
if not os.path.isdir(MEMORY_DIR):
return 0
total = 0
for fn in os.listdir(MEMORY_DIR):
if fn.endswith(".md"):
try:
total += os.path.getsize(os.path.join(MEMORY_DIR, fn))
except OSError:
pass
return total
def report_memory_stats():
if not os.path.isdir(MEMORY_DIR):
return "No memory directory found."
files = sorted(fn for fn in os.listdir(MEMORY_DIR) if fn.endswith(".md") and fn != "MEMORY.md")
total = _memory_total_size()
pct = int(total / MEMORY_SIZE_THRESHOLD * 100)
lines = [f"Memory: {len(files)} entries, {total:,} bytes ({pct}% of {MEMORY_SIZE_THRESHOLD//1000}KB compaction threshold)"]
for fn in files:
try:
size = os.path.getsize(os.path.join(MEMORY_DIR, fn))
lines.append(f" {fn[:-3]}: {size:,}b")
except OSError:
pass
return "\n".join(lines)
def _check_memory_threshold():
"""If memory is over the size threshold and hasn't been compacted recently, ask CC to compact."""
if _memory_total_size() < MEMORY_SIZE_THRESHOLD:
return
now = time.time()
try:
if os.path.exists(MEMORY_COMPACTION_STATE):
with open(MEMORY_COMPACTION_STATE) as f:
last = json.load(f).get("last_compacted", 0)
if now - last < MEMORY_COMPACTION_COOLDOWN:
return
except Exception:
pass
print(f"[memory] size threshold exceeded — requesting CC compaction")
result = ask_cc(
"Memory has grown large. Review all files in ~/.claude/projects/-home-mrgreen/memory/, "
"consolidate overlapping entries, summarise older content into fewer files, and remove "
"trivial or outdated facts. Preserve user preferences, recurring patterns, and active "
"project context. Update MEMORY.md accordingly."
)
if result.startswith("[error]"):
# Don't mark the cooldown on failure — retry on the next boot instead
# of silently sitting over threshold for a full cooldown period.
print(f"[memory] compaction failed, not marking cooldown: {result}")
notify_telegram(f"⚠️ memory compaction failed: {result}")
return
print("[memory] compaction finished")
os.makedirs(os.path.dirname(MEMORY_COMPACTION_STATE), exist_ok=True)
try:
with open(MEMORY_COMPACTION_STATE, "w") as f:
json.dump({"last_compacted": now}, f)
except Exception as e:
print(f"[memory] could not save compaction state: {e}")
reload_memory()
def _prune_file(path, keep):
"""Trim a line-delimited file to its last `keep` lines (atomic)."""
try:
with open(path) as f:
lines = f.readlines()
if len(lines) > keep:
tmp = path + ".tmp"
with open(tmp, "w") as f:
f.writelines(lines[-keep:])
os.replace(tmp, path)
except Exception as e: # noqa: BLE001
print(f"[prune] {path}: {e}")
def log_heartbeat():
os.makedirs(os.path.dirname(HEARTBEAT_FILE), exist_ok=True)
try:
rec = {"ts": datetime.now().isoformat(timespec="seconds"), "version": __version__}
with open(HEARTBEAT_FILE, "a") as f:
f.write(json.dumps(rec) + "\n")
except Exception as e:
print(f"[heartbeat] {e}")
_prune_file(HEARTBEAT_FILE, 1000)
def _build_system():
"""Build the cloud model system prompt from real runtime facts gathered once at startup."""
try:
raw = subprocess.check_output(
["grep", "PRETTY_NAME", "/etc/os-release"], text=True
).strip()
os_name = raw.split("=", 1)[-1].strip('"')
except Exception:
os_name = "Linux"
try:
result = subprocess.run(
["which", "pacman", "yay", "systemctl", "journalctl", "git", "python", "claude"],
capture_output=True, text=True,
)
tools = ", ".join(os.path.basename(t) for t in result.stdout.strip().splitlines() if t)
except Exception:
tools = "standard Linux tools"
return (
f"You are the first responder on the user's home server ({os_name}). "
"You are the first-responder cloud model: handle simple things yourself and be honest about your limits. "
"Use run_shell to inspect the box or run commands. "
"Delegate to Claude Code via delegate_to_cc WHENEVER a request needs reach you "
"don't have — email/Gmail, the web, GitHub, calendar, APIs, or any multi-step or "
"complex task. In particular, if the user asks about email, their inbox, messages, or "
"whether someone has written, replied or been in touch, call delegate_to_cc. "
"When you delegate, pass a complete, specific instruction that includes the user's "
"original request. Never invent things you can't actually access — delegate instead. "
"Be concise — lead with the answer. Confirm before anything destructive. "
f"Confirmed tools on this machine: {tools}. "
"Do not assume a tool is missing — verify with run_shell first. "
"Never refuse a task without attempting it. If a command fails, report the actual error. "
"The user is the sole owner of this machine — no need to ask for sudo confirmation. "
"For common sysadmin phrases, act immediately without asking for clarification. Examples:\n"
" 'update system' or 'update' -> run: sudo pacman -Syu --noconfirm\n"
" 'disk space' or 'storage' -> run: df -h\n"
" 'memory' or 'ram' -> run: free -h\n"
" 'what's running' or 'processes' -> run: ps aux or systemctl list-units --state=running\n"
" 'uptime' -> run: uptime\n"
" 'logs' -> run: journalctl -n 50 --no-pager\n"
" 'reboot' or 'restart' -> run: sudo reboot (confirm first)\n"
"If a request is ambiguous but has an obvious sysadmin interpretation, use it."
)
SYSTEM = _build_system()
TOOLS = [
{
"name": "run_shell",
"description": (
"Run a shell command on the server and return stdout, stderr, and exit "
"code. Use for inspecting the system, reading files, and running tasks."
),
"input_schema": {
"type": "object",
"properties": {
"command": {"type": "string", "description": "The shell command to run."}
},
"required": ["command"],
},
},
{
"name": "add_note",
"description": (
"Append a timestamped note to the user's notes file. Use this for any "
"'remember', 'note', 'jot' request — never shell out to echo for this."
),
"input_schema": {
"type": "object",
"properties": {
"text": {"type": "string", "description": "The note text to append verbatim."}
},
"required": ["text"],
},
},
{
"name": "list_notes",
"description": "Return the most recent saved notes from the notes file.",
"input_schema": {
"type": "object",
"properties": {
"limit": {"type": "integer", "description": "Max number of recent lines to return (default 40).", "default": 40}
},
},
},
{
"name": "save_memory",
"description": (
"Save something to long-term memory so it persists across sessions. "
"Use when the user says 'remember', or when you learn something important "
"about the user, their preferences, or their system that should persist."
),
"input_schema": {
"type": "object",
"properties": {
"fact": {"type": "string", "description": "What to remember. Be specific and include context."}
},
"required": ["fact"],
},
},
{
"name": "send_email",
"description": (
"Send an email to the user (the first address in EMAIL_TRUSTED_SENDERS). "
"Optionally attach a local file. Use for sharing files, images, or any "
"content better delivered by email than chat."
),
"input_schema": {
"type": "object",
"properties": {
"subject": {"type": "string", "description": "Email subject line."},
"body": {"type": "string", "description": "Plain-text email body."},
"attachment_path": {"type": "string", "description": "Absolute or ~-relative path to a file to attach. Omit if no attachment needed."},
},
"required": ["subject", "body"],
},
},
]
def load_env(path=".env"):
if not os.path.exists(path):
return
with open(path) as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
os.environ.setdefault(k.strip(), v.strip().strip('"').strip("'"))
# Warn if the secrets file is readable beyond the owner.
try:
if os.stat(path).st_mode & 0o077:
print(f"[env] warning: {path} is group/world-readable (chmod 600 recommended)")
except OSError:
pass
def _truncate(text, limit=SHELL_MAX_OUTPUT):
"""Keep head and tail when output is too long; the exit line lives in the tail."""
if len(text) <= limit:
return text
half = limit // 2
omitted = len(text) - limit
return f"{text[:half]}\n... [truncated {omitted} chars] ...\n{text[-half:]}"
def run_shell(command):
try:
p = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=60)
out = p.stdout
if p.stderr:
out += "\n[stderr]\n" + p.stderr
out += f"\n[exit {p.returncode}]"
return _truncate(out.strip())
except subprocess.TimeoutExpired:
return "[error] command timed out (60s)"
except Exception as e: # noqa: BLE001
return f"[error] {e}"
def add_note(text):
text = (text or "").strip()
if not text:
return "[error] empty note"
line = f"- [{datetime.now().strftime('%Y-%m-%d %H:%M')}] {text}\n"
try:
with open(NOTES_FILE, "a") as f:
f.write(line)
return f"noted: {text}"
except Exception as e: # noqa: BLE001
return f"[error] could not write note: {e}"
def list_notes(limit=40):
try:
with open(NOTES_FILE) as f:
lines = f.readlines()
except FileNotFoundError:
return "(no notes yet)"
except Exception as e: # noqa: BLE001
return f"[error] could not read notes: {e}"
if not lines:
return "(no notes yet)"
try:
n = max(1, int(limit))
except (TypeError, ValueError):
n = 40
return "".join(lines[-n:]).rstrip()
def save_memory(fact):
"""Write a memory note. Prefers the greenbrain vault (skills/vault) if
present; otherwise appends to the notes file so the command still works
out-of-tree — skills/ is gitignored and owner-provided, so the vault
module is not guaranteed to exist on a fresh clone."""
if ":" in fact[:40]:
topic, content = fact.split(":", 1)
else:
topic, content = "notes", fact
topic, content = topic.strip(), content.strip()
try:
from skills.vault import write_note
return write_note(topic, content)
except ImportError:
# No vault module shipped — degrade to a timestamped note.
return add_note(f"[memory:{topic}] {content}")
except Exception as e: # noqa: BLE001
return f"[memory] {e}"
def get_daily_cc_calls():
if not os.path.exists(CC_LOG_FILE):
return 0
today = datetime.now().strftime("%Y-%m-%d")
count = 0
with open(CC_LOG_FILE) as f:
for line in f:
try:
r = json.loads(line)
if r.get("ts", "").startswith(today):
count += 1
except Exception: # noqa: BLE001
continue
return count
def _prune_cc_log(max_days=14):
"""Drop CC call log entries older than max_days (atomic). Low volume, so
a full read/rewrite per call is fine."""
try:
if not os.path.exists(CC_LOG_FILE):
return
with open(CC_LOG_FILE) as f:
lines = f.readlines()
cutoff = time.time() - max_days * 86400
kept = []
for line in lines:
try:
if datetime.fromisoformat(json.loads(line).get("ts", "")).timestamp() >= cutoff:
kept.append(line)
except Exception: # noqa: BLE001
kept.append(line) # keep unparseable lines rather than lose them
if len(kept) < len(lines):
tmp = CC_LOG_FILE + ".tmp"
with open(tmp, "w") as f:
f.writelines(kept)
os.replace(tmp, CC_LOG_FILE)
except Exception as e: # noqa: BLE001
print(f"[cc log prune error] {e}")
def log_cc_call(prompt_preview):
try:
rec = {
"ts": datetime.now().isoformat(timespec="seconds"),
"prompt": prompt_preview[:120],
}
with open(CC_LOG_FILE, "a") as f:
f.write(json.dumps(rec) + "\n")
except Exception as e: # noqa: BLE001
print(f"[cc log error] {e}")
_prune_cc_log()
def report_usage():
return f"Claude Code calls today: {get_daily_cc_calls()}"
def report_version():
return f"greenclaw {__version__}"
def report_model():
lines = [f"cloud primary: {GC_CLOUD_MODEL}"]
for i, m in enumerate(CLOUD_CHAIN[1:], 1):
lines.append(f"fallback {i}: {m}")
return "\n".join(lines)
STATIC_DIR = os.path.join(_HERE, "static")
CHEAT_FILE = os.path.join(STATIC_DIR, "cheat.md")
def report_cheat():
"""Built-in cheat sheet — no LLM. Static text from cheat.md with {skills}
placeholder substituted from the live SKILLS dict."""
try:
with open(CHEAT_FILE) as f:
template = f.read()
except Exception as e: # noqa: BLE001
return f"[error] could not read cheat.md: {e}"
if SKILLS:
width = max(len(s["trigger"] or s["name"]) for s in SKILLS.values())
rows = []
for s in sorted(SKILLS.values(), key=lambda x: x["trigger"] or x["name"]):
key = s["trigger"] or f"({s['name']})"
rows.append(f" {key:<{width}} {s['description']}")
skills_block = "\n".join(rows)
else:
skills_block = " (none loaded)"
return template.replace("{skills}", skills_block).rstrip()
CC_BIN = shutil.which("claude") or os.path.expanduser("~/.local/bin/claude")
_ollama_proc = None
_ollama_timer = None
_ollama_lock = threading.Lock()
def _shutdown_ollama():
global _ollama_proc, _ollama_timer
with _ollama_lock:
if _ollama_proc and _ollama_proc.poll() is None:
_ollama_proc.terminate()
print("[ollama] shut down after idle timeout")
_ollama_proc = None
_ollama_timer = None
def _ensure_ollama():
"""Start ollama serve if not running; reset the idle shutdown timer."""
global _ollama_proc, _ollama_timer
with _ollama_lock:
# Cancel any pending shutdown
if _ollama_timer:
_ollama_timer.cancel()
_ollama_timer = None
# Check if already reachable (may have been started externally)
try:
httpx.get(f"{OLLAMA_URL}/api/tags", timeout=2)
running = True
except Exception:
running = False
if not running:
print("[ollama] starting on-demand…")
_ollama_proc = subprocess.Popen(
["ollama", "serve"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
# Wait up to 15s for it to become ready
for _ in range(15):
time.sleep(1)
try:
httpx.get(f"{OLLAMA_URL}/api/tags", timeout=1)
break
except Exception:
pass
else:
raise RuntimeError("ollama failed to start")
print("[ollama] ready")
# Schedule shutdown after idle timeout
_ollama_timer = threading.Timer(OLLAMA_IDLE_TIMEOUT, _shutdown_ollama)
_ollama_timer.daemon = True
_ollama_timer.start()
class CloudCallError(Exception):
"""Hard failure from a cloud model call (transport or non-2xx)."""
def __init__(self, reason, status=None):
super().__init__(f"{reason}:{status}")
self.reason = reason
self.status = status
# Set by _cloud_tool_loop when a side-effecting tool (run_shell,
# send_email, delegate_to_cc, ...) already ran this attempt before the
# failure — see converse_cloud, which uses this to avoid retrying the
# whole request on the next chain model (that would risk re-running
# the same tool call).
self.tool_calls_executed = False
_RETRYABLE_STATUS = {429, 502, 503} # rate-limited / temporarily unavailable
def call_cloud_model(model, messages, tools):
"""One Ollama /api/chat call to a cloud model. Returns (content, tool_calls).
tool_calls are normalized to [{"name": str, "arguments": dict}].
Raises CloudCallError("http", status) on non-2xx, CloudCallError("transport")
on connection/timeout/EOF. A 2xx reply with no content and no tool calls is
a valid empty reply, not an error. num_ctx is raised to mitigate the known
cloud tool-call parsing/truncation issue on large contexts.
A 429/502/503 gets one retry (2s backoff) on the same model before this
raises — cheaper than falling through to the next model in the chain for
what's usually a transient blip.
"""
payload = {
"model": model,
"messages": messages,
"tools": tools,
"stream": False,
"options": {"num_ctx": 40960},
}
for attempt in range(2):
try:
with CLOUD_SEMAPHORE:
r = httpx.post(f"{OLLAMA_URL}/api/chat", json=payload, timeout=120)
except Exception as e: # noqa: BLE001
raise CloudCallError("transport", None) from e
if attempt == 0 and r.status_code in _RETRYABLE_STATUS:
time.sleep(2)
continue
break
if r.status_code < 200 or r.status_code >= 300:
raise CloudCallError("http", r.status_code)
try:
msg = r.json().get("message", {})
except Exception as e: # noqa: BLE001
raise CloudCallError("transport", None) from e
content = (msg.get("content") or "").strip()
raw_calls = msg.get("tool_calls") or []
tool_calls = []
for tc in raw_calls:
if not isinstance(tc, dict):
continue # malformed tool-call entry from the model — skip, don't crash
fn = tc.get("function") or tc
if not isinstance(fn, dict):
continue
tool_calls.append({"name": fn.get("name", ""), "arguments": fn.get("arguments") or {}})
return content, tool_calls
def _cloud_tools(allow_shell=True):
"""Build Ollama-format tool definitions from TOOLS plus delegate_to_cc.
When allow_shell is False (the email path, where message bodies are
untrusted remote input), run_shell is withheld. delegate_to_cc is ALSO
withheld here: it routes to ask_cc() with --dangerously-skip-permissions,
i.e. full shell access — the same capability run_shell grants, just one
hop removed. The email From: header is not a real trust boundary (no
SPF/DKIM check), so a forged sender + prompt injection in the body could
otherwise reach delegate_to_cc and get full shell/sudo despite run_shell
being withheld. If email-initiated CC delegation is wanted later, it needs
its own narrower tool, not this one.
"""
tools = [t for t in TOOLS if not (t["name"] == "run_shell" and not allow_shell)]
out = [
{"type": "function",
"function": {"name": t["name"], "description": t["description"], "parameters": t["input_schema"]}}
for t in tools
]
if allow_shell:
out.append({
"type": "function",
"function": {
"name": "delegate_to_cc",
"description": (
"Delegate to Claude Code when you cannot handle a task yourself — "
"e.g. checking email/Gmail, searching the web, or anything requiring "
"external access you don't have. Returns Claude Code's reply."
),
"parameters": {
"type": "object",
"properties": {"query": {"type": "string", "description": "The task or question to send to Claude Code."}},
"required": ["query"],
},
},
})
return out
def _cloud_tool_loop(model, messages, tools):
"""Run the tool-calling loop for one model. Returns the final reply text.
Works on a copy of `messages` so a mid-loop failure leaves the caller's
transcript clean for a retry on the next chain model. Raises CloudCallError
on any hard failure from call_cloud_model. Bounded by CLOUD_MAX_STEPS.
If a CloudCallError happens AFTER at least one tool was already dispatched
(e.g. run_shell/send_email already ran, then the follow-up model call
fails), the error is tagged `.tool_calls_executed = True` so the caller
knows retrying on the next chain model would risk re-running the same
side-effecting tool call rather than just re-asking the same question.
"""
msgs = list(messages)
text_parts = []
any_tool_dispatched = False
for _ in range(CLOUD_MAX_STEPS):
try:
content, tool_calls = call_cloud_model(model, msgs, tools)
except CloudCallError as e:
e.tool_calls_executed = any_tool_dispatched
raise
if content:
text_parts.append(content)
if not tool_calls:
break
msgs.append({"role": "assistant", "content": content or "", "tool_calls": tool_calls})
for tc in tool_calls:
name = tc.get("name", "")
args = tc.get("arguments") or {}
preview = args.get("command") or args.get("query") or args.get("text") or ""
print(f" [c:{name}] {preview[:120]}")
result = dispatch_tool(name, args)
any_tool_dispatched = True
msgs.append({"role": "tool", "name": name, "content": str(result)})
return "\n".join(p for p in text_parts if p.strip()) or "(no reply)"
HERMES_BIN = os.path.expanduser("~/.local/bin/hermes")
def converse_hermes(text, system_extra=None, chat_id=None, allow_shell=True):
"""Delegate to Hermes Agent on localhost. Replaces converse_cloud as the
primary cloud path. Hermes does the tool loop, skills, memory, and
fallback chain. Falls back to converse_cloud if Hermes is unavailable.
system_extra: optional skill body prepended to the prompt.
chat_id: passed through for logging (Hermes manages its own history).
allow_shell: when False, Hermes is asked to withhold shell access (email
path — untrusted remote input).
"""
prompt = text
if system_extra:
prompt = f"{system_extra}\n\n--- user request ---\n{text}"
if not allow_shell:
prompt = f"[RESTRICTED: no shell commands]\n{prompt}"
try:
result = subprocess.run(
[HERMES_BIN, "chat", "-q", prompt, "-Q"],
capture_output=True, text=True, timeout=120,
env={k: v for k, v in os.environ.items() if k != "ANTHROPIC_API_KEY"},
)
out = (result.stdout or "").strip()
if not out or result.returncode != 0:
err = (result.stderr or "").strip()
print(f"[hermes] no response (rc={result.returncode}): {err[:200]}")
return converse_cloud(text, system_extra=system_extra, chat_id=chat_id, allow_shell=allow_shell)
return out
except subprocess.TimeoutExpired:
print("[hermes] timed out (120s) — falling back to converse_cloud")
return converse_cloud(text, system_extra=system_extra, chat_id=chat_id, allow_shell=allow_shell)
except FileNotFoundError:
print("[hermes] binary not found — falling back to converse_cloud")
return converse_cloud(text, system_extra=system_extra, chat_id=chat_id, allow_shell=allow_shell)
except Exception as e:
print(f"[hermes] error: {e} — falling back to converse_cloud")
return converse_cloud(text, system_extra=system_extra, chat_id=chat_id, allow_shell=allow_shell)
def converse_cloud(text, system_extra=None, chat_id=None, allow_shell=True):
"""Route to the cloud tier (Ollama :cloud models) with a tool-calling loop,
a two-model fallback chain, Telegram notify-on-fallback, and CC escalation
on exhaustion.
system_extra: optional skill body appended to SYSTEM for this run only.
chat_id: if provided, rolling history is loaded before and saved after.
allow_shell: when False, run_shell is withheld from the tool set (email path
— untrusted remote input). delegate_to_cc stays.
"""
try:
_ensure_ollama()
except Exception as e: # noqa: BLE001
return f"[cloud] could not start ollama: {e}"
mem_block = f"\n\n--- long-term memory ---\n{_memory_context}" if _memory_context else ""
system = SYSTEM + mem_block
if system_extra:
system = f"{system}\n\n--- skill ---\n{system_extra}"
with _history_lock:
stored = list(_history.get(str(chat_id), [])) if chat_id is not None else []
messages = [{"role": "system", "content": system}]
messages += [{"role": m["role"], "content": m["content"]} for m in stored]
messages.append({"role": "user", "content": f"[{_tz_stamp()}]\n{text}"})
tools = _cloud_tools(allow_shell)
for idx, model in enumerate(CLOUD_CHAIN):
try:
reply = _cloud_tool_loop(model, messages, tools)
except CloudCallError as e:
print(f"[cloud] {model} failed: {e.reason} ({e.status})")
if e.tool_calls_executed:
# A side-effecting tool (run_shell/send_email/delegate_to_cc)
# already ran this attempt. Retrying on the next chain model
# would replay the same request and risk re-running it — stop
# the chain here instead and escalate.
print(f"[cloud] {model} failed after executing a tool call — "
"not retrying on the next chain model to avoid a duplicate side effect")
break
if idx < len(CLOUD_CHAIN) - 1:
continue
break
# Success — a fallback model served (idx > 0): announce the fallback.
if idx > 0:
notify_telegram(f"cloud fallback: {CLOUD_CHAIN[idx - 1]} failed → {model}")
# Save history and return.
if chat_id is not None:
key = str(chat_id)
with _history_lock:
existing = _history.get(key, [])
merged = existing + [
{"role": "user", "content": text},
{"role": "assistant", "content": reply},
]
_history[key] = merged[-(HISTORY_MAX_TURNS * 2):]
_history_updated[key] = time.time()
save_history(key)
return reply
# Chain exhausted — urgent notify + auto-escalate to Claude Code.
notify_telegram(f"cloud tier exhausted: {' → '.join(CLOUD_CHAIN)}")
return ask_cc(text, chat_id=chat_id)
def ask_cc(prompt, chat_id=None):
"""Hand the whole job to Claude Code headless, full autonomy."""
if not os.path.exists(CC_BIN):
return "[error] claude CLI not found"
original_prompt = prompt
now = _tz_stamp()
mem_block = f"\n\n--- long-term memory ---\n{_memory_context}" if _memory_context else ""
hist_block = ""
if chat_id is not None:
with _history_lock:
history = list(_history.get(str(chat_id), []))
if history:
lines = []
for msg in history:
role = "Kev" if msg["role"] == "user" else "GreenClaw"
lines.append(f"{role}: {msg['content']}")
hist_block = "\n\n--- recent conversation ---\n" + "\n".join(lines)
prompt = f"[Current date/time: {now}]{mem_block}{hist_block}\n\n{prompt}"
log_cc_call(original_prompt) # log the user's actual request, not the augmented prompt
print(" [-> Claude Code]")
try:
cc_env = {k: v for k, v in os.environ.items() if k != "ANTHROPIC_API_KEY"}
# Own session so a timeout can kill the whole process group — CC spawns
# its own sub-agents/tool calls, and killing only the direct child
# (subprocess.run's default on TimeoutExpired) orphans the rest.
p = subprocess.Popen(
[CC_BIN, "-p", prompt, "--model", GC_CC_MODEL, "--dangerously-skip-permissions"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
env=cc_env, start_new_session=True,
)
try:
out, err = p.communicate(timeout=900)
except subprocess.TimeoutExpired:
os.killpg(p.pid, signal.SIGKILL)
p.communicate() # reap
return "[error] Claude Code timed out (15m)"
out = (out or "").strip()
err = (err or "").strip()
if err:
out += ("\n[stderr] " + err) if out else ("[stderr] " + err)
out = out or "(no output)"
if chat_id is not None:
key = str(chat_id)
with _history_lock:
existing = _history.get(key, [])
merged = existing + [
{"role": "user", "content": original_prompt},
{"role": "assistant", "content": out},
]
_history[key] = merged[-(HISTORY_MAX_TURNS * 2):]
_history_updated[key] = time.time()
save_history(key)
return out
except Exception as e: # noqa: BLE001
return f"[error] {e}"
def dispatch_tool(name, inp):
if name == "run_shell":
return run_shell(inp.get("command", ""))
if name == "add_note":
return add_note(inp.get("text", ""))
if name == "list_notes":
return list_notes(inp.get("limit", 40))
if name == "delegate_to_cc":
return ask_cc(inp.get("query", ""))
if name == "save_memory":
return save_memory(inp.get("fact", ""))
if name == "send_email":
err = send_email(inp.get("subject", ""), inp.get("body", ""), inp.get("attachment_path"))
return err or "email sent"
return f"[error] unknown tool {name}"
def load_skills():
"""Index skills/*.md at boot — front matter only, never the body. Applies the
skills.allow lock to locked skills and logs what loaded / was blocked."""
SKILLS.clear()
_trigger_map.clear()
if not os.path.isdir(SKILLS_DIR):
print("[skills] no skills/ directory — none loaded")
return
allow = set()
if os.path.exists(SKILLS_ALLOW):
with open(SKILLS_ALLOW) as f:
for line in f:
line = line.strip()
if line and not line.startswith("#"):
allow.add(line)
loaded, blocked = [], []
triggers_seen = {} # trigger -> first skill name that claimed it
for fn in sorted(os.listdir(SKILLS_DIR)):
if not fn.endswith(".md"):
continue
path = os.path.join(SKILLS_DIR, fn)
with open(path) as f:
head = f.read() # body is discarded here; loaded on demand by run_skill
meta, _ = parse_front_matter(head)
name = meta.get("name") or fn[:-3]
locked = meta.get("locked", "false").lower() == "true"
if locked and name not in allow:
blocked.append(name)
continue
trigger = meta.get("trigger", "")
if trigger and trigger in triggers_seen:
print(f"[skills] WARNING: {name} declares trigger {trigger!r} already used by {triggers_seen[trigger]} — ignoring trigger on {name}")
trigger = ""
elif trigger:
triggers_seen[trigger] = name
_trigger_map[trigger.lower()] = name
SKILLS[name] = {
"name": name,
"description": meta.get("description", ""),
"exposes": meta.get("exposes", "cc").lower(),
"trigger": trigger,
"locked": locked,
"source": meta.get("source", "unknown"),
"path": path,
}
loaded.append(f"{name}({SKILLS[name]['source']})")
if not trigger:
print(f"[skills] {name}: no trigger — not reachable until model-selection (v2)")
if loaded:
print(f"[skills] loaded {len(loaded)}: {', '.join(loaded)}")
if blocked:
print(f"[skills] blocked {len(blocked)} (locked, not in skills.allow): {', '.join(blocked)}")
# Load Qwen-native Python skills from skills/*.py