@pushary/agent-hooks 1.9.144 → 1.9.147

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +5 -4
  3. package/data/SKILL.md +3 -3
  4. package/data/cursor-plugin/scripts/redaction.mjs +2 -1
  5. package/data/cursor-plugin/skills/pushary/SKILL.md +2 -2
  6. package/data/openclaw-plugin/LICENSE +21 -0
  7. package/data/openclaw-plugin/README.md +113 -0
  8. package/data/openclaw-plugin/dist/api-key-shape.js +5 -0
  9. package/data/openclaw-plugin/dist/approval-hook.js +88 -0
  10. package/data/openclaw-plugin/dist/approval-question.js +66 -0
  11. package/data/openclaw-plugin/dist/connection.js +101 -0
  12. package/data/openclaw-plugin/dist/decision-reply.js +6 -0
  13. package/data/openclaw-plugin/dist/gate-result.js +58 -0
  14. package/data/openclaw-plugin/dist/gate.js +173 -0
  15. package/data/openclaw-plugin/dist/hook-budget.js +19 -0
  16. package/data/openclaw-plugin/dist/host-api.js +1 -0
  17. package/data/openclaw-plugin/dist/host-version.js +25 -0
  18. package/data/openclaw-plugin/dist/index.js +32 -0
  19. package/data/openclaw-plugin/dist/openclaw-paths.js +43 -0
  20. package/data/openclaw-plugin/dist/openclaw-write-guard.js +93 -0
  21. package/data/openclaw-plugin/dist/protected-writes.js +217 -0
  22. package/data/openclaw-plugin/dist/pushary-client.js +103 -0
  23. package/data/openclaw-plugin/dist/pushary-hosts.js +3 -0
  24. package/data/openclaw-plugin/dist/redaction.js +53 -0
  25. package/data/openclaw-plugin/dist/replies.js +65 -0
  26. package/data/openclaw-plugin/dist/settings.js +103 -0
  27. package/data/openclaw-plugin/openclaw.plugin.json +32 -0
  28. package/data/openclaw-plugin/package.json +70 -0
  29. package/data/vscode-plugin/scripts/redaction.mjs +2 -1
  30. package/data/vscode-plugin/skills/pushary/SKILL.md +2 -2
  31. package/dist/{api-ZV7TT25P.js → api-2KDVLXHT.js} +11 -11
  32. package/dist/bin/pushary-audit.js +3 -3
  33. package/dist/bin/pushary-bell-hook.js +28 -28
  34. package/dist/bin/pushary-bell.js +11 -11
  35. package/dist/bin/pushary-claude.js +27 -27
  36. package/dist/bin/pushary-clean.js +76 -39
  37. package/dist/bin/pushary-codex-bridge.js +23 -23
  38. package/dist/bin/pushary-codex-hook.js +35 -35
  39. package/dist/bin/pushary-codex-session.js +8 -8
  40. package/dist/bin/pushary-codex.js +16 -16
  41. package/dist/bin/pushary-connect.js +78 -36
  42. package/dist/bin/pushary-cowork.js +5 -5
  43. package/dist/bin/pushary-daemon.js +44 -43
  44. package/dist/bin/pushary-disconnect.js +28 -28
  45. package/dist/bin/pushary-display-hook.js +103 -44
  46. package/dist/bin/pushary-doctor.js +139 -55
  47. package/dist/bin/pushary-elicitation-hook.js +28 -28
  48. package/dist/bin/pushary-gemini-bridge.js +17 -17
  49. package/dist/bin/pushary-gemini-hook.js +32 -32
  50. package/dist/bin/pushary-hook.js +35 -35
  51. package/dist/bin/pushary-login.js +22 -22
  52. package/dist/bin/pushary-logout.js +33 -31
  53. package/dist/bin/pushary-mcp.js +12 -12
  54. package/dist/bin/pushary-mode.js +16 -16
  55. package/dist/bin/pushary-notification-hook.js +27 -27
  56. package/dist/bin/pushary-opencode-hook.js +31 -31
  57. package/dist/bin/pushary-permission-denied-hook.js +35 -35
  58. package/dist/bin/pushary-permission-hook.js +35 -35
  59. package/dist/bin/pushary-post-hook.js +28 -28
  60. package/dist/bin/pushary-prompt-hook.js +27 -27
  61. package/dist/bin/pushary-session-end-hook.js +27 -27
  62. package/dist/bin/pushary-session-start-hook.js +37 -36
  63. package/dist/bin/pushary-setup.js +209 -89
  64. package/dist/bin/pushary-stats.js +5 -5
  65. package/dist/bin/pushary-status.js +38 -36
  66. package/dist/bin/pushary-stop-hook.js +27 -27
  67. package/dist/bin/pushary-stopfailure-hook.js +27 -27
  68. package/dist/bin/pushary-suggestions.js +16 -16
  69. package/dist/bin/pushary-transcript-register.js +17 -17
  70. package/dist/bin/pushary-transcripts.js +25 -25
  71. package/dist/bin/pushary-upgrade.js +42 -41
  72. package/dist/bin/pushary-wait.js +16 -16
  73. package/dist/bin/pushary.js +7 -7
  74. package/dist/{chunk-LUVSHGLH.js → chunk-2EETRVCZ.js} +1 -1
  75. package/dist/{chunk-YESBU4VQ.js → chunk-2G54YLN3.js} +3 -3
  76. package/dist/{chunk-WGOTBZ23.js → chunk-2I6A34GJ.js} +15 -5
  77. package/dist/{chunk-WGT5LCIB.js → chunk-2QY2BD4T.js} +5 -5
  78. package/dist/{chunk-HGIW56MU.js → chunk-2RAIG6NF.js} +2 -2
  79. package/dist/{chunk-QLGLUUOP.js → chunk-2YNAQ5TX.js} +1 -1
  80. package/dist/{chunk-44WPMZGQ.js → chunk-37ZBJB2Q.js} +5 -5
  81. package/dist/{chunk-4EBJ4PTZ.js → chunk-3NMX4725.js} +1 -1
  82. package/dist/{chunk-E32SRYTE.js → chunk-3TTXOU6G.js} +3 -3
  83. package/dist/{chunk-GV3FDGQH.js → chunk-4P3ML7HP.js} +200 -59
  84. package/dist/{chunk-22CXL7YI.js → chunk-526XSNMS.js} +3 -3
  85. package/dist/{chunk-B4VIT5N3.js → chunk-57GVGSOQ.js} +1 -1
  86. package/dist/{chunk-6LALK6GI.js → chunk-5II3USXS.js} +2 -2
  87. package/dist/{chunk-WWCM6UL7.js → chunk-5K65H6OO.js} +1 -1
  88. package/dist/{chunk-56HFENZK.js → chunk-6C5QRJIH.js} +5 -5
  89. package/dist/{chunk-EOKUIOMT.js → chunk-6EPTMB7L.js} +4 -4
  90. package/dist/{chunk-C5LIS3XM.js → chunk-6JBX55K4.js} +38 -8
  91. package/dist/{chunk-23CGCD5L.js → chunk-6YVGY2ZX.js} +7 -7
  92. package/dist/{chunk-WC25Z4XS.js → chunk-72S6PF2I.js} +2 -2
  93. package/dist/{chunk-YY5YVMBA.js → chunk-7P32YU2M.js} +10 -74
  94. package/dist/{chunk-WTBFPSTR.js → chunk-7TVSWGAV.js} +8 -6
  95. package/dist/{chunk-S7WVJ6AR.js → chunk-7WDEJTNX.js} +4 -4
  96. package/dist/{chunk-AJQ4TTPJ.js → chunk-7XIJD7NL.js} +3 -3
  97. package/dist/{chunk-PYT4WXXR.js → chunk-A5MSVNFS.js} +10 -10
  98. package/dist/{chunk-FC2ENROR.js → chunk-ANLR5G2W.js} +4 -4
  99. package/dist/{chunk-7VMVMC4H.js → chunk-BEDAQAEN.js} +1 -1
  100. package/dist/{chunk-4JTZZXB3.js → chunk-BHGSNYG5.js} +3 -3
  101. package/dist/{chunk-5I3UQEAX.js → chunk-BU2J4P7P.js} +3 -3
  102. package/dist/{chunk-EMODTMHE.js → chunk-BYVLAPCF.js} +1 -1
  103. package/dist/{chunk-5BTAIFVV.js → chunk-CSNG5NQR.js} +1 -1
  104. package/dist/{chunk-7QWH257P.js → chunk-D7ZWJYXB.js} +1 -1
  105. package/dist/{chunk-AGUL2JDK.js → chunk-ELRZO6A7.js} +3 -3
  106. package/dist/{chunk-Z2WQD2W6.js → chunk-EV54ZQ5J.js} +4 -4
  107. package/dist/{chunk-5TZYAMGW.js → chunk-FHBJJOMF.js} +1 -1
  108. package/dist/{chunk-74QCFZKV.js → chunk-FKGWP4MF.js} +8 -7
  109. package/dist/{chunk-MCI6KYN7.js → chunk-FMAIUTVU.js} +3 -3
  110. package/dist/{chunk-WTULK73V.js → chunk-FWCECQTY.js} +2 -2
  111. package/dist/{chunk-ZVJIJPQY.js → chunk-GGCUXNZN.js} +1 -1
  112. package/dist/{chunk-VP4T5352.js → chunk-GIWI5IHB.js} +6 -6
  113. package/dist/{chunk-RPXSGCRG.js → chunk-GJV5RVUU.js} +98 -47
  114. package/dist/chunk-GPAMD5JG.js +157 -0
  115. package/dist/{chunk-ZGYGKKXF.js → chunk-I72UU75H.js} +16 -16
  116. package/dist/{chunk-CV4EIXPV.js → chunk-ISM6XF3V.js} +494 -15
  117. package/dist/{chunk-HNFYZPNJ.js → chunk-ISOP4ENY.js} +17 -5
  118. package/dist/{chunk-R7FSMUHG.js → chunk-JDIKCM2N.js} +6 -5
  119. package/dist/{chunk-BHNX7XNO.js → chunk-KDJIDRJS.js} +3 -3
  120. package/dist/{chunk-DDJHPMBJ.js → chunk-KFL7OWLI.js} +1 -1
  121. package/dist/{chunk-5AXDNDUJ.js → chunk-KH27X5CW.js} +2 -2
  122. package/dist/{chunk-BHKODM4L.js → chunk-KXMIDDUN.js} +2 -2
  123. package/dist/{chunk-3KRGT5AZ.js → chunk-L2M6D2N4.js} +67 -4
  124. package/dist/{chunk-KEBI7NYU.js → chunk-L6BTSIKF.js} +4 -4
  125. package/dist/{chunk-YFK3MJGZ.js → chunk-LO52V6WG.js} +2 -2
  126. package/dist/{chunk-LVOHE66T.js → chunk-MI7GHNTO.js} +5 -5
  127. package/dist/{chunk-4524ZR2U.js → chunk-MYJJNLT2.js} +2 -2
  128. package/dist/{chunk-CZOMD2IW.js → chunk-NAGF5ZJ2.js} +8 -8
  129. package/dist/{chunk-53KLGXFL.js → chunk-NMUEUDTT.js} +4 -3
  130. package/dist/{chunk-C6SKS6IU.js → chunk-OSYULPJO.js} +23 -12
  131. package/dist/{chunk-F37YD4YE.js → chunk-OXDKZYBO.js} +1 -1
  132. package/dist/chunk-OYIN77HO.js +72 -0
  133. package/dist/{chunk-XLMJEEW3.js → chunk-P6W2V2AP.js} +2 -2
  134. package/dist/{chunk-ZKKZEVNI.js → chunk-Q3JW44JV.js} +2 -2
  135. package/dist/{chunk-EY5CVFDL.js → chunk-Q6POCQOV.js} +12 -12
  136. package/dist/{chunk-P5QXH5QI.js → chunk-Q767Y4LY.js} +1 -1
  137. package/dist/{chunk-UK5DKLZY.js → chunk-QGKFDSEO.js} +8 -8
  138. package/dist/{chunk-YD376BLV.js → chunk-RZGR4G5G.js} +5 -5
  139. package/dist/{chunk-OZG6CGYW.js → chunk-RZJHCHEA.js} +6 -6
  140. package/dist/{chunk-H33CFJOF.js → chunk-T274HRSR.js} +4 -4
  141. package/dist/chunk-T2CR5REM.js +176 -0
  142. package/dist/{chunk-QESEICW4.js → chunk-T3TVMMXJ.js} +1 -1
  143. package/dist/{chunk-44BLJJPH.js → chunk-TZ7CBPCD.js} +2 -2
  144. package/dist/{chunk-YCU7Y77H.js → chunk-UGPNLU4O.js} +1 -1
  145. package/dist/{chunk-BE5LO5VW.js → chunk-UR55VBLY.js} +2 -2
  146. package/dist/{chunk-EC7VHNHE.js → chunk-WLKW2TF7.js} +19 -12
  147. package/dist/{chunk-CWWO3JTD.js → chunk-WNV3X2VU.js} +3 -3
  148. package/dist/{chunk-HIIXYZYV.js → chunk-XQOBM3E6.js} +3 -3
  149. package/dist/{chunk-JK7DTAQH.js → chunk-YICO6HEW.js} +5 -5
  150. package/dist/{chunk-FO3MDD26.js → chunk-YM2T76UM.js} +27 -0
  151. package/dist/chunk-YOVJOHM5.js +36 -0
  152. package/dist/{chunk-LS6BU5RM.js → chunk-ZKAQWXGO.js} +1 -1
  153. package/dist/{codex-app-cards-switch-5PWB62W3.js → codex-app-cards-switch-GN65VEKM.js} +11 -11
  154. package/dist/{codex-card-routing-I6YOJBTT.js → codex-card-routing-JTS75442.js} +2 -2
  155. package/dist/{codex-desktop-launch-BCPUKOCV.js → codex-desktop-launch-AQ2HSOQJ.js} +1 -1
  156. package/dist/{codex-session-launch-4ZUBROFZ.js → codex-session-launch-QYZZGVSQ.js} +20 -20
  157. package/dist/{config-2CHOLFNB.js → config-5ATI6KPI.js} +3 -3
  158. package/dist/{global-upgrade-4IKWJHLE.js → global-upgrade-K4HWVUMI.js} +9 -9
  159. package/dist/{identity-I2VWLZAQ.js → identity-V2GZCPJV.js} +4 -4
  160. package/dist/{live-capabilities-4CLCROSP.js → live-capabilities-PD62FO4K.js} +4 -4
  161. package/dist/{paths-YMHQKLFX.js → paths-WPJEIHUE.js} +7 -3
  162. package/dist/{reapply-FBQ7VR6L.js → reapply-ZEWMGDXT.js} +30 -29
  163. package/dist/src/index.js +34 -34
  164. package/dist/{upgrade-lock-7ONNXM6V.js → upgrade-lock-7OR6V323.js} +4 -4
  165. package/dist/{usage-GWUTCS5A.js → usage-GWZ3UGZG.js} +3 -3
  166. package/package.json +1 -1
  167. package/dist/chunk-I6HXZIER.js +0 -31
@@ -1,14 +1,34 @@
1
+ import {
2
+ OPENCLAW_PLUGIN_ID,
3
+ OPENCLAW_PLUGIN_PACKAGE,
4
+ currentOpenClawEnvironment,
5
+ enableOpenClawPlugin,
6
+ findOpenClawLauncher,
7
+ inspectOpenClawPlugin,
8
+ installOpenClawPluginFrom,
9
+ isOursToRemove,
10
+ openClawPathsNow,
11
+ openClawWiringState,
12
+ readOpenClawEntry,
13
+ uninstallOpenClawPlugin,
14
+ unsetOpenClawEntry,
15
+ writeOpenClawEntry
16
+ } from "./chunk-T2CR5REM.js";
1
17
  import {
2
18
  needsShell
3
19
  } from "./chunk-H6CL3T2S.js";
4
20
  import {
21
+ OPENCLAW_ENVIRONMENT_KEYS,
5
22
  hermesAppWiringRecord,
6
23
  hermesConfigReceipt,
7
- hermesSetupReceipt
8
- } from "./chunk-RPXSGCRG.js";
24
+ hermesSetupReceipt,
25
+ openClawDirectoriesToLookIn,
26
+ openClawPluginFolder,
27
+ openClawSetupReceiptDirectory
28
+ } from "./chunk-GJV5RVUU.js";
9
29
  import {
10
30
  resolvePathBinary
11
- } from "./chunk-5I3UQEAX.js";
31
+ } from "./chunk-BU2J4P7P.js";
12
32
  import {
13
33
  readJsonSafe,
14
34
  writeJsonAtomic
@@ -19,7 +39,7 @@ import {
19
39
  } from "./chunk-WIIMW5YO.js";
20
40
  import {
21
41
  isRecord
22
- } from "./chunk-C5LIS3XM.js";
42
+ } from "./chunk-6JBX55K4.js";
23
43
 
24
44
  // src/hermes/plugin-payload.ts
25
45
  import { createHash } from "crypto";
@@ -32,7 +52,7 @@ import os
32
52
  import threading
33
53
  from pathlib import Path
34
54
 
35
- from . import api, approval, history, host, identity, installation, schemas, tools
55
+ from . import api, approval, approval_coverage, history, host, identity, installation, schemas, tools
36
56
 
37
57
  logger = logging.getLogger(__name__)
38
58
 
@@ -125,6 +145,7 @@ def register(ctx):
125
145
  ctx.register_skill(child.name, skill_md)
126
146
 
127
147
  installation.record_plugin_load(transport)
148
+ _warn_when_hermes_skips_the_shell()
128
149
 
129
150
  logger.info(
130
151
  "[pushary] Plugin registered: %d tools, %d hooks, approval transport %s",
@@ -157,8 +178,14 @@ def _register_system_prompt_section(ctx):
157
178
 
158
179
 
159
180
  def _gated_tools():
160
- raw = os.environ.get("PUSHARY_GATE_TOOLS", "")
161
- return {name.strip().lower() for name in raw.split(",") if name.strip()}
181
+ raw = os.environ.get(approval_coverage.GATE_TOOLS_ENV, "")
182
+ return {name.strip().lower() for name in raw.split(approval_coverage.GATE_TOOLS_SEPARATOR) if name.strip()}
183
+
184
+
185
+ def _warn_when_hermes_skips_the_shell():
186
+ warning = approval_coverage.shell_gate_warning(os.environ, host.terminal_config(), _gated_tools())
187
+ if warning:
188
+ logger.warning(warning)
162
189
 
163
190
 
164
191
  def _egress_redactor():
@@ -949,6 +976,7 @@ def get_end_user_decision(decision_id, wait_seconds=45):
949
976
  seg = urllib.parse.quote(str(decision_id), safe="")
950
977
  return _rest_call("GET", f"/decisions/{seg}", params={"wait": wait_seconds})
951
978
  ` },
979
+ { path: "approval_coverage.py", contents: 'import json\nimport re\nfrom typing import AbstractSet, Any, List, Mapping, Optional\n\nHERMES_SHELL_TOOL = "terminal"\nGATE_TOOLS_ENV = "PUSHARY_GATE_TOOLS"\nTERMINAL_BACKEND_ENV = "TERMINAL_ENV"\nDOCKER_MOUNT_CWD_ENV = "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE"\nDOCKER_VOLUMES_ENV = "TERMINAL_DOCKER_VOLUMES"\n\nDEFAULT_BACKEND = "local"\nDOCKER_BACKEND = "docker"\nBACKENDS_THAT_SKIP_APPROVALS = frozenset({"modal", "daytona", "vercel_sandbox"})\n\nBACKEND_NAME = re.compile(r"^[a-z0-9_]+$")\nTRUE_WORDS = frozenset({"true", "1", "yes"})\nHOST_PATH_PREFIXES = ("/", "~", "./", "../")\nWINDOWS_DRIVE_SEPARATORS = ("/", "\\\\")\nGATE_TOOLS_SEPARATOR = ","\n\n\ndef _is_blank(value: Any) -> bool:\n return value is None or (isinstance(value, str) and not value.strip())\n\n\ndef _backend_name(value: Any) -> Optional[str]:\n if not isinstance(value, str):\n return None\n name = value.strip()\n return name if BACKEND_NAME.match(name) else None\n\n\ndef terminal_backend(environ: Mapping[str, str], terminal_config: Mapping[str, Any]) -> Optional[str]:\n for value in (environ.get(TERMINAL_BACKEND_ENV), terminal_config.get("backend")):\n if not _is_blank(value):\n return _backend_name(value)\n return DEFAULT_BACKEND\n\n\ndef _is_true(value: Any) -> bool:\n if isinstance(value, bool):\n return value\n if isinstance(value, int):\n return value == 1\n return isinstance(value, str) and value.strip().lower() in TRUE_WORDS\n\n\ndef volume_binds_host_path(spec: Any) -> bool:\n if not isinstance(spec, str):\n return False\n volume = spec.strip()\n if not volume:\n return False\n if volume.startswith(HOST_PATH_PREFIXES):\n return True\n return len(volume) >= 3 and volume[1] == ":" and volume[2] in WINDOWS_DRIVE_SEPARATORS\n\n\ndef _docker_volumes(environ: Mapping[str, str], terminal_config: Mapping[str, Any]) -> List[Any]:\n raw = environ.get(DOCKER_VOLUMES_ENV)\n volumes: Any = terminal_config.get("docker_volumes")\n if raw is not None:\n try:\n volumes = json.loads(raw)\n except ValueError:\n return []\n return volumes if isinstance(volumes, list) else []\n\n\ndef _docker_may_reach_host(environ: Mapping[str, str], terminal_config: Mapping[str, Any]) -> bool:\n mount = environ.get(DOCKER_MOUNT_CWD_ENV, terminal_config.get("docker_mount_cwd_to_workspace"))\n return _is_true(mount) or any(volume_binds_host_path(volume) for volume in _docker_volumes(environ, terminal_config))\n\n\ndef skips_dangerous_command_approvals(environ: Mapping[str, str], terminal_config: Mapping[str, Any]) -> bool:\n backend = terminal_backend(environ, terminal_config)\n if backend == DOCKER_BACKEND:\n return not _docker_may_reach_host(environ, terminal_config)\n return backend in BACKENDS_THAT_SKIP_APPROVALS\n\n\ndef _gate_tools_with_shell(environ: Mapping[str, str]) -> str:\n listed = [entry.strip() for entry in environ.get(GATE_TOOLS_ENV, "").split(GATE_TOOLS_SEPARATOR) if entry.strip()]\n return GATE_TOOLS_SEPARATOR.join([*listed, HERMES_SHELL_TOOL])\n\n\ndef shell_gate_warning(\n environ: Mapping[str, str],\n terminal_config: Mapping[str, Any],\n gated_tools: AbstractSet[str],\n) -> Optional[str]:\n if HERMES_SHELL_TOOL in gated_tools or not skips_dangerous_command_approvals(environ, terminal_config):\n return None\n backend = terminal_backend(environ, terminal_config)\n return (\n f"[pushary] Hermes skips its dangerous-command approvals on the {backend} terminal backend, "\n f"because it treats the container as the boundary. Pushary only gates the tools listed in "\n f"{GATE_TOOLS_ENV}, and {HERMES_SHELL_TOOL} is not one of them, so no shell command reaches "\n f"your phone. To gate them, run: hermes config set {GATE_TOOLS_ENV} {_gate_tools_with_shell(environ)} "\n f"and restart Hermes."\n )\n' },
952
980
  { path: "approval_ledger.py", contents: 'from __future__ import annotations\n\nimport json\nimport os\nimport re\nimport secrets\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Literal, Mapping, Optional, Set, Tuple, Union\n\nif TYPE_CHECKING:\n from typing_extensions import TypeGuard\n\nApprovalChoice = Literal["once", "session", "always", "deny"]\nRecordState = Literal["waiting", "settled"]\nClaimState = Literal["claiming", "won", "lost"]\nHandedBack = Literal["handed_to_hermes"]\nEnded = Literal["ended"]\nSettledOutcome = Union[ApprovalChoice, HandedBack]\nRecentOutcome = Union[SettledOutcome, Ended]\nDecider = Literal["hermes_desktop", "pushary_transport"]\nRefusedClaim = Literal["not_found", "not_waiting", "not_answerable_here", "not_offered", "already_claimed"]\nClaimResult = Union[Literal["claimed"], RefusedClaim]\nProcessIsRunning = Callable[[int], bool]\n\nAPPROVAL_CHOICES: Tuple[ApprovalChoice, ...] = ("once", "session", "always", "deny")\nWAITING: RecordState = "waiting"\nSETTLED: RecordState = "settled"\nCLAIMING: ClaimState = "claiming"\nWON: ClaimState = "won"\nLOST: ClaimState = "lost"\nCLAIM_STATES: Tuple[ClaimState, ...] = (CLAIMING, WON, LOST)\nHANDED_TO_HERMES: HandedBack = "handed_to_hermes"\nENDED: Ended = "ended"\nSETTLED_OUTCOMES: Tuple[SettledOutcome, ...] = (*APPROVAL_CHOICES, HANDED_TO_HERMES)\nRECENT_OUTCOMES: Tuple[RecentOutcome, ...] = (*SETTLED_OUTCOMES, ENDED)\nDECIDED_BY_DESKTOP: Decider = "hermes_desktop"\nDECIDED_BY_TRANSPORT: Decider = "pushary_transport"\n\nCLAIMED: Literal["claimed"] = "claimed"\nNOT_FOUND: RefusedClaim = "not_found"\nNOT_WAITING: RefusedClaim = "not_waiting"\nNOT_ANSWERABLE_HERE: RefusedClaim = "not_answerable_here"\nNOT_OFFERED: RefusedClaim = "not_offered"\nALREADY_CLAIMED: RefusedClaim = "already_claimed"\nREFUSED_CLAIMS: Tuple[RefusedClaim, ...] = (NOT_FOUND, NOT_WAITING, NOT_ANSWERABLE_HERE, NOT_OFFERED, ALREADY_CLAIMED)\n\nDESKTOP_ANSWER_SOURCE = "hermes_desktop"\nUNNAMED_ANSWER_SOURCE = "pushary"\n\nLEDGER_PATH = ("plugin-data", "pushary", "approvals")\nRECORD_SUFFIX = ".json"\nHOST_OUTCOME_PREFIX = "host-"\nTEMPORARY_PREFIX = "."\n\nCORRELATION_ID_PATTERN = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")\nREQUEST_ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,64}$")\nTOKEN_PATTERN = re.compile(r"^[a-z][a-z0-9_]{0,63}$")\n\nRETENTION_SECONDS = 24 * 60 * 60\nRECENT_LIMIT = 6\nSUBJECT_MAX = 200\nLABEL_MAX = 80\n\n\n@dataclass(frozen=True)\nclass OfferedChoice:\n choice: ApprovalChoice\n label: str\n\n\n@dataclass(frozen=True)\nclass OpenedApproval:\n correlation_id: str\n request_id: Optional[str]\n subject: str\n choices: Tuple[OfferedChoice, ...]\n pid: int\n opened_at_ms: int\n deadline_at_ms: int\n\n\n@dataclass(frozen=True)\nclass WaitingRecord:\n opened: OpenedApproval\n\n\n@dataclass(frozen=True)\nclass SettledRecord:\n opened: OpenedApproval\n outcome: SettledOutcome\n answer_source: Optional[str]\n settled_at_ms: int\n\n\nApprovalRecord = Union[WaitingRecord, SettledRecord]\n\n\n@dataclass(frozen=True)\nclass HostOutcome:\n request_id: str\n choice: str\n at_ms: int\n\n\n@dataclass(frozen=True)\nclass WaitingApproval:\n correlation_id: str\n subject: str\n choices: Tuple[OfferedChoice, ...]\n opened_at_ms: int\n deadline_at_ms: int\n answerable_here: bool\n routed_to: Optional[str]\n claim: Optional[ClaimState]\n\n\n@dataclass(frozen=True)\nclass RecentApproval:\n correlation_id: str\n subject: str\n opened_at_ms: int\n settled_at_ms: int\n outcome: RecentOutcome\n answer_source: Optional[str]\n host_outcome: Optional[str]\n\n\n@dataclass(frozen=True)\nclass ApprovalsView:\n waiting: Tuple[WaitingApproval, ...]\n recent: Tuple[RecentApproval, ...]\n\n\ndef is_correlation_id(value: object) -> TypeGuard[str]:\n return isinstance(value, str) and CORRELATION_ID_PATTERN.fullmatch(value) is not None\n\n\ndef is_request_id(value: object) -> TypeGuard[str]:\n return isinstance(value, str) and REQUEST_ID_PATTERN.fullmatch(value) is not None\n\n\ndef is_token(value: object) -> TypeGuard[str]:\n return isinstance(value, str) and TOKEN_PATTERN.fullmatch(value) is not None\n\n\ndef approval_choice(value: object) -> Optional[ApprovalChoice]:\n for choice in APPROVAL_CHOICES:\n if value == choice:\n return choice\n return None\n\n\ndef _record_state(value: object) -> Optional[RecordState]:\n for state in (WAITING, SETTLED):\n if value == state:\n return state\n return None\n\n\ndef _settled_outcome(value: object) -> Optional[SettledOutcome]:\n for outcome in SETTLED_OUTCOMES:\n if value == outcome:\n return outcome\n return None\n\n\ndef _instant(value: object) -> Optional[int]:\n return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None\n\n\ndef _bounded_text(value: object, limit: int) -> Optional[str]:\n return value if isinstance(value, str) and len(value) <= limit else None\n\n\ndef _fields(value: object) -> Optional[Mapping[object, object]]:\n return value if isinstance(value, dict) else None\n\n\ndef offered_choices(pairs: Iterable[Tuple[str, str]]) -> Tuple[OfferedChoice, ...]:\n offered = []\n for raw_choice, raw_label in pairs:\n choice = approval_choice(raw_choice)\n if choice is not None:\n offered.append(OfferedChoice(choice, str(raw_label)[:LABEL_MAX]))\n return tuple(offered)\n\n\ndef _parse_offered(value: object) -> Optional[OfferedChoice]:\n fields = _fields(value)\n if fields is None:\n return None\n choice = approval_choice(fields.get("choice"))\n label = _bounded_text(fields.get("label"), LABEL_MAX)\n return OfferedChoice(choice, label) if choice is not None and label is not None else None\n\n\ndef _parse_choices(value: object) -> Optional[Tuple[OfferedChoice, ...]]:\n if not isinstance(value, list):\n return None\n parsed: List[OfferedChoice] = []\n for item in value:\n offered = _parse_offered(item)\n if offered is None:\n return None\n parsed.append(offered)\n return tuple(parsed)\n\n\ndef _parse_opened(fields: Mapping[object, object]) -> Optional[OpenedApproval]:\n correlation_id = fields.get("correlationId")\n request_id = fields.get("requestId")\n subject = _bounded_text(fields.get("subject"), SUBJECT_MAX)\n choices = _parse_choices(fields.get("choices"))\n pid = fields.get("pid")\n opened_at_ms = _instant(fields.get("openedAtMs"))\n deadline_at_ms = _instant(fields.get("deadlineAtMs"))\n if not is_correlation_id(correlation_id):\n return None\n if request_id is not None and not is_request_id(request_id):\n return None\n if (\n subject is None\n or not choices\n or not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0\n or opened_at_ms is None\n or deadline_at_ms is None\n ):\n return None\n return OpenedApproval(\n correlation_id=correlation_id,\n request_id=request_id,\n subject=subject,\n choices=choices,\n pid=pid,\n opened_at_ms=opened_at_ms,\n deadline_at_ms=deadline_at_ms,\n )\n\n\ndef parse_record(value: object) -> Optional[ApprovalRecord]:\n fields = _fields(value)\n if fields is None:\n return None\n opened = _parse_opened(fields)\n state = _record_state(fields.get("state"))\n if opened is None or state is None:\n return None\n if state == WAITING:\n return WaitingRecord(opened)\n outcome = _settled_outcome(fields.get("outcome"))\n settled_at_ms = _instant(fields.get("settledAtMs"))\n answer_source = fields.get("answerSource")\n if outcome is None or settled_at_ms is None:\n return None\n if answer_source is not None and not is_token(answer_source):\n return None\n return SettledRecord(opened, outcome, answer_source, settled_at_ms)\n\n\ndef parse_host_outcome(value: object) -> Optional[HostOutcome]:\n fields = _fields(value)\n if fields is None:\n return None\n request_id = fields.get("requestId")\n choice = fields.get("choice")\n at_ms = _instant(fields.get("atMs"))\n if not is_request_id(request_id) or not is_token(choice) or at_ms is None:\n return None\n return HostOutcome(request_id, choice, at_ms)\n\n\ndef _offered_json(choice: OfferedChoice) -> Dict[str, object]:\n return {"choice": choice.choice, "label": choice.label}\n\n\ndef _opened_json(opened: OpenedApproval) -> Dict[str, object]:\n return {\n "correlationId": opened.correlation_id,\n "requestId": opened.request_id,\n "subject": opened.subject,\n "choices": [_offered_json(choice) for choice in opened.choices],\n "pid": opened.pid,\n "openedAtMs": opened.opened_at_ms,\n "deadlineAtMs": opened.deadline_at_ms,\n }\n\n\ndef _record_json(record: ApprovalRecord) -> Dict[str, object]:\n stored = _opened_json(record.opened)\n if isinstance(record, WaitingRecord):\n stored["state"] = WAITING\n return stored\n stored.update(state=SETTLED, outcome=record.outcome, answerSource=record.answer_source,\n settledAtMs=record.settled_at_ms)\n return stored\n\n\ndef _host_outcome_json(outcome: HostOutcome) -> Dict[str, object]:\n return {"requestId": outcome.request_id, "choice": outcome.choice, "atMs": outcome.at_ms}\n\n\ndef ledger_directory(home: Path) -> Path:\n return Path(home).joinpath(*LEDGER_PATH)\n\n\ndef _record_path(home: Path, correlation_id: str) -> Path:\n return ledger_directory(home) / f"{correlation_id}{RECORD_SUFFIX}"\n\n\ndef _host_outcome_path(home: Path, request_id: str) -> Path:\n return ledger_directory(home) / f"{HOST_OUTCOME_PREFIX}{request_id}{RECORD_SUFFIX}"\n\n\ndef _ensure_parent(path: Path) -> None:\n path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)\n\n\ndef _staged_json(path: Path, value: Dict[str, object]) -> Path:\n _ensure_parent(path)\n staged = path.with_name(f"{TEMPORARY_PREFIX}{path.name}.{secrets.token_hex(8)}.tmp")\n try:\n with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle:\n json.dump(value, handle)\n except BaseException:\n staged.unlink(missing_ok=True)\n raise\n return staged\n\n\ndef _replace_json(path: Path, value: Dict[str, object]) -> None:\n staged = _staged_json(path, value)\n try:\n os.replace(staged, path)\n finally:\n staged.unlink(missing_ok=True)\n\n\ndef _read_json(path: Path) -> object:\n try:\n return json.loads(path.read_text(encoding="utf-8"))\n except (OSError, ValueError):\n return None\n\n\ndef read_record(home: Path, correlation_id: str) -> Optional[ApprovalRecord]:\n if not is_correlation_id(correlation_id):\n return None\n record = parse_record(_read_json(_record_path(home, correlation_id)))\n return record if record is not None and record.opened.correlation_id == correlation_id else None\n\n\ndef read_host_outcome(home: Path, request_id: Optional[str]) -> Optional[HostOutcome]:\n if not is_request_id(request_id):\n return None\n outcome = parse_host_outcome(_read_json(_host_outcome_path(home, request_id)))\n return outcome if outcome is not None and outcome.request_id == request_id else None\n\n\ndef open_approval(\n home: Path,\n *,\n correlation_id: str,\n request_id: Optional[str],\n subject: str,\n choices: Tuple[OfferedChoice, ...],\n pid: int,\n opened_at_ms: int,\n deadline_at_ms: int,\n) -> bool:\n if not is_correlation_id(correlation_id) or pid <= 0 or not choices:\n return False\n opened = OpenedApproval(\n correlation_id=correlation_id,\n request_id=request_id if is_request_id(request_id) else None,\n subject=subject[:SUBJECT_MAX],\n choices=choices,\n pid=pid,\n opened_at_ms=opened_at_ms,\n deadline_at_ms=deadline_at_ms,\n )\n _replace_json(_record_path(home, correlation_id), _record_json(WaitingRecord(opened)))\n return True\n\n\ndef settle_approval(\n home: Path,\n correlation_id: str,\n *,\n outcome: SettledOutcome,\n answer_source: Optional[str],\n settled_at_ms: int,\n) -> bool:\n record = read_record(home, correlation_id)\n if not isinstance(record, WaitingRecord):\n return False\n source = answer_source if is_token(answer_source) else None\n _replace_json(_record_path(home, correlation_id), _record_json(SettledRecord(record.opened, outcome, source,\n settled_at_ms)))\n return True\n\n\ndef record_host_outcome(home: Path, request_id: str, choice: str, at_ms: int) -> bool:\n if not is_request_id(request_id) or not is_token(choice):\n return False\n _replace_json(_host_outcome_path(home, request_id), _host_outcome_json(HostOutcome(request_id, choice, at_ms)))\n return True\n\n\ndef host_has_finished(home: Path, request_id: Optional[str]) -> bool:\n return read_host_outcome(home, request_id) is not None\n\n\ndef _owner_is_running(opened: OpenedApproval, process_is_running: ProcessIsRunning) -> bool:\n return opened.pid > 0 and process_is_running(opened.pid)\n\n\ndef _is_live(record: ApprovalRecord, host_outcome: Optional[HostOutcome], now_ms: int,\n process_is_running: ProcessIsRunning) -> bool:\n return (\n isinstance(record, WaitingRecord)\n and host_outcome is None\n and now_ms < record.opened.deadline_at_ms\n and _owner_is_running(record.opened, process_is_running)\n )\n\n\ndef _waiting_elsewhere(record: WaitingRecord) -> WaitingApproval:\n opened = record.opened\n return WaitingApproval(\n correlation_id=opened.correlation_id,\n subject=opened.subject,\n choices=opened.choices,\n opened_at_ms=opened.opened_at_ms,\n deadline_at_ms=opened.deadline_at_ms,\n answerable_here=False,\n routed_to=None,\n claim=None,\n )\n\n\ndef _recent(record: ApprovalRecord, host_outcome: Optional[HostOutcome]) -> RecentApproval:\n opened = record.opened\n if isinstance(record, SettledRecord):\n outcome: RecentOutcome = record.outcome\n settled_at_ms = record.settled_at_ms\n answer_source = record.answer_source\n else:\n outcome = ENDED\n settled_at_ms = host_outcome.at_ms if host_outcome else opened.deadline_at_ms\n answer_source = None\n return RecentApproval(\n correlation_id=opened.correlation_id,\n subject=opened.subject,\n opened_at_ms=opened.opened_at_ms,\n settled_at_ms=settled_at_ms,\n outcome=outcome,\n answer_source=answer_source,\n host_outcome=host_outcome.choice if host_outcome else None,\n )\n\n\ndef approvals_view(\n records: Iterable[ApprovalRecord],\n host_outcomes: Mapping[str, HostOutcome],\n now_ms: int,\n process_is_running: ProcessIsRunning,\n) -> ApprovalsView:\n waiting = []\n recent = []\n for record in records:\n request_id = record.opened.request_id\n host_outcome = host_outcomes.get(request_id) if request_id else None\n if isinstance(record, WaitingRecord) and _is_live(record, host_outcome, now_ms, process_is_running):\n waiting.append(_waiting_elsewhere(record))\n else:\n recent.append(_recent(record, host_outcome))\n waiting.sort(key=lambda item: item.opened_at_ms)\n recent.sort(key=lambda item: item.settled_at_ms, reverse=True)\n return ApprovalsView(waiting=tuple(waiting), recent=tuple(recent[:RECENT_LIMIT]))\n\n\ndef _ledger_files(home: Path) -> List[Path]:\n try:\n return [path for path in ledger_directory(home).iterdir() if path.is_file()]\n except OSError:\n return []\n\n\ndef _correlation_id_of(name: str) -> Optional[str]:\n candidate = name[: -len(RECORD_SUFFIX)] if name.endswith(RECORD_SUFFIX) else None\n return candidate if is_correlation_id(candidate) else None\n\n\ndef _ledger_entries(home: Path) -> List[Tuple[Path, object]]:\n return [(path, _read_json(path)) for path in _ledger_files(home) if not path.name.startswith(TEMPORARY_PREFIX)]\n\n\ndef read_approvals(home: Path, now_ms: int, process_is_running: ProcessIsRunning) -> ApprovalsView:\n records: List[ApprovalRecord] = []\n host_outcomes: Dict[str, HostOutcome] = {}\n for path, value in _ledger_entries(home):\n name = path.name\n if name.startswith(HOST_OUTCOME_PREFIX):\n host_outcome = parse_host_outcome(value)\n if host_outcome is not None:\n host_outcomes[host_outcome.request_id] = host_outcome\n else:\n record = parse_record(value)\n if record is not None and name == f"{record.opened.correlation_id}{RECORD_SUFFIX}":\n records.append(record)\n return approvals_view(records, host_outcomes, now_ms, process_is_running)\n\n\ndef _unexpired_waiting(home: Path, now_ms: int) -> Set[str]:\n kept: Set[str] = set()\n for path, value in _ledger_entries(home):\n if path.name.startswith(HOST_OUTCOME_PREFIX) or not path.name.endswith(RECORD_SUFFIX):\n continue\n record = parse_record(value)\n if isinstance(record, WaitingRecord) and record.opened.deadline_at_ms > now_ms:\n kept.add(record.opened.correlation_id)\n return kept\n\n\ndef prune(home: Path, now_seconds: float) -> None:\n kept = _unexpired_waiting(home, int(now_seconds * 1000))\n for path in _ledger_files(home):\n if _correlation_id_of(path.name) in kept:\n continue\n try:\n if now_seconds - path.stat().st_mtime > RETENTION_SECONDS:\n path.unlink(missing_ok=True)\n except OSError:\n continue\n' },
953
981
  { path: "approval.py", contents: `import logging
954
982
  import os
@@ -957,10 +985,10 @@ import time
957
985
  from typing import Literal, Optional, Tuple
958
986
 
959
987
  from . import api, approval_ledger, cancellation, desktop_answers, desktop_contract, identity, installation
988
+ from .approval_coverage import HERMES_SHELL_TOOL
960
989
 
961
990
  logger = logging.getLogger(__name__)
962
991
 
963
- HERMES_SHELL_TOOL = "terminal"
964
992
  DECISION_LINE_MAX = 500
965
993
  ACTION_BODY_MAX = 4000
966
994
 
@@ -1313,7 +1341,7 @@ def _await_decision(request, created, correlation_id: str, offered, uses_select:
1313
1341
  return _decided(request, correlation_id, "deny", None)
1314
1342
  ` },
1315
1343
  { path: "cancellation.py", contents: 'from __future__ import annotations\n\nfrom typing import Literal, Mapping, Tuple\n\nCancellation = Literal[\n "withdrawn_by_this_call",\n "cancelled_unproven",\n "already_cancelled",\n "not_pending",\n "unreachable",\n]\n\nWITHDRAWN_BY_THIS_CALL: Cancellation = "withdrawn_by_this_call"\nCANCELLED_UNPROVEN: Cancellation = "cancelled_unproven"\nALREADY_CANCELLED: Cancellation = "already_cancelled"\nNOT_PENDING: Cancellation = "not_pending"\nUNREACHABLE: Cancellation = "unreachable"\nCANCELLATIONS: Tuple[Cancellation, ...] = (\n WITHDRAWN_BY_THIS_CALL,\n CANCELLED_UNPROVEN,\n ALREADY_CANCELLED,\n NOT_PENDING,\n UNREACHABLE,\n)\n\nUNAVAILABLE_STATUS = "unavailable"\nSTOP_HANDOFF = "stop"\n\n\ndef classify_cancellation(response: object) -> Cancellation:\n if not isinstance(response, Mapping):\n return UNREACHABLE\n fields: Mapping[object, object] = response\n cancelled = fields.get("cancelled")\n by_this_call = fields.get("cancelledByThisCall")\n if (\n not isinstance(cancelled, bool)\n or fields.get("status") == UNAVAILABLE_STATUS\n or fields.get("handoffAction") == STOP_HANDOFF\n or (by_this_call is not None and not isinstance(by_this_call, bool))\n or (by_this_call is True and not cancelled)\n ):\n return UNREACHABLE\n if not cancelled:\n return NOT_PENDING\n if by_this_call is None:\n return CANCELLED_UNPROVEN\n return WITHDRAWN_BY_THIS_CALL if by_this_call else ALREADY_CANCELLED\n' },
1316
- { path: "dashboard/manifest.json", contents: '{\n "name": "pushary",\n "label": "Pushary",\n "description": "Approvals Pushary is carrying to your phone, answerable from Hermes Desktop",\n "version": "1.0.1",\n "tab": { "hidden": true },\n "entry": "web.js",\n "api": "plugin_api.py"\n}\n' },
1344
+ { path: "dashboard/manifest.json", contents: '{\n "name": "pushary",\n "label": "Pushary",\n "description": "Approvals Pushary is carrying to your phone, answerable from Hermes Desktop",\n "version": "1.0.2",\n "tab": { "hidden": true },\n "entry": "web.js",\n "api": "plugin_api.py"\n}\n' },
1317
1345
  { path: "dashboard/plugin_api.py", contents: `import importlib
1318
1346
  import sys
1319
1347
  import time
@@ -1967,7 +1995,7 @@ def stop_history(session_id: str) -> None:
1967
1995
  if thread.is_alive():
1968
1996
  logger.warning("[pushary] Hermes final history export is still pending")
1969
1997
  ` },
1970
- { path: "host.py", contents: 'import os\n\nTRANSPORT_NAME = "pushary"\n\nHOOK_TIMEOUT_DEFAULT_SECONDS = 30.0\nHOOK_TIMEOUT_MAX_SECONDS = 600.0\n\nGATE_HEADROOM_SECONDS = 5.0\nGATE_MIN_SECONDS = 5.0\nGATE_MAX_SECONDS = 55.0\n\n# The last Hermes that runs a pre_tool_call callback to completion. Anything\n# after this abandons one that outlives plugins.hook_callback_timeout.\nUNBOUNDED_THROUGH_VERSION = (0, 20, 5)\n\n\ndef _config():\n try:\n from hermes_cli.config import load_config_readonly\n\n loaded = load_config_readonly()\n except Exception:\n return {}\n return loaded if isinstance(loaded, dict) else {}\n\n\ndef _section(node, *path):\n for key in path:\n node = node.get(key) if isinstance(node, dict) else None\n if node is None:\n return {}\n return node if isinstance(node, dict) else {}\n\n\ndef profile_secret(name):\n try:\n from agent.secret_scope import get_secret\n except Exception:\n return os.environ.get(name) or None\n try:\n return get_secret(name) or None\n except Exception:\n return None\n\n\ndef hermes_version_label():\n try:\n from importlib.metadata import version\n\n return version("hermes-cli")\n except Exception:\n try:\n import hermes_cli\n\n label = getattr(hermes_cli, "__version__", None)\n except Exception:\n return None\n return str(label) if label else None\n\n\ndef _hermes_version():\n """This Hermes as a comparable tuple, or None when it will not say."""\n raw = hermes_version_label()\n if not raw:\n return None\n parts = []\n for piece in str(raw).split(".")[:3]:\n digits = ""\n for char in piece:\n if not char.isdigit():\n break\n digits += char\n if not digits:\n return None\n parts.append(int(digits))\n while len(parts) < 3:\n parts.append(0)\n return tuple(parts)\n\n\ndef bounds_pre_tool_call():\n """Whether this Hermes abandons a slow pre_tool_call callback.\n\n The timeout was added after 0.20.5, which runs plugin hooks to completion.\n Clamping the wait on a host that would never have cut it off just shortens\n the window the user has to answer, for nothing.\n\n Unreadable means assume bounded. A wait that is shorter than it had to be\n costs the user seconds; a wait longer than the host allows costs them the\n answer they already gave.\n\n That rule is why the private symbol is not asked on its own. `hasattr` on\n `_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS` cannot tell "this host runs hooks to\n completion" apart from "the private name moved", and those two answers want\n opposite behaviour: the first earns the full window, the second spends 55\n seconds against a budget of 30 and loses an answer the user already gave.\n A rename is the likelier of the two, because a private name is the one thing\n a host is free to change. So the symbol is taken as proof of bounded, and\n only a version this side of the timeout landing is taken as proof of the\n other. Anything unreadable falls to bounded.\n """\n try:\n from hermes_cli import plugins\n except Exception:\n return True\n if hasattr(plugins, "_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS"):\n return True\n version = _hermes_version()\n if version is None:\n return True\n return version > UNBOUNDED_THROUGH_VERSION\n\n\ndef hook_callback_timeout_seconds():\n raw = _section(_config(), "plugins").get("hook_callback_timeout")\n if raw is None:\n return HOOK_TIMEOUT_DEFAULT_SECONDS\n try:\n timeout = float(raw)\n except (TypeError, ValueError):\n return HOOK_TIMEOUT_DEFAULT_SECONDS\n if timeout < 0:\n return HOOK_TIMEOUT_DEFAULT_SECONDS\n return min(timeout, HOOK_TIMEOUT_MAX_SECONDS)\n\n\ndef gate_budget_seconds(requested_seconds):\n if not bounds_pre_tool_call():\n return max(1.0, min(float(requested_seconds), GATE_MAX_SECONDS))\n timeout = hook_callback_timeout_seconds()\n ceiling = (\n GATE_MAX_SECONDS\n if timeout <= 0\n else max(GATE_MIN_SECONDS, timeout - GATE_HEADROOM_SECONDS)\n )\n return max(1.0, min(float(requested_seconds), ceiling, GATE_MAX_SECONDS))\n\n\ndef pushary_is_selected_transport():\n selected = _section(_config(), "security", "approval").get("transport")\n return str(selected or "").strip().lower() == TRANSPORT_NAME\n' },
1998
+ { path: "host.py", contents: 'import os\n\nTRANSPORT_NAME = "pushary"\n\nHOOK_TIMEOUT_DEFAULT_SECONDS = 30.0\nHOOK_TIMEOUT_MAX_SECONDS = 600.0\n\nGATE_HEADROOM_SECONDS = 5.0\nGATE_MIN_SECONDS = 5.0\nGATE_MAX_SECONDS = 55.0\n\n# The last Hermes that runs a pre_tool_call callback to completion. Anything\n# after this abandons one that outlives plugins.hook_callback_timeout.\nUNBOUNDED_THROUGH_VERSION = (0, 20, 5)\n\n\ndef _config():\n try:\n from hermes_cli.config import load_config_readonly\n\n loaded = load_config_readonly()\n except Exception:\n return {}\n return loaded if isinstance(loaded, dict) else {}\n\n\ndef _section(node, *path):\n for key in path:\n node = node.get(key) if isinstance(node, dict) else None\n if node is None:\n return {}\n return node if isinstance(node, dict) else {}\n\n\ndef profile_secret(name):\n try:\n from agent.secret_scope import get_secret\n except Exception:\n return os.environ.get(name) or None\n try:\n return get_secret(name) or None\n except Exception:\n return None\n\n\ndef hermes_version_label():\n try:\n from importlib.metadata import version\n\n return version("hermes-cli")\n except Exception:\n try:\n import hermes_cli\n\n label = getattr(hermes_cli, "__version__", None)\n except Exception:\n return None\n return str(label) if label else None\n\n\ndef _hermes_version():\n """This Hermes as a comparable tuple, or None when it will not say."""\n raw = hermes_version_label()\n if not raw:\n return None\n parts = []\n for piece in str(raw).split(".")[:3]:\n digits = ""\n for char in piece:\n if not char.isdigit():\n break\n digits += char\n if not digits:\n return None\n parts.append(int(digits))\n while len(parts) < 3:\n parts.append(0)\n return tuple(parts)\n\n\ndef bounds_pre_tool_call():\n """Whether this Hermes abandons a slow pre_tool_call callback.\n\n The timeout was added after 0.20.5, which runs plugin hooks to completion.\n Clamping the wait on a host that would never have cut it off just shortens\n the window the user has to answer, for nothing.\n\n Unreadable means assume bounded. A wait that is shorter than it had to be\n costs the user seconds; a wait longer than the host allows costs them the\n answer they already gave.\n\n That rule is why the private symbol is not asked on its own. `hasattr` on\n `_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS` cannot tell "this host runs hooks to\n completion" apart from "the private name moved", and those two answers want\n opposite behaviour: the first earns the full window, the second spends 55\n seconds against a budget of 30 and loses an answer the user already gave.\n A rename is the likelier of the two, because a private name is the one thing\n a host is free to change. So the symbol is taken as proof of bounded, and\n only a version this side of the timeout landing is taken as proof of the\n other. Anything unreadable falls to bounded.\n """\n try:\n from hermes_cli import plugins\n except Exception:\n return True\n if hasattr(plugins, "_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS"):\n return True\n version = _hermes_version()\n if version is None:\n return True\n return version > UNBOUNDED_THROUGH_VERSION\n\n\ndef hook_callback_timeout_seconds():\n raw = _section(_config(), "plugins").get("hook_callback_timeout")\n if raw is None:\n return HOOK_TIMEOUT_DEFAULT_SECONDS\n try:\n timeout = float(raw)\n except (TypeError, ValueError):\n return HOOK_TIMEOUT_DEFAULT_SECONDS\n if timeout < 0:\n return HOOK_TIMEOUT_DEFAULT_SECONDS\n return min(timeout, HOOK_TIMEOUT_MAX_SECONDS)\n\n\ndef gate_budget_seconds(requested_seconds):\n if not bounds_pre_tool_call():\n return max(1.0, min(float(requested_seconds), GATE_MAX_SECONDS))\n timeout = hook_callback_timeout_seconds()\n ceiling = (\n GATE_MAX_SECONDS\n if timeout <= 0\n else max(GATE_MIN_SECONDS, timeout - GATE_HEADROOM_SECONDS)\n )\n return max(1.0, min(float(requested_seconds), ceiling, GATE_MAX_SECONDS))\n\n\ndef terminal_config():\n return _section(_config(), "terminal")\n\n\ndef pushary_is_selected_transport():\n selected = _section(_config(), "security", "approval").get("transport")\n return str(selected or "").strip().lower() == TRANSPORT_NAME\n' },
1971
1999
  { path: "identity.py", contents: 'import hashlib\nimport os\nimport re\nimport socket\nfrom pathlib import Path\n\nDEFAULT_AGENT_NAME = "Hermes"\nMAX_ID_LENGTH = 128\nSHARED_MACHINE_ID_FILE = Path.home() / ".pushary" / "machine-id"\nSHARED_MACHINE_ID_PATTERN = re.compile(r"^[A-Za-z0-9-]{1,128}$")\n\n_session_id = None\n\n\ndef agent_name():\n return os.environ.get("PUSHARY_AGENT_NAME", DEFAULT_AGENT_NAME)\n\n\ndef labelled_agent_name(requested):\n project = str(requested or "").partition(" - ")[2].strip()\n return f"{agent_name()} - {project}" if project else agent_name()\n\n\ndef shared_machine_id(path=None):\n try:\n value = (path or SHARED_MACHINE_ID_FILE).read_text(encoding="utf-8").strip()\n except OSError:\n return None\n return value if SHARED_MACHINE_ID_PATTERN.match(value) else None\n\n\ndef hostname_machine_id():\n try:\n host = socket.gethostname()\n except Exception:\n return None\n if not host:\n return None\n return hashlib.sha256(host.encode("utf-8")).hexdigest()[:8]\n\n\ndef machine_id():\n return shared_machine_id() or hostname_machine_id()\n\n\ndef remember_session(value):\n global _session_id\n if value:\n _session_id = str(value)[:MAX_ID_LENGTH]\n\n\ndef forget_session():\n global _session_id\n _session_id = None\n\n\ndef session_id():\n return _session_id\n' },
1972
2000
  { path: "installation.py", contents: `import json
1973
2001
  import logging
@@ -2098,7 +2126,7 @@ def record_plugin_load(approval_transport_registered, home=None, pid=None, now=N
2098
2126
  logger.debug("[pushary] could not record the plugin load: %s", exc)
2099
2127
  return None
2100
2128
  ` },
2101
- { path: "plugin.yaml", contents: 'name: pushary\nversion: 1.0.1\ndescription: Push notifications and human-in-the-loop for Hermes Agent via Pushary\nauthor: RalphNex OU\nrequires_env:\n - name: PUSHARY_API_KEY\n description: Your Pushary API key\n url: https://pushary.com/sign-up?from=hermes\n secret: true\nconfig_schema:\n api_key:\n type: secret\n env: PUSHARY_API_KEY\n label: Pushary API key\n description: "Get one at pushary.com/sign-up?from=hermes"\n required: true\nprovides_tools:\n - pushary_remind\n - pushary_notify\n - pushary_ask\n - pushary_wait\n - pushary_cancel\n - pushary_propose_scope\n - pushary_enroll\n - pushary_ask_end_user\nprovides_hooks:\n - pre_llm_call\n - pre_tool_call\n - post_tool_call\n - on_session_start\n - on_session_end\n - on_session_finalize\n - post_approval_response\nprovides_approval_transports:\n - pushary\n' },
2129
+ { path: "plugin.yaml", contents: 'name: pushary\nversion: 1.0.2\ndescription: Push notifications and human-in-the-loop for Hermes Agent via Pushary\nauthor: RalphNex OU\nrequires_env:\n - name: PUSHARY_API_KEY\n description: Your Pushary API key\n url: https://pushary.com/sign-up?from=hermes\n secret: true\nconfig_schema:\n api_key:\n type: secret\n env: PUSHARY_API_KEY\n label: Pushary API key\n description: "Get one at pushary.com/sign-up?from=hermes"\n required: true\nprovides_tools:\n - pushary_remind\n - pushary_notify\n - pushary_ask\n - pushary_wait\n - pushary_cancel\n - pushary_propose_scope\n - pushary_enroll\n - pushary_ask_end_user\nprovides_hooks:\n - pre_llm_call\n - pre_tool_call\n - post_tool_call\n - on_session_start\n - on_session_end\n - on_session_finalize\n - post_approval_response\nprovides_approval_transports:\n - pushary\n' },
2102
2130
  { path: "schemas.py", contents: `PUSHARY_REMIND = {
2103
2131
  "name": "pushary_remind",
2104
2132
  "description": "Schedule a one-time personal reminder on Pushary, even after Hermes exits. Use body plus in_minutes or at (ISO timestamp with explicit UTC offset, within 30 days). Never guess the user's timezone. Confirm the returned time. No arguments lists pending reminders; cancel_reminder_id cancels a scheduled one. Use Hermes cron for agent work; use this for reminding the operator.",
@@ -2743,6 +2771,135 @@ var shippedHermesPlugin = (files = HERMES_PLUGIN_FILES) => {
2743
2771
  return { files, version, digest: hermesPluginDigest(files) };
2744
2772
  };
2745
2773
 
2774
+ // src/hermes/approval-coverage.ts
2775
+ var HERMES_TERMINAL_SECTION = "terminal";
2776
+ var HERMES_TERMINAL_ENV_KEY = "TERMINAL_ENV";
2777
+ var HERMES_GATE_TOOLS_KEY = "PUSHARY_GATE_TOOLS";
2778
+ var HERMES_SHELL_TOOL = "terminal";
2779
+ var HERMES_DOCKER_VOLUMES_KEY = "TERMINAL_DOCKER_VOLUMES";
2780
+ var HERMES_DOCKER_MOUNT_CWD_KEY = "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE";
2781
+ var HERMES_COMMAND_ALLOWLIST_KEY = "command_allowlist";
2782
+ var HERMES_ALWAYS_ALLOWED_SHELL_RULE = `plugin_rule:${HERMES_SHELL_TOOL}`;
2783
+ var HERMES_DEFAULT_BACKEND = "local";
2784
+ var HERMES_DOCKER_BACKEND = "docker";
2785
+ var BACKENDS_WHERE_HERMES_ASKS = /* @__PURE__ */ new Set(["local", "ssh"]);
2786
+ var BACKENDS_WHERE_HERMES_SKIPS = /* @__PURE__ */ new Set(["modal", "daytona", "vercel_sandbox"]);
2787
+ var BACKEND_NAME = /^[a-z0-9_]+$/;
2788
+ var TRUE_WORDS = /* @__PURE__ */ new Set(["true", "1", "yes"]);
2789
+ var HOST_PATH_PREFIXES = ["/", "~", "./", "../"];
2790
+ var WINDOWS_DRIVE_PATH = /^.:[/\\]/;
2791
+ var GATE_TOOLS_SEPARATOR = ",";
2792
+ var ABSENT = { kind: "absent" };
2793
+ var MALFORMED = { kind: "malformed" };
2794
+ var backendNameOf = (value) => {
2795
+ if (value === void 0 || value === null) return ABSENT;
2796
+ if (typeof value !== "string") return MALFORMED;
2797
+ const name = value.trim();
2798
+ if (name === "") return ABSENT;
2799
+ return BACKEND_NAME.test(name) ? { kind: "named", name } : MALFORMED;
2800
+ };
2801
+ var terminalSectionOf = (reading) => {
2802
+ if (reading.kind === "unset") return { kind: "read", section: {} };
2803
+ return isRecord(reading.value) ? { kind: "read", section: reading.value } : { kind: "malformed" };
2804
+ };
2805
+ var environmentBackendOf = (reading) => reading.kind === "unset" ? ABSENT : backendNameOf(reading.value);
2806
+ var effectiveBackend = (configured, environment) => {
2807
+ if (configured.kind === "malformed") return MALFORMED;
2808
+ if (configured.kind === "named" && configured.name !== HERMES_DEFAULT_BACKEND) return configured;
2809
+ if (environment.kind !== "absent") return environment;
2810
+ return { kind: "named", name: HERMES_DEFAULT_BACKEND };
2811
+ };
2812
+ var isTrueSetting = (value) => value === true || value === 1 || typeof value === "string" && TRUE_WORDS.has(value.trim().toLowerCase());
2813
+ var bindsHostPath = (volume) => {
2814
+ if (typeof volume !== "string") return false;
2815
+ const spec = volume.trim();
2816
+ return spec !== "" && (HOST_PATH_PREFIXES.some((prefix) => spec.startsWith(prefix)) || WINDOWS_DRIVE_PATH.test(spec));
2817
+ };
2818
+ var effectiveValue = (reading, configured) => reading.kind === "set" ? reading.value : configured;
2819
+ var volumeListOf = (value) => {
2820
+ if (typeof value !== "string") return value;
2821
+ try {
2822
+ return JSON.parse(value);
2823
+ } catch {
2824
+ return null;
2825
+ }
2826
+ };
2827
+ var mountsHostVolume = (access) => {
2828
+ const volumes = volumeListOf(access.volumes);
2829
+ return Array.isArray(volumes) && volumes.some(bindsHostPath);
2830
+ };
2831
+ var dockerCoverage = (access) => {
2832
+ const backend = HERMES_DOCKER_BACKEND;
2833
+ if (mountsHostVolume(access)) return { kind: "hermes_asks", backend };
2834
+ if (isTrueSetting(access.mountCwd)) return { kind: "hermes_may_skip", backend, doubt: "docker_start_folder" };
2835
+ return { kind: "hermes_skips", backend };
2836
+ };
2837
+ var dockerCoverageFrom = (section, readings) => {
2838
+ if (readings.dockerVolumes === null || readings.dockerMountCwd === null) return { kind: "unreadable" };
2839
+ return dockerCoverage({
2840
+ volumes: effectiveValue(readings.dockerVolumes, section.docker_volumes),
2841
+ mountCwd: effectiveValue(readings.dockerMountCwd, section.docker_mount_cwd_to_workspace)
2842
+ });
2843
+ };
2844
+ var coverageOn = (backend, section, readings) => {
2845
+ if (backend === HERMES_DOCKER_BACKEND) return dockerCoverageFrom(section, readings);
2846
+ if (BACKENDS_WHERE_HERMES_ASKS.has(backend)) return { kind: "hermes_asks", backend };
2847
+ if (BACKENDS_WHERE_HERMES_SKIPS.has(backend)) return { kind: "hermes_skips", backend };
2848
+ return { kind: "hermes_may_skip", backend, doubt: "plugin_backend" };
2849
+ };
2850
+ var hermesApprovalCoverage = (readings) => {
2851
+ if (readings.terminal === null || readings.terminalEnv === null) return { kind: "unreadable" };
2852
+ const terminal = terminalSectionOf(readings.terminal);
2853
+ if (terminal.kind === "malformed") return { kind: "unreadable" };
2854
+ const backend = effectiveBackend(backendNameOf(terminal.section.backend), environmentBackendOf(readings.terminalEnv));
2855
+ return backend.kind === "named" ? coverageOn(backend.name, terminal.section, readings) : { kind: "unreadable" };
2856
+ };
2857
+ var listedEntries = (raw) => raw.split(GATE_TOOLS_SEPARATOR).map((entry) => entry.trim()).filter((entry) => entry !== "");
2858
+ var hermesGateToolsFrom = (reading) => {
2859
+ if (reading === null) return { kind: "unreadable" };
2860
+ if (reading.kind === "unset") return { kind: "unset" };
2861
+ if (typeof reading.value !== "string") return { kind: "unreadable" };
2862
+ const entries = listedEntries(reading.value);
2863
+ return { kind: "listed", entries, tools: entries.map((entry) => entry.toLowerCase()) };
2864
+ };
2865
+ var gatesHermesShell = (gate) => gate.kind === "listed" && gate.tools.includes(HERMES_SHELL_TOOL);
2866
+ var gateToolsWithShell = (gate) => {
2867
+ if (gate.kind === "unreadable" || gatesHermesShell(gate)) return null;
2868
+ const entries = gate.kind === "listed" ? gate.entries : [];
2869
+ return [...entries, HERMES_SHELL_TOOL].join(GATE_TOOLS_SEPARATOR);
2870
+ };
2871
+ var LEGACY_FLOW_LIST = /^\[(.*)\]$/s;
2872
+ var LEGACY_LIST_SEPARATOR = ",";
2873
+ var QUOTED_ENTRY = /^(['"])(.*)\1$/s;
2874
+ var unquotedEntry = (entry) => {
2875
+ const trimmed = entry.trim();
2876
+ return QUOTED_ENTRY.exec(trimmed)?.[2] ?? trimmed;
2877
+ };
2878
+ var legacyListEntries = (raw) => {
2879
+ const list = LEGACY_FLOW_LIST.exec(raw.trim());
2880
+ return list ? list[1].split(LEGACY_LIST_SEPARATOR).map(unquotedEntry) : [];
2881
+ };
2882
+ var allowlistEntries = (allowlist) => {
2883
+ if (allowlist?.kind !== "set") return [];
2884
+ if (Array.isArray(allowlist.value)) return allowlist.value;
2885
+ return typeof allowlist.value === "string" ? legacyListEntries(allowlist.value) : [];
2886
+ };
2887
+ var escalatesToHermesApprovals = (transport) => transport?.kind === "set" && transport.value === HERMES_PUSHARY_TRANSPORT;
2888
+ var hermesAlwaysAllowsShell = ({ allowlist, transport }) => escalatesToHermesApprovals(transport) && allowlistEntries(allowlist).includes(HERMES_ALWAYS_ALLOWED_SHELL_RULE);
2889
+ var skipOf = (coverage) => coverage.kind === "hermes_skips" ? { kind: "skips" } : { kind: "may_skip", doubt: coverage.doubt };
2890
+ var hermesShellGateState = ({ coverage, gate, alwaysAllowed }) => {
2891
+ if (coverage.kind === "unreadable") return { kind: "unreadable" };
2892
+ if (coverage.kind === "hermes_asks") return { kind: "hermes_asks", backend: coverage.backend };
2893
+ const skip = skipOf(coverage);
2894
+ const backend = coverage.backend;
2895
+ if (!gatesHermesShell(gate)) return { kind: "ungated", backend, skip };
2896
+ return alwaysAllowed ? { kind: "always_allowed", backend, skip } : { kind: "pushary_gates", backend, skip };
2897
+ };
2898
+ var hermesShellGateChoice = (input) => {
2899
+ if (input.requested) return "apply";
2900
+ return input.canAsk ? "ask" : "report";
2901
+ };
2902
+
2746
2903
  // src/hermes/runtime.ts
2747
2904
  import { execFile } from "child_process";
2748
2905
  import { accessSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
@@ -2793,9 +2950,18 @@ var PUSHARY_VALUES = {
2793
2950
  [HERMES_APPROVAL_TRANSPORT_KEY]: HERMES_PUSHARY_TRANSPORT,
2794
2951
  [HERMES_APPROVAL_FALLBACK_KEY]: HERMES_PUSHARY_FALLBACK
2795
2952
  };
2953
+ var readingBefore = (snapshot) => snapshot.wasSet ? { kind: "set", value: snapshot.before } : { kind: "unset" };
2954
+ var valueSetupWrote = (snapshot) => {
2955
+ if (snapshot.key === HERMES_GATE_TOOLS_KEY) return gateToolsWithShell(hermesGateToolsFrom(readingBefore(snapshot)));
2956
+ return Object.hasOwn(PUSHARY_VALUES, snapshot.key) ? PUSHARY_VALUES[snapshot.key] : null;
2957
+ };
2958
+ var receiptWithSnapshot = (receipt, snapshot) => ({
2959
+ ...receipt,
2960
+ settings: [...receipt.settings.filter((setting) => setting.key !== snapshot.key), snapshot]
2961
+ });
2796
2962
  var hermesSettingRestore = (snapshot, current) => {
2797
- const ours = PUSHARY_VALUES[snapshot.key];
2798
- const stillOurs = current.kind === "set" && current.value === ours;
2963
+ const ours = valueSetupWrote(snapshot);
2964
+ const stillOurs = ours !== null && current.kind === "set" && current.value === ours;
2799
2965
  const oursBeforeSetup = snapshot.wasSet && snapshot.before === ours;
2800
2966
  return stillOurs && !oursBeforeSetup ? { kind: "restore", key: snapshot.key, snapshot } : { kind: "leave", key: snapshot.key };
2801
2967
  };
@@ -2880,13 +3046,20 @@ var commandOutput = (error) => {
2880
3046
  };
2881
3047
  var stoppedAtTimeout = (error) => isRecord(error) && error.killed === true;
2882
3048
  var runFileAsync = promisify(execFile);
3049
+ var SETTINGS_A_SERVICE_GATEWAY_NEVER_INHERITS = [
3050
+ HERMES_GATE_TOOLS_KEY,
3051
+ HERMES_TERMINAL_ENV_KEY,
3052
+ HERMES_DOCKER_VOLUMES_KEY,
3053
+ HERMES_DOCKER_MOUNT_CWD_KEY
3054
+ ];
3055
+ var environmentAsTheGatewaySeesIt = (environment) => Object.fromEntries(Object.entries(environment).filter(([name]) => !SETTINGS_A_SERVICE_GATEWAY_NEVER_INHERITS.includes(name)));
2883
3056
  var runHermesCommand = async (launcher, args, timeoutMs = HERMES_COMMAND_TIMEOUT_MS) => {
2884
3057
  const shell = needsShell(launcher.path);
2885
3058
  try {
2886
3059
  const running = runFileAsync(
2887
3060
  shell ? quotedForWindowsShell(launcher.path) : launcher.path,
2888
3061
  shell ? args.map(quotedForWindowsShell) : [...args],
2889
- { encoding: "utf-8", timeout: timeoutMs, maxBuffer: HERMES_OUTPUT_LIMIT_BYTES, shell }
3062
+ { encoding: "utf-8", timeout: timeoutMs, maxBuffer: HERMES_OUTPUT_LIMIT_BYTES, shell, env: environmentAsTheGatewaySeesIt(process.env) }
2890
3063
  );
2891
3064
  running.child.stdin?.end();
2892
3065
  const { stdout } = await running;
@@ -3360,10 +3533,308 @@ var removeHermesWiring = async (request) => {
3360
3533
  return { kind: "removed", pluginRemoved: folder.kind === "pushary", settingsRestored, dryRun: false };
3361
3534
  };
3362
3535
 
3536
+ // src/openclaw/install.ts
3537
+ import { createHash as createHash3 } from "crypto";
3538
+ import { existsSync as existsSync4, readdirSync as readdirSync2, rmSync as rmSync4 } from "fs";
3539
+ import { join as join3 } from "path";
3540
+
3541
+ // src/openclaw/bundled-plugin.ts
3542
+ import { createHash as createHash2 } from "crypto";
3543
+ import { cpSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, renameSync as renameSync2, rmSync as rmSync3, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
3544
+ import { dirname as dirname2, join as join2, relative } from "path";
3545
+ import { fileURLToPath } from "url";
3546
+ var OPENCLAW_BUNDLE_DIRECTORY = "openclaw-plugin";
3547
+ var OPENCLAW_MANIFEST_FILE = "openclaw.plugin.json";
3548
+ var OPENCLAW_PACKAGE_FILE = "package.json";
3549
+ var OPENCLAW_ENTRY_FILE = join2("dist", "index.js");
3550
+ var OPENCLAW_INSTALL_MARKER_FILE = ".pushary-install.json";
3551
+ var INSTALL_MARKER_OWNER = "pushary";
3552
+ var parsedJsonFile = (path) => {
3553
+ try {
3554
+ return JSON.parse(readFileSync2(path, "utf-8"));
3555
+ } catch {
3556
+ return null;
3557
+ }
3558
+ };
3559
+ var filesUnder = (root, directory = root) => readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
3560
+ const path = join2(directory, entry.name);
3561
+ if (entry.name === OPENCLAW_INSTALL_MARKER_FILE) return [];
3562
+ return entry.isDirectory() ? filesUnder(root, path) : [relative(root, path)];
3563
+ }).sort();
3564
+ var digestOfPluginFolder = (directory) => {
3565
+ const hash = createHash2("sha256");
3566
+ for (const file of filesUnder(directory)) {
3567
+ hash.update(file.split("\\").join("/"));
3568
+ hash.update("\0");
3569
+ hash.update(readFileSync2(join2(directory, file)));
3570
+ hash.update("\0");
3571
+ }
3572
+ return `sha256:${hash.digest("hex")}`;
3573
+ };
3574
+ var readPluginBundle = (directory) => {
3575
+ const manifest = parsedJsonFile(join2(directory, OPENCLAW_MANIFEST_FILE));
3576
+ const pkg = parsedJsonFile(join2(directory, OPENCLAW_PACKAGE_FILE));
3577
+ if (!isRecord(manifest) || manifest.id !== OPENCLAW_PLUGIN_ID) return null;
3578
+ if (!isRecord(pkg) || pkg.name !== OPENCLAW_PLUGIN_PACKAGE || typeof pkg.version !== "string") return null;
3579
+ if (!existsSync3(join2(directory, OPENCLAW_ENTRY_FILE))) return null;
3580
+ return { directory, version: pkg.version, digest: digestOfPluginFolder(directory) };
3581
+ };
3582
+ var bundledPluginCandidates = (moduleDirectory) => [
3583
+ join2(moduleDirectory, "..", "..", "data", OPENCLAW_BUNDLE_DIRECTORY),
3584
+ join2(moduleDirectory, "..", "data", OPENCLAW_BUNDLE_DIRECTORY)
3585
+ ];
3586
+ var findBundledOpenClawPlugin = () => {
3587
+ const moduleDirectory = dirname2(fileURLToPath(import.meta.url));
3588
+ for (const candidate of bundledPluginCandidates(moduleDirectory)) {
3589
+ const bundle = readPluginBundle(candidate);
3590
+ if (bundle !== null) return bundle;
3591
+ }
3592
+ return null;
3593
+ };
3594
+ var readInstallMarker = (directory) => {
3595
+ const marker = parsedJsonFile(join2(directory, OPENCLAW_INSTALL_MARKER_FILE));
3596
+ if (!isRecord(marker) || marker.owner !== INSTALL_MARKER_OWNER) return null;
3597
+ return typeof marker.version === "string" && typeof marker.digest === "string" ? { owner: INSTALL_MARKER_OWNER, version: marker.version, digest: marker.digest } : null;
3598
+ };
3599
+ var ownedFolderIsCurrent = (directory, bundle) => readInstallMarker(directory)?.digest === bundle.digest;
3600
+ var isDirectory = (path) => {
3601
+ try {
3602
+ return statSync2(path).isDirectory();
3603
+ } catch {
3604
+ return false;
3605
+ }
3606
+ };
3607
+ var writeOwnedPluginFolder = (bundle, target) => {
3608
+ const staging = `${target}.staging-${process.pid}`;
3609
+ const previous = `${target}.previous-${process.pid}`;
3610
+ rmSync3(staging, { recursive: true, force: true });
3611
+ mkdirSync2(dirname2(target), { recursive: true });
3612
+ cpSync(bundle.directory, staging, { recursive: true, filter: (path) => !path.endsWith(OPENCLAW_INSTALL_MARKER_FILE) });
3613
+ const marker = { owner: INSTALL_MARKER_OWNER, version: bundle.version, digest: bundle.digest };
3614
+ writeFileSync2(join2(staging, OPENCLAW_INSTALL_MARKER_FILE), `${JSON.stringify(marker, null, 2)}
3615
+ `);
3616
+ rmSync3(previous, { recursive: true, force: true });
3617
+ const hadTarget = isDirectory(target);
3618
+ if (hadTarget) renameSync2(target, previous);
3619
+ try {
3620
+ renameSync2(staging, target);
3621
+ } catch (error) {
3622
+ if (hadTarget) renameSync2(previous, target);
3623
+ rmSync3(staging, { recursive: true, force: true });
3624
+ throw error;
3625
+ }
3626
+ rmSync3(previous, { recursive: true, force: true });
3627
+ };
3628
+
3629
+ // src/openclaw/setup-receipt.ts
3630
+ var OPENCLAW_RECEIPT_VERSION = 1;
3631
+ var CONFIG_FIELD = "config";
3632
+ var ENABLED_FIELD = "enabled";
3633
+ var environmentFrom = (value) => {
3634
+ if (!isRecord(value)) return null;
3635
+ const entries = Object.entries(value);
3636
+ const known = new Set(OPENCLAW_ENVIRONMENT_KEYS);
3637
+ if (!entries.every(([key, setting]) => known.has(key) && typeof setting === "string")) return null;
3638
+ return Object.fromEntries(entries.flatMap(([key, setting]) => typeof setting === "string" ? [[key, setting]] : []));
3639
+ };
3640
+ var entryBeforeFrom = (value) => {
3641
+ if (!isRecord(value) || typeof value.present !== "boolean") return null;
3642
+ return value.present ? { present: true, value: value.value } : { present: false };
3643
+ };
3644
+ var parseOpenClawSetupReceipt = (value) => {
3645
+ if (!isRecord(value) || value.version !== OPENCLAW_RECEIPT_VERSION) return null;
3646
+ const environment = environmentFrom(value.environment);
3647
+ const entryBefore = entryBeforeFrom(value.entryBefore);
3648
+ return environment === null || entryBefore === null ? null : { version: OPENCLAW_RECEIPT_VERSION, environment, entryBefore };
3649
+ };
3650
+ var userConfigOf = (entry) => {
3651
+ if (!isRecord(entry)) return null;
3652
+ const config = entry[CONFIG_FIELD];
3653
+ return isRecord(config) && Object.keys(config).length > 0 ? config : null;
3654
+ };
3655
+ var entryToRestore = (before, now) => {
3656
+ const userConfig = userConfigOf(now);
3657
+ if (before.present) {
3658
+ return userConfig !== null && isRecord(before.value) ? { kind: "set", value: { ...before.value, [CONFIG_FIELD]: userConfig } } : { kind: "set", value: before.value };
3659
+ }
3660
+ return userConfig === null ? { kind: "unset" } : { kind: "set", value: { [ENABLED_FIELD]: false, [CONFIG_FIELD]: userConfig } };
3661
+ };
3662
+
3663
+ // src/openclaw/install.ts
3664
+ var FAILURE_DETAIL_MAX_LENGTH = 300;
3665
+ var RECEIPT_MODE2 = 384;
3666
+ var RECEIPT_EXTENSION = ".json";
3667
+ var RECEIPT_NAME_LENGTH = 16;
3668
+ var openClawFilesNow = () => ({ ownedFolder: openClawPluginFolder(), receiptDirectory: openClawSetupReceiptDirectory() });
3669
+ var lastLineOf = (output) => output.trim().split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0).at(-1)?.slice(0, FAILURE_DETAIL_MAX_LENGTH) ?? "";
3670
+ var failureDetail = (result) => lastLineOf(result.output);
3671
+ var readReceipt = (path) => {
3672
+ const read = readJsonSafe(path);
3673
+ if (read.kind === "missing") return { kind: "missing" };
3674
+ const receipt = read.kind === "ok" ? parseOpenClawSetupReceipt(read.value) : null;
3675
+ return receipt === null ? { kind: "invalid" } : { kind: "ok", receipt };
3676
+ };
3677
+ var receiptPathFor = (files, environment) => {
3678
+ const stateDirectory = openClawPathsNow(environment).stateDirectory;
3679
+ return join3(files.receiptDirectory, `${createHash3("sha256").update(stateDirectory, "utf8").digest("hex").slice(0, RECEIPT_NAME_LENGTH)}${RECEIPT_EXTENSION}`);
3680
+ };
3681
+ var recordedSetups = (files) => {
3682
+ if (!existsSync4(files.receiptDirectory)) return [];
3683
+ return readdirSync2(files.receiptDirectory).filter((name) => name.endsWith(RECEIPT_EXTENSION)).sort().map((name) => join3(files.receiptDirectory, name)).map((path) => ({ path, read: readReceipt(path) }));
3684
+ };
3685
+ var openClawLivesHere = (environment) => openClawDirectoriesToLookIn(openClawPathsNow(environment)).some(existsSync4);
3686
+ var sessionFor = (launcher, environment) => ({ launcher, environment });
3687
+ var launcherFor = (launcher, lookUp) => launcher === void 0 ? lookUp() : launcher;
3688
+ var inspectWith = async (session, runtime) => {
3689
+ const facts = await inspectOpenClawPlugin(session, { runtime });
3690
+ return { kind: "inspected", session, facts, state: openClawWiringState(facts) };
3691
+ };
3692
+ var launcherWhereOpenClawLives = (environment, receipt) => receipt.kind === "ok" || openClawLivesHere(environment) ? findOpenClawLauncher() : null;
3693
+ var inspectOpenClawWiring = async (files, launcher) => {
3694
+ const environment = currentOpenClawEnvironment();
3695
+ const receipt = readReceipt(receiptPathFor(files, environment));
3696
+ const found = launcherFor(launcher, () => launcherWhereOpenClawLives(environment, receipt));
3697
+ return found === null ? { kind: "no_launcher" } : inspectWith(sessionFor(found, environment), true);
3698
+ };
3699
+ var pluginIdTakenBySomeoneElse = (facts) => facts.kind === "installed" && !isOursToRemove(facts);
3700
+ var ensureReceipt = async (session, receiptPath) => {
3701
+ const existing = readReceipt(receiptPath);
3702
+ if (existing.kind === "ok") return { kind: "ok" };
3703
+ if (existing.kind === "invalid") return { kind: "failed", reason: "receipt_invalid" };
3704
+ const entry = await readOpenClawEntry(session);
3705
+ if (entry.kind === "unreadable") return { kind: "failed", reason: "config_unreadable" };
3706
+ const receipt = {
3707
+ version: OPENCLAW_RECEIPT_VERSION,
3708
+ environment: session.environment,
3709
+ entryBefore: entry.kind === "present" ? { present: true, value: entry.value } : { present: false }
3710
+ };
3711
+ writeJsonAtomic(receiptPath, receipt, RECEIPT_MODE2);
3712
+ return { kind: "ok" };
3713
+ };
3714
+ var writeOwnedFolder = (bundle, folder) => {
3715
+ try {
3716
+ writeOwnedPluginFolder(bundle, folder);
3717
+ return true;
3718
+ } catch {
3719
+ return false;
3720
+ }
3721
+ };
3722
+ var installOpenClawPlugin = async (request) => {
3723
+ const launcher = launcherFor(request.launcher, findOpenClawLauncher);
3724
+ if (launcher === null) return { kind: "no_launcher" };
3725
+ const bundle = request.bundle === void 0 ? findBundledOpenClawPlugin() : request.bundle;
3726
+ if (bundle === null) return { kind: "failed", reason: "bundle_missing", detail: "" };
3727
+ const environment = currentOpenClawEnvironment();
3728
+ const session = sessionFor(launcher, environment);
3729
+ const before = await inspectOpenClawPlugin(session, { runtime: false });
3730
+ if (before.kind === "unreadable") return { kind: "failed", reason: "inspect_unreadable", detail: "" };
3731
+ if (pluginIdTakenBySomeoneElse(before)) {
3732
+ return { kind: "failed", reason: "plugin_id_taken", detail: before.kind === "installed" ? before.packageName ?? "" : "" };
3733
+ }
3734
+ const receipt = await ensureReceipt(session, receiptPathFor(request.files, environment));
3735
+ if (receipt.kind === "failed") return { kind: "failed", reason: receipt.reason, detail: "" };
3736
+ if (!writeOwnedFolder(bundle, request.files.ownedFolder)) return { kind: "failed", reason: "plugin_write_failed", detail: "" };
3737
+ const installed = await installOpenClawPluginFrom(session, request.files.ownedFolder);
3738
+ if (installed.kind === "failed") {
3739
+ return { kind: "failed", reason: installed.timedOut ? "install_timed_out" : "install_failed", detail: failureDetail(installed) };
3740
+ }
3741
+ const enabled = await enableOpenClawPlugin(session);
3742
+ if (enabled.kind === "failed") return { kind: "failed", reason: "enable_failed", detail: failureDetail(enabled) };
3743
+ return { kind: "installed", inspection: await inspectWith(session, true), version: bundle.version };
3744
+ };
3745
+ var setupsRecordedOk = (files) => recordedSetups(files).flatMap((setup) => setup.read.kind === "ok" ? [setup.read.receipt] : []);
3746
+ var reinstallInto = async (launcher, receipt, folder) => {
3747
+ const session = sessionFor(launcher, receipt.environment);
3748
+ if (!isOursToRemove(await inspectOpenClawPlugin(session, { runtime: false }))) return "skipped";
3749
+ return (await installOpenClawPluginFrom(session, folder)).kind === "ok" ? "refreshed" : "failed";
3750
+ };
3751
+ var refreshOpenClawPlugin = async (request) => {
3752
+ const receipts = setupsRecordedOk(request.files);
3753
+ if (receipts.length === 0) return "not_set_up";
3754
+ const bundle = request.bundle === void 0 ? findBundledOpenClawPlugin() : request.bundle;
3755
+ if (bundle === null) return "failed";
3756
+ if (ownedFolderIsCurrent(request.files.ownedFolder, bundle)) return "current";
3757
+ const launcher = launcherFor(request.launcher, findOpenClawLauncher);
3758
+ if (launcher === null) return "failed";
3759
+ if (!writeOwnedFolder(bundle, request.files.ownedFolder)) return "failed";
3760
+ const results = [];
3761
+ for (const receipt of receipts) results.push(await reinstallInto(launcher, receipt, request.files.ownedFolder));
3762
+ if (results.includes("failed")) return "failed";
3763
+ return results.includes("refreshed") ? "refreshed" : "not_set_up";
3764
+ };
3765
+ var restoreEntry = async (session, receipt, entryNow) => {
3766
+ if (receipt.kind !== "ok") return unsetOpenClawEntry(session);
3767
+ const restore = entryToRestore(receipt.receipt.entryBefore, entryNow);
3768
+ return restore.kind === "unset" ? unsetOpenClawEntry(session) : writeOpenClawEntry(session, restore.value);
3769
+ };
3770
+ var removalTargets = (files) => {
3771
+ const recorded = recordedSetups(files).flatMap((setup) => setup.read.kind === "ok" ? [{ environment: setup.read.receipt.environment, receipt: setup.read, receiptPath: setup.path }] : []);
3772
+ const current = currentOpenClawEnvironment();
3773
+ const currentPath = receiptPathFor(files, current);
3774
+ return recorded.some((target) => target.receiptPath === currentPath) ? recorded : [...recorded, { environment: current, receipt: { kind: "missing" }, receiptPath: currentPath }];
3775
+ };
3776
+ var removeFromOneOpenClaw = async (target, request) => {
3777
+ const { environment, receipt } = target;
3778
+ const launcher = launcherFor(request.launcher, () => launcherWhereOpenClawLives(environment, receipt));
3779
+ if (launcher === null) return receipt.kind === "ok" ? { kind: "runtime_missing" } : { kind: "not_found" };
3780
+ const session = sessionFor(launcher, environment);
3781
+ const facts = await inspectOpenClawPlugin(session, { runtime: false });
3782
+ if (facts.kind === "unreadable") return { kind: "unreadable" };
3783
+ if (facts.kind === "installed" && !isOursToRemove(facts)) return { kind: "not_ours", packageName: facts.packageName };
3784
+ if (facts.kind === "not_installed" && receipt.kind === "missing") return { kind: "not_found" };
3785
+ if (request.dryRun) return { kind: "removed", dryRun: true, settingsRestored: true };
3786
+ const entryNow = await readOpenClawEntry(session);
3787
+ if (entryNow.kind === "unreadable") return { kind: "unreadable" };
3788
+ if (facts.kind === "installed") {
3789
+ const removed = await uninstallOpenClawPlugin(session, false);
3790
+ if (removed.kind === "failed") return { kind: "failed", detail: failureDetail(removed) };
3791
+ }
3792
+ const settingsRestored = await restoreEntry(session, receipt, entryNow.kind === "present" ? entryNow.value : void 0);
3793
+ if (settingsRestored) rmSync4(target.receiptPath, { force: true });
3794
+ return { kind: "removed", dryRun: false, settingsRestored };
3795
+ };
3796
+ var REMOVAL_PRECEDENCE = ["failed", "unreadable", "runtime_missing", "not_ours", "removed", "not_found"];
3797
+ var combinedRemoval = (outcomes) => {
3798
+ const worst = REMOVAL_PRECEDENCE.map((kind) => outcomes.find((outcome) => outcome.kind === kind)).find((outcome) => outcome !== void 0);
3799
+ if (worst === void 0) return { kind: "not_found" };
3800
+ if (worst.kind !== "removed") return worst;
3801
+ const everyRemoval = outcomes.flatMap((outcome) => outcome.kind === "removed" ? [outcome] : []);
3802
+ return { kind: "removed", dryRun: worst.dryRun, settingsRestored: everyRemoval.every((outcome) => outcome.settingsRestored) };
3803
+ };
3804
+ var removeOpenClawPlugin = async (request) => {
3805
+ if (recordedSetups(request.files).some((setup) => setup.read.kind === "invalid")) return { kind: "failed", detail: "setup receipt is unreadable" };
3806
+ const outcomes = [];
3807
+ for (const target of removalTargets(request.files)) outcomes.push(await removeFromOneOpenClaw(target, request));
3808
+ const combined = combinedRemoval(outcomes);
3809
+ if (combined.kind === "removed" && !combined.dryRun && recordedSetups(request.files).length === 0) rmSync4(request.files.ownedFolder, { recursive: true, force: true });
3810
+ return combined;
3811
+ };
3812
+ var openClawRemovalLeavesThePluginInstalled = (outcome) => outcome.kind === "failed" || outcome.kind === "unreadable" || outcome.kind === "runtime_missing";
3813
+
3363
3814
  export {
3364
3815
  HERMES_INSTALL_MARKER_FILE,
3816
+ HERMES_APPROVAL_TRANSPORT_KEY,
3365
3817
  shippedHermesPlugin,
3818
+ HERMES_TERMINAL_SECTION,
3819
+ HERMES_TERMINAL_ENV_KEY,
3820
+ HERMES_GATE_TOOLS_KEY,
3821
+ HERMES_SHELL_TOOL,
3822
+ HERMES_DOCKER_VOLUMES_KEY,
3823
+ HERMES_DOCKER_MOUNT_CWD_KEY,
3824
+ HERMES_COMMAND_ALLOWLIST_KEY,
3825
+ HERMES_ALWAYS_ALLOWED_SHELL_RULE,
3826
+ hermesApprovalCoverage,
3827
+ hermesGateToolsFrom,
3828
+ gatesHermesShell,
3829
+ gateToolsWithShell,
3830
+ hermesAlwaysAllowsShell,
3831
+ hermesShellGateState,
3832
+ hermesShellGateChoice,
3833
+ settingSnapshot,
3834
+ receiptWithSnapshot,
3366
3835
  findHermesLauncher,
3836
+ readHermesSetting,
3837
+ writeHermesSetting,
3367
3838
  hermesPluginDirectory,
3368
3839
  HERMES_CONFIG_FILE,
3369
3840
  defaultHermesHome,
@@ -3378,7 +3849,15 @@ export {
3378
3849
  hermesReceiptPaths,
3379
3850
  hermesSetupWasRecorded,
3380
3851
  hermesSetupPredatesThePluginFolder,
3852
+ readSetupReceipt,
3853
+ writeSetupReceipt,
3381
3854
  installHermesPlugin,
3382
3855
  refreshHermesPluginFiles,
3383
- removeHermesWiring
3856
+ removeHermesWiring,
3857
+ openClawFilesNow,
3858
+ inspectOpenClawWiring,
3859
+ installOpenClawPlugin,
3860
+ refreshOpenClawPlugin,
3861
+ removeOpenClawPlugin,
3862
+ openClawRemovalLeavesThePluginInstalled
3384
3863
  };