-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathzcode-keysmith.py
More file actions
executable file
·3368 lines (3014 loc) · 136 KB
/
Copy pathzcode-keysmith.py
File metadata and controls
executable file
·3368 lines (3014 loc) · 136 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
"""Install a managed true-system prompt entrypoint for the local ZCode App.
On ZCode 3.12+ desktop builds, overriding ZCODE_AGENT_SERVER_COMMAND drops
supportsStorageStartup and the app stays on the isolated-storage failure
screen. Packaged Electron also deletes NODE_OPTIONS, so a parent-process
--require preload never reaches the agent and Keysmith does not inject.
Those builds keep the official agent-server command and patch glm/zcode.cjs
in place so customSystemPrompt reads the managed system-role.md first.
Older ZCode builds still use the agent-server wrapper. Both paths prefer
the managed file over any ZCode-provided systemPrompt.
"""
from __future__ import annotations
import argparse
import ctypes
import hashlib
import json
import os
import plistlib
import platform
import re
import runpy
import shutil
import stat
import subprocess
import sys
import tempfile
import time
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Iterable
# PyInstaller extracts bundled examples under _MEIPASS. Keep source runs
# relative to this file while making frozen defaults resolve to embedded data.
REPO_ROOT = (
Path(getattr(sys, "_MEIPASS"))
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS")
else Path(__file__).resolve().parent
)
__version__ = "0.3.3"
VERSION = __version__
JSON_SCHEMA = "zcode-keysmith/v1"
_LAST_USAGE_ERROR: list[str | None] = [None]
DEFAULT_SOURCE_SYSTEM_FILE = REPO_ROOT / "examples" / "system-role.md"
DEFAULT_MANAGED_DIR = Path.home() / ".zcode-keysmith"
DEFAULT_SYSTEM_FILE_NAME = "system-role.md"
DEFAULT_CONFIG_FILE_NAME = "config.json"
DEFAULT_WRAPPER_NAME = "zcode-agent-wrapper.py"
DEFAULT_PRELOAD_NAME = "zcode-keysmith-preload.cjs"
DEFAULT_ENV_SCRIPT_NAME = "zcode-keysmith-env.sh"
DEFAULT_WINDOWS_ENV_SCRIPT_NAME = "zcode-keysmith-env.ps1"
DEFAULT_LAUNCH_AGENT_LABEL = "com.jia.zcode-keysmith.env"
DEFAULT_LAUNCH_AGENT_NAME = f"{DEFAULT_LAUNCH_AGENT_LABEL}.plist"
DEFAULT_REARM_LAUNCH_AGENT_LABEL = "com.jia.zcode-keysmith.rearm"
DEFAULT_REARM_LAUNCH_AGENT_NAME = f"{DEFAULT_REARM_LAUNCH_AGENT_LABEL}.plist"
DEFAULT_REARM_SCRIPT_NAME = "zcode-keysmith-rearm.sh"
DEFAULT_ZCODE_APP = Path("/Applications/ZCode.app")
DEFAULT_ZCODE_RUNTIME = DEFAULT_ZCODE_APP / "Contents" / "Resources" / "glm" / "zcode.cjs"
DEFAULT_ZCODE_HELPER_NODE_COMMAND = DEFAULT_ZCODE_APP / "Contents" / "Frameworks" / "ZCode Helper.app" / "Contents" / "MacOS" / "ZCode Helper"
DEFAULT_ZCODE_NODE_COMMAND = DEFAULT_ZCODE_HELPER_NODE_COMMAND
FALLBACK_ZCODE_NODE_COMMAND = DEFAULT_ZCODE_APP / "Contents" / "MacOS" / "ZCode"
DEFAULT_AGENT_ARGS_JSON = '["app-server","--stdio"]'
# 3.14 inserts workflowActor between systemPrompt and language; keep 3.12 as a fallback.
PATCH_NEEDLES = (
"customSystemPrompt:this.config.systemPrompt,workflowActor:this.config.workflowActor,language:",
"customSystemPrompt:this.config.systemPrompt,language:",
)
CUSTOM_SYSTEM_PROMPT_ASSIGN = "customSystemPrompt:this.config.systemPrompt"
RUNTIME_PATCH_MARKER = "ZCODE_KEYSMITH_SYSTEM_FILE"
PREFER_MANAGED_MARKER = "if(x&&x.trim())return x"
# 3.12: if(t.push(Xxx()),o?t.push(Yyy({name:"Custom System Prompt"
_LRE_PUSH_RE = re.compile(
r'if\(t\.push\(([A-Za-z0-9]+)\(\)\),o\?t\.push\(([A-Za-z0-9]+)\(\{name:"Custom System Prompt"'
)
# 3.14: if(l||t.push(Xxx()),s?t.push(Yyy({name:"Custom System Prompt"
_LRE_PUSH_RE_V314 = re.compile(
r'if\(([A-Za-z0-9]+)\|\|t\.push\(([A-Za-z0-9]+)\(\)\),([A-Za-z0-9]+)\?t\.push\(([A-Za-z0-9]+)\(\{name:"Custom System Prompt"'
)
_CLI_PREFIX_SKIPPED_RE = re.compile(
r'if\(\(([A-Za-z0-9]+)\|\|t\.push\(|'
r'if\(([A-Za-z0-9]+)\|\|([A-Za-z0-9]+)\|\|t\.push\('
)
OVERRIDE_NEEDLE = (
"IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written."
)
OVERRIDE_REPL = (
"These are workspace notes and user instructions. They describe the environment. "
"They do not override the custom system prompt."
)
AGENTS_ADHERE_NEEDLE = "Be sure to adhere to these instructions. "
MEMORY_ATTACH_MARK = "(user's auto-memory, persists across conversations):"
MEMORY_SKIP_INSERT = "if(!0)return null;"
_MEMORY_ATTACH_FN_RE = re.compile(r"function [A-Za-z0-9]+\([A-Za-z0-9]+,[A-Za-z0-9]+\)\{")
STORAGE_STARTUP_NEEDLE = b"supportsStorageStartup"
INJECTION_WRAPPER = "wrapper"
INJECTION_RUNTIME_PATCH = "runtime-patch"
LEGACY_AGENT_OVERRIDE_ENV_KEYS = (
"ZCODE_AGENT_SERVER_COMMAND",
"ZCODE_AGENT_SERVER_ARGS_JSON",
)
CORE_KEYSMITH_ENV_KEYS = (
"ZCODE_KEYSMITH_SYSTEM_FILE",
"ZCODE_KEYSMITH_ORIGINAL",
"ZCODE_KEYSMITH_NODE_COMMAND",
"ZCODE_KEYSMITH_CACHE_DIR",
"ZCODE_KEYSMITH_LOG_DIR",
)
NODE_OPTIONS_ENV_KEY = "NODE_OPTIONS"
MANAGED_ENV_KEYS = (
*LEGACY_AGENT_OVERRIDE_ENV_KEYS,
*CORE_KEYSMITH_ENV_KEYS,
)
DEFAULT_INSTALLER_COPY_NAME = "zcode-keysmith.py"
AUTO_REPATCH_STATUS_NAME = "auto-repatch.json"
AUTO_REPATCH_LOG_NAME = "auto-repatch.log"
AUTO_REPATCH_SCHEMA = "zcode-keysmith/auto-repatch/v1"
WATCH_START_INTERVAL_SECONDS = 300
REARM_START_INTERVAL_SECONDS = 60
WATCH_THROTTLE_INTERVAL_SECONDS = 10
WATCH_SETTLE_TIMEOUT_SECONDS = 90.0
WATCH_SETTLE_STABLE_SECONDS = 3.0
WATCH_SETTLE_POLL_SECONDS = 0.5
WATCH_QUIT_TIMEOUT_SECONDS = 20.0
class KeysmithError(Exception):
"""User-facing installer error."""
@dataclass(frozen=True)
class InstallPaths:
managed_dir: Path
system_file: Path
config_file: Path
wrapper: Path
preload: Path
env_script: Path
launch_agent: Path | None
rearm_script: Path
rearm_launch_agent: Path | None
log_dir: Path
cache_dir: Path
wrapper_log: Path
@dataclass(frozen=True)
class InstallPlan:
paths: InstallPaths
source_system_file: Path
zcode_runtime: Path
node_command: Path
activate: bool
injection_mode: str = "wrapper"
def expand_path(value: str | Path) -> Path:
return Path(value).expanduser().resolve()
def default_launch_agent_path() -> Path:
return Path.home() / "Library" / "LaunchAgents" / DEFAULT_LAUNCH_AGENT_NAME
def build_paths(managed_dir: Path, launch_agent: Path | None = None) -> InstallPaths:
managed_dir = expand_path(managed_dir)
bin_dir = managed_dir / "bin"
is_windows = platform.system() == "Windows"
launch_agent_path = None if is_windows else (expand_path(launch_agent) if launch_agent else default_launch_agent_path())
return InstallPaths(
managed_dir=managed_dir,
system_file=managed_dir / DEFAULT_SYSTEM_FILE_NAME,
config_file=managed_dir / DEFAULT_CONFIG_FILE_NAME,
wrapper=bin_dir / DEFAULT_WRAPPER_NAME,
preload=bin_dir / DEFAULT_PRELOAD_NAME,
env_script=bin_dir / (DEFAULT_WINDOWS_ENV_SCRIPT_NAME if is_windows else DEFAULT_ENV_SCRIPT_NAME),
launch_agent=launch_agent_path,
rearm_script=bin_dir / DEFAULT_REARM_SCRIPT_NAME,
rearm_launch_agent=None if launch_agent_path is None else launch_agent_path.with_name(DEFAULT_REARM_LAUNCH_AGENT_NAME),
log_dir=managed_dir / "logs",
cache_dir=managed_dir / "cache",
wrapper_log=managed_dir / "logs" / "wrapper-start.jsonl",
)
def resolve_zcode_bundle_paths(zcode_app: Path) -> tuple[Path, Path]:
app = expand_path(zcode_app)
if app.is_file() and app.name.lower() == "zcode.exe":
app = app.parent
windows_runtime = app / "resources" / "glm" / "zcode.cjs"
windows_node = app / "ZCode.exe"
if windows_runtime.exists() or windows_node.exists() or platform.system() == "Windows":
return windows_runtime.resolve(), windows_node.resolve()
runtime = app / "Contents" / "Resources" / "glm" / "zcode.cjs"
helper_node = app / "Contents" / "Frameworks" / "ZCode Helper.app" / "Contents" / "MacOS" / "ZCode Helper"
main_node = app / "Contents" / "MacOS" / "ZCode"
node_command = helper_node if helper_node.exists() else main_node
return runtime.resolve(), node_command.resolve()
def windows_running_zcode_paths() -> list[Path]:
"""Return executable paths for running ZCode processes without extra dependencies."""
if platform.system() != "Windows":
return []
from ctypes import wintypes
TH32CS_SNAPPROCESS = 0x00000002
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
class PROCESSENTRY32W(ctypes.Structure):
_fields_ = [
("dwSize", wintypes.DWORD),
("cntUsage", wintypes.DWORD),
("th32ProcessID", wintypes.DWORD),
("th32DefaultHeapID", ctypes.c_size_t),
("th32ModuleID", wintypes.DWORD),
("cntThreads", wintypes.DWORD),
("th32ParentProcessID", wintypes.DWORD),
("pcPriClassBase", wintypes.LONG),
("dwFlags", wintypes.DWORD),
("szExeFile", wintypes.WCHAR * 260),
]
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
kernel32.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
kernel32.Process32FirstW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)]
kernel32.Process32FirstW.restype = wintypes.BOOL
kernel32.Process32NextW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)]
kernel32.Process32NextW.restype = wintypes.BOOL
kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
kernel32.OpenProcess.restype = wintypes.HANDLE
kernel32.QueryFullProcessImageNameW.argtypes = [
wintypes.HANDLE,
wintypes.DWORD,
wintypes.LPWSTR,
ctypes.POINTER(wintypes.DWORD),
]
kernel32.QueryFullProcessImageNameW.restype = wintypes.BOOL
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
kernel32.CloseHandle.restype = wintypes.BOOL
snapshot = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
if snapshot == INVALID_HANDLE_VALUE or snapshot is None:
return []
paths: list[Path] = []
try:
entry = PROCESSENTRY32W()
entry.dwSize = ctypes.sizeof(entry)
has_entry = kernel32.Process32FirstW(snapshot, ctypes.byref(entry))
while has_entry:
if entry.szExeFile.lower() == "zcode.exe":
process = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, entry.th32ProcessID)
if process:
try:
size = wintypes.DWORD(32768)
buffer = ctypes.create_unicode_buffer(size.value)
if kernel32.QueryFullProcessImageNameW(process, 0, buffer, ctypes.byref(size)):
paths.append(Path(buffer.value))
finally:
kernel32.CloseHandle(process)
has_entry = kernel32.Process32NextW(snapshot, ctypes.byref(entry))
finally:
kernel32.CloseHandle(snapshot)
return paths
def windows_registry_zcode_paths() -> list[Path]:
if platform.system() != "Windows":
return []
import winreg
paths: list[Path] = []
locations = (
(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\App Paths\ZCode.exe"),
(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\CurrentVersion\App Paths\ZCode.exe"),
)
for hive, subkey in locations:
try:
with winreg.OpenKey(hive, subkey) as key:
value, _ = winreg.QueryValueEx(key, None)
except OSError:
continue
if isinstance(value, str) and value.strip():
paths.append(Path(value.strip().strip('"')))
return paths
def discover_zcode_app_path() -> Path:
env_app = os.environ.get("ZCODE_APP_PATH")
candidates: list[Path] = []
if env_app:
candidates.append(Path(env_app))
if platform.system() == "Windows":
candidates.extend(windows_running_zcode_paths())
candidates.extend(windows_registry_zcode_paths())
path_executable = shutil.which("ZCode.exe")
if path_executable:
candidates.append(Path(path_executable))
local_app_data = os.environ.get("LOCALAPPDATA")
program_files = os.environ.get("ProgramFiles")
if local_app_data:
candidates.extend([Path(local_app_data) / "Programs" / "ZCode", Path(local_app_data) / "ZCode"])
if program_files:
candidates.append(Path(program_files) / "ZCode")
else:
candidates.append(DEFAULT_ZCODE_APP)
if platform.system() == "Darwin":
completed = subprocess.run(
["mdfind", "kMDItemCFBundleIdentifier == 'dev.zcode.app'"],
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=False,
)
if completed.returncode == 0:
candidates.extend(Path(line.strip()) for line in completed.stdout.splitlines() if line.strip())
for candidate in candidates:
expanded = candidate.expanduser()
if expanded.is_file() and expanded.name.lower() == "zcode.exe":
expanded = expanded.parent
if expanded.exists() and expanded.is_dir():
runtime, node = resolve_zcode_bundle_paths(expanded)
if runtime.exists() and node.exists():
return expanded.resolve()
if platform.system() == "Windows":
local_app_data = Path(os.environ.get("LOCALAPPDATA", str(Path.home() / "AppData" / "Local")))
return (local_app_data / "Programs" / "ZCode").resolve()
return DEFAULT_ZCODE_APP.resolve()
def zcode_app_from_runtime(runtime_path: Path) -> Path | None:
runtime = expand_path(runtime_path)
if runtime.parent.name.lower() == "glm" and runtime.parent.parent.name.lower() == "resources":
windows_app = runtime.parent.parent.parent
if (windows_app / "ZCode.exe").exists() or platform.system() == "Windows":
return windows_app
for parent in runtime.parents:
if parent.name.endswith(".app"):
return parent
return None
def app_supports_agent_server_override(zcode_app: Path | None) -> bool:
return app_asar_contains(zcode_app, b"ZCODE_AGENT_SERVER_COMMAND")
def app_asar_candidates(zcode_app: Path) -> tuple[Path, ...]:
app = expand_path(zcode_app)
return (
app / "Contents" / "Resources" / "app.asar",
app / "resources" / "app.asar",
)
def app_asar_contains(zcode_app: Path | None, needle: bytes) -> bool:
if not zcode_app:
return False
for app_asar in app_asar_candidates(zcode_app):
if not app_asar.exists() or not app_asar.is_file():
continue
try:
overlap = b""
with app_asar.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
data = overlap + chunk
if needle in data:
return True
overlap = data[-(len(needle) - 1) :]
except OSError:
continue
return False
def app_requires_storage_startup(zcode_app: Path | None) -> bool:
return app_asar_contains(zcode_app, STORAGE_STARTUP_NEEDLE)
def injection_mode_for_app(zcode_app: Path | None) -> str:
return INJECTION_RUNTIME_PATCH if app_requires_storage_startup(zcode_app) else INJECTION_WRAPPER
def is_zcode_running() -> bool:
if platform.system() == "Windows":
return bool(windows_running_zcode_paths())
if platform.system() != "Darwin":
return False
completed = subprocess.run(["pgrep", "-x", "ZCode"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
return completed.returncode == 0
def normalize_system_prompt_content(content: str) -> str:
"""Normalize common exported system-prompt wrappers into prompt body text."""
leading = content[: len(content) - len(content.lstrip())]
text = content.lstrip()
prefixes = [
"<|im_start|>system:<project_instructions>",
"<|im_start|>system:",
"<|im_start|>system",
]
for prefix in prefixes:
if text.startswith(prefix):
rest = text[len(prefix) :]
if prefix.endswith("<project_instructions>"):
text = "<project_instructions>" + rest
else:
text = rest.lstrip("\r\n")
break
stripped = text.rstrip()
if stripped.endswith("<|im_end|>"):
text = stripped[: -len("<|im_end|>")].rstrip() + "\n"
return leading + text
def read_required_text(path: Path, label: str) -> str:
if not path.exists():
raise KeysmithError(f"{label} not found: {path}")
if not path.is_file():
raise KeysmithError(f"{label} is not a regular file: {path}")
try:
text = path.read_text(encoding="utf-8")
except UnicodeDecodeError as exc:
raise KeysmithError(f"{label} must be UTF-8: {path}") from exc
except OSError as exc:
raise KeysmithError(f"Could not read {label}: {path}\nReason: {exc}") from exc
if not text.strip():
raise KeysmithError(f"{label} is empty: {path}")
return text
def read_system_prompt_source(path: Path) -> str:
text = normalize_system_prompt_content(read_required_text(path, "source system prompt"))
if not text.strip():
raise KeysmithError(f"source system prompt is empty after normalization: {path}")
return text
def runtime_text_is_keysmith_patched(text: str) -> bool:
return RUNTIME_PATCH_MARKER in text
def runtime_text_prefers_managed(text: str) -> bool:
return runtime_text_is_keysmith_patched(text) and PREFER_MANAGED_MARKER in text
def vendor_patch_anchor(text: str) -> str | None:
for needle in PATCH_NEEDLES:
if needle in text:
return needle
return None
def runtime_is_patchable_text(text: str) -> bool:
return vendor_patch_anchor(text) is not None or runtime_text_is_keysmith_patched(text)
def ensure_runtime_patchable(runtime_path: Path) -> None:
runtime = read_required_text(runtime_path, "ZCode runtime")
if runtime_is_patchable_text(runtime):
return
raise KeysmithError(
"ZCode runtime entrypoint shape was not recognized.\n"
f"Runtime: {runtime_path}\n"
"The installer expected the runtime context builder anchor used by current ZCode releases."
)
def build_system_prompt_expression(system_file: str) -> str:
system_file_json = json.dumps(system_file, ensure_ascii=False)
return (
"(()=>{try{let e=process.env.ZCODE_KEYSMITH_SYSTEM_FILE||"
+ system_file_json
+ ';let t=require("node:fs");if(t.existsSync(e)){let x=t.readFileSync(e,"utf8");if(x&&x.trim())return x}}catch{}'
+ "return this.config.systemPrompt})()"
)
def replace_vendor_system_prompt_anchor(original_runtime: str, expression: str) -> str:
needle = vendor_patch_anchor(original_runtime)
if needle is None:
raise KeysmithError("ZCode runtime patch anchor not found")
if needle == PATCH_NEEDLES[0]:
expression = "this.config.workflowActor===void 0?" + expression + ":void 0"
suffix = needle[len(CUSTOM_SYSTEM_PROMPT_ASSIGN) :]
return original_runtime.replace(needle, "customSystemPrompt:" + expression + suffix, 1)
def _memory_attach_body_at(text: str) -> int | None:
"""Return the index of the MEMORY.md attach function body, if present."""
mark_at = text.find(MEMORY_ATTACH_MARK)
if mark_at < 0:
return None
search_from = max(0, mark_at - 240)
matches = list(_MEMORY_ATTACH_FN_RE.finditer(text, search_from, mark_at))
if not matches:
return None
return matches[-1].end()
def _skip_memory_attach(text: str) -> str:
"""Stop project MEMORY.md from being concatenated into agentsMd."""
body_at = _memory_attach_body_at(text)
if body_at is None:
return text
if text.startswith(MEMORY_SKIP_INSERT, body_at):
return text
return text[:body_at] + MEMORY_SKIP_INSERT + text[body_at:]
def apply_followup_runtime_patches(text: str) -> str:
"""Keep Pier above platform CLI prefix, agentsMd OVERRIDE copy, and project MEMORY.md."""
patched, _n = _LRE_PUSH_RE.subn(
r'if((o||t.push(\1())),o?t.push(\2({name:"Custom System Prompt"',
text,
count=1,
)
patched, _n = _LRE_PUSH_RE_V314.subn(
r'if(\3||\1||t.push(\2()),\3?t.push(\4({name:"Custom System Prompt"',
patched,
count=1,
)
if OVERRIDE_NEEDLE in patched:
patched = patched.replace(OVERRIDE_NEEDLE, OVERRIDE_REPL, 1)
if AGENTS_ADHERE_NEEDLE in patched:
patched = patched.replace(AGENTS_ADHERE_NEEDLE, "", 1)
return _skip_memory_attach(patched)
def build_patched_runtime_text(original_runtime: str, system_file: str) -> str:
patched = replace_vendor_system_prompt_anchor(
original_runtime, build_system_prompt_expression(system_file)
)
return apply_followup_runtime_patches(patched)
def original_runtime_backup_path(plan: InstallPlan, original_sha256: str | None = None) -> Path:
backups = plan.paths.managed_dir / "backups"
if original_sha256:
return backups / f"zcode.cjs.{original_sha256[:16]}.original"
if not plan.zcode_runtime.exists():
return backups / "zcode.cjs.unknown.original"
text = plan.zcode_runtime.read_text(encoding="utf-8", errors="ignore")
if runtime_text_is_keysmith_patched(text):
saved = load_saved_config(plan.paths) or {}
saved_backup = saved.get("runtime_original_backup")
if isinstance(saved_backup, str) and saved_backup and Path(saved_backup).is_file():
return Path(saved_backup)
if backups.is_dir():
originals = sorted(backups.glob("zcode.cjs.*.original"))
if originals:
return originals[-1]
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
return backups / f"zcode.cjs.{digest[:16]}.original"
def write_text_atomic(path: Path, content: str, mode: int | None = None) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
"w",
encoding="utf-8",
dir=str(path.parent),
prefix=f".{path.name}.",
suffix=".tmp",
delete=False,
) as handle:
handle.write(content)
tmp = Path(handle.name)
if mode is not None:
tmp.chmod(mode)
tmp.replace(path)
def apply_runtime_patch(plan: InstallPlan) -> list[Path]:
"""Patch glm/zcode.cjs in place so the official agent reads Keysmith first."""
backups: list[Path] = []
runtime_path = plan.zcode_runtime
text = read_required_text(runtime_path, "ZCode runtime")
if runtime_text_prefers_managed(text):
follow = apply_followup_runtime_patches(text)
if follow != text:
mode = stat.S_IMODE(runtime_path.stat().st_mode)
write_text_atomic(runtime_path, follow, mode)
return backups
if runtime_text_is_keysmith_patched(text) and vendor_patch_anchor(text) is None:
saved = load_saved_config(plan.paths) or {}
backup = saved.get("runtime_original_backup")
if not isinstance(backup, str) or not Path(backup).is_file():
raise KeysmithError(
"ZCode runtime is already patched with an older Keysmith expression, "
"and the original backup is missing. Restore the vendor zcode.cjs first."
)
text = Path(backup).read_text(encoding="utf-8")
if vendor_patch_anchor(text) is None:
raise KeysmithError(f"ZCode runtime patch anchor not found: {runtime_path}")
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
backup_path = original_runtime_backup_path(plan, digest)
backup_path.parent.mkdir(parents=True, exist_ok=True)
if not backup_path.exists():
write_text_atomic(backup_path, text)
backups.append(backup_path)
patched = build_patched_runtime_text(text, str(plan.paths.system_file))
mode = stat.S_IMODE(runtime_path.stat().st_mode) if runtime_path.exists() else 0o755
write_text_atomic(runtime_path, patched, mode)
return backups
def restore_runtime_from_config(config: dict[str, object] | None) -> list[str]:
if not config or not config.get("app_bundle_modified"):
return []
backup = config.get("runtime_original_backup")
runtime = config.get("zcode_runtime")
if not isinstance(backup, str) or not isinstance(runtime, str):
return []
backup_path = Path(backup)
runtime_path = Path(runtime)
if not backup_path.is_file() or not runtime_path.is_file():
return [f"runtime restore skipped: backup or runtime missing"]
current = runtime_path.read_text(encoding="utf-8", errors="ignore")
if not runtime_text_is_keysmith_patched(current):
return ["runtime already vendor-shaped"]
mode = stat.S_IMODE(runtime_path.stat().st_mode)
write_text_atomic(runtime_path, backup_path.read_text(encoding="utf-8"), mode)
return [f"runtime restored: {runtime_path}"]
def reserve_backup_path(path: Path) -> Path:
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup = path.with_name(f"{path.name}.bak_{stamp}")
counter = 1
while True:
try:
descriptor = os.open(backup, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
except FileExistsError:
backup = path.with_name(f"{path.name}.bak_{stamp}_{counter}")
counter += 1
continue
os.close(descriptor)
return backup
def backup_existing(path: Path) -> Path | None:
if not path.exists():
return None
backup = reserve_backup_path(path)
try:
path.replace(backup)
except Exception:
backup.unlink(missing_ok=True)
raise
return backup
@contextmanager
def operation_lock(paths: InstallPaths):
paths.managed_dir.mkdir(parents=True, exist_ok=True)
lock_path = paths.managed_dir / ".operation.lock"
handle = lock_path.open("a+b")
if lock_path.stat().st_size == 0:
handle.write(b"0")
handle.flush()
try:
if os.name == "nt":
import msvcrt
handle.seek(0)
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except (OSError, BlockingIOError) as exc:
handle.close()
raise KeysmithError(f"another zcode-keysmith operation is already running: {lock_path}") from exc
try:
yield
finally:
try:
if os.name == "nt":
import msvcrt
handle.seek(0)
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
finally:
handle.close()
def atomic_write_text(path: Path, content: str, mode: int | None = None) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
"w",
encoding="utf-8",
dir=str(path.parent),
prefix=f".{path.name}.",
suffix=".tmp",
delete=False,
) as handle:
handle.write(content)
tmp = Path(handle.name)
if mode is not None:
tmp.chmod(mode)
tmp.replace(path)
if mode is not None:
path.chmod(mode)
def atomic_write_plist(path: Path, payload: dict[str, object]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
"wb",
dir=str(path.parent),
prefix=f".{path.name}.",
suffix=".tmp",
delete=False,
) as handle:
plistlib.dump(payload, handle, sort_keys=False)
tmp = Path(handle.name)
tmp.replace(path)
def rollback_replaced_files(replaced: list[tuple[Path, Path | None]]) -> list[str]:
errors: list[str] = []
for target, previous in reversed(replaced):
try:
if previous is None:
target.unlink(missing_ok=True)
else:
previous.replace(target)
except OSError as exc:
errors.append(f"{target}: {exc}")
return errors
def restore_replaced_files(replaced: list[tuple[Path, Path | None]]) -> None:
errors = rollback_replaced_files(replaced)
if errors:
raise KeysmithError("file rollback failed:\n" + "\n".join(errors))
def installer_copy_path(paths: InstallPaths) -> Path:
return paths.managed_dir / "bin" / DEFAULT_INSTALLER_COPY_NAME
def auto_repatch_status_path(paths: InstallPaths) -> Path:
return paths.log_dir / AUTO_REPATCH_STATUS_NAME
def auto_repatch_log_path(paths: InstallPaths) -> Path:
return paths.log_dir / AUTO_REPATCH_LOG_NAME
def install_managed_files(
plan: InstallPlan,
system_prompt: str,
config: str,
) -> tuple[list[Path], list[tuple[Path, Path | None]]]:
payloads: list[tuple[Path, str, int | None]] = [
(plan.paths.system_file, system_prompt, None),
(plan.paths.config_file, config, None),
(plan.paths.wrapper, render_wrapper(plan), 0o755),
(plan.paths.env_script, render_env_script(plan), 0o755),
]
if not uses_runtime_patch(plan):
payloads.insert(3, (plan.paths.preload, render_preload(plan), 0o644))
if uses_runtime_patch(plan) and platform.system() == "Darwin":
payloads.append(
(
installer_copy_path(plan.paths),
Path(__file__).resolve().read_text(encoding="utf-8"),
0o755,
)
)
payloads.append((plan.paths.rearm_script, render_rearm_script(plan), 0o755))
staged: list[tuple[Path, Path]] = []
replaced: list[tuple[Path, Path | None]] = []
backups: list[Path] = []
try:
for target, content, mode in payloads:
target.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
"w",
encoding="utf-8",
dir=str(target.parent),
prefix=f".{target.name}.",
suffix=".install.tmp",
delete=False,
) as handle:
handle.write(content)
tmp = Path(handle.name)
if mode is not None:
tmp.chmod(mode)
staged.append((target, tmp))
if plan.paths.launch_agent is not None:
target = plan.paths.launch_agent
target.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
"wb",
dir=str(target.parent),
prefix=f".{target.name}.",
suffix=".install.tmp",
delete=False,
) as handle:
plistlib.dump(render_launch_agent(plan), handle, sort_keys=False)
tmp = Path(handle.name)
staged.append((target, tmp))
if uses_runtime_patch(plan) and plan.paths.rearm_launch_agent is not None:
target = plan.paths.rearm_launch_agent
target.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
"wb",
dir=str(target.parent),
prefix=f".{target.name}.",
suffix=".install.tmp",
delete=False,
) as handle:
plistlib.dump(render_rearm_launch_agent(plan), handle, sort_keys=False)
tmp = Path(handle.name)
staged.append((target, tmp))
for target, tmp in staged:
previous = reserve_backup_path(target) if target.exists() else None
if previous is not None:
try:
target.replace(previous)
except Exception:
previous.unlink(missing_ok=True)
raise
replaced.append((target, previous))
tmp.replace(target)
if previous is not None:
backups.append(previous)
return backups, replaced
except Exception as exc:
rollback_errors = rollback_replaced_files(replaced)
if rollback_errors:
raise KeysmithError(
f"{exc}\nFile rollback failed:\n" + "\n".join(rollback_errors)
) from exc
raise
finally:
for _, tmp in staged:
tmp.unlink(missing_ok=True)
def agent_server_command(plan: InstallPlan) -> str:
if platform.system() == "Windows":
return str(Path(sys.executable).resolve())
return str(plan.paths.wrapper)
def agent_server_args_json(plan: InstallPlan) -> str:
args = ["app-server", "--stdio"]
if platform.system() == "Windows":
args.insert(0, str(plan.paths.wrapper))
return json.dumps(args, ensure_ascii=False, separators=(",", ":"))
def uses_runtime_patch(plan: InstallPlan) -> bool:
return plan.injection_mode == INJECTION_RUNTIME_PATCH
def uses_preload_injection(plan: InstallPlan) -> bool:
# Kept as a compatibility alias for leftover NODE_OPTIONS cleanup.
return False
def node_options_require_flag(plan: InstallPlan) -> str:
return f"--require {plan.paths.preload}"
def merge_node_options(existing: str | None, require_flag: str) -> str:
parts = [part for part in (existing or "").split() if part]
flag_parts = require_flag.split()
if len(flag_parts) >= 2:
for index, part in enumerate(parts[:-1]):
if part == flag_parts[0] and parts[index + 1] == flag_parts[1]:
return " ".join(parts)
parts.extend(flag_parts)
return " ".join(parts)
def strip_node_options(existing: str | None, require_flag: str) -> str | None:
parts = [part for part in (existing or "").split() if part]
flag_parts = require_flag.split()
if len(flag_parts) >= 2:
filtered: list[str] = []
skip = False
for index, part in enumerate(parts):
if skip:
skip = False
continue
if part == flag_parts[0] and index + 1 < len(parts) and parts[index + 1] == flag_parts[1]:
skip = True
continue
filtered.append(part)
parts = filtered
return " ".join(parts) or None
def node_options_value(plan: InstallPlan, existing: str | None = None) -> str:
if existing is None:
existing = os.environ.get(NODE_OPTIONS_ENV_KEY)
return merge_node_options(existing, node_options_require_flag(plan))
def env_values(plan: InstallPlan) -> dict[str, str]:
values = {
"ZCODE_KEYSMITH_SYSTEM_FILE": str(plan.paths.system_file),
"ZCODE_KEYSMITH_ORIGINAL": str(plan.zcode_runtime),
"ZCODE_KEYSMITH_NODE_COMMAND": str(plan.node_command),
"ZCODE_KEYSMITH_CACHE_DIR": str(plan.paths.cache_dir),
"ZCODE_KEYSMITH_LOG_DIR": str(plan.paths.log_dir),
}
if not uses_runtime_patch(plan):
values["ZCODE_AGENT_SERVER_COMMAND"] = agent_server_command(plan)
values["ZCODE_AGENT_SERVER_ARGS_JSON"] = agent_server_args_json(plan)
return values
def managed_env_keys_for_plan(plan: InstallPlan) -> tuple[str, ...]:
return tuple(env_values(plan))
def all_managed_env_keys() -> tuple[str, ...]:
return MANAGED_ENV_KEYS
def render_env_script(plan: InstallPlan) -> str:
if platform.system() == "Windows":
lines = [
"$ErrorActionPreference = 'Stop'",
"$values = [ordered]@{",
]
for key, value in env_values(plan).items():
lines.append(f" {key} = {powershell_single_quote(value)}")
lines.extend(
[
"}",
"foreach ($entry in $values.GetEnumerator()) {",
" [Environment]::SetEnvironmentVariable($entry.Key, $entry.Value, 'User')",
"}",
"Write-Output 'zcode-keysmith Windows environment activated'",
"",
]
)
return "\n".join(lines)
lines = ["#!/bin/sh", "set -eu"]
for key, value in env_values(plan).items():
lines.append(f"launchctl setenv {key} {sh_single_quote(value)}")
if uses_runtime_patch(plan):
lines.append(
"exec "
f"{sh_single_quote(str(Path(sys.executable).resolve()))} "
f"{sh_single_quote(str(installer_copy_path(plan.paths)))} "
"watch "
f"--managed-dir {sh_single_quote(str(plan.paths.managed_dir))} "
f"--zcode-runtime {sh_single_quote(str(plan.zcode_runtime))} "
f"--node-command {sh_single_quote(str(plan.node_command))} "
"--yes"
)
lines.append("")
return "\n".join(lines)
def sh_single_quote(value: str) -> str:
return "'" + value.replace("'", "'\\''") + "'"
def powershell_single_quote(value: str) -> str:
return "'" + value.replace("'", "''") + "'"
def render_launch_agent(plan: InstallPlan) -> dict[str, object]:
if plan.paths.launch_agent is None:
raise KeysmithError("LaunchAgent is only available on macOS")
payload: dict[str, object] = {
"Label": DEFAULT_LAUNCH_AGENT_LABEL,
"ProgramArguments": [str(plan.paths.env_script)],
"RunAtLoad": True,
"StandardOutPath": str(plan.paths.log_dir / "launchagent.out.log"),
"StandardErrorPath": str(plan.paths.log_dir / "launchagent.err.log"),
}
if uses_runtime_patch(plan):
app = zcode_app_from_runtime(plan.zcode_runtime)
watch_paths = [str(plan.zcode_runtime)]
if app is not None and str(app) not in watch_paths:
watch_paths.append(str(app))
payload["StartInterval"] = WATCH_START_INTERVAL_SECONDS
payload["ThrottleInterval"] = WATCH_THROTTLE_INTERVAL_SECONDS
payload["ExitTimeOut"] = 180