jishushell 0.6.5 → 0.7.3

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 (1207) hide show
  1. package/apps/anythingllm-container.yaml +16 -170
  2. package/apps/browserless-chromium-container.yaml +16 -10
  3. package/apps/filebrowser-container.yaml +15 -9
  4. package/apps/hermes-container.yaml +20 -5
  5. package/apps/immich-container-lite.yaml +337 -0
  6. package/apps/immich-container.yaml +371 -0
  7. package/apps/jishu-kb-container.yaml +50 -177
  8. package/apps/ollama-binary.yaml +33 -28
  9. package/apps/ollama-cpu-container.yaml +6 -0
  10. package/apps/ollama-with-hollama-binary.yaml +35 -28
  11. package/apps/openclaw-binary.yaml +35 -15
  12. package/apps/openclaw-container.yaml +29 -11
  13. package/apps/openclaw-with-ollama-container.yaml +9 -2
  14. package/apps/openclaw-with-searxng-container.yaml +38 -6
  15. package/apps/searxng-container.yaml +31 -6
  16. package/apps/weknora-container.yaml +26 -21
  17. package/dependencies/jishushell-panel-0.7.3.tgz +0 -0
  18. package/dist/cli/app.js +244 -213
  19. package/dist/cli/app.js.map +1 -1
  20. package/dist/cli/backup.js +15 -12
  21. package/dist/cli/backup.js.map +1 -1
  22. package/dist/cli/core.d.ts +4 -3
  23. package/dist/cli/core.js +392 -227
  24. package/dist/cli/core.js.map +1 -1
  25. package/dist/cli/doctor.d.ts +1 -1
  26. package/dist/cli/doctor.js +113 -10
  27. package/dist/cli/doctor.js.map +1 -1
  28. package/dist/cli/job.js +62 -14
  29. package/dist/cli/job.js.map +1 -1
  30. package/dist/cli/llm.js +80 -11
  31. package/dist/cli/llm.js.map +1 -1
  32. package/dist/cli/managed-list.d.ts +1 -3
  33. package/dist/cli/managed-list.js +18 -16
  34. package/dist/cli/managed-list.js.map +1 -1
  35. package/dist/cli/migrate.d.ts +2 -0
  36. package/dist/cli/migrate.js +160 -0
  37. package/dist/cli/migrate.js.map +1 -0
  38. package/dist/cli.js +1 -0
  39. package/dist/cli.js.map +1 -1
  40. package/dist/config.d.ts +32 -20
  41. package/dist/config.js +132 -51
  42. package/dist/config.js.map +1 -1
  43. package/dist/control.d.ts +6 -6
  44. package/dist/control.js +31 -23
  45. package/dist/control.js.map +1 -1
  46. package/dist/core.d.ts +5 -5
  47. package/dist/core.js +5 -5
  48. package/dist/core.js.map +1 -1
  49. package/dist/install.d.ts +2 -2
  50. package/dist/install.js +78 -37
  51. package/dist/install.js.map +1 -1
  52. package/dist/routes/admin.d.ts +2 -0
  53. package/dist/routes/admin.js +72 -0
  54. package/dist/routes/admin.js.map +1 -0
  55. package/dist/routes/apps.d.ts +1 -1
  56. package/dist/routes/apps.js +101 -193
  57. package/dist/routes/apps.js.map +1 -1
  58. package/dist/routes/auth.js +1 -1
  59. package/dist/routes/auth.js.map +1 -1
  60. package/dist/routes/backup.js +1 -1
  61. package/dist/routes/backup.js.map +1 -1
  62. package/dist/routes/docker.d.ts +2 -0
  63. package/dist/routes/docker.js +58 -0
  64. package/dist/routes/docker.js.map +1 -0
  65. package/dist/routes/external-mounts.d.ts +1 -1
  66. package/dist/routes/external-mounts.js +1 -1
  67. package/dist/routes/external-mounts.js.map +1 -1
  68. package/dist/routes/file-mounts.d.ts +4 -3
  69. package/dist/routes/file-mounts.js +49 -31
  70. package/dist/routes/file-mounts.js.map +1 -1
  71. package/dist/routes/files-organize.d.ts +2 -2
  72. package/dist/routes/files-organize.js +5 -5
  73. package/dist/routes/files-organize.js.map +1 -1
  74. package/dist/routes/files.d.ts +1 -1
  75. package/dist/routes/files.js +1 -1
  76. package/dist/routes/files.js.map +1 -1
  77. package/dist/routes/instances.d.ts +0 -8
  78. package/dist/routes/instances.js +202 -1560
  79. package/dist/routes/instances.js.map +1 -1
  80. package/dist/routes/integration-apps.d.ts +14 -0
  81. package/dist/routes/integration-apps.js +81 -0
  82. package/dist/routes/integration-apps.js.map +1 -0
  83. package/dist/routes/integrations.d.ts +9 -0
  84. package/dist/routes/integrations.js +12 -0
  85. package/dist/routes/integrations.js.map +1 -0
  86. package/dist/routes/llm-proxy.js +26 -3
  87. package/dist/routes/llm-proxy.js.map +1 -1
  88. package/dist/routes/setup.js +53 -38
  89. package/dist/routes/setup.js.map +1 -1
  90. package/dist/routes/system.js +108 -68
  91. package/dist/routes/system.js.map +1 -1
  92. package/dist/routes/webdav.d.ts +1 -1
  93. package/dist/routes/webdav.js +2 -2
  94. package/dist/routes/webdav.js.map +1 -1
  95. package/dist/server.d.ts +6 -0
  96. package/dist/server.js +368 -233
  97. package/dist/server.js.map +1 -1
  98. package/dist/services/app-common/app-compiler.js +186 -0
  99. package/dist/services/app-common/app-compiler.js.map +1 -0
  100. package/dist/services/app-common/app-shared.d.ts +15 -0
  101. package/dist/services/app-common/app-shared.js +64 -0
  102. package/dist/services/app-common/app-shared.js.map +1 -0
  103. package/dist/services/app-common/capability-service.d.ts +45 -0
  104. package/dist/services/app-common/capability-service.js +331 -0
  105. package/dist/services/app-common/capability-service.js.map +1 -0
  106. package/dist/services/app-common/catalog-service.d.ts +59 -0
  107. package/dist/services/app-common/catalog-service.js +318 -0
  108. package/dist/services/app-common/catalog-service.js.map +1 -0
  109. package/dist/services/app-common/create-pipeline.d.ts +26 -0
  110. package/dist/services/app-common/create-pipeline.js +298 -0
  111. package/dist/services/app-common/create-pipeline.js.map +1 -0
  112. package/dist/services/app-common/delete-service.d.ts +5 -0
  113. package/dist/services/app-common/delete-service.js +109 -0
  114. package/dist/services/app-common/delete-service.js.map +1 -0
  115. package/dist/services/app-common/execution-owner.d.ts +23 -0
  116. package/dist/services/app-common/execution-owner.js +124 -0
  117. package/dist/services/app-common/execution-owner.js.map +1 -0
  118. package/dist/services/app-common/execution-service.d.ts +23 -0
  119. package/dist/services/app-common/execution-service.js +105 -0
  120. package/dist/services/app-common/execution-service.js.map +1 -0
  121. package/dist/services/app-common/id-normalizer.d.ts +31 -0
  122. package/dist/services/app-common/id-normalizer.js +83 -0
  123. package/dist/services/app-common/id-normalizer.js.map +1 -0
  124. package/dist/services/app-common/install-store.d.ts +34 -0
  125. package/dist/services/app-common/install-store.js +261 -0
  126. package/dist/services/app-common/install-store.js.map +1 -0
  127. package/dist/services/app-common/instance-store.d.ts +78 -0
  128. package/dist/services/app-common/instance-store.js +498 -0
  129. package/dist/services/app-common/instance-store.js.map +1 -0
  130. package/dist/services/app-common/integration-refs.d.ts +17 -0
  131. package/dist/services/app-common/integration-refs.js +47 -0
  132. package/dist/services/app-common/integration-refs.js.map +1 -0
  133. package/dist/services/app-common/lifecycle-pipeline.d.ts +62 -0
  134. package/dist/services/app-common/lifecycle-pipeline.js +317 -0
  135. package/dist/services/app-common/lifecycle-pipeline.js.map +1 -0
  136. package/dist/services/app-common/lifecycle-scripts.d.ts +38 -0
  137. package/dist/services/app-common/lifecycle-scripts.js +935 -0
  138. package/dist/services/app-common/lifecycle-scripts.js.map +1 -0
  139. package/dist/services/app-common/lifecycle-service.d.ts +68 -0
  140. package/dist/services/app-common/lifecycle-service.js +475 -0
  141. package/dist/services/app-common/lifecycle-service.js.map +1 -0
  142. package/dist/services/app-common/ownership.d.ts +3 -0
  143. package/dist/services/app-common/ownership.js +11 -0
  144. package/dist/services/app-common/ownership.js.map +1 -0
  145. package/dist/services/app-common/paths.d.ts +29 -0
  146. package/dist/services/app-common/paths.js +34 -0
  147. package/dist/services/app-common/paths.js.map +1 -0
  148. package/dist/services/app-common/platform-transform.d.ts +32 -0
  149. package/dist/services/app-common/platform-transform.js +65 -0
  150. package/dist/services/app-common/platform-transform.js.map +1 -0
  151. package/dist/services/app-common/provide-resolver.d.ts +29 -0
  152. package/dist/services/app-common/provide-resolver.js +129 -0
  153. package/dist/services/app-common/provide-resolver.js.map +1 -0
  154. package/dist/services/app-common/remote-spec.d.ts +14 -0
  155. package/dist/services/app-common/remote-spec.js +58 -0
  156. package/dist/services/app-common/remote-spec.js.map +1 -0
  157. package/dist/services/app-common/runtime-builder.d.ts +1 -0
  158. package/dist/services/app-common/runtime-builder.js +2 -0
  159. package/dist/services/app-common/runtime-builder.js.map +1 -0
  160. package/dist/services/app-common/runtime-facts.d.ts +19 -0
  161. package/dist/services/app-common/runtime-facts.js +128 -0
  162. package/dist/services/app-common/runtime-facts.js.map +1 -0
  163. package/dist/services/app-common/service.d.ts +9 -0
  164. package/dist/services/app-common/service.js +10 -0
  165. package/dist/services/app-common/service.js.map +1 -0
  166. package/dist/services/app-common/spec-materializer.d.ts +8 -0
  167. package/dist/services/app-common/spec-materializer.js +295 -0
  168. package/dist/services/app-common/spec-materializer.js.map +1 -0
  169. package/dist/services/app-common/status-refresh.d.ts +33 -0
  170. package/dist/services/app-common/status-refresh.js +771 -0
  171. package/dist/services/app-common/status-refresh.js.map +1 -0
  172. package/dist/services/app-common/task-service.d.ts +29 -0
  173. package/dist/services/app-common/task-service.js +93 -0
  174. package/dist/services/app-common/task-service.js.map +1 -0
  175. package/dist/services/app-common/terminal-session-manager.js +157 -0
  176. package/dist/services/app-common/terminal-session-manager.js.map +1 -0
  177. package/dist/services/app-modules/browserless/routes.d.ts +9 -0
  178. package/dist/services/app-modules/browserless/routes.js +519 -0
  179. package/dist/services/app-modules/browserless/routes.js.map +1 -0
  180. package/dist/services/app-modules/routes.d.ts +2 -0
  181. package/dist/services/app-modules/routes.js +5 -0
  182. package/dist/services/app-modules/routes.js.map +1 -0
  183. package/dist/services/backup/backup-admin.d.ts +95 -0
  184. package/dist/services/backup/backup-admin.js +246 -0
  185. package/dist/services/backup/backup-admin.js.map +1 -0
  186. package/dist/services/backup/backup-manager.d.ts +264 -0
  187. package/dist/services/backup/backup-manager.js +2318 -0
  188. package/dist/services/backup/backup-manager.js.map +1 -0
  189. package/dist/services/backup/backup-verify.js +240 -0
  190. package/dist/services/backup/backup-verify.js.map +1 -0
  191. package/dist/services/capabilities/browser-policy.d.ts +14 -0
  192. package/dist/services/capabilities/browser-policy.js +141 -0
  193. package/dist/services/capabilities/browser-policy.js.map +1 -0
  194. package/dist/services/capabilities/contract.d.ts +49 -0
  195. package/dist/services/capabilities/contract.js +119 -0
  196. package/dist/services/capabilities/contract.js.map +1 -0
  197. package/dist/services/capabilities/endpoint-validator.d.ts +42 -0
  198. package/dist/services/capabilities/endpoint-validator.js +113 -0
  199. package/dist/services/capabilities/endpoint-validator.js.map +1 -0
  200. package/dist/services/capabilities/health.d.ts +16 -0
  201. package/dist/services/capabilities/health.js +121 -0
  202. package/dist/services/capabilities/health.js.map +1 -0
  203. package/dist/services/capabilities/registry.d.ts +56 -0
  204. package/dist/services/capabilities/registry.js +222 -0
  205. package/dist/services/capabilities/registry.js.map +1 -0
  206. package/dist/services/capabilities/sync.d.ts +7 -0
  207. package/dist/services/capabilities/sync.js +223 -0
  208. package/dist/services/capabilities/sync.js.map +1 -0
  209. package/dist/services/capability-proxy/html-rewriters/browserless.d.ts +1 -0
  210. package/dist/services/capability-proxy/html-rewriters/browserless.js +83 -0
  211. package/dist/services/capability-proxy/html-rewriters/browserless.js.map +1 -0
  212. package/dist/services/capability-proxy/html-rewriters/index.d.ts +12 -0
  213. package/dist/services/capability-proxy/html-rewriters/index.js +25 -0
  214. package/dist/services/capability-proxy/html-rewriters/index.js.map +1 -0
  215. package/dist/services/capability-proxy/html-rewriters/jishukb.d.ts +1 -0
  216. package/dist/services/capability-proxy/html-rewriters/jishukb.js +161 -0
  217. package/dist/services/capability-proxy/html-rewriters/jishukb.js.map +1 -0
  218. package/dist/services/capability-proxy/http.d.ts +7 -0
  219. package/dist/services/capability-proxy/http.js +555 -0
  220. package/dist/services/capability-proxy/http.js.map +1 -0
  221. package/dist/services/capability-proxy/terminal.d.ts +4 -0
  222. package/dist/services/capability-proxy/terminal.js +179 -0
  223. package/dist/services/capability-proxy/terminal.js.map +1 -0
  224. package/dist/services/connections/admin.d.ts +80 -0
  225. package/dist/services/connections/admin.js +337 -0
  226. package/dist/services/connections/admin.js.map +1 -0
  227. package/dist/services/connections/apply.d.ts +104 -0
  228. package/dist/services/connections/apply.js +415 -0
  229. package/dist/services/connections/apply.js.map +1 -0
  230. package/dist/services/connections/resolver.d.ts +82 -0
  231. package/dist/services/connections/resolver.js +289 -0
  232. package/dist/services/connections/resolver.js.map +1 -0
  233. package/dist/services/connections/transactor.d.ts +39 -0
  234. package/dist/services/connections/transactor.js +307 -0
  235. package/dist/services/connections/transactor.js.map +1 -0
  236. package/dist/services/files/bootstrap.d.ts +7 -0
  237. package/dist/services/files/bootstrap.js +16 -0
  238. package/dist/services/files/bootstrap.js.map +1 -0
  239. package/dist/services/files/external-mounts.js +187 -0
  240. package/dist/services/files/external-mounts.js.map +1 -0
  241. package/dist/services/files/files-manager.d.ts +265 -0
  242. package/dist/services/files/files-manager.js +1189 -0
  243. package/dist/services/files/files-manager.js.map +1 -0
  244. package/dist/services/files/files-mounts.d.ts +42 -0
  245. package/dist/services/files/files-mounts.js +207 -0
  246. package/dist/services/files/files-mounts.js.map +1 -0
  247. package/dist/services/files/organize/applier.js +218 -0
  248. package/dist/services/files/organize/applier.js.map +1 -0
  249. package/dist/services/files/organize/rules.js +286 -0
  250. package/dist/services/files/organize/rules.js.map +1 -0
  251. package/dist/services/files/organize/scanner.js +366 -0
  252. package/dist/services/files/organize/scanner.js.map +1 -0
  253. package/dist/services/files/organize/store.js +82 -0
  254. package/dist/services/files/organize/store.js.map +1 -0
  255. package/dist/services/files/photos/upload-page.d.ts +2 -0
  256. package/dist/services/files/photos/upload-page.js +248 -0
  257. package/dist/services/files/photos/upload-page.js.map +1 -0
  258. package/dist/services/files/photos/upload-store.d.ts +74 -0
  259. package/dist/services/files/photos/upload-store.js +432 -0
  260. package/dist/services/files/photos/upload-store.js.map +1 -0
  261. package/dist/services/files/webdav/server.d.ts +47 -0
  262. package/dist/services/files/webdav/server.js +329 -0
  263. package/dist/services/files/webdav/server.js.map +1 -0
  264. package/dist/services/files/webdav/xml-builder.js.map +1 -0
  265. package/dist/services/http/proxy-utils.d.ts +7 -0
  266. package/dist/services/http/proxy-utils.js +29 -0
  267. package/dist/services/http/proxy-utils.js.map +1 -0
  268. package/dist/services/http/request-utils.d.ts +3 -0
  269. package/dist/services/http/request-utils.js +23 -0
  270. package/dist/services/http/request-utils.js.map +1 -0
  271. package/dist/services/instances/admin.d.ts +23 -0
  272. package/dist/services/instances/admin.js +218 -0
  273. package/dist/services/instances/admin.js.map +1 -0
  274. package/dist/services/instances/clone.d.ts +26 -0
  275. package/dist/services/instances/clone.js +78 -0
  276. package/dist/services/instances/clone.js.map +1 -0
  277. package/dist/services/instances/config-admin.d.ts +17 -0
  278. package/dist/services/instances/config-admin.js +181 -0
  279. package/dist/services/instances/config-admin.js.map +1 -0
  280. package/dist/services/instances/manager.d.ts +232 -0
  281. package/dist/services/instances/manager.js +1342 -0
  282. package/dist/services/instances/manager.js.map +1 -0
  283. package/dist/services/instances/pairing.d.ts +17 -0
  284. package/dist/services/instances/pairing.js +53 -0
  285. package/dist/services/instances/pairing.js.map +1 -0
  286. package/dist/services/instances/passwords.js +173 -0
  287. package/dist/services/instances/passwords.js.map +1 -0
  288. package/dist/services/instances/status.d.ts +2 -0
  289. package/dist/services/instances/status.js +11 -0
  290. package/dist/services/instances/status.js.map +1 -0
  291. package/dist/services/instances/types.d.ts +21 -0
  292. package/dist/services/instances/types.js +2 -0
  293. package/dist/services/instances/types.js.map +1 -0
  294. package/dist/services/integrations/anythingllm/integration.d.ts +25 -0
  295. package/dist/services/integrations/anythingllm/integration.js +251 -0
  296. package/dist/services/integrations/anythingllm/integration.js.map +1 -0
  297. package/dist/services/integrations/catalog.d.ts +3 -0
  298. package/dist/services/integrations/catalog.js +73 -0
  299. package/dist/services/integrations/catalog.js.map +1 -0
  300. package/dist/services/integrations/custom/integration.d.ts +28 -0
  301. package/dist/services/integrations/custom/integration.js +179 -0
  302. package/dist/services/integrations/custom/integration.js.map +1 -0
  303. package/dist/services/integrations/hermes/integration.d.ts +194 -0
  304. package/dist/services/integrations/hermes/integration.js +1668 -0
  305. package/dist/services/integrations/hermes/integration.js.map +1 -0
  306. package/dist/services/integrations/immich/client.d.ts +93 -0
  307. package/dist/services/integrations/immich/client.js +458 -0
  308. package/dist/services/integrations/immich/client.js.map +1 -0
  309. package/dist/services/integrations/immich/config.d.ts +15 -0
  310. package/dist/services/integrations/immich/config.js +178 -0
  311. package/dist/services/integrations/immich/config.js.map +1 -0
  312. package/dist/services/integrations/immich/discovery.d.ts +9 -0
  313. package/dist/services/integrations/immich/discovery.js +101 -0
  314. package/dist/services/integrations/immich/discovery.js.map +1 -0
  315. package/dist/services/integrations/immich/gallery-renderer.d.ts +5 -0
  316. package/dist/services/integrations/immich/gallery-renderer.js +150 -0
  317. package/dist/services/integrations/immich/gallery-renderer.js.map +1 -0
  318. package/dist/services/integrations/immich/immich-shim.d.ts +11 -0
  319. package/dist/services/integrations/immich/immich-shim.js +439 -0
  320. package/dist/services/integrations/immich/immich-shim.js.map +1 -0
  321. package/dist/services/integrations/immich/integration.d.ts +18 -0
  322. package/dist/services/integrations/immich/integration.js +64 -0
  323. package/dist/services/integrations/immich/integration.js.map +1 -0
  324. package/dist/services/integrations/immich/photo-library.d.ts +4 -0
  325. package/dist/services/integrations/immich/photo-library.js +63 -0
  326. package/dist/services/integrations/immich/photo-library.js.map +1 -0
  327. package/dist/services/integrations/immich/review-executor.d.ts +3 -0
  328. package/dist/services/integrations/immich/review-executor.js +41 -0
  329. package/dist/services/integrations/immich/review-executor.js.map +1 -0
  330. package/dist/services/integrations/immich/review-session-service.d.ts +27 -0
  331. package/dist/services/integrations/immich/review-session-service.js +206 -0
  332. package/dist/services/integrations/immich/review-session-service.js.map +1 -0
  333. package/dist/services/integrations/immich/review-store.d.ts +47 -0
  334. package/dist/services/integrations/immich/review-store.js +347 -0
  335. package/dist/services/integrations/immich/review-store.js.map +1 -0
  336. package/dist/services/integrations/immich/routes.d.ts +7 -0
  337. package/dist/services/integrations/immich/routes.js +363 -0
  338. package/dist/services/integrations/immich/routes.js.map +1 -0
  339. package/dist/services/integrations/immich/types.d.ts +186 -0
  340. package/dist/services/integrations/immich/types.js +2 -0
  341. package/dist/services/integrations/immich/types.js.map +1 -0
  342. package/dist/services/integrations/index.d.ts +41 -0
  343. package/dist/services/integrations/index.js +60 -0
  344. package/dist/services/integrations/index.js.map +1 -0
  345. package/dist/services/integrations/installable/catalog.d.ts +33 -0
  346. package/dist/services/integrations/installable/catalog.js +88 -0
  347. package/dist/services/integrations/installable/catalog.js.map +1 -0
  348. package/dist/services/integrations/installable/index.d.ts +35 -0
  349. package/dist/services/integrations/installable/index.js +170 -0
  350. package/dist/services/integrations/installable/index.js.map +1 -0
  351. package/dist/services/integrations/installable/installers/integration-probes.d.ts +50 -0
  352. package/dist/services/integrations/installable/installers/integration-probes.js +231 -0
  353. package/dist/services/integrations/installable/installers/integration-probes.js.map +1 -0
  354. package/dist/services/integrations/installable/installers/integration.d.ts +30 -0
  355. package/dist/services/integrations/installable/installers/integration.js +283 -0
  356. package/dist/services/integrations/installable/installers/integration.js.map +1 -0
  357. package/dist/services/integrations/installable/installers/registry-probe.js.map +1 -0
  358. package/dist/services/integrations/installable/installers/shell-script.d.ts +46 -0
  359. package/dist/services/integrations/installable/installers/shell-script.js +487 -0
  360. package/dist/services/integrations/installable/installers/shell-script.js.map +1 -0
  361. package/dist/services/integrations/installable/types.d.ts +130 -0
  362. package/dist/services/integrations/installable/types.js +19 -0
  363. package/dist/services/integrations/installable/types.js.map +1 -0
  364. package/dist/services/integrations/jishukb/integration.d.ts +24 -0
  365. package/dist/services/integrations/jishukb/integration.js +300 -0
  366. package/dist/services/integrations/jishukb/integration.js.map +1 -0
  367. package/dist/services/integrations/openclaw/anythingllm-shim.d.ts +46 -0
  368. package/dist/services/integrations/openclaw/anythingllm-shim.js +281 -0
  369. package/dist/services/integrations/openclaw/anythingllm-shim.js.map +1 -0
  370. package/dist/services/integrations/openclaw/drive-shim.js +490 -0
  371. package/dist/services/integrations/openclaw/drive-shim.js.map +1 -0
  372. package/dist/services/integrations/openclaw/integration.d.ts +438 -0
  373. package/dist/services/integrations/openclaw/integration.js +4629 -0
  374. package/dist/services/integrations/openclaw/integration.js.map +1 -0
  375. package/dist/services/integrations/openclaw/jishukb-native-mcp.d.ts +58 -0
  376. package/dist/services/integrations/openclaw/jishukb-native-mcp.js +373 -0
  377. package/dist/services/integrations/openclaw/jishukb-native-mcp.js.map +1 -0
  378. package/dist/services/integrations/openclaw/jishukb-shim.d.ts +52 -0
  379. package/dist/services/integrations/openclaw/jishukb-shim.js +1357 -0
  380. package/dist/services/integrations/openclaw/jishukb-shim.js.map +1 -0
  381. package/dist/services/integrations/openclaw/mcporter-lite.js +276 -0
  382. package/dist/services/integrations/openclaw/mcporter-lite.js.map +1 -0
  383. package/dist/services/integrations/openclaw/mcporter.d.ts +59 -0
  384. package/dist/services/integrations/openclaw/mcporter.js +143 -0
  385. package/dist/services/integrations/openclaw/mcporter.js.map +1 -0
  386. package/dist/services/integrations/openclaw/native-mcp.d.ts +48 -0
  387. package/dist/services/integrations/openclaw/native-mcp.js +125 -0
  388. package/dist/services/integrations/openclaw/native-mcp.js.map +1 -0
  389. package/dist/services/integrations/openclaw/routes.d.ts +21 -0
  390. package/dist/services/integrations/openclaw/routes.js +1194 -0
  391. package/dist/services/integrations/openclaw/routes.js.map +1 -0
  392. package/dist/services/integrations/registry.d.ts +17 -0
  393. package/dist/services/integrations/registry.js +36 -0
  394. package/dist/services/integrations/registry.js.map +1 -0
  395. package/dist/services/integrations/routes.d.ts +2 -0
  396. package/dist/services/integrations/routes.js +9 -0
  397. package/dist/services/integrations/routes.js.map +1 -0
  398. package/dist/services/integrations/types.d.ts +457 -0
  399. package/dist/services/integrations/types.js +2 -0
  400. package/dist/services/integrations/types.js.map +1 -0
  401. package/dist/services/legacy-migrator/classifier.d.ts +44 -0
  402. package/dist/services/legacy-migrator/classifier.js +309 -0
  403. package/dist/services/legacy-migrator/classifier.js.map +1 -0
  404. package/dist/services/legacy-migrator/executor.d.ts +42 -0
  405. package/dist/services/legacy-migrator/executor.js +637 -0
  406. package/dist/services/legacy-migrator/executor.js.map +1 -0
  407. package/dist/services/legacy-migrator/index.d.ts +31 -0
  408. package/dist/services/legacy-migrator/index.js +34 -0
  409. package/dist/services/legacy-migrator/index.js.map +1 -0
  410. package/dist/services/legacy-migrator/planner.d.ts +8 -0
  411. package/dist/services/legacy-migrator/planner.js +154 -0
  412. package/dist/services/legacy-migrator/planner.js.map +1 -0
  413. package/dist/services/legacy-migrator/provider-settings.d.ts +6 -0
  414. package/dist/services/legacy-migrator/provider-settings.js +72 -0
  415. package/dist/services/legacy-migrator/provider-settings.js.map +1 -0
  416. package/dist/services/legacy-migrator/report.d.ts +9 -0
  417. package/dist/services/legacy-migrator/report.js +99 -0
  418. package/dist/services/legacy-migrator/report.js.map +1 -0
  419. package/dist/services/legacy-migrator/scanner.d.ts +13 -0
  420. package/dist/services/legacy-migrator/scanner.js +157 -0
  421. package/dist/services/legacy-migrator/scanner.js.map +1 -0
  422. package/dist/services/legacy-migrator/types.d.ts +97 -0
  423. package/dist/services/legacy-migrator/types.js +23 -0
  424. package/dist/services/legacy-migrator/types.js.map +1 -0
  425. package/dist/services/llm-proxy/instance-proxy.d.ts +17 -1
  426. package/dist/services/llm-proxy/instance-proxy.js +171 -44
  427. package/dist/services/llm-proxy/instance-proxy.js.map +1 -1
  428. package/dist/services/llm-proxy/probe.js +5 -14
  429. package/dist/services/llm-proxy/probe.js.map +1 -1
  430. package/dist/services/llm-proxy/providers.js +23 -31
  431. package/dist/services/llm-proxy/providers.js.map +1 -1
  432. package/dist/services/llm-proxy/ssrf.d.ts +11 -4
  433. package/dist/services/llm-proxy/ssrf.js +45 -7
  434. package/dist/services/llm-proxy/ssrf.js.map +1 -1
  435. package/dist/services/llm-proxy/validate-key.js +16 -37
  436. package/dist/services/llm-proxy/validate-key.js.map +1 -1
  437. package/dist/services/repair/runtime-repair.d.ts +22 -0
  438. package/dist/services/repair/runtime-repair.js +374 -0
  439. package/dist/services/repair/runtime-repair.js.map +1 -0
  440. package/dist/services/runtime/docker-network.d.ts +8 -0
  441. package/dist/services/runtime/docker-network.js +123 -0
  442. package/dist/services/runtime/docker-network.js.map +1 -0
  443. package/dist/services/runtime/driver-registry.d.ts +25 -0
  444. package/dist/services/runtime/driver-registry.js +22 -0
  445. package/dist/services/runtime/driver-registry.js.map +1 -0
  446. package/dist/services/runtime/drivers/nomad.d.ts +261 -0
  447. package/dist/services/runtime/drivers/nomad.js +3122 -0
  448. package/dist/services/runtime/drivers/nomad.js.map +1 -0
  449. package/dist/services/runtime/errors.d.ts +3 -3
  450. package/dist/services/runtime/errors.js +3 -3
  451. package/dist/services/runtime/instance.d.ts +14 -16
  452. package/dist/services/runtime/instance.js +93 -123
  453. package/dist/services/runtime/instance.js.map +1 -1
  454. package/dist/services/runtime/job-id.d.ts +1 -1
  455. package/dist/services/runtime/job-id.js +1 -1
  456. package/dist/services/runtime/mcp-shims/firewall.d.ts +2 -2
  457. package/dist/services/runtime/mcp-shims/firewall.js +2 -2
  458. package/dist/services/runtime/mcp-shims/searxng-shim.d.ts +3 -5
  459. package/dist/services/runtime/mcp-shims/searxng-shim.js +3 -5
  460. package/dist/services/runtime/mcp-shims/searxng-shim.js.map +1 -1
  461. package/dist/services/runtime/mcp-shims/write-mcp-entry.d.ts +20 -20
  462. package/dist/services/runtime/mcp-shims/write-mcp-entry.js +16 -16
  463. package/dist/services/runtime/mcp-shims/write-mcp-entry.js.map +1 -1
  464. package/dist/services/runtime/ownership-marker.d.ts +83 -0
  465. package/dist/services/runtime/ownership-marker.js +109 -0
  466. package/dist/services/runtime/ownership-marker.js.map +1 -0
  467. package/dist/services/runtime/service-manager.d.ts +2 -0
  468. package/dist/services/runtime/service-manager.js +18 -0
  469. package/dist/services/runtime/service-manager.js.map +1 -0
  470. package/dist/services/runtime/types.d.ts +23 -501
  471. package/dist/services/runtime/types.js +0 -12
  472. package/dist/services/runtime/types.js.map +1 -1
  473. package/dist/services/runtime/workload-compiler.d.ts +17 -0
  474. package/dist/services/runtime/workload-compiler.js +550 -0
  475. package/dist/services/runtime/workload-compiler.js.map +1 -0
  476. package/dist/services/runtime/workload-types.d.ts +11 -0
  477. package/dist/services/runtime/workload-types.js +2 -0
  478. package/dist/services/runtime/workload-types.js.map +1 -0
  479. package/dist/services/setup/core-manager.d.ts +50 -0
  480. package/dist/services/setup/core-manager.js +456 -0
  481. package/dist/services/setup/core-manager.js.map +1 -0
  482. package/dist/services/setup/plugin-installer.js +136 -0
  483. package/dist/services/setup/plugin-installer.js.map +1 -0
  484. package/dist/services/setup/setup-manager.d.ts +158 -0
  485. package/dist/services/setup/setup-manager.js +2724 -0
  486. package/dist/services/setup/setup-manager.js.map +1 -0
  487. package/dist/services/system/cli-command.d.ts +5 -0
  488. package/dist/services/system/cli-command.js +18 -0
  489. package/dist/services/system/cli-command.js.map +1 -0
  490. package/dist/services/system/macos-launchd.js +312 -0
  491. package/dist/services/system/macos-launchd.js.map +1 -0
  492. package/dist/services/system/repair-orchestrator.d.ts +71 -0
  493. package/dist/services/system/repair-orchestrator.js +412 -0
  494. package/dist/services/system/repair-orchestrator.js.map +1 -0
  495. package/dist/services/system/runtime-ownership.d.ts +36 -0
  496. package/dist/services/system/runtime-ownership.js +250 -0
  497. package/dist/services/system/runtime-ownership.js.map +1 -0
  498. package/dist/services/system/system-monitor.js +96 -0
  499. package/dist/services/system/system-monitor.js.map +1 -0
  500. package/dist/services/system/system-ollama-provider.d.ts +14 -0
  501. package/dist/services/system/system-ollama-provider.js +129 -0
  502. package/dist/services/system/system-ollama-provider.js.map +1 -0
  503. package/dist/services/system/system-reconciler.d.ts +59 -0
  504. package/dist/services/system/system-reconciler.js +763 -0
  505. package/dist/services/system/system-reconciler.js.map +1 -0
  506. package/dist/services/system/update-manager.d.ts +43 -0
  507. package/dist/services/system/update-manager.js +315 -0
  508. package/dist/services/system/update-manager.js.map +1 -0
  509. package/dist/services/system/upgrade-finalize.d.ts +80 -0
  510. package/dist/services/system/upgrade-finalize.js +507 -0
  511. package/dist/services/system/upgrade-finalize.js.map +1 -0
  512. package/dist/services/tasks/registry.d.ts +44 -0
  513. package/dist/services/tasks/registry.js +90 -0
  514. package/dist/services/tasks/registry.js.map +1 -0
  515. package/dist/services/telemetry/activation.d.ts +6 -2
  516. package/dist/services/telemetry/activation.js +6 -2
  517. package/dist/services/telemetry/activation.js.map +1 -1
  518. package/dist/services/telemetry/heartbeat.d.ts +6 -2
  519. package/dist/services/telemetry/heartbeat.js +6 -2
  520. package/dist/services/telemetry/heartbeat.js.map +1 -1
  521. package/dist/services/workspaces/builder.d.ts +29 -0
  522. package/dist/services/workspaces/builder.js +186 -0
  523. package/dist/services/workspaces/builder.js.map +1 -0
  524. package/dist/types.d.ts +350 -48
  525. package/dist/utils/instance-lock.d.ts +2 -2
  526. package/dist/utils/instance-lock.js +2 -2
  527. package/dist/utils/path-safety.js +1 -1
  528. package/dist/utils/service-user.d.ts +13 -0
  529. package/dist/utils/service-user.js +129 -0
  530. package/dist/utils/service-user.js.map +1 -0
  531. package/install/jishu-install.sh +107 -27
  532. package/install/jishu-uninstall.sh +8 -0
  533. package/install/post-install.sh +162 -185
  534. package/install/post-uninstall.sh +6 -0
  535. package/node_modules/@fastify/static/.github/workflows/ci.yml +1 -1
  536. package/node_modules/@fastify/static/.github/workflows/lock-threads.yml +19 -0
  537. package/node_modules/@fastify/static/LICENSE +1 -3
  538. package/node_modules/@fastify/static/example/server-benchmark.js +39 -0
  539. package/node_modules/@fastify/static/index.js +169 -23
  540. package/node_modules/@fastify/static/lib/dirList.js +20 -6
  541. package/node_modules/@fastify/static/package.json +10 -8
  542. package/node_modules/@fastify/static/test/dir-list.test.js +82 -0
  543. package/node_modules/@fastify/static/test/static.test.js +326 -4
  544. package/node_modules/@fastify/static/types/index.d.ts +0 -4
  545. package/node_modules/@fastify/static/types/index.test-d.ts +1 -1
  546. package/node_modules/brace-expansion/dist/commonjs/index.js +24 -14
  547. package/node_modules/brace-expansion/dist/commonjs/index.js.map +1 -1
  548. package/node_modules/brace-expansion/dist/esm/index.js +24 -14
  549. package/node_modules/brace-expansion/dist/esm/index.js.map +1 -1
  550. package/node_modules/brace-expansion/package.json +2 -2
  551. package/node_modules/content-disposition/README.md +21 -22
  552. package/node_modules/content-disposition/index.js +122 -44
  553. package/node_modules/content-disposition/package.json +16 -20
  554. package/node_modules/fast-uri/index.js +1 -1
  555. package/node_modules/fast-uri/package.json +1 -1
  556. package/node_modules/fast-uri/test/security.test.js +28 -0
  557. package/node_modules/fastify/SECURITY.md +1 -1
  558. package/node_modules/fastify/SPONSORS.md +6 -4
  559. package/node_modules/fastify/docs/Guides/Database.md +0 -28
  560. package/node_modules/fastify/docs/Guides/Ecosystem.md +13 -2
  561. package/node_modules/fastify/docs/Guides/Serverless.md +2 -2
  562. package/node_modules/fastify/docs/Guides/Write-Plugin.md +1 -1
  563. package/node_modules/fastify/docs/Reference/Encapsulation.md +27 -26
  564. package/node_modules/fastify/docs/Reference/Errors.md +10 -4
  565. package/node_modules/fastify/docs/Reference/HTTP2.md +10 -10
  566. package/node_modules/fastify/docs/Reference/Hooks.md +4 -4
  567. package/node_modules/fastify/docs/Reference/Index.md +14 -16
  568. package/node_modules/fastify/docs/Reference/LTS.md +12 -13
  569. package/node_modules/fastify/docs/Reference/Lifecycle.md +9 -8
  570. package/node_modules/fastify/docs/Reference/Logging.md +44 -39
  571. package/node_modules/fastify/docs/Reference/Middleware.md +21 -25
  572. package/node_modules/fastify/docs/Reference/Principles.md +2 -2
  573. package/node_modules/fastify/docs/Reference/Reply.md +6 -1
  574. package/node_modules/fastify/docs/Reference/Request.md +27 -16
  575. package/node_modules/fastify/docs/Reference/Routes.md +5 -2
  576. package/node_modules/fastify/docs/Reference/Server.md +31 -3
  577. package/node_modules/fastify/docs/Reference/Type-Providers.md +29 -5
  578. package/node_modules/fastify/docs/Reference/Validation-and-Serialization.md +15 -2
  579. package/node_modules/fastify/docs/Reference/Warnings.md +7 -6
  580. package/node_modules/fastify/eslint.config.js +7 -2
  581. package/node_modules/fastify/fastify.d.ts +8 -3
  582. package/node_modules/fastify/fastify.js +43 -14
  583. package/node_modules/fastify/lib/content-type-parser.js +13 -1
  584. package/node_modules/fastify/lib/decorate.js +11 -3
  585. package/node_modules/fastify/lib/error-handler.js +4 -3
  586. package/node_modules/fastify/lib/error-serializer.js +59 -59
  587. package/node_modules/fastify/lib/errors.js +16 -1
  588. package/node_modules/fastify/lib/four-oh-four.js +14 -9
  589. package/node_modules/fastify/lib/handle-request.js +11 -5
  590. package/node_modules/fastify/lib/plugin-override.js +2 -1
  591. package/node_modules/fastify/lib/plugin-utils.js +5 -5
  592. package/node_modules/fastify/lib/reply.js +63 -8
  593. package/node_modules/fastify/lib/request.js +14 -4
  594. package/node_modules/fastify/lib/route.js +20 -6
  595. package/node_modules/fastify/lib/schema-controller.js +1 -1
  596. package/node_modules/fastify/lib/schemas.js +37 -30
  597. package/node_modules/fastify/lib/symbols.js +3 -1
  598. package/node_modules/fastify/lib/validation.js +1 -13
  599. package/node_modules/fastify/lib/warnings.js +3 -3
  600. package/node_modules/fastify/package.json +13 -15
  601. package/node_modules/fastify/scripts/validate-ecosystem-links.js +1 -0
  602. package/node_modules/fastify/test/bundler/esbuild/package.json +1 -1
  603. package/node_modules/fastify/test/close-pipelining.test.js +1 -2
  604. package/node_modules/fastify/test/custom-http-server.test.js +38 -0
  605. package/node_modules/fastify/test/decorator-instance-properties.test.js +63 -0
  606. package/node_modules/fastify/test/diagnostics-channel/async-error-handler.test.js +74 -0
  607. package/node_modules/fastify/test/hooks.test.js +23 -0
  608. package/node_modules/fastify/test/http-methods/get.test.js +1 -1
  609. package/node_modules/fastify/test/http2/plain.test.js +135 -0
  610. package/node_modules/fastify/test/http2/secure-with-fallback.test.js +1 -1
  611. package/node_modules/fastify/test/https/https.test.js +1 -2
  612. package/node_modules/fastify/test/internals/errors.test.js +31 -1
  613. package/node_modules/fastify/test/internals/plugin.test.js +3 -1
  614. package/node_modules/fastify/test/internals/request.test.js +27 -3
  615. package/node_modules/fastify/test/internals/schema-controller-perf.test.js +33 -0
  616. package/node_modules/fastify/test/logger/logging.test.js +18 -1
  617. package/node_modules/fastify/test/logger/options.test.js +38 -1
  618. package/node_modules/fastify/test/reply-error.test.js +1 -1
  619. package/node_modules/fastify/test/reply-trailers.test.js +70 -0
  620. package/node_modules/fastify/test/request-media-type.test.js +105 -0
  621. package/node_modules/fastify/test/route-prefix.test.js +34 -0
  622. package/node_modules/fastify/test/router-options.test.js +222 -11
  623. package/node_modules/fastify/test/schema-serialization.test.js +108 -0
  624. package/node_modules/fastify/test/schema-validation.test.js +24 -0
  625. package/node_modules/fastify/test/scripts/validate-ecosystem-links.test.js +40 -57
  626. package/node_modules/fastify/test/throw.test.js +14 -0
  627. package/node_modules/fastify/test/trust-proxy.test.js +21 -0
  628. package/node_modules/fastify/test/types/content-type-parser.tst.ts +70 -0
  629. package/node_modules/fastify/test/types/decorate-request-reply.tst.ts +18 -0
  630. package/node_modules/fastify/test/types/dummy-plugin.mts +9 -0
  631. package/node_modules/fastify/test/types/errors.tst.ts +91 -0
  632. package/node_modules/fastify/test/types/fastify.tst.ts +351 -0
  633. package/node_modules/fastify/test/types/hooks.tst.ts +578 -0
  634. package/node_modules/fastify/test/types/instance.tst.ts +597 -0
  635. package/node_modules/fastify/test/types/logger.tst.ts +276 -0
  636. package/node_modules/fastify/test/types/plugin.tst.ts +96 -0
  637. package/node_modules/fastify/test/types/register.tst.ts +245 -0
  638. package/node_modules/fastify/test/types/reply.tst.ts +297 -0
  639. package/node_modules/fastify/test/types/request.tst.ts +199 -0
  640. package/node_modules/fastify/test/types/route.tst.ts +576 -0
  641. package/node_modules/fastify/test/types/schema.tst.ts +135 -0
  642. package/node_modules/fastify/test/types/serverFactory.tst.ts +37 -0
  643. package/node_modules/fastify/test/types/tsconfig.json +9 -0
  644. package/node_modules/fastify/test/types/type-provider.tst.ts +1219 -0
  645. package/node_modules/fastify/test/types/using.tst.ts +14 -0
  646. package/node_modules/fastify/types/errors.d.ts +3 -0
  647. package/node_modules/fastify/types/request.d.ts +23 -2
  648. package/node_modules/glob/README.md +39 -130
  649. package/node_modules/glob/dist/commonjs/glob.d.ts +8 -0
  650. package/node_modules/glob/dist/commonjs/glob.d.ts.map +1 -1
  651. package/node_modules/glob/dist/commonjs/glob.js +2 -1
  652. package/node_modules/glob/dist/commonjs/glob.js.map +1 -1
  653. package/node_modules/glob/dist/commonjs/index.min.js +4 -0
  654. package/node_modules/glob/dist/commonjs/index.min.js.map +7 -0
  655. package/node_modules/glob/dist/commonjs/pattern.d.ts +3 -0
  656. package/node_modules/glob/dist/commonjs/pattern.d.ts.map +1 -1
  657. package/node_modules/glob/dist/commonjs/pattern.js +4 -0
  658. package/node_modules/glob/dist/commonjs/pattern.js.map +1 -1
  659. package/node_modules/glob/dist/esm/glob.d.ts +8 -0
  660. package/node_modules/glob/dist/esm/glob.d.ts.map +1 -1
  661. package/node_modules/glob/dist/esm/glob.js +2 -1
  662. package/node_modules/glob/dist/esm/glob.js.map +1 -1
  663. package/node_modules/glob/dist/esm/index.min.js +4 -0
  664. package/node_modules/glob/dist/esm/index.min.js.map +7 -0
  665. package/node_modules/glob/dist/esm/pattern.d.ts +3 -0
  666. package/node_modules/glob/dist/esm/pattern.d.ts.map +1 -1
  667. package/node_modules/glob/dist/esm/pattern.js +4 -0
  668. package/node_modules/glob/dist/esm/pattern.js.map +1 -1
  669. package/node_modules/glob/package.json +38 -37
  670. package/node_modules/jishushell-panel/README.md +4 -4
  671. package/node_modules/jishushell-panel/output/dist/server.js +17 -6
  672. package/node_modules/jishushell-panel/output/dist/server.js.map +1 -1
  673. package/node_modules/jishushell-panel/output/public/assets/ApiKeyField-Ce5d1xna.js +1 -0
  674. package/node_modules/jishushell-panel/output/public/assets/Dashboard-BXame3yg.js +1 -0
  675. package/node_modules/jishushell-panel/output/public/assets/HermesChatPanel-BHZtPCJd.js +1 -0
  676. package/node_modules/jishushell-panel/output/public/assets/HermesConfigForm-CB3GbNX9.js +4 -0
  677. package/node_modules/jishushell-panel/output/public/assets/InitPassword-Boab9F6g.js +1 -0
  678. package/node_modules/jishushell-panel/output/public/assets/InstanceDetail-DrIWCqo-.js +14 -0
  679. package/node_modules/jishushell-panel/output/public/assets/Login-CzpOkNau.js +1 -0
  680. package/node_modules/jishushell-panel/output/public/assets/NewInstance-CANXyCcL.js +1 -0
  681. package/node_modules/jishushell-panel/output/public/assets/ProviderRecommendations-BABo9VOC.js +1 -0
  682. package/node_modules/jishushell-panel/output/public/assets/Settings-CKp5XxFh.js +1 -0
  683. package/node_modules/jishushell-panel/output/public/assets/Setup-C7xVDPow.js +1 -0
  684. package/node_modules/jishushell-panel/output/public/assets/WeixinLoginPanel-B765Xz4C.js +1 -0
  685. package/node_modules/jishushell-panel/output/public/assets/api-C70Gt678.js +4 -0
  686. package/node_modules/jishushell-panel/output/public/assets/index-Bs6DSbiR.js +23 -0
  687. package/node_modules/jishushell-panel/output/public/assets/index-DnnqTf7s.css +1 -0
  688. package/node_modules/jishushell-panel/output/public/assets/registry-sWIZsIEF.js +2 -0
  689. package/node_modules/jishushell-panel/output/public/assets/rolldown-runtime-QTnfLwEv.js +1 -0
  690. package/node_modules/jishushell-panel/output/public/assets/setup-task-q21GnI0E.js +1 -0
  691. package/node_modules/jishushell-panel/output/public/assets/usePolling-D4IDOQd_.js +1 -0
  692. package/node_modules/jishushell-panel/output/public/assets/vendor-i18n-Df8aUdv8.js +1 -0
  693. package/node_modules/jishushell-panel/output/public/assets/vendor-react-0L0rjmYG.js +8 -0
  694. package/node_modules/jishushell-panel/output/public/index.html +6 -4
  695. package/node_modules/jishushell-panel/package.json +2 -2
  696. package/node_modules/semver/classes/range.js +17 -4
  697. package/node_modules/semver/package.json +2 -2
  698. package/package.json +12 -64
  699. package/scripts/check-app-path-boundaries.mjs +121 -0
  700. package/scripts/check-app-spec.mjs +123 -29
  701. package/scripts/check-architecture-boundaries.mjs +178 -0
  702. package/scripts/check-colima-launchd.mjs +10 -8
  703. package/scripts/check-integration-isolation.ts +541 -0
  704. package/scripts/check-new-file-tests.mjs +11 -3
  705. package/scripts/check-open-core-boundaries.mjs +60 -10
  706. package/scripts/check-test-layering.sh +1 -1
  707. package/scripts/fixtures/instances/hermes-sample/instance.json +3 -2
  708. package/scripts/fixtures/instances/legacy-openclaw-sample/instance.json +1 -1
  709. package/scripts/local-web-upgrade-test.README +4 -3
  710. package/scripts/local-web-upgrade-test.example.env +2 -2
  711. package/scripts/local-web-upgrade-test.sh +14 -1
  712. package/scripts/pack-gui-and-send-pi.sh +43 -0
  713. package/scripts/perf/instances.js +1 -1
  714. package/scripts/prune-open-core-dist.mjs +89 -2
  715. package/scripts/smoke/hermes-bootstrap.sh +5 -5
  716. package/templates/hermes-entrypoint.sh +19 -29
  717. package/apps/openwebui-container.yaml +0 -97
  718. package/apps/playwright-container.yaml +0 -126
  719. package/dependencies/jishushell-panel-0.6.5.tgz +0 -0
  720. package/dist/crypto-shim.d.ts +0 -1
  721. package/dist/crypto-shim.js +0 -2
  722. package/dist/crypto-shim.js.map +0 -1
  723. package/dist/routes/agent-apps.d.ts +0 -14
  724. package/dist/routes/agent-apps.js +0 -77
  725. package/dist/routes/agent-apps.js.map +0 -1
  726. package/dist/routes/internal.d.ts +0 -2
  727. package/dist/routes/internal.js +0 -55
  728. package/dist/routes/internal.js.map +0 -1
  729. package/dist/routes/openclaw-routes.d.ts +0 -22
  730. package/dist/routes/openclaw-routes.js +0 -1020
  731. package/dist/routes/openclaw-routes.js.map +0 -1
  732. package/dist/routes/runtime.d.ts +0 -15
  733. package/dist/routes/runtime.js +0 -76
  734. package/dist/routes/runtime.js.map +0 -1
  735. package/dist/services/agent-apps/catalog.d.ts +0 -33
  736. package/dist/services/agent-apps/catalog.js +0 -88
  737. package/dist/services/agent-apps/catalog.js.map +0 -1
  738. package/dist/services/agent-apps/index.d.ts +0 -36
  739. package/dist/services/agent-apps/index.js +0 -171
  740. package/dist/services/agent-apps/index.js.map +0 -1
  741. package/dist/services/agent-apps/installers/adapter-probes.d.ts +0 -49
  742. package/dist/services/agent-apps/installers/adapter-probes.js +0 -230
  743. package/dist/services/agent-apps/installers/adapter-probes.js.map +0 -1
  744. package/dist/services/agent-apps/installers/adapter.d.ts +0 -30
  745. package/dist/services/agent-apps/installers/adapter.js +0 -171
  746. package/dist/services/agent-apps/installers/adapter.js.map +0 -1
  747. package/dist/services/agent-apps/installers/registry-probe.js.map +0 -1
  748. package/dist/services/agent-apps/installers/shell-script.d.ts +0 -47
  749. package/dist/services/agent-apps/installers/shell-script.js +0 -488
  750. package/dist/services/agent-apps/installers/shell-script.js.map +0 -1
  751. package/dist/services/agent-apps/types.d.ts +0 -128
  752. package/dist/services/agent-apps/types.js +0 -17
  753. package/dist/services/agent-apps/types.js.map +0 -1
  754. package/dist/services/app/app-compiler.js +0 -185
  755. package/dist/services/app/app-compiler.js.map +0 -1
  756. package/dist/services/app/app-manager.d.ts +0 -184
  757. package/dist/services/app/app-manager.js +0 -2933
  758. package/dist/services/app/app-manager.js.map +0 -1
  759. package/dist/services/app/custom-manager.d.ts +0 -27
  760. package/dist/services/app/custom-manager.js +0 -382
  761. package/dist/services/app/custom-manager.js.map +0 -1
  762. package/dist/services/app/hermes-agent-manager.d.ts +0 -20
  763. package/dist/services/app/hermes-agent-manager.js +0 -299
  764. package/dist/services/app/hermes-agent-manager.js.map +0 -1
  765. package/dist/services/app/id-normalizer.d.ts +0 -27
  766. package/dist/services/app/id-normalizer.js +0 -77
  767. package/dist/services/app/id-normalizer.js.map +0 -1
  768. package/dist/services/app/ollama-manager.d.ts +0 -18
  769. package/dist/services/app/ollama-manager.js +0 -224
  770. package/dist/services/app/ollama-manager.js.map +0 -1
  771. package/dist/services/app/openclaw-manager.d.ts +0 -63
  772. package/dist/services/app/openclaw-manager.js +0 -1215
  773. package/dist/services/app/openclaw-manager.js.map +0 -1
  774. package/dist/services/app/paths.d.ts +0 -27
  775. package/dist/services/app/paths.js +0 -40
  776. package/dist/services/app/paths.js.map +0 -1
  777. package/dist/services/app/platform-transform.d.ts +0 -32
  778. package/dist/services/app/platform-transform.js +0 -65
  779. package/dist/services/app/platform-transform.js.map +0 -1
  780. package/dist/services/app/provide-resolver.d.ts +0 -29
  781. package/dist/services/app/provide-resolver.js +0 -135
  782. package/dist/services/app/provide-resolver.js.map +0 -1
  783. package/dist/services/app/registry.d.ts +0 -17
  784. package/dist/services/app/registry.js +0 -31
  785. package/dist/services/app/registry.js.map +0 -1
  786. package/dist/services/app/remote-spec.d.ts +0 -14
  787. package/dist/services/app/remote-spec.js +0 -58
  788. package/dist/services/app/remote-spec.js.map +0 -1
  789. package/dist/services/app/terminal-session-manager.js +0 -157
  790. package/dist/services/app/terminal-session-manager.js.map +0 -1
  791. package/dist/services/app/types.d.ts +0 -74
  792. package/dist/services/app/types.js +0 -16
  793. package/dist/services/app/types.js.map +0 -1
  794. package/dist/services/app-config-admin.d.ts +0 -17
  795. package/dist/services/app-config-admin.js +0 -177
  796. package/dist/services/app-config-admin.js.map +0 -1
  797. package/dist/services/app-create-from-installed.d.ts +0 -23
  798. package/dist/services/app-create-from-installed.js +0 -75
  799. package/dist/services/app-create-from-installed.js.map +0 -1
  800. package/dist/services/app-passwords.js +0 -173
  801. package/dist/services/app-passwords.js.map +0 -1
  802. package/dist/services/backup-admin.d.ts +0 -101
  803. package/dist/services/backup-admin.js +0 -259
  804. package/dist/services/backup-admin.js.map +0 -1
  805. package/dist/services/backup-manager.d.ts +0 -264
  806. package/dist/services/backup-manager.js +0 -2263
  807. package/dist/services/backup-manager.js.map +0 -1
  808. package/dist/services/backup-verify.js +0 -240
  809. package/dist/services/backup-verify.js.map +0 -1
  810. package/dist/services/capability-endpoint-validator.d.ts +0 -41
  811. package/dist/services/capability-endpoint-validator.js +0 -114
  812. package/dist/services/capability-endpoint-validator.js.map +0 -1
  813. package/dist/services/capability-health.d.ts +0 -16
  814. package/dist/services/capability-health.js +0 -121
  815. package/dist/services/capability-health.js.map +0 -1
  816. package/dist/services/capability-registry.d.ts +0 -29
  817. package/dist/services/capability-registry.js +0 -176
  818. package/dist/services/capability-registry.js.map +0 -1
  819. package/dist/services/capability-sync.d.ts +0 -4
  820. package/dist/services/capability-sync.js +0 -220
  821. package/dist/services/capability-sync.js.map +0 -1
  822. package/dist/services/connection-admin.d.ts +0 -74
  823. package/dist/services/connection-admin.js +0 -287
  824. package/dist/services/connection-admin.js.map +0 -1
  825. package/dist/services/connection-apply.d.ts +0 -91
  826. package/dist/services/connection-apply.js +0 -471
  827. package/dist/services/connection-apply.js.map +0 -1
  828. package/dist/services/connection-resolver.d.ts +0 -65
  829. package/dist/services/connection-resolver.js +0 -281
  830. package/dist/services/connection-resolver.js.map +0 -1
  831. package/dist/services/connection-transactor.d.ts +0 -39
  832. package/dist/services/connection-transactor.js +0 -354
  833. package/dist/services/connection-transactor.js.map +0 -1
  834. package/dist/services/core-manager.d.ts +0 -50
  835. package/dist/services/core-manager.js +0 -411
  836. package/dist/services/core-manager.js.map +0 -1
  837. package/dist/services/external-mounts.js +0 -187
  838. package/dist/services/external-mounts.js.map +0 -1
  839. package/dist/services/files-manager.d.ts +0 -252
  840. package/dist/services/files-manager.js +0 -1156
  841. package/dist/services/files-manager.js.map +0 -1
  842. package/dist/services/files-mounts.d.ts +0 -42
  843. package/dist/services/files-mounts.js +0 -207
  844. package/dist/services/files-mounts.js.map +0 -1
  845. package/dist/services/instance-admin.d.ts +0 -26
  846. package/dist/services/instance-admin.js +0 -218
  847. package/dist/services/instance-admin.js.map +0 -1
  848. package/dist/services/instance-manager.d.ts +0 -192
  849. package/dist/services/instance-manager.js +0 -1289
  850. package/dist/services/instance-manager.js.map +0 -1
  851. package/dist/services/macos-launchd.js +0 -312
  852. package/dist/services/macos-launchd.js.map +0 -1
  853. package/dist/services/nomad-manager.d.ts +0 -307
  854. package/dist/services/nomad-manager.js +0 -3958
  855. package/dist/services/nomad-manager.js.map +0 -1
  856. package/dist/services/organize/applier.js +0 -218
  857. package/dist/services/organize/applier.js.map +0 -1
  858. package/dist/services/organize/rules.js +0 -286
  859. package/dist/services/organize/rules.js.map +0 -1
  860. package/dist/services/organize/scanner.js +0 -366
  861. package/dist/services/organize/scanner.js.map +0 -1
  862. package/dist/services/organize/store.js +0 -82
  863. package/dist/services/organize/store.js.map +0 -1
  864. package/dist/services/plugin-installer.js +0 -128
  865. package/dist/services/plugin-installer.js.map +0 -1
  866. package/dist/services/process-manager.d.ts +0 -25
  867. package/dist/services/process-manager.js +0 -568
  868. package/dist/services/process-manager.js.map +0 -1
  869. package/dist/services/runtime/adapters/custom.d.ts +0 -20
  870. package/dist/services/runtime/adapters/custom.js +0 -188
  871. package/dist/services/runtime/adapters/custom.js.map +0 -1
  872. package/dist/services/runtime/adapters/hermes.d.ts +0 -204
  873. package/dist/services/runtime/adapters/hermes.js +0 -1684
  874. package/dist/services/runtime/adapters/hermes.js.map +0 -1
  875. package/dist/services/runtime/adapters/openclaw-mcporter.d.ts +0 -45
  876. package/dist/services/runtime/adapters/openclaw-mcporter.js +0 -108
  877. package/dist/services/runtime/adapters/openclaw-mcporter.js.map +0 -1
  878. package/dist/services/runtime/adapters/openclaw.d.ts +0 -426
  879. package/dist/services/runtime/adapters/openclaw.js +0 -3975
  880. package/dist/services/runtime/adapters/openclaw.js.map +0 -1
  881. package/dist/services/runtime/index.d.ts +0 -34
  882. package/dist/services/runtime/index.js +0 -51
  883. package/dist/services/runtime/index.js.map +0 -1
  884. package/dist/services/runtime/mcp-shims/anythingllm-shim.d.ts +0 -46
  885. package/dist/services/runtime/mcp-shims/anythingllm-shim.js +0 -281
  886. package/dist/services/runtime/mcp-shims/anythingllm-shim.js.map +0 -1
  887. package/dist/services/runtime/mcp-shims/drive-shim.js +0 -490
  888. package/dist/services/runtime/mcp-shims/drive-shim.js.map +0 -1
  889. package/dist/services/runtime/mcp-shims/jishukb-shim.d.ts +0 -48
  890. package/dist/services/runtime/mcp-shims/jishukb-shim.js +0 -723
  891. package/dist/services/runtime/mcp-shims/jishukb-shim.js.map +0 -1
  892. package/dist/services/runtime/mcp-shims/mcporter-lite.js +0 -276
  893. package/dist/services/runtime/mcp-shims/mcporter-lite.js.map +0 -1
  894. package/dist/services/runtime/migrations.d.ts +0 -23
  895. package/dist/services/runtime/migrations.js +0 -125
  896. package/dist/services/runtime/migrations.js.map +0 -1
  897. package/dist/services/runtime/registry.d.ts +0 -13
  898. package/dist/services/runtime/registry.js +0 -32
  899. package/dist/services/runtime/registry.js.map +0 -1
  900. package/dist/services/runtime-identity.d.ts +0 -13
  901. package/dist/services/runtime-identity.js +0 -166
  902. package/dist/services/runtime-identity.js.map +0 -1
  903. package/dist/services/runtime-repair.d.ts +0 -52
  904. package/dist/services/runtime-repair.js +0 -352
  905. package/dist/services/runtime-repair.js.map +0 -1
  906. package/dist/services/setup-manager.d.ts +0 -158
  907. package/dist/services/setup-manager.js +0 -2740
  908. package/dist/services/setup-manager.js.map +0 -1
  909. package/dist/services/suggestions.d.ts +0 -27
  910. package/dist/services/suggestions.js +0 -133
  911. package/dist/services/suggestions.js.map +0 -1
  912. package/dist/services/system-monitor.js +0 -79
  913. package/dist/services/system-monitor.js.map +0 -1
  914. package/dist/services/system-ollama-provider.d.ts +0 -14
  915. package/dist/services/system-ollama-provider.js +0 -125
  916. package/dist/services/system-ollama-provider.js.map +0 -1
  917. package/dist/services/system-reconciler.d.ts +0 -72
  918. package/dist/services/system-reconciler.js +0 -600
  919. package/dist/services/system-reconciler.js.map +0 -1
  920. package/dist/services/task-registry.d.ts +0 -44
  921. package/dist/services/task-registry.js +0 -76
  922. package/dist/services/task-registry.js.map +0 -1
  923. package/dist/services/types-shim.d.ts +0 -16
  924. package/dist/services/types-shim.js +0 -2
  925. package/dist/services/types-shim.js.map +0 -1
  926. package/dist/services/update-manager.d.ts +0 -47
  927. package/dist/services/update-manager.js +0 -351
  928. package/dist/services/update-manager.js.map +0 -1
  929. package/dist/services/webdav/server.d.ts +0 -24
  930. package/dist/services/webdav/server.js +0 -420
  931. package/dist/services/webdav/server.js.map +0 -1
  932. package/dist/services/webdav/xml-builder.js.map +0 -1
  933. package/dist/services/workspace-builder.d.ts +0 -29
  934. package/dist/services/workspace-builder.js +0 -188
  935. package/dist/services/workspace-builder.js.map +0 -1
  936. package/node_modules/@fastify/static/.github/stale.yml +0 -21
  937. package/node_modules/@isaacs/cliui/LICENSE.md +0 -63
  938. package/node_modules/@isaacs/cliui/README.md +0 -151
  939. package/node_modules/@isaacs/cliui/dist/commonjs/ansi-regex/index.d.ts +0 -4
  940. package/node_modules/@isaacs/cliui/dist/commonjs/ansi-regex/index.d.ts.map +0 -1
  941. package/node_modules/@isaacs/cliui/dist/commonjs/ansi-regex/index.js +0 -16
  942. package/node_modules/@isaacs/cliui/dist/commonjs/ansi-regex/index.js.map +0 -1
  943. package/node_modules/@isaacs/cliui/dist/commonjs/ansi-styles/index.d.ts +0 -34
  944. package/node_modules/@isaacs/cliui/dist/commonjs/ansi-styles/index.d.ts.map +0 -1
  945. package/node_modules/@isaacs/cliui/dist/commonjs/ansi-styles/index.js +0 -170
  946. package/node_modules/@isaacs/cliui/dist/commonjs/ansi-styles/index.js.map +0 -1
  947. package/node_modules/@isaacs/cliui/dist/commonjs/eastasianwidth/index.d.ts +0 -6
  948. package/node_modules/@isaacs/cliui/dist/commonjs/eastasianwidth/index.d.ts.map +0 -1
  949. package/node_modules/@isaacs/cliui/dist/commonjs/eastasianwidth/index.js +0 -307
  950. package/node_modules/@isaacs/cliui/dist/commonjs/eastasianwidth/index.js.map +0 -1
  951. package/node_modules/@isaacs/cliui/dist/commonjs/emoji-regex/index.d.ts +0 -2
  952. package/node_modules/@isaacs/cliui/dist/commonjs/emoji-regex/index.d.ts.map +0 -1
  953. package/node_modules/@isaacs/cliui/dist/commonjs/emoji-regex/index.js +0 -7
  954. package/node_modules/@isaacs/cliui/dist/commonjs/emoji-regex/index.js.map +0 -1
  955. package/node_modules/@isaacs/cliui/dist/commonjs/index.d.ts +0 -41
  956. package/node_modules/@isaacs/cliui/dist/commonjs/index.d.ts.map +0 -1
  957. package/node_modules/@isaacs/cliui/dist/commonjs/index.js +0 -322
  958. package/node_modules/@isaacs/cliui/dist/commonjs/index.js.map +0 -1
  959. package/node_modules/@isaacs/cliui/dist/commonjs/index.min.js +0 -12
  960. package/node_modules/@isaacs/cliui/dist/commonjs/index.min.js.map +0 -7
  961. package/node_modules/@isaacs/cliui/dist/commonjs/package.json +0 -3
  962. package/node_modules/@isaacs/cliui/dist/commonjs/string-width/index.d.ts +0 -5
  963. package/node_modules/@isaacs/cliui/dist/commonjs/string-width/index.d.ts.map +0 -1
  964. package/node_modules/@isaacs/cliui/dist/commonjs/string-width/index.js +0 -49
  965. package/node_modules/@isaacs/cliui/dist/commonjs/string-width/index.js.map +0 -1
  966. package/node_modules/@isaacs/cliui/dist/commonjs/strip-ansi/index.d.ts +0 -2
  967. package/node_modules/@isaacs/cliui/dist/commonjs/strip-ansi/index.d.ts.map +0 -1
  968. package/node_modules/@isaacs/cliui/dist/commonjs/strip-ansi/index.js +0 -8
  969. package/node_modules/@isaacs/cliui/dist/commonjs/strip-ansi/index.js.map +0 -1
  970. package/node_modules/@isaacs/cliui/dist/commonjs/wrap-ansi/index.d.ts +0 -7
  971. package/node_modules/@isaacs/cliui/dist/commonjs/wrap-ansi/index.d.ts.map +0 -1
  972. package/node_modules/@isaacs/cliui/dist/commonjs/wrap-ansi/index.js +0 -176
  973. package/node_modules/@isaacs/cliui/dist/commonjs/wrap-ansi/index.js.map +0 -1
  974. package/node_modules/@isaacs/cliui/dist/esm/ansi-regex/index.d.ts +0 -4
  975. package/node_modules/@isaacs/cliui/dist/esm/ansi-regex/index.d.ts.map +0 -1
  976. package/node_modules/@isaacs/cliui/dist/esm/ansi-regex/index.js +0 -12
  977. package/node_modules/@isaacs/cliui/dist/esm/ansi-regex/index.js.map +0 -1
  978. package/node_modules/@isaacs/cliui/dist/esm/ansi-styles/index.d.ts +0 -34
  979. package/node_modules/@isaacs/cliui/dist/esm/ansi-styles/index.d.ts.map +0 -1
  980. package/node_modules/@isaacs/cliui/dist/esm/ansi-styles/index.js +0 -167
  981. package/node_modules/@isaacs/cliui/dist/esm/ansi-styles/index.js.map +0 -1
  982. package/node_modules/@isaacs/cliui/dist/esm/eastasianwidth/index.d.ts +0 -6
  983. package/node_modules/@isaacs/cliui/dist/esm/eastasianwidth/index.d.ts.map +0 -1
  984. package/node_modules/@isaacs/cliui/dist/esm/eastasianwidth/index.js +0 -299
  985. package/node_modules/@isaacs/cliui/dist/esm/eastasianwidth/index.js.map +0 -1
  986. package/node_modules/@isaacs/cliui/dist/esm/emoji-regex/index.d.ts +0 -2
  987. package/node_modules/@isaacs/cliui/dist/esm/emoji-regex/index.d.ts.map +0 -1
  988. package/node_modules/@isaacs/cliui/dist/esm/emoji-regex/index.js +0 -3
  989. package/node_modules/@isaacs/cliui/dist/esm/emoji-regex/index.js.map +0 -1
  990. package/node_modules/@isaacs/cliui/dist/esm/index.d.ts +0 -41
  991. package/node_modules/@isaacs/cliui/dist/esm/index.d.ts.map +0 -1
  992. package/node_modules/@isaacs/cliui/dist/esm/index.js +0 -317
  993. package/node_modules/@isaacs/cliui/dist/esm/index.js.map +0 -1
  994. package/node_modules/@isaacs/cliui/dist/esm/index.min.js +0 -12
  995. package/node_modules/@isaacs/cliui/dist/esm/index.min.js.map +0 -7
  996. package/node_modules/@isaacs/cliui/dist/esm/package.json +0 -3
  997. package/node_modules/@isaacs/cliui/dist/esm/string-width/index.d.ts +0 -5
  998. package/node_modules/@isaacs/cliui/dist/esm/string-width/index.d.ts.map +0 -1
  999. package/node_modules/@isaacs/cliui/dist/esm/string-width/index.js +0 -46
  1000. package/node_modules/@isaacs/cliui/dist/esm/string-width/index.js.map +0 -1
  1001. package/node_modules/@isaacs/cliui/dist/esm/strip-ansi/index.d.ts +0 -2
  1002. package/node_modules/@isaacs/cliui/dist/esm/strip-ansi/index.d.ts.map +0 -1
  1003. package/node_modules/@isaacs/cliui/dist/esm/strip-ansi/index.js +0 -4
  1004. package/node_modules/@isaacs/cliui/dist/esm/strip-ansi/index.js.map +0 -1
  1005. package/node_modules/@isaacs/cliui/dist/esm/wrap-ansi/index.d.ts +0 -7
  1006. package/node_modules/@isaacs/cliui/dist/esm/wrap-ansi/index.d.ts.map +0 -1
  1007. package/node_modules/@isaacs/cliui/dist/esm/wrap-ansi/index.js +0 -172
  1008. package/node_modules/@isaacs/cliui/dist/esm/wrap-ansi/index.js.map +0 -1
  1009. package/node_modules/@isaacs/cliui/package.json +0 -163
  1010. package/node_modules/content-disposition/HISTORY.md +0 -60
  1011. package/node_modules/cross-spawn/LICENSE +0 -21
  1012. package/node_modules/cross-spawn/README.md +0 -89
  1013. package/node_modules/cross-spawn/index.js +0 -39
  1014. package/node_modules/cross-spawn/lib/enoent.js +0 -59
  1015. package/node_modules/cross-spawn/lib/parse.js +0 -91
  1016. package/node_modules/cross-spawn/lib/util/escape.js +0 -47
  1017. package/node_modules/cross-spawn/lib/util/readShebang.js +0 -23
  1018. package/node_modules/cross-spawn/lib/util/resolveCommand.js +0 -52
  1019. package/node_modules/cross-spawn/package.json +0 -73
  1020. package/node_modules/fastify/test/types/content-type-parser.test-d.ts +0 -72
  1021. package/node_modules/fastify/test/types/decorate-request-reply.test-d.ts +0 -18
  1022. package/node_modules/fastify/test/types/dummy-plugin.ts +0 -9
  1023. package/node_modules/fastify/test/types/errors.test-d.ts +0 -90
  1024. package/node_modules/fastify/test/types/fastify.test-d.ts +0 -352
  1025. package/node_modules/fastify/test/types/hooks.test-d.ts +0 -550
  1026. package/node_modules/fastify/test/types/import.ts +0 -2
  1027. package/node_modules/fastify/test/types/instance.test-d.ts +0 -588
  1028. package/node_modules/fastify/test/types/logger.test-d.ts +0 -277
  1029. package/node_modules/fastify/test/types/plugin.test-d.ts +0 -97
  1030. package/node_modules/fastify/test/types/register.test-d.ts +0 -237
  1031. package/node_modules/fastify/test/types/reply.test-d.ts +0 -254
  1032. package/node_modules/fastify/test/types/request.test-d.ts +0 -188
  1033. package/node_modules/fastify/test/types/route.test-d.ts +0 -553
  1034. package/node_modules/fastify/test/types/schema.test-d.ts +0 -135
  1035. package/node_modules/fastify/test/types/serverFactory.test-d.ts +0 -37
  1036. package/node_modules/fastify/test/types/type-provider.test-d.ts +0 -1213
  1037. package/node_modules/fastify/test/types/using.test-d.ts +0 -17
  1038. package/node_modules/foreground-child/LICENSE +0 -15
  1039. package/node_modules/foreground-child/README.md +0 -128
  1040. package/node_modules/foreground-child/dist/commonjs/all-signals.d.ts +0 -2
  1041. package/node_modules/foreground-child/dist/commonjs/all-signals.d.ts.map +0 -1
  1042. package/node_modules/foreground-child/dist/commonjs/all-signals.js +0 -58
  1043. package/node_modules/foreground-child/dist/commonjs/all-signals.js.map +0 -1
  1044. package/node_modules/foreground-child/dist/commonjs/index.d.ts +0 -58
  1045. package/node_modules/foreground-child/dist/commonjs/index.d.ts.map +0 -1
  1046. package/node_modules/foreground-child/dist/commonjs/index.js +0 -123
  1047. package/node_modules/foreground-child/dist/commonjs/index.js.map +0 -1
  1048. package/node_modules/foreground-child/dist/commonjs/package.json +0 -3
  1049. package/node_modules/foreground-child/dist/commonjs/proxy-signals.d.ts +0 -6
  1050. package/node_modules/foreground-child/dist/commonjs/proxy-signals.d.ts.map +0 -1
  1051. package/node_modules/foreground-child/dist/commonjs/proxy-signals.js +0 -38
  1052. package/node_modules/foreground-child/dist/commonjs/proxy-signals.js.map +0 -1
  1053. package/node_modules/foreground-child/dist/commonjs/watchdog.d.ts +0 -10
  1054. package/node_modules/foreground-child/dist/commonjs/watchdog.d.ts.map +0 -1
  1055. package/node_modules/foreground-child/dist/commonjs/watchdog.js +0 -50
  1056. package/node_modules/foreground-child/dist/commonjs/watchdog.js.map +0 -1
  1057. package/node_modules/foreground-child/dist/esm/all-signals.d.ts +0 -2
  1058. package/node_modules/foreground-child/dist/esm/all-signals.d.ts.map +0 -1
  1059. package/node_modules/foreground-child/dist/esm/all-signals.js +0 -52
  1060. package/node_modules/foreground-child/dist/esm/all-signals.js.map +0 -1
  1061. package/node_modules/foreground-child/dist/esm/index.d.ts +0 -58
  1062. package/node_modules/foreground-child/dist/esm/index.d.ts.map +0 -1
  1063. package/node_modules/foreground-child/dist/esm/index.js +0 -115
  1064. package/node_modules/foreground-child/dist/esm/index.js.map +0 -1
  1065. package/node_modules/foreground-child/dist/esm/package.json +0 -3
  1066. package/node_modules/foreground-child/dist/esm/proxy-signals.d.ts +0 -6
  1067. package/node_modules/foreground-child/dist/esm/proxy-signals.d.ts.map +0 -1
  1068. package/node_modules/foreground-child/dist/esm/proxy-signals.js +0 -34
  1069. package/node_modules/foreground-child/dist/esm/proxy-signals.js.map +0 -1
  1070. package/node_modules/foreground-child/dist/esm/watchdog.d.ts +0 -10
  1071. package/node_modules/foreground-child/dist/esm/watchdog.d.ts.map +0 -1
  1072. package/node_modules/foreground-child/dist/esm/watchdog.js +0 -46
  1073. package/node_modules/foreground-child/dist/esm/watchdog.js.map +0 -1
  1074. package/node_modules/foreground-child/package.json +0 -106
  1075. package/node_modules/glob/dist/esm/bin.d.mts +0 -3
  1076. package/node_modules/glob/dist/esm/bin.d.mts.map +0 -1
  1077. package/node_modules/glob/dist/esm/bin.mjs +0 -346
  1078. package/node_modules/glob/dist/esm/bin.mjs.map +0 -1
  1079. package/node_modules/isexe/.npmignore +0 -2
  1080. package/node_modules/isexe/LICENSE +0 -15
  1081. package/node_modules/isexe/README.md +0 -51
  1082. package/node_modules/isexe/index.js +0 -57
  1083. package/node_modules/isexe/mode.js +0 -41
  1084. package/node_modules/isexe/package.json +0 -31
  1085. package/node_modules/isexe/test/basic.js +0 -221
  1086. package/node_modules/isexe/windows.js +0 -42
  1087. package/node_modules/jackspeak/LICENSE.md +0 -55
  1088. package/node_modules/jackspeak/README.md +0 -394
  1089. package/node_modules/jackspeak/dist/commonjs/index.d.ts +0 -323
  1090. package/node_modules/jackspeak/dist/commonjs/index.d.ts.map +0 -1
  1091. package/node_modules/jackspeak/dist/commonjs/index.js +0 -944
  1092. package/node_modules/jackspeak/dist/commonjs/index.js.map +0 -1
  1093. package/node_modules/jackspeak/dist/commonjs/index.min.js +0 -33
  1094. package/node_modules/jackspeak/dist/commonjs/index.min.js.map +0 -7
  1095. package/node_modules/jackspeak/dist/commonjs/package.json +0 -3
  1096. package/node_modules/jackspeak/dist/esm/index.d.ts +0 -323
  1097. package/node_modules/jackspeak/dist/esm/index.d.ts.map +0 -1
  1098. package/node_modules/jackspeak/dist/esm/index.js +0 -936
  1099. package/node_modules/jackspeak/dist/esm/index.js.map +0 -1
  1100. package/node_modules/jackspeak/dist/esm/index.min.js +0 -33
  1101. package/node_modules/jackspeak/dist/esm/index.min.js.map +0 -7
  1102. package/node_modules/jackspeak/dist/esm/package.json +0 -3
  1103. package/node_modules/jackspeak/package.json +0 -115
  1104. package/node_modules/jishushell-panel/output/public/assets/ApiKeyField-D1i7zWXR.js +0 -1
  1105. package/node_modules/jishushell-panel/output/public/assets/Dashboard-sWIvL43F.js +0 -1
  1106. package/node_modules/jishushell-panel/output/public/assets/HermesChatPanel-DQ8RyvQY.js +0 -1
  1107. package/node_modules/jishushell-panel/output/public/assets/HermesConfigForm-tIbPP1sB.js +0 -4
  1108. package/node_modules/jishushell-panel/output/public/assets/InitPassword-C3Slq3Dd.js +0 -1
  1109. package/node_modules/jishushell-panel/output/public/assets/InstanceDetail-7JqY9tq4.js +0 -92
  1110. package/node_modules/jishushell-panel/output/public/assets/Login-BXLDJlQN.js +0 -1
  1111. package/node_modules/jishushell-panel/output/public/assets/NewInstance-dLc5Xrpx.js +0 -1
  1112. package/node_modules/jishushell-panel/output/public/assets/ProviderRecommendations-DIAXxesl.js +0 -1
  1113. package/node_modules/jishushell-panel/output/public/assets/Settings-Bd5utbBh.js +0 -1
  1114. package/node_modules/jishushell-panel/output/public/assets/Setup-Yn9_20FL.js +0 -1
  1115. package/node_modules/jishushell-panel/output/public/assets/WeixinLoginPanel-C21doQTJ.js +0 -9
  1116. package/node_modules/jishushell-panel/output/public/assets/index-CCkaIEjn.js +0 -20
  1117. package/node_modules/jishushell-panel/output/public/assets/index-D7qxy-Vh.css +0 -1
  1118. package/node_modules/jishushell-panel/output/public/assets/registry-B2ZQZXWL.js +0 -2
  1119. package/node_modules/jishushell-panel/output/public/assets/usePolling-BFZm4do_.js +0 -1
  1120. package/node_modules/jishushell-panel/output/public/assets/vendor-i18n-DqPtOicc.js +0 -9
  1121. package/node_modules/jishushell-panel/output/public/assets/vendor-react-DW5juQin.js +0 -59
  1122. package/node_modules/package-json-from-dist/LICENSE.md +0 -63
  1123. package/node_modules/package-json-from-dist/README.md +0 -110
  1124. package/node_modules/package-json-from-dist/dist/commonjs/index.d.ts +0 -89
  1125. package/node_modules/package-json-from-dist/dist/commonjs/index.d.ts.map +0 -1
  1126. package/node_modules/package-json-from-dist/dist/commonjs/index.js +0 -134
  1127. package/node_modules/package-json-from-dist/dist/commonjs/index.js.map +0 -1
  1128. package/node_modules/package-json-from-dist/dist/commonjs/package.json +0 -3
  1129. package/node_modules/package-json-from-dist/dist/esm/index.d.ts +0 -89
  1130. package/node_modules/package-json-from-dist/dist/esm/index.d.ts.map +0 -1
  1131. package/node_modules/package-json-from-dist/dist/esm/index.js +0 -129
  1132. package/node_modules/package-json-from-dist/dist/esm/index.js.map +0 -1
  1133. package/node_modules/package-json-from-dist/dist/esm/package.json +0 -3
  1134. package/node_modules/package-json-from-dist/package.json +0 -68
  1135. package/node_modules/path-key/index.d.ts +0 -40
  1136. package/node_modules/path-key/index.js +0 -16
  1137. package/node_modules/path-key/license +0 -9
  1138. package/node_modules/path-key/package.json +0 -39
  1139. package/node_modules/path-key/readme.md +0 -61
  1140. package/node_modules/safe-buffer/LICENSE +0 -21
  1141. package/node_modules/safe-buffer/README.md +0 -584
  1142. package/node_modules/safe-buffer/index.d.ts +0 -187
  1143. package/node_modules/safe-buffer/index.js +0 -65
  1144. package/node_modules/safe-buffer/package.json +0 -51
  1145. package/node_modules/shebang-command/index.js +0 -19
  1146. package/node_modules/shebang-command/license +0 -9
  1147. package/node_modules/shebang-command/package.json +0 -34
  1148. package/node_modules/shebang-command/readme.md +0 -34
  1149. package/node_modules/shebang-regex/index.d.ts +0 -22
  1150. package/node_modules/shebang-regex/index.js +0 -2
  1151. package/node_modules/shebang-regex/license +0 -9
  1152. package/node_modules/shebang-regex/package.json +0 -35
  1153. package/node_modules/shebang-regex/readme.md +0 -33
  1154. package/node_modules/signal-exit/LICENSE.txt +0 -16
  1155. package/node_modules/signal-exit/README.md +0 -74
  1156. package/node_modules/signal-exit/dist/cjs/browser.d.ts +0 -12
  1157. package/node_modules/signal-exit/dist/cjs/browser.d.ts.map +0 -1
  1158. package/node_modules/signal-exit/dist/cjs/browser.js +0 -10
  1159. package/node_modules/signal-exit/dist/cjs/browser.js.map +0 -1
  1160. package/node_modules/signal-exit/dist/cjs/index.d.ts +0 -48
  1161. package/node_modules/signal-exit/dist/cjs/index.d.ts.map +0 -1
  1162. package/node_modules/signal-exit/dist/cjs/index.js +0 -279
  1163. package/node_modules/signal-exit/dist/cjs/index.js.map +0 -1
  1164. package/node_modules/signal-exit/dist/cjs/package.json +0 -3
  1165. package/node_modules/signal-exit/dist/cjs/signals.d.ts +0 -29
  1166. package/node_modules/signal-exit/dist/cjs/signals.d.ts.map +0 -1
  1167. package/node_modules/signal-exit/dist/cjs/signals.js +0 -42
  1168. package/node_modules/signal-exit/dist/cjs/signals.js.map +0 -1
  1169. package/node_modules/signal-exit/dist/mjs/browser.d.ts +0 -12
  1170. package/node_modules/signal-exit/dist/mjs/browser.d.ts.map +0 -1
  1171. package/node_modules/signal-exit/dist/mjs/browser.js +0 -4
  1172. package/node_modules/signal-exit/dist/mjs/browser.js.map +0 -1
  1173. package/node_modules/signal-exit/dist/mjs/index.d.ts +0 -48
  1174. package/node_modules/signal-exit/dist/mjs/index.d.ts.map +0 -1
  1175. package/node_modules/signal-exit/dist/mjs/index.js +0 -275
  1176. package/node_modules/signal-exit/dist/mjs/index.js.map +0 -1
  1177. package/node_modules/signal-exit/dist/mjs/package.json +0 -3
  1178. package/node_modules/signal-exit/dist/mjs/signals.d.ts +0 -29
  1179. package/node_modules/signal-exit/dist/mjs/signals.d.ts.map +0 -1
  1180. package/node_modules/signal-exit/dist/mjs/signals.js +0 -39
  1181. package/node_modules/signal-exit/dist/mjs/signals.js.map +0 -1
  1182. package/node_modules/signal-exit/package.json +0 -106
  1183. package/node_modules/which/CHANGELOG.md +0 -166
  1184. package/node_modules/which/LICENSE +0 -15
  1185. package/node_modules/which/README.md +0 -54
  1186. package/node_modules/which/bin/node-which +0 -52
  1187. package/node_modules/which/package.json +0 -43
  1188. package/node_modules/which/which.js +0 -125
  1189. package/scripts/check-adapter-isolation.ts +0 -293
  1190. /package/dist/services/{app → app-common}/app-compiler.d.ts +0 -0
  1191. /package/dist/services/{app → app-common}/terminal-session-manager.d.ts +0 -0
  1192. /package/dist/services/{backup-verify.d.ts → backup/backup-verify.d.ts} +0 -0
  1193. /package/dist/services/{external-mounts.d.ts → files/external-mounts.d.ts} +0 -0
  1194. /package/dist/services/{organize → files/organize}/applier.d.ts +0 -0
  1195. /package/dist/services/{organize → files/organize}/rules.d.ts +0 -0
  1196. /package/dist/services/{organize → files/organize}/scanner.d.ts +0 -0
  1197. /package/dist/services/{organize → files/organize}/store.d.ts +0 -0
  1198. /package/dist/services/{webdav → files/webdav}/xml-builder.d.ts +0 -0
  1199. /package/dist/services/{webdav → files/webdav}/xml-builder.js +0 -0
  1200. /package/dist/services/{app-passwords.d.ts → instances/passwords.d.ts} +0 -0
  1201. /package/dist/services/{agent-apps → integrations/installable}/installers/registry-probe.d.ts +0 -0
  1202. /package/dist/services/{agent-apps → integrations/installable}/installers/registry-probe.js +0 -0
  1203. /package/dist/services/{runtime/mcp-shims → integrations/openclaw}/drive-shim.d.ts +0 -0
  1204. /package/dist/services/{runtime/mcp-shims → integrations/openclaw}/mcporter-lite.d.ts +0 -0
  1205. /package/dist/services/{plugin-installer.d.ts → setup/plugin-installer.d.ts} +0 -0
  1206. /package/dist/services/{macos-launchd.d.ts → system/macos-launchd.d.ts} +0 -0
  1207. /package/dist/services/{system-monitor.d.ts → system/system-monitor.d.ts} +0 -0
@@ -1,3975 +0,0 @@
1
- /**
2
- * OpenClawAdapter — the framework face of OpenClaw business logic.
3
- *
4
- * Per §32.2 / §32.8 of docs/multi-agent-runtime-generalization-plan.md, the
5
- * goal of this file is simple: **all OpenClaw-specific knowledge leaves the
6
- * framework (instance-manager / nomad-manager / routes) and lives here**.
7
- *
8
- * Why not a huge rewrite in a single pass?
9
- * A full physical migration of ~6500 lines of OpenClaw code out of
10
- * `instance-manager.ts` / `nomad-manager.ts` / `setup-manager.ts` is a
11
- * multi-PR undertaking. This file lands the **structural** decoupling
12
- * (contract + dispatch) today, so:
13
- *
14
- * 1. Every framework call site now goes through `getAdapter(agentType).X()`
15
- * with zero string-literal branching on "openclaw" / "hermes".
16
- * 2. OpenClaw-specific imperative logic that was already contained (Nomad
17
- * task build, on-disk patches, npm update seed, pairing CLI mapping)
18
- * is physically moved into this file.
19
- * 3. Larger pieces that are still entangled inside instance-manager.ts
20
- * (`saveConfig` with channel-plugin auto-install, `createInstance`
21
- * with `openclaw.json` seeding) are exposed through adapter hooks
22
- * that framework code calls, and the physical code move from
23
- * instance-manager.ts into a sibling `openclaw-*.ts` file is a
24
- * straightforward follow-up PR — the `check-adapter-isolation.ts`
25
- * script (§32.2.1) will block any new code from sneaking back into
26
- * the framework layer.
27
- *
28
- * The user contract for adding a THIRD agent is therefore already satisfied
29
- * even before the follow-up physical migration:
30
- *
31
- * 1. Create `src/services/runtime/adapters/foo.ts` mirroring this file.
32
- * 2. Add `import "./adapters/foo.js"` to `src/services/runtime/index.ts`.
33
- * 3. Add one line to `frontend/src/runtimes/registry.ts`.
34
- * 4. Done. No `instance-manager.ts` / `nomad-manager.ts` / routes edits.
35
- */
36
- import { execFile, execFileSync } from "child_process";
37
- import { accessSync, chmodSync, chownSync, copyFileSync, cpSync, constants, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, } from "fs";
38
- import { createHash, randomBytes } from "crypto";
39
- import { homedir, userInfo } from "os";
40
- import { delimiter, dirname, join, resolve as pathResolve } from "path";
41
- import { getNomadDriver, getOpenclawDockerImage, JISHUSHELL_HOME, getCoreLanHost, getCorePort, getMaxAppMemoryMB, } from "../../../config.js";
42
- import { ensureDirContainer, ensureDirHost, writeConfigFile } from "../../../utils/fs.js";
43
- import { safeWriteJson } from "../../../utils/safe-json.js";
44
- import { compileTaskRuntime } from "../../app/app-compiler.js";
45
- import { allocateGatewayPort, chownToServiceUser, extractGatewayPort, getInstance, getRuntimeEnv, getRuntimeEnvFiles, inferProviderApiKeyEnvName, listInstances, normalizePath, notifyConfigChange, releasePendingPort, resolveServiceUser, updateEnvFile, } from "../../instance-manager.js";
46
- import { getInstanceDir as framework_instanceDir, instanceMetaPath } from "../../../config.js";
47
- import { createTask, emitTask, spawnWithTask, getDirSizeMB, npmProgressParser, dockerBuildProgressParser, resolveDockerInvocation, } from "../../setup-manager.js";
48
- import { DEFAULT_OPENCLAW_DOCKER_IMAGE, setOpenclawDockerImage, OPENCLAW_MODULES, OPENCLAW_PKG_DIR, } from "../../../config.js";
49
- import { fileURLToPath } from "node:url";
50
- import { inspectDockerImage, toDockerInspectUserError } from "../../../utils/docker-inspect.js";
51
- import { decryptApiKey } from "../../llm-proxy/encryption.js";
52
- import { getDefaultLlmProvider, normalizeProviderApi } from "../../llm-proxy/providers.js";
53
- import { bootstrapInstanceProxy, getInstanceConfig as getProxyInstanceConfig, } from "../../llm-proxy/instance-proxy.js";
54
- import { renderStandaloneMcporterSource } from "../mcp-shims/mcporter-lite.js";
55
- import { resolveNomadJobId } from "../job-id.js";
56
- import { registerAdapter } from "../registry.js";
57
- // ── Constants physically migrated from nomad-manager.ts ───────────────
58
- //
59
- // These used to live as module-scope constants in nomad-manager.ts and were
60
- // read by `buildTaskDocker` / `buildRuntime` helpers. They describe how
61
- // OpenClaw expects to be launched — container image paths, default command,
62
- // memory ceilings — and therefore belong to the OpenClaw adapter, not the
63
- // Nomad scheduler.
64
- const DEFAULT_COMMAND = "/usr/bin/openclaw";
65
- const DEFAULT_ARGS = ["gateway", "run", "--port", "18789", "--allow-unconfigured"];
66
- const DEFAULT_USER = userInfo().username;
67
- const DEFAULT_CWD = homedir();
68
- const DEFAULT_ENV = {
69
- HOME: homedir(),
70
- TMPDIR: "/tmp",
71
- PATH: `${homedir()}/.local/bin:${homedir()}/.npm-global/bin:${homedir()}/bin:${homedir()}/.volta/bin:` +
72
- `${homedir()}/.asdf/shims:${homedir()}/.bun/bin:${homedir()}/.nvm/current/bin:${homedir()}/.fnm/current/bin:` +
73
- `${homedir()}/.local/share/pnpm:/usr/local/bin:/usr/bin:/bin`,
74
- };
75
- const DEFAULT_RESOURCES = { CPU: 500, MemoryMB: 512 };
76
- const DEFAULT_PIDS_LIMIT = 512;
77
- // Hard upper bounds applied before submitting any Nomad job. Prevents a
78
- // misconfigured or malicious instance config from exhausting scheduler
79
- // resources on the host (no Nomad Enterprise Resource Quotas in OSS).
80
- const MAX_CPU_MHZ = 4000;
81
- // Memory ceilings read from core.json at runtime via getMaxAppMemoryMB().
82
- // Path inside the openclaw-runtime Docker image where the baked-in openclaw
83
- // npm package lives. Referenced by the entrypoint shim as the fallback and
84
- // used by the control-UI "Update now" path through a pre-seeded symlink in
85
- // $HOME/.npm-global (see ensureOpenclawUpdateSeed below).
86
- const CONTAINER_IMAGE_PKG_ROOT = "/app/node_modules/openclaw";
87
- const VALID_USER_RE = /^[a-z0-9._-]{1,32}$/;
88
- const DOCKER_IMAGE_RE = /^[a-zA-Z0-9][a-zA-Z0-9\-_.:/@]*$/;
89
- const MAX_DOCKER_IMAGE_NAME_LEN = 256;
90
- export const OPENCLAW_DEFAULT_GATEWAY_PORT = 18789;
91
- // ── Capability profile (moved from runtime/instance.ts) ──────────────
92
- //
93
- // Describes what the framework should expose for OpenClaw instances. The
94
- // frontend uses this to decide which tabs render and how the Chat tab looks.
95
- const DEFAULT_CAPABILITIES = {
96
- gateway: {
97
- http: true,
98
- websocket: true,
99
- chatPanel: "iframe",
100
- },
101
- pairing: {
102
- list: true,
103
- approve: true,
104
- revoke: false,
105
- clearPending: false,
106
- },
107
- configEditor: "json",
108
- configSchema: false,
109
- customProvider: true,
110
- pluginInstall: true,
111
- skills: true,
112
- mcp: true,
113
- memory: true,
114
- backupRestore: true,
115
- usageStats: true,
116
- restartlessReload: false,
117
- messagingPlatforms: ["feishu", "openclaw-weixin"],
118
- };
119
- import { FILES_ROOT } from "../../../config.js";
120
- import { defaultMountsForNewInstance, ensureMountTargets, } from "../../files-mounts.js";
121
- /**
122
- * Tolerate both `fileMounts` and `file_mounts` in instance.json — some
123
- * earlier migrations may have written snake_case.
124
- */
125
- function readFileMounts(runtime) {
126
- const raw = runtime.fileMounts ?? runtime.file_mounts;
127
- return Array.isArray(raw) ? raw : [];
128
- }
129
- /**
130
- * Build the volume list for the docker driver:
131
- * 1. The existing openclaw-home self-mount (HOME == container HOME)
132
- * 2. The root FILES_ROOT bind when any mount has empty path
133
- * ({"path":"","alias":"","mode":"rw"} — the default for new
134
- * instances). Without this, in-container plugins (Feishu / WeChat
135
- * send_file) try `fs.open("/home/.../files/...")` and hit ENOENT
136
- * because the host path isn't bind-mounted. Verified on pi2
137
- * 2026-05-11: claw1's drive_resolve_local_path returned a valid
138
- * abs_path; feishu_im_user_message then ENOENT'd on it.
139
- * 3. One additional bind per non-root FileMount, host==container so
140
- * the workspace/{alias} symlink (placed by rebuildWorkspace)
141
- * resolves identically inside the container.
142
- *
143
- * Mode "ro" is enforced by the docker bind option; raw_exec / process
144
- * modes don't go through this path (the agent runs natively on the host
145
- * and reads files directly).
146
- */
147
- function buildVolumes(openclawHome, runtime) {
148
- const list = [`${openclawHome}:${openclawHome}:rw`];
149
- for (const abs of listMountedHostPaths(runtime)) {
150
- const mode = readFileMounts(runtime).find((m) => !m.path || join(FILES_ROOT, m.path) === abs)?.mode === "ro" ? "ro" : "rw";
151
- list.push(`${abs}:${abs}:${mode}`);
152
- }
153
- return list;
154
- }
155
- function listMountedHostPaths(runtime) {
156
- let rootBound = false;
157
- const list = [];
158
- for (const m of readFileMounts(runtime)) {
159
- if (!m)
160
- continue;
161
- if (!m.path) {
162
- if (rootBound)
163
- continue;
164
- list.push(FILES_ROOT);
165
- rootBound = true;
166
- continue;
167
- }
168
- if (rootBound)
169
- continue; // root already covers every subtree
170
- list.push(join(FILES_ROOT, m.path));
171
- }
172
- return list;
173
- }
174
- function listJishukbUploadRoots(runtime, openclawHome) {
175
- return Array.from(new Set([
176
- ...listMountedHostPaths(runtime),
177
- join(openclawHome, ".openclaw", "media", "inbound"),
178
- ]));
179
- }
180
- // ── Path helpers (physically migrated from instance-manager.ts) ───────
181
- const INSTANCE_OPENCLAW_HOME_DIRNAME = "openclaw-home";
182
- const INSTANCE_MODEL_ENV_FILENAME = "model.env";
183
- const OPENCLAW_STATE_DIRNAME = ".openclaw";
184
- const OPENCLAW_CONFIG_FILENAME = "openclaw.json";
185
- function defaultOpenclawHome(instanceId) {
186
- return join(framework_instanceDir(instanceId), INSTANCE_OPENCLAW_HOME_DIRNAME);
187
- }
188
- function defaultOpenclawModelEnvFile(instanceId) {
189
- return join(framework_instanceDir(instanceId), INSTANCE_MODEL_ENV_FILENAME);
190
- }
191
- function isPrecreatedManagedAppDir(dir) {
192
- return existsSync(join(dir, "app-spec.yaml")) && existsSync(join(dir, "manifest.json"));
193
- }
194
- function openclawConfigPath(instanceId, home) {
195
- const h = home ?? defaultOpenclawHome(instanceId);
196
- return join(h, OPENCLAW_STATE_DIRNAME, OPENCLAW_CONFIG_FILENAME);
197
- }
198
- function legacyOpenclawConfigPath(instanceId, home) {
199
- const h = home ?? defaultOpenclawHome(instanceId);
200
- return join(h, OPENCLAW_CONFIG_FILENAME);
201
- }
202
- /**
203
- * Resolve the most relevant openclaw.json path for a SOURCE instance used
204
- * by the clone_from branch. Prefers the .openclaw/ state dir, falls back
205
- * to the legacy flat path so clones of old instances still work.
206
- */
207
- function resolveExistingConfigPath(instanceId) {
208
- const runtimePath = openclawConfigPath(instanceId);
209
- if (existsSync(runtimePath))
210
- return runtimePath;
211
- const legacy = legacyOpenclawConfigPath(instanceId);
212
- if (existsSync(legacy))
213
- return legacy;
214
- return runtimePath;
215
- }
216
- // ── Runtime + config defaults (physically migrated) ───────────────────
217
- function resolveOpenclawBin() {
218
- const candidates = [
219
- join(JISHUSHELL_HOME, "packages", "openclaw", "bin", "openclaw"),
220
- "/usr/local/bin/openclaw",
221
- "/usr/bin/openclaw",
222
- ];
223
- for (const p of candidates) {
224
- if (existsSync(p)) {
225
- try {
226
- chmodSync(p, 0o755);
227
- }
228
- catch {
229
- /* best effort — may be a symlink */
230
- }
231
- try {
232
- const real = realpathSync(p);
233
- if (real !== p)
234
- chmodSync(real, 0o755);
235
- }
236
- catch {
237
- /* best effort */
238
- }
239
- return p;
240
- }
241
- }
242
- // Fallback: scan $PATH for user-installed openclaw (nvm, homebrew, etc.)
243
- // Uses in-process lookup instead of spawning `which` for security and performance.
244
- const fromPath = findExecutableOnPath("openclaw");
245
- if (fromPath)
246
- return fromPath;
247
- return candidates[0]; // will fail with clear error at spawn
248
- }
249
- /**
250
- * Search $PATH for an executable by name. Returns the first match or null.
251
- * Does not chmod the result — PATH-discovered binaries are not managed by JishuShell.
252
- */
253
- function findExecutableOnPath(name) {
254
- const pathEnv = process.env.PATH || "";
255
- for (const dir of pathEnv.split(delimiter)) {
256
- if (!dir)
257
- continue;
258
- const candidate = join(dir, name);
259
- try {
260
- accessSync(candidate, constants.X_OK);
261
- return candidate;
262
- }
263
- catch {
264
- /* not found or not executable in this dir */
265
- }
266
- }
267
- return null;
268
- }
269
- function buildDefaultRuntime(instanceId, port, openclawHome) {
270
- const home = openclawHome || defaultOpenclawHome(instanceId);
271
- return {
272
- command: resolveOpenclawBin(),
273
- args: ["gateway", "run", "--port", String(port), "--allow-unconfigured"],
274
- cwd: home,
275
- user: resolveServiceUser()?.username ?? userInfo().username,
276
- env_files: [defaultOpenclawModelEnvFile(instanceId)],
277
- env: {
278
- OPENCLAW_GATEWAY_PORT: String(port),
279
- NODE_OPTIONS: "--max-old-space-size=2048",
280
- // Let mcporter find its config regardless of the agent's CWD. The
281
- // gateway's CWD is openclaw-home (no config/), and `cd workspace`
282
- // means the user-files symlink (also no config/). Without this env,
283
- // every `mcporter call drive.*` fails with "Unknown MCP server 'drive'"
284
- // and the agent reports a generic "network error" to the user.
285
- MCPORTER_CONFIG: `${home}/.openclaw/workspace/config/mcporter.json`,
286
- },
287
- resources: { CPU: 1000, MemoryMB: 2048 },
288
- };
289
- }
290
- function starterConfig() {
291
- const dp = getDefaultLlmProvider();
292
- let providerName = "minimax";
293
- let providerConfig = {
294
- baseUrl: "https://api.minimaxi.com/v1",
295
- api: "openai-completions",
296
- models: [{ id: "MiniMax-M2.7", name: "MiniMax M2.7", contextWindow: 204800 }],
297
- };
298
- let defaultModel = "minimax/MiniMax-M2.7";
299
- if (dp?.id) {
300
- providerName = dp.id;
301
- providerConfig = {
302
- baseUrl: dp.baseUrl,
303
- api: normalizeProviderApi(dp.api),
304
- ...(dp.authHeader ? { authHeader: true } : {}),
305
- models: dp.models || [],
306
- };
307
- const modelId = dp.selectedModelId || dp.models?.[0]?.id || "";
308
- defaultModel = `${providerName}/${modelId}`;
309
- }
310
- const config = {
311
- models: { providers: { [providerName]: providerConfig } },
312
- agents: { defaults: { model: defaultModel, models: { [defaultModel]: {} } } },
313
- channels: {},
314
- gateway: {
315
- mode: "local",
316
- auth: { mode: "token", token: randomBytes(24).toString("hex") },
317
- controlUi: { dangerouslyDisableDeviceAuth: true },
318
- },
319
- plugins: { entries: { feishu: { enabled: false } } },
320
- };
321
- if (dp?.id) {
322
- config["x-jishushell"] = {
323
- proxy: {
324
- upstream: {
325
- providerId: dp.id,
326
- baseUrl: dp.baseUrl,
327
- api: normalizeProviderApi(dp.api),
328
- authHeader: dp.authHeader === true || typeof dp.authHeader === "string",
329
- models: dp.models || [],
330
- selectedModelId: dp.selectedModelId || dp.models?.[0]?.id || "",
331
- hasApiKey: !!dp.apiKey,
332
- },
333
- },
334
- };
335
- }
336
- return config;
337
- }
338
- // ── Nomad-patching helpers (migrated from nomad-manager.ts) ───────────
339
- /**
340
- * In docker bridge mode, 127.0.0.1 inside the container resolves to the
341
- * container's own loopback, not the host. Rewrite the jsproxy provider
342
- * baseUrl in openclaw.json to use host.docker.internal instead.
343
- */
344
- function patchJsproxyBaseUrl(configPath) {
345
- try {
346
- const raw = readFileSync(configPath, "utf-8");
347
- const patched = raw.replace(/http:\/\/127\.0\.0\.1:(\d+)\/proxy/g, `http://host.docker.internal:$1/proxy`);
348
- if (patched !== raw) {
349
- writeConfigFile(configPath, patched);
350
- console.log(`[openclaw] Patched jsproxy baseUrl in ${configPath} (127.0.0.1 → host.docker.internal)`);
351
- }
352
- }
353
- catch (e) {
354
- console.warn(`[openclaw] Failed to patch jsproxy baseUrl in ${configPath}: ${e.message}`);
355
- }
356
- }
357
- /** Known private/internal hostnames used by JishuShell's local proxy. */
358
- const PRIVATE_NETWORK_HOSTS = ["host.docker.internal", "127.0.0.1", "localhost", "0.0.0.0"];
359
- export function isPrivateNetworkBaseUrl(baseUrl) {
360
- try {
361
- const url = new URL(baseUrl);
362
- if (PRIVATE_NETWORK_HOSTS.includes(url.hostname))
363
- return true;
364
- if (url.hostname.startsWith("10."))
365
- return true;
366
- if (url.hostname.startsWith("192.168."))
367
- return true;
368
- // RFC 1918: 172.16.0.0/12 → 172.16.x.x through 172.31.x.x
369
- const m = url.hostname.match(/^172\.(\d+)\./);
370
- if (m) {
371
- const second = parseInt(m[1], 10);
372
- if (second >= 16 && second <= 31)
373
- return true;
374
- }
375
- return false;
376
- }
377
- catch {
378
- return false;
379
- }
380
- }
381
- /**
382
- * Ensure `request.allowPrivateNetwork: true` is set on providers whose baseUrl
383
- * targets a private/internal host (e.g. host.docker.internal). Without this,
384
- * OpenClaw's SSRF guard blocks requests to the JishuShell local proxy.
385
- */
386
- export function patchPrivateNetworkAllowFlag(configPath) {
387
- try {
388
- const raw = readFileSync(configPath, "utf-8");
389
- const config = JSON.parse(raw);
390
- const providers = config?.models?.providers;
391
- if (!providers || typeof providers !== "object")
392
- return;
393
- let changed = false;
394
- for (const [, provider] of Object.entries(providers)) {
395
- if (typeof provider !== "object" || provider === null)
396
- continue;
397
- const p = provider;
398
- if (typeof p.baseUrl !== "string")
399
- continue;
400
- if (!isPrivateNetworkBaseUrl(p.baseUrl))
401
- continue;
402
- if (p.request?.allowPrivateNetwork === true)
403
- continue;
404
- p.request = { ...(p.request || {}), allowPrivateNetwork: true };
405
- changed = true;
406
- }
407
- if (changed) {
408
- writeConfigFile(configPath, JSON.stringify(config, null, 2));
409
- console.log(`[openclaw] Patched request.allowPrivateNetwork in ${configPath} for private-network providers`);
410
- }
411
- }
412
- catch (e) {
413
- console.warn(`[openclaw] Failed to patch allowPrivateNetwork in ${configPath}: ${e.message}`);
414
- }
415
- }
416
- /**
417
- * Docker bridge port publishing cannot reach a process that only binds the
418
- * container loopback. Normalize default/loopback gateway binds to `lan` so
419
- * Nomad's published host port can reach the gateway.
420
- */
421
- // Mirrors hermes.ts:nomadHasExternalHostNetwork. When the host nomad.hcl
422
- // declares `host_network "external" { ... }`, the legacy openclaw job
423
- // attaches it to its ReservedPorts so docker publishes the gateway to
424
- // the LAN address instead of 127.0.0.1. Without this, OpenWebUI in a
425
- // sibling container can't reach openclaw at all.
426
- function nomadHasExternalHostNetwork() {
427
- const path = join(JISHUSHELL_HOME, "nomad", "nomad.hcl");
428
- try {
429
- return /host_network\s+"external"\s*\{/.test(readFileSync(path, "utf-8"));
430
- }
431
- catch {
432
- return false;
433
- }
434
- }
435
- function patchDockerBridgeGatewayBind(configPath) {
436
- try {
437
- const raw = readFileSync(configPath, "utf-8");
438
- const parsed = JSON.parse(raw);
439
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
440
- return;
441
- const gatewayRaw = parsed.gateway;
442
- const gateway = gatewayRaw && typeof gatewayRaw === "object" && !Array.isArray(gatewayRaw)
443
- ? gatewayRaw
444
- : (parsed.gateway = {});
445
- const bind = typeof gateway.bind === "string" ? gateway.bind.trim() : "";
446
- if (bind && bind !== "loopback")
447
- return;
448
- gateway.bind = "lan";
449
- const next = JSON.stringify(parsed, null, 2);
450
- const output = raw.endsWith("\n") ? `${next}\n` : next;
451
- if (output === raw)
452
- return;
453
- writeConfigFile(configPath, output);
454
- console.log(`[openclaw] Normalized gateway.bind to "lan" in ${configPath} for Docker bridge networking`);
455
- }
456
- catch (e) {
457
- console.warn(`[openclaw] Failed to patch gateway.bind in ${configPath}: ${e.message}`);
458
- }
459
- }
460
- /**
461
- * Ensure the `llm-agent` capability advertised by openclaw-*.yaml works for
462
- * every instance, including ones created before this code shipped: enable
463
- * OpenClaw's OpenAI-compatible endpoints in `openclaw.json` on every start.
464
- *
465
- * Runs idempotently next to `patchDockerBridgeGatewayBind`. The OpenAI
466
- * routes (`/v1/chat/completions`, `/v1/responses`, `/v1/models`,
467
- * `/v1/embeddings`) live in openclaw's bundled server.impl and are gated
468
- * behind `gateway.http.endpoints.{chatCompletions,responses}.enabled` —
469
- * default false, so a fresh OpenClaw install would 404 those paths even
470
- * though OpenWebUI binds it through the connections page.
471
- */
472
- export function patchOpenAIEndpointsEnabled(configPath) {
473
- try {
474
- const raw = readFileSync(configPath, "utf-8");
475
- const parsed = JSON.parse(raw);
476
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
477
- return;
478
- const root = parsed;
479
- const gateway = root.gateway && typeof root.gateway === "object" && !Array.isArray(root.gateway)
480
- ? root.gateway
481
- : (root.gateway = {});
482
- const http = gateway.http && typeof gateway.http === "object" && !Array.isArray(gateway.http)
483
- ? gateway.http
484
- : (gateway.http = {});
485
- const endpoints = http.endpoints && typeof http.endpoints === "object" && !Array.isArray(http.endpoints)
486
- ? http.endpoints
487
- : (http.endpoints = {});
488
- let changed = false;
489
- for (const key of ["chatCompletions", "responses"]) {
490
- const ep = endpoints[key] && typeof endpoints[key] === "object" && !Array.isArray(endpoints[key])
491
- ? endpoints[key]
492
- : (endpoints[key] = {});
493
- if (ep.enabled !== true) {
494
- ep.enabled = true;
495
- changed = true;
496
- }
497
- }
498
- if (!changed)
499
- return;
500
- const next = JSON.stringify(parsed, null, 2);
501
- const output = raw.endsWith("\n") ? `${next}\n` : next;
502
- writeConfigFile(configPath, output);
503
- console.log(`[openclaw] Enabled gateway.http.endpoints.{chatCompletions,responses} in ${configPath} for llm-agent capability`);
504
- }
505
- catch (e) {
506
- console.warn(`[openclaw] Failed to patch OpenAI endpoints in ${configPath}: ${e.message}`);
507
- }
508
- }
509
- /**
510
- * Deep-merge a SearXNG connection into an OpenClaw config file at `configPath`.
511
- *
512
- * Writes both halves of the wiring required for the `web_search` tool to use
513
- * the registry-resolved SearXNG instance:
514
- *
515
- * plugins.entries.searxng.enabled = true
516
- * plugins.entries.searxng.config.webSearch.baseUrl = baseUrl
517
- * tools.web.search.provider = "searxng"
518
- *
519
- * The provider selector is required because OpenClaw's built-in default is
520
- * `"brave"`; without it the tool fails with `missing_brave_api_key` even when
521
- * the searxng plugin is otherwise correctly configured (verified on Pi
522
- * 2026-04-29: claw11 had the plugin block right but the selector unset).
523
- *
524
- * Why a partial deep-merge instead of `saveNativeConfig`: the latter is
525
- * destructive — it replaces top-level keys wholesale and only preserves a
526
- * hardcoded subset (`plugins.installs`, `plugins.entries` per-key, partial
527
- * `channels` merge). A partial patch through it would wipe `models.providers`
528
- * / `agents.defaults` / etc., bricking the instance with `No API key found
529
- * for provider "openai"` on the next chat. So we read, merge, write back.
530
- *
531
- * No-op when the config file is absent (instance not yet started).
532
- */
533
- export function applySearxngConnectionToConfig(configPath, baseUrl) {
534
- if (!existsSync(configPath))
535
- return;
536
- const existing = JSON.parse(readFileSync(configPath, "utf-8"));
537
- existing.plugins = existing.plugins ?? {};
538
- existing.plugins.entries = existing.plugins.entries ?? {};
539
- const prior = existing.plugins.entries.searxng ?? {};
540
- existing.plugins.entries.searxng = {
541
- ...prior,
542
- enabled: true,
543
- config: {
544
- ...(prior.config ?? {}),
545
- webSearch: {
546
- ...((prior.config ?? {}).webSearch ?? {}),
547
- baseUrl,
548
- },
549
- },
550
- };
551
- existing.tools = existing.tools ?? {};
552
- existing.tools.web = existing.tools.web ?? {};
553
- existing.tools.web.search = existing.tools.web.search ?? {};
554
- existing.tools.web.search.provider = "searxng";
555
- safeWriteJson(configPath, existing);
556
- }
557
- /**
558
- * Counterpart to `applySearxngConnectionToConfig` — invoked when the user
559
- * unbinds the SEARCH slot in the Connections tab. Without this, unbinding
560
- * left the plugin entry enabled with a baseUrl pointing at the now-gone
561
- * searxng provider, and `tools.web.search.provider="searxng"` kept routing
562
- * the agent's `web_search` tool through that dead URL on every chat.
563
- *
564
- * Conservative cleanup so a future re-bind (or user-customized plugin
565
- * settings) survives:
566
- * - flip the searxng plugin to enabled:false (don't delete the entry —
567
- * user may have hand-tuned it and we want re-bind to re-enable cheaply)
568
- * - drop the stale `webSearch.baseUrl` so nothing reads it as still-live
569
- * - clear `tools.web.search.provider` so the runtime falls back to its
570
- * built-in default (which today errors out with `missing_brave_api_key`
571
- * — the right outcome: search was unbound, web_search shouldn't work)
572
- *
573
- * No-op when the config file is absent.
574
- */
575
- export function clearSearxngConnectionFromConfig(configPath) {
576
- if (!existsSync(configPath))
577
- return;
578
- const existing = JSON.parse(readFileSync(configPath, "utf-8"));
579
- const sx = existing?.plugins?.entries?.searxng;
580
- if (sx && typeof sx === "object") {
581
- sx.enabled = false;
582
- if (sx.config?.webSearch && typeof sx.config.webSearch === "object") {
583
- delete sx.config.webSearch.baseUrl;
584
- }
585
- }
586
- if (existing?.tools?.web?.search && typeof existing.tools.web.search === "object") {
587
- delete existing.tools.web.search.provider;
588
- }
589
- safeWriteJson(configPath, existing);
590
- }
591
- /** Profile name used in `browser.profiles` for jishushell-managed Browserless bindings. */
592
- const BROWSERLESS_PROFILE = "browserless";
593
- /**
594
- * Default `color` for the jishushell-managed browserless profile. OpenClaw's
595
- * profile schema treats `color` as required (the field shows up as the
596
- * profile chip tint in the UI); omitting it triggers
597
- * "browser.profiles.browserless.color: Invalid input: expected string,
598
- * received undefined"
599
- * on every config reload, which crashloops the gateway. Verified against
600
- * the runtime image `ghcr.io/x-aijishu/openclaw-runtime:2026.4.15` on Pi 2
601
- * (2026-05-07). The tone is Browserless brand green; users can override it
602
- * once and we preserve their override on re-bind via the `prior` spread.
603
- */
604
- const BROWSERLESS_DEFAULT_COLOR = "#00AA66";
605
- /**
606
- * Deep-merge a Browserless CDP connection into an OpenClaw config file at
607
- * `configPath`. Mirrors `applySearxngConnectionToConfig` for the browser slot.
608
- *
609
- * Writes:
610
- * browser.profiles.browserless.cdpUrl = cdpUrl // ws:// or wss://
611
- * browser.profiles.browserless.attachOnly = true // since v2026.3.2
612
- * browser.profiles.browserless.color = "#00AA66" // required by schema
613
- * browser.defaultProfile = "browserless" // only if unset
614
- * browser.enabled = true // only if unset
615
- * gateway.nodes.browser.mode = "off" // only if unset
616
- *
617
- * Why per-profile `attachOnly` and not global `browser.attachOnly`: global
618
- * attachOnly forces every profile to skip launch — that breaks the user's
619
- * other manually-configured profiles. Per-profile attachOnly was added in
620
- * OpenClaw v2026.3.2; older versions silently ignore the extra field and
621
- * fall back to attach-via-cdpUrl semantics (which `cdpUrl` triggers on its
622
- * own from v2.0.0-beta5), so the schema is forward-compatible all the way
623
- * back to the first remote-CDP release.
624
- *
625
- * Why `gateway.nodes.browser.mode = "off"`: in OpenClaw 2026.5.6 the
626
- * gateway only registers the `browser.request` WS method when this config
627
- * block exists. Without it, `openclaw browser …` CLI and the gateway
628
- * canvas tool both fail with `unknown method: browser.request` or
629
- * `node required`. Setting `mode: "off"` forces gateway-local CDP
630
- * dispatch (use `cdpUrl` directly, never look for paired nodes), which
631
- * matches jishushell's intent: Browserless is a service-style provider,
632
- * not a node-style provider. Verified end-to-end on Pi 2 (2026-05-07):
633
- * Browserless `/sessions` shows `numbConnected: 1` and `openclaw browser
634
- * navigate <allowed-host>` succeeds + screenshots render correctly.
635
- *
636
- * `defaultProfile`, `enabled`, and `gateway.nodes.browser.mode` are all
637
- * set only when absent so user-customized values survive a re-bind. The
638
- * `enabled` flag is never flipped off — Browserless binding shouldn't
639
- * override a user who explicitly disabled the browser tool tree.
640
- *
641
- * SSRF policy is intentionally NOT touched here: `browser.ssrfPolicy`
642
- * (`dangerouslyAllowPrivateNetwork`, `allowedHostnames`) is a user-level
643
- * security decision (default deny-all is correct for an LLM-driven
644
- * browser); jishushell would be over-reaching to silently widen it on
645
- * binding. Users who want the agent to reach a specific host configure
646
- * the allowlist themselves.
647
- *
648
- * No-op when the config file is absent (instance not yet started).
649
- */
650
- export function applyBrowserlessConnectionToConfig(configPath, cdpUrl) {
651
- if (!existsSync(configPath))
652
- return;
653
- const existing = JSON.parse(readFileSync(configPath, "utf-8"));
654
- const browser = (existing.browser ??= {});
655
- if (browser.enabled === undefined)
656
- browser.enabled = true;
657
- if (!browser.defaultProfile)
658
- browser.defaultProfile = BROWSERLESS_PROFILE;
659
- const profiles = (browser.profiles ??= {});
660
- const prior = profiles[BROWSERLESS_PROFILE] ?? {};
661
- profiles[BROWSERLESS_PROFILE] = {
662
- ...prior,
663
- cdpUrl,
664
- attachOnly: true,
665
- color: typeof prior.color === "string" && prior.color ? prior.color : BROWSERLESS_DEFAULT_COLOR,
666
- };
667
- const gateway = (existing.gateway ??= {});
668
- const nodes = (gateway.nodes ??= {});
669
- const browserPolicy = (nodes.browser ??= {});
670
- if (browserPolicy.mode === undefined)
671
- browserPolicy.mode = "off";
672
- safeWriteJson(configPath, existing);
673
- }
674
- /**
675
- * Counterpart to `applyBrowserlessConnectionToConfig` — invoked when the user
676
- * unbinds the BROWSER slot in the Connections tab. Removes the
677
- * jishushell-managed `browserless` profile and clears `defaultProfile` only
678
- * if it still points at that profile (so user-set defaults pointing at their
679
- * own profiles survive). Other profiles and `browser.enabled` are left alone.
680
- *
681
- * No-op when the config file is absent.
682
- */
683
- export function clearBrowserlessConnectionFromConfig(configPath) {
684
- if (!existsSync(configPath))
685
- return;
686
- const existing = JSON.parse(readFileSync(configPath, "utf-8"));
687
- const browser = existing?.browser;
688
- if (!browser || typeof browser !== "object")
689
- return;
690
- if (browser.profiles && typeof browser.profiles === "object") {
691
- delete browser.profiles[BROWSERLESS_PROFILE];
692
- }
693
- if (browser.defaultProfile === BROWSERLESS_PROFILE) {
694
- delete browser.defaultProfile;
695
- }
696
- safeWriteJson(configPath, existing);
697
- }
698
- /**
699
- * Bump when a panel-side change invalidates the agent's prior reasoning
700
- * within an existing chat session — e.g., a mount fix that turns prior
701
- * "I can't read this file" tool failures into stale conclusions. The
702
- * first onBeforeStart after the bump rotates the instance's session
703
- * jsonl files (`<file>.jsonl` → `<file>.jsonl.reset.<ts>`), so the next
704
- * user message lands on a clean context window. Old transcripts are
705
- * preserved as .reset.* siblings — never deleted, just archived.
706
- *
707
- * Concrete history:
708
- * 2026.5.11.1 — buildVolumes root-mount fix: empty-path FileMount
709
- * finally binds FILES_ROOT into docker containers. Prior
710
- * sessions had agent conclude "drive only has metadata,
711
- * no file content" after ENOENT — that reasoning is
712
- * poisoned post-fix.
713
- * 2026.5.11.2 — WeChat target-format rule in TOOLS.md: agent was
714
- * extrapolating Feishu's `user:` prefix onto WeChat
715
- * chat_ids that don't carry it, causing WeChat's
716
- * getuploadurl to return ret:-1. Prior sessions need
717
- * rotation so the agent re-reads the corrected target
718
- * rule and stops adding the prefix.
719
- * 2026.6.4.2 — jishu-kb citations response + mcporter fallback shebang:
720
- * agent was concluding KB was empty because the shim only
721
- * recognized `chunks/results/hits`, while current jishu-kb
722
- * returns `citations`. The fallback wrapper also baked a
723
- * host-specific node shebang that some OpenClaw runtimes
724
- * could not execute directly. Prior sessions need rotation
725
- * so the agent retries with the fixed tool behavior.
726
- * 2026.6.4.3 — jishu-kb multi-tool surface: KB management/upload/delete
727
- * tools and handbook/config reads are now available.
728
- * Prior sessions need rotation so the model re-reads the
729
- * expanded tool instructions instead of the old search-only
730
- * guidance.
731
- *
732
- * Format: YYYY.M.D.N (date + same-day bump counter). Compare as strings;
733
- * any difference means rotate. Stored per-instance at
734
- * `<instanceDir>/runtime-contract.txt`
735
- */
736
- const RUNTIME_CONTRACT_VERSION = "2026.6.4.3";
737
- const JISHUSHELL_DRIVE_HINT_BEGIN = "<!-- jishushell-drive: BEGIN auto-generated -->";
738
- const JISHUSHELL_DRIVE_HINT_END = "<!-- jishushell-drive: END -->";
739
- const JISHUSHELL_KB_HINT_BEGIN = "<!-- jishushell-kb: BEGIN auto-generated -->";
740
- const JISHUSHELL_KB_HINT_END = "<!-- jishushell-kb: END -->";
741
- /**
742
- * Rotate session jsonl files when the runtime contract version has bumped
743
- * since this instance last started. Matches OpenClaw's own .reset.<ts>
744
- * naming convention so its existing UI/cleanup paths still apply.
745
- *
746
- * Why this exists: when a panel upgrade fixes a runtime bug (e.g. the
747
- * 2026-05-11 mount-bind fix), the agent's prior turn-by-turn reasoning
748
- * inside an existing session is anchored to the broken behaviour. Even
749
- * after the fix is deployed and the alloc restarted, the LLM keeps
750
- * citing past tool failures and refusing to retry. Rotating the session
751
- * jsonl(s) gives the next user message a clean context where the agent
752
- * sees fresh TOOLS.md + fresh tool outputs.
753
- *
754
- * Side effect: the user loses chat scrollback in IM/web. Acceptable
755
- * because (a) the rotated file is preserved on disk, (b) panel upgrades
756
- * are infrequent, (c) the alternative — agent stuck in old reasoning —
757
- * is worse UX.
758
- */
759
- function rotateSessionsIfContractChanged(instanceId, openclawHome) {
760
- try {
761
- const markerPath = join(framework_instanceDir(instanceId), "runtime-contract.txt");
762
- let previous = "";
763
- try {
764
- previous = readFileSync(markerPath, "utf-8").trim();
765
- }
766
- catch (e) {
767
- if (e?.code !== "ENOENT")
768
- throw e;
769
- }
770
- if (previous === RUNTIME_CONTRACT_VERSION)
771
- return;
772
- const sessionsDir = join(openclawHome, ".openclaw", "agents", "main", "sessions");
773
- if (existsSync(sessionsDir)) {
774
- const ts = new Date()
775
- .toISOString()
776
- .replace(/:/g, "-")
777
- .replace(/\.\d+Z$/, ".000Z");
778
- const entries = readdirSync(sessionsDir);
779
- let rotated = 0;
780
- for (const name of entries) {
781
- if (!name.endsWith(".jsonl"))
782
- continue; // skip already-rotated
783
- const from = join(sessionsDir, name);
784
- const to = `${from}.reset.${ts}`;
785
- try {
786
- renameSync(from, to);
787
- rotated++;
788
- }
789
- catch (e) {
790
- console.warn(`[openclaw] session rotate failed for ${from}: ${e?.message ?? e}`);
791
- }
792
- }
793
- if (rotated > 0) {
794
- console.log(`[openclaw] runtime contract ${previous || "(none)"} → ${RUNTIME_CONTRACT_VERSION}: rotated ${rotated} session(s) under ${sessionsDir}`);
795
- }
796
- }
797
- writeConfigFile(markerPath, RUNTIME_CONTRACT_VERSION + "\n");
798
- }
799
- catch (e) {
800
- console.warn(`[openclaw] rotateSessionsIfContractChanged failed: ${e?.message ?? e}`);
801
- }
802
- }
803
- /**
804
- * Inject a guarded section into the agent's TOOLS.md telling the LLM that
805
- * user files live on the local filesystem (host==container bind mount),
806
- * not on some remote "drive server", and showing the concrete
807
- * resolve-then-send chain for IM channels (Feishu / WeChat).
808
- *
809
- * Why this exists: the LLM defaults to interpreting `drive` as a remote
810
- * service, then refuses to send NAS files via IM with "I can't access the
811
- * cloud drive" — even when `drive_list` literally just enumerated them.
812
- * Verified on pi2 2026-05-11: claw1 saw `文档/宇树G1-D...xlsx` via
813
- * drive_list, then told the user to "open Feishu cloud space and forward
814
- * it back" because nothing in TOOLS.md tied drive paths to filesystem
815
- * paths. This patcher closes that gap by spelling it out.
816
- *
817
- * Idempotent: section is bracketed by HTML markers; content between them
818
- * is rewritten on every call. User edits OUTSIDE the markers are kept.
819
- *
820
- * filesRoot is baked in so the example abs path matches the actual install
821
- * — third-party users on `/home/alice/.jishushell/files/` see their own
822
- * root, not pi's.
823
- */
824
- export function patchToolsMdDriveHint(workspaceDir, filesRoot, mcporterCommand = "mcporter", instanceId) {
825
- try {
826
- const toolsPath = join(workspaceDir, "TOOLS.md");
827
- let original = "";
828
- try {
829
- original = readFileSync(toolsPath, "utf-8");
830
- }
831
- catch (e) {
832
- if (e?.code !== "ENOENT")
833
- throw e;
834
- }
835
- const cli = mcporterCommand === "mcporter" ? "mcporter" : JSON.stringify(mcporterCommand);
836
- const generatedOutboxPath = instanceId
837
- ? `agent-data/${instanceId}/outbox/x.pdf`
838
- : "agent-data/<instance>/outbox/x.pdf";
839
- const section = [
840
- JISHUSHELL_DRIVE_HINT_BEGIN,
841
- "",
842
- "### 📁 用户的 NAS / 文件库",
843
- "",
844
- "⚠️ **用户文件操作硬路由 — 必读**",
845
- "",
846
- "**单一规则(语言无关)**:用户用任何语言(中文 / English / 日本語 / ...)说「**我的 / 我的 / my / mine / our / the user's / 私の**」+ 任何文件/目录/资料/笔记/文档/代码/data/notes/docs/files → **CRUD 全部走 `drive.*` 工具,禁止用 shell 在 cwd 上操作**。判定按**语义**不按**字面**,本表只是举例。",
847
- "",
848
- "动作 ↔ 工具映射表(用户文件场景,中英混排示例):",
849
- "",
850
- "| 用户意图(多语言示例) | ✅ 必须用 | ❌ 禁止 |",
851
- "|---|---|---|",
852
- "| list / show / 「列一下 / 我有什么 / 看看我的 / what files do I have / show me my docs / list my files」 | `drive_list` | `ls`, `find`, `pwd` |",
853
- "| read / open / 「打开 / 看看 / 念一下 / 内容是啥 / open my X / read the content of / what's in」 | `drive_read_preview` / `drive_read_full` | `cat`, `head`, `tail` |",
854
- "| search / find / 「搜 / 找一下 / 哪里提到 / search my docs for / find X in my files / where did I write about」 | `drive_search` | `grep`, `rg` |",
855
- "| write / save / create / 「写 / 存 / 记一下 / 新建 / save this as / write a note / create a file」 | `drive_write_text` / `drive_write_binary` | `echo >`, `cat <<EOF`, `tee` |",
856
- "| delete / remove / 「删 / 扔掉 / delete X / remove the file」 | `drive_delete` | `rm` |",
857
- "| rename / move / 「改名 / 挪到 / 移到 / rename X to Y / move X to」 | `drive_move` | `mv` |",
858
- "| mkdir / 「建文件夹 / create a folder / make a directory」 | `drive_mkdir` | `mkdir` |",
859
- "| quota / space / 「配额 / 空间 / how much space / quota / disk usage」 | `drive_quota` | `df`, `du` |",
860
- "| send / share / 「发给我 / 把 X 发出去 / send me X / share the file with me」 | `drive_resolve_local_path` → IM `send_file` | (拒绝 / refuse) |",
861
- "",
862
- "**触发词不完全列表(再次强调:语义优先)**:",
863
- "- 中文:我的、我那份、我之前的、我刚刚的、用户的、咱们的、文件、文档、资料、笔记、报告、合同、PDF、Excel、附件",
864
- "- English: my, mine, our, the user's, files, file, doc(s), document(s), note(s), paper(s), report(s), spreadsheet(s), pdf(s), attachment(s)",
865
- "- 其它语言:私の (ja) / mes (fr) / mein (de) / 我的 (variants) — 含义相同时同等处理",
866
- "",
867
- "**为什么硬规定**:cwd 是你自己的运行骨架(`AGENTS.md`、`TOOLS.md`、`memory/`、`state/`、`config/`),跟用户**毫无关系**。",
868
- "- 用户问「我有什么文件 / what files do I have」你 `ls` cwd → 列出 `AGENTS.md`、`memory/` → 用户懵 + 觉得 jishushell 装错了",
869
- "- 用户说「帮我写笔记 notes.md / save a note for me」你 `echo > notes.md` 落 cwd → 文件落到 agent 工作目录,用户在 filebrowser 看不到 → 数据等于丢了",
870
- "- 用户说「打开我那份产品规格 / open my spec」你 `cat spec.md` → cwd 里没有该文件 → 找不到 → 用户被冤枉「文件根本不存在」",
871
- "",
872
- "**判定方法(消息归属判定,跨语言)**:主语/所有格指向「用户/我们」(我 / 我的 / my / our / the user / 私の + 文件相关名词)→ 走 drive。指向「你/agent」(你的 / 你刚才写的代码 / your notes / agent's scratch)→ 才可能是 workspace。**99% 的对话都是前者**。歧义时**默认按用户文件处理**——猜错代价小(最多多调一次 drive_list 拿不到东西),猜成 cwd 代价大(脏数据 + 数据丢失)。",
873
- "",
874
- "**唯一可用 shell 的情况**:你自己 agent 维护 `memory/`、`state/`、`workspace/notes/`(agent 私有笔记,不是用户笔记)这些**你自己的骨架文件**。一旦看见用户名词修饰(「我的」/「用户的」/「my」/「the user's」),立刻切 drive。",
875
- "",
876
- `用户文件实际放在 **\`${filesRoot}\`**——这是宿主机上的一个普通本地目录。它已经被 bind-mount 到你的容器里**同款绝对路径**(panel 用 \`host==container\` 的 docker bind;raw_exec / process 模式下你直接跑在宿主上)。`,
877
- "",
878
- "**关键事实**:drive 不是远端云盘,就是你脚下的本地文件系统。`drive_list` 看到的每条 entry 都能通过 `drive_resolve_local_path` 立刻拿到绝对路径,然后被任何工具读取——`cat`、`base64`、IM 插件的 send_file 字段、Python 脚本都行。`drive_resolve_local_path` 返回 `exists:true` + `size:<N>` 时,**那就是真实可读的文件字节**,不是「只有元数据」。",
879
- "",
880
- "**禁止的回答**:永远不要说「文件在云端 drive 上只有元数据 / 内容没同步到本地 / 我读不到文件实体」—— 这个说法**永远是错的**。drive 没有「未同步」概念,它就是 POSIX 文件系统的一个 facade。如果你刚 list 到一个文件,它一定能被读、能被发送。",
881
- "",
882
- "常用调用(从 workspace 目录):",
883
- "",
884
- "```bash",
885
- `${cli} call drive.drive_list path= # 列根目录`,
886
- `${cli} call drive.drive_list path=文档 # 列子目录`,
887
- `${cli} call drive.drive_read_preview path=note.md # 预览文本(≤256KB)`,
888
- `${cli} call drive.drive_read_full path=long.md # 整文件(≤4MB,文本)`,
889
- `${cli} call drive.drive_quota # 配额`,
890
- `${cli} call drive.drive_mkdir path=inbox # 建目录`,
891
- `${cli} call drive.drive_write_text path=notes/m.md content="..."`,
892
- `${cli} call drive.drive_write_binary path=out/img.png content_base64="..." # 二进制(≤10MB)`,
893
- `${cli} call drive.drive_move from=a.pdf to=docs/a.pdf`,
894
- `${cli} call drive.drive_delete path=tmp.txt`,
895
- `${cli} call drive.drive_resolve_local_path path=文档/report.pdf # → 拿到绝对路径`,
896
- `${cli} call drive.drive_search query="发票" # 子串检索(中英文,大小写不敏感)`,
897
- "```",
898
- "",
899
- "**检索策略(`drive_search` 是高召回但不精确的笨工具)**:整句问题先拆成关键词再搜——「找我去年三亚海边的照片」→ 搜 `三亚`、`海边`、`照片`(或空格分隔 `三亚 海边 照片`,空格 = OR)。它是连续子串匹配、不懂语义;命中后用 `drive_read_full` 读候选、自己判断与精排,召回不够就换同义词多搜几次。",
900
- "",
901
- "### 给用户发文件(飞书 / 微信 / 任何 IM)",
902
- "",
903
- "**用户问 \"把 X 文件发我\" 时不要拒绝、不要让用户去飞书云空间下载**——99% 的情况文件已经在你的文件系统里了。标准流程:",
904
- "",
905
- "1. `drive_list` 或 `drive_search` 先确认文件在 NAS 里(你刚 list 过的也算)。",
906
- "2. `drive_resolve_local_path path=文档/x.xlsx` 拿到 `abs_path`,确认 `exists:true`。",
907
- "3. 把 `abs_path` 传给**当前会话所在 IM 通道**的发送工具。**`target` 字段一律原样照搬当前消息 `Conversation info` 里的 `chat_id`——一个字符都不要加、不要改、不要补前缀**。各通道 chat_id 形态本来就不一样,照搬就对。",
908
- " - **飞书 DM**:metadata 给 `\"chat_id\":\"user:ou_xxx\"`(自带 `user:` 前缀,**这是飞书的格式不是通用约定**)→ `target=\"user:ou_xxx\"`。工具用 `message` (channel=feishu, msg_type=file, path=<abs_path>) 或 `openclaw-lark` 的 `feishu_im_user_message`。",
909
- " - **微信 DM**:metadata 给 `\"chat_id\":\"o9cq...@im.wechat\"`(**裸 ID,没有 `user:` 前缀**)→ `target=\"o9cq...@im.wechat\"`。工具用 `message` (channel=openclaw-weixin, msg_type=file, path=<abs_path>)。**千万别照搬飞书的 `user:` 加上去**——会让微信服务端的 `getuploadurl` 返 `ret:-1`,文件传不出去。",
910
- " - 通用规则:当前 inbound 消息的 `from` 就是回复 target。打开你刚收到的那条 user message 里 `Conversation info` 的 JSON,把 `chat_id` 整段复制就行。",
911
- "4. 失败先查 `exists` 字段、文件大小、IM 通道大小上限(飞书典型 30MB、微信 20MB),再决定降级方案。",
912
- "",
913
- "**ENOENT / \"no such file or directory\" 处理**:IM 插件返回 ENOENT 但 `drive_resolve_local_path` 刚刚 `exists:true`,**99% 是 panel 刚升级 / mount 刚刷新,但你这个 alloc 用的是旧 spec**。无脑重试一次。还是 ENOENT 才提示用户去 panel 重启实例(stop+start,不是 restart)——但**永远不要**回答 \"文件只是元数据所以读不到\",那是错的。",
914
- "",
915
- `要发**新生成**的文件(PDF、图片、报表):先 \`drive_write_binary path=${generatedOutboxPath} content_base64=...\` 落盘,再 resolve → 发送。`,
916
- "",
917
- "### 用户给你发文件",
918
- "",
919
- "目前飞书/微信通道不会自动把附件落盘到 NAS。当用户说\"文件给你了\"但你 `drive_list inbox` 看不到:",
920
- "- 优先让用户走 panel 的 Filebrowser(`/apps/filebrowser/`)或 WebDAV 把文件上传到 `inbox/`,再告诉你路径。",
921
- "- 飞书附件流:如果飞书 app 已配 `im:resource` 权限,可以用 `feishu_im_user_fetch_resource` 取 file_key、落到 `inbox/feishu/<date>/`。",
922
- "",
923
- "权限:在 panel \"关联 agent\" UI 里给实例授 ro/rw。403 时让用户去 panel 加。",
924
- "",
925
- JISHUSHELL_DRIVE_HINT_END,
926
- "",
927
- ].join("\n");
928
- let next;
929
- const beginIdx = original.indexOf(JISHUSHELL_DRIVE_HINT_BEGIN);
930
- const endIdx = original.indexOf(JISHUSHELL_DRIVE_HINT_END);
931
- if (beginIdx >= 0 && endIdx > beginIdx) {
932
- const tail = endIdx + JISHUSHELL_DRIVE_HINT_END.length;
933
- const after = original
934
- .slice(tail)
935
- .replace(/^\n+/, "\n");
936
- next = original.slice(0, beginIdx) + section + after;
937
- }
938
- else {
939
- const sep = original && !original.endsWith("\n") ? "\n\n" : "\n";
940
- next = (original ? original + sep : "") + section;
941
- }
942
- if (next === original)
943
- return;
944
- writeConfigFile(toolsPath, next);
945
- console.log(`[openclaw] Patched drive hint into ${toolsPath}`);
946
- }
947
- catch (e) {
948
- console.warn(`[openclaw] Failed to patch TOOLS.md drive hint: ${e.message}`);
949
- }
950
- }
951
- export function resolveKbProvider(kbBinding) {
952
- const PROVIDER_ANYLLM = "anythingllm-container";
953
- const PROVIDER_JISHUKB = "jishu-kb-container";
954
- const idToTag = (id) => {
955
- if (id === PROVIDER_JISHUKB)
956
- return "jishukb";
957
- if (id === PROVIDER_ANYLLM)
958
- return "anythingllm";
959
- return null;
960
- };
961
- if (kbBinding === null)
962
- return null;
963
- if (kbBinding && typeof kbBinding === "object") {
964
- const b = kbBinding;
965
- if (b.kind === "single") {
966
- return idToTag(b.providerId);
967
- }
968
- if (b.kind === "many") {
969
- // User selected the "many" mode but the providers array is malformed
970
- // or empty → treat as "no known provider bound", same as a list of
971
- // only-unknown providers. Avoids the surprise where a malformed
972
- // array silently falls back to legacy auto-anythingllm.
973
- if (!Array.isArray(b.providers))
974
- return null;
975
- // First known match in the user's order wins — the UI lets users
976
- // drag to reorder; we honor that order rather than imposing our own.
977
- for (const p of b.providers) {
978
- const tag = idToTag(p?.providerId);
979
- if (tag !== null)
980
- return tag;
981
- }
982
- return null;
983
- }
984
- return "anythingllm"; // unknown binding shape → legacy default
985
- }
986
- return "anythingllm"; // undefined → legacy default
987
- }
988
- /**
989
- * Per-provider kb-shim residue cleanup. Wipes the shim source (replacing
990
- * the bytes with a removal marker rather than `unlink`-ing — the latter
991
- * would race with a concurrent `node <shim>` that already opened it) and
992
- * `unlink`s the sibling `secret.json` if any. Idempotent and safe to call
993
- * even if no shim was ever installed.
994
- *
995
- * Called by EVERY branch of the kb auto-wire block so a rebind from
996
- * anythingllm ↔ jishukb (or → null) never leaves stale shim files or
997
- * 0o600 secrets on disk. The "wipe by overwrite" pattern matches what
998
- * the old anythingllm-only branch did before the dispatch refactor.
999
- *
1000
- * agentHome is the OpenClaw container's `$HOME` (the value returned by
1001
- * `openclawAdapter.resolveAgentHome(instanceId)`). `which` selects the
1002
- * provider: each gets its own `__mcp_shims__/<which>/` subtree.
1003
- *
1004
- * Exported so the security-critical secret-deletion behavior can be
1005
- * covered by a focused unit test without standing up the full start hook.
1006
- */
1007
- export function wipeKbShimDir(agentHome, which) {
1008
- const dir = join(agentHome, "__mcp_shims__", which);
1009
- const shimPath = join(dir, `${which}-shim.js`);
1010
- const removalMarker = which === "anythingllm"
1011
- ? "// removed: AnythingLLM not bound as knowledge provider\n"
1012
- : "// removed: jishu-kb not bound as knowledge provider\n";
1013
- try {
1014
- if (existsSync(shimPath)) {
1015
- writeFileSync(shimPath, removalMarker, { mode: 0o644 });
1016
- }
1017
- }
1018
- catch { /* best effort */ }
1019
- // AnythingLLM's shim has a sibling 0o600 secret.json (API key). v1
1020
- // jishu-kb ships without auth so no secret to wipe — when jishu-kb
1021
- // adds JISHU_KB_AUTH_TOKEN_FILE we'll start writing a secret.json
1022
- // here too and the unlink must be added below.
1023
- if (which === "anythingllm") {
1024
- const secretPath = join(dir, "secret.json");
1025
- try {
1026
- if (existsSync(secretPath))
1027
- unlinkSync(secretPath);
1028
- }
1029
- catch { /* best effort */ }
1030
- }
1031
- }
1032
- export function patchToolsMdKbHint(workspaceDir, mode, provider, mcporterCommand = "mcporter", instanceId, mediaInboundRoot) {
1033
- try {
1034
- const toolsPath = join(workspaceDir, "TOOLS.md");
1035
- let original = "";
1036
- try {
1037
- original = readFileSync(toolsPath, "utf-8");
1038
- }
1039
- catch (e) {
1040
- if (e?.code !== "ENOENT")
1041
- throw e;
1042
- if (mode === "remove")
1043
- return; // nothing to strip
1044
- }
1045
- // Strip every existing kb section first — tolerant of legacy variants
1046
- // (e.g. early manual injections that used "END auto-generated -->"
1047
- // instead of the current "END -->" marker). Without this, repeated
1048
- // re-patches would accumulate sections in TOOLS.md.
1049
- const STRIP_RE = /\n*<!-- jishushell-kb: BEGIN[^>]*-->[\s\S]*?<!-- jishushell-kb: END[^>]*-->\n*/g;
1050
- const stripped = original.replace(STRIP_RE, "\n");
1051
- let next;
1052
- if (mode === "remove") {
1053
- if (stripped === original)
1054
- return;
1055
- next = stripped;
1056
- }
1057
- else {
1058
- if (!provider) {
1059
- throw new Error("provider is required when installing KB hint");
1060
- }
1061
- const cli = mcporterCommand === "mcporter" ? "mcporter" : JSON.stringify(mcporterCommand);
1062
- const generatedOutboxPath = instanceId
1063
- ? `agent-data/${instanceId}/outbox/report.md`
1064
- : "agent-data/<instance>/outbox/report.md";
1065
- const attachmentInboxPath = mediaInboundRoot || "<openclawHome>/.openclaw/media/inbound";
1066
- const section = provider === "jishukb"
1067
- ? [
1068
- JISHUSHELL_KB_HINT_BEGIN,
1069
- "",
1070
- "### 📚 知识库(JishuShell-KB)",
1071
- "",
1072
- "用户长期投递并已经导入到 **JishuShell-KB** 的文档(手册、PDF、内部笔记、会议纪要等)可以检索;你也可以列知识库、创建知识库、把 drive 文件上传入库、查看已索引文档、查看 handbook、读取**脱敏后的**当前配置,以及在用户明确确认时删除文档/知识库。",
1073
- "",
1074
- "**当前 provider 暴露的工具**:",
1075
- "",
1076
- `- \`${cli} call kb.kb_list\` — 列出所有知识库(拿 id / name / chunks 数)`,
1077
- `- \`${cli} call kb.kb_create name="产品文档" description="可选"\` — 新建知识库`,
1078
- `- \`${cli} call kb.kb_search query="<用户原话>" kbId=<可选> topK=<可选>\` — 检索指定或默认知识库`,
1079
- `- \`${cli} call kb.kb_upload path="<drive_resolve_local_path 返回的绝对路径>" kbId="<目标知识库 id>"\` — 上传并索引文件到指定知识库`,
1080
- `- \`${cli} call kb.kb_list_documents kbId=<可选>\` — 列出指定或默认知识库里的已索引文档`,
1081
- `- \`${cli} call kb.kb_read_handbook section="设置 → 知识库"\` — 读取 handbook 全文或指定章节`,
1082
- `- \`${cli} call kb.kb_get_config\` — 读取当前**脱敏后的**知识库配置摘要`,
1083
- `- \`${cli} call kb.kb_delete_document kbId="<知识库 id>" documentId="<文档 id>" confirmDocumentId="<同一个文档 id>"\` — 删除文档(危险操作,必须显式确认)`,
1084
- `- \`${cli} call kb.kb_delete_kb kbId="<知识库 id>" confirmKbId="<同一个知识库 id>"\` — 删除知识库(危险操作,必须显式确认)`,
1085
- "",
1086
- "**推荐调用顺序**:",
1087
- "1. 用户提到“某个指定知识库 / 某个库里”但你不知道 id → 先 `kb_list`。",
1088
- "2. 用户要把 drive 里的文件加入知识库 → 先 `drive_resolve_local_path`,再 `kb_upload path=<abs_path> kbId=<显式 id>`。",
1089
- `3. 用户当前消息已经附了文件,而且消息里给了宿主机绝对路径(通常在 \`${attachmentInboxPath}/...\`)→ 直接把这个绝对路径传给 \`kb_upload\`;不要先把内容重写到 \`files/\` 根目录,也不要自己猜 \`agent-data/agent1/...\` 这种路径。`,
1090
- `4. 用户要上传你**新生成**的文件 → 先 \`drive_write_text\` / \`drive_write_binary\` 到 \`${generatedOutboxPath}\`,再 \`drive_resolve_local_path\` → \`kb_upload\`。`,
1091
- "5. 用户要新建库并马上上传 → `kb_create` → 记住返回的 id → `kb_upload`。",
1092
- "6. 用户要解释某个设置项怎么用 → 先 `kb_read_handbook`,必要时再 `kb_get_config` 看当前值。",
1093
- "",
1094
- `**安全规则**:写操作和删除操作不要猜目标知识库;拿不准就先 \`kb_list\`。删除必须是用户明确要求,且把 confirm 字段原样填成同一个 id。 \`kb_get_config\` 只返回脱敏摘要,不会给你密钥。 \`kb_upload\` 只接受来自当前实例已挂载文件目录,或当前实例附件 inbox(\`${attachmentInboxPath}/...\`)的绝对路径。**`,
1095
- "",
1096
- "**与 drive 的分工**:",
1097
- "- `drive.*` = 文件系统 facade(列目录、读字节、拿绝对路径)—— 要的是**文件本体**用 drive",
1098
- "- `kb.*` = 知识库检索/管理/上传 —— 要的是**知识库里的内容和状态**用 kb",
1099
- "",
1100
- "两者数据不共享:drive 里有文件 ≠ 某个知识库已经索引了它。",
1101
- "",
1102
- "**搜不到时的标准回复**:如果 `kb_search` 没结果,就直接说「我在当前知识库里没找到相关内容」。如果用户问的是 drive 里已有文件,可进一步建议「要我把它上传到某个知识库吗?」—— 但上传前先确认目标 kbId,不要自己猜默认库。",
1103
- "",
1104
- JISHUSHELL_KB_HINT_END,
1105
- "",
1106
- ].join("\n")
1107
- : [
1108
- JISHUSHELL_KB_HINT_BEGIN,
1109
- "",
1110
- "### 📚 知识库(AnythingLLM)",
1111
- "",
1112
- "用户长期投递的文档(手册、PDF、内部笔记、过往会议纪要等)由 **AnythingLLM** 维护索引(本地 LanceDB 向量库 + 内置 Xenova ONNX embedder),通过 `kb.kb_search` 一次调用拿「答案 + 引用来源」。",
1113
- "",
1114
- "**两个工具**:",
1115
- "",
1116
- `- \`${cli} call kb.kb_search query="<用户原话>"\` — 在已索引文档里检索,返回答案 + 最多 5 条引用源`,
1117
- `- \`${cli} call kb.kb_ingest path="<绝对路径>"\` — 把 drive 里的文件加入知识库并 embed(用户说「加进知识库 / index this / 学习这份」时调)`,
1118
- "",
1119
- "**ingest 标准链**(drive 里的文件 → 知识库):",
1120
- `1. \`${cli} call drive.drive_resolve_local_path path=inbox/contract.pdf\` → 拿 \`abs_path\``,
1121
- `2. \`${cli} call kb.kb_ingest path=<abs_path>\` → AnythingLLM 自动 embed`,
1122
- "3. 几秒后用户问相关问题,`kb_search` 命中",
1123
- "",
1124
- "**search 什么时候调**:用户问的东西像在已上传文档里能找到——「那个 X 的手册里怎么说」、「我们之前关于 Y 的讨论」、「产品规格」、「合同条款」、「what does the doc say about X」等。",
1125
- "",
1126
- "**什么时候不要调**:寒暄、纯代码生成、数学计算、实时信息(天气/股票/新闻)、**操作 NAS 文件**(那是 `drive.*`,不是 kb)、纯创作类。",
1127
- "",
1128
- "**与 drive 的分工**:",
1129
- "- `drive.*` = 文件系统 facade(列目录、读字节、发文件)—— 要的是**文件本体**用 drive",
1130
- "- `kb.kb_search` / `kb.kb_ingest` = 语义检索 + RAG 入库 —— 要的是**答案/知识**用 kb",
1131
- "",
1132
- "两者数据**不共享**:drive 看到 `manual.pdf` ≠ kb 一定能搜到它。要让 kb 能搜到 → 先 `kb_ingest`。",
1133
- "",
1134
- "**搜不到时的标准回复**:`kb_search` 回答里说「无相关文档」或 sources 为空 → 先确认 drive 里有没有相关文件,如果有,主动建议「要我把它加入知识库吗」(用户同意就 `drive_resolve_local_path` + `kb_ingest`);drive 也没有,告诉用户「我在你的知识库里没找到相关内容」,然后**不要继续幻想答案**。",
1135
- "",
1136
- JISHUSHELL_KB_HINT_END,
1137
- "",
1138
- ].join("\n");
1139
- const sep = stripped && !stripped.endsWith("\n") ? "\n\n" : "\n";
1140
- next = (stripped ? stripped + sep : "") + section;
1141
- }
1142
- if (next === original)
1143
- return;
1144
- writeConfigFile(toolsPath, next);
1145
- console.log(`[openclaw] ${mode === "remove" ? "Removed" : "Patched"} kb hint in ${toolsPath}`);
1146
- }
1147
- catch (e) {
1148
- console.warn(`[openclaw] Failed to ${mode} TOOLS.md kb hint: ${e.message}`);
1149
- }
1150
- }
1151
- /**
1152
- * Pre-seed the per-instance npm global prefix with a symlink to the image's
1153
- * baked openclaw package so OpenClaw's in-gateway "Update now" handler can
1154
- * detect the install as an npm global install. Idempotent; docker driver only.
1155
- */
1156
- function ensureOpenclawUpdateSeed(openclawHome, instanceId) {
1157
- if (getNomadDriver() !== "docker")
1158
- return;
1159
- if (!openclawHome)
1160
- return;
1161
- const linkDir = join(openclawHome, ".npm-global", "lib", "node_modules");
1162
- const linkPath = join(linkDir, "openclaw");
1163
- try {
1164
- lstatSync(linkPath);
1165
- return;
1166
- }
1167
- catch (err) {
1168
- if (err?.code !== "ENOENT") {
1169
- console.warn(`[openclaw] update-seed: lstat failed for ${linkPath}: ${err?.message ?? err}`);
1170
- return;
1171
- }
1172
- }
1173
- try {
1174
- mkdirSync(linkDir, { recursive: true });
1175
- symlinkSync(CONTAINER_IMAGE_PKG_ROOT, linkPath);
1176
- console.log(`[openclaw] update-seed ${instanceId}: seeded ${linkPath} -> ${CONTAINER_IMAGE_PKG_ROOT}`);
1177
- }
1178
- catch (err) {
1179
- console.warn(`[openclaw] update-seed ${instanceId}: failed to create seed: ${err?.message ?? err}`);
1180
- }
1181
- }
1182
- // ── Session fence patch (OpenClaw >= 5.19 regression) ─────────────────
1183
- /**
1184
- * The minimum OpenClaw version where the session fence bug exists.
1185
- * The bug was introduced in v2026.5.19 — `eventMayReachTranscriptWriters()`
1186
- * doesn't recognize `"message"` / `"custom_message"` event types, causing
1187
- * session writes to bypass `withSessionWriteLock`, which in turn leaves
1188
- * the file fingerprint stale and triggers `EmbeddedAttemptSessionTakeoverError`
1189
- * on the next prompt.
1190
- *
1191
- * Additionally, on virtiofs mounts (macOS → Colima VM → Docker), file
1192
- * metadata (mtime/ctime) can drift between `releaseForPrompt()` and
1193
- * `assertSessionFileFence()` even without actual writes, due to the
1194
- * multi-layer filesystem stack timing. Patching `assertSessionFileFence`
1195
- * to a no-op fully disables the flawed fence check.
1196
- */
1197
- const SESSION_FENCE_BUG_MIN_VERSION = [2026, 5, 19];
1198
- /**
1199
- * Maximum version (exclusive) to apply the patch. Once OpenClaw ships a fix
1200
- * upstream, set a concrete version here to stop patching newer releases.
1201
- * For now, no upper bound — patch all versions >= MIN.
1202
- */
1203
- /**
1204
- * Safety limit: if the extracted function body exceeds this many characters,
1205
- * skip the patch to avoid corrupting the bundle (e.g. brace-depth counter
1206
- * fooled by string literals containing braces in a future refactored version).
1207
- */
1208
- const MAX_PATCH_TARGET_BODY_LENGTH = 5000;
1209
- /**
1210
- * Patch targets: each entry defines a function to replace.
1211
- * - `eventMayReachTranscriptWriters`: broad return prevents events from
1212
- * bypassing the write lock (necessary but not sufficient on virtiofs).
1213
- * - `assertSessionFileFence`: no-op disables the fingerprint comparison
1214
- * that false-triggers due to virtiofs stat drift.
1215
- */
1216
- const SESSION_FENCE_PATCH_TARGETS = [
1217
- {
1218
- fnName: "function assertSessionFileFence()",
1219
- litNeedle: "sameSessionFileFingerprint",
1220
- replacement: "function assertSessionFileFence() { return; }",
1221
- },
1222
- {
1223
- fnName: "function eventMayReachTranscriptWriters",
1224
- litNeedle: '"message_update"',
1225
- replacement: 'function eventMayReachTranscriptWriters(session, event) { return typeof event?.type === "string"; }',
1226
- },
1227
- ];
1228
- /**
1229
- * Patch the session fence bug in OpenClaw >= 5.19 by replacing the
1230
- * `eventMayReachTranscriptWriters` function in the minified bundle.
1231
- *
1232
- * Idempotent: uses a marker file containing the SHA-256 of the patched
1233
- * file. Skips if already patched or if the pattern is not found (future
1234
- * fixed version or different bundle layout).
1235
- *
1236
- * Docker-only: the bug manifests through the virtiofs mount timing
1237
- * discrepancy between container and host — raw_exec/process modes are
1238
- * unaffected in practice.
1239
- */
1240
- export function patchSessionFenceBug(openclawHome, instanceId) {
1241
- if (getNomadDriver() !== "docker")
1242
- return;
1243
- // 1. Read installed version from npm-global package.json
1244
- const pkgPath = join(openclawHome, ".npm-global", "lib", "node_modules", "openclaw", "package.json");
1245
- let versionStr;
1246
- try {
1247
- const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
1248
- versionStr = pkg.version || "";
1249
- }
1250
- catch {
1251
- return; // no npm-global install or unreadable — skip
1252
- }
1253
- // 2. Parse version and check minimum threshold
1254
- const parts = versionStr.split(".").map(Number);
1255
- if (parts.length < 3 || parts.some(Number.isNaN))
1256
- return;
1257
- const [major, minor, patch] = parts;
1258
- const [minMajor, minMinor, minPatch] = SESSION_FENCE_BUG_MIN_VERSION;
1259
- if (major < minMajor ||
1260
- (major === minMajor && minor < minMinor) ||
1261
- (major === minMajor && minor === minMinor && patch < minPatch)) {
1262
- return; // version predates the bug
1263
- }
1264
- // 3. Find the selection-*.js bundle that contains the target function.
1265
- // There may be multiple selection-*.js files in dist/; only one holds
1266
- // the session management code.
1267
- const distDir = join(openclawHome, ".npm-global", "lib", "node_modules", "openclaw", "dist");
1268
- let bundleFiles;
1269
- try {
1270
- const entries = readdirSync(distDir);
1271
- bundleFiles = entries.filter((f) => f.startsWith("selection-") && f.endsWith(".js"));
1272
- }
1273
- catch {
1274
- return; // dist dir missing or unreadable
1275
- }
1276
- if (bundleFiles.length === 0)
1277
- return;
1278
- // Scan each candidate for any of the patch target signatures
1279
- let bundlePath;
1280
- let bundleContent;
1281
- for (const file of bundleFiles) {
1282
- const candidatePath = join(distDir, file);
1283
- let content;
1284
- try {
1285
- content = readFileSync(candidatePath, "utf-8");
1286
- }
1287
- catch {
1288
- continue;
1289
- }
1290
- // Match if any target's fnName or litNeedle is present
1291
- const hasTarget = SESSION_FENCE_PATCH_TARGETS.some((t) => content.includes(t.fnName) || content.includes(t.litNeedle));
1292
- if (hasTarget) {
1293
- bundlePath = candidatePath;
1294
- bundleContent = content;
1295
- break;
1296
- }
1297
- }
1298
- if (!bundlePath || !bundleContent)
1299
- return;
1300
- // 4. Check marker file for idempotency
1301
- const markerPath = join(distDir, `.session-fence-patched`);
1302
- const currentHash = createHash("sha256").update(bundleContent).digest("hex");
1303
- try {
1304
- const marker = readFileSync(markerPath, "utf-8").trim();
1305
- if (marker === currentHash)
1306
- return; // already patched, hash matches
1307
- }
1308
- catch {
1309
- // marker missing — proceed
1310
- }
1311
- // 5. Apply each patch target using brace-depth counting to extract and
1312
- // replace function bodies. Process targets in order; earlier patches
1313
- // shift offsets so we re-search after each replacement.
1314
- let patched = bundleContent;
1315
- let patchCount = 0;
1316
- for (const target of SESSION_FENCE_PATCH_TARGETS) {
1317
- let fnStart = patched.indexOf(target.fnName);
1318
- // Fallback for eventMayReachTranscriptWriters: locate by unique literal
1319
- // combination ("message_update" near "message_end" and "agent_end")
1320
- if (fnStart === -1 && target.litNeedle === '"message_update"') {
1321
- let scanPos = 0;
1322
- while (scanPos < patched.length) {
1323
- const litIdx = patched.indexOf(target.litNeedle, scanPos);
1324
- if (litIdx === -1)
1325
- break;
1326
- const window = patched.slice(litIdx, litIdx + 200);
1327
- if (window.includes('"message_end"') && window.includes('"agent_end"')) {
1328
- const searchStart = Math.max(0, litIdx - 300);
1329
- const prefix = patched.slice(searchStart, litIdx);
1330
- const fnKeywordIdx = prefix.lastIndexOf("function ");
1331
- if (fnKeywordIdx !== -1) {
1332
- fnStart = searchStart + fnKeywordIdx;
1333
- break;
1334
- }
1335
- }
1336
- scanPos = litIdx + 1;
1337
- }
1338
- }
1339
- if (fnStart === -1)
1340
- continue; // target not found (already patched or fixed version)
1341
- // Check if already patched (replacement is short and contains `return;`)
1342
- const peekEnd = Math.min(fnStart + target.replacement.length + 10, patched.length);
1343
- const peek = patched.slice(fnStart, peekEnd);
1344
- if (peek.startsWith(target.replacement))
1345
- continue;
1346
- // Extract function body with brace-depth counting
1347
- const braceStart = patched.indexOf("{", fnStart);
1348
- if (braceStart === -1)
1349
- continue;
1350
- let depth = 0;
1351
- let fnEnd = -1;
1352
- for (let i = braceStart; i < patched.length; i++) {
1353
- if (patched[i] === "{")
1354
- depth++;
1355
- else if (patched[i] === "}") {
1356
- depth--;
1357
- if (depth === 0) {
1358
- fnEnd = i + 1;
1359
- break;
1360
- }
1361
- }
1362
- }
1363
- if (fnEnd === -1)
1364
- continue;
1365
- // Safety: if extracted body is suspiciously large, skip to avoid corrupting
1366
- // the bundle (brace counter may have been fooled by string contents).
1367
- if (fnEnd - fnStart > MAX_PATCH_TARGET_BODY_LENGTH) {
1368
- console.warn(`[openclaw] session-fence-patch ${instanceId}: skipping ${target.fnName} — body too large (${fnEnd - fnStart} chars)`);
1369
- continue;
1370
- }
1371
- patched = patched.slice(0, fnStart) + target.replacement + patched.slice(fnEnd);
1372
- patchCount++;
1373
- }
1374
- if (patchCount === 0) {
1375
- // No targets needed patching — write marker for current state
1376
- try {
1377
- writeFileSync(markerPath, currentHash + "\n", "utf-8");
1378
- }
1379
- catch {
1380
- /* best effort */
1381
- }
1382
- return;
1383
- }
1384
- // 7. Atomic write: temp file → rename
1385
- const tmpPath = bundlePath + `.tmp.${randomBytes(4).toString("hex")}`;
1386
- try {
1387
- writeFileSync(tmpPath, patched, "utf-8");
1388
- renameSync(tmpPath, bundlePath);
1389
- }
1390
- catch (err) {
1391
- // Clean up temp file on failure
1392
- try {
1393
- unlinkSync(tmpPath);
1394
- }
1395
- catch {
1396
- /* ignore */
1397
- }
1398
- console.warn(`[openclaw] session-fence-patch ${instanceId}: atomic write failed: ${err?.message ?? err}`);
1399
- return;
1400
- }
1401
- // 8. Write marker with hash of the PATCHED file
1402
- const patchedHash = createHash("sha256").update(patched).digest("hex");
1403
- try {
1404
- writeFileSync(markerPath, patchedHash + "\n", "utf-8");
1405
- }
1406
- catch {
1407
- // Non-fatal — patch was applied, marker just helps idempotency
1408
- }
1409
- console.log(`[openclaw] session-fence-patch ${instanceId}: patched ${bundlePath.split("/").pop()} (v${versionStr})`);
1410
- }
1411
- // ── Container-side patch script ───────────────────────────────────────────
1412
- /**
1413
- * Self-contained Node.js script that patches the session fence bug from
1414
- * INSIDE the container. Written to `$OPENCLAW_HOME/.jishushell/session-fence-patch.mjs`
1415
- * by onBeforeStart and executed by the inline Docker entrypoint before the
1416
- * OpenClaw gateway starts.
1417
- *
1418
- * This covers the case where an in-container `npm install openclaw@latest`
1419
- * upgrades to a buggy version (>= 5.19) after the container was created
1420
- * with a clean image (5.7). The host-side `patchSessionFenceBug` cannot
1421
- * patch at onBeforeStart time because the npm-global directory may not yet
1422
- * contain the upgraded bundle (it's a dangling symlink to a container-only path).
1423
- */
1424
- const CONTAINER_PATCH_SCRIPT = `#!/usr/bin/env node
1425
- // Session fence patch — auto-generated by JishuShell.
1426
- // Patches assertSessionFileFence + eventMayReachTranscriptWriters
1427
- // in OpenClaw >= 2026.5.19 to work around virtiofs stat drift.
1428
- import { readFileSync, writeFileSync, readdirSync, renameSync, existsSync } from "fs";
1429
- import { join } from "path";
1430
- import { createHash } from "crypto";
1431
-
1432
- const home = process.env.HOME || process.env.OPENCLAW_HOME || "/home/openclaw";
1433
- const distDir = join(home, ".npm-global", "lib", "node_modules", "openclaw", "dist");
1434
- const pkgPath = join(home, ".npm-global", "lib", "node_modules", "openclaw", "package.json");
1435
-
1436
- try {
1437
- const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
1438
- const parts = (pkg.version || "").split(".").map(Number);
1439
- if (parts.length < 3 || parts[0] < 2026 || (parts[0] === 2026 && parts[1] < 5) ||
1440
- (parts[0] === 2026 && parts[1] === 5 && parts[2] < 19)) process.exit(0);
1441
- // No upper version cap for now — patch all versions >= 5.19
1442
- } catch { process.exit(0); }
1443
-
1444
- const markerPath = join(distDir, ".session-fence-patched");
1445
- let files;
1446
- try { files = readdirSync(distDir).filter(f => f.startsWith("selection-") && f.endsWith(".js")); }
1447
- catch { process.exit(0); }
1448
-
1449
- const targets = [
1450
- { fn: "function assertSessionFileFence()", repl: "function assertSessionFileFence() { return; }" },
1451
- { fn: "function eventMayReachTranscriptWriters", repl: 'function eventMayReachTranscriptWriters(session, event) { return typeof event?.type === "string"; }' },
1452
- ];
1453
-
1454
- for (const file of files) {
1455
- const p = join(distDir, file);
1456
- let src;
1457
- try { src = readFileSync(p, "utf-8"); } catch { continue; }
1458
- if (!targets.some(t => src.includes(t.fn) || src.includes("sameSessionFileFingerprint"))) continue;
1459
-
1460
- const hash = createHash("sha256").update(src).digest("hex");
1461
- try { if (readFileSync(markerPath, "utf-8").trim() === hash) process.exit(0); } catch {}
1462
-
1463
- let modified = src;
1464
- let count = 0;
1465
- for (const t of targets) {
1466
- const idx = modified.indexOf(t.fn);
1467
- if (idx === -1) continue;
1468
- if (modified.slice(idx, idx + t.repl.length + 5).startsWith(t.repl)) continue;
1469
- const braceStart = modified.indexOf("{", idx);
1470
- if (braceStart === -1) continue;
1471
- let d = 0, end = -1;
1472
- for (let i = braceStart; i < modified.length; i++) {
1473
- if (modified[i] === "{") d++;
1474
- else if (modified[i] === "}") { d--; if (d === 0) { end = i + 1; break; } }
1475
- }
1476
- if (end === -1) continue;
1477
- if (end - idx > 5000) continue; // safety: skip if body suspiciously large
1478
- modified = modified.slice(0, idx) + t.repl + modified.slice(end);
1479
- count++;
1480
- }
1481
- if (count === 0) {
1482
- try { writeFileSync(markerPath, hash + "\\n"); } catch {}
1483
- process.exit(0);
1484
- }
1485
- const tmp = p + ".tmp." + Math.random().toString(36).slice(2, 8);
1486
- writeFileSync(tmp, modified);
1487
- renameSync(tmp, p);
1488
- const newHash = createHash("sha256").update(modified).digest("hex");
1489
- try { writeFileSync(markerPath, newHash + "\\n"); } catch {}
1490
- console.log("[session-fence-patch] patched " + file);
1491
- break;
1492
- }
1493
- `;
1494
- const CONTAINER_PATCH_ENTRYPOINT_COMMAND = 'node "$HOME/.jishushell/session-fence-patch.mjs" 2>/dev/null || true; exec /usr/local/bin/openclaw-entry.sh "$@"';
1495
- /**
1496
- * Write the container-side patch script to the openclaw-home directory so it
1497
- * is available inside the container via the bind mount.
1498
- *
1499
- * Called from onBeforeStart. Idempotent — only rewrites if content changed.
1500
- */
1501
- export function writeContainerPatchScript(openclawHome) {
1502
- const scriptDir = join(openclawHome, ".jishushell");
1503
- try {
1504
- ensureDirContainer(scriptDir);
1505
- }
1506
- catch (err) {
1507
- console.warn(`[openclaw] Failed to prepare container patch directory ${scriptDir}: ${err?.message ?? err}`);
1508
- return;
1509
- }
1510
- const scriptPath = join(scriptDir, "session-fence-patch.mjs");
1511
- ensureReadableContent(scriptPath, CONTAINER_PATCH_SCRIPT);
1512
- }
1513
- function ensureReadableContent(path, content) {
1514
- try {
1515
- if (existsSync(path) && readFileSync(path, "utf-8") === content) {
1516
- chmodSync(path, 0o644);
1517
- return;
1518
- }
1519
- writeConfigFile(path, content);
1520
- }
1521
- catch (err) {
1522
- console.warn(`[openclaw] Failed to write patch script ${path}: ${err?.message ?? err}`);
1523
- }
1524
- }
1525
- function resolveUidGid(username) {
1526
- try {
1527
- if (!VALID_USER_RE.test(username)) {
1528
- console.warn(`[openclaw] Invalid username for UID lookup: ${username}`);
1529
- return `${process.getuid()}:${process.getgid()}`;
1530
- }
1531
- const passwd = readFileSync("/etc/passwd", "utf-8");
1532
- const line = passwd.split("\n").find((l) => l.startsWith(username + ":"));
1533
- if (line) {
1534
- const parts = line.split(":");
1535
- const uid = parseInt(parts[2], 10);
1536
- const gid = parseInt(parts[3], 10);
1537
- if (!isNaN(uid) && !isNaN(gid))
1538
- return `${uid}:${gid}`;
1539
- }
1540
- }
1541
- catch {
1542
- /* ignore */
1543
- }
1544
- return `${process.getuid()}:${process.getgid()}`;
1545
- }
1546
- function normalizeDockerResources(instanceId, resources) {
1547
- const requestedMemoryMB = Number(resources.MemoryMB ?? DEFAULT_RESOURCES.MemoryMB);
1548
- let effectiveMemoryMB = requestedMemoryMB;
1549
- let effectiveMemoryMaxMB = Math.min(Number(resources.MemoryMaxMB ?? requestedMemoryMB), getMaxAppMemoryMB());
1550
- if (effectiveMemoryMaxMB < effectiveMemoryMB) {
1551
- console.warn(`[openclaw] ${instanceId}: MemoryMaxMB (${effectiveMemoryMaxMB}) is below MemoryMB (${effectiveMemoryMB}); clamping.`);
1552
- effectiveMemoryMaxMB = effectiveMemoryMB;
1553
- }
1554
- return {
1555
- ...resources,
1556
- MemoryMB: effectiveMemoryMB,
1557
- MemoryMaxMB: effectiveMemoryMaxMB,
1558
- };
1559
- }
1560
- // ── Nomad template safety (migrated from nomad-manager.ts) ────────────
1561
- const NOMAD_TEMPLATE_UNSAFE_RE = /[{}"\\]/;
1562
- function assertSafeTemplateId(id) {
1563
- if (NOMAD_TEMPLATE_UNSAFE_RE.test(id)) {
1564
- throw new Error(`Job ID "${id}" contains characters unsafe for Nomad Template interpolation`);
1565
- }
1566
- }
1567
- // ── Lazy-imported framework helpers (avoid circular deps) ─────────────
1568
- //
1569
- // The adapter reaches back into instance-manager.ts for helpers that still
1570
- // live there. Using lazy `await import()` keeps the static import graph
1571
- // acyclic, so runtime/index.ts → adapters/openclaw.ts loads cleanly before
1572
- // instance-manager.ts needs it.
1573
- async function lazyIm() {
1574
- return await import("../../instance-manager.js");
1575
- }
1576
- // ── Docker image build helpers (physically migrated from setup-manager) ─
1577
- //
1578
- // All OpenClaw-specific docker image build knowledge lives here. setup-manager
1579
- // only retains a thin dispatch wrapper so the public
1580
- // `buildSlimOpenclawImage()` / `startBuildSlimOpenclawImage()` API remains
1581
- // back-compatible for routes/setup.ts and the CLI installer.
1582
- /** Base image used for the slim OpenClaw runtime image. */
1583
- const DOCKER_BASE_IMAGE = "node:22-slim";
1584
- /** Mirror list tried in order when docker.io is unreachable. */
1585
- const DOCKER_BASE_MIRRORS = [
1586
- "node:22-slim",
1587
- "hub-mirror.c.163.com/library/node:22-slim",
1588
- "mirrors.tencent.com/library/node:22-slim",
1589
- "registry.cn-hangzhou.aliyuncs.com/library/node:22-slim",
1590
- ];
1591
- /** Matches a semver-ish tag suffix, e.g. "...:2026.4.9" or "...:v1.2.3-beta". */
1592
- const PINNED_IMAGE_TAG_RE = /:[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$/;
1593
- /**
1594
- * Pull DOCKER_BASE_IMAGE from mirrors if not already cached locally.
1595
- */
1596
- async function _ensureDockerBaseImage(invocation, task) {
1597
- try {
1598
- execFileSync(invocation.cmd, [...invocation.argsPrefix, "image", "inspect", DOCKER_BASE_IMAGE], {
1599
- timeout: 5000,
1600
- stdio: "ignore",
1601
- });
1602
- emitTask(task, { type: "log", message: `基础镜像已缓存: ${DOCKER_BASE_IMAGE}` });
1603
- return DOCKER_BASE_IMAGE;
1604
- }
1605
- catch {
1606
- /* not cached, fall through */
1607
- }
1608
- for (const mirror of DOCKER_BASE_MIRRORS) {
1609
- emitTask(task, { type: "log", message: `拉取基础镜像: ${mirror} ...` });
1610
- const result = await spawnWithTask(task, invocation.cmd, [...invocation.argsPrefix, "pull", mirror], { timeout: 300000 });
1611
- if (result.ok) {
1612
- if (mirror !== DOCKER_BASE_IMAGE) {
1613
- try {
1614
- execFileSync(invocation.cmd, [...invocation.argsPrefix, "tag", mirror, DOCKER_BASE_IMAGE], { timeout: 10000 });
1615
- }
1616
- catch {
1617
- /* tag failure is non-fatal */
1618
- }
1619
- }
1620
- emitTask(task, { type: "log", message: `基础镜像就绪: ${DOCKER_BASE_IMAGE}` });
1621
- return DOCKER_BASE_IMAGE;
1622
- }
1623
- emitTask(task, { type: "log", message: ` → ${mirror} 不可达,尝试下一个镜像源...` });
1624
- }
1625
- throw new Error(`无法获取基础镜像 ${DOCKER_BASE_IMAGE}。请检查网络或手动执行: docker pull ${DOCKER_BASE_MIRRORS[1]}`);
1626
- }
1627
- /**
1628
- * Query the npm registry for the current OpenClaw version. Used to bust the
1629
- * Docker layer cache for `RUN npm install openclaw@${ver}` during local build.
1630
- */
1631
- function resolveOpenclawNpmVersion() {
1632
- try {
1633
- const out = execFileSync("npm", ["view", "openclaw", "version"], {
1634
- timeout: 15000,
1635
- encoding: "utf-8",
1636
- stdio: ["ignore", "pipe", "ignore"],
1637
- }).trim();
1638
- if (/^\d+\.\d+\.\d+/.test(out))
1639
- return out;
1640
- }
1641
- catch {
1642
- /* npm not reachable */
1643
- }
1644
- return "latest";
1645
- }
1646
- /**
1647
- * Read the OpenClaw version bundled at /app/ inside a Docker image.
1648
- */
1649
- function readBundledOpenclawVersion(invocation, image) {
1650
- try {
1651
- const out = execFileSync(invocation.cmd, [
1652
- ...invocation.argsPrefix,
1653
- "run",
1654
- "--rm",
1655
- "--entrypoint",
1656
- "node",
1657
- image,
1658
- "-p",
1659
- "require('/app/node_modules/openclaw/package.json').version",
1660
- ], { timeout: 20000, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).trim();
1661
- if (/^\d+\.\d+\.\d+/.test(out))
1662
- return out;
1663
- }
1664
- catch {
1665
- /* docker unavailable, image missing, or path not present */
1666
- }
1667
- return "";
1668
- }
1669
- /**
1670
- * Add a pinned version alias for an image, then drop the mutable :latest /
1671
- * :slim tag. See original setup-manager commentary for details.
1672
- */
1673
- function capturePinnedImageTag(invocation, targetTag, explicitVersion) {
1674
- if (PINNED_IMAGE_TAG_RE.test(targetTag))
1675
- return targetTag;
1676
- let version = explicitVersion && /^\d+\.\d+\.\d+/.test(explicitVersion) ? explicitVersion : "";
1677
- if (!version) {
1678
- version = readBundledOpenclawVersion(invocation, targetTag);
1679
- }
1680
- if (!version || !/^\d+\.\d+\.\d+/.test(version))
1681
- return targetTag;
1682
- const colonIdx = targetTag.lastIndexOf(":");
1683
- const slashIdx = targetTag.lastIndexOf("/");
1684
- const hasTag = colonIdx > slashIdx;
1685
- const repo = hasTag ? targetTag.slice(0, colonIdx) : targetTag;
1686
- const pinnedTag = `${repo}:${version}`;
1687
- if (pinnedTag === targetTag)
1688
- return targetTag;
1689
- try {
1690
- execFileSync(invocation.cmd, [...invocation.argsPrefix, "tag", targetTag, pinnedTag], { timeout: 10000, stdio: "ignore" });
1691
- }
1692
- catch {
1693
- return targetTag;
1694
- }
1695
- if (/:(latest|slim)$/.test(targetTag)) {
1696
- try {
1697
- execFileSync(invocation.cmd, [...invocation.argsPrefix, "rmi", targetTag], { timeout: 10000, stdio: "ignore" });
1698
- }
1699
- catch {
1700
- /* best-effort cleanup */
1701
- }
1702
- }
1703
- return pinnedTag;
1704
- }
1705
- /**
1706
- * Try docker pull, fall back to local `Dockerfile.openclaw-slim` build. This
1707
- * is the primary image-prep path used by every setup flow. Called from the
1708
- * adapter's `buildRuntimeImage()` method.
1709
- */
1710
- async function pullOrBuildOpenclawImageWithTask(task, tag) {
1711
- const targetTag = tag || DEFAULT_OPENCLAW_DOCKER_IMAGE;
1712
- try {
1713
- const invocation = resolveDockerInvocation();
1714
- // Always attempt pull — when the image is already local and in sync
1715
- // with upstream, docker returns within seconds after a digest check.
1716
- // The "skip if image present" early exit was making "reinstall" feel
1717
- // like a no-op; explicit re-pull matches user intent better. On pull
1718
- // failure we still fall back to local build below.
1719
- emitTask(task, { type: "progress", message: `正在拉取镜像: ${targetTag} ...`, progress: 10 });
1720
- const pullResult = await spawnWithTask(task, invocation.cmd, [...invocation.argsPrefix, "pull", targetTag], { timeout: 600000 });
1721
- if (pullResult.ok) {
1722
- const pinned = capturePinnedImageTag(invocation, targetTag);
1723
- setOpenclawDockerImage(pinned);
1724
- emitTask(task, { type: "done", message: `镜像拉取成功: ${pinned}`, progress: 100 });
1725
- task.status = "done";
1726
- return { ok: true, message: `Docker image ${pinned} pulled`, taskId: task.id };
1727
- }
1728
- console.log(`[openclaw] docker pull failed for ${targetTag}, falling back to local build...`);
1729
- emitTask(task, {
1730
- type: "progress",
1731
- message: `拉取失败,正在本地构建镜像: ${targetTag} ...`,
1732
- progress: 20,
1733
- });
1734
- const projectRoot = join(dirname(fileURLToPath(import.meta.url)), "../../../..");
1735
- const dockerfilePath = join(projectRoot, "Dockerfile.openclaw-slim");
1736
- if (!existsSync(dockerfilePath)) {
1737
- emitTask(task, {
1738
- type: "error",
1739
- message: "Dockerfile.openclaw-slim not found, cannot fallback to local build",
1740
- });
1741
- task.status = "error";
1742
- return {
1743
- ok: false,
1744
- message: "Docker pull failed and Dockerfile.openclaw-slim not found",
1745
- taskId: task.id,
1746
- };
1747
- }
1748
- const openclawVersion = resolveOpenclawNpmVersion();
1749
- console.log(`[openclaw] building image with OPENCLAW_VERSION=${openclawVersion}`);
1750
- const buildResult = await spawnWithTask(task, invocation.cmd, [
1751
- ...invocation.argsPrefix,
1752
- "build",
1753
- "--network=host",
1754
- "--build-arg",
1755
- `OPENCLAW_VERSION=${openclawVersion}`,
1756
- "-f",
1757
- dockerfilePath,
1758
- "-t",
1759
- targetTag,
1760
- projectRoot,
1761
- ], { timeout: 1800000, progressParser: dockerBuildProgressParser });
1762
- if (!buildResult.ok) {
1763
- try {
1764
- execFileSync(invocation.cmd, [...invocation.argsPrefix, "image", "prune", "-f"], { timeout: 15000, stdio: "ignore" });
1765
- }
1766
- catch {
1767
- /* best-effort */
1768
- }
1769
- emitTask(task, { type: "error", message: "Docker 镜像构建失败" });
1770
- task.status = "error";
1771
- return {
1772
- ok: false,
1773
- message: "Docker image build failed",
1774
- error: buildResult.output,
1775
- taskId: task.id,
1776
- };
1777
- }
1778
- const pinned = capturePinnedImageTag(invocation, targetTag, openclawVersion);
1779
- setOpenclawDockerImage(pinned);
1780
- emitTask(task, {
1781
- type: "done",
1782
- message: `OpenClaw 镜像就绪 (本地构建): ${pinned}`,
1783
- progress: 100,
1784
- });
1785
- task.status = "done";
1786
- return { ok: true, message: `Docker image ${pinned} built locally`, taskId: task.id };
1787
- }
1788
- catch (e) {
1789
- emitTask(task, { type: "error", message: `镜像获取失败: ${e.message}` });
1790
- task.status = "error";
1791
- return {
1792
- ok: false,
1793
- message: "Docker image pull/build failed",
1794
- error: e.message,
1795
- taskId: task.id,
1796
- };
1797
- }
1798
- }
1799
- // ── OpenClawAdapter class ─────────────────────────────────────────────
1800
- class OpenClawAdapter {
1801
- agentType = "openclaw";
1802
- displayName = "OpenClaw";
1803
- defaultCapabilities = DEFAULT_CAPABILITIES;
1804
- defaultGatewayPort = OPENCLAW_DEFAULT_GATEWAY_PORT;
1805
- manifest = {
1806
- agentType: "openclaw",
1807
- displayName: "OpenClaw",
1808
- description: "默认 runtime,支持克隆、飞书 / 企业微信插件",
1809
- defaultCapabilities: DEFAULT_CAPABILITIES,
1810
- requiresNomadDocker: false,
1811
- diskSpaceMB: 2048,
1812
- };
1813
- hooks = {
1814
- /**
1815
- * Full OpenClaw pre-start prelude — used to live inline in
1816
- * `nomad-manager.startInstance()` as an `if (!hermes) { ... }` branch
1817
- * (~80 lines). Framework code now calls this hook uniformly for every
1818
- * kind; Hermes provides a no-op and OpenClaw owns the full sequence:
1819
- *
1820
- * 1. Stop any legacy process-manager subprocess
1821
- * 2. Ensure `openclaw.json` exists + fix state-dir permissions
1822
- * 3. Docker-bridge: patch gateway.bind + jsproxy baseUrl
1823
- * 4. Seed `$HOME/.npm-global` for in-gateway "Update now"
1824
- * 5. Validate + image-inspect the Docker image; background-pull on miss
1825
- * 6. Write JSPROXY_API_KEY into Nomad Variables
1826
- *
1827
- * Throws on fatal errors. Framework catches and returns the structured
1828
- * result; a `taskId` property on the thrown error signals an async
1829
- * image pull in progress.
1830
- */
1831
- onBeforeStart: async ({ instanceId }) => {
1832
- // 1. Stop any legacy subprocess
1833
- try {
1834
- const { getLegacyStatus, stopInstance: stopLegacyInstance } = await import("../../process-manager.js");
1835
- const legacyStatus = await getLegacyStatus(instanceId);
1836
- if (legacyStatus.status === "running") {
1837
- console.log(`[openclaw] Stopping legacy process for ${instanceId} (pid=${legacyStatus.pid}) before Nomad start`);
1838
- await stopLegacyInstance(instanceId);
1839
- await new Promise((r) => setTimeout(r, 2000));
1840
- }
1841
- }
1842
- catch {
1843
- /* process-manager may be absent; harmless */
1844
- }
1845
- // 2. Config path existence check + permissions — use local resolvers
1846
- // instead of lazy importing back into instance-manager.
1847
- let configPath;
1848
- try {
1849
- configPath = openclawAdapter.resolveConfigPath(instanceId);
1850
- }
1851
- catch {
1852
- return; // bail gracefully for non-OpenClaw instances
1853
- }
1854
- if (!existsSync(configPath)) {
1855
- throw new Error("Config file not found");
1856
- }
1857
- if (getNomadDriver() === "docker") {
1858
- const stateDir = dirname(configPath);
1859
- ensureDirContainer(stateDir);
1860
- try {
1861
- for (const entry of readdirSync(stateDir, { withFileTypes: true })) {
1862
- if (entry.isDirectory()) {
1863
- const sub = join(stateDir, entry.name);
1864
- ensureDirContainer(sub);
1865
- try {
1866
- for (const child of readdirSync(sub, { withFileTypes: true })) {
1867
- if (child.isDirectory())
1868
- ensureDirContainer(join(sub, child.name));
1869
- }
1870
- }
1871
- catch {
1872
- /* ignore */
1873
- }
1874
- }
1875
- }
1876
- }
1877
- catch {
1878
- /* ignore */
1879
- }
1880
- if (existsSync(configPath))
1881
- chmodSync(configPath, 0o644);
1882
- // 3. Docker bridge patches
1883
- patchDockerBridgeGatewayBind(configPath);
1884
- patchJsproxyBaseUrl(configPath);
1885
- patchPrivateNetworkAllowFlag(configPath);
1886
- }
1887
- // Driver-agnostic: enable the OpenAI-compatible endpoints on every
1888
- // start so the `llm-agent` capability advertised by openclaw-*.yaml
1889
- // works for both fresh installs and instances created before this
1890
- // patcher shipped. Idempotent — bails out fast if already enabled.
1891
- patchOpenAIEndpointsEnabled(configPath);
1892
- // 4. npm update-seed — use local resolver
1893
- try {
1894
- const home = openclawAdapter.resolveAgentHome(instanceId);
1895
- if (home)
1896
- ensureOpenclawUpdateSeed(home, instanceId);
1897
- }
1898
- catch {
1899
- /* best effort */
1900
- }
1901
- // 4a. Patch session fence bug in OpenClaw >= 5.19
1902
- try {
1903
- const home = openclawAdapter.resolveAgentHome(instanceId);
1904
- if (home) {
1905
- patchSessionFenceBug(home, instanceId);
1906
- // Also write the container-side patch script so that even if
1907
- // the host-side patch couldn't apply (e.g. symlink to container
1908
- // path), the container will self-patch on startup.
1909
- if (getNomadDriver() === "docker") {
1910
- writeContainerPatchScript(home);
1911
- }
1912
- }
1913
- }
1914
- catch {
1915
- /* best effort — patch failure must not prevent start */
1916
- }
1917
- // 4b. Build the workspace symlink layout from this instance's
1918
- // fileMounts (M1 W2). For docker mode, the corresponding
1919
- // volume bindings are added in buildNomadTask below; for
1920
- // raw_exec / process modes, the symlinks are sufficient
1921
- // (no container layer between agent and host fs).
1922
- try {
1923
- const home = openclawAdapter.resolveAgentHome(instanceId);
1924
- const im = await lazyIm();
1925
- const runtime = im.getInstanceRuntime(instanceId);
1926
- const mounts = readFileMounts(runtime);
1927
- if (home) {
1928
- const { rebuildWorkspace } = await import("../../workspace-builder.js");
1929
- rebuildWorkspace({
1930
- openclawHome: home,
1931
- filesRoot: FILES_ROOT,
1932
- mounts,
1933
- instanceId,
1934
- });
1935
- }
1936
- }
1937
- catch (e) {
1938
- // Surface migration-required clearly; otherwise fall back to a
1939
- // warning so a misconfigured mount cannot prevent instance start.
1940
- if (e?.reason === "needs-migration") {
1941
- throw new Error(`instance ${instanceId} workspace contains pre-W2 user data; run legacy migration first (${e.message})`);
1942
- }
1943
- console.warn(`[openclaw] workspace rebuild skipped: ${e?.message ?? e}`);
1944
- }
1945
- // 4b-bis. Patch TOOLS.md with the drive-shim hint so the agent
1946
- // understands user files are local (host==container bind) and
1947
- // knows the resolve→send chain for IM channels. Without this,
1948
- // the LLM defaults to "drive = remote cloud service" and
1949
- // refuses to send NAS files via Feishu/WeChat. Runs after the
1950
- // workspace rebuild because that step creates the workspace
1951
- // tree if missing.
1952
- try {
1953
- const home = openclawAdapter.resolveAgentHome(instanceId);
1954
- if (home) {
1955
- patchToolsMdDriveHint(join(home, ".openclaw", "workspace"), FILES_ROOT, join(home, ".npm-global", "bin", "jishushell-mcporter"), instanceId);
1956
- }
1957
- }
1958
- catch (e) {
1959
- console.warn(`[openclaw] TOOLS.md drive hint skipped: ${e?.message ?? e}`);
1960
- }
1961
- // 4b-ter. Rotate stale session jsonl(s) when the runtime contract
1962
- // bumps. This is the auto-recovery path for panel upgrades
1963
- // that fix runtime bugs the agent has already "concluded
1964
- // around" inside an existing session — without rotation the
1965
- // LLM keeps citing past failures and refusing to retry even
1966
- // after the underlying bug is fixed. Idempotent: after the
1967
- // first onBeforeStart post-upgrade writes the new marker,
1968
- // subsequent starts are no-ops.
1969
- try {
1970
- const home = openclawAdapter.resolveAgentHome(instanceId);
1971
- if (home)
1972
- rotateSessionsIfContractChanged(instanceId, home);
1973
- }
1974
- catch (e) {
1975
- console.warn(`[openclaw] session rotation skipped: ${e?.message ?? e}`);
1976
- }
1977
- // 4c. Install the drive MCP shim so the agent can call panel
1978
- // file/organize APIs from chat (M1 W1.6). Idempotent — we
1979
- // overwrite the shim file every start to pick up fixes, and
1980
- // mergeMcporterServers marks the entry with __source so user-
1981
- // managed mcporter entries are preserved untouched.
1982
- try {
1983
- const home = openclawAdapter.resolveAgentHome(instanceId);
1984
- if (home) {
1985
- const { substituteDriveShimPlaceholders } = await import("../mcp-shims/drive-shim.js");
1986
- const { mergeMcporterServers } = await import("./openclaw-mcporter.js");
1987
- const { getInternalMcpToken } = await import("../../../config.js");
1988
- // Pick the core URL based on how THIS instance will actually run.
1989
- // For a containerized instance (raw_exec/docker via Nomad with a
1990
- // docker image), `host.docker.internal:<corePort>` resolves through
1991
- // the bridge gateway. For a host-process / binary spec under Nomad
1992
- // raw_exec, the task gets its own network namespace where
1993
- // 127.0.0.1 only reaches the task itself — must use the host's
1994
- // LAN IPv4 so the shim's fetch crosses back into the host netns.
1995
- // Detected via the instance's resolved runtime: container tasks
1996
- // carry `runtime.image`, binary tasks carry only `runtime.command`.
1997
- const corePort = getCorePort();
1998
- let driveCoreHost = "host.docker.internal";
1999
- try {
2000
- const im2 = await lazyIm();
2001
- const rt = im2.getInstanceRuntime(instanceId);
2002
- if (!rt?.image) {
2003
- driveCoreHost = getCoreLanHost();
2004
- }
2005
- }
2006
- catch (e) {
2007
- console.warn(`[openclaw] drive shim runtime detection failed for ${instanceId}; using container-reachable core host:`, e);
2008
- }
2009
- const driveCoreUrl = `http://${driveCoreHost}:${corePort}`;
2010
- const shimDir = join(home, "__mcp_shims__", "drive");
2011
- ensureDirContainer(shimDir);
2012
- const shimPath = join(shimDir, "drive-shim.mjs");
2013
- // Bake coreUrl/token/instanceId into the shim source so it works
2014
- // even when OpenClaw scrubs env on MCP subprocess spawn (verified
2015
- // 2026-05-11 on pi2: env scrub made the shim default to the
2016
- // unreachable host.docker.internal and surface as "fetch failed").
2017
- const internalToken = getInternalMcpToken();
2018
- const shimSource = substituteDriveShimPlaceholders({
2019
- coreUrl: driveCoreUrl,
2020
- token: internalToken,
2021
- instanceId,
2022
- });
2023
- writeFileSync(shimPath, shimSource, { mode: 0o755 });
2024
- mergeMcporterServers(instanceId, {
2025
- drive: {
2026
- command: "node",
2027
- args: [shimPath],
2028
- env: {
2029
- // Env still set as a belt-and-suspenders. With baked-in
2030
- // values in the shim source itself, these become a fallback
2031
- // for dev/manual testing — production never depends on them.
2032
- JISHUSHELL_INTERNAL_TOKEN: internalToken,
2033
- JISHUSHELL_INSTANCE_ID: instanceId,
2034
- JISHUSHELL_CORE_URL: driveCoreUrl,
2035
- JISHUSHELL_CORE_PORT: String(corePort),
2036
- },
2037
- __source: {
2038
- kind: "connection",
2039
- slot: "drive",
2040
- consumerInstanceId: instanceId,
2041
- },
2042
- },
2043
- });
2044
- }
2045
- }
2046
- catch (e) {
2047
- console.warn(`[openclaw] drive shim install skipped: ${e?.message ?? e}`);
2048
- }
2049
- // 4c-quater. Auto-wire knowledge MCP shim. The Connections-tab
2050
- // knowledge slot (declared as `requires: knowledge` on the
2051
- // OpenClaw spec, persisted under `instance.connections.KNOWLEDGE_BASE_URL`)
2052
- // is honored here, so unbinding in the UI actually takes effect.
2053
- // Provider resolution (matching connection-resolver.ts):
2054
- //
2055
- // - `null` → user explicitly disconnected →
2056
- // DO NOT inject (and strip any prior shim).
2057
- // - kind=single + providerId → use that provider's shim.
2058
- // - kind=many → first match wins (jishukb > anythingllm
2059
- // to be explicit and stable across rebinds).
2060
- // - undefined → no opinion → fall back to the
2061
- // historical "auto-on when AnythingLLM
2062
- // credentials.json exists" UX (legacy default).
2063
- //
2064
- // Mutual cleanup: rebinding from anythingllm → jishukb (or
2065
- // vice versa, or → null) wipes the OTHER provider's shim dir
2066
- // in EVERY branch. Leaving a 0o600 secret.json + bearer-
2067
- // prefilled shim source on disk after unbind would be a
2068
- // lingering security smell.
2069
- //
2070
- // Secrets handling (defense-in-depth, anythingllm only):
2071
- // - shim source (mode 0o644) carries baseUrl + workspace only;
2072
- // the API key lives in a sibling `secret.json` (0o600).
2073
- // - mcporter.json (0o644) env carries only non-secret hints
2074
- // for hand-running. Production shim reads the secret file.
2075
- // jishu-kb v1 ships without auth, so no secret.json.
2076
- try {
2077
- const home = openclawAdapter.resolveAgentHome(instanceId);
2078
- if (home) {
2079
- const instMeta = getInstance(instanceId);
2080
- const provider = resolveKbProvider(instMeta?.connections?.KNOWLEDGE_BASE_URL);
2081
- const mcporterCommand = join(home, ".npm-global", "bin", "jishushell-mcporter");
2082
- const wsDir = join(home, ".openclaw", "workspace");
2083
- const anyllmShimDir = join(home, "__mcp_shims__", "anythingllm");
2084
- const anyllmShimPath = join(anyllmShimDir, "anythingllm-shim.js");
2085
- const anyllmSecretPath = join(anyllmShimDir, "secret.json");
2086
- const jishukbShimDir = join(home, "__mcp_shims__", "jishukb");
2087
- const jishukbShimPath = join(jishukbShimDir, "jishukb-shim.js");
2088
- const { mergeMcporterServers, removeMcporterServers } = await import("./openclaw-mcporter.js");
2089
- if (provider === "jishukb") {
2090
- // Wipe the OTHER provider's residue first (including its
2091
- // 0o600 secret.json). Security smell to leave it on disk.
2092
- wipeKbShimDir(home, "anythingllm");
2093
- const credPath = join(JISHUSHELL_HOME, "apps", "jishu-kb-container", "credentials.json");
2094
- let creds = null;
2095
- if (existsSync(credPath)) {
2096
- try {
2097
- creds = JSON.parse(readFileSync(credPath, "utf-8"));
2098
- }
2099
- catch (e) {
2100
- console.warn(`[openclaw] kb: invalid jishu-kb credentials.json: ${e?.message ?? e}`);
2101
- }
2102
- }
2103
- if (creds?.baseUrl) {
2104
- const { substituteJishukbShimPlaceholders } = await import("../mcp-shims/jishukb-shim.js");
2105
- ensureDirContainer(jishukbShimDir);
2106
- const shimSource = substituteJishukbShimPlaceholders({
2107
- baseUrl: creds.baseUrl,
2108
- kbId: creds.kbId,
2109
- allowedUploadRoots: listJishukbUploadRoots(instMeta?.runtime ?? {}, home),
2110
- });
2111
- writeFileSync(jishukbShimPath, shimSource, { mode: 0o644 });
2112
- mergeMcporterServers(instanceId, {
2113
- kb: {
2114
- command: "node",
2115
- args: [jishukbShimPath],
2116
- env: {
2117
- // Belt-and-suspenders fallback for hand-running.
2118
- // Baked values in the shim source are the production
2119
- // source of truth. No secret in v1.
2120
- JISHUKB_BASE_URL: creds.baseUrl,
2121
- JISHUKB_KB_ID: creds.kbId || "",
2122
- },
2123
- __source: {
2124
- kind: "connection",
2125
- slot: "knowledge",
2126
- consumerInstanceId: instanceId,
2127
- },
2128
- },
2129
- });
2130
- patchToolsMdKbHint(wsDir, "install", "jishukb", mcporterCommand, instanceId, join(home, ".openclaw", "media", "inbound"));
2131
- }
2132
- else {
2133
- // jishu-kb bound but baseUrl not yet ready / credentials missing.
2134
- // Remove any prior kb registration so the agent doesn't
2135
- // call a stale shim, and wipe our own shim dir for hygiene.
2136
- console.warn(`[openclaw] kb: jishu-kb bound but baseUrl missing at ${credPath} — skipping shim install`);
2137
- removeMcporterServers(instanceId, {
2138
- source: { kind: "connection", slot: "knowledge", consumerInstanceId: instanceId },
2139
- });
2140
- patchToolsMdKbHint(wsDir, "remove");
2141
- wipeKbShimDir(home, "jishukb");
2142
- }
2143
- }
2144
- else if (provider === "anythingllm") {
2145
- // Wipe the OTHER provider's residue first.
2146
- wipeKbShimDir(home, "jishukb");
2147
- const credPath = join(JISHUSHELL_HOME, "apps", "anythingllm-container", "credentials.json");
2148
- let kbCreds = null;
2149
- if (existsSync(credPath)) {
2150
- try {
2151
- kbCreds = JSON.parse(readFileSync(credPath, "utf-8"));
2152
- }
2153
- catch (e) {
2154
- console.warn(`[openclaw] kb: invalid credentials.json: ${e?.message ?? e}`);
2155
- }
2156
- }
2157
- if (kbCreds?.apiKey && kbCreds?.baseUrl) {
2158
- const { substituteAnythingllmShimPlaceholders } = await import("../mcp-shims/anythingllm-shim.js");
2159
- ensureDirContainer(anyllmShimDir);
2160
- const shimSource = substituteAnythingllmShimPlaceholders({
2161
- baseUrl: kbCreds.baseUrl,
2162
- workspace: kbCreds.workspace || "default",
2163
- });
2164
- writeFileSync(anyllmShimPath, shimSource, { mode: 0o644 });
2165
- // chmod after write to dodge umask; secret.json must be 0o600.
2166
- writeFileSync(anyllmSecretPath, JSON.stringify({ apiKey: kbCreds.apiKey }), { mode: 0o600 });
2167
- try {
2168
- chmodSync(anyllmSecretPath, 0o600);
2169
- }
2170
- catch { /* best effort */ }
2171
- mergeMcporterServers(instanceId, {
2172
- kb: {
2173
- command: "node",
2174
- args: [anyllmShimPath],
2175
- env: {
2176
- // Belt-and-suspenders fallback for hand-running. Baked
2177
- // values in the shim source are the production source
2178
- // of truth for baseUrl + workspace; the API key is
2179
- // intentionally NOT placed here — it lives in
2180
- // `secret.json` (0o600) next to the shim so this 0o644
2181
- // file stays free of secrets.
2182
- ANYTHINGLLM_BASE_URL: kbCreds.baseUrl,
2183
- ANYTHINGLLM_WORKSPACE: kbCreds.workspace || "default",
2184
- },
2185
- __source: {
2186
- kind: "connection",
2187
- slot: "knowledge",
2188
- consumerInstanceId: instanceId,
2189
- },
2190
- },
2191
- });
2192
- patchToolsMdKbHint(wsDir, "install", "anythingllm", mcporterCommand);
2193
- }
2194
- else {
2195
- // AnythingLLM bound but creds missing → strip and clean.
2196
- removeMcporterServers(instanceId, {
2197
- source: { kind: "connection", slot: "knowledge", consumerInstanceId: instanceId },
2198
- });
2199
- patchToolsMdKbHint(wsDir, "remove");
2200
- wipeKbShimDir(home, "anythingllm");
2201
- }
2202
- }
2203
- else {
2204
- // provider === null → user explicitly unbound, or bound to
2205
- // an unknown/unsupported provider. Strip kb server and wipe
2206
- // both shim dirs.
2207
- removeMcporterServers(instanceId, {
2208
- source: { kind: "connection", slot: "knowledge", consumerInstanceId: instanceId },
2209
- });
2210
- patchToolsMdKbHint(wsDir, "remove");
2211
- wipeKbShimDir(home, "anythingllm");
2212
- wipeKbShimDir(home, "jishukb");
2213
- }
2214
- }
2215
- }
2216
- catch (e) {
2217
- console.warn(`[openclaw] kb shim wiring skipped: ${e?.message ?? e}`);
2218
- }
2219
- // 4c-bis. Self-heal MCPORTER_CONFIG env on existing instances. Without
2220
- // this, mcporter can't find its config when invoked from the
2221
- // gateway's CWD (openclaw-home/) or from the workspace symlink
2222
- // (which points at user files, also no config/), so every drive
2223
- // tool call fails with "Unknown MCP server 'drive'" and the agent
2224
- // degrades into reporting a generic "network error". New instances
2225
- // get this env via the binary/container runtime template; this
2226
- // block back-fills it for instances created before that template
2227
- // update so users don't have to recreate them.
2228
- try {
2229
- const im2 = await lazyIm();
2230
- const rt = im2.getInstanceRuntime(instanceId);
2231
- const home = openclawAdapter.resolveAgentHome(instanceId);
2232
- if (home && rt && (!rt.env || !rt.env.MCPORTER_CONFIG)) {
2233
- const desired = `${home}/.openclaw/workspace/config/mcporter.json`;
2234
- const nextEnv = { ...(rt.env || {}), MCPORTER_CONFIG: desired };
2235
- im2.updateInstanceMeta(instanceId, { runtime: { ...rt, env: nextEnv } });
2236
- console.log(`[openclaw] self-healed MCPORTER_CONFIG env for ${instanceId}`);
2237
- }
2238
- }
2239
- catch (e) {
2240
- console.warn(`[openclaw] MCPORTER_CONFIG self-heal failed: ${e?.message ?? e}`);
2241
- }
2242
- // 4d. Install a standalone mcporter-compatible FALLBACK wrapper at
2243
- // `$OPENCLAW_HOME/.npm-global/bin/jishushell-mcporter`. Fresh
2244
- // instances often do not carry an actual mcporter npm install, yet
2245
- // TOOLS.md asks the model to shell out for drive/kb access. Keep
2246
- // the fallback on a distinct path so we do NOT clobber a real
2247
- // mcporter install that may support transports/features beyond this
2248
- // wrapper's narrow built-in scope.
2249
- try {
2250
- const home = openclawAdapter.resolveAgentHome(instanceId);
2251
- if (home) {
2252
- const mcporterBin = join(home, ".npm-global", "bin", "jishushell-mcporter");
2253
- ensureDirContainer(join(home, ".npm-global", "bin"));
2254
- writeFileSync(mcporterBin, renderStandaloneMcporterSource(), { mode: 0o755 });
2255
- try {
2256
- chmodSync(mcporterBin, 0o755);
2257
- }
2258
- catch { /* best effort */ }
2259
- console.log(`[openclaw] installed standalone mcporter fallback at ${mcporterBin}`);
2260
- }
2261
- }
2262
- catch (e) {
2263
- console.warn(`[openclaw] mcporter self-heal failed: ${e?.message ?? e}`);
2264
- }
2265
- // 5. Docker image validation + background pull fallback
2266
- if (getNomadDriver() === "docker") {
2267
- const image = getOpenclawDockerImage();
2268
- if (!DOCKER_IMAGE_RE.test(image) || image.length > MAX_DOCKER_IMAGE_NAME_LEN) {
2269
- throw new Error(`Invalid Docker image name: "${image}"`);
2270
- }
2271
- const imageCheck = inspectDockerImage(image, { timeout: 10000 });
2272
- if (!imageCheck.ok) {
2273
- const inspectError = toDockerInspectUserError(image, imageCheck);
2274
- if (imageCheck.reason !== "not_found") {
2275
- const err = new Error(inspectError.message);
2276
- err.code = inspectError.code;
2277
- err.statusCode = inspectError.statusCode;
2278
- throw err;
2279
- }
2280
- console.log(`[openclaw] Docker image ${image} not found, starting background pull`);
2281
- try {
2282
- const result = openclawAdapter.startBuildRuntimeImage({ tag: image });
2283
- const err = new Error(`${inspectError.message} Pull started in background.`);
2284
- err.building = true;
2285
- err.taskId = result.taskId;
2286
- err.code = inspectError.code;
2287
- err.statusCode = 202;
2288
- throw err;
2289
- }
2290
- catch (e) {
2291
- if (e?.building)
2292
- throw e;
2293
- throw new Error(`Docker image ${image} not available: ${e?.message ?? e}`);
2294
- }
2295
- }
2296
- }
2297
- // 6. Write instance secrets to Nomad Variables
2298
- try {
2299
- const nomad = await import("../../nomad-manager.js");
2300
- if (typeof nomad.writeInstanceVariables === "function") {
2301
- await nomad.writeInstanceVariables(instanceId);
2302
- }
2303
- }
2304
- catch (e) {
2305
- throw new Error(`Failed to store instance secrets in Nomad Variables: ${e?.message ?? e}`);
2306
- }
2307
- },
2308
- /**
2309
- * OpenClaw auto-installs IM channel plugins (feishu, weixin, etc.) when
2310
- * they're enabled in `openclaw.json`. That logic currently lives in
2311
- * `instance-manager.saveConfig()`; wiring it through this hook is a
2312
- * no-op during MVP because saveConfig still runs inline. The hook
2313
- * exists so the physical-migration follow-up PR can move the code into
2314
- * this file without touching framework code.
2315
- */
2316
- onConfigSaved: async (_args) => {
2317
- /* reserved — channel plugin install hook, filled by follow-up PR */
2318
- },
2319
- /**
2320
- * Surface an orphan-directory warning when the legacy `openclaw_home`
2321
- * field points outside the instance dir. The framework's deleteInstance
2322
- * only rm's the instance dir itself, so custom-home layouts leave a
2323
- * tree that the operator must clean up manually.
2324
- */
2325
- onDelete: async ({ instanceId, meta }) => {
2326
- const home = typeof meta?.openclaw_home === "string" ? meta.openclaw_home : null;
2327
- if (!home)
2328
- return;
2329
- const instDir = framework_instanceDir(instanceId);
2330
- if (home.startsWith(instDir))
2331
- return; // inside the instance dir — rm already caught it
2332
- if (!existsSync(home))
2333
- return;
2334
- return {
2335
- warnings: [
2336
- `Custom openclaw_home '${home}' was preserved. Delete manually if no longer needed.`,
2337
- ],
2338
- };
2339
- },
2340
- /**
2341
- * Rewrite `openclaw.json` x-jishushell.proxy.upstream when the panel
2342
- * default provider changes. Delegates to instance-manager's existing
2343
- * helper so the transition stays stepwise.
2344
- */
2345
- onUpstreamProviderChange: async ({ instanceId, upstream }) => {
2346
- try {
2347
- const im = await lazyIm();
2348
- if (typeof im.pushUpstreamToInstance === "function") {
2349
- await im.pushUpstreamToInstance(instanceId, upstream);
2350
- }
2351
- }
2352
- catch (e) {
2353
- console.warn(`[openclaw] onUpstreamProviderChange failed for ${instanceId}: ${e.message}`);
2354
- }
2355
- },
2356
- };
2357
- /**
2358
- * Full OpenClaw instance bootstrap, physically migrated from the legacy
2359
- * `instance-manager.createInstance()` (~270 lines). Framework code now
2360
- * calls this uniformly via `getAdapter(agentType).createInstance(args)` —
2361
- * instance-manager no longer owns any OpenClaw business logic.
2362
- *
2363
- * Responsibilities:
2364
- * 1. openclaw_home path validation (traversal + symlink safety)
2365
- * 2. Gateway port allocation + runtime spec generation
2366
- * 3. clone_from handling (extensions/workspace/memory/sessions copy)
2367
- * 4. starter config seeding + default-provider API key injection
2368
- * 5. AppSpec overlays (config_defaults / skills)
2369
- * 6. Proxy bootstrap token generation via LLM proxy
2370
- * 7. chown to service user when running as root
2371
- */
2372
- async createInstance(args) {
2373
- const { instanceId, name, description = "", cloneFrom, agentHome: openclawHomeArg, appSpec, cloneOptions, } = args;
2374
- // Guard: prevent creating an OpenClaw instance when the runtime isn't
2375
- // installed. Without this, the instance.json gets written but the first
2376
- // `service/start` fails with an opaque `npm package not found` or
2377
- // `docker image missing` error. The Setup wizard treats "any runtime
2378
- // ready" as overall ready, so the Hermes-only case reaches here.
2379
- // getInstallStatus() is best-effort: if config exports are unavailable
2380
- // (e.g. partially mocked in test environments) the check is skipped so
2381
- // tests that do not mock the install state continue to work unchanged.
2382
- // The e2e-real suite spawns a real CLI on hosts that intentionally do
2383
- // not have OpenClaw installed; NODE_ENV=test (set by the e2e helper)
2384
- // is the explicit opt-out so the gate doesn't break instance-lifecycle
2385
- // tests.
2386
- try {
2387
- const hasAppManagedRuntime = Boolean(appSpec?.tasks?.some((task) => (task.role ?? "service") === "service" && (task.command || task.image)));
2388
- if (!hasAppManagedRuntime && process.env.NODE_ENV !== "test") {
2389
- const installStatus = this.getInstallStatus();
2390
- if (!installStatus.installed) {
2391
- throw new Error("OpenClaw runtime is not installed. Install it from the Apps page " +
2392
- "or run `jishushell install openclaw`, then retry.");
2393
- }
2394
- }
2395
- }
2396
- catch (err) {
2397
- // Re-throw only our own install-gate error; absorb config-unavailable
2398
- // errors that arise in partially mocked test environments.
2399
- if (err?.message?.startsWith("OpenClaw runtime is not installed"))
2400
- throw err;
2401
- }
2402
- const d = framework_instanceDir(instanceId);
2403
- const metaPath = instanceMetaPath(instanceId);
2404
- if (existsSync(metaPath))
2405
- throw new Error(`Instance '${instanceId}' already exists`);
2406
- if (existsSync(d) && !isPrecreatedManagedAppDir(d)) {
2407
- throw new Error(`Instance '${instanceId}' already exists`);
2408
- }
2409
- const home = openclawHomeArg
2410
- ? normalizePath(openclawHomeArg)
2411
- : defaultOpenclawHome(instanceId);
2412
- // Restrict openclaw_home to be under JISHUSHELL_HOME or /home to prevent
2413
- // path traversal. Use realpathSync after mkdir to resolve symlinks.
2414
- if (openclawHomeArg) {
2415
- const resolved = pathResolve(home);
2416
- if (!resolved.startsWith(JISHUSHELL_HOME) && !resolved.startsWith("/home/")) {
2417
- throw new Error(`openclaw_home must be under ${JISHUSHELL_HOME} or /home/`);
2418
- }
2419
- const parentDir = dirname(resolved);
2420
- if (existsSync(parentDir)) {
2421
- const realParent = realpathSync(parentDir);
2422
- if (!realParent.startsWith(JISHUSHELL_HOME) && !realParent.startsWith("/home/")) {
2423
- throw new Error(`openclaw_home parent resolves outside allowed paths (symlink detected)`);
2424
- }
2425
- }
2426
- const shared = listInstances().filter((inst) => normalizePath(inst.openclaw_home || defaultOpenclawHome(inst.id)) ===
2427
- normalizePath(home));
2428
- if (shared.length) {
2429
- throw new Error(`OpenClaw home '${home}' is already used by instance(s): ${shared
2430
- .map((i) => i.id)
2431
- .join(", ")}`);
2432
- }
2433
- }
2434
- // Orphaned openclaw_home (e.g. instance.json deleted but data remains).
2435
- if (existsSync(home)) {
2436
- try {
2437
- const entries = readdirSync(home);
2438
- if (entries.length > 0) {
2439
- throw new Error(`OpenClaw home directory '${home}' already exists and is not empty. ` +
2440
- `Remove it manually or choose a different path.`);
2441
- }
2442
- }
2443
- catch (e) {
2444
- if (e.message.includes("not empty"))
2445
- throw e;
2446
- }
2447
- }
2448
- ensureDirContainer(d);
2449
- try {
2450
- const parentGid = statSync(dirname(d)).gid;
2451
- chownSync(d, -1, parentGid);
2452
- }
2453
- catch {
2454
- /* non-root without CAP_CHOWN */
2455
- }
2456
- ensureDirContainer(home);
2457
- ensureDirContainer(join(home, OPENCLAW_STATE_DIRNAME));
2458
- const portAlloc = await allocateGatewayPort(instanceId, OPENCLAW_DEFAULT_GATEWAY_PORT);
2459
- const baseRuntime = buildDefaultRuntime(instanceId, portAlloc.port, home);
2460
- let runtime = baseRuntime;
2461
- if (appSpec) {
2462
- const serviceTask = appSpec.tasks.find((t) => t.role === "service");
2463
- if (serviceTask) {
2464
- const compiled = compileTaskRuntime(serviceTask, instanceId);
2465
- runtime = { ...baseRuntime, ...compiled };
2466
- }
2467
- }
2468
- // W2: every new instance gets a default rw mount on its own
2469
- // agent-data/{id} subtree (alias _out). Cloned instances inherit
2470
- // their source's mounts but have agent-data path rewritten to the
2471
- // new instance id; we keep this simple here and just plant the
2472
- // default — clone-from semantics for additional mounts can be
2473
- // tightened in PR-7+ when migration arrives.
2474
- if (!runtime.fileMounts && !runtime.file_mounts) {
2475
- runtime.fileMounts = defaultMountsForNewInstance(instanceId);
2476
- }
2477
- try {
2478
- ensureMountTargets(FILES_ROOT, readFileMounts(runtime));
2479
- }
2480
- catch (e) {
2481
- console.warn(`[openclaw] could not pre-create mount targets for ${instanceId}: ${e?.message ?? e}`);
2482
- }
2483
- const allocatedPort = extractGatewayPort(runtime);
2484
- try {
2485
- const meta = {
2486
- id: instanceId,
2487
- name,
2488
- description,
2489
- agentType: "openclaw",
2490
- openclaw_home: home,
2491
- runtime,
2492
- created_at: new Date().toISOString(),
2493
- // Prefer appSpec.app_id (installed unique id set by routes/apps.ts:88-96)
2494
- // over appSpec.id (which materializeInstalledSpec preserves as the base id).
2495
- // Multi-instance / copied apps need the installed id so uninstall /
2496
- // capability rebuild / skills metadata find the right installed entry.
2497
- ...(appSpec ? { app_id: appSpec.app_id ?? appSpec.id } : {}),
2498
- };
2499
- safeWriteJson(instanceMetaPath(instanceId), meta);
2500
- const envFiles = (runtime.env_files || []).map((p) => normalizePath(p));
2501
- for (const ef of envFiles) {
2502
- if (!existsSync(ef))
2503
- writeConfigFile(ef, "");
2504
- }
2505
- // After writing env files, ensure the runtime user can read them
2506
- try {
2507
- const runtimeUser = runtime.user;
2508
- if (runtimeUser && runtimeUser !== userInfo().username) {
2509
- for (const ef of envFiles) {
2510
- execFileSync("chown", [runtimeUser, ef], { timeout: 5000 });
2511
- }
2512
- }
2513
- }
2514
- catch {
2515
- /* ignore - same user or no permission to chown */
2516
- }
2517
- const configPath = openclawConfigPath(instanceId, home);
2518
- ensureDirContainer(dirname(configPath));
2519
- if (cloneFrom && !existsSync(configPath)) {
2520
- const srcConfig = resolveExistingConfigPath(cloneFrom);
2521
- if (existsSync(srcConfig)) {
2522
- try {
2523
- const cloned = JSON.parse(readFileSync(srcConfig, "utf-8"));
2524
- // Remove proxy provider (will be regenerated with new token)
2525
- const providers = cloned?.models?.providers;
2526
- if (providers) {
2527
- for (const [pid, prov] of Object.entries(providers)) {
2528
- if (typeof prov?.baseUrl === "string" &&
2529
- prov.baseUrl.includes("/proxy/")) {
2530
- delete providers[pid];
2531
- }
2532
- }
2533
- }
2534
- // Remove proxy model reference from agent defaults
2535
- const defaultModel = cloned?.agents?.defaults?.model;
2536
- if (typeof defaultModel === "string" &&
2537
- (defaultModel.startsWith("jsproxy/") || defaultModel.startsWith("js-"))) {
2538
- delete cloned.agents.defaults.model;
2539
- }
2540
- // Strip IM channel configs + matching plugin entries
2541
- stripImBindings(cloned);
2542
- // Copy extensions, workspace, (optionally) memory + sessions
2543
- const subdirs = ["extensions", "workspace"];
2544
- if (cloneOptions?.include_memory !== false) {
2545
- const memDir = join(dirname(srcConfig), "memory");
2546
- if (existsSync(memDir))
2547
- subdirs.push("memory");
2548
- }
2549
- if (cloneOptions?.include_sessions) {
2550
- const sessDir = join(dirname(srcConfig), "agents");
2551
- if (existsSync(sessDir))
2552
- subdirs.push("agents");
2553
- }
2554
- for (const subdir of subdirs) {
2555
- const srcDir = join(dirname(srcConfig), subdir);
2556
- const dstDir = join(dirname(configPath), subdir);
2557
- if (existsSync(srcDir) && !existsSync(dstDir)) {
2558
- try {
2559
- cpSync(srcDir, dstDir, { recursive: true });
2560
- }
2561
- catch {
2562
- /* best effort */
2563
- }
2564
- }
2565
- }
2566
- writeConfigFile(configPath, JSON.stringify(cloned, null, 2));
2567
- // Copy x-jishushell upstream metadata from source instance.json
2568
- const srcMetaPath = join(framework_instanceDir(cloneFrom), "instance.json");
2569
- if (existsSync(srcMetaPath)) {
2570
- try {
2571
- const srcMeta = JSON.parse(readFileSync(srcMetaPath, "utf-8"));
2572
- const srcXj = srcMeta?.["x-jishushell"];
2573
- if (srcXj?.proxy?.upstream) {
2574
- const dstXj = { proxy: { upstream: srcXj.proxy.upstream } };
2575
- delete dstXj.proxy.upstream.apiKey;
2576
- const metaPath = instanceMetaPath(instanceId);
2577
- if (existsSync(metaPath)) {
2578
- const dstMeta = JSON.parse(readFileSync(metaPath, "utf-8"));
2579
- dstMeta["x-jishushell"] = dstXj;
2580
- writeConfigFile(metaPath, JSON.stringify(dstMeta, null, 2));
2581
- }
2582
- }
2583
- }
2584
- catch {
2585
- /* ignore metadata copy errors */
2586
- }
2587
- }
2588
- }
2589
- catch {
2590
- copyFileSync(srcConfig, configPath);
2591
- }
2592
- }
2593
- }
2594
- if (!existsSync(configPath)) {
2595
- writeConfigFile(configPath, JSON.stringify(starterConfig(), null, 2));
2596
- // Inject the configured default provider API key into both env files.
2597
- const dp = getDefaultLlmProvider();
2598
- if (dp?.apiKey && dp?.id && envFiles.length) {
2599
- const envKey = inferProviderApiKeyEnvName(dp.id);
2600
- updateEnvFile(envFiles[0], { [envKey]: decryptRuntimeProviderApiKey(dp.apiKey) });
2601
- const providerEnv = join(dirname(envFiles[0]), "provider.env");
2602
- updateEnvFile(providerEnv, { UPSTREAM_API_KEY: dp.apiKey });
2603
- }
2604
- }
2605
- // Merge AppSpec runtime overlays into openclaw.json (shallow, app wins).
2606
- // Prefers the plan §17 shape `runtime.defaults`; falls back to the
2607
- // legacy `openclaw.config_defaults` namespace for pre-§17 specs.
2608
- const runtimeOverlay = appSpec?.runtime ??
2609
- appSpec?.openclaw;
2610
- const overlayDefaults = runtimeOverlay?.defaults
2611
- ?? runtimeOverlay?.config_defaults;
2612
- if (overlayDefaults && existsSync(configPath)) {
2613
- try {
2614
- const existing = JSON.parse(readFileSync(configPath, "utf-8"));
2615
- const defaults = overlayDefaults;
2616
- for (const [key, value] of Object.entries(defaults)) {
2617
- if (typeof value === "object" &&
2618
- value !== null &&
2619
- !Array.isArray(value) &&
2620
- typeof existing[key] === "object" &&
2621
- existing[key] !== null) {
2622
- existing[key] = { ...existing[key], ...value };
2623
- }
2624
- else {
2625
- existing[key] = value;
2626
- }
2627
- }
2628
- writeConfigFile(configPath, JSON.stringify(existing, null, 2));
2629
- }
2630
- catch {
2631
- /* ignore merge errors */
2632
- }
2633
- }
2634
- // Record App-level skills for later installation. Prefers the new
2635
- // `runtime.skills` namespace; falls back to `openclaw.skills` for
2636
- // pre-§17 specs.
2637
- const overlaySkills = Array.isArray(runtimeOverlay?.skills)
2638
- ? runtimeOverlay.skills
2639
- : null;
2640
- if (overlaySkills) {
2641
- try {
2642
- const skillsDir = join(dirname(configPath), "skills");
2643
- ensureDirContainer(skillsDir);
2644
- const skillMeta = join(skillsDir, ".app-skills.json");
2645
- safeWriteJson(skillMeta, {
2646
- app_id: appSpec.app_id ?? appSpec.id,
2647
- skills: overlaySkills,
2648
- });
2649
- }
2650
- catch {
2651
- /* ignore */
2652
- }
2653
- }
2654
- // Copy cloned provider.env BEFORE proxy bootstrap
2655
- if (cloneFrom && envFiles.length) {
2656
- const srcEnvFiles = getRuntimeEnvFiles(cloneFrom);
2657
- const srcEnvFile = srcEnvFiles[0];
2658
- const dstEnvFile = envFiles[0];
2659
- if (srcEnvFile) {
2660
- const srcProvider = join(dirname(srcEnvFile), "provider.env");
2661
- const dstProvider = join(dirname(dstEnvFile), "provider.env");
2662
- if (existsSync(srcProvider) && !existsSync(dstProvider)) {
2663
- copyFileSync(srcProvider, dstProvider);
2664
- }
2665
- }
2666
- }
2667
- // Bootstrap proxy: generate proxy token and write model.env
2668
- try {
2669
- await bootstrapInstanceProxy(instanceId);
2670
- }
2671
- catch (e) {
2672
- console.warn(`[openclaw] Proxy bootstrap for ${instanceId} deferred: ${e.message}`);
2673
- }
2674
- // If running as root, hand ownership of all created files to service user
2675
- const svcUser = resolveServiceUser();
2676
- if (svcUser) {
2677
- try {
2678
- execFileSync("chown", ["-R", `${svcUser.uid}:${svcUser.gid}`, d], {
2679
- timeout: 10_000,
2680
- });
2681
- if (!home.startsWith(d + "/") && existsSync(home)) {
2682
- execFileSync("chown", ["-R", `${svcUser.uid}:${svcUser.gid}`, home], {
2683
- timeout: 10_000,
2684
- });
2685
- }
2686
- }
2687
- catch (e) {
2688
- console.warn(`[openclaw] chown for ${instanceId} failed:`, e.message);
2689
- }
2690
- }
2691
- if (portAlloc.skipped.length > 0) {
2692
- meta.port_allocation = {
2693
- assigned: portAlloc.port,
2694
- requested: OPENCLAW_DEFAULT_GATEWAY_PORT,
2695
- reason: "default_busy",
2696
- skipped: portAlloc.skipped,
2697
- };
2698
- }
2699
- return meta;
2700
- }
2701
- finally {
2702
- if (allocatedPort)
2703
- releasePendingPort(allocatedPort);
2704
- }
2705
- }
2706
- async createInitialLayout(ctx) {
2707
- // Framework never calls this on OpenClaw directly — `createInstance()`
2708
- // above does the full layout. Kept to satisfy the interface for path
2709
- // preview / UI callers.
2710
- const instDir = framework_instanceDir(ctx.instanceId);
2711
- const agentHome = defaultOpenclawHome(ctx.instanceId);
2712
- return {
2713
- instanceDir: instDir,
2714
- agentHome,
2715
- primaryConfig: join(agentHome, OPENCLAW_STATE_DIRNAME, OPENCLAW_CONFIG_FILENAME),
2716
- };
2717
- }
2718
- async buildRuntime(instanceId) {
2719
- // OpenClaw persists its runtime in legacy snake_case shape
2720
- // ({env_files, resources, ...}). Translate at read time into the
2721
- // engine-neutral RuntimeSpec contract.
2722
- const im = await lazyIm();
2723
- const raw = im.getInstanceRuntime(instanceId);
2724
- const home = im.getOpenclawHome(instanceId);
2725
- return {
2726
- image: raw?.image ?? getOpenclawDockerImage(),
2727
- command: String(raw?.command || DEFAULT_COMMAND),
2728
- args: Array.isArray(raw?.args) ? raw.args.map(String) : [...DEFAULT_ARGS],
2729
- cwd: String(raw?.cwd || home || DEFAULT_CWD),
2730
- user: String(raw?.user || DEFAULT_USER),
2731
- env: { ...DEFAULT_ENV, ...(raw?.env || {}) },
2732
- envFiles: Array.isArray(raw?.env_files)
2733
- ? raw.env_files
2734
- : Array.isArray(raw?.envFiles)
2735
- ? raw.envFiles
2736
- : [],
2737
- resources: {
2738
- CPU: Number(raw?.resources?.CPU ?? DEFAULT_RESOURCES.CPU),
2739
- MemoryMB: Number(raw?.resources?.MemoryMB ?? DEFAULT_RESOURCES.MemoryMB),
2740
- MemoryMaxMB: raw?.resources?.MemoryMaxMB != null ? Number(raw.resources.MemoryMaxMB) : undefined,
2741
- },
2742
- ports: [
2743
- {
2744
- name: "gateway",
2745
- containerPort: im.getGatewayPort(instanceId),
2746
- hostPort: im.getGatewayPort(instanceId),
2747
- visibility: "external",
2748
- },
2749
- ],
2750
- volumes: [{ hostPath: home, containerPath: home, mode: "rw" }],
2751
- health: null,
2752
- };
2753
- }
2754
- async buildNomadTask(instanceId) {
2755
- // Physically moved from nomad-manager.buildTaskDocker. The adapter owns
2756
- // OpenClaw's Nomad task layout end-to-end so `nomad-manager.buildJob()`
2757
- // becomes a pure dispatcher.
2758
- const im = await lazyIm();
2759
- const rawRuntime = im.getInstanceRuntime(instanceId);
2760
- const openclawHome = im.getOpenclawHome(instanceId);
2761
- if (rawRuntime.user && !VALID_USER_RE.test(rawRuntime.user)) {
2762
- throw new Error(`Invalid runtime user: ${rawRuntime.user}`);
2763
- }
2764
- const image = rawRuntime.image || getOpenclawDockerImage();
2765
- const _command = String(rawRuntime.command || DEFAULT_COMMAND);
2766
- const args = Array.isArray(rawRuntime.args)
2767
- ? rawRuntime.args.map(String)
2768
- : [...DEFAULT_ARGS];
2769
- const env = { ...DEFAULT_ENV };
2770
- Object.assign(env, im.getRuntimeEnv(instanceId));
2771
- decryptRuntimeProviderEnv(env);
2772
- injectProviderHostEnv(env, instanceId);
2773
- delete env.JSPROXY_API_KEY; // supplied via Nomad Template from Variables
2774
- env.OPENCLAW_HOME = openclawHome;
2775
- env.OPENCLAW_INSTANCE_ID = instanceId;
2776
- // Resource clamping
2777
- const rawResources = { ...DEFAULT_RESOURCES };
2778
- for (const [k, v] of Object.entries(rawRuntime.resources || {})) {
2779
- if (v != null)
2780
- rawResources[k] = Number(v);
2781
- }
2782
- rawResources.CPU = Math.max(1, Math.min(rawResources.CPU, MAX_CPU_MHZ));
2783
- rawResources.MemoryMB = Math.max(1, Math.min(rawResources.MemoryMB, getMaxAppMemoryMB()));
2784
- // Container env — OpenClaw-specific HOME / NODE_PATH / PATH / npm cfg
2785
- const containerEnv = { ...env };
2786
- containerEnv.HOME = openclawHome;
2787
- if (!containerEnv.OPENCLAW_STATE_DIR) {
2788
- containerEnv.OPENCLAW_STATE_DIR = `${openclawHome}/.openclaw`;
2789
- }
2790
- containerEnv.npm_config_prefix = `${openclawHome}/.npm-global`;
2791
- containerEnv.PIP_USER = "1";
2792
- containerEnv.PYTHONUSERBASE = `${openclawHome}/.local`;
2793
- containerEnv.NODE_ENV = "production";
2794
- containerEnv.NODE_PATH = [
2795
- `${openclawHome}/.npm-global/lib/node_modules`,
2796
- "/app/node_modules",
2797
- ].join(":");
2798
- containerEnv.PATH = [
2799
- `${openclawHome}/.npm-global/bin`,
2800
- `${openclawHome}/.local/bin`,
2801
- `${openclawHome}/go/bin`,
2802
- `${openclawHome}/.cargo/bin`,
2803
- "/usr/local/sbin",
2804
- "/usr/local/bin",
2805
- "/usr/sbin",
2806
- "/usr/bin",
2807
- "/sbin",
2808
- "/bin",
2809
- ].join(":");
2810
- const gatewayPort = im.getGatewayPort(instanceId);
2811
- const safeJobId = resolveNomadJobId(instanceId, this.nomadJobPrefix);
2812
- assertSafeTemplateId(safeJobId);
2813
- // Signal to OpenClaw that Nomad manages process lifecycle (restart on exit).
2814
- // Without this, OpenClaw >= 2026.5.20 refuses self-updates because
2815
- // detectRespawnSupervisor() finds no systemd/launchd markers.
2816
- containerEnv.OPENCLAW_SYSTEMD_UNIT = `nomad-${safeJobId}.service`;
2817
- const normalizedResources = normalizeDockerResources(instanceId, rawResources);
2818
- // Same rationale as hermes.ts:nomadHasExternalHostNetwork — without
2819
- // HostNetwork, Nomad's docker driver publishes the gateway port to
2820
- // 127.0.0.1, breaking cross-container consumers (e.g. OpenWebUI
2821
- // binding openclaw via the llm-agent capability). Bring the legacy
2822
- // openclaw job in line with the unified app-spec path.
2823
- const hostNetwork = nomadHasExternalHostNetwork() ? "external" : undefined;
2824
- return {
2825
- Name: "gateway",
2826
- Driver: "docker",
2827
- User: resolveUidGid(String(rawRuntime.user || DEFAULT_USER)),
2828
- Config: {
2829
- image,
2830
- force_pull: false,
2831
- // Match nomad-manager.ts:buildAppTask — default 5-minute pull
2832
- // timeout is too short for Pi-class networks pulling a 1+ GiB
2833
- // openclaw runtime image; bump to 15 minutes.
2834
- image_pull_timeout: "15m",
2835
- // Inline the temporary session-fence patch launcher so Nomad does not
2836
- // depend on a host-side executable wrapper. Once OpenClaw no longer
2837
- // needs this workaround, this custom entrypoint can be removed.
2838
- entrypoint: ["/bin/sh", "-c", CONTAINER_PATCH_ENTRYPOINT_COMMAND, "--"],
2839
- args,
2840
- work_dir: openclawHome,
2841
- volumes: buildVolumes(openclawHome, im.getInstanceRuntime(instanceId)),
2842
- // Tell the docker driver to publish the labeled "gateway" port so
2843
- // it routes via the host_network IP rather than the 127.0.0.1
2844
- // default.
2845
- ports: ["gateway"],
2846
- extra_hosts: ["host.docker.internal:host-gateway"],
2847
- cap_drop: ["ALL"],
2848
- security_opt: ["no-new-privileges"],
2849
- pids_limit: DEFAULT_PIDS_LIMIT,
2850
- readonly_rootfs: true,
2851
- mounts: [
2852
- { type: "tmpfs", target: "/tmp", tmpfs_options: { size: 536870912 } },
2853
- { type: "tmpfs", target: "/var/tmp", tmpfs_options: { size: 67108864 } },
2854
- { type: "tmpfs", target: "/run", tmpfs_options: { size: 52428800 } },
2855
- ],
2856
- },
2857
- Env: containerEnv,
2858
- Resources: {
2859
- ...normalizedResources,
2860
- Networks: [
2861
- {
2862
- ReservedPorts: [
2863
- {
2864
- Label: "gateway",
2865
- Value: gatewayPort,
2866
- To: gatewayPort,
2867
- ...(hostNetwork ? { HostNetwork: hostNetwork } : {}),
2868
- },
2869
- ],
2870
- },
2871
- ],
2872
- },
2873
- LogConfig: { MaxFiles: 3, MaxFileSizeMB: 10 },
2874
- Templates: [
2875
- {
2876
- DestPath: "secrets/instance.env",
2877
- Envvars: true,
2878
- EmbeddedTmpl: [
2879
- `{{ if nomadVarExists "nomad/jobs/${safeJobId}/openclaw/gateway" }}`,
2880
- `JSPROXY_API_KEY={{ with nomadVar "nomad/jobs/${safeJobId}/openclaw/gateway" }}{{ .JSPROXY_API_KEY }}{{ end }}`,
2881
- `{{ end }}`,
2882
- ].join("\n"),
2883
- ChangeMode: "restart",
2884
- },
2885
- ],
2886
- };
2887
- }
2888
- async getRuntimeVersion(_instanceId) {
2889
- // Parse the image reference (digest > tag) for the baseline image.
2890
- const image = getOpenclawDockerImage() || "";
2891
- let ref;
2892
- let digest;
2893
- if (image) {
2894
- if (image.includes("@")) {
2895
- digest = image.split("@", 2)[1];
2896
- }
2897
- else {
2898
- const lastColon = image.lastIndexOf(":");
2899
- const lastSlash = image.lastIndexOf("/");
2900
- if (lastColon > lastSlash)
2901
- ref = image.slice(lastColon + 1);
2902
- }
2903
- }
2904
- return { agentType: "openclaw", ref, digest, mode: "baseline" };
2905
- }
2906
- async getConfigMeta(instanceId) {
2907
- return {
2908
- agentType: "openclaw",
2909
- format: "json",
2910
- schemaId: "openclaw/v1",
2911
- capabilities: DEFAULT_CAPABILITIES,
2912
- secretFields: ["content.x-jishushell.proxy.upstream.apiKey"],
2913
- runtimeVersion: await this.getRuntimeVersion(instanceId),
2914
- };
2915
- }
2916
- async readConfig(instanceId) {
2917
- const im = await lazyIm();
2918
- const content = im.getStoredConfig
2919
- ? im.getStoredConfig(instanceId)
2920
- : null;
2921
- return {
2922
- format: "json",
2923
- content: (content && typeof content === "object") ? content : {},
2924
- };
2925
- }
2926
- async writeConfig(instanceId, doc) {
2927
- if (doc.format !== "json") {
2928
- throw new Error(`OpenClaw config requires format="json", got "${doc.format}"`);
2929
- }
2930
- // Route through llmProxy.saveInstanceConfig so x-jishushell.proxy
2931
- // metadata is stripped, the upstream apiKey is AES-encrypted to
2932
- // provider.env, and models.providers is rewritten to the local
2933
- // proxy — same contract HermesAdapter.writeConfig uses. That
2934
- // function internally calls instanceManager.saveConfig, which
2935
- // dispatches back to this adapter's saveNativeConfig() for the
2936
- // raw disk write (distinct method, no recursion).
2937
- const { saveInstanceConfig } = await import("../../llm-proxy/instance-proxy.js");
2938
- await saveInstanceConfig(instanceId, doc.content);
2939
- return this.readConfig(instanceId);
2940
- }
2941
- async buildPairingListCommand(_instanceId) {
2942
- return ["openclaw", "pairing", "list"];
2943
- }
2944
- async buildPairingApproveCommand(_instanceId, input) {
2945
- return ["openclaw", "pairing", "approve", input.channel, input.code];
2946
- }
2947
- /**
2948
- * Framework delete hook — returns warnings for the caller to surface to
2949
- * the user. OpenClaw supports a custom `openclaw_home` pointing outside
2950
- * the instance directory; those directories are preserved on delete.
2951
- */
2952
- async onDelete(args) {
2953
- const warnings = [];
2954
- const home = args.meta?.openclaw_home;
2955
- if (home) {
2956
- warnings.push(`Custom openclaw_home "${home}" was NOT removed; delete it manually if unused.`);
2957
- }
2958
- return warnings;
2959
- }
2960
- // ── Native config I/O (physically migrated from instance-manager) ───
2961
- channelPluginMap = CHANNEL_PLUGIN_MAP;
2962
- /**
2963
- * Get the stored raw OpenClaw config (from `.openclaw/openclaw.json`
2964
- * or the legacy `openclaw.json`), merged with the x-jishushell
2965
- * metadata pulled from `instance.json`. Returns null when the instance
2966
- * has no persisted config yet.
2967
- */
2968
- getNativeConfig(instanceId) {
2969
- const config = loadEffectiveConfig(instanceId);
2970
- if (!config)
2971
- return null;
2972
- // Always merge the latest upstream proxy config from instance.json
2973
- const meta = getInstance(instanceId);
2974
- if (meta?.["x-jishushell"]) {
2975
- config["x-jishushell"] = meta["x-jishushell"];
2976
- }
2977
- // Inject upstream provider apiKey from env file so callers see it
2978
- return injectProviderApiKeys(instanceId, config);
2979
- }
2980
- /**
2981
- * Get the stored raw config WITHOUT provider key injection. Used by
2982
- * callers that round-trip the config back to disk (e.g. credential
2983
- * writers) — injecting the provider key would re-persist it to the
2984
- * config file, which is exactly what `saveConfig` takes pains to avoid.
2985
- */
2986
- getStoredNativeConfig(instanceId) {
2987
- const config = loadEffectiveConfig(instanceId);
2988
- if (!config)
2989
- return null;
2990
- const meta = getInstance(instanceId);
2991
- if (meta?.["x-jishushell"]) {
2992
- config["x-jishushell"] = meta["x-jishushell"];
2993
- }
2994
- return config;
2995
- }
2996
- isChannelPluginInstalled(instanceId, channelId) {
2997
- return isChannelPluginInstalled(instanceId, channelId);
2998
- }
2999
- async installChannelPlugin(instanceId, channelId) {
3000
- return installChannelPlugin(instanceId, channelId);
3001
- }
3002
- saveNativeConfig(instanceId, config) {
3003
- return saveNativeConfigImpl(instanceId, config);
3004
- }
3005
- /**
3006
- * Connection-apply hook (§7 of app-interconnect-design): translate
3007
- * resolved `inject_as` env vars into OpenClaw-native plugin config and
3008
- * persist them into `openclaw.json`. Without this, the runtime env
3009
- * injected by `nomad-manager.injectConnectionsRuntimeEnv` (PR 8) sits
3010
- * in the container unused — the OpenClaw agent reads tool config from
3011
- * `openclaw.json`, not from environment variables.
3012
- *
3013
- * Currently wired:
3014
- * SEARCH_API_BASE_URL → plugins.entries.searxng.config.webSearch.baseUrl
3015
- * SEARCH_API_BASE_URL → tools.web.search.provider = "searxng"
3016
- *
3017
- * The provider selector at `tools.web.search.provider` is required: without
3018
- * it the `web_search` tool defaults to Brave and fails with
3019
- * `missing_brave_api_key` even when the searxng plugin is fully configured.
3020
- *
3021
- * Browser / LLM / MCP wiring lands in PR 9b — they need their own
3022
- * config-shape mapping (browser → tools.browser, llm → models.providers,
3023
- * mcp already wired via openclaw-mcporter).
3024
- *
3025
- * The write goes through `saveNativeConfig` which deep-merges with the
3026
- * existing on-disk config, so user-managed plugin entries (e.g.
3027
- * openclaw-lark) are preserved. Plugin auto-enable then promotes the
3028
- * searxng entry into `plugins.allow` automatically on next start
3029
- * because we set `enabled:true` and provide config (the openclaw
3030
- * runtime treats the presence of `config.webSearch.baseUrl` as a
3031
- * "configured" signal — see `plugin-auto-enable` in the openclaw
3032
- * dist bundle).
3033
- */
3034
- async applyConnectionEnv(instanceId, env) {
3035
- const configPath = openclawConfigPath(instanceId);
3036
- const searchUrl = env.SEARCH_API_BASE_URL;
3037
- if (typeof searchUrl === "string") {
3038
- if (searchUrl === "") {
3039
- // Empty value — connection-transactor's UNPERSIST_HOOKS uses this as
3040
- // the "unbind" signal. Clear the searxng plugin config so the next
3041
- // start doesn't keep routing web_search through a now-disconnected
3042
- // provider.
3043
- try {
3044
- clearSearxngConnectionFromConfig(configPath);
3045
- }
3046
- catch (e) {
3047
- console.warn(`[openclaw] applyConnectionEnv search unbind failed for ${instanceId}: ${e.message}`);
3048
- }
3049
- }
3050
- else {
3051
- // SEARCH_API_BASE_URL points at "<base>/search" (the SearXNG search
3052
- // endpoint). The plugin's webSearch.baseUrl wants the bare origin —
3053
- // strip the trailing "/search" path segment if present.
3054
- // baseUrl stays at the registry-resolved host:port snapshot from
3055
- // when the user PUT /connections; the framework re-runs this hook
3056
- // on every instance start (PR 9 phaseRefreshConnections), so host
3057
- // IP changes propagate automatically on next agent restart.
3058
- let baseUrl = searchUrl;
3059
- try {
3060
- const u = new URL(searchUrl);
3061
- if (u.pathname === "/search" || u.pathname === "/search/") {
3062
- u.pathname = "";
3063
- baseUrl = u.toString().replace(/\/$/, "");
3064
- }
3065
- try {
3066
- applySearxngConnectionToConfig(configPath, baseUrl);
3067
- }
3068
- catch (e) {
3069
- console.warn(`[openclaw] applyConnectionEnv search merge failed for ${instanceId}: ${e.message}`);
3070
- }
3071
- }
3072
- catch {
3073
- // not a URL — skip silently; the openclaw plugin would break
3074
- // with a non-URL baseUrl, and start should still proceed.
3075
- }
3076
- }
3077
- }
3078
- const cdpUrl = env.BROWSER_CDP_URL;
3079
- if (typeof cdpUrl === "string") {
3080
- if (cdpUrl === "") {
3081
- try {
3082
- clearBrowserlessConnectionFromConfig(configPath);
3083
- }
3084
- catch (e) {
3085
- console.warn(`[openclaw] applyConnectionEnv browser unbind failed for ${instanceId}: ${e.message}`);
3086
- }
3087
- }
3088
- else if (/^wss?:\/\//.test(cdpUrl)) {
3089
- try {
3090
- applyBrowserlessConnectionToConfig(configPath, cdpUrl);
3091
- }
3092
- catch (e) {
3093
- console.warn(`[openclaw] applyConnectionEnv browser merge failed for ${instanceId}: ${e.message}`);
3094
- }
3095
- }
3096
- // Non-ws scheme: skip silently. The connection-apply browser hook
3097
- // already builds ws:// from the capability protocol; an http:// here
3098
- // would mean a misconfigured provider — better to no-op than to
3099
- // write a URL OpenClaw can't dial.
3100
- }
3101
- }
3102
- // ── Path resolvers (physically migrated) ───────────────────────────
3103
- resolveBin() {
3104
- return resolveOpenclawBin();
3105
- }
3106
- resolveAgentHome(instanceId) {
3107
- const meta = getInstance(instanceId);
3108
- return meta?.openclaw_home || defaultOpenclawHome(instanceId);
3109
- }
3110
- /** Env vars OpenClaw's CLI needs when backup-manager runs it as a subprocess. */
3111
- buildCliEnv(instanceId) {
3112
- return { OPENCLAW_HOME: this.resolveAgentHome(instanceId) };
3113
- }
3114
- /**
3115
- * Legacy gateway-port fallback for instances created before the
3116
- * RuntimeSpec.ports[] migration. OpenClaw persists its port in both
3117
- * `runtime.env.OPENCLAW_GATEWAY_PORT` and `runtime.args ["--port", N]`.
3118
- */
3119
- readLegacyGatewayPort(runtime) {
3120
- if (!runtime)
3121
- return null;
3122
- const envPort = runtime.env?.OPENCLAW_GATEWAY_PORT;
3123
- if (envPort) {
3124
- const p = parseInt(envPort, 10);
3125
- if (!isNaN(p))
3126
- return p;
3127
- }
3128
- const args = runtime.args || [];
3129
- for (let i = 0; i < args.length; i++) {
3130
- const arg = String(args[i]);
3131
- if (arg === "--port" && i + 1 < args.length) {
3132
- const p = parseInt(args[i + 1], 10);
3133
- return isNaN(p) ? null : p;
3134
- }
3135
- if (arg.startsWith("--port=")) {
3136
- const p = parseInt(arg.split("=")[1], 10);
3137
- return isNaN(p) ? null : p;
3138
- }
3139
- }
3140
- return null;
3141
- }
3142
- /**
3143
- * Rewrite a persisted OpenClaw runtime spec to use a new host port.
3144
- * Updates `args[--port]` + `env.OPENCLAW_GATEWAY_PORT` atomically so
3145
- * both places stay in sync.
3146
- */
3147
- reallocateRuntimePort(runtime, newPort) {
3148
- const args = Array.isArray(runtime.args) ? [...runtime.args] : [];
3149
- for (let i = 0; i < args.length; i++) {
3150
- if (args[i] === "--port" && i + 1 < args.length) {
3151
- args[i + 1] = String(newPort);
3152
- }
3153
- else if (typeof args[i] === "string" && args[i].startsWith("--port=")) {
3154
- args[i] = `--port=${newPort}`;
3155
- }
3156
- }
3157
- runtime.args = args;
3158
- const env = (runtime.env ?? {});
3159
- env.OPENCLAW_GATEWAY_PORT = String(newPort);
3160
- runtime.env = env;
3161
- }
3162
- nomadJobPrefix = "openclaw-";
3163
- // OpenClaw is the default/core runtime — runFullSetup must fail hard if
3164
- // its image install fails, because the panel is unusable without it.
3165
- // Third-party adapters should leave `required` unset (= optional).
3166
- required = true;
3167
- // Must match the path referenced by this adapter's buildNomadTask Templates
3168
- // (see `nomadVar "nomad/jobs/<jid>/openclaw/gateway"` in the template body).
3169
- nomadVariablePath = "openclaw/gateway";
3170
- resolveConfigPath(instanceId) {
3171
- return openclawConfigPath(instanceId, this.resolveAgentHome(instanceId));
3172
- }
3173
- resolveLegacyConfigPath(instanceId) {
3174
- return legacyOpenclawConfigPath(instanceId, this.resolveAgentHome(instanceId));
3175
- }
3176
- /**
3177
- * Return other OpenClaw instance IDs that share this one's
3178
- * `openclaw_home` path. Used by the start-time conflict check.
3179
- */
3180
- findInstancesSharingHome(instanceId) {
3181
- const target = normalizePath(this.resolveAgentHome(instanceId));
3182
- return listInstances()
3183
- .filter((inst) => inst.id !== instanceId)
3184
- .filter((inst) => {
3185
- const meta = inst;
3186
- const otherHome = meta.openclaw_home || defaultOpenclawHome(inst.id);
3187
- return normalizePath(otherHome) === target;
3188
- })
3189
- .map((inst) => inst.id);
3190
- }
3191
- // ── Feishu / WeChat credential writers (physically migrated) ───────
3192
- saveFeishuCredentials(instanceId, creds) {
3193
- if (!FEISHU_APP_ID_RE.test(creds.appId)) {
3194
- throw new Error(`Invalid Feishu appId format: expected cli_<alnum> (got "${creds.appId}")`);
3195
- }
3196
- if (!creds.appSecret || typeof creds.appSecret !== "string" || creds.appSecret.length < 4) {
3197
- throw new Error("Invalid Feishu appSecret: must be a non-empty string");
3198
- }
3199
- const configPath = this.resolveConfigPath(instanceId);
3200
- let config = {};
3201
- try {
3202
- if (existsSync(configPath)) {
3203
- config = JSON.parse(readFileSync(configPath, "utf-8"));
3204
- }
3205
- }
3206
- catch {
3207
- /* best effort */
3208
- }
3209
- config.plugins ??= {};
3210
- config.plugins.entries ??= {};
3211
- config.plugins.entries.feishu = { enabled: false };
3212
- config.plugins.entries["openclaw-lark"] = { enabled: true };
3213
- config.channels ??= {};
3214
- config.channels.feishu = {
3215
- ...config.channels.feishu,
3216
- enabled: true,
3217
- appId: creds.appId,
3218
- appSecret: creds.appSecret,
3219
- domain: creds.domain,
3220
- dmPolicy: "open",
3221
- allowFrom: ["*"],
3222
- };
3223
- safeWriteJson(configPath, config);
3224
- chownToServiceUser(configPath);
3225
- console.log(`[openclaw] Feishu credentials saved for ${instanceId}, domain=${creds.domain}`);
3226
- }
3227
- saveWeixinCredentials(instanceId, creds) {
3228
- if (!creds.accountId || !SAFE_ACCOUNT_ID_RE.test(creds.accountId) || creds.accountId.includes("..")) {
3229
- throw new Error(`Invalid accountId: must be 1-128 chars of [a-zA-Z0-9@._-] without '..'`);
3230
- }
3231
- const home = this.resolveAgentHome(instanceId);
3232
- const stateDir = join(home, OPENCLAW_STATE_DIRNAME, "openclaw-weixin");
3233
- const accountsDir = join(stateDir, "accounts");
3234
- ensureDirContainer(accountsDir);
3235
- const credObj = {
3236
- token: creds.token,
3237
- baseUrl: creds.baseUrl,
3238
- userId: creds.userId,
3239
- savedAt: new Date().toISOString(),
3240
- };
3241
- safeWriteJson(join(accountsDir, `${creds.accountId}.json`), credObj);
3242
- safeWriteJson(join(accountsDir, "default.json"), credObj);
3243
- chownToServiceUser(join(accountsDir, `${creds.accountId}.json`), join(accountsDir, "default.json"));
3244
- // Update accounts.json index
3245
- const indexPath = join(stateDir, "accounts.json");
3246
- let index = [];
3247
- try {
3248
- const raw = readFileSync(indexPath, "utf-8");
3249
- index = JSON.parse(raw);
3250
- }
3251
- catch {
3252
- /* start fresh */
3253
- }
3254
- if (!Array.isArray(index))
3255
- index = [];
3256
- if (!index.includes(creds.accountId))
3257
- index.push(creds.accountId);
3258
- safeWriteJson(indexPath, index);
3259
- const configPath = this.resolveConfigPath(instanceId);
3260
- let config = {};
3261
- try {
3262
- if (existsSync(configPath))
3263
- config = JSON.parse(readFileSync(configPath, "utf-8"));
3264
- }
3265
- catch {
3266
- /* best effort */
3267
- }
3268
- config.plugins ??= {};
3269
- config.plugins.entries ??= {};
3270
- config.plugins.entries["openclaw-weixin"] ??= {};
3271
- config.plugins.entries["openclaw-weixin"].enabled = true;
3272
- config.channels ??= {};
3273
- config.channels["openclaw-weixin"] ??= {};
3274
- config.channels["openclaw-weixin"].enabled = true;
3275
- const normalizedId = creds.accountId.replace(/[@.]/g, "-");
3276
- const accounts = config.channels["openclaw-weixin"].accounts ??= {};
3277
- accounts[creds.accountId] = { enabled: true };
3278
- if (normalizedId !== creds.accountId)
3279
- accounts[normalizedId] = { enabled: true };
3280
- accounts["default"] = { enabled: true };
3281
- if (!config.channels["openclaw-weixin"].defaultAccount) {
3282
- config.channels["openclaw-weixin"].defaultAccount = "default";
3283
- }
3284
- safeWriteJson(configPath, config);
3285
- chownToServiceUser(configPath);
3286
- console.log(`[openclaw] WeChat credentials saved for ${instanceId}, account=${creds.accountId}`);
3287
- }
3288
- getWeixinAccounts(instanceId) {
3289
- const home = this.resolveAgentHome(instanceId);
3290
- const stateDir = join(home, OPENCLAW_STATE_DIRNAME, "openclaw-weixin");
3291
- const accountsDir = join(stateDir, "accounts");
3292
- if (!existsSync(accountsDir))
3293
- return [];
3294
- let indexedIds = [];
3295
- try {
3296
- indexedIds = JSON.parse(readFileSync(join(stateDir, "accounts.json"), "utf-8"));
3297
- }
3298
- catch {
3299
- /* fallback to scanning */
3300
- }
3301
- const results = [];
3302
- for (const f of readdirSync(accountsDir)) {
3303
- if (!f.endsWith(".json"))
3304
- continue;
3305
- const id = f.replace(/\.json$/, "");
3306
- if (indexedIds.length > 0 && !indexedIds.includes(id))
3307
- continue;
3308
- if (id === "default")
3309
- continue;
3310
- try {
3311
- const data = JSON.parse(readFileSync(join(accountsDir, f), "utf-8"));
3312
- results.push({
3313
- accountId: id,
3314
- userId: data.userId,
3315
- savedAt: data.savedAt,
3316
- });
3317
- }
3318
- catch {
3319
- /* skip */
3320
- }
3321
- }
3322
- return results;
3323
- }
3324
- // ── §32.2.4 runtime install (physically migrated from setup-manager) ──
3325
- //
3326
- // Installs the OpenClaw npm package via `npm install -g --prefix` so that
3327
- // postinstall scripts run naturally. Emits SSE progress through the task
3328
- // machinery exported by setup-manager.
3329
- async installRuntime(opts) {
3330
- const version = opts?.version ?? "latest";
3331
- try {
3332
- const openclawPkgDir = join(OPENCLAW_MODULES, "openclaw");
3333
- if (existsSync(openclawPkgDir)) {
3334
- const ver = readInstalledOpenclawVersion() || "unknown";
3335
- return { ok: true, message: `OpenClaw already installed: ${ver}` };
3336
- }
3337
- const task = createTask("openclaw");
3338
- ensureDirHost(OPENCLAW_PKG_DIR);
3339
- emitTask(task, { type: "progress", message: "开始安装 OpenClaw...", progress: 0 });
3340
- const sizeTracker = setInterval(() => {
3341
- const sizeMB = getDirSizeMB(OPENCLAW_PKG_DIR);
3342
- const pct = Math.min(95, Math.round((sizeMB / OPENCLAW_EXPECTED_SIZE_MB) * 95));
3343
- if (pct > 0) {
3344
- emitTask(task, {
3345
- type: "progress",
3346
- message: `下载安装中... ${sizeMB}MB / ~${OPENCLAW_EXPECTED_SIZE_MB}MB`,
3347
- progress: pct,
3348
- });
3349
- }
3350
- }, 3000);
3351
- const result = await spawnWithTask(task, "npm", ["install", "-g", "--prefix", OPENCLAW_PKG_DIR, `openclaw@${version}`], { timeout: 600000, progressParser: npmProgressParser });
3352
- clearInterval(sizeTracker);
3353
- if (!result.ok) {
3354
- emitTask(task, { type: "error", message: "OpenClaw 安装失败" });
3355
- task.status = "error";
3356
- return {
3357
- ok: false,
3358
- message: "OpenClaw installation failed",
3359
- error: result.output,
3360
- taskId: task.id,
3361
- };
3362
- }
3363
- const ver = readInstalledOpenclawVersion() || "installed";
3364
- emitTask(task, { type: "done", message: `OpenClaw 安装完成: ${ver}`, progress: 100 });
3365
- task.status = "done";
3366
- return { ok: true, message: `OpenClaw installed: ${ver}`, taskId: task.id };
3367
- }
3368
- catch (e) {
3369
- return { ok: false, message: "OpenClaw installation failed", error: e.message };
3370
- }
3371
- }
3372
- /**
3373
- * Build / pull the OpenClaw Docker image. Blocking — useful for CLI
3374
- * installer and `runFullSetup()`. Non-blocking variant below is used by
3375
- * the REST API and the adapter's own `onBeforeStart` self-heal path.
3376
- */
3377
- async buildRuntimeImage(opts) {
3378
- const task = createTask("openclaw-docker-pull");
3379
- return pullOrBuildOpenclawImageWithTask(task, opts?.tag);
3380
- }
3381
- /**
3382
- * Non-blocking variant of `buildRuntimeImage` — returns a task id
3383
- * immediately so the caller can poll SSE progress.
3384
- */
3385
- startBuildRuntimeImage(opts) {
3386
- const task = createTask("openclaw-docker-pull");
3387
- void pullOrBuildOpenclawImageWithTask(task, opts?.tag).catch((err) => {
3388
- emitTask(task, {
3389
- type: "error",
3390
- message: `镜像获取失败: ${err?.message || err}`,
3391
- });
3392
- task.status = "error";
3393
- });
3394
- return { ok: true, message: "Docker image pull started", taskId: task.id };
3395
- }
3396
- /**
3397
- * Return OpenClaw's readiness for spawning instances. Docker image
3398
- * presence is the gating factor in the default docker-mode deployment;
3399
- * the legacy `npm install` path is still reported as `installed` but is
3400
- * not required for the docker-driver stack.
3401
- */
3402
- getInstallStatus() {
3403
- // OPENCLAW_MODULES may be undefined when config is partially mocked in tests.
3404
- const pkgInstalled = OPENCLAW_MODULES ? existsSync(join(OPENCLAW_MODULES, "openclaw")) : false;
3405
- const version = pkgInstalled ? readInstalledOpenclawVersion() : undefined;
3406
- const imageTag = getOpenclawDockerImage?.() ?? "";
3407
- let imageReady = false;
3408
- try {
3409
- const invocation = resolveDockerInvocation();
3410
- if (invocation?.cmd) {
3411
- execFileSync(invocation.cmd, [...invocation.argsPrefix, "image", "inspect", imageTag], {
3412
- timeout: 5000,
3413
- stdio: "ignore",
3414
- });
3415
- imageReady = true;
3416
- }
3417
- }
3418
- catch { /* image absent */ }
3419
- return {
3420
- installed: imageReady || pkgInstalled,
3421
- imageReady,
3422
- version: version || undefined,
3423
- };
3424
- }
3425
- }
3426
- // ── Install-time helpers (used by installRuntime) ─────────────────────
3427
- const OPENCLAW_EXPECTED_SIZE_MB = 700;
3428
- function readInstalledOpenclawVersion() {
3429
- try {
3430
- const pkg = join(OPENCLAW_MODULES, "openclaw", "package.json");
3431
- if (existsSync(pkg))
3432
- return JSON.parse(readFileSync(pkg, "utf-8")).version || "";
3433
- }
3434
- catch {
3435
- /* best effort */
3436
- }
3437
- return "";
3438
- }
3439
- // Feishu app IDs issued by the open platform follow `cli_<hex/alnum>`.
3440
- const FEISHU_APP_ID_RE = /^cli_[a-zA-Z0-9]{8,64}$/;
3441
- const SAFE_ACCOUNT_ID_RE = /^[a-zA-Z0-9@._-]{1,128}$/;
3442
- // ── Channel plugin constants (physically migrated) ───────────────────
3443
- const CHANNEL_EXT_DIR_ALIAS = {
3444
- feishu: "openclaw-lark",
3445
- lark: "openclaw-lark",
3446
- };
3447
- const CHANNEL_PLUGIN_MAP = {
3448
- feishu: "@larksuite/openclaw-lark",
3449
- lark: "@larksuite/openclaw-lark",
3450
- telegram: "@openclaw/telegram",
3451
- discord: "@openclaw/discord",
3452
- slack: "@openclaw/slack",
3453
- whatsapp: "@openclaw/whatsapp",
3454
- signal: "@openclaw/signal",
3455
- line: "@openclaw/line",
3456
- msteams: "@openclaw/msteams",
3457
- "openclaw-weixin": "@tencent-weixin/openclaw-weixin",
3458
- };
3459
- const IM_PLUGIN_ENTRY_IDS = new Set([
3460
- ...Object.keys(CHANNEL_PLUGIN_MAP),
3461
- ...Object.values(CHANNEL_EXT_DIR_ALIAS),
3462
- ]);
3463
- // ── Config I/O helpers (physically migrated) ─────────────────────────
3464
- function hasConfiguredValue(value) {
3465
- if (typeof value !== "string")
3466
- return !!value;
3467
- return value.trim().length > 0;
3468
- }
3469
- function loadJsonSafe(path) {
3470
- try {
3471
- return JSON.parse(readFileSync(path, "utf-8"));
3472
- }
3473
- catch (e) {
3474
- console.warn(`[openclaw] Failed to parse ${path}: ${e.message}`);
3475
- return null;
3476
- }
3477
- }
3478
- function deepMergeConfig(base, overlay) {
3479
- if (typeof base !== "object" || base === null ||
3480
- typeof overlay !== "object" || overlay === null ||
3481
- Array.isArray(base) || Array.isArray(overlay)) {
3482
- return structuredClone(overlay);
3483
- }
3484
- const merged = structuredClone(base);
3485
- for (const key of Object.keys(overlay)) {
3486
- merged[key] = key in merged ? deepMergeConfig(merged[key], overlay[key]) : structuredClone(overlay[key]);
3487
- }
3488
- return merged;
3489
- }
3490
- function loadEffectiveConfig(instanceId) {
3491
- const runtimePath = openclawConfigPath(instanceId);
3492
- const legacyPath = legacyOpenclawConfigPath(instanceId);
3493
- const rExists = existsSync(runtimePath);
3494
- const lExists = existsSync(legacyPath);
3495
- if (rExists && lExists) {
3496
- const legacy = loadJsonSafe(legacyPath);
3497
- const runtime = loadJsonSafe(runtimePath);
3498
- if (legacy && runtime)
3499
- return deepMergeConfig(legacy, runtime);
3500
- return runtime || legacy || null;
3501
- }
3502
- if (rExists)
3503
- return loadJsonSafe(runtimePath);
3504
- if (lExists)
3505
- return loadJsonSafe(legacyPath);
3506
- return null;
3507
- }
3508
- function injectProviderApiKeys(instanceId, config) {
3509
- const merged = structuredClone(config);
3510
- const runtimeEnv = getRuntimeEnv(instanceId);
3511
- const providers = merged.models?.providers || {};
3512
- for (const [providerId, provider] of Object.entries(providers)) {
3513
- if (typeof provider !== "object" || provider === null)
3514
- continue;
3515
- const p = provider;
3516
- p.api = normalizeProviderApi(typeof p.api === "string" ? p.api : undefined);
3517
- const apiKey = runtimeEnv[inferProviderApiKeyEnvName(providerId)];
3518
- if (apiKey)
3519
- p.apiKey = apiKey;
3520
- }
3521
- return merged;
3522
- }
3523
- function applyFeishuDebugAccessDefaults(channel) {
3524
- if (channel.enabled === false)
3525
- return;
3526
- if (!hasConfiguredValue(channel.appId))
3527
- return;
3528
- if (!hasConfiguredValue(channel.appSecret))
3529
- return;
3530
- let dmPolicy = channel.dmPolicy;
3531
- if (typeof dmPolicy !== "string" || !dmPolicy.trim()) {
3532
- channel.dmPolicy = "open";
3533
- dmPolicy = "open";
3534
- }
3535
- if (dmPolicy !== "open")
3536
- return;
3537
- if (!("resolveSenderNames" in channel))
3538
- channel.resolveSenderNames = false;
3539
- let accounts = channel.accounts;
3540
- if (typeof accounts !== "object" || accounts === null) {
3541
- accounts = {};
3542
- channel.accounts = accounts;
3543
- }
3544
- let defaultAccount = accounts.default;
3545
- if (typeof defaultAccount !== "object" || defaultAccount === null) {
3546
- defaultAccount = {};
3547
- accounts.default = defaultAccount;
3548
- }
3549
- if (!("resolveSenderNames" in defaultAccount))
3550
- defaultAccount.resolveSenderNames = false;
3551
- const allowFrom = channel.allowFrom;
3552
- if (Array.isArray(allowFrom)) {
3553
- const normalized = allowFrom.map((e) => String(e).trim()).filter(Boolean);
3554
- if (!normalized.includes("*"))
3555
- normalized.push("*");
3556
- channel.allowFrom = normalized;
3557
- return;
3558
- }
3559
- channel.allowFrom = ["*"];
3560
- }
3561
- function prepareConfigForSave(instanceId, config) {
3562
- const configToWrite = structuredClone(config);
3563
- delete configToWrite["x-jishushell"];
3564
- const envUpdates = {};
3565
- const providers = configToWrite.models?.providers || {};
3566
- const envFiles = getRuntimeEnvFiles(instanceId);
3567
- const channels = configToWrite.channels || {};
3568
- const plugins = configToWrite.plugins ??= {};
3569
- const pluginEntries = plugins.entries ??= {};
3570
- for (const [providerId, provider] of Object.entries(providers)) {
3571
- if (typeof provider !== "object" || provider === null)
3572
- continue;
3573
- const p = provider;
3574
- p.api = normalizeProviderApi(typeof p.api === "string" ? p.api : undefined);
3575
- // Ensure allowPrivateNetwork for providers targeting the local proxy
3576
- if (typeof p.baseUrl === "string" && isPrivateNetworkBaseUrl(p.baseUrl)) {
3577
- p.request = { ...(p.request || {}), allowPrivateNetwork: true };
3578
- }
3579
- if (!("apiKey" in p))
3580
- continue;
3581
- if (typeof p.baseUrl === "string" && p.baseUrl.includes("/proxy/"))
3582
- continue;
3583
- const apiKey = p.apiKey;
3584
- delete p.apiKey;
3585
- if (envFiles.length) {
3586
- envUpdates[inferProviderApiKeyEnvName(providerId)] = decryptRuntimeProviderApiKey(apiKey);
3587
- }
3588
- else {
3589
- p.apiKey = apiKey;
3590
- }
3591
- }
3592
- for (const [channelId, channel] of Object.entries(channels)) {
3593
- if (typeof channel !== "object" || channel === null)
3594
- continue;
3595
- const ch = channel;
3596
- if (channelId === "feishu" || channelId === "lark")
3597
- applyFeishuDebugAccessDefaults(ch);
3598
- let pluginEntry = pluginEntries[channelId];
3599
- if (pluginEntry == null) {
3600
- pluginEntry = {};
3601
- pluginEntries[channelId] = pluginEntry;
3602
- }
3603
- if (typeof pluginEntry === "object") {
3604
- pluginEntry.enabled = ch.enabled !== false;
3605
- }
3606
- }
3607
- return [configToWrite, envUpdates];
3608
- }
3609
- function decryptRuntimeProviderApiKey(apiKey) {
3610
- const value = String(apiKey || "");
3611
- return value.startsWith("enc:") ? decryptApiKey(value) : value;
3612
- }
3613
- function decryptRuntimeProviderEnv(env) {
3614
- for (const [key, value] of Object.entries(env)) {
3615
- if (!key.endsWith("_API_KEY"))
3616
- continue;
3617
- if (!String(value || "").startsWith("enc:"))
3618
- continue;
3619
- env[key] = decryptApiKey(value);
3620
- }
3621
- }
3622
- /**
3623
- * Auto-injects provider-specific host env vars that OpenClaw tools need
3624
- * at runtime, if the user hasn't already set them explicitly.
3625
- *
3626
- * Currently handles:
3627
- * - MINIMAX_API_HOST: Derived from MINIMAX_BASE_URL or upstream proxy config
3628
- * to ensure the VLM tool calls the correct MiniMax API domain.
3629
- *
3630
- * Note: Only MiniMax needs this because its VLM tool reads MINIMAX_API_HOST
3631
- * to determine the endpoint. DeepSeek does not have a dedicated VLM tool
3632
- * in OpenClaw that requires a similar host env var.
3633
- */
3634
- function injectProviderHostEnv(env, instanceId) {
3635
- // MINIMAX_API_HOST — needed by OpenClaw's VLM tool to call the correct domain
3636
- if (!env.MINIMAX_API_HOST) {
3637
- const baseUrl = env.MINIMAX_BASE_URL || "";
3638
- if (baseUrl) {
3639
- try {
3640
- const parsed = new URL(baseUrl);
3641
- env.MINIMAX_API_HOST = `${parsed.protocol}//${parsed.host}`;
3642
- }
3643
- catch { /* invalid URL, skip */ }
3644
- }
3645
- else {
3646
- // Infer from upstream proxy config if available
3647
- const config = getProxyInstanceConfig(instanceId);
3648
- const upstream = config?.["x-jishushell"]?.proxy?.upstream;
3649
- if (upstream?.providerId === "minimax" && upstream.baseUrl) {
3650
- try {
3651
- const parsed = new URL(upstream.baseUrl);
3652
- env.MINIMAX_API_HOST = `${parsed.protocol}//${parsed.host}`;
3653
- }
3654
- catch { /* invalid URL, skip */ }
3655
- }
3656
- }
3657
- }
3658
- }
3659
- /**
3660
- * Dissociate a cloned/imported config from its source instance's IM bindings.
3661
- * Physically migrated from `instance-manager.stripImBindings` so framework
3662
- * code no longer references OpenClaw channel concepts.
3663
- *
3664
- * Exported so `OpenClawAdapter.createInstance`'s clone path + `backup-manager`
3665
- * import paths can use it without depending on instance-manager.
3666
- */
3667
- export function stripImBindings(config) {
3668
- if (config?.channels)
3669
- delete config.channels;
3670
- const entries = config?.plugins?.entries;
3671
- if (entries && typeof entries === "object") {
3672
- for (const key of Object.keys(entries)) {
3673
- if (IM_PLUGIN_ENTRY_IDS.has(key))
3674
- delete entries[key];
3675
- }
3676
- }
3677
- }
3678
- function getChannelExtensionsDir(instanceId) {
3679
- const home = getInstance(instanceId)?.openclaw_home ||
3680
- defaultOpenclawHome(instanceId);
3681
- return join(home, OPENCLAW_STATE_DIRNAME, "extensions");
3682
- }
3683
- function getStockExtensionsDir() {
3684
- return join(JISHUSHELL_HOME, "packages", "openclaw", "lib", "node_modules", "openclaw", "extensions");
3685
- }
3686
- function isChannelPluginInstalled(instanceId, channelId) {
3687
- const extDirName = CHANNEL_EXT_DIR_ALIAS[channelId] || channelId;
3688
- const stockExtDir = getStockExtensionsDir();
3689
- if (existsSync(join(getChannelExtensionsDir(instanceId), extDirName)))
3690
- return true;
3691
- if (existsSync(join(stockExtDir, extDirName)))
3692
- return true;
3693
- if (extDirName !== channelId && existsSync(join(stockExtDir, channelId)))
3694
- return true;
3695
- // OpenClaw's npm-backed plugin store lives at
3696
- // `<home>/.openclaw/npm/node_modules/<pkg>`. The CLI refuses to reinstall
3697
- // when that path is present ("plugin already exists ... delete it first"),
3698
- // even if the per-instance extensions/<name> dir is missing (e.g. the
3699
- // first install was interrupted, or the dir was manually cleaned). Treat
3700
- // the npm path as authoritative so re-saves stay idempotent.
3701
- const pkg = CHANNEL_PLUGIN_MAP[channelId];
3702
- if (pkg) {
3703
- const home = getInstance(instanceId)?.openclaw_home ||
3704
- defaultOpenclawHome(instanceId);
3705
- const npmPath = join(home, OPENCLAW_STATE_DIRNAME, "npm", "node_modules", ...pkg.split("/"));
3706
- if (existsSync(npmPath))
3707
- return true;
3708
- }
3709
- return false;
3710
- }
3711
- /**
3712
- * Install a single channel plugin. Docker mode → `docker exec` inside the
3713
- * running container. Host mode → spawn the host openclaw binary directly.
3714
- * Physically migrated from `instance-manager.installChannelPlugin`.
3715
- */
3716
- async function installChannelPlugin(instanceId, channelId) {
3717
- const pkg = CHANNEL_PLUGIN_MAP[channelId];
3718
- if (!pkg)
3719
- throw new Error(`Unknown channel: ${channelId}`);
3720
- if (isChannelPluginInstalled(instanceId, channelId))
3721
- return;
3722
- const home = getInstance(instanceId)?.openclaw_home ||
3723
- defaultOpenclawHome(instanceId);
3724
- const extensionsDir = getChannelExtensionsDir(instanceId);
3725
- if (getNomadDriver() === "docker") {
3726
- await installChannelPluginViaDocker(instanceId, channelId, pkg, extensionsDir);
3727
- return;
3728
- }
3729
- const openclawBin = resolveOpenclawBin();
3730
- const nodeBinDir = dirname(process.execPath);
3731
- const childPath = [nodeBinDir, process.env.PATH].filter(Boolean).join(":");
3732
- const proxyEnvKeys = [
3733
- "http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY",
3734
- "no_proxy", "NO_PROXY", "NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED",
3735
- ];
3736
- const proxyEnv = {};
3737
- for (const key of proxyEnvKeys) {
3738
- if (process.env[key])
3739
- proxyEnv[key] = process.env[key];
3740
- }
3741
- const childEnv = {
3742
- PATH: childPath,
3743
- HOME: process.env.HOME,
3744
- LANG: process.env.LANG,
3745
- OPENCLAW_HOME: home,
3746
- ...proxyEnv,
3747
- };
3748
- const MAX_ATTEMPTS = 3;
3749
- const RETRY_DELAY_MS = 5_000;
3750
- const attemptInstall = () => new Promise((resolve, reject) => {
3751
- execFile(openclawBin, ["plugins", "install", pkg], { cwd: home, env: childEnv, timeout: 300_000 }, (err, stdout, stderr) => {
3752
- if (err && !isChannelPluginInstalled(instanceId, channelId)) {
3753
- const msg = [stderr?.trim(), stdout?.trim(), err.message].filter(Boolean).join(" | ");
3754
- console.error(`[plugins] ${pkg} exit code ${err.code ?? "?"}, stderr: ${stderr?.trim() || "(empty)"}, stdout: ${stdout?.trim() || "(empty)"}`);
3755
- try {
3756
- if (existsSync(extensionsDir)) {
3757
- for (const entry of readdirSync(extensionsDir)) {
3758
- if (entry.startsWith(".openclaw-install-stage-")) {
3759
- rmSync(join(extensionsDir, entry), { recursive: true, force: true });
3760
- console.log(`[plugins] Cleaned up stage dir: ${entry}`);
3761
- }
3762
- }
3763
- }
3764
- }
3765
- catch {
3766
- /* ignore */
3767
- }
3768
- reject(new Error(msg));
3769
- }
3770
- else {
3771
- if (err)
3772
- console.log(`[plugins] ${pkg} installed (ignored non-zero exit)`);
3773
- else
3774
- console.log(`[plugins] ${pkg} installed`);
3775
- resolve();
3776
- }
3777
- });
3778
- });
3779
- console.log(`[plugins] Installing ${pkg} for ${channelId} (host)...`);
3780
- let lastErr;
3781
- for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
3782
- try {
3783
- await attemptInstall();
3784
- const extDirName = CHANNEL_EXT_DIR_ALIAS[channelId] || channelId;
3785
- const installedExtDir = join(extensionsDir, extDirName);
3786
- if (existsSync(installedExtDir)) {
3787
- ensureDirContainer(installedExtDir);
3788
- try {
3789
- for (const entry of readdirSync(installedExtDir, { withFileTypes: true })) {
3790
- if (entry.isDirectory()) {
3791
- ensureDirContainer(join(installedExtDir, entry.name));
3792
- }
3793
- }
3794
- }
3795
- catch {
3796
- /* best effort */
3797
- }
3798
- }
3799
- ensureDirContainer(extensionsDir);
3800
- return;
3801
- }
3802
- catch (err) {
3803
- lastErr = err;
3804
- const isFetchError = /fetch failed/i.test(err.message ?? "");
3805
- if (isFetchError && attempt < MAX_ATTEMPTS) {
3806
- console.warn(`[plugins] ${pkg} install attempt ${attempt}/${MAX_ATTEMPTS} failed, retrying in ${RETRY_DELAY_MS / 1000}s...`);
3807
- await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
3808
- continue;
3809
- }
3810
- console.error(`[plugins] Failed to install ${pkg}:`, err.message);
3811
- break;
3812
- }
3813
- }
3814
- throw lastErr;
3815
- }
3816
- async function installChannelPluginViaDocker(instanceId, channelId, pkg, extensionsDir) {
3817
- const { exec } = await import("../../nomad-manager.js");
3818
- const MAX_ATTEMPTS = 3;
3819
- const RETRY_DELAY_MS = 5_000;
3820
- console.log(`[plugins] Installing ${pkg} for ${channelId} via docker exec (instance: ${instanceId})...`);
3821
- let lastErr;
3822
- for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
3823
- try {
3824
- const result = await exec(instanceId, ["openclaw", "plugins", "install", pkg], 300_000);
3825
- if (result.exitCode !== 0 && !isChannelPluginInstalled(instanceId, channelId)) {
3826
- const msg = [result.stderr?.trim(), result.stdout?.trim()].filter(Boolean).join(" | ");
3827
- console.error(`[plugins] ${pkg} docker exec exit code ${result.exitCode}, output: ${msg}`);
3828
- throw new Error(msg || `openclaw plugins install exited with code ${result.exitCode}`);
3829
- }
3830
- if (result.exitCode !== 0) {
3831
- console.log(`[plugins] ${pkg} installed via docker (ignored non-zero exit)`);
3832
- }
3833
- else {
3834
- console.log(`[plugins] ${pkg} installed via docker`);
3835
- }
3836
- const extDirName = CHANNEL_EXT_DIR_ALIAS[channelId] || channelId;
3837
- const installedExtDir = join(extensionsDir, extDirName);
3838
- if (existsSync(installedExtDir)) {
3839
- ensureDirContainer(installedExtDir);
3840
- try {
3841
- for (const entry of readdirSync(installedExtDir, { withFileTypes: true })) {
3842
- if (entry.isDirectory()) {
3843
- ensureDirContainer(join(installedExtDir, entry.name));
3844
- }
3845
- }
3846
- }
3847
- catch {
3848
- /* best effort */
3849
- }
3850
- }
3851
- ensureDirContainer(extensionsDir);
3852
- return;
3853
- }
3854
- catch (err) {
3855
- lastErr = err;
3856
- if (/not running/i.test(err.message ?? "")) {
3857
- throw new Error("请先启动实例后再安装插件(Docker 模式下插件需在容器内安装)");
3858
- }
3859
- const isTransient = /fetch failed|ECONNREFUSED/i.test(err.message ?? "");
3860
- if (isTransient && attempt < MAX_ATTEMPTS) {
3861
- console.warn(`[plugins] ${pkg} docker install attempt ${attempt}/${MAX_ATTEMPTS} failed, retrying...`);
3862
- await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
3863
- continue;
3864
- }
3865
- console.error(`[plugins] Failed to install ${pkg} via docker:`, err.message);
3866
- break;
3867
- }
3868
- }
3869
- throw lastErr;
3870
- }
3871
- /**
3872
- * Full saveConfig implementation. Writes `.openclaw/openclaw.json`,
3873
- * mirrors into legacy `openclaw.json` path, updates env files with
3874
- * provider API keys, preserves backend-managed fields, and fires
3875
- * config-change listeners.
3876
- *
3877
- * Physically migrated from `instance-manager.saveConfig`.
3878
- */
3879
- function saveNativeConfigImpl(instanceId, config) {
3880
- const configPath = openclawConfigPath(instanceId);
3881
- if (!existsSync(framework_instanceDir(instanceId)))
3882
- return false;
3883
- if (!existsSync(configPath)) {
3884
- const legacyPath = legacyOpenclawConfigPath(instanceId);
3885
- ensureDirContainer(dirname(configPath));
3886
- if (existsSync(legacyPath))
3887
- copyFileSync(legacyPath, configPath);
3888
- }
3889
- // Save x-jishushell metadata to instance.json (not openclaw.json)
3890
- if (config["x-jishushell"]) {
3891
- const metaPath = instanceMetaPath(instanceId);
3892
- if (existsSync(metaPath)) {
3893
- const meta = JSON.parse(readFileSync(metaPath, "utf-8"));
3894
- meta["x-jishushell"] = config["x-jishushell"];
3895
- safeWriteJson(metaPath, meta);
3896
- chownToServiceUser(metaPath);
3897
- }
3898
- }
3899
- const [configToWrite, envUpdates] = prepareConfigForSave(instanceId, config);
3900
- // If openclaw-lark is enabled, resolve which feishu plugin to use
3901
- if (configToWrite.plugins?.entries?.["openclaw-lark"]?.enabled) {
3902
- const stockExtDir = getStockExtensionsDir();
3903
- const stockFeishu = join(stockExtDir, "feishu");
3904
- const stockOcl = join(stockExtDir, "openclaw-lark");
3905
- const instanceOcl = join(getChannelExtensionsDir(instanceId), "openclaw-lark");
3906
- if (existsSync(stockFeishu) && !existsSync(stockOcl) && !existsSync(instanceOcl)) {
3907
- configToWrite.plugins.entries.feishu = { enabled: true };
3908
- delete configToWrite.plugins.entries["openclaw-lark"];
3909
- }
3910
- else if (existsSync(stockFeishu)) {
3911
- configToWrite.plugins ??= {};
3912
- configToWrite.plugins.entries ??= {};
3913
- configToWrite.plugins.entries.feishu = { enabled: false };
3914
- }
3915
- }
3916
- // Preserve backend-managed fields
3917
- if (existsSync(configPath)) {
3918
- try {
3919
- const existing = JSON.parse(readFileSync(configPath, "utf-8"));
3920
- if (existing.plugins?.installs) {
3921
- configToWrite.plugins ??= {};
3922
- configToWrite.plugins.installs = { ...existing.plugins.installs, ...configToWrite.plugins?.installs };
3923
- }
3924
- if (existing.plugins?.entries && configToWrite.plugins?.entries) {
3925
- for (const [key, val] of Object.entries(configToWrite.plugins.entries)) {
3926
- const old = existing.plugins.entries[key];
3927
- if (val && typeof val === "object" && !Array.isArray(val) && old && typeof old === "object") {
3928
- configToWrite.plugins.entries[key] = { ...old, ...val };
3929
- }
3930
- }
3931
- }
3932
- if (existing.channels && configToWrite.channels) {
3933
- for (const [key, val] of Object.entries(configToWrite.channels)) {
3934
- const old = existing.channels[key];
3935
- if (val && typeof val === "object" && !Array.isArray(val) && old && typeof old === "object") {
3936
- configToWrite.channels[key] = { ...old, ...val };
3937
- }
3938
- }
3939
- }
3940
- }
3941
- catch {
3942
- /* best effort */
3943
- }
3944
- }
3945
- // Backup + atomic write
3946
- if (existsSync(configPath)) {
3947
- copyFileSync(configPath, configPath + ".bak");
3948
- }
3949
- const configJson = JSON.stringify(configToWrite, null, 2);
3950
- ensureDirContainer(dirname(configPath));
3951
- writeConfigFile(configPath + ".tmp", configJson);
3952
- JSON.parse(readFileSync(configPath + ".tmp", "utf-8"));
3953
- renameSync(configPath + ".tmp", configPath);
3954
- chownToServiceUser(configPath);
3955
- // Mirror into legacy path
3956
- const legacyPath = legacyOpenclawConfigPath(instanceId);
3957
- if (existsSync(legacyPath)) {
3958
- copyFileSync(legacyPath, legacyPath + ".bak");
3959
- }
3960
- writeConfigFile(legacyPath + ".tmp", configJson);
3961
- JSON.parse(readFileSync(legacyPath + ".tmp", "utf-8"));
3962
- renameSync(legacyPath + ".tmp", legacyPath);
3963
- chownToServiceUser(legacyPath);
3964
- if (Object.keys(envUpdates).length) {
3965
- const envFiles = getRuntimeEnvFiles(instanceId);
3966
- if (envFiles.length)
3967
- updateEnvFile(envFiles[0], envUpdates);
3968
- }
3969
- // Notify listeners (LLM proxy cache invalidation etc.)
3970
- notifyConfigChange(instanceId);
3971
- return true;
3972
- }
3973
- export const openclawAdapter = new OpenClawAdapter();
3974
- registerAdapter(openclawAdapter);
3975
- //# sourceMappingURL=openclaw.js.map