Repository navigation
Expand file tree
/
Copy pathinstall.py
More file actions
349 lines (299 loc) · 13.3 KB
/
Copy pathinstall.py
File metadata and controls
349 lines (299 loc) · 13.3 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
#!/usr/bin/env python3
"""install.py -- install the long-session handoff guard into Hermes Agent.
python install.py install (skill + plugin + config entry)
python install.py --dry-run print every change, write nothing
python install.py --uninstall remove exactly what this added
python install.py --check report what is installed and whether it works
What it installs:
<hermes home>/skills/productivity/long-session-handoff/ the procedure + 3 scripts
<hermes home>/plugins/session-weight-watch/ the detector (one hook)
config.yaml: plugins.enabled += session-weight-watch opt-in, via `hermes config set`
Nothing else is touched. config.yaml is edited through Hermes' own
`hermes config set` when the launcher is available -- a stray indent in that file
breaks the live gateway, so this never hand-writes YAML unless it has to, and
when it has to it backs the file up first.
Hermes' compression settings are NOT modified. The guard hands a session off
before the limit is reached; it does not change what happens when the limit is
reached.
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
SKILL_NAME = "long-session-handoff"
SKILL_CATEGORY = "productivity"
PLUGIN_NAME = "session-weight-watch"
GREEN, YELLOW, RED, DIM, RESET = (
"\x1b[32m", "\x1b[33m", "\x1b[31m", "\x1b[2m", "\x1b[0m")
MIN_PY = (3, 8)
def say(msg="", colour=""):
if colour and not sys.stdout.isatty():
colour = ""
sys.stdout.write((colour + msg + RESET if colour else msg) + "\n")
def hermes_home(profile=None):
env = os.environ.get("HERMES_HOME", "").strip()
if env:
base = Path(env)
elif sys.platform == "win32":
local = os.environ.get("LOCALAPPDATA", "").strip()
base = (Path(local) if local else Path.home() / "AppData" / "Local") / "hermes"
else:
base = Path.home() / ".hermes"
return base / "profiles" / profile if profile else base
def hermes_launcher():
"""Path to the `hermes` launcher, or "" when it is not on PATH."""
return shutil.which("hermes") or ""
def run_hermes(args, timeout=120):
exe = hermes_launcher()
if not exe:
return None
try:
proc = subprocess.run([exe] + list(args), capture_output=True, text=True,
encoding="utf-8", errors="replace", timeout=timeout,
stdin=subprocess.DEVNULL)
return proc
except (OSError, subprocess.SubprocessError):
return None
# ------------------------------------------------------------------ preflight
def preflight(home, dry):
"""Refuse to install where it cannot work. A half-installed hook is worse
than none: it would fire and fail silently on every turn."""
problems = []
notes = []
if sys.version_info < MIN_PY:
problems.append("this Python is %d.%d; %d.%d+ is required"
% (sys.version_info[0], sys.version_info[1], MIN_PY[0], MIN_PY[1]))
if not home.exists():
problems.append(
"no Hermes home at %s. Run `hermes setup` first, or set HERMES_HOME "
"if your install lives elsewhere." % home)
else:
if not (home / "state.db").exists():
notes.append("no state.db yet at %s -- the watcher stays idle until "
"Hermes has run at least once." % home)
for sub in ("skills", "plugins"):
target = home / sub
probe = target if target.exists() else home
if not dry and not os.access(probe, os.W_OK):
problems.append("no write access to %s" % probe)
if not hermes_launcher():
notes.append(
"`hermes` is not on PATH. The skill and plugin still install, but "
"config.yaml has to be edited directly (backed up first), and "
"handoff.py will need `hermes` on PATH to create a continuation.")
for src in (HERE / "skill" / SKILL_NAME, HERE / "plugin" / PLUGIN_NAME):
if not src.exists():
problems.append("missing from this checkout: %s" % src)
for note in notes:
say("note: " + note, YELLOW)
if problems:
say("Cannot install:", RED)
for problem in problems:
say(" - " + problem)
raise SystemExit(2)
# -------------------------------------------------------------------- payload
def copy_tree(src, dst, dry):
if dry:
say(" would %s %s" % ("replace" if dst.exists() else "create", dst))
return
dst.parent.mkdir(parents=True, exist_ok=True)
if dst.exists():
shutil.rmtree(dst)
shutil.copytree(src, dst, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
say(" installed %s" % dst)
def enabled_list(home, use_launcher=True):
"""plugins.enabled from config.yaml, read via Hermes when possible.
``use_launcher=False`` forces the file parser. That matters for --dry-run:
invoking `hermes config get` against a fresh HERMES_HOME makes Hermes
scaffold its whole home directory, which a dry run must never do (caught by
tests/test_compat.py, which asserted the temp dir stayed empty and found
eleven new directories in it).
"""
if use_launcher:
proc = run_hermes(["config", "get", "plugins.enabled"])
if proc is not None and proc.returncode == 0:
names = []
for line in (proc.stdout or "").splitlines():
line = line.strip()
if line.startswith("- "):
names.append(line[2:].strip().strip("'\""))
elif line and line not in ("null", "[]", "None"):
names.append(line.strip("[]").strip().strip("'\""))
return [n for n in names if n], "hermes config get"
# Fallback: parse the file just enough to find the list.
path = home / "config.yaml"
if not path.exists():
return [], "no config.yaml"
names, inside = [], False
try:
for raw in path.read_text(encoding="utf-8").splitlines():
stripped = raw.strip()
if stripped.startswith("enabled:") and inside:
continue
if stripped == "plugins:":
inside = True
continue
if inside:
if stripped.startswith("- "):
names.append(stripped[2:].strip().strip("'\""))
elif stripped and not raw.startswith((" ", "\t")):
break
except OSError:
return [], "config.yaml unreadable"
return names, "config.yaml"
def set_enabled(home, names, dry):
payload = json.dumps(sorted(set(names)))
if dry:
say(" would set plugins.enabled = %s" % payload)
return True
proc = run_hermes(["config", "set", "plugins.enabled", payload])
if proc is not None and proc.returncode == 0:
say(" plugins.enabled = %s" % payload)
return True
# No launcher: edit the file, but back it up first. `hermes config set`
# rewrites config.yaml from its own loaded model and drops commented-out
# example blocks, so the direct edit below is deliberately surgical.
path = home / "config.yaml"
backup = None
try:
text = path.read_text(encoding="utf-8") if path.exists() else ""
backup = path.with_suffix(".yaml.bak-%s" % time.strftime("%Y%m%d-%H%M%S"))
if text:
path.write_text(text, encoding="utf-8") # touch check
shutil.copy2(path, backup)
block = "plugins:\n enabled:\n" + "".join(
" - %s\n" % n for n in sorted(set(names)))
if "plugins:" in text:
say(" config.yaml already has a `plugins:` block and `hermes` is not "
"on PATH -- refusing to rewrite YAML blind.", YELLOW)
say(" add this line under plugins.enabled yourself:", DIM)
say(" - %s" % PLUGIN_NAME)
return False
path.write_text((text.rstrip("\n") + "\n\n" if text else "") + block,
encoding="utf-8")
say(" appended a plugins block to config.yaml"
+ (" (backup: %s)" % backup.name if backup else ""))
return True
except OSError as exc:
say(" could not update config.yaml: %s" % exc, RED)
return False
# ----------------------------------------------------------------- operations
def install(args):
home = hermes_home(args.profile)
say("%s into %s" % ("DRY RUN -- nothing will be written" if args.dry_run
else "Installing", home), DIM)
preflight(home, args.dry_run)
skill_dst = home / "skills" / SKILL_CATEGORY / SKILL_NAME
plugin_dst = home / "plugins" / PLUGIN_NAME
copy_tree(HERE / "skill" / SKILL_NAME, skill_dst, args.dry_run)
copy_tree(HERE / "plugin" / PLUGIN_NAME, plugin_dst, args.dry_run)
names, source = enabled_list(home, use_launcher=not args.dry_run)
if PLUGIN_NAME in names:
say(" plugins.enabled already lists %s (%s)" % (PLUGIN_NAME, source))
ok = True
else:
ok = set_enabled(home, names + [PLUGIN_NAME], args.dry_run)
if args.dry_run:
say()
say("dry run complete -- nothing changed.", GREEN)
return 0
say()
say("done.", GREEN)
say("Next:")
say(" 1. RESTART Hermes (the desktop app, and `hermes gateway restart` if you")
say(" run the gateway). Plugins are discovered once per process, so the")
say(" watcher is NOT active in any chat that is already open.")
say(" 2. Check what it measures:")
say(" python \"%s\"" % (skill_dst / "scripts" / "session_weight.py"))
if not ok:
say()
say(" plugins.enabled was NOT updated -- the plugin is installed but "
"will be ignored until you add it.", YELLOW)
return 0
def uninstall(args):
home = hermes_home(args.profile)
say("%sRemoving from %s" % ("DRY RUN -- " if args.dry_run else "", home), DIM)
targets = [home / "skills" / SKILL_CATEGORY / SKILL_NAME,
home / "plugins" / PLUGIN_NAME]
for target in targets:
if not target.exists():
continue
if args.dry_run:
say(" would delete %s" % target)
continue
shutil.rmtree(target)
say(" deleted %s" % target)
state = home / "runtime" / "session-weight-watch.json"
if state.exists():
if args.dry_run:
say(" would delete %s" % state)
else:
state.unlink()
say(" deleted %s" % state.name)
names, _ = enabled_list(home)
if PLUGIN_NAME in names:
set_enabled(home, [n for n in names if n != PLUGIN_NAME], args.dry_run)
else:
say(" plugins.enabled does not list %s" % PLUGIN_NAME)
keep = home / "handoffs"
if keep.exists():
say()
say(" LEFT IN PLACE: %s" % keep, YELLOW)
say(" Those are your session exports and the chain log -- your data, not "
"the tool's. Delete them yourself if you want them gone.", DIM)
if not args.dry_run:
say()
say("done. Restart Hermes.", GREEN)
return 0
def check(args):
home = hermes_home(args.profile)
skill_dst = home / "skills" / SKILL_CATEGORY / SKILL_NAME
plugin_dst = home / "plugins" / PLUGIN_NAME
say("Hermes home %s" % home)
say("state.db %s" % ("present" if (home / "state.db").exists() else "MISSING"))
say("skill %s" % ("installed" if skill_dst.exists() else "not installed"))
say("plugin %s" % ("installed" if plugin_dst.exists() else "not installed"))
names, source = enabled_list(home)
say("enabled %s (%s)" % ("yes" if PLUGIN_NAME in names else "NO", source))
say("launcher %s" % (hermes_launcher() or "not on PATH"))
script = skill_dst / "scripts" / "session_weight.py"
if script.exists():
say()
say("Running the scorer against your newest session:", DIM)
proc = subprocess.run([sys.executable, str(script)], capture_output=True,
text=True, encoding="utf-8", errors="replace",
timeout=120, stdin=subprocess.DEVNULL)
for line in (proc.stdout or "").splitlines():
say(" " + line)
if proc.returncode != 0:
# A missing or empty store is a state to report, not an installation
# failure: a fresh Hermes home has no sessions to measure yet.
if not (home / "state.db").exists():
say(" (nothing to measure yet -- run Hermes once.)", DIM)
return 0
say((proc.stderr or "")[-800:], RED)
return 1
return 0
def main(argv=None):
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
ap = argparse.ArgumentParser(prog="install.py",
description=__doc__.splitlines()[0])
ap.add_argument("--dry-run", "-n", action="store_true")
ap.add_argument("--uninstall", action="store_true")
ap.add_argument("--check", action="store_true")
ap.add_argument("--profile", default=None, help="install into a Hermes profile")
args = ap.parse_args(argv)
if args.check:
return check(args)
return uninstall(args) if args.uninstall else install(args)
if __name__ == "__main__":
raise SystemExit(main())